file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/215768232.c
#include<stdio.h> void bubble_sort(int digit[],int size); int main(void) { int size; scanf("%d",&size); int nums[size]; int odd[100]; int even[100]; for(int i =0;i < size;i++) { scanf("%d",&nums[i]); } int index_odd = 0; int index_even = 0; for(int i =0;i < size;i++) { if(nums[i] % 2 == 0) { even[index_even] = nums[i]; index_even++; } else { odd[index_odd] = nums[i]; index_odd++; } } bubble_sort(odd,index_odd); bubble_sort(even,index_even); for(int i = 0;i < index_even;i++) { printf("%d ",even[i]); } for(int i = 0;i < index_odd;i++) { printf("%d ",odd[i]); } return 0; } void bubble_sort(int digit[],int size) { for(int i = 0;i < size;i++) { for(int j = 0;j < size - i - 1;j++) { if(digit[j] < digit[j+1]) { int temp = digit[j+1]; digit[j+1] = digit[j]; digit[j] = temp; } } } }
the_stack_data/450929.c
/* Copyright 2013-2014 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ void stop_frame () { /* The debug information for this frame is modified in the accompanying .S file, to mark a set of registers as being DW_CFA_same_value. */ } void first_frame () { stop_frame (); } int main () { first_frame (); return 0; }
the_stack_data/863566.c
#include <stdlib.h> long jrand48(unsigned short xsub[3]) { return 0; } /* XOPEN(4) */
the_stack_data/757582.c
#include<stdlib.h> #include<locale.h> #include<wchar.h> #include<stdio.h> #include<time.h> char rank[9]; int pos[8]; void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; for(i=0;i<8;i++){ rank[i] = 'e'; pos[i] = i; } do{ kPos = rand()%8; rPos1 = rand()%8; rPos2 = rand()%8; }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2)); rank[pos[rPos1]] = 'R'; rank[pos[kPos]] = 'K'; rank[pos[rPos2]] = 'R'; swap(rPos1,7); swap(rPos2,6); swap(kPos,5); do{ bPos1 = rand()%5; bPos2 = rand()%5; }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2)); rank[pos[bPos1]] = 'B'; rank[pos[bPos2]] = 'B'; swap(bPos1,4); swap(bPos2,3); do{ qPos = rand()%3; nPos1 = rand()%3; }while(qPos==nPos1); rank[pos[qPos]] = 'Q'; rank[pos[nPos1]] = 'N'; for(i=0;i<8;i++) if(rank[i]=='e'){ rank[i] = 'N'; break; } } void printRank(){ int i; #ifdef _WIN32 printf("%s\n",rank); #else { setlocale(LC_ALL,""); printf("\n"); for(i=0;i<8;i++){ if(rank[i]=='K') printf("%lc",(wint_t)9812); else if(rank[i]=='Q') printf("%lc",(wint_t)9813); else if(rank[i]=='R') printf("%lc",(wint_t)9814); else if(rank[i]=='B') printf("%lc",(wint_t)9815); if(rank[i]=='N') printf("%lc",(wint_t)9816); } } #endif } int main() { int i; srand((unsigned)time(NULL)); for(i=0;i<9;i++){ generateFirstRank(); printRank(); } return 0; }
the_stack_data/47589.c
/**********************************************************************************************/ /* Copyright (c) 2015 Amanda Randles, John Gounley */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, are */ /* permitted provided that the following conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above copyright notice, this list of */ /* conditions and the following disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above copyright notice, this list of */ /* conditions and the following disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS*/ /* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ /* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */ /* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF */ /* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) */ /* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR */ /* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /**********************************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> // parameters #define MC 19 // number of discrete velocities #define LX_MAX 41 // number of lattice points, x-direction #define LY_MAX 41 // number of lattice points, y-direction #define LZ_MAX 121 // number of lattice points, z-direction #define T (1.0 / 3.0) // speed of sound squared in LB units #define omega 1.0 // relaxation time for LBM double distr[MC][LX_MAX][LY_MAX][LZ_MAX]; // distribution function double distr_adv[MC][LX_MAX][LY_MAX][LZ_MAX]; // distribution function, to advance int node_id[LX_MAX][LY_MAX][LZ_MAX]; // id: 0 if wall, 1 if fluid double norm(double a[3]) { double b = sqrt( a[0]*a[0] + a[1]*a[1] + a[2]*a[2] ); return b; } // main program int main(int argc, char **argv) { printf("starting setup...\n"); /* SETUP SECTION */ // variable definitions */ int ic[MC][3], idg[MC], iop[MC]; double distr_eq[MC]; int lx, ly, lz; double rho, ux, uy, uz, distr0, distr1, uke, rhoinv; double px, py, pz, delNi; double u0 = 1e-4; double cdotu; FILE *vtk_fp, *fp, *g_fp; int i, ix, iy, iz, is, ik, istate, j, i1, js; // read state vectors */ fp = fopen("stencil.i", "r"); if (fp == NULL) { fprintf(stderr, "Error: cannot open file states19.i.\n"); return 1; } for(i = 0; i < MC; i++) { fscanf(fp, "%d %d %d %d %d %d", &istate, &ic[i][0], &ic[i][1], &ic[i][2], &idg[i], &iop[i]); } fclose(fp); // setup time int n_step; int n_step_max = 1000; int n_step_out = 1000; // setup grid dimensions lx = LX_MAX; ly = LY_MAX; lz = LZ_MAX; double dx = 4.0/( (double) (lx-1)); double dt = dx; // fix printf("dx= %lf \n",dx); for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { for(iz = 0; iz < lz; iz++) { // compute lattice point coordinates double tempx = dx*ix - 2.0; double tempy = dx*iy - 2.0; double tempz = dx*iz; // assign inside or outside of cylinder if (sqrt( pow(tempx,2.0) + pow(tempy,2.0) ) < 1.75) { node_id[ix][iy][iz] = 1; } else{ node_id[ix][iy][iz] = 0; } } } } // setup initial flow (shear flow) distr1 = 1.0 / 36.0; distr0 = 1.0 / 3.0; for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { for(iz = 0; iz < lz; iz++) { if (node_id[ix][iy][iz] == 1) { rho = 1.0; ux = 0.0; uy = 0.0; uz = 0.0; uke = 0.5*(ux*ux + uy*uy + uz*uz); for(is = 0; is < MC-1; is++) { cdotu = ic[is][0]*ux + ic[is][1]*uy + ic[is][2]*uz; distr[is][ix][iy][iz] = rho*distr1*idg[is]*(1.0 + cdotu/T + 0.5*(cdotu/T)*(cdotu/T) - uke/T); } distr[MC-1][ix][iy][iz] = distr0*(1.0 - uke/T); } } } } printf("starting loop...\n"); /* THE TIMESTEPPING LOOP */ for(n_step = 1; n_step <= n_step_max; n_step++) { printf("step %i \n", n_step); /* collision - vanilla version */ for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { for(iz = 0; iz < lz; iz++) { if (node_id[ix][iy][iz] == 1) { rho = px = py = pz = 0.0; for(is = 0; is < MC; is++) { rho += distr[is][ix][iy][iz]; px += distr[is][ix][iy][iz]*ic[is][0]; py += distr[is][ix][iy][iz]*ic[is][1]; pz += distr[is][ix][iy][iz]*ic[is][2]; } ux = px / rho; uy = py / rho; uz = pz / rho; uke = 0.5*(ux*ux + uy*uy + uz*uz); for(is = 0; is < MC-1; is++) { cdotu = ic[is][0]*ux + ic[is][1]*uy + ic[is][2]*uz; distr_eq[is] = rho*distr1*idg[is]*(1.0 + cdotu/T + 0.5*(cdotu/T)*(cdotu/T) - uke/T); } distr_eq[MC-1] = distr0*(1.0 - uke/T); for(is = 0; is < MC; is++) { delNi = -omega * (distr[is][ix][iy][iz] - distr_eq[is]); distr_adv[is][ix][iy][iz] = distr[is][ix][iy][iz] + delNi; } } } } } /* advection */ for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { for(iz = 0; iz < lz; iz++) { if (node_id[ix][iy][iz] == 1) { int ixa, iya, iza; for(is = 0; is < MC; is++) { ixa = ix + ic[is][0]; iya = iy + ic[is][1]; iza = iz + ic[is][2]; if (node_id[ixa][iya][iza] == 1) { distr[is][ixa][iya][iza] = distr_adv[is][ix][iy][iz]; } else if(iza > 0 && iza < lz) { distr[iop[is]][ix][iy][iz] = distr_adv[is][ix][iy][iz]; } } } } } } // bottom // iz = 0; // double n[3] = {0.0, 0.0, -1.0}; // double umax[3] = {0.0, 0.0, 0.0}; // double deltarho = 0.1; // double cdotn[19]; // double cdotu[19]; // double tdotu[19]; // double t[19][3]; // int exitVel[5]; // int tangVel[9]; // int exitCount = 0; // int tangCount = 0; // // for(is = 0; is < MC; is++) { // cdotn[is] = ic[is][0]*n[0] + ic[is][1]*n[1] + ic[is][2]*n[2]; // t[is][0] = ic[is][0] - cdotn[is]*n[0]; // t[is][1] = ic[is][1] - cdotn[is]*n[1]; // t[is][2] = ic[is][2] - cdotn[is]*n[2]; // if (cdotn[is] > 0.5) // { // exitVel[exitCount] = is; // exitCount++; // } // else if (cdotn[is] > -0.5) // { // tangVel[tangCount] = is; // tangCount++; // } // } // // for(ix = 0; ix < lx; ix++) { // for(iy = 0; iy < ly; iy++) { // // if (node_id[ix][iy][iz] == 1) // { // double tempx = dx*ix - 1.5; // double tempy = dx*iy - 1.5; // double disqrd = pow(1.25,2.0) - (tempx*tempx+tempy*tempy); // umax[2] = 0.005*disqrd; //(deltarho*disqrd)/(12.0*(dx*lz)*0.16666); // // double tempRho = 0.0; // for (unsigned in=0; in<9; ++in) // { // is = tangVel[in]; // tempRho += distr[is][ix][iy][iz]; // } // // for (unsigned in=0; in<5; ++in) // { // is = exitVel[in]; // tempRho += 2.0*distr[is][ix][iy][iz]; // } // // double rho = tempRho/(1+n[0]*umax[0]+n[1]*umax[1]+n[2]*umax[2]); // // // compute sum in equation 27 of Hecht, Harting (JSM, 2010) // double temp_sum[MC]; // for(is = 0; is < MC; is++) // { // temp_sum[is] = 0.0; // for(js = 0; js < MC; js++) // { // double cdottij = (ic[js][0]*t[is][0] + ic[js][1]*t[is][1] + ic[js][2]*t[is][2]); // temp_sum[is] += distr[js][ix][iy][iz]*cdottij*(1.-fabs(cdotn[js])); // } // } // // // equation 27 of Hecht, Harting (JSM, 2010), with fix based on stencil weight idg // for (unsigned in=0; in<5; ++in) // { // int is = exitVel[in]; // cdotu[is] = ic[is][0]*umax[0] + ic[is][1]*umax[1] + ic[is][2]*umax[2]; // tdotu[is] = t[is][0]*umax[0] + t[is][1]*umax[1] + t[is][2]*umax[2]; // // distr[iop[is]][ix][iy][iz] = distr[is][ix][iy][iz] // - cdotu[is]*rho*(double)idg[is]/6. - tdotu[is]*rho/3. + 0.5*temp_sum[is]; // } // } // } // } // alt bottom iz = 0; double n[3] = {0.0, 0.0, -1.0}; double umax[3] = {0.0, 0.0, 0.0}; double deltarho = 0.1; double cdotn[19]; double cdotu[19]; double tdotu[19]; double t[19][3]; int exitVel[5]; int tangVel[9]; int exitCount = 0; int tangCount = 0; rho = 1.005; rhoinv = 1.0/rho; for(is = 0; is < MC; is++) { cdotn[is] = ic[is][0]*n[0] + ic[is][1]*n[1] + ic[is][2]*n[2]; t[is][0] = ic[is][0] - cdotn[is]*n[0]; t[is][1] = ic[is][1] - cdotn[is]*n[1]; t[is][2] = ic[is][2] - cdotn[is]*n[2]; if (cdotn[is] > 0.5) { exitVel[exitCount] = is; exitCount++; } else if (cdotn[is] > -0.5) { tangVel[tangCount] = is; tangCount++; } } for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { if (node_id[ix][iy][iz] == 1) { double tempVel = 0.0; for (unsigned in=0; in<9; ++in) { is = tangVel[in]; tempVel += rhoinv*distr[is][ix][iy][iz]; } for (unsigned in=0; in<5; ++in) { is = exitVel[in]; tempVel += 2.0*rhoinv*distr[is][ix][iy][iz]; } umax[0] = (-1.0 + tempVel)*n[0]; umax[1] = (-1.0 + tempVel)*n[1]; umax[2] = (-1.0 + tempVel)*n[2]; // compute sum in equation 27 of Hecht, Harting (JSM, 2010) double temp_sum[MC]; for(is = 0; is < MC; is++) { temp_sum[is] = 0.0; for(js = 0; js < MC; js++) { double cdottij = (ic[js][0]*t[is][0] + ic[js][1]*t[is][1] + ic[js][2]*t[is][2]); temp_sum[is] += distr[js][ix][iy][iz]*cdottij*(1.-fabs(cdotn[js])); } } // equation 27 of Hecht, Harting (JSM, 2010), with fix based on stencil weight idg for (unsigned in=0; in<5; ++in) { int is = exitVel[in]; cdotu[is] = ic[is][0]*umax[0] + ic[is][1]*umax[1] + ic[is][2]*umax[2]; tdotu[is] = t[is][0]*umax[0] + t[is][1]*umax[1] + t[is][2]*umax[2]; distr[iop[is]][ix][iy][iz] = distr[is][ix][iy][iz] - cdotu[is]*rho*(double)idg[is]/6. - tdotu[is]*rho/3. + 0.5*temp_sum[is]; } } } } // top iz = lz-1; n[0] = 0.0; n[1] = 0.0; n[2] = 1.0; umax[0] = 0.0; umax[1] = 0.0; umax[2] = 0.0; exitCount = 0; tangCount = 0; rho = 1.0; rhoinv = 1.0; for(is = 0; is < MC; is++) { cdotn[is] = ic[is][0]*n[0] + ic[is][1]*n[1] + ic[is][2]*n[2]; t[is][0] = ic[is][0] - cdotn[is]*n[0]; t[is][1] = ic[is][1] - cdotn[is]*n[1]; t[is][2] = ic[is][2] - cdotn[is]*n[2]; if (cdotn[is] > 0.5) { exitVel[exitCount] = is; exitCount++; } else if (cdotn[is] > -0.5) { tangVel[tangCount] = is; tangCount++; } } for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { if (node_id[ix][iy][iz] == 1) { double tempVel = 0.0; for (unsigned in=0; in<9; ++in) { is = tangVel[in]; tempVel += rhoinv*distr[is][ix][iy][iz]; } for (unsigned in=0; in<5; ++in) { is = exitVel[in]; tempVel += 2.0*rhoinv*distr[is][ix][iy][iz]; } umax[0] = (-1.0 + tempVel)*n[0]; umax[1] = (-1.0 + tempVel)*n[1]; umax[2] = (-1.0 + tempVel)*n[2]; // compute sum in equation 27 of Hecht, Harting (JSM, 2010) double temp_sum[MC]; for(is = 0; is < MC; is++) { temp_sum[is] = 0.0; for(js = 0; js < MC; js++) { double cdottij = (ic[js][0]*t[is][0] + ic[js][1]*t[is][1] + ic[js][2]*t[is][2]); temp_sum[is] += distr[js][ix][iy][iz]*cdottij*(1.-fabs(cdotn[js])); } } // equation 27 of Hecht, Harting (JSM, 2010), with fix based on stencil weight idg for (unsigned in=0; in<5; ++in) { int is = exitVel[in]; cdotu[is] = ic[is][0]*umax[0] + ic[is][1]*umax[1] + ic[is][2]*umax[2]; tdotu[is] = t[is][0]*umax[0] + t[is][1]*umax[1] + t[is][2]*umax[2]; distr[iop[is]][ix][iy][iz] = distr[is][ix][iy][iz] - cdotu[is]*rho*(double)idg[is]/6. - tdotu[is]*rho/3. + 0.5*temp_sum[is]; } } } } /* output */ if (n_step % n_step_out == 0) { printf("%d\n", n_step); char fname[15]; sprintf(fname,"lbe_%d.vtk",n_step); vtk_fp = fopen(fname, "w"); if (vtk_fp == NULL) { fprintf(stderr, "Error: cannot open file lbe.vtk. \n"); return 1; } fprintf(vtk_fp, "# vtk DataFile Version 3.0"); fprintf(vtk_fp, "\nvtk global output\n"); fprintf(vtk_fp, "ASCII\n"); fprintf(vtk_fp, "DATASET STRUCTURED_POINTS\n"); fprintf(vtk_fp, "DIMENSIONS %i %i %i\n", lx, ly, lz); fprintf(vtk_fp, "ORIGIN 0. 0. 0.\n"); fprintf(vtk_fp, "SPACING 1 1 1\n"); fprintf(vtk_fp, "\nPOINT_DATA %d\n",lx*ly*lz); fprintf(vtk_fp, "SCALARS rho double \n"); fprintf(vtk_fp, "LOOKUP_TABLE default\n"); for(iz = 0; iz < lz; iz++) { for(iy = 0; iy < ly; iy++) { for(ix = 0; ix < lx; ix++) { rho = px = py = pz = 0.0; if (node_id[ix][iy][iz] == 1.0) { for(is = 0; is < MC; is++) { rho += distr[is][ix][iy][iz]; } } // nonsense begins double ax = dx*ix - 2.0; double ay = dx*iy - 2.0; if (iz % 8 == 0) { rho = ax*ax*ax; } else if (iz % 8 == 4) { rho = ax*ay*ax; } else if (iz % 8 == 2) { rho = ay*ay*ay; } else if (iz % 8 == 6) { rho = ay*ay*ax; } else { rho = 0.0; } // nonsense ends fprintf(vtk_fp, "%f\n",rho); } } } fprintf(vtk_fp, "SCALARS id int \n"); fprintf(vtk_fp, "LOOKUP_TABLE default\n"); for(iz = 0; iz < lz; iz++) { for(iy = 0; iy < ly; iy++) { for(ix = 0; ix < lx; ix++) { fprintf(vtk_fp, "%i\n",node_id[ix][iy][iz]); } } } fprintf(vtk_fp, "VECTORS velocity double \n"); for(iz = 0; iz < lz; iz++) { for(iy = 0; iy < ly; iy++) { for(ix = 0; ix < lx; ix++) { rho = px = py = pz = ux = uy = uz = 0.0; if (node_id[ix][iy][iz] == 1.0) { for(is = 0; is < MC; is++) { rho += distr[is][ix][iy][iz]; px += distr[is][ix][iy][iz]*ic[is][0]; py += distr[is][ix][iy][iz]*ic[is][1]; pz += distr[is][ix][iy][iz]*ic[is][2]; } ux = px / rho; uy = py / rho; uz = pz / rho; } fprintf(vtk_fp, "%f %f %f\n",ux,uy,uz); } } } fprintf(vtk_fp, "VECTORS coordinates double \n"); for(iz = 0; iz < lz; iz++) { for(iy = 0; iy < ly; iy++) { for(ix = 0; ix < lx; ix++) { fprintf(vtk_fp, "%f %f %f\n",ix*dx,iy*dx,iz*dx); } } } fclose(vtk_fp); } } return 0; }
the_stack_data/242329862.c
#include <stdio.h> #include <signal.h> void sig_handler(int sig) { if( sig == 9) { puts("hello world"); } } int main() { signal(9 , sig_handler); while(1); return 0; }
the_stack_data/81401.c
#include <arpa/inet.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> //sockaddr_in #include <stdio.h> #include <stdlib.h> #include <string.h> // 打印域名别名 static void print_alias_names(char **alias_names) { printf("alias names: ["); int first_name = 1; for (char **alias_name = alias_names; *alias_name != NULL; alias_name++) { printf("%s%s", (first_name == 1 ? "" : ", "), *alias_name); first_name = 0; } printf("]\n"); } // 打印ip地址列表 static void print_ip_address(char **ip_address, int addr_len) { printf("ip address: ["); int first_name = 1; if (addr_len == sizeof(struct in_addr)) { // 打印ipv4地址的点分十进制 char ip_string[INET_ADDRSTRLEN]; for (char **ip = ip_address; *ip != NULL; ip++) { printf("%s%s", (first_name == 1 ? "" : ", "), inet_ntop(AF_INET, *ip, ip_string, INET_ADDRSTRLEN)); first_name = 0; } } else if (addr_len == sizeof(struct in6_addr)) { // 打印ipv6地址的十六进制字符串形式 char ip_string[INET6_ADDRSTRLEN]; for (char **ip = ip_address; *ip != NULL; ip++) { printf("%s%s", (first_name == 1 ? "" : ", "), inet_ntop(AF_INET6, *ip, ip_string, INET6_ADDRSTRLEN)); first_name = 0; } } else { printf("unknown ip address type!"); } printf("]\n"); } static void print_servent(const struct servent *serv_info) { printf("service name: %s\n", serv_info->s_name); printf("alias names: ["); int first_name = 1; for (char **alias_name = serv_info->s_aliases; *alias_name != NULL; alias_name++) { printf("%s%s", (first_name == 1 ? "" : ", "), *alias_name); first_name = 0; } printf("]\n"); printf("port number: %d\n", ntohs(serv_info->s_port)); printf("protocol: %s\n", serv_info->s_proto); } int main(int argc, char *argv[]) { struct in_addr ipv4_address; int ret = inet_pton(AF_INET, "127.0.0.1", &ipv4_address); if (ret != 0) { printf("%s\n", strerror(errno)); } struct hostent *host_info = gethostbyaddr(&ipv4_address, sizeof(struct in_addr), AF_INET); printf("hostname: %s\n", host_info->h_name); print_alias_names(host_info->h_aliases); print_ip_address(host_info->h_addr_list, host_info->h_length); // Output: // hostname: localhost // alias names: [] // ip address: [127.0.0.1] host_info = gethostbyname("www.163.com"); printf("hostname: %s\n", host_info->h_name); print_alias_names(host_info->h_aliases); print_ip_address(host_info->h_addr_list, host_info->h_length); // Output: // hostname: z163ipv6.v.bsgslb.cn // alias names: [www.163.com, www.163.com.163jiasu.com, www.163.com.bsgslb.cn] // ip address: [183.47.233.10, 183.47.233.9, 183.47.233.13, 183.47.233.6, 183.47.233.12, // 183.47.233.7, 183.47.233.14, 183.47.233.8, 183.47.233.11] struct servent *serv_info = getservbyname("https", "tcp"); if (serv_info != NULL) { print_servent(serv_info); } else { printf("failed to get port by service name!\n"); } // Output: // service name: https // alias names: [] // port number: 443 // protocol: tcp serv_info = getservbyport(htons(22), "tcp"); if (serv_info != NULL) { print_servent(serv_info); } else { printf("failed to get service name by port number!\n"); } // Output: // service name: ssh // alias names: [] // port number: 22 // protocol: tcp return 0; }
the_stack_data/122015403.c
/* ACM 11150 Cola * mythnc * 2012/01/04 17:25:04 * run time: 0.008 */ #include <stdio.h> int change(int); int main(void) { int n; while (scanf("%d", &n) == 1) printf("%d\n", change(n)); return 0; } /* change: return the max colas we can get * from this change mechanism */ int change(int n) { int sum; sum = n; while (n >= 3) { sum += n / 3; n = n / 3 + n % 3; } if (n == 2) sum++; return sum; }
the_stack_data/154830193.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2004-2021 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <unistd.h> static void *p; void pass (void) { } static void handler (int sig, siginfo_t *info, void *context) { if (info->si_addr == p) pass (); _exit (0); } int main (void) { /* Set up unwritable memory. */ { size_t len; len = sysconf(_SC_PAGESIZE); p = mmap (0, len, PROT_NONE, MAP_ANON|MAP_PRIVATE, -1, 0); if (p == MAP_FAILED) { perror ("mmap"); return 1; } } /* Set up the signal handler. */ { struct sigaction action; memset (&action, 0, sizeof (action)); action.sa_sigaction = handler; action.sa_flags |= SA_SIGINFO; if (sigaction (SIGSEGV, &action, NULL)) { perror ("sigaction"); return 1; } } /* Trigger SIGSEGV. */ *(int *)p = 0; return 0; }
the_stack_data/211080357.c
#include <stdio.h> int sommeDesImpairs(int n); int main() { } int sommeDesImpairs(int n) { int somme = 0; for (int i = 0; i < n + 1; i++) { if (i % 2 == 1) somme += i; } return somme; }
the_stack_data/115766021.c
#include <stdio.h> int main(int argc, char * argv[]) { if (argc != 2) { fprintf(stderr, "Usage: ic filename\n"); return 1; } FILE *file = fopen(argv[1], "r"); if (file == NULL) { fprintf(stderr, "Failed to open file\n"); return 2; } int sum = 0; char firstChar = fgetc(file); char curChar = firstChar; while (curChar != EOF) { char nextChar = fgetc(file); if (nextChar == EOF) { break; } if (curChar == nextChar) { sum += (int)curChar - 48; } curChar = nextChar; } fclose(file); if (firstChar == curChar) { sum += (int)firstChar - 48; } printf("Solution: %d\n", sum); return 0; }
the_stack_data/92324990.c
// wrapper for dlldata.c #ifdef _MERGE_PROXYSTUB // merge proxy stub DLL #define REGISTER_PROXY_DLL //DllRegisterServer, etc. #define USE_STUBLESS_PROXY //defined only with MIDL switch /Oicf #pragma comment(lib, "rpcns4.lib") #pragma comment(lib, "rpcrt4.lib") #define ENTRY_PREFIX Prx #include "dlldata.c" #include "SimpleOutOfProcessCOM_p.c" #endif //_MERGE_PROXYSTUB
the_stack_data/80789.c
/* Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <string.h> extern void toms510_(float *xin, float *yin, float *err, int *n, float *xout, float *yout, float *w, int *k, int *p); #define N 5 #define fEQ(a, b, d) (((a > b) ? a - b : b - a) < d) int main() { float x[N] = {0.f, 1.f, 2.f, 3.f, 4.f}; float y[N] = {0.f, 1.f, 4.f, 1.f, 0.f}; float err = .02 * 4; // max(x)-min(x) = 4; int n = N; float xout[N]; float yout[N]; int i; for (i = 0; i < n; i++) { xout[i] = (float)i; yout[i] = (float)i; } float w[N]; memcpy(w, x, sizeof(x)); int k = 0; int p = 6; toms510_(x, y, &err, &n, xout, yout, w, &k, &p); float ey[N] = {-.08, 1.08, 3.99781, 1., 0.}; float ex[N] = {0., 1., 2.0274, 3., 4.}; for (i = 0; i < N; i++) { if (!fEQ(ex[i], xout[i], 1e-5f)) return 1; if (!fEQ(ey[i], yout[i], 1e-5f)) return 1; } return 0; }
the_stack_data/61147.c
/* Fig. 8.13: fig08_13.c Using fgets and putchar */ #include <stdio.h> void reverse( const char * const sPtr ); /* prototype */ int main( void ) { char sentence[ 80 ]; /* create char array */ printf( "Enter a line of text:\n" ); /* use fgets to read line of text */ fgets( sentence, 80, stdin ); printf( "\nThe line printed backward is:\n" ); reverse( sentence ); return 0; /* indicates successful termination */ } /* end main */ /* recursively outputs characters in string in reverse order */ void reverse( const char * const sPtr ) { /* if end of the string */ if ( sPtr[ 0 ] == '\0' ) { /* base case */ return; } /* end if */ else { /* if not end of the string */ reverse( &sPtr[ 1 ] ); /* recursion step */ putchar( sPtr[ 0 ] ); /* use putchar to display character */ } /* end else */ } /* end function reverse */ /************************************************************************** * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
the_stack_data/187643326.c
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); /* show that we are working */ fflush(stdout); /* max_p/2: valid limit, because one side of triangle * must be less than the sum of the other two */ for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
the_stack_data/46601.c
static int foo(volatile int *a, int v) { *a = v; *a = 0; return *a; } /* * check-name: memops-volatile * check-command: test-linearize $file * * check-output-ignore * check-output-contains: store\\..*%arg2 -> 0\\[%arg1] * check-output-contains: store\\..*\\$0 -> 0\\[%arg1] * check-output-contains: load\\..*%r.* <- 0\\[%arg1] */
the_stack_data/168894047.c
int IStart, IEnd, JEnd; void foo(int N, int JStart, double * restrict * restrict U) { for (int I = IStart; I < IEnd; ++I) for (int J = JStart; J < JEnd; ++J) U[I][J] = U[I][J] + 1; }
the_stack_data/49617.c
int __return_main; void __VERIFIER_error(); void __VERIFIER_assume(int); void __VERIFIER_assert(int cond); int __VERIFIER_nondet_int(); int main(); int __return_720; int main() { int main__x = 0; int main__y = 50; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_649:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_656:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_663:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_670:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_677:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_684:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_691:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_698:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_705:; label_706:; if (main__x < 100) { if (main__x < 50) { main__x = main__x + 1; label_712:; goto label_706; } else { main__x = main__x + 1; main__y = main__y + 1; goto label_712; } } else { { int __tmp_1; __tmp_1 = main__y == 100; int __VERIFIER_assert__cond; __VERIFIER_assert__cond = __tmp_1; if (__VERIFIER_assert__cond == 0) { __VERIFIER_error(); return __return_main; } else { __return_720 = 0; return __return_720; } } } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_705; } } else { return __return_main; } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_698; } } else { return __return_main; } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_691; } } else { return __return_main; } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_684; } } else { return __return_main; } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_677; } } else { return __return_main; } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_670; } } else { return __return_main; } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_663; } } else { return __return_main; } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_656; } } else { return __return_main; } } else { main__x = main__x + 1; main__y = main__y + 1; goto label_649; } } else { return __return_main; } }
the_stack_data/22012557.c
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<limits.h> #include<string.h> #include<time.h> #include<stdbool.h> #include <ctype.h> // 定义最长能够允许输入的明文(密文)字符个数 #define char_max 1000 // 此代码运行环境 Visual Studio 2017 // "#define _CRT_SECURE_NO_WARNINGS" 去掉VS安全检查 // !!!请不要输入中文字符 // 加密解密函数 void singleTablereplacement(char* text, char *result, char*key, bool isEnycript); // 检查密钥函数 bool check_key(char *key); int main() { // 存储输入的明文(或密文) char* text = (char*)calloc(sizeof(char),char_max); // 存储结果 char* result = (char*)calloc(sizeof(char),char_max); // 存储密钥 char *key = (char*)calloc(sizeof(char), 27); // 加密还是解密 bool isEnycript = true; char ch = 'Y'; // 错误输入次数,连续出错三次程序退出 int fail_time = 0; // 临时变量,用于清空输入区 int c = 0; printf_s("请输入明文(或密文),以回车键结束:\n"); // 获取需要加密或解密的字符 gets(text); // 获取密钥 printf_s("请输入密钥:"); gets(key); // 读取密钥,保证输入的密钥只含字母 while (!check_key(key)) { // 如果连续输入错误超过3次,程序退出 fail_time++; if (fail_time == 3) { printf_s("连续输入错误超过3次,程序退出\n"); system("pause"); return 0; } printf_s("密钥含有非法字符,请重新输入(密钥只能为字母,且长度小于等于26):"); gets(key); } fail_time = 0; // 选择加密或解密 printf_s("请问是加密(Y)或解密(N):"); scanf_s("%c", &ch); while (toupper(ch)!='Y'&&toupper(ch)!='N') { while ((c = getchar()) != '\n' && c != EOF); fail_time++; if (fail_time == 3) { printf_s("连续输入错误超过3次,程序退出\n"); system("pause"); return 0; } printf_s("请输入Y(加密)或N(解密):"); scanf_s("%c", &ch); } // 执行加密 singleTablereplacement(text, result, key,true); printf_s("%s\n", result); free(text); free(result); system("pause"); return 0; } bool check_key(char *key) { int i = 0, length = 0; length = strlen(key); for (i = 0; i < length; i++) { if (!isalpha(key[i])) return false; } return true; } void singleTablereplacement(char* text,char *result,char*key,bool isEnycript) { // 存储明文 char *plain_table = (char*)calloc(sizeof(char), 27); // 存储密文 char *cipher_table = (char*)calloc(sizeof(char), 27); // 检查密文中的字母是否重复,哈希值 int *check_repeat = (int*)calloc(sizeof(int), 27); int i = 0, pos = 0, pass = 0; // 明文字母 for (i = 65; i < 91; i++) { plain_table[i-65] = (char)i; } // 填写密文字母 i = 0; // 依次遍历密钥 while (key[i]) { // 如果该字母还没有出现过,该字母哈希值所在位置对应为0 if (!check_repeat[(toupper(key[i]) - 65)]) { // 将密钥放到密文表中 cipher_table[pos] = toupper(key[i]); // 标记该字母已经出现过 check_repeat[(toupper(key[i]) - 65)] = 1; pos++; } i++; } for (i = 65; i < 91; i++) { // 把没有出现过的密钥字母填入密文表中 if (!check_repeat[i - 65]) { cipher_table[pos] = (char)i; check_repeat[i - 65] = 1; pos++; } } // 进行加密或解密 i = 0; if (isEnycript) { while (text[i]) { // 如果是字母,找到该明文字母对应的密文字母 if (isalpha(text[i])) result[i - pass] = cipher_table[toupper(text[i]) - 65]; // 去掉所有' ','\t','\n','\v','\r','\f'显示为空的字符 else if (isspace(text[i])) { i++; pass++; continue; } // 其它字符原样输出 else result[i - pass] = text[i]; i++; } } else { while (text[i]) { if (isalpha(text[i])) result[i - pass] = plain_table[toupper(text[i] - 65)]; else if (isspace(text[i])) { i++; pass++; continue; } else result[i - pass] = text[i]; i++; } } return; }
the_stack_data/1190835.c
#include <stdio.h> int Equation(int x1, int y1, int x2, int y2) { int m, c; m = (y2 - y1) / (x2 - x1); c = y1 - m * x1; printf("\n Equation of line: y = %dx + %d", m, c); } int main() { int x1, x2, y1, y2; int m, c; printf("\n Enter the First co-ordinates: "); scanf("\n %d%d", &x1, &y1); printf("\n Enter the Second co-ordinates: "); scanf("\n %d%d", &x2, &y2); Equation(x1, y1, x2, y2); }
the_stack_data/167329500.c
// gcc -O2 algo.c -o nombre -fopenmp #include <stdlib.h> #include <stdio.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #define omp_get_num_threads() 1 #endif int main(int argc, char** argv) { int i, j; double t1, t2, total; //Argumento de entrada, N es el número de componentes del vector if (argc<2){ printf("Falta tamaño de la matriz y del vector\n"); exit(-1); } unsigned int N = atoi(argv[1]); double *v1, *v2, **M; v1 = (double*) malloc(N*sizeof(double)); v2 = (double*) malloc(N*sizeof(double)); M = (double**) malloc(N*sizeof(double *)); if ( (v1==NULL) || (v2==NULL) || (M==NULL) ){ printf("Error en la reserva de espacio para los vectores\n"); exit(-2); } for (i=0; i<N; i++){ M[i] = (double*) malloc(N*sizeof(double)); if ( M[i]==NULL ){ printf("Error en la reserva de espacio para la matriz\n"); exit(-2); } } //Inicializar matriz y vectores for (i=0; i<N;i++){ v1[i] = i; v2[i] = 0; for(j=0;j<N;j++) M[i][j] = i+j; } //Tomamos tiempo antes de operar t1 = omp_get_wtime(); #pragma omp parallel { #pragma omp for //Calcular producto de matriz por vector M * v1 = v2 for (i=0; i<N;i++){ for(j=0;j<N;j++){ v2[i] += M[i][j] * v1[j]; } } } //Tomamos tiempo después de operar t2 = omp_get_wtime(); total = t2 - t1; //Imprimir el resultado primero y último, además del tiempo de ejecución printf("Tiempo(seg.):%11.9f\t / Tamaño:%u\t/ V2[0]=%8.6f V2[%d]=%8.6f\n", total,N,v2[0],N-1,v2[N-1]); // Imprimir todos los componentes de v2 para valores de entrada no muy altos if (N<20){ for (i=0; i<N;i++){ printf(" V2[%d]=%5.2f\n", i, v2[i]); } } free(v1); // libera el espacio reservado para v1 free(v2); // libera el espacio reservado para v2 for (i=0; i<N; i++) free(M[i]); free(M); return 0; }
the_stack_data/746750.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'mul_hi_uint2uint2.cl' */ source_code = read_buffer("mul_hi_uint2uint2.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "mul_hi_uint2uint2", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_uint2 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_uint2)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_uint2){{2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uint2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uint2), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_uint2 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_uint2)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_uint2){{2, 2}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uint2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uint2), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_uint2 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_uint2)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_uint2)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_uint2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_uint2), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_uint2)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
the_stack_data/198362.c
#include <stdio.h> #include <stdlib.h> #include <string.h> struct bit_field { int number :2; //2 bit memory unsigned int unumber :1; //1 bit memory char charecter :8; //8 bit memory } b1; int main() { b1.number= 1; printf("namber = %d\n", b1.number); b1.unumber = 1; printf("unamber = %d\n", b1.unumber); b1.charecter = 'x'; printf("charecter = %c\n", b1.charecter); return 0; }
the_stack_data/215767224.c
/*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kevin Ruddy. * * %sccs.include.redist.c% */ #ifndef lint static char copyright[] = "@(#) Copyright (c) 1990, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint static char sccsid[] = "@(#)fold.c 8.1 (Berkeley) 06/06/93"; #endif /* not lint */ #include <stdio.h> #include <string.h> #define DEFLINEWIDTH 80 main(argc, argv) int argc; char **argv; { extern int errno, optind; extern char *optarg; register int ch; int width; char *p; width = -1; while ((ch = getopt(argc, argv, "0123456789w:")) != EOF) switch (ch) { case 'w': if ((width = atoi(optarg)) <= 0) { (void)fprintf(stderr, "fold: illegal width value.\n"); exit(1); } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (width == -1) { p = argv[optind - 1]; if (p[0] == '-' && p[1] == ch && !p[2]) width = atoi(++p); else width = atoi(argv[optind] + 1); } break; default: (void)fprintf(stderr, "usage: fold [-w width] [file ...]\n"); exit(1); } argv += optind; argc -= optind; if (width == -1) width = DEFLINEWIDTH; if (!*argv) fold(width); else for (; *argv; ++argv) if (!freopen(*argv, "r", stdin)) { (void)fprintf(stderr, "fold: %s: %s\n", *argv, strerror(errno)); exit(1); } else fold(width); exit(0); } fold(width) register int width; { register int ch, col, new; for (col = 0;;) { switch (ch = getchar()) { case EOF: return; case '\b': new = col ? col - 1 : 0; break; case '\n': case '\r': new = 0; break; case '\t': new = (col + 8) & ~7; break; default: new = col + 1; break; } if (new > width) { putchar('\n'); col = 0; } putchar(ch); switch (ch) { case '\b': if (col > 0) --col; break; case '\n': case '\r': col = 0; break; case '\t': col += 8; col &= ~7; break; default: ++col; break; } } }
the_stack_data/697469.c
/* * Copyright (c) 2006-2021, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2006-10-09 Bernard the first version for i386 */ #include <stdint.h> uint32_t __umodsi3(uint32_t num, uint32_t den) { register uint32_t quot = 0, qbit = 1; if (den == 0) { asm volatile ("int $0"); return 0; /* if trap returns... */ } /* left-justify denominator and count shift */ while ((int32_t) den >= 0) { den <<= 1; qbit <<= 1; } while (qbit) { if (den <= num) { num -= den; quot += qbit; } den >>= 1; qbit >>= 1; } return num; }
the_stack_data/18889014.c
/* A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N). Write a function that, given a non-empty array A, returns the value of the maximal product of any triplet. For example, array A such that: A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6 contains the following example triplets: (0, 1, 2), product is −3 * 1 * 2 = −6 (1, 2, 4), product is 1 * 2 * 5 = 10 (2, 4, 5), product is 2 * 5 * 6 = 60 Therefore the function should return 60, as the product of triplet (2, 4, 5) is maximal. */ int solution(int A[], int N) { int i,j; int max1=-1001; int max2=-1001; int max3=-1001; int min1=1001; int min2=1001; for(i=0;i<N;i++){ if(A[i]>=max1){ max3=max2; max2=max1; max1=A[i]; }else if(A[i]>=max2 && A[i]<max1){ max3=max2; max2=A[i]; }else if(A[i]>=max3){ max3=A[i]; } if(A[i]<=min1){ min2=min1; min1=A[i]; }else if(A[i]<=min2 && A[i]>min1){ min2=A[i]; } } if((max1*max2*max3)>(max1*min1*min2)){ return (max1*max2*max3); }else{ return (max1*min1*min2); } }
the_stack_data/176706325.c
#define _POSIX_C_SOURCE 199309L #include <time.h> #include <curses.h> #include <stdlib.h> #define ALIVE 'o' #define DEAD ' ' /* initialize_map: initialize the map to contain only DEAD cells */ void initialize_map(void) { int y; for (y = 0; y < LINES; y++) { mvhline(y, 0, DEAD, COLS); } } /* add_glider: adds a glider at x, y, where x and y are the leftmost and * uppermost corner of the object */ void add_glider(int y, const int x) { /* make sure there's enough space */ if (y > LINES - 3 || x > COLS - 3) { endwin(); perror("add_glider: insufficient screen space"); exit(EXIT_FAILURE); } /* top row */ mvaddch(y, x, DEAD); mvaddch(y, x+1, ALIVE); mvaddch(y, x+2, DEAD); /* middle row */ y++; mvaddch(y, x, DEAD); mvaddch(y, x+1, DEAD); mvaddch(y, x+2, ALIVE); /* bottom row */ y++; mvaddch(y, x, ALIVE); mvaddch(y, x+1, ALIVE); mvaddch(y, x+2, ALIVE); refresh(); } /* add_small_exploder: adds a small exploder at x, y, where x and y are the * leftmost and uppermost corner of the object */ void add_small_exploder(int y, const int x) { if (y > LINES - 4 || x > COLS - 3) { endwin(); perror("add_small_exploder: insufficient screen space"); exit(EXIT_FAILURE); } /* top row */ mvaddch(y, x, DEAD); mvaddch(y, x+1, ALIVE); mvaddch(y, x+2, DEAD); /* mid-top row */ y++; mvaddch(y, x, ALIVE); mvaddch(y, x+1, ALIVE); mvaddch(y, x+2, ALIVE); /* mid-bottom row */ y++; mvaddch(y, x, ALIVE); mvaddch(y, x+1, DEAD); mvaddch(y, x+2, ALIVE); /* bottom row */ y++; mvaddch(y, x, DEAD); mvaddch(y, x+1, ALIVE); mvaddch(y, x+2, DEAD); refresh(); } void make_being(int y, int x, bool being[]); #define CHECK_AND_INC(y, x)\ if (mvinch((y), (x)) == ALIVE) {\ count++;\ } /* count_neighbours: counts the number of neighbours that are alive */ unsigned int count_neighbours(int y, int x) { unsigned int count = 0; /* normal case, need to check all 8 neighbors */ if (y != 0 && y != LINES - 1 && x != 0 && x != COLS - 1) { CHECK_AND_INC(y-1, x-1) /* up-left */ CHECK_AND_INC(y-1, x) /* up */ CHECK_AND_INC(y-1, x+1) /* up-right */ CHECK_AND_INC( y, x-1) /* left */ CHECK_AND_INC( y, x+1) /* right */ CHECK_AND_INC(y+1, x-1) /* down-left */ CHECK_AND_INC(y+1, x) /* down */ CHECK_AND_INC(y+1, x+1) /* down-right */ } /* want edges to wrap so that the top connects to the bottom, left to * right, etc. */ /* top edge */ else if (y == 0 && x != 0 && x != COLS - 1) { CHECK_AND_INC(LINES-1, x-1) /* up-left becomes bottom edge-left */ CHECK_AND_INC(LINES-1, x) /* up becomes bottom */ CHECK_AND_INC(LINES-1, x+1) /* up-right becomes bottom-right */ CHECK_AND_INC( y, x-1) /* left */ CHECK_AND_INC( y, x+1) /* right */ CHECK_AND_INC( y+1, x-1) /* down-left */ CHECK_AND_INC( y+1, x) /* down */ CHECK_AND_INC( y+1, x+1) /* down-right */ } /* left edge */ else if (x == 0 && y != 0 && y != LINES - 1) { CHECK_AND_INC(y-1, COLS-1) /* up-left becomes up-right edge */ CHECK_AND_INC(y-1, x) /* up */ CHECK_AND_INC(y-1, x+1) /* up-right */ CHECK_AND_INC( y, COLS-1) /* left becomes right edge */ CHECK_AND_INC( y, x+1) /* right */ CHECK_AND_INC(y+1, COLS-1) /* down-left becomes down-right edge */ CHECK_AND_INC(y+1, x) /* down */ CHECK_AND_INC(y+1, x+1) /* down-right */ } /* right edge */ else if (x == COLS - 1 && y != 0 && y != LINES - 1) { CHECK_AND_INC(y-1, x-1) /* etc. */ CHECK_AND_INC(y-1, x) CHECK_AND_INC(y-1, 0) CHECK_AND_INC( y, x-1) CHECK_AND_INC( y, 0) CHECK_AND_INC(y+1, x-1) CHECK_AND_INC(y+1, x) CHECK_AND_INC(y+1, 0) } /* bottom edge */ else if (y == LINES - 1 && x != 0 && x != COLS - 1) { CHECK_AND_INC(y-1, x-1) CHECK_AND_INC(y-1, x) CHECK_AND_INC(y-1, x+1) CHECK_AND_INC( y, x-1) CHECK_AND_INC( y, x+1) CHECK_AND_INC( 0, x-1) CHECK_AND_INC( 0, x) CHECK_AND_INC( 0, x+1) } /* top-left corner */ else if (y == 0 && x == 0) { CHECK_AND_INC(LINES-1, COLS-1) /* up-left becomes bottom edge-right edge */ CHECK_AND_INC(LINES-1, x) /* up becomes bottom-edge */ CHECK_AND_INC(LINES-1, x+1) /* up-right becomes bottom edge-right */ CHECK_AND_INC( y, COLS-1) /* left becomes right edge */ CHECK_AND_INC( y, x+1) /* right */ CHECK_AND_INC( y+1, COLS-1) /* down-left becomes down-right edge */ CHECK_AND_INC( y+1, x) /* down */ CHECK_AND_INC( y+1, x+1) /* down-right */ } /* top-right corner */ else if (y == 0 && x == COLS - 1) { CHECK_AND_INC(LINES-1, x-1) /* etc. */ CHECK_AND_INC(LINES-1, x) CHECK_AND_INC(LINES-1, 0) CHECK_AND_INC( y, x-1) CHECK_AND_INC( y, 0) CHECK_AND_INC( y+1, x-1) CHECK_AND_INC( y+1, x) CHECK_AND_INC( y+1, 0) } /* bottom-left corner */ else if (y == LINES - 1 && x == 0) { CHECK_AND_INC(y-1, COLS-1) CHECK_AND_INC(y-1, x) CHECK_AND_INC(y-1, x+1) CHECK_AND_INC( y, COLS-1) CHECK_AND_INC( y, x+1) CHECK_AND_INC( 0, COLS-1) CHECK_AND_INC( 0, x) CHECK_AND_INC( 0, x+1) } /* bottom-right corner */ else if (y == LINES - 1 && x == COLS - 1) { CHECK_AND_INC(y-1, x-1) CHECK_AND_INC(y-1, x) CHECK_AND_INC(y-1, 0) CHECK_AND_INC( y, x-1) CHECK_AND_INC( y, 0) CHECK_AND_INC( 0, x-1) CHECK_AND_INC( 0, x) CHECK_AND_INC( 0, 0) } return count; } void update_cell(chtype testch, unsigned int count, int y, int x) { if (testch == ALIVE) { if (count <= 1) { mvaddch(y, x, DEAD); /* cell dies if it has 0 or 1 neighbour */ } else if (count >= 4) { mvaddch(y, x, DEAD); /* cell dies if it has 4 or more neighbours */ } else { ; /* cell survives if it has 2 or 3 neighbours */ } } else if (testch == DEAD) { if (count == 3) { mvaddch(y, x, ALIVE); /* cell becomes populated */ } else { ; /* cell stays dead */ } } } int main(void) { const struct timespec ts = {0, 5000000}; int *neighbour_count; /* initialize curses */ initscr(); cbreak(); noecho(); curs_set(0); clear(); printw("LINES: %d, COLS: %d\n", LINES, COLS); refresh(); /* initialize the game of life */ initialize_map(); add_glider(0, 80); add_glider(0, 70); add_glider(0, 60); add_small_exploder(25, 105); add_small_exploder(40, 15); refresh(); /* main loop to update the screen */ while (true) { int x, y; neighbour_count = malloc(LINES*COLS*(sizeof *neighbour_count)); /* generate the neighbour_count array */ for (y = 0; y < LINES; y++) { for (x = 0; x < COLS; x++) { /* equivalent to neighbour_count[y][x], alternate form: *neighbour_count[y*COLS+x] = count_neighbours(y, x); */ *(neighbour_count + y*COLS + x) = count_neighbours(y, x); } } /* revive or kill each cell based on its neighbour count */ for (y = 0; y < LINES; y++) { for (x = 0; x < COLS; x++) { chtype testch = mvinch(y, x) & A_CHARTEXT; int count = *(neighbour_count + y*COLS + x); update_cell(testch, count, y, x); } } nanosleep(&ts, NULL); refresh(); } /* release malloc'd memory */ free(neighbour_count); /* make ncurses clean up */ endwin(); exit(EXIT_SUCCESS); }
the_stack_data/206392495.c
// // Created by dingjing on 2020/1/14. // #include <X11/Xlib.h> /* 每个Xlib必须包含的头文件 */ #include <assert.h> /* 返回值验证 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> int main(void) { Display *d; Window w; XEvent e; char *msg = "Hello, World!"; int s; bool done = false; /* 与XServer 进行连接 */ d = XOpenDisplay(NULL); if (d == NULL) { fprintf(stderr, "Cannot open display\n"); exit(1); } /* 获取屏幕 */ s = DefaultScreen(d); /* 创建窗口 */ w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 640, 480, 0, BlackPixel(d, s), WhitePixel(d, s)); /* register interest in the delete window message */ Atom wmDeleteMessage = XInternAtom(d, "WM_DELETE_WINDOW", False); XSetWMProtocols(d, w, &wmDeleteMessage, 1); /* 设置感兴趣的事件 */ XSelectInput(d, w, ExposureMask | KeyPressMask | StructureNotifyMask); /* 在`屏幕上`显示`窗口` */ XMapWindow(d, w); /* 事件循环 */ while (!done) { XNextEvent(d, &e); #if 0 /* 绘制窗口 */ if (e.type == Expose) { XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10); XDrawString(d, w, DefaultGC(d, s), 50, 50, msg, strlen(msg)); } /* 按键退出 */ switch(e.type){ /*绘制*/ case KeyPress: XDestroyWindow(d, w); break; case DestroyNotify: done = true; break; case ClientMessage: if (e.xclient.data.l[0] == wmDeleteMessage){ done = true; } break; } #endif } XCloseDisplay(d); return 0; }
the_stack_data/170454336.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include <sys/sem.h> #define WAIT_TIME 2 /* * CS356 Operating System Project 1 Problem 4: * Burger Buddies Problem * * a simple multithread program using semaphores * in order to solve the burgur buddies problem * * auther: Ma Yesheng 5140209064 */ // declarations of thread functions void *cook_func(void *args); void *cashier_func(void *args); void *customer_func(void *args); // declaration of global variables int cook_size; int cashier_size; int customer_size; int rack_size; int burger_cnt; int remain_cnt; // declarations for semaphores sem_t console_mutex; sem_t burger_cnt_mutex; sem_t remain_cnt_mutex; sem_t rack; sem_t burger_on_rack; sem_t customer_order; sem_t cashier_serve; int main(int argc, char **argv) { // fetch arguments and validity test int i; if (argc != 5) { printf("USAGE: four arguments cook, cashier, customer, rack_size\n"); return -1; } cook_size = (int)strtol(argv[1], NULL, 10); cashier_size = (int)strtol(argv[2], NULL, 10); customer_size = (int)strtol(argv[3], NULL, 10); rack_size = (int)strtol(argv[4], NULL, 10); if (cook_size<=0 || cashier_size<=0 || customer_size<=0 || rack_size<=0) { printf("ERROR: invalid argument\n"); return -1; } srand(time(NULL)); printf("cook[%d], cashier[%d], customer[%d], rack[%d]\n", cook_size, cashier_size, customer_size, rack_size); printf("====== Burger Buddies Begin ======\n"); // initialize global variables burger_cnt = 0; remain_cnt = customer_size; // initialize semaphores sem_init(&console_mutex, 0, 1); sem_init(&burger_cnt_mutex, 0, 1); sem_init(&rack, 0, rack_size); sem_init(&customer_order, 0, 0); sem_init(&cashier_serve, 0, 0); sem_init(&remain_cnt_mutex, 0, customer_size); sem_init(&burger_on_rack, 0, 0); // create threads int *cook_args = malloc(cook_size*sizeof(int)); int *cashier_args = malloc(cashier_size*sizeof(int)); int *customer_args= malloc(customer_size*sizeof(int)); pthread_t *cook_thread = malloc(cook_size*sizeof(pthread_t)); pthread_t *cashier_thread = malloc(cashier_size*sizeof(pthread_t)); pthread_t *customer_thread = malloc(customer_size*sizeof(pthread_t)); for (i = 0; i < cook_size; ++i) { cook_args[i] = i+1; pthread_create(cook_thread+i, NULL, cook_func, cook_args+i); } for (i = 0; i < cashier_size; ++i) { cashier_args[i] = i+1; pthread_create(cashier_thread+i, NULL, cashier_func, cashier_args+i); } for (i = 0; i < customer_size; ++i) { customer_args[i] = i+1; pthread_create(customer_thread+i, NULL, customer_func, customer_args+i); } // join threads for (i = 0; i < cook_size; ++i) pthread_join(cook_thread[i], NULL); for (i = 0; i < cashier_size; ++i) pthread_join(cashier_thread[i], NULL); for (i = 0; i < customer_size; ++i) pthread_join(customer_thread[i], NULL); printf("====== Burger Buddies Finish ======\n"); // destroy semaphores sem_destroy(&console_mutex); sem_destroy(&burger_cnt_mutex); sem_destroy(&rack); sem_destroy(&customer_order); sem_destroy(&cashier_serve); sem_destroy(&remain_cnt_mutex); sem_destroy(&burger_on_rack); // free resources free(cook_args); free(cashier_args); free(customer_args); free(cook_thread); free(cashier_thread); free(customer_thread); return 0; } /* * cook thread definition: * 1. check if enough burgers have been produced * 2. wait for empty rack * 3. produce burger and put on rack */ void *cook_func(void *args) { int cook_id = *(int *) args; while (1) { sleep(rand()%WAIT_TIME); sem_wait(&burger_cnt_mutex); if (burger_cnt >= customer_size) { sem_post(&burger_cnt_mutex); break; } else { burger_cnt++; sem_post(&burger_cnt_mutex); } sem_wait(&console_mutex); printf("cooker[%d] makes a burger\n", cook_id); sem_post(&console_mutex); sem_wait(&rack); sem_post(&burger_on_rack); } return NULL; } /* * definiton of cashier thread: * 1. check if all customers have been served * 2. wait for a customer to come * 3. wait for burger to be put on rack * 4. decrement the number of burgers in rack * 5. take burger to customer */ void *cashier_func(void *args) { int cashier_id = *(int *) args; while (1) { sem_wait(&remain_cnt_mutex); if (remain_cnt == 0) { sem_post(&remain_cnt_mutex); break; } else { remain_cnt--; sem_post(&remain_cnt_mutex); } sem_wait(&customer_order); sem_wait(&console_mutex); printf("cashier[%d] accepts order\n", cashier_id); sem_post(&console_mutex); sem_wait(&burger_on_rack); sem_post(&rack); sem_post(&cashier_serve); sem_wait(&console_mutex); printf("cashier[%d] takes a burger to customer\n", cashier_id); sem_post(&console_mutex); } return NULL; } /* * customer_thread: * 1. inform a cashier of arrival and order * 2. wait for a burger to be taken * 3. leave */ void *customer_func(void *args) { int customer_id = *(int *) args; sleep(rand()%WAIT_TIME); sem_wait(&console_mutex); printf("customer[%d] comes\n", customer_id); sem_post(&console_mutex); sem_post(&customer_order); sem_wait(&cashier_serve); return NULL; }
the_stack_data/70395.c
bitcnt(var) int var; /* ** Count the number of 1's in the integer var. As long ** as left shift is zero fill this routine is machine ** independent. */ { register int i, j, ret; j = var; for (ret = 0, i = 1; i; i <<= 1) if (i & j) ret++; return (ret); }
the_stack_data/178624.c
extern void abort (void); extern void exit (int); typedef int fract32; int main () { fract32 f = 0xfffffedc, g; int a; a = __builtin_bfin_norm_fr1x32 (f); g = f << a; if (g != 0xb7000000) abort (); exit (0); }
the_stack_data/1040884.c
int main() { int a = ~~5; return !(a == 5); }
the_stack_data/26699356.c
//int foo(int a) { return a+1; } void demo3(char *src, char *dst) { char *s1 = src; char *d1 = dst; char c1 = *s1; while( c1 != 0 ) { if( c1 == '/' ) { *d1 = '\\'; } else { *d1 = c1; } ++s1; ++d1; c1 = *s1; } return; }
the_stack_data/112135.c
/* * POK header * * The following file is a part of the POK project. Any modification should * be made according to the POK licence. You CANNOT use this file or a part * of a file for your own project. * * For more information on the POK licence, please see our LICENCE FILE * * Please follow the coding guidelines described in doc/CODING_GUIDELINES * * Copyright (c) 2007-2021 POK team */ /* s_tanf.c -- float version of s_tan.c. * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #ifdef POK_NEEDS_LIBMATH #include "math_private.h" #include <libm.h> float tanf(float x) { float y[2], z = 0.0; int32_t n, ix; GET_FLOAT_WORD(ix, x); /* |x| ~< pi/4 */ ix &= 0x7fffffff; if (ix <= 0x3f490fda) return __kernel_tanf(x, z, 1); /* tan(Inf or NaN) is NaN */ else if (ix >= 0x7f800000) return x - x; /* NaN */ /* argument reduction needed */ else { n = __ieee754_rem_pio2f(x, y); return __kernel_tanf(y[0], y[1], 1 - ((n & 1) << 1)); /* 1 -- n even -1 -- n odd */ } } #endif
the_stack_data/135673.c
int x = 4294967295; int main(void) { return 0; }
the_stack_data/103266151.c
#include<stdio.h> int main() { int i=1; int n=5; while(i<=10) { printf("%d x %d = %d\n", n , i , n*i); i++; } return 0; }
the_stack_data/98576381.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "zara Ali"); description = (char *)malloc(30 * sizeof(char)); if (description == NULL) { fprintf(stderr, "Error = unable to allocate requried memory. \n"); } else { strcpy(description, "zara ali a DPS student."); } description = (char *)realloc( description,100 * sizeof(char)); if (description == NULL) { fprintf(stderr, "Error - unable to allocate requried memory. \n"); } else { strcat( description, "She is in class 10th"); } printf("Name = %s \n", name); printf("Description: %s \n", description); free(description); }
the_stack_data/55980.c
#include <stdio.h> #include <string.h> int main(void) { char buy[1001]; char want[1001]; unsigned int number = 0; scanf("%s", buy); scanf("%s", want); for (int i = 0; want[i] != '\0'; i++) { for (int j = 0; buy[j] != '\0'; j++) { if (want[i] == buy[j]) { want[i] = '*'; buy[j] = '!'; number++; } } } if (number == strlen(want)) printf("Yes %lu", strlen(buy) - number); else printf("No %lu", strlen(want) - number); }
the_stack_data/93808.c
/* * Copyright (c) 2016 Simon Schmidt * * Copyright(C) Caldera International Inc. 2001-2002. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code and documentation must retain the above * copyright notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - All advertising materials mentioning features or use of this software must * display the following acknowledgement: This product includes software developed * or owned by Caldera International, Inc. * * - Neither the name of Caldera International, Inc. nor the names of other * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA INTERNATIONAL, INC. * AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE FOR * ANY DIRECT, INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #define L 512 #define N 7 #define C 20 #define MEM (16*2048) #define NF 10 FILE *is, *os; char *dirtry[] = {"/usr/tmp", "/tmp", NULL}; char **dirs; char file1[30]; char *file = file1; char *filep; int nfiles; unsigned nlines; unsigned ntext; int *lspace; char *tspace; char *eol(); int mflg; int cflg; int uflg; char *outfil; int unsafeout; /*kludge to assure -m -o works*/ char tabchar; int eargc; char **eargv; char zero[256]; char fold[256] = { 0200,0201,0202,0203,0204,0205,0206,0207, 0210,0211,0212,0213,0214,0215,0216,0217, 0220,0221,0222,0223,0224,0225,0226,0227, 0230,0231,0232,0233,0234,0235,0236,0237, 0240,0241,0242,0243,0244,0245,0246,0247, 0250,0251,0252,0253,0254,0255,0256,0257, 0260,0261,0262,0263,0264,0265,0266,0267, 0270,0271,0272,0273,0274,0275,0276,0277, 0300,0301,0302,0303,0304,0305,0306,0307, 0310,0311,0312,0313,0314,0315,0316,0317, 0320,0321,0322,0323,0324,0325,0326,0327, 0330,0331,0332,0333,0334,0335,0336,0337, 0340,0341,0342,0343,0344,0345,0346,0347, 0350,0351,0352,0353,0354,0355,0356,0357, 0360,0361,0362,0363,0364,0365,0366,0367, 0370,0371,0372,0373,0374,0375,0376,0377, 0000,0001,0002,0003,0004,0005,0006,0007, 0010,0011,0012,0013,0014,0015,0016,0017, 0020,0021,0022,0023,0024,0025,0026,0027, 0030,0031,0032,0033,0034,0035,0036,0037, 0040,0041,0042,0043,0044,0045,0046,0047, 0050,0051,0052,0053,0054,0055,0056,0057, 0060,0061,0062,0063,0064,0065,0066,0067, 0070,0071,0072,0073,0074,0075,0076,0077, 0100,0101,0102,0103,0104,0105,0106,0107, 0110,0111,0112,0113,0114,0115,0116,0117, 0120,0121,0122,0123,0124,0125,0126,0127, 0130,0131,0132,0133,0134,0134,0136,0137, 0140,0101,0102,0103,0104,0105,0106,0107, 0110,0111,0112,0113,0114,0115,0116,0117, 0120,0121,0122,0123,0124,0125,0126,0127, 0130,0131,0132,0173,0174,0175,0176,0177 }; char nofold[256] = { 0200,0201,0202,0203,0204,0205,0206,0207, 0210,0211,0212,0213,0214,0215,0216,0217, 0220,0221,0222,0223,0224,0225,0226,0227, 0230,0231,0232,0233,0234,0235,0236,0237, 0240,0241,0242,0243,0244,0245,0246,0247, 0250,0251,0252,0253,0254,0255,0256,0257, 0260,0261,0262,0263,0264,0265,0266,0267, 0270,0271,0272,0273,0274,0275,0276,0277, 0300,0301,0302,0303,0304,0305,0306,0307, 0310,0311,0312,0313,0314,0315,0316,0317, 0320,0321,0322,0323,0324,0325,0326,0327, 0330,0331,0332,0333,0334,0335,0336,0337, 0340,0341,0342,0343,0344,0345,0346,0347, 0350,0351,0352,0353,0354,0355,0356,0357, 0360,0361,0362,0363,0364,0365,0366,0367, 0370,0371,0372,0373,0374,0375,0376,0377, 0000,0001,0002,0003,0004,0005,0006,0007, 0010,0011,0012,0013,0014,0015,0016,0017, 0020,0021,0022,0023,0024,0025,0026,0027, 0030,0031,0032,0033,0034,0035,0036,0037, 0040,0041,0042,0043,0044,0045,0046,0047, 0050,0051,0052,0053,0054,0055,0056,0057, 0060,0061,0062,0063,0064,0065,0066,0067, 0070,0071,0072,0073,0074,0075,0076,0077, 0100,0101,0102,0103,0104,0105,0106,0107, 0110,0111,0112,0113,0114,0115,0116,0117, 0120,0121,0122,0123,0124,0125,0126,0127, 0130,0131,0132,0133,0134,0135,0136,0137, 0140,0141,0142,0143,0144,0145,0146,0147, 0150,0151,0152,0153,0154,0155,0156,0157, 0160,0161,0162,0163,0164,0165,0166,0167, 0170,0171,0172,0173,0174,0175,0176,0177 }; char nonprint[256] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 }; char dict[256] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1 }; struct field { char *code; char *ignore; int nflg; int rflg; int bflg[2]; int m[2]; int n[2]; } fields[NF]; struct field proto = { nofold+128, zero+128, 0, 1, 0,0, 0,-1, 0,0 }; int nfields; int error = 1; char *setfil(); //char *sbrk(); //char *brk(); #define qsort qsux struct merg { char l[L]; FILE *b; } *ibuf[256]; void sort(); void merge(int a,int b); int rline(struct merg *mp); void disorder(char *s,char *t); void newfile(); char * setfil(int i); void oldfile(); void safeoutfil(); void cant(char *f); void diag(char *s,char *t); void term(); int cmp(char *i, char *j); int cmpa(register char *pa, register char *pb); char * skip(char *pp, struct field *fp, int j); char * eol(register char *p); void copyproto(); void field(char *s,int k); int number(char **ppa); int blank(int c); void qsort(char **a, char**); int (*compare)(register char *pa, register char *pb) = cmpa; void main(int argc, char **argv) { register int a; extern char end[1]; char *ep; char *arg; struct field *p, *q; int i; copyproto(); eargv = argv; while (--argc > 0) { if(**++argv == '-') for(arg = *argv;;) { switch(*++arg) { case '\0': if(arg[-1] == '-') eargv[eargc++] = "-"; break; case 'o': if(--argc > 0) outfil = *++argv; continue; case 'T': if (--argc > 0) dirtry[0] = *++argv; continue; default: field(++*argv,nfields>0); break; } break; } else if (**argv == '+') { if(++nfields>=NF) { diag("too many keys",""); exit(1); } copyproto(); field(++*argv,0); } else eargv[eargc++] = *argv; } q = &fields[0]; for(a=1; a<=nfields; a++) { p = &fields[a]; if(p->code != proto.code) continue; if(p->ignore != proto.ignore) continue; if(p->nflg != proto.nflg) continue; if(p->rflg != proto.rflg) continue; if(p->bflg[0] != proto.bflg[0]) continue; if(p->bflg[1] != proto.bflg[1]) continue; p->code = q->code; p->ignore = q->ignore; p->nflg = q->nflg; p->rflg = q->rflg; p->bflg[0] = p->bflg[1] = q->bflg[0]; } if(eargc == 0) eargv[eargc++] = "-"; if(cflg && eargc>1) { diag("can check only 1 file",""); exit(1); } safeoutfil(); ep = end + MEM; lspace = (int *)sbrk(0); while((int)brk(ep) == -1) ep -= 512; brk(ep -= 512); /* for recursion */ a = ep - (char*)lspace; nlines = (a-L); nlines /= (5*(sizeof(char *)/sizeof(char))); ntext = nlines*8; tspace = (char *)(lspace + nlines); a = -1; for(dirs=dirtry; *dirs; dirs++) { sprintf(filep=file1, "%s/stm%05uaa", *dirs, getpid()); while (*filep) filep++; filep -= 2; if ( (a=open(file, O_RDWR|O_CREAT|O_TRUNC, 0600)) >=0) break; } if(a < 0) { diag("can't locate temp",""); exit(1); } close(a); signal(SIGHUP, term); if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, term); signal(SIGPIPE,term); signal(SIGTERM,term); nfiles = eargc; if(!mflg && !cflg) { sort(); fclose(stdin); } for(a = mflg|cflg?0:eargc; a+N<nfiles || unsafeout&&a<eargc; a=i) { i = a+N; if(i>=nfiles) i = nfiles; newfile(); merge(a, i); } if(a != nfiles) { oldfile(); merge(a, nfiles); } error = 0; term(); } void sort() { register char *cp; register char **lp; register int c; int done; int i; char *f; done = 0; i = 0; c = EOF; do { cp = tspace; lp = (char **)lspace; while(lp < (char **)lspace+nlines && cp < tspace+ntext) { *lp++ = cp; while(c != '\n') { if(c != EOF) { *cp++ = c; c = getc(is); continue; } else if(is) fclose(is); if(i < eargc) { if((f = setfil(i++)) == 0) is = stdin; else if((is = fopen(f, "r")) == NULL) cant(f); c = getc(is); } else break; } *cp++ = '\n'; if(c == EOF) { done++; lp--; break; } c = getc(is); } qsort((char **)lspace, lp); if(done == 0 || nfiles != eargc) newfile(); else oldfile(); while(lp > (char **)lspace) { cp = *--lp; if(*cp) do putc(*cp, os); while(*cp++ != '\n'); } fclose(os); } while(done == 0); } void merge(int a,int b) { struct merg *p; register char *cp, *dp; register int i; struct merg **ip, *jp; char *f; int j; int k, l; int muflg; p = (struct merg *)lspace; j = 0; for(i=a; i < b; i++) { f = setfil(i); if(f == 0) p->b = stdin; else if((p->b = fopen(f, "r")) == NULL) cant(f); ibuf[j] = p; if(!rline(p)) j++; p++; } do { i = j; qsort((char **)ibuf, (char **)(ibuf+i)); l = 0; while(i--) { cp = ibuf[i]->l; if(*cp == '\0') { l = 1; if(rline(ibuf[i])) { k = i; while(++k < j) ibuf[k-1] = ibuf[k]; j--; } } } } while(l); muflg = mflg & uflg | cflg; i = j; while(i > 0) { cp = ibuf[i-1]->l; if(!cflg && (uflg == 0 || muflg || (*compare)(ibuf[i-1]->l,ibuf[i-2]->l))) do putc(*cp, os); while(*cp++ != '\n'); if(muflg){ cp = ibuf[i-1]->l; dp = p->l; do { } while((*dp++ = *cp++) != '\n'); } for(;;) { if(rline(ibuf[i-1])) { i--; if(i == 0) break; if(i == 1) muflg = uflg; } ip = &ibuf[i]; while(--ip>ibuf&&(*compare)(ip[0]->l,ip[-1]->l)<0){ jp = *ip; *ip = *(ip-1); *(ip-1) = jp; } if(!muflg) break; j = (*compare)(ibuf[i-1]->l,p->l); if(cflg) { if(j > 0) disorder("disorder:",ibuf[i-1]->l); else if(uflg && j==0) disorder("nonunique:",ibuf[i-1]->l); } else if(j == 0) continue; break; } } p = (struct merg *)lspace; for(i=a; i<b; i++) { fclose(p->b); p++; if(i >= eargc) unlink(setfil(i)); } fclose(os); } int rline(struct merg *mp) { char *cp; char *ce; FILE *bp; int c; bp = mp->b; cp = mp->l; ce = cp+L; do { c = getc(bp); if(c == EOF) return(1); if(cp>=ce) cp--; *cp++ = c; } while(c!='\n'); return(0); } void disorder(char *s,char *t) { register char *u; for(u=t; *u!='\n';u++) ; *u = 0; diag(s,t); term(); } void newfile() { register char *f; f = setfil(nfiles); if((os=fopen(f, "w")) == NULL) { diag("can't create ",f); term(); } nfiles++; } char * setfil(int i) { if(i < eargc) if(eargv[i][0] == '-' && eargv[i][1] == '\0') return(0); else return(eargv[i]); i -= eargc; filep[0] = i/26 + 'a'; filep[1] = i%26 + 'a'; return(file); } void oldfile() { if(outfil) { if((os=fopen(outfil, "w")) == NULL) { diag("can't create ",outfil); term(); } } else os = stdout; } void safeoutfil() { register int i; struct stat obuf,ibuf; if(!mflg||outfil==0) return; if(stat(outfil,&obuf)==-1) return; for(i=eargc-N;i<eargc;i++) { /*-N is suff., not nec.*/ if(stat(eargv[i],&ibuf)==-1) continue; if(obuf.st_dev==ibuf.st_dev&& obuf.st_ino==ibuf.st_ino) unsafeout++; } } void cant(char *f) { diag("can't open ",f); term(); } void diag(char *s,char *t) { fputs("sort: ",stderr); fputs(s,stderr); fputs(t,stderr); fputs("\n",stderr); } void term() { register int i; signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGTERM, SIG_IGN); if(nfiles == eargc) nfiles++; for(i=eargc; i<=nfiles; i++) { /*<= in case of interrupt*/ unlink(setfil(i)); /*with nfiles not updated*/ } exit(error); } int cmp(char *i, char *j) { register char *pa, *pb; char *code, *ignore; int a, b; int k; char *la, *lb; int sa; int sb; char *ipa, *ipb, *jpa, *jpb; struct field *fp; for(k = nfields>0; k<=nfields; k++) { fp = &fields[k]; pa = i; pb = j; if(k) { la = skip(pa, fp, 1); pa = skip(pa, fp, 0); lb = skip(pb, fp, 1); pb = skip(pb, fp, 0); } else { la = eol(pa); lb = eol(pb); } if(fp->nflg) { while(blank(*pa)) pa++; while(blank(*pb)) pb++; sa = sb = fp->rflg; if(*pa == '-') { pa++; sa = -sa; } if(*pb == '-') { pb++; sb = -sb; } for(ipa = pa; ipa<la&&isdigit(*ipa); ipa++) ; for(ipb = pb; ipb<lb&&isdigit(*ipb); ipb++) ; jpa = ipa; jpb = ipb; a = 0; if(sa==sb) while(ipa > pa && ipb > pb) if(b = *--ipb - *--ipa) a = b; while(ipa > pa) if(*--ipa != '0') return(-sa); while(ipb > pb) if(*--ipb != '0') return(sb); if(a) return(a*sa); if(*(pa=jpa) == '.') pa++; if(*(pb=jpb) == '.') pb++; if(sa==sb) while(pa<la && isdigit(*pa) && pb<lb && isdigit(*pb)) if(a = *pb++ - *pa++) return(a*sa); while(pa<la && isdigit(*pa)) if(*pa++ != '0') return(-sa); while(pb<lb && isdigit(*pb)) if(*pb++ != '0') return(sb); continue; } code = fp->code; ignore = fp->ignore; loop: while(ignore[*pa]) pa++; while(ignore[*pb]) pb++; if(pa>=la || *pa=='\n') if(pb<lb && *pb!='\n') return(fp->rflg); else continue; if(pb>=lb || *pb=='\n') return(-fp->rflg); if((sa = code[*pb++]-code[*pa++]) == 0) goto loop; return(sa*fp->rflg); } if(uflg) return(0); return(cmpa(i, j)); } int cmpa(register char *pa, register char *pb) { while(*pa == *pb) { if(*pa++ == '\n') return(0); pb++; } return( *pa == '\n' ? fields[0].rflg: *pb == '\n' ?-fields[0].rflg: *pb > *pa ? fields[0].rflg: -fields[0].rflg ); } char * skip(char *pp, struct field *fp, int j) { register int i; register char *p; p = pp; if( (i=fp->m[j]) < 0) return(eol(p)); while(i-- > 0) { if(tabchar != 0) { while(*p != tabchar) if(*p != '\n') p++; else goto ret; p++; } else { while(blank(*p)) p++; while(!blank(*p)) if(*p != '\n') p++; else goto ret; } } if(fp->bflg[j]) while(blank(*p)) p++; i = fp->n[j]; while(i-- > 0) { if(*p != '\n') p++; else goto ret; } ret: return(p); } char * eol(register char *p) { while(*p != '\n') p++; return(p); } void copyproto() { register int i; register int *p, *q; p = (int *)&proto; q = (int *)&fields[nfields]; for(i=0; i<sizeof(proto)/sizeof(*p); i++) *q++ = *p++; } void field(char *s,int k) { register struct field *p; register int d; p = &fields[nfields]; d = 0; for(; *s!=0; s++) { switch(*s) { case '\0': return; case 'b': p->bflg[k]++; break; case 'd': p->ignore = dict+128; break; case 'f': p->code = fold+128; break; case 'i': p->ignore = nonprint+128; break; case 'c': cflg = 1; continue; case 'm': mflg = 1; continue; case 'n': p->nflg++; break; case 't': tabchar = *++s; if(tabchar == 0) s--; continue; case 'r': p->rflg = -1; continue; case 'u': uflg = 1; break; case '.': if(p->m[k] == -1) /* -m.n with m missing */ p->m[k] = 0; d = &fields[0].n[0]-&fields[0].m[0]; default: p->m[k+d] = number(&s); } compare = cmp; } } int number(char **ppa) { int n; register char *pa; pa = *ppa; n = 0; while(isdigit(*pa)) { n = n*10 + *pa - '0'; *ppa = pa++; } return(n); } int blank(int c) { if(c==' ' || c=='\t') return(1); return(0); } #define qsexc(p,q) t= *p;*p= *q;*q=t #define qstexc(p,q,r) t= *p;*p= *r;*r= *q;*q=t void qsort(char **a, char **l) { register char **i, **j; char **k; char **lp, **hp; int c; char *t; unsigned n; start: if((n=l-a) <= 1) return; n /= 2; hp = lp = a+n; i = a; j = l-1; for(;;) { if(i < lp) { if((c = (*compare)(*i, *lp)) == 0) { --lp; qsexc(i, lp); continue; } if(c < 0) { ++i; continue; } } loop: if(j > hp) { if((c = (*compare)(*hp, *j)) == 0) { ++hp; qsexc(hp, j); goto loop; } if(c > 0) { if(i == lp) { ++hp; qstexc(i, hp, j); i = ++lp; goto loop; } qsexc(i, j); --j; ++i; continue; } --j; goto loop; } if(i == lp) { if(uflg) for(k=lp+1; k<=hp;) **k++ = '\0'; if(lp-a >= l-hp) { qsort(hp+1, l); l = lp; } else { qsort(a, lp); a = hp+1; } goto start; } --lp; qstexc(j, lp, i); j = --hp; } }
the_stack_data/263518.c
#ifdef STM32F4xx #include "stm32f4xx_hal_ltdc.c" #endif #ifdef STM32F7xx #include "stm32f7xx_hal_ltdc.c" #endif #ifdef STM32H7xx #include "stm32h7xx_hal_ltdc.c" #endif #ifdef STM32L4xx #include "stm32l4xx_hal_ltdc.c" #endif
the_stack_data/198580541.c
/*** *strtokex.c - tokenize a string with given delimiters * * Copyright (c) 1989-1993, Microsoft Corporation. All rights reserved. * *Purpose: * defines strtok() - breaks string into series of token * via repeated calls. * *******************************************************************************/ #if defined(unix) #define __cdecl #endif #include <string.h> /*** *char *StrTokEx(pstring, control) - tokenize string with delimiter in control * *Purpose: * StrTokEx considers the string to consist of a sequence of zero or more * text tokens separated by spans of one or more control chars. the first * call, with string specified, returns a pointer to the first char of the * first token, and will write a null char into pstring immediately * following the returned token. when no tokens remain * in pstring a NULL pointer is returned. remember the control chars with a * bit map, one bit per ascii char. the null char is always a control char. * *Entry: * char **pstring - ptr to ptr to string to tokenize * char *control - string of characters to use as delimiters * *Exit: * returns pointer to first token in string, * returns NULL when no more tokens remain. * pstring points to the beginning of the next token. * *WARNING!!! * upon exit, the first delimiter in the input string will be replaced with '\0' * *******************************************************************************/ char * __cdecl StrTokEx (char ** pstring, const char * control) { /*unsigned*/ char *str; const /*unsigned*/ char *ctrl = control; unsigned char map[32]; int count; char *tokenstr; if(*pstring == NULL) return NULL; /* Clear control map */ for (count = 0; count < 32; count++) map[count] = 0; /* Set bits in delimiter table */ do { map[*ctrl >> 3] |= (1 << (*ctrl & 7)); } while (*ctrl++); /* Initialize str. */ str = *pstring; /* Find beginning of token (skip over leading delimiters). Note that * there is no token if this loop sets str to point to the terminal * null (*str == '\0') */ while ( (map[*str >> 3] & (1 << (*str & 7))) && *str ) str++; tokenstr = str; /* Find the end of the token. If it is not the end of the string, * put a null there. */ for ( ; *str ; str++ ) { if ( map[*str >> 3] & (1 << (*str & 7)) ) { *str++ = '\0'; break; } } /* string now points to beginning of next token */ *pstring = str; /* Determine if a token has been found. */ if ( tokenstr == str ) return NULL; else return tokenstr; }
the_stack_data/151706141.c
/******************************************************************************* * Leonardo Mudrek de Almeida * UTFPR - CT * * Descrição: Programa recebe como input na linha de comando o nome do arquivo a * ser aberto, estando no mesmo diretório e existir, sera exibido o conteúdo e * parando a cada 20 leituras de 256 caracteres do arquivo, caso contrário * finaliza execução. * * License : MIT *******************************************************************************/ /******************************************************************************* * INCLUDES *******************************************************************************/ #include <stdio.h> #include <stdbool.h> /******************************************************************************* * DEFINES E ENUMS *******************************************************************************/ #define FILE_BUFFER_SIZE 256 #define LINE_COUNT_MAX 20 /******************************************************************************* * TYPEDEFS *******************************************************************************/ /******************************************************************************* * CONSTANTES *******************************************************************************/ /******************************************************************************* * VARIÁVEIS *******************************************************************************/ /******************************************************************************* * PROTÓTIPOS DE FUNÇÕES *******************************************************************************/ static void printArgs(int quantity, char * args[]); static bool readFile(char * fileName); static void waitForEnter(void); /******************************************************************************* * FUNÇÕES EXPORTADAS *******************************************************************************/ /** * Função main * * @param parametersQuantity - quantidade parâmetros * @param args - argumentos incluídos na execução do arquivo */ void main (int parametersQuantity, char * args[]) { /* O path do arquivo executado é sempre repassado, ou seja, caso tenha algum parâmetros informado na execução, sempre será a quantidade maior que um */ if (parametersQuantity < 1) { printf("Não foram fornecidos parâmetros, finalizando execução!"); return; } printArgs(parametersQuantity, args); } /******************************************************************************* * FUNÇÕES LOCAIS *******************************************************************************/ /** * Realiza impressão/leitura de um arquivo e suas linhas * * @param quantity - quantidade parâmetros * @param argsPtr - ponteiro para o array de argumentos */ static void printArgs(int quantity, char * argsPtr[]) { for (int idx = 1; idx < quantity; idx++) { bool result = readFile(argsPtr[idx]); if (result == false) { printf("Falha ao utilizar o parâmetro \"%s\"", argsPtr[idx]); } } } /** * Leitura de um arquivo e a impressão de suas linhas * * @param fileName - nome/path do arquivo * @return true - leitura realizada com sucesso * @return false - falha na leitura */ static bool readFile(char * fileName) { FILE * filePtr = fopen(fileName, "r"); char line [FILE_BUFFER_SIZE]; if (filePtr == NULL) { return false; } int count = 0; while (feof(filePtr) == false) { if (count == LINE_COUNT_MAX) { /* Chegou no máximo para leitura, aguarda ação usuário */ waitForEnter(); count = 0; } fgets(line, FILE_BUFFER_SIZE, filePtr); printf("%s", line); count ++; } fclose(filePtr); return true; } /** * Aguarda enter ser pressionado */ static void waitForEnter(void) { fflush(stdin); printf("Aguardando enter"); fflush(stdout); getchar(); } /******************************************************************************* * END OF FILE *******************************************************************************/
the_stack_data/11074949.c
// RUN: %ucc -o %t %s -fno-semantic-interposition __attribute((always_inline)) f(int ok) { if(ok) return 1; return; // ensure this doesn't cause a crash } main() { int x = f(1); int y = f(0); return x + y; }
the_stack_data/161079840.c
/* cc transient.c -o transient -lX11 */ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <stdlib.h> #include <unistd.h> int main(void) { Display *d; Window r, f, t = None; XSizeHints h; XEvent e; d = XOpenDisplay(NULL); if (!d) exit(1); r = DefaultRootWindow(d); f = XCreateSimpleWindow(d, r, 100, 100, 400, 400, 0, 0, 0); h.min_width = h.max_width = h.min_height = h.max_height = 400; h.flags = PMinSize | PMaxSize; XSetWMNormalHints(d, f, &h); XStoreName(d, f, "floating"); XMapWindow(d, f); XSelectInput(d, f, ExposureMask); while (1) { XNextEvent(d, &e); if (t == None) { sleep(5); t = XCreateSimpleWindow(d, r, 50, 50, 100, 100, 0, 0, 0); XSetTransientForHint(d, t, f); XStoreName(d, t, "transient"); XMapWindow(d, t); XSelectInput(d, t, ExposureMask); } } XCloseDisplay(d); exit(0); }
the_stack_data/181393582.c
#include<stdio.h> int main() { int i,j; for(i=1;i<=4;i++) { for(j=1;j<=4-i;j++) printf(" "); while(j>4-i&&j<=i+3) { printf("*"); j++; } printf("\n"); } for(i=5;i<=7;i++) { for(j=1;j<=i-4;j++) printf(" "); while(j<=11-i&&j>=i-3) { printf("*"); j++; } printf("\n"); } }
the_stack_data/262690.c
/** ****************************************************************************** * @file stm32f3xx_ll_opamp.c * @author MCD Application Team * @version V1.4.0 * @date 16-December-2016 * @brief OPAMP LL module driver ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f3xx_ll_opamp.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F3xx_LL_Driver * @{ */ #if defined (OPAMP1) || defined (OPAMP2) || defined (OPAMP3) || defined (OPAMP4) /** @addtogroup OPAMP_LL OPAMP * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @addtogroup OPAMP_LL_Private_Macros * @{ */ /* Check of parameters for configuration of OPAMP hierarchical scope: */ /* OPAMP instance. */ #define IS_LL_OPAMP_FUNCTIONAL_MODE(__FUNCTIONAL_MODE__) \ ( ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_STANDALONE) \ || ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_FOLLOWER) \ || ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_PGA) \ ) /* Note: Comparator non-inverting inputs parameters are the same on all */ /* OPAMP instances. */ /* However, comparator instance kept as macro parameter for */ /* compatibility with other STM32 families. */ #define IS_LL_OPAMP_INPUT_NONINVERTING(__OPAMPX__, __INPUT_NONINVERTING__) \ ( ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO0) \ || ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO1) \ || ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO2) \ || ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO3) \ ) /* Note: Comparator non-inverting inputs parameters are the same on all */ /* OPAMP instances. */ /* However, comparator instance kept as macro parameter for */ /* compatibility with other STM32 families. */ #define IS_LL_OPAMP_INPUT_INVERTING(__OPAMPX__, __INPUT_INVERTING__) \ ( ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_IO0) \ || ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_IO1) \ || ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_CONNECT_NO) \ ) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup OPAMP_LL_Exported_Functions * @{ */ /** @addtogroup OPAMP_LL_EF_Init * @{ */ /** * @brief De-initialize registers of the selected OPAMP instance * to their default reset values. * @note If comparator is locked, de-initialization by software is * not possible. * The only way to unlock the comparator is a device hardware reset. * @param OPAMPx OPAMP instance * @retval An ErrorStatus enumeration value: * - SUCCESS: OPAMP registers are de-initialized * - ERROR: OPAMP registers are not de-initialized */ ErrorStatus LL_OPAMP_DeInit(OPAMP_TypeDef* OPAMPx) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_OPAMP_ALL_INSTANCE(OPAMPx)); /* Note: Hardware constraint (refer to description of this function): */ /* OPAMP instance must not be locked. */ if(LL_OPAMP_IsLocked(OPAMPx) == 0U) { LL_OPAMP_WriteReg(OPAMPx, CSR, 0x00000000U); } else { /* OPAMP instance is locked: de-initialization by software is */ /* not possible. */ /* The only way to unlock the OPAMP is a device hardware reset. */ status = ERROR; } return status; } /** * @brief Initialize some features of OPAMP instance. * @note This function reset bit of calibration mode to ensure * to be in functional mode, in order to have OPAMP parameters * (inputs selection, ...) set with the corresponding OPAMP mode * to be effective. * @param OPAMPx OPAMP instance * @param OPAMP_InitStruct Pointer to a @ref LL_OPAMP_InitTypeDef structure * @retval An ErrorStatus enumeration value: * - SUCCESS: OPAMP registers are initialized * - ERROR: OPAMP registers are not initialized */ ErrorStatus LL_OPAMP_Init(OPAMP_TypeDef *OPAMPx, LL_OPAMP_InitTypeDef *OPAMP_InitStruct) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_OPAMP_ALL_INSTANCE(OPAMPx)); assert_param(IS_LL_OPAMP_FUNCTIONAL_MODE(OPAMP_InitStruct->FunctionalMode)); assert_param(IS_LL_OPAMP_INPUT_NONINVERTING(OPAMPx, OPAMP_InitStruct->InputNonInverting)); /* Note: OPAMP inverting input can be used with OPAMP in mode standalone */ /* or PGA with external capacitors for filtering circuit. */ /* Otherwise (OPAMP in mode follower), OPAMP inverting input is */ /* not used (not connected to GPIO pin). */ if(OPAMP_InitStruct->FunctionalMode != LL_OPAMP_MODE_FOLLOWER) { assert_param(IS_LL_OPAMP_INPUT_INVERTING(OPAMPx, OPAMP_InitStruct->InputInverting)); } /* Note: Hardware constraint (refer to description of this function): */ /* OPAMP instance must not be locked. */ if(LL_OPAMP_IsLocked(OPAMPx) == 0U) { /* Configuration of OPAMP instance : */ /* - Functional mode */ /* - Input non-inverting */ /* - Input inverting */ /* Note: Bit OPAMP_CSR_CALON reset to ensure to be in functional mode. */ if(OPAMP_InitStruct->FunctionalMode != LL_OPAMP_MODE_FOLLOWER) { MODIFY_REG(OPAMPx->CSR, OPAMP_CSR_CALON | OPAMP_CSR_VMSEL | OPAMP_CSR_VPSEL , OPAMP_InitStruct->FunctionalMode | OPAMP_InitStruct->InputNonInverting | OPAMP_InitStruct->InputInverting ); } else { MODIFY_REG(OPAMPx->CSR, OPAMP_CSR_CALON | OPAMP_CSR_VMSEL | OPAMP_CSR_VPSEL , LL_OPAMP_MODE_FOLLOWER | OPAMP_InitStruct->InputNonInverting ); } } else { /* Initialization error: OPAMP instance is locked. */ status = ERROR; } return status; } /** * @brief Set each @ref LL_OPAMP_InitTypeDef field to default value. * @param OPAMP_InitStruct pointer to a @ref LL_OPAMP_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_OPAMP_StructInit(LL_OPAMP_InitTypeDef *OPAMP_InitStruct) { /* Set OPAMP_InitStruct fields to default values */ OPAMP_InitStruct->FunctionalMode = LL_OPAMP_MODE_FOLLOWER; OPAMP_InitStruct->InputNonInverting = LL_OPAMP_INPUT_NONINVERT_IO0; /* Note: Parameter discarded if OPAMP in functional mode follower, */ /* set anyway to its default value. */ OPAMP_InitStruct->InputInverting = LL_OPAMP_INPUT_INVERT_CONNECT_NO; } /** * @} */ /** * @} */ /** * @} */ #endif /* OPAMP1 || OPAMP2 || OPAMP3 || OPAMP4 */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/325869.c
int main() { if(0); printf("Hello"); printf("Hi"); return 0; } /* Output: HelloHi Explanation: There is a semicolon after the if statement, so this statement will be considered as separate statement; and here printf("Hello"); will not be associated with the if statement. Both printf statements will be executed. */
the_stack_data/23106.c
#include <threads.h> #include <pthread.h> #include <stdint.h> _Noreturn void thrd_exit(int result) { __pthread_exit((void*)(intptr_t)result); }
the_stack_data/11885.c
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_18__ TYPE_9__ ; typedef struct TYPE_17__ TYPE_8__ ; typedef struct TYPE_16__ TYPE_7__ ; typedef struct TYPE_15__ TYPE_6__ ; typedef struct TYPE_14__ TYPE_5__ ; typedef struct TYPE_13__ TYPE_4__ ; typedef struct TYPE_12__ TYPE_3__ ; typedef struct TYPE_11__ TYPE_2__ ; typedef struct TYPE_10__ TYPE_1__ ; /* Type definitions */ typedef union mfi_sgl {int dummy; } mfi_sgl ; struct TYPE_13__ {int /*<<< orphan*/ high; } ; union mfi_sense_ptr {int /*<<< orphan*/ * user_space; TYPE_4__ addr; TYPE_9__* sense_ptr_data; } ; struct TYPE_14__ {int /*<<< orphan*/ cmd_status; } ; struct TYPE_15__ {TYPE_5__ hdr; int /*<<< orphan*/ * raw; } ; struct mfi_linux_ioc_packet {int lioc_sge_count; size_t lioc_sgl_off; int lioc_sense_len; size_t lioc_sense_off; int /*<<< orphan*/ laen_class_locale; int /*<<< orphan*/ laen_seq_num; TYPE_8__* p; TYPE_6__ lioc_frame; TYPE_3__* lioc_sgl; } ; typedef struct mfi_linux_ioc_packet uint8_t ; typedef int uint64_t ; typedef void* uint32_t ; typedef int u_long ; struct thread {int dummy; } ; struct mfi_softc {int /*<<< orphan*/ mfi_dev; int /*<<< orphan*/ mfi_io_lock; int /*<<< orphan*/ mfi_aen_pids; } ; struct mfi_linux_ioc_aen {int lioc_sge_count; size_t lioc_sgl_off; int lioc_sense_len; size_t lioc_sense_off; int /*<<< orphan*/ laen_class_locale; int /*<<< orphan*/ laen_seq_num; TYPE_8__* p; TYPE_6__ lioc_frame; TYPE_3__* lioc_sgl; } ; struct mfi_command {int cm_flags; int cm_len; TYPE_9__* cm_frame; struct mfi_linux_ioc_packet* cm_sense; int /*<<< orphan*/ cm_sense_busaddr; struct mfi_linux_ioc_packet* cm_data; union mfi_sgl* cm_sg; int /*<<< orphan*/ cm_total_frame_size; } ; struct mfi_aen {int lioc_sge_count; size_t lioc_sgl_off; int lioc_sense_len; size_t lioc_sense_off; int /*<<< orphan*/ laen_class_locale; int /*<<< orphan*/ laen_seq_num; TYPE_8__* p; TYPE_6__ lioc_frame; TYPE_3__* lioc_sgl; } ; struct cdev {struct mfi_softc* si_drv1; } ; typedef int /*<<< orphan*/ l_ioc ; typedef int /*<<< orphan*/ l_aen ; typedef int /*<<< orphan*/ * caddr_t ; struct TYPE_16__ {int flags; int data_len; struct mfi_linux_ioc_packet cmd_status; int /*<<< orphan*/ cmd; void* context; int /*<<< orphan*/ pad0; int /*<<< orphan*/ scsi_status; } ; struct TYPE_11__ {void* sense_addr_hi; void* sense_addr_lo; } ; struct TYPE_10__ {int /*<<< orphan*/ opcode; } ; struct TYPE_18__ {TYPE_7__ header; TYPE_2__ pass; TYPE_1__ dcmd; int /*<<< orphan*/ * bytes; } ; struct TYPE_17__ {int p_pid; } ; struct TYPE_12__ {int iov_len; int /*<<< orphan*/ iov_base; } ; /* Variables and functions */ int EBUSY ; int EINVAL ; int ENOENT ; int MAX_LINUX_IOCTL_SGE ; int MFI_CMD_DATAIN ; int MFI_CMD_DATAOUT ; int /*<<< orphan*/ MFI_CMD_DCMD ; int /*<<< orphan*/ MFI_CMD_PD_SCSI_IO ; int MFI_DCMD_FRAME_SIZE ; int MFI_FRAME_DATAIN ; int MFI_FRAME_DATAOUT ; #define MFI_LINUX_CMD_2 129 #define MFI_LINUX_SET_AEN_2 128 int /*<<< orphan*/ M_MFIBUF ; int M_WAITOK ; int M_ZERO ; int /*<<< orphan*/ * PTRIN (int /*<<< orphan*/ ) ; int /*<<< orphan*/ TAILQ_INSERT_TAIL (int /*<<< orphan*/ *,struct mfi_linux_ioc_packet*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ TAILQ_REMOVE (int /*<<< orphan*/ *,struct mfi_linux_ioc_packet*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ aen_link ; int /*<<< orphan*/ bcopy (int /*<<< orphan*/ *,TYPE_9__*,int) ; int copyin (int /*<<< orphan*/ *,struct mfi_linux_ioc_packet*,int) ; int copyout (struct mfi_linux_ioc_packet*,int /*<<< orphan*/ *,int) ; TYPE_8__* curproc ; int /*<<< orphan*/ device_printf (int /*<<< orphan*/ ,char*,...) ; int /*<<< orphan*/ free (struct mfi_linux_ioc_packet*,int /*<<< orphan*/ ) ; struct mfi_linux_ioc_packet* malloc (int,int /*<<< orphan*/ ,int) ; int mfi_aen_register (struct mfi_softc*,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ mfi_check_command_post (struct mfi_softc*,struct mfi_command*) ; int mfi_check_command_pre (struct mfi_softc*,struct mfi_command*) ; int mfi_config_lock (struct mfi_softc*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ mfi_config_unlock (struct mfi_softc*,int) ; struct mfi_command* mfi_dequeue_free (struct mfi_softc*) ; int /*<<< orphan*/ mfi_release_command (struct mfi_command*) ; int mfi_wait_command (struct mfi_softc*,struct mfi_command*) ; int /*<<< orphan*/ mtx_lock (int /*<<< orphan*/ *) ; int /*<<< orphan*/ mtx_unlock (int /*<<< orphan*/ *) ; int /*<<< orphan*/ printf (char*,int) ; __attribute__((used)) static int mfi_linux_ioctl_int(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thread *td) { struct mfi_softc *sc; struct mfi_linux_ioc_packet l_ioc; struct mfi_linux_ioc_aen l_aen; struct mfi_command *cm = NULL; struct mfi_aen *mfi_aen_entry; union mfi_sense_ptr sense_ptr; uint32_t context = 0; uint8_t *data = NULL, *temp; int i; int error, locked; sc = dev->si_drv1; error = 0; switch (cmd) { case MFI_LINUX_CMD_2: /* Firmware Linux ioctl shim */ error = copyin(arg, &l_ioc, sizeof(l_ioc)); if (error != 0) return (error); if (l_ioc.lioc_sge_count > MAX_LINUX_IOCTL_SGE) { return (EINVAL); } mtx_lock(&sc->mfi_io_lock); if ((cm = mfi_dequeue_free(sc)) == NULL) { mtx_unlock(&sc->mfi_io_lock); return (EBUSY); } mtx_unlock(&sc->mfi_io_lock); locked = 0; /* * save off original context since copying from user * will clobber some data */ context = cm->cm_frame->header.context; bcopy(l_ioc.lioc_frame.raw, cm->cm_frame, 2 * MFI_DCMD_FRAME_SIZE); /* this isn't quite right */ cm->cm_total_frame_size = (sizeof(union mfi_sgl) * l_ioc.lioc_sge_count) + l_ioc.lioc_sgl_off; cm->cm_frame->header.scsi_status = 0; cm->cm_frame->header.pad0 = 0; if (l_ioc.lioc_sge_count) cm->cm_sg = (union mfi_sgl *)&cm->cm_frame->bytes[l_ioc.lioc_sgl_off]; cm->cm_flags = 0; if (cm->cm_frame->header.flags & MFI_FRAME_DATAIN) cm->cm_flags |= MFI_CMD_DATAIN; if (cm->cm_frame->header.flags & MFI_FRAME_DATAOUT) cm->cm_flags |= MFI_CMD_DATAOUT; cm->cm_len = cm->cm_frame->header.data_len; if (cm->cm_len && (cm->cm_flags & (MFI_CMD_DATAIN | MFI_CMD_DATAOUT))) { cm->cm_data = data = malloc(cm->cm_len, M_MFIBUF, M_WAITOK | M_ZERO); } else { cm->cm_data = 0; } /* restore header context */ cm->cm_frame->header.context = context; temp = data; if (cm->cm_flags & MFI_CMD_DATAOUT) { for (i = 0; i < l_ioc.lioc_sge_count; i++) { error = copyin(PTRIN(l_ioc.lioc_sgl[i].iov_base), temp, l_ioc.lioc_sgl[i].iov_len); if (error != 0) { device_printf(sc->mfi_dev, "Copy in failed\n"); goto out; } temp = &temp[l_ioc.lioc_sgl[i].iov_len]; } } if (cm->cm_frame->header.cmd == MFI_CMD_DCMD) locked = mfi_config_lock(sc, cm->cm_frame->dcmd.opcode); if (cm->cm_frame->header.cmd == MFI_CMD_PD_SCSI_IO) { cm->cm_frame->pass.sense_addr_lo = (uint32_t)cm->cm_sense_busaddr; cm->cm_frame->pass.sense_addr_hi = (uint32_t)((uint64_t)cm->cm_sense_busaddr >> 32); } mtx_lock(&sc->mfi_io_lock); error = mfi_check_command_pre(sc, cm); if (error) { mtx_unlock(&sc->mfi_io_lock); goto out; } if ((error = mfi_wait_command(sc, cm)) != 0) { device_printf(sc->mfi_dev, "Controller polled failed\n"); mtx_unlock(&sc->mfi_io_lock); goto out; } mfi_check_command_post(sc, cm); mtx_unlock(&sc->mfi_io_lock); temp = data; if (cm->cm_flags & MFI_CMD_DATAIN) { for (i = 0; i < l_ioc.lioc_sge_count; i++) { error = copyout(temp, PTRIN(l_ioc.lioc_sgl[i].iov_base), l_ioc.lioc_sgl[i].iov_len); if (error != 0) { device_printf(sc->mfi_dev, "Copy out failed\n"); goto out; } temp = &temp[l_ioc.lioc_sgl[i].iov_len]; } } if (l_ioc.lioc_sense_len) { /* get user-space sense ptr then copy out sense */ bcopy(&((struct mfi_linux_ioc_packet*)arg) ->lioc_frame.raw[l_ioc.lioc_sense_off], &sense_ptr.sense_ptr_data[0], sizeof(sense_ptr.sense_ptr_data)); #ifdef __amd64__ /* * only 32bit Linux support so zero out any * address over 32bit */ sense_ptr.addr.high = 0; #endif error = copyout(cm->cm_sense, sense_ptr.user_space, l_ioc.lioc_sense_len); if (error != 0) { device_printf(sc->mfi_dev, "Copy out failed\n"); goto out; } } error = copyout(&cm->cm_frame->header.cmd_status, &((struct mfi_linux_ioc_packet*)arg) ->lioc_frame.hdr.cmd_status, 1); if (error != 0) { device_printf(sc->mfi_dev, "Copy out failed\n"); goto out; } out: mfi_config_unlock(sc, locked); if (data) free(data, M_MFIBUF); if (cm) { mtx_lock(&sc->mfi_io_lock); mfi_release_command(cm); mtx_unlock(&sc->mfi_io_lock); } return (error); case MFI_LINUX_SET_AEN_2: /* AEN Linux ioctl shim */ error = copyin(arg, &l_aen, sizeof(l_aen)); if (error != 0) return (error); printf("AEN IMPLEMENTED for pid %d\n", curproc->p_pid); mfi_aen_entry = malloc(sizeof(struct mfi_aen), M_MFIBUF, M_WAITOK); mtx_lock(&sc->mfi_io_lock); if (mfi_aen_entry != NULL) { mfi_aen_entry->p = curproc; TAILQ_INSERT_TAIL(&sc->mfi_aen_pids, mfi_aen_entry, aen_link); } error = mfi_aen_register(sc, l_aen.laen_seq_num, l_aen.laen_class_locale); if (error != 0) { TAILQ_REMOVE(&sc->mfi_aen_pids, mfi_aen_entry, aen_link); free(mfi_aen_entry, M_MFIBUF); } mtx_unlock(&sc->mfi_io_lock); return (error); default: device_printf(sc->mfi_dev, "IOCTL 0x%lx not handled\n", cmd); error = ENOENT; break; } return (error); }
the_stack_data/99781.c
#include <stdio.h> #include <string.h> #define MAXPOLE 100000 #define BUF_SIZE 1000 //program, ktory vypise informacie o crambine do subora typedef struct { //definice struktury residui int prvy_atom; int posledny_atom; int cisloresidua; char menoresidua[4]; } RESIDUE; RESIDUE resid[MAXPOLE]; int pocet_resid = 0; typedef struct { // definicia struktury char nazovzaznamu[7]; int cisloatomu; char menoatomu[5]; char alt_loc; char chain_id; // identifikator proteinoveho retazca 21 char i_code; // kod indikujuci vlozenie residua 26 double hodnota; double tepelny_faktor; char menoresidua[4]; int cisloresidua; double x, y, z; // suradnice char symbolprvku[3]; char formal_naboj[3]; } ATOM; ATOM atoms[MAXPOLE]; //pole struktur int pocet_atomov = 0; //pocet riadkov suboru int center(); int residue() { //vypise informacie o residuach int n = 0; for (n = 0; n < pocet_atomov; n++) { if (n == 0) { // som na prvom riadku resid[pocet_resid].cisloresidua = atoms[n].cisloresidua; strcpy(resid[pocet_resid].menoresidua, atoms[n].menoresidua); resid[pocet_resid].prvy_atom = n; } else if (resid[pocet_resid].cisloresidua != atoms[n].cisloresidua) { resid[pocet_resid].posledny_atom = n - 1; //index posledniho atomu pocet_resid++; resid[pocet_resid].cisloresidua = atoms[n].cisloresidua; strcpy(resid[pocet_resid].menoresidua, atoms[n].menoresidua); resid[pocet_resid].prvy_atom = n; } else { resid[pocet_resid].posledny_atom = n; //index posledniho atomu } } center(); } int center() { int i = 0; int j = 0; double stred_x = 0; double stred_y = 0; double stred_z = 0; double sucet_x = 0; double sucet_y = 0; double sucet_z = 0; int pocet = 0; char bezvodik[] = "H"; for (i = 0; i < pocet_resid; i++) { // inicializujem sucet_x = 0; sucet_y = 0; sucet_z = 0; stred_x = 0; stred_y = 0; stred_z = 0; pocet = 0; for (j = resid[i].prvy_atom; j <= resid[i].posledny_atom; j++) { if (strstr(atoms[j].symbolprvku, bezvodik) == NULL) // tato funkce vyhledava retezec v jinem retezci { sucet_x += atoms[j].x; sucet_y += atoms[j].y; sucet_z += atoms[j].z; pocet++; } } stred_x = sucet_x / pocet; stred_y = sucet_y / pocet; stred_z = sucet_z / pocet; printf("Residium: % 4d %-3.3s, center: %.2f %.2f %.2f\n", resid[i].cisloresidua, resid[i].menoresidua, stred_x, stred_y, stred_z); } } int nacitanie(char subor_nacitania[]) { // otvorenie vstupneho suboru char buf[BUF_SIZE] = ""; char s[30] = ""; FILE *f = NULL; f = fopen(subor_nacitania, "r"); // nacitanie suboru if (f == NULL) { // kontrola suboru printf("Neda sa otvorit subor!\n"); return 1; } while (feof(f) == 0) { if (pocet_atomov >= MAXPOLE) { //kontrola velikosti pole printf("Male pole!\n"); break; } memset(buf, '\0', BUF_SIZE); // zapise n(BUF_SIZE) znakov c(\0) na miesto urcene ukazovatelom s(buf) if (fgets(buf, BUF_SIZE, f) == NULL) // nacita 1 riadok zo suboru f do retazca buf dokial nenarazí na znak koiec riadku/suboru break; if (strncmp(buf, "ATOM", 4) == 0 || strncmp(buf, "HETATM", 6) == 0) { strncpy(atoms[pocet_atomov].nazovzaznamu, buf, 6); //nacitanie mena zaznamu, skopiruje dany pocet znakov atoms[pocet_atomov].nazovzaznamu[6] = '\0'; // na koniec musime zapisat nulu strncpy(s, buf + 6, 5); // nacitanie cisla atomu s[5] = '\0'; sscanf(s, "%d", &atoms[pocet_atomov].cisloatomu); strncpy(atoms[pocet_atomov].menoatomu, buf + 12, 4); // nacitanie mena atomu skopiruje 4 znaky od pozicie 12 atoms[pocet_atomov].menoatomu[4] = '\0'; atoms[pocet_atomov].alt_loc = buf[16]; //nacitanie alternativnej pozicii strncpy(atoms[pocet_atomov].menoresidua, buf + 17, 3); //nacitanie mena residua atoms[pocet_atomov].menoresidua[3] = '\0'; atoms[pocet_atomov].chain_id = buf[21]; // nacitanie identifikatoru proteinu strncpy(s, buf + 22, 4); // nacitanie cisla residua s[4] = '\0'; sscanf(s, "%d", &atoms[pocet_atomov].cisloresidua); atoms[pocet_atomov].i_code = buf[26]; // nacitanie kodu indikujucu vlozenie residua strncpy(s, buf + 30, 8); //nacitanie souradnice x s[8] = '\0'; sscanf(s, "%lf", &atoms[pocet_atomov].x); strncpy(s, buf + 38, 8); //nacitanie souradnice y s[8] = '\0'; sscanf(s, "%lf", &atoms[pocet_atomov].y); strncpy(s, buf + 46, 8); //nacitanie souradnice z s[8] = '\0'; sscanf(s, "%lf", &atoms[pocet_atomov].z); strncpy(s, buf + 54, 6); //nacitanie hodnoty s[6] = '\0'; sscanf(s, "%lf", &atoms[pocet_atomov].hodnota); strncpy(s, buf + 60, 6); //nacitanie teplotneho faktoru s[6] = '\0'; sscanf(s, "%lf", &atoms[pocet_atomov].tepelny_faktor); strncpy(atoms[pocet_atomov].symbolprvku, buf + 76, 2); //nacitanie symbolu prvku atoms[pocet_atomov].symbolprvku[2] = '\0'; strncpy(atoms[pocet_atomov].formal_naboj, buf + 78, 2); //nacitanie formalneho naboja atoms[pocet_atomov].formal_naboj[2] = '\0'; pocet_atomov++; } } fclose(f); return 0; } int zapis(char subor_zapisu[]) { // otvorenie vystupneho suboru a zapis hodnot do suboru FILE *fout = NULL; int i = 0; fout = fopen(subor_zapisu, "w"); // otvori subor pre zapis hodnot if (fout == NULL) { // kontrola printf("Neda sa otvorit subor!\n"); return 1; } for (i = 0; i < pocet_atomov; i++) { fprintf(fout, "%-6.6s %5d %-4.4s %3s %4d %8.3f %8.3f %8.3f %2.2s\n", atoms[i].nazovzaznamu, atoms[i].cisloatomu, atoms[i].menoatomu, atoms[i].menoresidua, atoms[i].cisloresidua, atoms[i].x, atoms[i].y, atoms[i].z, atoms[i].symbolprvku); } fclose(fout); return 0; } int main(int argc, char *argv[]) { //ziska nazvy suboru ako parametre z prikazoveho radku char subor_nacitania[MAXPOLE] = ""; char subor_zapisu[MAXPOLE] = ""; if (argc > 1) { nacitanie(argv[1]); zapis(argv[2]); } else { //spyta sa na nazvy suborou, ked nebudu zadane ako parametre printf("Zadajte nazov suboru pre nacitanie: \n"); scanf("%s", subor_nacitania); nacitanie(subor_nacitania); printf("Zadajte nazov suboru pre zapis: \n"); scanf("%s", subor_zapisu); zapis(subor_zapisu); } residue(); return 0; }
the_stack_data/62638172.c
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> int numb = 0; typedef struct node{ char username[10]; struct sockaddr_storage sockaddr; struct node * next; }chatList; chatList *head = NULL; chatList *current = NULL; void push(char * username, struct sockaddr_storage json) //Add item to the linked list { chatList *link = malloc(sizeof(chatList)); strcpy(link->username,username); link->sockaddr = json; //point it to old first node link->next = head; //point first to new first node head = link; } void printList() { // print items from the linked list chatList *amp = head; printf("\nUpdated List: [ "); //start from the beginning while(amp != NULL) { printf("(%s,) ",amp->username); amp = amp->next; } printf(" ]"); } chatList* delete(char * a) //delete a username form the linked list { chatList* now = head; chatList* previous = NULL; chatList* temp = malloc(sizeof(chatList)); if(head == NULL) { return NULL; } while(strcmp(now->username,a) != 0) {// Compares the list if(now->next == NULL) { return NULL; } else { previous = now; now = now->next; } }if(now == head) { head = head->next; } else { previous->next = now->next; } return now; } int checkName(char * a) { chatList *ptr = head; chatList *temp = malloc(sizeof(chatList)); //start from the beginning while(ptr != NULL) { if(strcmp(ptr->username,a) == 0) { return 1; } ptr = ptr->next; } return 0; } int main() { struct PDU { char type; char sname[10]; char data[100]; } rpdu, tpdu; int udpSocket, nBytes; char buffer[100]; char buf[100]; struct sockaddr_in serverAddr, clientAddr; struct sockaddr_storage serverStorage; socklen_t addr_size, client_addr_size; int i; /*Create UDP socket*/ udpSocket = socket(PF_INET, SOCK_DGRAM, 0); /*Configure settings in address struct*/ serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(7891); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero); /*Bind socket with address struct*/ bind(udpSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)); /*Initialize size variable to be used later on*/ addr_size = sizeof clientAddr; while(1) { /* Try to receive any incoming UDP datagram. Address and port of requesting client will be stored on serverStorage variable */ if((nBytes = recvfrom(udpSocket,(char *)&rpdu,120,0,(struct sockaddr *)&serverStorage, &addr_size)) == -1) { printf("error recieving"); // exit(1); } char a = rpdu.type; char *name = rpdu.sname; switch(a){ case 'L': // Sending a List to the client printf("Sending List:"); chatList *al = head; while(al != NULL) { printf("Got message from %s", rpdu.sname); tpdu.type = 'L'; //Broadcast strcpy(tpdu.sname,rpdu.sname); //username strcat(tpdu.data,al->username); al = al->next; } sendto(udpSocket,(char *)&tpdu,120,0,(struct sockaddr *)&serverStorage,addr_size); printf("Sent List to %s", rpdu.sname); printf("List requested"); break; case 'M': //Recieved Message printf("Messaging:"); chatList *ptr = head; while(ptr != NULL) { printf("Got message from %s", rpdu.sname); tpdu.type = 'B'; //Broadcast strcpy(tpdu.sname,rpdu.sname); //username strcpy(tpdu.data,rpdu.data); sendto(udpSocket,(char *)&tpdu,120,0,(struct sockaddr *)&ptr->sockaddr,addr_size); ptr = ptr->next; } printf("Sent Message to %s", rpdu.sname); break; case 'U': printf("Sending Unicast:");//Sending the Unicast chatList *ball = head; while(ball != NULL) { int a = strcmp(ball->username,name); if(a == 10) { tpdu.type = 'U'; //Broadcast strcpy(tpdu.sname,rpdu.sname); //username strcpy(tpdu.data,rpdu.data); sendto(udpSocket,(char *)&tpdu,120,0,(struct sockaddr *)&ball->sockaddr,addr_size); } ball = ball->next; } break; case 'R'://Recieved request to be registered printf("Received registration request from: %s\n",rpdu.sname); if((checkName(rpdu.sname)) == 1) { printf("Checking if %s already exists",rpdu.sname); strcpy(tpdu.sname,rpdu.sname); //username tpdu.type = 'E'; //error strcpy(tpdu.data,"Unable to register"); //Unable to register sendto(udpSocket,(char *)&tpdu,120,0,(struct sockaddr *)&serverStorage,addr_size); } else {//Trying to register printf("Trying to register %s",rpdu.sname); push(rpdu.sname,serverStorage); // add the username and the ipaddress to the linkedlist strcpy(tpdu.sname,rpdu.sname); //username tpdu.type = 'A'; //error strcpy(tpdu.data,"Registered"); //Unable to register sendto(udpSocket,(char *)&tpdu,120,0,(struct sockaddr *)&serverStorage,addr_size); //sending a broadcast message to everyone chatList *sam = head; while(sam != NULL) { printf("Got message from %s", rpdu.sname); tpdu.type = 'B'; //Broadcast strcpy(tpdu.sname,rpdu.sname); //username strcpy(tpdu.data,rpdu.data); sendto(udpSocket,(char *)&tpdu,120,0,(struct sockaddr *)&sam->sockaddr,addr_size); sam = sam->next; } } break; case 'Q':// Request to quit the chat delete(name); printList(); chatList *any = head; while(any != NULL) { printf("Got message from %s", rpdu.sname); tpdu.type = 'B'; //Broadcast strcpy(tpdu.sname,rpdu.sname); //username strcpy(tpdu.data,strcat(rpdu.sname," has left chat")); sendto(udpSocket,(char *)&tpdu,120,0,(struct sockaddr *)&any->sockaddr,addr_size); any = any->next; } printf("Removed"); break; default: printf("polling inside switch"); //Still polling the switch } printf("\n polling out side of switch \n"); } return 0; }
the_stack_data/211079619.c
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char* mk_read_file(const char* path, size_t* file_size) { FILE* file = fopen(path, "r"); if (!file) return NULL; int rc = fseek(file, 0, SEEK_END); if (rc == -1) { fclose(file); return NULL; } size_t size = ftell(file); rc = fseek(file, 0, SEEK_SET); if (rc == -1) { fclose(file); return NULL; } char* buf = malloc(size); if (!buf) { fclose(file); return NULL; } size_t nread = fread(buf, 1, size, file); fclose(file); if (nread != size) { free(buf); return NULL; } *file_size = size; return buf; } int mk_write_file(const char* path, const char* output, size_t output_size) { FILE* file = fopen(path, "wx"); if (!file) return 0; size_t nwritten = fwrite(output, 1, output_size, file); fclose(file); return (nwritten == output_size) ? 1 : 0; }
the_stack_data/154828213.c
/* * Copyright (c) 1989, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#) Copyright (c) 1989, 1993, 1994 The Regents of the University of California. All rights reserved. * @(#)chmod.c 8.8 (Berkeley) 4/1/94 * $FreeBSD: src/bin/chmod/chmod.c,v 1.16.2.6 2002/10/18 01:36:38 trhodes Exp $ * $DragonFly: src/bin/chmod/chmod.c,v 1.9 2008/09/02 22:13:11 swildner Exp $ */ #include <sys/types.h> #include <sys/stat.h> #include <err.h> #include <errno.h> #include <fts.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static void usage (void); int main(int argc, char **argv) { FTS *ftsp; FTSENT *p; mode_t newmode; void *set; int Hflag, Lflag, Rflag, ch, fflag; int fts_options, hflag, rval, vflag; char *mode; int (*change_mode) (const char *, mode_t); Hflag = Lflag = Rflag = fflag = hflag = vflag = 0; while ((ch = getopt(argc, argv, "HLPRXfghorstuvwx")) != -1) switch (ch) { case 'H': Hflag = 1; Lflag = 0; break; case 'L': Lflag = 1; Hflag = 0; break; case 'P': Hflag = Lflag = 0; break; case 'R': Rflag = 1; break; case 'f': fflag = 1; break; case 'h': /* * In System V (and probably POSIX.2) the -h option * causes chmod to change the mode of the symbolic * link. 4.4BSD's symbolic links didn't have modes, * so it was an undocumented noop. In FreeBSD 3.0, * lchmod(2) is introduced and this option does real * work. */ hflag = 1; break; /* * XXX * "-[rwx]" are valid mode commands. If they are the entire * argument, getopt has moved past them, so decrement optind. * Regardless, we're done argument processing. */ case 'g': case 'o': case 'r': case 's': case 't': case 'u': case 'w': case 'X': case 'x': if (argv[optind - 1][0] == '-' && argv[optind - 1][1] == ch && argv[optind - 1][2] == '\0') --optind; goto done; case 'v': vflag = 1; break; default: usage(); } done: argv += optind; argc -= optind; if (argc < 2) usage(); fts_options = FTS_PHYSICAL; if (Rflag) { if (hflag) errx(1, "the -R and -h options may not be specified together."); if (Hflag) fts_options |= FTS_COMFOLLOW; if (Lflag) { fts_options &= ~FTS_PHYSICAL; fts_options |= FTS_LOGICAL; } } if (hflag) change_mode = lchmod; else change_mode = chmod; mode = *argv; errno = 0; if ((set = setmode(mode)) == NULL) { if (!errno) errx(1, "invalid file mode: %s", mode); else /* malloc for setmode() failed */ err(1, "setmode failed"); } if ((ftsp = fts_open(++argv, fts_options, 0)) == NULL) err(1, NULL); for (rval = 0; (p = fts_read(ftsp)) != NULL;) { switch (p->fts_info) { case FTS_D: /* Change it at FTS_DP. */ if (!Rflag) fts_set(ftsp, p, FTS_SKIP); continue; case FTS_DNR: /* Warn, chmod, continue. */ warnx("%s: %s", p->fts_path, strerror(p->fts_errno)); rval = 1; break; case FTS_ERR: /* Warn, continue. */ case FTS_NS: warnx("%s: %s", p->fts_path, strerror(p->fts_errno)); rval = 1; continue; case FTS_SL: /* Ignore. */ case FTS_SLNONE: /* * The only symlinks that end up here are ones that * don't point to anything and ones that we found * doing a physical walk. */ if (!hflag) continue; /* else */ /* FALLTHROUGH */ default: break; } newmode = getmode(set, p->fts_statp->st_mode); if ((newmode & ALLPERMS) == (p->fts_statp->st_mode & ALLPERMS)) continue; if ((*change_mode)(p->fts_accpath, newmode) && !fflag) { warn("%s", p->fts_path); rval = 1; } else { if (vflag) printf("%s\n", p->fts_accpath); } } if (errno) err(1, "fts_read"); free(set); exit(rval); } static void usage(void) { fprintf(stderr, "usage: chmod [-fhv] [-R [-H | -L | -P]] mode file ...\n"); exit(1); }
the_stack_data/3262196.c
/******************************************************************************/ /* */ /* Copyright (c) 1990-2016, KAIST */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* */ /* 3. Neither the name of the copyright holder nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ /* */ /******************************************************************************/ /******************************************************************************/ /* */ /* ODYSSEUS/OOSQL DB-IR-Spatial Tightly-Integrated DBMS */ /* Version 5.0 */ /* */ /* Developed by Professor Kyu-Young Whang et al. */ /* */ /* Advanced Information Technology Research Center (AITrc) */ /* Korea Advanced Institute of Science and Technology (KAIST) */ /* */ /* e-mail: [email protected] */ /* */ /* Bibliography: */ /* [1] Whang, K., Lee, J., Lee, M., Han, W., Kim, M., and Kim, J., "DB-IR */ /* Integration Using Tight-Coupling in the Odysseus DBMS," World Wide */ /* Web, Vol. 18, No. 3, pp. 491-520, May 2015. */ /* [2] Whang, K., Lee, M., Lee, J., Kim, M., and Han, W., "Odysseus: a */ /* High-Performance ORDBMS Tightly-Coupled with IR Features," In Proc. */ /* IEEE 21st Int'l Conf. on Data Engineering (ICDE), pp. 1104-1105 */ /* (demo), Tokyo, Japan, April 5-8, 2005. This paper received the Best */ /* Demonstration Award. */ /* [3] Whang, K., Park, B., Han, W., and Lee, Y., "An Inverted Index */ /* Storage Structure Using Subindexes and Large Objects for Tight */ /* Coupling of Information Retrieval with Database Management */ /* Systems," U.S. Patent No.6,349,308 (2002) (Appl. No. 09/250,487 */ /* (1999)). */ /* [4] Whang, K., Lee, J., Kim, M., Lee, M., Lee, K., Han, W., and Kim, */ /* J., "Tightly-Coupled Spatial Database Features in the */ /* Odysseus/OpenGIS DBMS for High-Performance," GeoInformatica, */ /* Vol. 14, No. 4, pp. 425-446, Oct. 2010. */ /* [5] Whang, K., Lee, J., Kim, M., Lee, M., and Lee, K., "Odysseus: a */ /* High-Performance ORDBMS Tightly-Coupled with Spatial Database */ /* Features," In Proc. 23rd IEEE Int'l Conf. on Data Engineering */ /* (ICDE), pp. 1493-1494 (demo), Istanbul, Turkey, Apr. 16-20, 2007. */ /* */ /******************************************************************************/ #ifndef SLIMDOWN_TEXTIR #include <stdio.h> #include <string.h> #include <ctype.h> static int WordSize(); static int ContainsVowel(); static int AddAnE(); static int RemoveAnE(); static int ReplaceEnd(); #define FALSE 0 #define TRUE 1 #define EOS '\0' #define IsVowel(c) ('a'==(c) || 'e'==(c) || 'i'==(c) || 'o'==(c) || 'u'==(c)) typedef struct { int id; char *old_end; char *new_end; int old_offset; int new_offset; int min_root_size; int (*condition)(); } RuleList; static char LAMBDA[1] = ""; static char *end; static RuleList step1a_rules[] = { 101, "sses", "ss", 3, 1, -1, NULL, 102, "ies", "i", 2, 0, -1, NULL, 103, "ss", "ss", 1, 1, -1, NULL, 104, "s", LAMBDA, 0, -1, -1, NULL, 000, NULL, NULL, 0, 0, 0, NULL }; static RuleList step1b_rules[] = { 105, "eed", "ee", 2, 1, 0, NULL, 106, "ed", LAMBDA, 1, -1, -1, ContainsVowel, 107, "ing", LAMBDA, 2, -1, -1, ContainsVowel, 000, NULL, NULL, 0, 0, 0, NULL }; static RuleList step1b1_rules[] = { 108, "at", "ate", 1, 2, -1, NULL, 109, "bl", "ble", 1, 2, -1, NULL, 110, "iz", "ize", 1, 2, -1, NULL, 111, "bb", "b", 1, 0, -1, NULL, 112, "dd", "d", 1, 0, -1, NULL, 113, "ff", "f", 1, 0, -1, NULL, 114, "gg", "g", 1, 0, -1, NULL, 115, "mm", "m", 1, 0, -1, NULL, 116, "nn", "n", 1, 0, -1, NULL, 117, "pp", "p", 1, 0, -1, NULL, 118, "rr", "r", 1, 0, -1, NULL, 119, "tt", "t", 1, 0, -1, NULL, 120, "ww", "w", 1, 0, -1, NULL, 121, "xx", "x", 1, 0, -1, NULL, 122, LAMBDA, "e", -1, 0, -1, AddAnE, 000, NULL, NULL, 0, 0, 0, NULL, }; static RuleList step1c_rules[] = { 123, "y", "i", 0, 0, -1, ContainsVowel, 000, NULL, NULL, 0, 0, 0, NULL, }; static RuleList step2_rules[] = { 203, "ational", "ate", 6, 2, 0, NULL, 204, "tional", "tion", 5, 3, 0, NULL, 205, "enci", "ence", 3, 3, 0, NULL, 206, "anci", "ance", 3, 3, 0, NULL, 207, "izer", "ize", 3, 2, 0, NULL, 208, "abli", "able", 3, 3, 0, NULL, 209, "alli", "al", 3, 1, 0, NULL, 210, "entli", "ent", 4, 2, 0, NULL, 211, "eli", "e", 2, 0, 0, NULL, 213, "ousli", "ous", 4, 2, 0, NULL, 214, "ization", "ize", 6, 2, 0, NULL, 215, "ation", "ate", 4, 2, 0, NULL, 216, "ator", "ate", 3, 2, 0, NULL, 217, "alism", "al", 4, 1, 0, NULL, 218, "iveness", "ive", 6, 2, 0, NULL, 219, "fulnes", "ful", 5, 2, 0, NULL, 220, "ousness", "ous", 6, 2, 0, NULL, 221, "aliti", "al", 4, 1, 0, NULL, 222, "iviti", "ive", 4, 2, 0, NULL, 223, "biliti", "ble", 5, 2, 0, NULL, 000, NULL, NULL, 0, 0, 0, NULL, }; static RuleList step3_rules[] = { 301, "icate", "ic", 4, 1, 0, NULL, 302, "ative", LAMBDA, 4, -1, 0, NULL, 303, "alize", "al", 4, 1, 0, NULL, 304, "iciti", "ic", 4, 1, 0, NULL, 305, "ical", "ic", 3, 1, 0, NULL, 308, "ful", LAMBDA, 2, -1, 0, NULL, 309, "ness", LAMBDA, 3, -1, 0, NULL, 000, NULL, NULL, 0, 0, 0, NULL, }; static RuleList step4_rules[] = { 401, "al", LAMBDA, 1, -1, 1, NULL, 402, "ance", LAMBDA, 3, -1, 1, NULL, 403, "ence", LAMBDA, 3, -1, 1, NULL, 405, "er", LAMBDA, 1, -1, 1, NULL, 406, "ic", LAMBDA, 1, -1, 1, NULL, 407, "able", LAMBDA, 3, -1, 1, NULL, 408, "ible", LAMBDA, 3, -1, 1, NULL, 409, "ant", LAMBDA, 2, -1, 1, NULL, 410, "ement", LAMBDA, 4, -1, 1, NULL, 411, "ment", LAMBDA, 3, -1, 1, NULL, 412, "ent", LAMBDA, 2, -1, 1, NULL, 423, "sion", "s", 3, 0, 1, NULL, 424, "tion", "t", 3, 0, 1, NULL, 415, "ou", LAMBDA, 1, -1, 1, NULL, 416, "ism", LAMBDA, 2, -1, 1, NULL, 417, "ate", LAMBDA, 2, -1, 1, NULL, 418, "iti", LAMBDA, 2, -1, 1, NULL, 419, "ous", LAMBDA, 2, -1, 1, NULL, 420, "ive", LAMBDA, 2, -1, 1, NULL, 421, "ize", LAMBDA, 2, -1, 1, NULL, 000, NULL, NULL, 0, 0, 0, NULL, }; static RuleList step5a_rules[] = { 501, "e", LAMBDA, 0, -1, 1, NULL, 502, "e", LAMBDA, 0, -1, -1, RemoveAnE, 000, NULL, NULL, 0, 0, 0, NULL, }; static RuleList step5b_rules[] = { 503, "ll", "l", 1, 0, 1, NULL, 000, NULL, NULL, 0, 0, 0, NULL, }; static int WordSize(word) register char *word; { register int result; register int state; result = 0; state = 0; while (EOS != *word) { switch(state) { case 0: state = (IsVowel(*word)) ? 1 : 2; break; case 1: state = (IsVowel(*word)) ? 1 : 2; if (2 == state) result++; break; case 2: state = (IsVowel(*word) || ('y' == *word)) ? 1 : 2; break; } word++; } return(result); } static int ContainsVowel(word) register char *word; { if (EOS == *word) return(FALSE); else return(IsVowel(*word) || (NULL != strpbrk(word+1, "aeiouy"))); } static int EndsWithCVC(word) register char *word; { int length; if ((length = strlen(word)) < 2) return(FALSE); else { end = word + length - 1; return( (NULL == strchr("aeiouwxy", *end--)) && (NULL != strchr("aeiouy", *end--)) && (NULL == strchr("aeiou", *end))); } } static int AddAnE(word) register char *word; { return((1 == WordSize(word)) && EndsWithCVC(word)); } static int RemoveAnE(word) register char *word; { return((1 == WordSize(word)) && !EndsWithCVC(word)); } static int ReplaceEnd(word, rule) register char *word; RuleList *rule; { register char *ending; char tmp_ch; while (0 != rule->id) { ending = end - rule->old_offset; if (word != ending) if (0 == strcmp(ending, rule->old_end)) { tmp_ch = *ending; *ending = EOS; if (rule->min_root_size < WordSize(word)) if (!rule->condition || (*rule->condition)(word)) { (void)strcat(word, rule->new_end); end = ending + rule->new_offset; break; } *ending = tmp_ch; } rule++; } return(rule->id); } int Stem(word) register char *word; { int rule; for (end = word; *end != EOS; end++) if (!isalpha(*end)) return(FALSE); end--; ReplaceEnd(word, step1a_rules); rule = ReplaceEnd(word, step1b_rules); if ((106 == rule) || (107 == rule)) ReplaceEnd(word, step1b1_rules); ReplaceEnd(word, step1c_rules); ReplaceEnd(word, step2_rules); ReplaceEnd(word, step3_rules); ReplaceEnd(word, step4_rules); ReplaceEnd(word, step5a_rules); ReplaceEnd(word, step5b_rules); return(TRUE); } #else /* SLIMDOWN_TEXTIR */ #include <LOM.h> #include <stdio.h> int Stem(word) register char *word; { return eTEXTIR_NOTENABLED_LOM; } #endif /* SLIMDOWN_TEXTIR */
the_stack_data/6486.c
/* Write a free'd pointer into a pipe and use it to write data on the other end. */ #include <stdlib.h> #include <unistd.h> #include <string.h> void read_ptr_from_fd(int fd) { char *ptr; read(fd, &ptr, sizeof(char*)); strcpy(ptr, "String"); } int main() { char *ptr1; int fd[2]; pipe(fd); ptr1 = malloc(1000); write(fd[1], &ptr1, sizeof(char*)); free(ptr1); read_ptr_from_fd(fd[0]); close(fd[0]); close(fd[1]); return 0; }
the_stack_data/98409.c
#include <stdio.h> char * fgets(s, n, iop) char *s; int n; register FILE *iop; { register int c = EOF; register char *cs; cs = s; while (--n>0 && (c = getc(iop)) != EOF) { *cs++ = c; if (c=='\n') break; } if (c == EOF && cs==s) return(NULL); *cs++ = '\0'; return(s); }
the_stack_data/111076782.c
#define PORT 8080 #include <sys/socket.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <netinet/in.h> #include <string.h> struct sockaddr_in address; void initialize_socket(struct sockaddr_in); void attach_to_port(); typedef struct { int opt; int server_fd; int new_socket; int value_read; char buffer[1024]; char hello[25]; int address_len; } Server; void initialize_socket(struct sockaddr_in addressIn) { Server *server = malloc(sizeof(Server)); server -> opt = 1; if ((server -> server_fd = socket(AF_INET, SOCK_STREAM, 0) == 0)) { perror("Socket failed to initialize"); exit(EXIT_FAILURE); } if (setsockopt(server -> server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &server -> opt, sizeof(server -> opt))) { perror("setsocketopt"); exit(EXIT_FAILURE); } else { addressIn.sin_family = AF_INET; addressIn.sin_addr.s_addr = INADDR_ANY; addressIn.sin_port = htons(PORT); } } void attach_to_port(Server *server) { if (bind(server -> server_fd, (struct sockaddr *) &address, sizeof(address)) < 0) { perror("Unable to connect to port."); exit(EXIT_FAILURE); } if (listen(server -> server_fd, 3) < 0) { perror("Listen"); exit(EXIT_FAILURE); } if ((server -> new_socket = accept(server -> server_fd, (struct sockaddr *) (struct socket_address_in *) &address, (socklen_t*) &server -> address_len)) < 0) { perror("Accept"); exit(EXIT_FAILURE); } server -> value_read = read(server -> new_socket, server -> buffer, 1024); printf("%s\n", server -> buffer); send(server -> new_socket, server -> hello, strlen(server -> hello), 0); printf("Message sent\n"); }
the_stack_data/67003.c
#include <stdio.h> int main() { float num; printf("Informe uma nota entre 0 e 10:\n"); while (scanf("%f", &num) && !(num >= 0 && num <= 10)) { printf("Valor invalido\n"); printf("Informe uma nota entre 0 e 10:\n"); } return(0); }
the_stack_data/40745.c
int main(void) { char hello[6+5*8] = "hello"; char* h = hello; h++; *hello = 'u'; int const bb = 1; int bbb = 2; int const constarr[2] = {1, 2}; // char* = char[] h = "newst"; // char* = char h = 'n'; //error h = 8; // error h = "no error"; return 0; }
the_stack_data/168892103.c
#include <stdio.h> void do_podst_n(unsigned long n, unsigned int podstawa); int main(void) { unsigned long liczba; unsigned int podstawa; printf("Podaj liczbe calkowita i podstawe (q konczy program): \n"); while (scanf("%ld %d", &liczba, &podstawa) == 2) { printf("Odpowiednik dwojkowy: "); do_podst_n(liczba, podstawa); putchar('\n'); printf("Podaj liczbe calkowita i podstawe (q konczy program): \n"); } printf("Gotowe.\n"); return 0; } void do_podst_n(unsigned long n, unsigned int podstawa) { int r; r = n % podstawa; if (n >= podstawa) do_podst_n(n / podstawa, podstawa); if (r == 0) putchar('0'); else printf("%d", r); return; }
the_stack_data/1217940.c
void predic(data,ndata,d,npoles,future,nfut) float data[],d[],future[]; int ndata,npoles,nfut; { int k,j; float sum,discrp,*reg,*vector(); void free_vector(); reg=vector(1,npoles); for (j=1;j<=npoles;j++) reg[j]=data[ndata+1-j]; for (j=1;j<=nfut;j++) { discrp=0.0; sum=discrp; for (k=1;k<=npoles;k++) sum += d[k]*reg[k]; for (k=npoles;k>=2;k--) reg[k]=reg[k-1]; future[j]=reg[1]=sum; } free_vector(reg,1,npoles); }
the_stack_data/126704028.c
#include <stdio.h> int main() { int t, n, m, a[1000000], b[1000000], i, u, s, r, p; int doudou, count; while (scanf("%d", &t) != EOF) { for (i = 1; i <= t; i++) { scanf("%d %d %d", &n, &m, &p); for (u = 0; u < n; u++) scanf("%d", &a[u]); for (u = 0; u < m; u++) scanf("%d", &b[u]); count = 0; for (s = 0; s < (n - (m-1)*p); s++) { doudou = 1; for (r = 0; r < m; r++) { if (b[r] == (a[s + r*p])) continue; else { doudou = 0; break; } } if (doudou == 1) count++; } printf("Case #%d: %d\n", i, count); } } return 0; }
the_stack_data/87545.c
/* The Computer Language Benchmarks Game * http://benchmarksgame.alioth.debian.org/ * * contributed by Christoph Bauer * slightly sped up by Petr Prokhorenkov */ #ifdef STATIC #undef STATIC #define STATIC static #else #define STATIC #endif #ifdef PRINTF #define PRINTF2(a,b) printf(a,b) #else #define PRINTF2(a,b) #endif #ifdef TIMER #define TIMER_START() intrinsic_label(TIMER_START) #define TIMER_STOP() intrinsic_label(TIMER_STOP) #else #define TIMER_START() #define TIMER_STOP() #endif #ifdef __Z88DK #include <intrinsic.h> #ifdef PRINTF // enable printf %f #pragma output CLIB_OPT_PRINTF = 0xffffffff //#pragma output CLIB_OPT_PRINTF = 0x04000000 #endif #endif #include <math.h> #include <stdio.h> #include <stdlib.h> #define pi 3.141592653589793 #define solar_mass (4 * pi * pi) #define days_per_year 365.24 struct planet { double x, y, z; double vx, vy, vz; double mass; }; /* * Here's one weird thing: inlining of this function * decreases performance by 25%. (I.e. do not compile this with -O3) * Advances with dt == 1.0 */ void advance(int nbodies, struct planet * bodies) { STATIC int i, j; STATIC struct planet *b, *b2; STATIC double dx, dy, dz; STATIC double inv_distance, mag; for (i = 0; i < nbodies; i++) { b = &(bodies[i]); for (j = i + 1; j < nbodies; j++) { b2 = &(bodies[j]); dx = b->x - b2->x; dy = b->y - b2->y; dz = b->z - b2->z; inv_distance = 1.0/sqrt(dx * dx + dy * dy + dz * dz); mag = inv_distance * inv_distance * inv_distance; b->vx -= dx * b2->mass * mag; b->vy -= dy * b2->mass * mag; b->vz -= dz * b2->mass * mag; b2->vx += dx * b->mass * mag; b2->vy += dy * b->mass * mag; b2->vz += dz * b->mass * mag; } } for (i = 0; i < nbodies; i++) { b = &(bodies[i]); b->x += b->vx; b->y += b->vy; b->z += b->vz; } } double energy(int nbodies, struct planet * bodies) { STATIC double e; STATIC int i, j; STATIC struct planet *b, *b2; STATIC double dx, dy, dz; STATIC double distance; e = 0.0; for (i = 0; i < nbodies; i++) { b = &(bodies[i]); e += 0.5 * b->mass * (b->vx * b->vx + b->vy * b->vy + b->vz * b->vz); for (j = i + 1; j < nbodies; j++) { b2 = &(bodies[j]); dx = b->x - b2->x; dy = b->y - b2->y; dz = b->z - b2->z; distance = sqrt(dx * dx + dy * dy + dz * dz); e -= (b->mass * b2->mass) / distance; } } return e; } void offset_momentum(int nbodies, struct planet * bodies) { STATIC double px, py, pz; STATIC int i; px = py = pz = 0.0; for (i = 0; i < nbodies; i++) { px += bodies[i].vx * bodies[i].mass; py += bodies[i].vy * bodies[i].mass; pz += bodies[i].vz * bodies[i].mass; } bodies[0].vx = - px / solar_mass; bodies[0].vy = - py / solar_mass; bodies[0].vz = - pz / solar_mass; } #define NBODIES 5 struct planet bodies[NBODIES] = { { /* sun */ 0, 0, 0, 0, 0, 0, solar_mass }, { /* jupiter */ 4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01, 1.66007664274403694e-03 * days_per_year, 7.69901118419740425e-03 * days_per_year, -6.90460016972063023e-05 * days_per_year, 9.54791938424326609e-04 * solar_mass }, { /* saturn */ 8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01, -2.76742510726862411e-03 * days_per_year, 4.99852801234917238e-03 * days_per_year, 2.30417297573763929e-05 * days_per_year, 2.85885980666130812e-04 * solar_mass }, { /* uranus */ 1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01, 2.96460137564761618e-03 * days_per_year, 2.37847173959480950e-03 * days_per_year, -2.96589568540237556e-05 * days_per_year, 4.36624404335156298e-05 * solar_mass }, { /* neptune */ 1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01, 2.68067772490389322e-03 * days_per_year, 1.62824170038242295e-03 * days_per_year, -9.51592254519715870e-05 * days_per_year, 5.15138902046611451e-05 * solar_mass } }; #define DT 1e-2 #define RECIP_DT (1.0/DT) /* * Rescale certain properties of bodies. That allows doing * consequential advance()'s as if dt were equal to 1.0. * * When all advances done, rescale bodies back to obtain correct energy. */ void scale_bodies(int nbodies, struct planet * bodies, double scale) { STATIC int i; for (i = 0; i < nbodies; i++) { bodies[i].mass *= scale*scale; bodies[i].vx *= scale; bodies[i].vy *= scale; bodies[i].vz *= scale; } } int main(int argc, char ** argv) { int i; int n = 1000; #ifdef COMMAND n = atoi(argv[1]); #endif TIMER_START(); offset_momentum(NBODIES, bodies); PRINTF2("%.9f\n", energy(NBODIES, bodies)); scale_bodies(NBODIES, bodies, DT); for (i = 1; i <= n; i++) { advance(NBODIES, bodies); } scale_bodies(NBODIES, bodies, RECIP_DT); PRINTF2("%.9f\n", energy(NBODIES, bodies)); TIMER_STOP(); return 0; }
the_stack_data/9512279.c
/* * Noah Wimmer * Lab sect. A * 9/28 * Lab 5 * */ #include <stdio.h> #include <math.h> double logAny(double x, double b); //Returns the value of log base b of x double logAny(double x, double b) { return(log(x)/log(b)); } int main(void) { //loop through each outer number for(int i = 0; i <= 13; i++) { printf("Number %d:\n", (int) pow(2,i)); // loop through each inner number (2-32) for(int j = 1; j <= 5; j++) { //loops through each outer number and prints their log with the base of each inner number printf("\tlog base %d = %lf\n",(int) pow(2,j), logAny(pow(2,i), pow(2,j))); } } return 0; }
the_stack_data/1199967.c
/* / file : server.c /------------------------------------------ / This is a server socket program that echos recieved messages / from the client.c program. Run the server on one of the ECN / machines and the client on your laptop. */ // For compiling this file: // Linux: gcc server.c -o server // Solaris: gcc server.c -o server -lsocket // OS X: gcc -g -fno-stack-protector -D_FORTIFY_SOURCE=0 -o server server.c // // For running the server program: // // server 9000 <----WRONG! // server 127.0.0.1 // // where 9000 is the port you want your server to monitor. Of course, // this can be any high-numbered that is not currently being used by others. #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> #include <arpa/inet.h> #include <unistd.h> #define MAX_PENDING 10 /* maximun # of pending for connection */ #define MAX_DATA_SIZE 5 int DataPrint(char *recvBuff,char *str, int numBytes); int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); } int PORT = atoi(argv[1]); char *recvBuff; /* recv data buffer */ int numBytes = 0; int senderBuffSize; char str[MAX_DATA_SIZE]; int servSockfd, clntSockfd; struct sockaddr_in sevrAddr; struct sockaddr_in clntAddr; int clntLen; socklen_t optlen = sizeof senderBuffSize; /* make socket */ if ((servSockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("sock failed"); exit(1); } /* set IP address and port */ sevrAddr.sin_family = AF_INET; sevrAddr.sin_port = htons(PORT); sevrAddr.sin_addr.s_addr = INADDR_ANY; bzero(&(sevrAddr.sin_zero), 8); if (bind(servSockfd, (struct sockaddr *)&sevrAddr, sizeof(struct sockaddr)) == -1) { perror("bind failed"); exit(1); } if (listen(servSockfd, MAX_PENDING) == -1) { perror("listen failed"); exit(1); } while(1) { clntLen = sizeof(struct sockaddr_in); if ((clntSockfd = accept(servSockfd, (struct sockaddr *) &clntAddr, &clntLen)) == -1) { perror("accept failed"); exit(1); } printf("Connected from %s\n", inet_ntoa(clntAddr.sin_addr)); if (send(clntSockfd, "Connected!!!\n", strlen("Connected!!!\n"), 0) == -1) { perror("send failed"); close(clntSockfd); exit(1); } /* repeat for one clinet service */ while(1) { /* recv data from the client */ getsockopt(clntSockfd, SOL_SOCKET,SO_SNDBUF, &senderBuffSize, &optlen); /* check sender buffer size */ recvBuff = malloc(senderBuffSize * sizeof (char)); if ((numBytes = recv(clntSockfd, recvBuff, senderBuffSize, 0)) == -1) { perror("recv failed"); exit(1); } recvBuff[numBytes] = '\0'; //MODIFICATION - ADD LINE: char str[strlen(recvBuff + 1)]; strcpy(str, recvBuff); /* send data to the client */ if (send(clntSockfd, str, strlen(str), 0) == -1) { perror("send failed"); close(clntSockfd); exit(1); } if(DataPrint(recvBuff, str, numBytes)){ fprintf(stderr,"ERROR, no way to print out\n"); exit(1); } } close(clntSockfd); exit(1); } } int DataPrint(char *recvBuff,char *str, int numBytes) { printf("RECEIVED: %s", recvBuff); printf("SENT: %s", str); printf("RECEIVED BYTES: %d\n\n", numBytes); return(0); }
the_stack_data/344379.c
#include <stddef.h> #include <stdio.h> #include <time.h> void show_sec(){ time_t timer =time(NULL); struct tm *local = localtime(&timer); printf( "%d\n", local->tm_sec ); } void show_min(){ time_t timer =time(NULL); struct tm *local = localtime(&timer); printf( "%d\n", local->tm_min ); } void show_xxx( size_t offset ){ time_t timer =time(NULL); struct tm *local = localtime(&timer); printf( "%d\n", *(int*)(((char*)local)+offset) ); } void use_show_xxx(void){ show_xxx(offsetof(struct tm, tm_sec)); } int main(int argc, char const * argv[]) { use_show_xxx(); if ( 1<argc && argv[1][0]=='1' ){ show_sec(); show_xxx(offsetof(struct tm, tm_sec)); } else { show_min(); show_xxx(offsetof(struct tm, tm_min)); } return 0; }
the_stack_data/48574070.c
#include <stdio.h> #define CHARS 128 int main() { int character, i, characters[CHARS]; for (i = 0; i < CHARS; ++i) { characters[i] = 0; } printf("Input text below, to count characters:\n"); while((character = getchar()) != EOF) { ++characters[character]; } printf("\nHorizontal Histogram of the input:\n"); for (i = 0; i < CHARS; ++i) { if (!(characters[i] > 0)) { continue; } if (i == '\b') { printf("\\b:\t"); } else if (i == '\n') { printf("\\n:\t"); } else if (i == '\t') { printf("\\t:\t"); } else { printf("%2c:\t", i); } int j; j = 0; while(j < characters[i]) { putchar('#'); ++j; } putchar('\n'); } }
the_stack_data/90764373.c
/* Remark: If you change anything in the configuration of miniz, you MUST also update the header file miniz.h! - JD */ /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <[email protected]>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks [email protected]) which could cause locate files to not find files. This bug would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From [email protected] and [email protected] - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <[email protected]> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED #include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. #define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. #define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. // #define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. // #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. // #define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) #include <time.h> #endif //Hardcoded options for Xtensa - JD #define MINIZ_X86_OR_X64_CPU 0 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 #define MINIZ_HAS_64BIT_REGISTERS 0 #define TINFL_USE_64BIT_BITBUF 0 #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. // (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 512 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 8, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table *m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 1 // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool(*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = (1024), TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 256, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 9, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1, } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 *m_dict; mz_uint16 *m_huff_count[TDEFL_MAX_HUFF_TABLES]; mz_uint16 *m_huff_codes[TDEFL_MAX_HUFF_TABLES]; mz_uint8 *m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES]; mz_uint8 *m_lz_code_buf; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 *m_hash; mz_uint8 *m_output_buf; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; #include <string.h> #include <assert.h> //Disable asserts #define MZ_ASSERT(x) //#define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a,b) (((a)>(b))?(a):(b)) #define MZ_MIN(a,b) (((a)<(b))?(a):(b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) { return MZ_ADLER32_INIT; } while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) { s1 += *ptr++, s2 += s1; } s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) { return MZ_CRC32_INIT; } crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } // static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) { return MZ_STREAM_ERROR; } if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) { return MZ_PARAM_ERROR; } pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) { pStream->zalloc = def_alloc_func; } if (!pStream->zfree) { pStream->zfree = def_free_func; } pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); pComp->m_dict = pStream->zalloc(pStream->opaque, 1, TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1); pComp->m_lz_code_buf = pStream->zalloc(pStream->opaque, 1, TDEFL_LZ_CODE_BUF_SIZE); pComp->m_hash = pStream->zalloc(pStream->opaque, 1, TDEFL_LZ_DICT_SIZE); pComp->m_output_buf = pStream->zalloc(pStream->opaque, 1, TDEFL_OUT_BUF_SIZE); for (int i = 0; i < TDEFL_MAX_HUFF_TABLES; i++) { pComp->m_huff_count[i] = pStream->zalloc(pStream->opaque, 1, TDEFL_MAX_HUFF_SYMBOLS * sizeof(mz_uint16)); pComp->m_huff_codes[i] = pStream->zalloc(pStream->opaque, 1, TDEFL_MAX_HUFF_SYMBOLS * sizeof(mz_uint16)); pComp->m_huff_code_sizes[i] = pStream->zalloc(pStream->opaque, 1, TDEFL_MAX_HUFF_SYMBOLS * sizeof(mz_uint8)); } if (!pComp) { return MZ_MEM_ERROR; } pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) { return MZ_STREAM_ERROR; } pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) { return MZ_STREAM_ERROR; } if (!pStream->avail_out) { return MZ_BUF_ERROR; } if (flush == MZ_PARTIAL_FLUSH) { flush = MZ_SYNC_FLUSH; } if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) { return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; } orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (; ;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) { break; } else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) { break; } return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) { return MZ_STREAM_ERROR; } if (pStream->state) { tdefl_compressor *pComp = (tdefl_compressor *)pStream->state; pStream->zfree(pStream->opaque, pComp->m_dict); pStream->zfree(pStream->opaque, pComp->m_lz_code_buf); pStream->zfree(pStream->opaque, pComp->m_hash); pStream->zfree(pStream->opaque, pComp->m_output_buf); for (int i = 0; i < TDEFL_MAX_HUFF_TABLES; i++) { pStream->zfree(pStream->opaque, pComp->m_huff_count[i]); pStream->zfree(pStream->opaque, pComp->m_huff_codes[i]); pStream->zfree(pStream->opaque, pComp->m_huff_code_sizes[i]); } pStream->zfree(pStream->opaque, pComp); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) { return MZ_PARAM_ERROR; } stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32) * pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) { return status; } status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) { return MZ_STREAM_ERROR; } if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) { return MZ_PARAM_ERROR; } pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) { pStream->zalloc = def_alloc_func; } if (!pStream->zfree) { pStream->zfree = def_free_func; } pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); for (int i = 0; i < TINFL_MAX_HUFF_TABLES; ++i) { pDecomp->m_decomp.m_tables[i] = pStream->zalloc(pStream->opaque, 1, sizeof(tinfl_huff_table)); } if (!pDecomp) { return MZ_MEM_ERROR; } pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) { return MZ_STREAM_ERROR; } if (flush == MZ_PARTIAL_FLUSH) { flush = MZ_SYNC_FLUSH; } if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) { return MZ_STREAM_ERROR; } pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) { decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; } orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) { return MZ_DATA_ERROR; } if (pState->m_has_flushed && (flush != MZ_FINISH)) { return MZ_STREAM_ERROR; } pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) { return MZ_DATA_ERROR; } else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) { decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; } if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (; ;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) { return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). } else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) { return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. } else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) { return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; } // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. else if (!pStream->avail_out) { return MZ_BUF_ERROR; } } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) { break; } } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) { return MZ_STREAM_ERROR; } if (pStream->state) { inflate_state *pDecomp = (inflate_state *)pStream->state; for (int i = 0; i < TINFL_MAX_HUFF_TABLES; ++i) { pStream->zfree(pStream->opaque, pDecomp->m_decomp.m_tables[i]); } pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) { return MZ_PARAM_ERROR; } stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32) * pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) { return status; } status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = { { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } }; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) { return s_error_descs[i].m_pDesc; } return NULL; } #endif //MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN switch(r->m_state) { case 0: #define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for ( ; ; ) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else c = *pIn_buf_cur++; } MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) \ break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ int temp; mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static const int s_min_table_sizes[3] = { 257, 1, 4 }; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t) - 1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); } if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) { TINFL_GET_BITS(6, r->m_raw_header[counter], 8); } else { TINFL_GET_BYTE(7, r->m_raw_header[counter]); } } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0]->m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1]->m_code_size, 5, 32); for (i = 0; i <= 143; ++i) { *p++ = 8; } for (; i <= 255; ++i) { *p++ = 9; } for (; i <= 279; ++i) { *p++ = 7; } for (; i <= 287; ++i) { *p++ = 8; } } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2]->m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2]->m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) { total_syms[pTable->m_code_size[i]]++; } used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) { continue; } cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) { rev_code = (rev_code << 1) | (cur_code & 1); } if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else { tree_cur = pTable->m_tree[-tree_cur - 1]; } } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0]->m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1]->m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (; ;) { mz_uint8 *pSrc; for (; ;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, r->m_tables[0]); if (counter >= 256) { break; } while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0]->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) { code_len = sym2 >> 9; } else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0]->m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) { break; } #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0]->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) { code_len = sym2 >> 9; } else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0]->m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) { break; } num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) { pOut_buf_cur[1] = pSrc[1]; } pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) { pOut_buf_cur[1] = pSrc[1]; } pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) { TINFL_GET_BITS(41, s, 8); } else { TINFL_GET_BYTE(42, s); } r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) { s1 += *ptr++, s2 += s1; } s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) { status = TINFL_STATUS_ADLER32_MISMATCH; } } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (; ;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) { break; } new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) { new_out_buf_capacity = 128; } pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) { return TINFL_STATUS_FAILED; } tinfl_init(&decomp); for (; ;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) { break; } if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 }; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 }; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 }; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 }; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) { total_passes--; } for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) { pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; } { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, [email protected], Jyrki Katajainen, [email protected], November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) { return; } else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else { A[next].m_key = A[leaf++].m_key; } if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else { A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) { A[next].m_key = A[A[next].m_key].m_key + 1; } avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) { return; } for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) { pNum_codes[max_code_size] += pNum_codes[i]; } for (i = max_code_size; i > 0; i--) { total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); } while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) { num_codes[d->m_huff_code_sizes[table_num][i]]++; } } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) { num_codes[pSyms[i].m_key]++; } tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); memset(d->m_huff_codes[table_num], 0, TDEFL_MAX_HUFF_SYMBOLS * sizeof(mz_uint16)); memset(d->m_huff_code_sizes[table_num], 0, TDEFL_MAX_HUFF_SYMBOLS); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) { d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) { next_code[i] = j = ((j + num_codes[i - 1]) << 1); } for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) { continue; } code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) { rev_code = (rev_code << 1) | (code & 1); } d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) do { \ mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ } rle_repeat_count = 0; } } #define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ } rle_z_count = 0; } } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) { break; } for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) { break; } memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) { break; } num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) { TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); } for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) { TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) { *p++ = 8; } for (; i <= 255; ++i) { *p++ = 9; } for (; i <= 279; ++i) { *p++ = 7; } for (; i <= 287; ++i) { *p++ = 8; } memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) { flags = *pLZ_codes++ | 0x100; } if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) { return MZ_FALSE; } *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) { flags = *pLZ_codes++ | 0x100; } if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) { tdefl_start_static_block(d); } else { tdefl_start_dynamic_block(d); } return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) { comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); } // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) { return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) { return; } for (; ;) { for (; ;) { if (--num_probes_left == 0) { return; } #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) { break; } q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) { continue; } p = s; probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) { break; } c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) { return; } for (; ;) { for (; ;) { if (--num_probes_left == 0) { return; } #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) { break; } p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) { break; } if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) { return; } c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) { memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); } d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) { break; } while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) { cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; } if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) { return (n < 0) ? MZ_FALSE : MZ_TRUE; } total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) { return (n < 0) ? MZ_FALSE : MZ_TRUE; } total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) { d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) { d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; } hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) { d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; } if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { break; } // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) { break; } cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) { cur_match_len = 0; } else { cur_match_dist = 1; } } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) { tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1 - 1)]); } else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1 - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output buffer. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) { return (n < 0) ? MZ_FALSE : MZ_TRUE; } } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) { *pIn_buf_size = 0; } if (pOut_buf_size) { *pOut_buf_size = 0; } return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) { *pIn_buf_size = 0; } if (pOut_buf_size) { *pOut_buf_size = 0; } return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) { return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) { return d->m_prev_return_status; } } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) { return d->m_prev_return_status; } } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) { d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); } if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) { return d->m_prev_return_status; } d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { memset(d->m_hash, 0, TDEFL_LZ_HASH_SIZE); memset(d->m_next, 0, TDEFL_LZ_DICT_SIZE); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) { memset(d->m_hash, 0, TDEFL_LZ_HASH_SIZE); } d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) { return MZ_FALSE; } pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) { return MZ_FALSE; } succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) { return MZ_FALSE; } do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) { return MZ_FALSE; } p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) { return MZ_FALSE; } else { *pOut_len = 0; } out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) { return NULL; } *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) { return 0; } out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) { return 0; } return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; // level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) { comp_flags |= TDEFL_WRITE_ZLIB_HEADER; } if (!level) { comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; } else if (strategy == MZ_FILTERED) { comp_flags |= TDEFL_FILTER_MATCHES; } else if (strategy == MZ_HUFFMAN_ONLY) { comp_flags &= ~TDEFL_MAX_PROBES_MASK; } else if (strategy == MZ_FIXED) { comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; } else if (strategy == MZ_RLE) { comp_flags |= TDEFL_RLE_MATCHES; } return comp_flags; } #endif //MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) { return NULL; } MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) { tdefl_output_buffer_putter(&z, 1, &out_buf); } // compress image data tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8) *pLen_out, 0x49, 0x44, 0x41, 0x54 }; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) { ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); } memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) { (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); } // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } #ifdef _MSC_VER #pragma warning (pop) #endif // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) { return NULL; } return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) { return MZ_TRUE; } if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) { new_capacity *= 2; } } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) { return MZ_FALSE; } pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) { return MZ_FALSE; } } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) { return MZ_FALSE; } } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) { return MZ_FALSE; } memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) { return MZ_FALSE; } mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) { return MZ_FALSE; } if (!pZip->m_pAlloc) { pZip->m_pAlloc = def_alloc_func; } if (!pZip->m_pFree) { pZip->m_pFree = def_free_func; } if (!pZip->m_pRealloc) { pZip->m_pRealloc = def_realloc_func; } pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) { return MZ_FALSE; } memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) { break; } pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for (; ;) { if ((child = (root << 1) + 1) >= size) { break; } child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) { break; } MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (; ;) { if ((child = (root << 1) + 1) >= end) { break; } child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) { break; } MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) { return MZ_FALSE; } // Find the end of central directory record by scanning the file from the end towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (; ;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) { return MZ_FALSE; } for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) { break; } if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) { return MZ_FALSE; } cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) { return MZ_FALSE; } if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) { return MZ_FALSE; } num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) { return MZ_FALSE; } if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) { return MZ_FALSE; } cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) { return MZ_FALSE; } pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) { return MZ_FALSE; } if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) { return MZ_FALSE; } } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) { return MZ_FALSE; } // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) { return MZ_FALSE; } MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) { MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; } comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) { return MZ_FALSE; } disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) { return MZ_FALSE; } if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) { return MZ_FALSE; } if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) { return MZ_FALSE; } n -= total_header_size; p += total_header_size; } } if (sort_central_dir) { mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); } return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) { return MZ_FALSE; } if (!mz_zip_reader_init_internal(pZip, flags)) { return MZ_FALSE; } pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) { return MZ_FALSE; } pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) { return 0; } return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) { return MZ_FALSE; } if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { return NULL; } return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { return MZ_FALSE; } m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { return MZ_FALSE; } // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') { return MZ_TRUE; } } // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) { return MZ_TRUE; } return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) { return MZ_FALSE; } // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) { pFilename[0] = '\0'; } return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) { return 0 == memcmp(pA, pB, len); } for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) { return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) { break; } pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) { return file_index; } else if (comp < 0) { l = m + 1; } else { h = m - 1; } } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { return -1; } if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) { return mz_zip_reader_locate_file_binary_search(pZip, pName); } name_len = strlen(pName); if (name_len > 0xFFFF) { return -1; } comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) { return -1; } for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) { continue; } if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) { continue; } } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) { break; } } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) { return file_index; } } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) { return MZ_FALSE; } if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) { return MZ_FALSE; } // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) { return MZ_TRUE; } // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) { return MZ_TRUE; } // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) { return MZ_FALSE; } // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) { return MZ_FALSE; } // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) { return MZ_FALSE; } // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) { return MZ_FALSE; } if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) { return MZ_FALSE; } cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) { return MZ_FALSE; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) { return MZ_FALSE; } return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) { return MZ_FALSE; } pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) { return MZ_FALSE; } read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) { status = TINFL_STATUS_FAILED; } } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { return MZ_FALSE; } return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) { *pSize = 0; } if (!p) { return NULL; } comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) { return NULL; } if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) { *pSize = (size_t)alloc_size; } return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) { *pSize = 0; } return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) { return MZ_FALSE; } // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) { return MZ_TRUE; } // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) { return MZ_TRUE; } // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) { return MZ_FALSE; } // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) { return MZ_FALSE; } // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) { return MZ_FALSE; } if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) { return MZ_FALSE; } cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) { return MZ_FALSE; } // Decompress the file either directly from memory or from a file input buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) { return MZ_FALSE; } read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) { status = TINFL_STATUS_FAILED; } else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); } cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); } if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) { status = TINFL_STATUS_FAILED; } else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) { status = TINFL_STATUS_FAILED; } } if (!pZip->m_pState->m_pMem) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } if (pWrite_buf) { pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); } return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { return MZ_FALSE; } return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) { return MZ_FALSE; } pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) { return MZ_FALSE; } status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) { return MZ_FALSE; } #ifndef MINIZ_NO_TIME if (status) { mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); } #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { return MZ_FALSE; } if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) { return MZ_FALSE; } return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) { return MZ_FALSE; } if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) { return MZ_FALSE; } } if (!pZip->m_pAlloc) { pZip->m_pAlloc = def_alloc_func; } if (!pZip->m_pFree) { pZip->m_pFree = def_free_func; } if (!pZip->m_pRealloc) { pZip->m_pRealloc = def_realloc_func; } pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) { return MZ_FALSE; } memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) { new_capacity *= 2; } if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) { return 0; } pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) { return MZ_FALSE; } if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) { return 0; } return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) { return MZ_FALSE; } if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { return MZ_FALSE; } // No sense in trying to write to an archive that's already at the support max size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) { return MZ_FALSE; } pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) { return MZ_FALSE; } if (!pFilename) { return MZ_FALSE; } pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) { return MZ_FALSE; } pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the user has specified a write function too. else if (!pZip->m_pWrite) { return MZ_FALSE; } // Start writing new files at the archive's current central directory location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) { return MZ_FALSE; } pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) { return MZ_FALSE; } if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) { return MZ_FALSE; } if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. if (*pArchive_name == '/') { return MZ_FALSE; } while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) { return MZ_FALSE; } pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) { return 0; } n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) { return MZ_FALSE; } cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) { level_and_flags = MZ_DEFAULT_LEVEL; } level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) { return MZ_FALSE; } pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) { return MZ_FALSE; } // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) { return MZ_FALSE; } if (!mz_zip_writer_validate_archive_name(pArchive_name)) { return MZ_FALSE; } #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) { return MZ_FALSE; } num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) { return MZ_FALSE; } if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) { return MZ_FALSE; } } // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) { return MZ_FALSE; } if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) { return MZ_FALSE; } } if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) { method = MZ_DEFLATED; } } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) { return MZ_FALSE; } if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) { return MZ_FALSE; } if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) { return MZ_FALSE; } if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) { return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) { level_and_flags = MZ_DEFAULT_LEVEL; } level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) { return MZ_FALSE; } if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) { return MZ_FALSE; } if (!mz_zip_writer_validate_archive_name(pArchive_name)) { return MZ_FALSE; } archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) { return MZ_FALSE; } num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) { return MZ_FALSE; } if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) { return MZ_FALSE; } pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) { return MZ_FALSE; } MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) { level = 0; } if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for (; ;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) { break; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) { break; } } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) { return MZ_FALSE; } if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) { return MZ_FALSE; } if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) { return MZ_FALSE; } if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) { return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) { return MZ_FALSE; } if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) { return MZ_FALSE; } pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) { return MZ_FALSE; } cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) { return MZ_FALSE; } if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) { return MZ_FALSE; } cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) { return MZ_FALSE; } cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) { return MZ_FALSE; } cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) { return MZ_FALSE; } while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) { return MZ_FALSE; } orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) { return MZ_FALSE; } n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) { return MZ_FALSE; } n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) { return MZ_FALSE; } pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) { return MZ_FALSE; } central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) { return MZ_FALSE; } pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) { return MZ_FALSE; } #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) { return MZ_FALSE; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) { return MZ_FALSE; } if (pZip->m_pWrite != mz_zip_heap_write_func) { return MZ_FALSE; } if (!mz_zip_writer_finalize_archive(pZip)) { return MZ_FALSE; } *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) { return MZ_FALSE; } pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) { level_and_flags = MZ_DEFAULT_LEVEL; } if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) { return MZ_FALSE; } if (!mz_zip_writer_validate_archive_name(pArchive_name)) { return MZ_FALSE; } if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) { return MZ_FALSE; } created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) { return MZ_FALSE; } if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) { status = MZ_FALSE; } if (!mz_zip_writer_end(&zip_archive)) { status = MZ_FALSE; } if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) { *pSize = 0; } if ((!pZip_filename) || (!pArchive_name)) { return NULL; } MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) { return NULL; } if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) { p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); } mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */
the_stack_data/1092441.c
/*************************************************************************** * FILE: ser_pi_calc.c * DESCRIPTION: * Serial pi Calculation - C Version * This program calculates pi using a "dartboard" algorithm. See * Fox et al.(1988) Solving Problems on Concurrent Processors, vol.1 * page 207. * AUTHOR: unknown * REVISED: 02/23/12 Blaise Barney ***************************************************************************/ #include <stdio.h> #include <stdlib.h> void srandom (unsigned seed); double dboard (int darts); #define DARTS 10000 /* number of throws at dartboard */ #define ROUNDS 100 /* number of times "darts" is iterated */ int main(int argc, char *argv[]) { double pi; /* average of pi after "darts" is thrown */ double avepi; /* average pi value for all iterations */ int i, n; printf("Starting serial version of pi calculation using dartboard algorithm...\n"); srandom (5); /* seed the random number generator */ avepi = 0; for (i = 0; i < ROUNDS; i++) { /* Perform pi calculation on serial processor */ pi = dboard(DARTS); avepi = ((avepi * i) + pi)/(i + 1); printf(" After %3d throws, average value of pi = %10.8f\n", (DARTS * (i + 1)),avepi); } printf("\nReal value of PI: 3.1415926535897 \n"); } /***************************************************************************** * dboard *****************************************************************************/ #define sqr(x) ((x)*(x)) long random(void); double dboard(int darts) { double x_coord, /* x coordinate, between -1 and 1 */ y_coord, /* y coordinate, between -1 and 1 */ pi, /* pi */ r; /* random number scaled between 0 and 1 */ int score, /* number of darts that hit circle */ n; unsigned int cconst; /* must be 4-bytes in size */ /************************************************************************* * The cconst variable must be 4 bytes. We check this and bail if it is * not the right size ************************************************************************/ if (sizeof(cconst) != 4) { printf("Wrong data size for cconst variable in dboard routine!\n"); printf("See comments in source file. Quitting.\n"); exit(1); } /* 2 bit shifted to MAX_RAND later used to scale random number between 0 and 1 */ cconst = 2 << (31 - 1); score = 0; /*********************************************************************** * Throw darts at board. Done by generating random numbers * between 0 and 1 and converting them to values for x and y * coordinates and then testing to see if they "land" in * the circle." If so, score is incremented. After throwing the * specified number of darts, pi is calculated. The computed value * of pi is returned as the value of this function, dboard. ************************************************************************/ for (n = 1; n <= darts; n++) { /* generate random numbers for x and y coordinates */ r = (double)random()/cconst; x_coord = (2.0 * r) - 1.0; r = (double)random()/cconst; y_coord = (2.0 * r) - 1.0; /* if dart lands in circle, increment score */ if ((sqr(x_coord) + sqr(y_coord)) <= 1.0) score++; } /* calculate pi */ pi = 4.0 * (double)score/(double)darts; return(pi); }
the_stack_data/85816.c
#include<stdio.h> int main() { int a, b ,count = 0, result = 0; printf("Enter two numbers to perform multiplication : "); scanf("%d %d",&a,&b); while(b) { if(b % 2 == 1) result += a << count; count++; b/=2; } printf("a * b = %d\n",result); return 0; }
the_stack_data/275506.c
#include <unistd.h> #include <fcntl.h> #define BUF_SIZE 1000 int main(int argc, char** argv) { if (argc > 1) { int fd = creat(argv[1], 0644); close(1); dup(fd); } char buf[BUF_SIZE]; int len; while ((len = read(0, buf, BUF_SIZE))) write(1, buf, len); return 0; }
the_stack_data/1143778.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #define BYTES_PER_PIXEL 3 #define FILE_HEADER_SIZE 14 #define INFO_HEADER_SIZE 40 unsigned char *createBitmapInfoHeader(int height, int width){ static unsigned char infoHeader[] = { 0,0,0,0, /// header size 0,0,0,0, /// image width 0,0,0,0, /// image height 0,0, /// number of color planes 0,0, /// bits per pixel 0,0,0,0, /// compression 0,0,0,0, /// image size 0,0,0,0, /// horizontal resolution 0,0,0,0, /// vertical resolution 0,0,0,0, /// colors in color table 0,0,0,0, /// important color count }; infoHeader[ 0] = (unsigned char)(INFO_HEADER_SIZE); infoHeader[ 4] = (unsigned char)(width ); infoHeader[ 5] = (unsigned char)(width >> 8); infoHeader[ 6] = (unsigned char)(width >> 16); infoHeader[ 7] = (unsigned char)(width >> 24); infoHeader[ 8] = (unsigned char)(height ); infoHeader[ 9] = (unsigned char)(height >> 8); infoHeader[10] = (unsigned char)(height >> 16); infoHeader[11] = (unsigned char)(height >> 24); infoHeader[12] = (unsigned char)(1); infoHeader[14] = (unsigned char)(BYTES_PER_PIXEL*8); return infoHeader; } unsigned char *createBitmapFileHeader(int height, int stride){ int fileSize = FILE_HEADER_SIZE + INFO_HEADER_SIZE + (stride * height); static unsigned char fileHeader[] = { 0,0, /// signature 0,0,0,0, /// image file size in bytes 0,0,0,0, /// reserved 0,0,0,0, /// start of pixel array }; fileHeader[ 0] = (unsigned char)('B'); fileHeader[ 1] = (unsigned char)('M'); fileHeader[ 2] = (unsigned char)(fileSize ); fileHeader[ 3] = (unsigned char)(fileSize >> 8); fileHeader[ 4] = (unsigned char)(fileSize >> 16); fileHeader[ 5] = (unsigned char)(fileSize >> 24); fileHeader[10] = (unsigned char)(FILE_HEADER_SIZE + INFO_HEADER_SIZE); return fileHeader; } void generateBitmapImage(unsigned char *image, int height, int width, FILE *imageFile){ int widthInBytes = width * BYTES_PER_PIXEL; unsigned char padding[3] = {0, 0, 0}; int paddingSize = (4 - (widthInBytes) % 4) % 4; int stride = (widthInBytes) + paddingSize; unsigned char* fileHeader = createBitmapFileHeader(height, stride); fwrite(fileHeader, 1, FILE_HEADER_SIZE, imageFile); unsigned char* infoHeader = createBitmapInfoHeader(height, width); fwrite(infoHeader, 1, INFO_HEADER_SIZE, imageFile); int i; for (i = 0; i < height; i++) { fwrite(image + (i*widthInBytes), BYTES_PER_PIXEL, width, imageFile); fwrite(padding, 1, paddingSize, imageFile); } } unsigned char *create_bitmap(int size, double *vals){ unsigned char *image = (unsigned char *) malloc(sizeof(unsigned char) * size * BYTES_PER_PIXEL); int index = 0; for (int i = 0; i < size; i++) { double val = vals[i]; val = (val + 1.0) / 2.0; unsigned char gray = (unsigned char) (val * 255); image[index++] = gray; image[index++] = gray; image[index++] = gray; } return image; } char *save_bitmap(char *filename, int width, int height, double *vals){ unsigned char *image = create_bitmap(width * height, vals); FILE *f = fopen(filename, "wb"); generateBitmapImage(image, height, width, f); fclose(f); free(image); free(vals); return filename; } unsigned char *load_bitmap(char *filename, long *num_bytes){ FILE *f = fopen(filename,"rb"); unsigned char info[54]; // read the 54-byte header fread(info, sizeof(unsigned char), 54, f); // extract image height and width from header int width = *(int*)&info[18]; int height = *(int*)&info[22]; // allocate 3 bytes per pixel int size = BYTES_PER_PIXEL * width * height; unsigned char *data = (unsigned char *) malloc(sizeof(unsigned char) * size); // read the rest of the data at once fread(data, sizeof(unsigned char), size, f); fclose(f); for (int i = 0; i < size; i += BYTES_PER_PIXEL){ // flip the order of every 3 bytes unsigned char tmp = data[i]; data[i] = data[i+2]; data[i+2] = tmp; } *num_bytes = sizeof(unsigned char) * size; return data; } int bitmap_compare(char *filename1, char *filename2){ long num_bytes; unsigned char *data1 = load_bitmap(filename1, &num_bytes); unsigned char *data2 = load_bitmap(filename2, &num_bytes); return memcmp(data1, data2, num_bytes) == 0; }
the_stack_data/72013881.c
#include<stdio.h> int a[105]; int mMin(int a,int b){ if(a>b) return b; else return a; } int mMax(int a,int b){ if(a<b) return b; else return a; } int na(int l,int r,int n){ int i,result,sum=0; for(i=l;i<=r;i++) sum+=a[i]; return sum%n; } int ma(int l,int r,int n){ int i,result,sum=1; for(i=l;i<=r;i++) { sum*=a[i]; sum=sum%n; } return sum; } int ha(int l,int r){ int i,result=0; for(i=l;i<=r;i++){ result=result^a[i];} return result; } int main(){ int K,n,N,i,l,r,min,max,sss; scanf("%d%d",&n,&K); for(i=0;i<n;i++) scanf("%d",&a[i]); N=K; while(N--) { scanf("%d%d",&l,&r); min=mMin(na(l,r,n),ma(l,r,n)); max=mMax(na(l,r,n),ma(l,r,n)); sss=ha(min,max); printf("%d\n",sss); } return 0; }
the_stack_data/34290.c
#include <stdio.h> #include <stdlib.h> struct node{ char a; struct node* next; }; struct node* create_node(char a) { struct node* node = malloc(sizeof(struct node)); node->a = a; node->next = 0; return node; } void print_linked_list(struct node* head) { while(head){ printf("%c",head->a); head = head->next; } puts(""); } int main() { struct node* head = 0; struct node* node = 0; char c = 0; while(1){ c = getchar(); if(c=='\n') continue; if(c==' ') break; node = create_node(c); if(head){ node->next = head; } head = node; }; print_linked_list(head); // destroy the linked list after using // complete the code here return 0; }
the_stack_data/920788.c
/* * $Id: strhandler.c 1.1 02/01/03 00:59:53-00:00 twouters@ $ * * Author: Markus Stenberg <[email protected]> * * Copyright (c) 1998 Markus Stenberg * All rights reserved * * Created: Thu Jun 4 21:41:16 1998 fingon * Last modified: Thu Dec 10 22:09:46 1998 fingon * */
the_stack_data/35118.c
#include <stdio.h> main() { while (!feof(stdin)) { int c = getchar(); if (c != EOF) { putchar(c); } } }
the_stack_data/1184578.c
#include<stdio.h> int main() { // Declare Variables int nb,blockSize[100],n,jobSize[100],i,j,alloc[100],avail[100],min,max; //Input initial values printf("Enter the number of available memory blocks: "); scanf("%d",&nb); printf("Enter the size of each memory block: \n"); for(i=0;i<nb;i++) { printf("Size of block%d: ",i+1); scanf("%d",&blockSize[i]); } printf("Enter the number of processes: "); scanf("%d",&n); printf("Enter the size of each process: \n"); for(i=0;i<n;i++) { printf("Size of process%d: ",i+1); scanf("%d",&jobSize[i]); } // Initialize alloc vector to -1 and avail to 99999 for(i=0;i<n;i++) { alloc[i]=-1; } for(i=0;i<nb;i++){ avail[i]=-1; } // Check for each process the blocks available for(i=0;i<n;i++) { for(j=0;j<nb;j++) { if(blockSize[j]>jobSize[i]){ avail[j]=blockSize[j]-jobSize[i]; } } max=0; for(j=0;j<nb;j++) { if(avail[max]<avail[j]) { max=j; } } alloc[i]=max; if(avail[max]<=50){ alloc[i]=-1; } blockSize[min]=-1; // Initialize avail to 99999 for(j=0;j<n;j++) { avail[j]=9999; } } // Print the results printf("Process P of {size} is allocated to block \n"); for(i=0;i<n;i++) { if(alloc[i]!=-1) printf("Process %d of %d --> Block %d\n",i+1,jobSize[i],alloc[i]+1); else printf("Process %d of %d --> is not allocated \n",i+1,jobSize[i]); } }
the_stack_data/6386485.c
// // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005-2014 Simon Howard // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // DESCRIPTION: // Random number LUT. // // // M_Random // Returns a 0-255 number // static const unsigned char rndtable[256] = { 0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66 , 74, 21, 211, 47, 80, 242, 154, 27, 205, 128, 161, 89, 77, 36 , 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188 , 52, 140, 202, 120, 68, 145, 62, 70, 184, 190, 91, 197, 152, 224 , 149, 104, 25, 178, 252, 182, 202, 182, 141, 197, 4, 81, 181, 242 , 145, 42, 39, 227, 156, 198, 225, 193, 219, 93, 122, 175, 249, 0 , 175, 143, 70, 239, 46, 246, 163, 53, 163, 109, 168, 135, 2, 235 , 25, 92, 20, 145, 138, 77, 69, 166, 78, 176, 173, 212, 166, 113 , 94, 161, 41, 50, 239, 49, 111, 164, 70, 60, 2, 37, 171, 75 , 136, 156, 11, 56, 42, 146, 138, 229, 73, 146, 77, 61, 98, 196 , 135, 106, 63, 197, 195, 86, 96, 203, 113, 101, 170, 247, 181, 113 , 80, 250, 108, 7, 255, 237, 129, 226, 79, 107, 112, 166, 103, 241 , 24, 223, 239, 120, 198, 58, 60, 82, 128, 3, 184, 66, 143, 224 , 145, 224, 81, 206, 163, 45, 63, 90, 168, 114, 59, 33, 159, 95 , 28, 139, 123, 98, 125, 196, 15, 70, 194, 253, 54, 14, 109, 226 , 71, 17, 161, 93, 186, 87, 244, 138, 20, 52, 123, 251, 26, 36 , 17, 46, 52, 231, 232, 76, 31, 221, 84, 37, 216, 165, 212, 106 , 197, 242, 98, 43, 39, 175, 254, 145, 190, 84, 118, 222, 187, 136 , 120, 163, 236, 249 }; int rndindex = 0; int prndindex = 0; // Which one is deterministic? int P_Random (void) { prndindex = (prndindex+1)&0xff; return rndtable[prndindex]; } int M_Random (void) { rndindex = (rndindex+1)&0xff; return rndtable[rndindex]; } void M_ClearRandom (void) { rndindex = prndindex = 0; }
the_stack_data/23576504.c
/* ** EPITECH PROJECT, 2017 ** my_showmem ** File description: ** show mem */ int my_showmem(char const *str, int size) { return (0); }
the_stack_data/132952386.c
// Nothing Special #include <stdio.h> #include <stdlib.h> #include <math.h> int manhattan_dist(int a1 , int a2 , int b1 , int b2) { return (abs(a1 - a2) + abs(b1 - b2)); } int main() { int x1, x2, y1, y2, dist=0; printf("Enter points of A: "); scanf("%d %d" , &x1 , &x2); printf("Enter points of B: "); scanf("%d %d" , &x2 , &y2); dist = manhattan_dist(x1 , x2 , y1 , y2); printf("The Manhattan distance is: %d\n" , dist); return 0; }
the_stack_data/200144468.c
#include <stdlib.h> #include <string.h> #define MOD ((int)(1e9 + 7)) int dfs(int M, int N, int move, int row, int col, int (*dp)[M][N]) { if (row < 0 || row >= M || col < 0 || col >= N) return 1; if (move < 0) return 0; if (dp[move][row][col] != -1) return dp[move][row][col]; int res = 0; int path[] = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) res = (res + dfs(M, N, move - 1, row + path[k], col + path[k + 1], dp)) % MOD; dp[move][row][col] = res; return res; } int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { int dp[maxMove][m][n]; memset(dp, -1, sizeof(dp)); return dfs(m, n, maxMove - 1, startRow, startColumn, dp); }
the_stack_data/150141424.c
#include <stdio.h> #include <string.h> void test(char *dest_str, char *src, unsigned int size) { char dest[size]; char ft_dest[size]; int diff; strcpy(dest, dest_str); strcpy(ft_dest, dest_str); diff = ft_strlcat(ft_dest, src, size) == strlcat(dest, src, size); printf("%d, %d\n", diff, strcmp(ft_dest, dest)); } int main(void) { test("Hello", " world!", 13); test("Hello", " world!", 20); test("Hello", " w", 13); test("", "Hello world!", 15); test("Hello", ", append very long string", 15); test("Hello", " world!", 3); return (0); }
the_stack_data/114071.c
/*This is tone file*/ const char* tone_uri[] = { "flash://tone/0_already_new.mp3", "flash://tone/1_boot.mp3", "flash://tone/2_bt_connect.mp3", "flash://tone/3_bt_disconnect.mp3", "flash://tone/4_downloaded.mp3", "flash://tone/5_linked.mp3", "flash://tone/6_not_find.mp3", "flash://tone/7_ota_fail.mp3", "flash://tone/8_ota_start.mp3", "flash://tone/9_shut_down.mp3", "flash://tone/10_smart_config.mp3", "flash://tone/11_unlinked.mp3", "flash://tone/12_wakeup.mp3", }; int get_tone_uri_num() { return sizeof(tone_uri) / sizeof(char *) - 1; }
the_stack_data/133737.c
/* K.N.King "C Programming. A Modern Approach." Programming project 9 p.157 Write a program that asks the user for a 12-hour time, then displays the time in 24-hour form: hours:minutes followed by either A, P, AM, or PM (either lowercase or uppercase). Whitespace is allowed (but not required) between the numerical time and the AM/PM indicator. */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #define BUFFER_SIZE 256 #define MINUTES_PER_HOUR 60 #define MIDDAY_HOUR 12 enum TimePeriod { AM, PM }; struct ShortTimeStamp24Hour { int hours; int minutes; }; struct ShortTimeStamp12Hour { int hours; int minutes; enum TimePeriod timePeriod; }; struct ShortTimeStamp24Hour* ShortTimeStamp12HourConvertToShortTimeStamp24Hour( const struct ShortTimeStamp12Hour* stamp, struct ShortTimeStamp24Hour* OutResult); int main(void) { char buffer[BUFFER_SIZE] = { 0 }; int hours = 0; int minutes = 0; char c = '\0'; char* pchar = NULL; struct ShortTimeStamp12Hour userTime12Hour = { 0 }; struct ShortTimeStamp24Hour userTime24Hour = { 0 }; while (1) { if (!fgets(buffer, BUFFER_SIZE, stdin)) { return EXIT_FAILURE; } // if user enters input longer than BUFFER_SIZE - 1, // discard the trailing input // we can detect that if the last character before // the null terminating character is not equal to a // new line feed if (buffer[strlen(buffer) - 1] != '\n') { while ( (c = getchar()) != '\n' && c != EOF) continue; } // consume the numbers, store the rest of input back // in the buffer if ( sscanf(buffer, "%d : %d %s", &hours, &minutes, buffer) <3 || (hours < 0 || hours > MIDDAY_HOUR) || (minutes < 0 || minutes >= MINUTES_PER_HOUR)) { fprintf(stderr, "Input invalid. Please try again.\n"); continue; } pchar = buffer; // convert to upper case for case insensitive comparison while ((c = *pchar) != '\0') { *pchar = toupper(c); ++pchar; } if (strcmp(buffer, "AM") == 0 || strcmp(buffer, "A") == 0) { userTime12Hour.timePeriod = AM; break; } else if (strcmp(buffer, "PM") == 0 || strcmp(buffer, "P") == 0) { userTime12Hour.timePeriod = PM; break; } else { fprintf(stderr, "Input invalid. Please try again.\n"); continue; } } userTime12Hour.hours = hours; userTime12Hour.minutes = minutes; ShortTimeStamp12HourConvertToShortTimeStamp24Hour(&userTime12Hour, &userTime24Hour); printf("%d:%d\n", userTime24Hour.hours, userTime24Hour.minutes); getchar(); return EXIT_SUCCESS; } struct ShortTimeStamp24Hour* ShortTimeStamp12HourConvertToShortTimeStamp24Hour( const struct ShortTimeStamp12Hour* stamp, struct ShortTimeStamp24Hour* OutResult) { if (!stamp || !OutResult) return NULL; OutResult->hours = (stamp->timePeriod == PM && stamp->hours != MIDDAY_HOUR) ? stamp->hours + MIDDAY_HOUR : stamp->hours; OutResult->minutes = stamp->minutes; return OutResult; }
the_stack_data/25042.c
#include <stdlib.h> int main(void) { int counter = 0; while (counter < 5) { counter++; } while (counter < 10) { counter++; } while (counter < 15) { counter++; } return (0); }
the_stack_data/67325855.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" /* * _D_cplx_lr_div_rx(a, w) returns a / w computed by the textbook * formula without regard to exceptions or special cases. * * This code is intended to be used only when CX_LIMITED_RANGE is * ON; otherwise use _D_cplx_div_rx. */ #if !defined(i386) && !defined(__i386) && !defined(__amd64) #error This code is for x86 only #endif double _Complex _D_cplx_lr_div_rx(double a, double _Complex w) { double _Complex v; long double c, d, r; /* LINTED alignment */ c = ((double *)&w)[0]; /* LINTED alignment */ d = ((double *)&w)[1]; r = a / (c * c + d * d); /* LINTED alignment */ ((double *)&v)[0] = (double)(r * c); /* LINTED alignment */ ((double *)&v)[1] = (double)(r * -d); return (v); }
the_stack_data/45450614.c
#include<stdio.h> double taylorSimplifiedRecursion(double power, double nthTerm) { static double sum = 1.00; if(nthTerm == 0.00) { return sum; } else { sum = 1.00 + (power / nthTerm) * sum; return taylorSimplifiedRecursion(power, nthTerm - 1.00); } } double taylorIterative(double power, double nthTerm) { double sum = 1.00; for( ; nthTerm > 0.00; nthTerm--) { sum = 1.00 + (power / nthTerm) * sum; } return sum; } int main() { double power = 1.00, nthTerm = 20.00; printf("Using Simplified Taylor Series for Power %lf till %lf term, e = %lf\n", power, nthTerm, taylorSimplifiedRecursion(power, nthTerm)); printf("Using Iterative Metorh Taylor Series for Power %lf till %lf term, e = %lf\n", power, nthTerm, taylorSimplifiedRecursion(power, nthTerm)); return 0; }
the_stack_data/89199568.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BLPATH "/sys/class/leds/smc::kbd_backlight" #define BLVALFILE BLPATH "/brightness" #define BLMAXFILE BLPATH "/max_brightness" #define BLCHANGE 16 void usage() { printf("Usage: kbdlight [up [<percentage>]|down [<percentage>]|off|max|get|set <value>]\n"); exit(0); } int main(int argc, char* argv[]) { int current, change, next, maxval; FILE *file; if (argc < 2) { usage(); } if(!(file = fopen(BLVALFILE, "r"))) { perror("failed to open the keyboard backlight file: " BLVALFILE); return 1; } fscanf(file, "%d", &current); fclose(file); if((file = fopen(BLMAXFILE, "r"))) { fscanf(file, "%d", &maxval); fclose(file); } else { maxval = 255; } if (!strcmp(argv[1], "up") || !strcmp(argv[1], "down")) { if (argv[2]) { char *endp; change = strtol(argv[2], &endp, 10); if (endp == argv[2]) { fprintf(stderr, "percentage must be a number from 0 to 100.\n"); return 1; } change = change * 0.01 * maxval; } else { change = BLCHANGE; } } if (!strcmp(argv[1], "up")) next = current >= maxval - change ? maxval : current + change; else if (!strcmp(argv[1], "down")) next = current <= change ? 0 : current - change; else if (!strcmp(argv[1], "off")) next = 0; else if (!strcmp(argv[1], "max")) next = maxval; else if (!strcmp(argv[1], "set")) { char *endp; if(!argv[2] || (next = strtol(argv[2], &endp, 10), endp == argv[2])) { fprintf(stderr, "set must be followed by a number from 0 to %d\n", maxval); return 1; } } else if(!strcmp(argv[1], "get")) { printf("%d\n", current); return 0; } else usage(); if((file = fopen(BLVALFILE, "w"))) { fprintf(file, "%d", next); fclose(file); } else { perror("failed to write to the keyboard backlight file: " BLVALFILE); } return 0; }
the_stack_data/178264267.c
/* Generated by CIL v. 1.3.7 */ /* print_CIL_Input is true */ #line 14 "../versisec/bind/progs1/../lib/stubs.h" typedef int size_t; #line 7 "../versisec/bind/progs1/../bind.h" typedef char u_char; #line 8 "../versisec/bind/progs1/../bind.h" typedef int u_int; #line 27 "../versisec/bind/progs1/../lib/stubs.h" extern unsigned int strlen(char const *s ) ; #line 53 extern void *r_memcpy(void *dest , void const *src , size_t n ) ; #line 46 "../versisec/bind/progs1/../bind.h" extern int dn_expand(u_char const *msg , u_char const *eomorig , u_char const *comp_dn , char *exp_dn , int length ) ; #line 50 extern int __VERIFIER_nondet_int() ; extern int __VERIFIER_nondet_short() ; #line 71 "/usr/include/assert.h" extern __attribute__((__nothrow__, __noreturn__)) void __assert_fail(char const *__assertion , char const *__file , unsigned int __line , char const *__function ) ; #line 6 "../versisec/bind/progs1/bindCA-1999-14rrextract-nxt_two_expands_ok.c" static int rrextract(u_char *msg , int msglen , u_char *rrp , u_char *dname , int namelen ) { u_char *eom ; u_char *cp ; u_char *cp1 ; u_int dlen ; int n ; int n1 ; int n2 ; u_char data[6] ; int tmp ; unsigned int tmp___0 ; unsigned int tmp___1 ; unsigned long __cil_tmp20 ; unsigned long __cil_tmp21 ; unsigned long __cil_tmp22 ; u_char *__cil_tmp23 ; unsigned long __cil_tmp24 ; u_char const *__cil_tmp25 ; u_char const *__cil_tmp26 ; u_char const *__cil_tmp27 ; u_char const *__cil_tmp28 ; u_char const *__cil_tmp29 ; u_char const *__cil_tmp30 ; unsigned long __cil_tmp31 ; unsigned long __cil_tmp32 ; u_char *__cil_tmp33 ; int __cil_tmp34 ; unsigned long __cil_tmp35 ; unsigned long __cil_tmp36 ; u_char *__cil_tmp37 ; char const *__cil_tmp38 ; unsigned int __cil_tmp39 ; unsigned long __cil_tmp40 ; unsigned long __cil_tmp41 ; u_char *__cil_tmp42 ; unsigned long __cil_tmp43 ; unsigned long __cil_tmp44 ; unsigned long __cil_tmp45 ; unsigned long __cil_tmp46 ; unsigned long __cil_tmp47 ; u_char *__cil_tmp48 ; char const *__cil_tmp49 ; unsigned int __cil_tmp50 ; unsigned long __cil_tmp51 ; unsigned long __cil_tmp52 ; u_int __cil_tmp53 ; unsigned long __cil_tmp54 ; void *__cil_tmp55 ; void const *__cil_tmp56 ; { #line 14 __cil_tmp20 = 5 * 1UL; #line 14 __cil_tmp21 = (unsigned long )(data) + __cil_tmp20; #line 14 *((u_char *)__cil_tmp21) = (char)0; #line 16 cp = rrp; #line 17 eom = msg + msglen; { #line 19 while (1) { while_0_continue: /* CIL Label */ ; { #line 19 dlen = __VERIFIER_nondet_short(); #line 19 cp = cp + 2; } goto while_0_break; } while_0_break: /* CIL Label */ ; } { #line 20 while (1) { while_1_continue: /* CIL Label */ ; { #line 20 __cil_tmp22 = (unsigned long )eom; #line 20 __cil_tmp23 = cp + dlen; #line 20 __cil_tmp24 = (unsigned long )__cil_tmp23; #line 20 if (__cil_tmp24 > __cil_tmp22) { #line 20 return (-1); } else { } } goto while_1_break; } while_1_break: /* CIL Label */ ; } { #line 22 __cil_tmp25 = (u_char const *)msg; #line 22 __cil_tmp26 = (u_char const *)eom; #line 22 __cil_tmp27 = (u_char const *)cp; #line 22 n = dn_expand(__cil_tmp25, __cil_tmp26, __cil_tmp27, dname, namelen); } #line 22 if (n < 0) { #line 23 return (-1); } else { } { #line 26 cp = cp + n; #line 30 __cil_tmp28 = (u_char const *)msg; #line 30 __cil_tmp29 = (u_char const *)eom; #line 30 __cil_tmp30 = (u_char const *)cp; #line 30 __cil_tmp31 = 0 * 1UL; #line 30 __cil_tmp32 = (unsigned long )(data) + __cil_tmp31; #line 30 __cil_tmp33 = (u_char *)__cil_tmp32; #line 30 __cil_tmp34 = (int )6UL; #line 30 n = dn_expand(__cil_tmp28, __cil_tmp29, __cil_tmp30, __cil_tmp33, __cil_tmp34); } #line 32 if (n < 0) { #line 33 return (-1); } else { #line 32 if (n >= dlen) { #line 33 return (-1); } else { } } { #line 36 tmp = __VERIFIER_nondet_int(); } #line 36 if (tmp) { #line 37 return (-1); } else { } { #line 39 cp = cp + n; #line 41 __cil_tmp35 = 0 * 1UL; #line 41 __cil_tmp36 = (unsigned long )(data) + __cil_tmp35; #line 41 __cil_tmp37 = (u_char *)__cil_tmp36; #line 41 __cil_tmp38 = (char const *)__cil_tmp37; #line 41 tmp___0 = strlen(__cil_tmp38); #line 41 __cil_tmp39 = tmp___0 + 1U; #line 41 n1 = (int )__cil_tmp39; #line 42 __cil_tmp40 = 0 * 1UL; #line 42 __cil_tmp41 = (unsigned long )(data) + __cil_tmp40; #line 42 __cil_tmp42 = (u_char *)__cil_tmp41; #line 42 cp1 = __cil_tmp42 + n1; #line 44 n2 = dlen - n; } { #line 45 __cil_tmp43 = (unsigned long )n1; #line 45 __cil_tmp44 = 6UL - __cil_tmp43; #line 45 __cil_tmp45 = (unsigned long )n2; #line 45 if (__cil_tmp45 > __cil_tmp44) { #line 46 return (-1); } else { } } { #line 50 __cil_tmp46 = 0 * 1UL; #line 50 __cil_tmp47 = (unsigned long )(data) + __cil_tmp46; #line 50 __cil_tmp48 = (u_char *)__cil_tmp47; #line 50 __cil_tmp49 = (char const *)__cil_tmp48; #line 50 tmp___1 = strlen(__cil_tmp49); } { #line 50 __cil_tmp50 = tmp___1 + 1U; #line 50 __cil_tmp51 = (unsigned long )__cil_tmp50; #line 50 __cil_tmp52 = 6UL - __cil_tmp51; #line 50 __cil_tmp53 = dlen - n; #line 50 __cil_tmp54 = (unsigned long )__cil_tmp53; #line 50 if (__cil_tmp54 <= __cil_tmp52) { } else { { #line 50 __assert_fail("dlen - n <= sizeof data - (strlen((char *)data) + 1)", "../versisec/bind/progs1/bindCA-1999-14rrextract-nxt_two_expands_ok.c", 50U, "rrextract"); } } } { #line 52 __cil_tmp55 = (void *)cp1; #line 52 __cil_tmp56 = (void const *)cp; #line 52 r_memcpy(__cil_tmp55, __cil_tmp56, n2); } #line 54 return (0); } } #line 57 "../versisec/bind/progs1/bindCA-1999-14rrextract-nxt_two_expands_ok.c" int main(void) { int msglen ; int ret ; u_char *dp ; u_char name[3] ; u_char msg[6] ; unsigned long __cil_tmp6 ; unsigned long __cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; unsigned long __cil_tmp10 ; unsigned long __cil_tmp11 ; unsigned long __cil_tmp12 ; unsigned long __cil_tmp13 ; u_char *__cil_tmp14 ; unsigned long __cil_tmp15 ; unsigned long __cil_tmp16 ; u_char *__cil_tmp17 ; { { #line 64 __cil_tmp6 = 2 * 1UL; #line 64 __cil_tmp7 = (unsigned long )(name) + __cil_tmp6; #line 64 *((u_char *)__cil_tmp7) = (char)0; #line 65 __cil_tmp8 = 5 * 1UL; #line 65 __cil_tmp9 = (unsigned long )(msg) + __cil_tmp8; #line 65 *((u_char *)__cil_tmp9) = (char)0; #line 67 msglen = 4; #line 68 __cil_tmp10 = 0 * 1UL; #line 68 __cil_tmp11 = (unsigned long )(msg) + __cil_tmp10; #line 68 dp = (u_char *)__cil_tmp11; #line 70 __cil_tmp12 = 0 * 1UL; #line 70 __cil_tmp13 = (unsigned long )(msg) + __cil_tmp12; #line 70 __cil_tmp14 = (u_char *)__cil_tmp13; #line 70 __cil_tmp15 = 0 * 1UL; #line 70 __cil_tmp16 = (unsigned long )(name) + __cil_tmp15; #line 70 __cil_tmp17 = (u_char *)__cil_tmp16; #line 70 ret = rrextract(__cil_tmp14, msglen, dp, __cil_tmp17, 3); } #line 72 return (0); } }
the_stack_data/1196971.c
#include <sys/time.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <stdlib.h> #include <string.h> int period_us = 1000; int ticks = 0; char filename[] = "channel0"; #define T_MAX_US 10000 static void periodic(int signal); int main(int argc, char *argv[]) { /* Set up periodic SIGALRM and its handler */ struct itimerval period = { { period_us / 1000000, period_us % 1000000, }, { period_us / 1000000, period_us % 1000000, }, }; signal(SIGALRM, periodic); setitimer(ITIMER_REAL, &period, NULL); int fdr = -1; static char buffer[] = " \n"; while (ticks < T_MAX_US) { if (fdr < 0) { fdr = open(filename, O_RDONLY); } if (fdr >= 0) { lseek(fdr, 0, SEEK_SET); read(fdr, buffer, 4); write(1, buffer, 5); } } close(fdr); return 0; } /* SIGALRM handler stores times, re-installs for 1min, eval each 1000 cycles */ static void periodic(int sig) { int fdw; static char buffer[4]; if (!ticks) { fdw = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0600); } if (ticks++ < T_MAX_US) { memset(buffer, '0' + ticks % 10, 4); lseek(fdw, 0, SEEK_SET); write(fdw, buffer, 4); signal(SIGALRM, periodic); } else { close(fdw); unlink(filename); } }
the_stack_data/88553.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putnbr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mateussavaris <[email protected] +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/20 14:59:40 by mateussavar #+# #+# */ /* Updated: 2021/09/20 15:00:36 by mateussavar ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } void ft_putnbr(int nb) { if (nb == -2147483648) { ft_putchar('-'); ft_putchar('2'); nb = 147483648; } if (nb < 0) { ft_putchar('-'); nb = -nb; } if (nb < 10) { ft_putchar(nb + '0'); return ; } else ft_putnbr(nb / 10); ft_putnbr(nb % 10); }
the_stack_data/61075515.c
#include <assert.h> #include <stdio.h> #include <string.h> const char * long_string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const char * short_string = "ABCD"; void test_explicit_printf_format() { printf("\n===== test_explicit_printf_format\n"); printf("> printf(\"Prints just 5 characters (should print 'ABCDE'): %%.5s\\n\", long_string);\n"); printf("Prints just 5 characters (should print 'ABCDE'): %.5s\n", long_string); } void test_printf_width_as_argument() { printf("\n===== test_printf_width_as_argument\n"); printf("> printf(\"Prints just %%d characters (should print 'AB'): %%.*s\\n\", 2, 2, long_string);\n"); printf("Prints just %d characters (should print 'AB'): %.*s\n", 2, 2, long_string); } void test_printf_still_honours_null_termination() { printf("\n===== test_explicit_printf_format\n"); printf("> printf(\"Asking for 5 characters, but only 4 available (should print 'ABCD'): %%.5s\\n\", short_string);\n"); printf("Asking for 5 characters, but only 4 available (should print 'ABCD'): %.5s\n", short_string); } void test_explicit_sprintf_format() { printf("\n===== test_explicit_sprintf_format\n"); char result[10]; char expected[] = "ABCDE"; printf("> sprintf(result, \"%%.5s\", long_string);\n"); sprintf(result, "%.5s", long_string); assert(strcmp(result, expected) == 0); } void test_sprintf_with_width_as_argument() { printf("\n===== test_sprintf_with_width_as_argument\n"); char result[10]; char expected[] = "AB"; printf("> sprintf(result, \"%%.*s\", 2, long_string);\n"); sprintf(result, "%.*s", 2, long_string); assert(strcmp(result, expected) == 0); } int main(void) { test_explicit_printf_format(); test_printf_width_as_argument(); test_printf_still_honours_null_termination(); test_explicit_sprintf_format(); test_sprintf_with_width_as_argument(); }
the_stack_data/175142610.c
/* DataToC output of file <fill_png> */ extern int datatoc_fill_png_size; extern char datatoc_fill_png[]; int datatoc_fill_png_size = 12244; char datatoc_fill_png[] = { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 96, 0, 0, 0, 96, 8, 2, 0, 0, 0,109,250,224,111, 0, 0, 0, 4,103, 65, 77, 65, 0, 0,177,143, 11,252, 97, 5, 0, 0, 0, 9,112, 72, 89,115, 0, 0, 13,215, 0, 0, 13,215, 1, 66, 40,155,120, 0, 0, 0, 7,116, 73, 77, 69, 7,218, 7, 19, 0, 34, 12, 33,249,187,131, 0, 0, 0, 6, 98, 75, 71, 68, 0, 0, 0, 0, 0, 0,249, 67,187,127, 0, 0, 47, 81, 73, 68, 65, 84,120,218,237,125, 73,172,110,233,117,213,233,155,191,185,255,189,247, 53,245,158, 93,109,108,167,108,202, 85,114,111, 17, 55, 16, 7,108, 18, 20,145, 12,130, 33,129, 56, 68,142,101, 69, 65, 8, 24, 16, 4, 3,164, 48, 1, 49, 64, 12,152, 48, 98,194,128, 1, 30, 6,201, 9, 65, 34,194,200,196,144,132,216, 49,114,226, 56,213,191,122,239,222,191, 61,127,115,254,211,176,214,218,223, 57,231,127,149, 56,177, 98,199, 2, 81,183,238,171,119,235,189,123, 79,179,191,189,215, 94,123,237,253,125,229,127,244,163, 31,245,222,248,248,230, 31, 17,126,205,231,243,197, 98,225,251,254, 27,230,232, 63,218,182, 61, 63, 63,191,184,184,160,129, 96,157, 23, 94,120,225, 13,163,252,193, 15, 24, 40,192,111,111,248,206, 31,250, 97,102, 9,222, 48,196, 31,253,241,134,129,222, 48,208, 27, 6,250, 83, 79,243,223,205,143, 48, 12, 31,123,211,173, 39, 31,187, 51, 29,229,117,219,174, 55,187, 95,255,242,215,214,155,237,255,143, 6,202,179,244,124, 54,189, 56, 63,123,234,137, 55,191,251,217,167,159,120,244,246,219,158,184, 19,135,237,126,187,219,108,182,251,237,126,183, 59, 28,246,135,191,254, 23, 63, 88,108,247,191,253,123, 47,253,151, 47,125,229,197,215,174,118,251,242,155,229,148, 27, 23,103,227, 81, 54,202,211,192,247,171,170, 46,118,123,124,243,114, 93,224,235,255,151, 12, 4,187,124,223, 7,223,245,253, 31,249,192, 99,111,190,243,166,187,119,110,223, 60,143,163,160,220,109,118,219, 85,177, 90,227,125,138,205,118,183, 61,236,247,135,114,127, 44,203,227,177,170,155,170,126,252,198,249, 79,124,252,251, 94,186, 63,255,181,175,124,253,127,126,237, 27,175,187,230, 95,249,193, 63,255,161,247,189,227,177, 55,221, 56,159,230, 73, 28,181, 77, 83, 29,235,117,177, 91,172, 54, 47,191,114,245,210,189, 7, 95,249,218, 11, 95,253,221, 23, 30,204, 87,255, 87, 27,232,153,183,191,229, 51,127,235,175,125,226, 7, 62,220,212,109, 16,133, 88,243,182,169,171,227,110,179,188, 42,214,243, 98, 85,208,113,138,253,110, 91,150, 7, 90,166,174,234,250, 88,183, 94,211,182, 94, 24, 69,126,224, 61,245,232,237, 71, 31,185,249,129,103,222,246,239, 62,255,171,120,127, 92,243,199,126,228, 19,127,231,103, 62,153, 68, 77, 91,149, 53,127, 0,113,217, 52,117, 19, 4,193, 69, 28,206,206,198, 8, 88,252,241, 95,254,216,251,203, 99,253,234,189,235, 95,249,194,111,252,242, 23,126, 19,203,240, 29, 99, 67,168,197,190,241,141,111, 60,255,252,243,127,114,151,201,179,119, 63,247,103,254,238,207,253,244,187,158,125,135, 31,132,120,124, 60,189,215,122,117, 85, 30,182,203,205,242,181,205,114,181, 89, 21,219, 98, 7,199, 65, 76,193,103,176,254, 45, 95,180, 33, 23,107,253, 40, 14,226, 36,201,199, 89,156, 68,126, 27, 52, 94,189,221,150,191,242,235, 95,255,201, 31,255,145,183, 62,113,103,191,219, 52,199, 3,173,210,226,159, 70,246,169,249,195,252,192, 18,224,191,248, 69,133, 72,171,155, 99,137,187,150, 95,127,254,149, 95,250,175,191,241,213,175,191,120,239,106,137, 27,253,201,222,235,241,199, 31,127,242,201, 39,191, 93, 15,122,239,187,223,249,247,126,238,211,239,123,239,115,113,156,200,224, 94,208, 70,120,247, 35,144,102,125,127, 61,127,176,134,117,214,136,169,253, 97, 71,191,129,105,100, 23, 63,138,194, 40,142,162, 56, 12, 2, 88, 53,204,243, 36, 31,229,121,158, 38,105, 28,166,227,217,173, 55,127,236,135, 71,117,181, 63, 28,182, 52, 97, 24, 6,114,200,214,199, 15,215, 0, 36,124,225,251,117,128, 63,194,111,126,221, 10,134, 96, 34, 44, 0,150,225,124,148,255,240,135,223,243,145,231,158,254,218,239,191,252, 31,255,219,111, 46,190, 13,135,250,182, 12,244,243,127,255,103, 63,251,233,191,129, 8,193, 59,226,223, 62, 28,135,171,124, 44,119,235, 98,113,111, 5,235, 44, 54, 5, 29,103, 95,238, 17, 82, 71,172, 48,126, 10,102,129,117,146, 44,206,242, 52, 78, 98, 51, 22,190, 72,211, 56,205,210,124,118,251,252,214,163, 94,115,196, 85,128, 52,190,143,107,227,170, 32, 36,176, 6,126,222,167,165,252,186,241, 9,219, 48, 86, 75, 95,245, 16,122,135, 67, 89,172,119,197,122,187, 33,204,237, 15,251, 18, 97,252,200,116,250,169,143,127,232,151,254,199,111,127,249,247, 94,248,174, 26,232,217,119,190,253,159,255,211,127,244,206,103,222,142, 69,195,234,194,113, 66,149,192, 85,123, 60, 20,139,205,245,171, 75, 88, 7, 97,181, 65,166, 57,148, 7, 4, 85,133, 40, 64,232,193,107,100,136, 36,203, 96,146, 36,142, 35,152, 38,166, 43, 37, 48, 82,126,118,123,122,113,171, 62, 30,170,227,193,107, 97, 77, 88,131, 1, 18,132,180, 60, 12, 1,243,120,252, 99,242, 55,152, 5,127,214, 84, 13, 76,131, 27,225,118,171,197,198,221,148,214,169,202, 35,239,138,251,190,255,123,159,132, 5,191,250,252,203,223, 37, 3,253,236,103,126,242,179, 63,243,169,139,243, 25,188, 6,113,226,228,129,166,173,203,195,110,115,127,125,245,234,106, 49, 95,175, 54,187,205,158,169,170,172, 0, 19,198,128, 0, 49, 8, 34, 96, 13, 12, 4,171, 36, 73,156,192, 70, 48, 85, 58,242,195,124, 52,187,153,164, 89,117,220, 55, 53, 50,125, 75, 15,129, 57,218,128, 24, 2,207,129,171, 96, 33,104,157,150, 98, 4, 92, 8,217,239,120,220,237, 15,155,213,118,185,216,172, 22,200,145, 64, 58,220, 20,177,140, 80,174, 43,186, 51,191, 25, 63,244,158,183, 61,185, 40,182,175, 94, 45,254,116, 13,148,166,201,191,250, 23,191,240, 67,127,233, 47,104, 89,125,122,142, 62,144,172,170,227,118,187,122,109,117,245,202,106,190, 4,232, 0,146,177,176, 21,173,131,199,243,195,136,190, 3, 56,159, 76,243,108, 68,243, 36, 89,154,102,121,156,141,227,116, 20,132, 89, 50, 58, 67,224, 85, 10, 43,193,106, 64,248,198, 63,176, 19,239,226, 43,196,148,240,188, 0,183,195, 39,156, 4,230,216, 44, 55, 88,142,229,124,189, 89, 22,224, 83, 92, 17,165,199,134, 87,193, 19,114, 97,112, 29, 92,226, 19,239,125,246,243, 95,250,173,151,175,230,223,121, 3,221,184, 60,191,121, 49,185,115,231,238,167,127,250, 83, 31,251,254, 15,195,107,153,167,156,178,228,129,148, 84,135, 98,179,120,117,253,224,213,213,114, 41, 72, 62,208, 58,199,138,192, 20,250,244,157, 40,202,242,100, 52, 1, 12,103,249, 40,203, 70,227, 52,159,154,117,144,196,194, 56,133, 67, 85,135, 29, 46, 69, 72,198,123, 33,149, 53,180, 9, 96,217,107,144,217,240, 21,128,136,192,211, 34, 90,224,102,251, 61,224,102,181, 88, 47,230,171,229,124,131,175, 11, 46, 9,130, 19,182, 33,210, 1,252, 1,111,248,185, 40, 12,240, 53, 96, 14,127,248, 3,239,121,230,115,191,250,107, 8,193,239,152,129, 62,242,103,223,243,163, 63,248,161, 59,151,147,155,183,239,190,229,153,247,229,163, 9,110,143,172,163,124,197, 95,120,216,114,183,218,204, 95, 93, 49,178, 64,117, 68,111,247, 71, 17, 22, 47,208,147, 49,148, 0, 58, 8,174, 60, 29,141,179,209,116,150,142,207, 97,160, 40, 25, 85,117, 11, 92,198, 91, 87,229,190,105,204,119,112, 85,251,205,135,121,153, 21,145,178,232, 3,248, 79, 68, 75,117, 44, 15,224,224,155,213, 6, 94,179,184, 94, 1,119,108, 73,140, 63,112, 73,240, 86, 92,146,192,178, 65,108,255, 17,112,157, 38,103,227,143,127,240,185,255,240,159,191,248, 29, 48,208, 7,222,251,220, 63,249,249,207,222,158, 37,219,245,210,143, 71,143, 63,253,190, 40,201, 8,198, 97,216,139,146, 88,201,195,118, 81, 92,191,188,188, 70,206, 90, 43,254, 1, 0,204,228,248, 91, 60, 19,208, 23, 40,147,230, 9, 98, 51,203,210,209,100, 4,235,100,147,139, 36,131,251,140,142,199, 6,129, 38,235, 28,228, 59,142,154, 17,127, 12,132, 60,139, 49,216,168, 38,148,240,126,187,253,118,187,166,117, 86,243, 43, 88,103,141, 37,217,110,233,175, 10, 43,162,122, 12,131,128, 42,224,142, 57,147,128,101, 6,192, 31,140, 21, 70,225,173,219, 23,143,189,233,246,191,254,247,191,120,252,214, 10,148, 63,196, 64, 31,124,255,187, 62,243, 83,127,245,131,239,250,222,221,250,106,189,184, 74, 39, 55, 31,125,219,187,163, 36,241, 90,247,252, 66, 29, 60, 46,173,179,185,122,105,121,117,111,189, 68, 58,223,130,233, 16, 0, 0, 58, 0,239, 16,190, 19,165,114, 28,251,119, 54, 26,141, 38,103,233,248, 34, 29,157,133,113, 14,223, 65, 98, 7,221, 62,194,119,234,202, 57,141,231,157,178, 58,186,143,199,171,121, 92,140,178, 58,108,119,197, 6, 72,188,112,214,161,239, 40, 97,225,101, 97, 65, 56, 14,188, 6,214, 97,162, 28, 41, 21,224, 25,152, 40, 83,102,130,208,130, 45, 8,110,223,189,241,244,211,143,125,238,243, 95,248,253,151, 31,236, 15, 21,172,121,235,198,236,114, 54, 46, 15,213,107, 87,243, 23, 94,190, 63, 95, 21,230, 1,175, 55, 16,172,254,207,126,225, 31,254,185, 15,189, 39,108,246,197,234,126,185,223,141, 47,238,222,121,234,157,113,156,182,114, 93,123,108,174,101, 93,238,139,197,250,234,197,213,213,189,213,114, 99,153,245, 88, 30, 27,241, 18,159,214,177, 53,100,206, 2,240,228, 99, 96, 51, 35, 11,153, 60, 74,114,144,162, 44,203, 61, 6,204, 30,175,238,117, 62,211, 23,166,250,186,109,237, 55,143,174, 10,223, 1,204,224, 94,243, 43, 64,178,112, 7, 53,221, 78,113, 37, 86, 20,134,114, 88,101, 69,228, 1,221, 29, 84, 11, 41, 50,230, 39,211,102, 28,198,138,184, 40,186,251,230, 71,158,121,246, 29,135, 38,160,215, 85,251,200, 71,136,151,160, 8,128,208,251, 15,230, 95,250,173,223,253,220,127,250, 98,211, 27,200, 76,245,150,239,121,226,223,254,155,127,121,235, 98,180, 93, 61,216,239,214,112,251, 36,159,221,125,234, 89,120, 39,161, 64,132,132, 15,222,240,113, 97,157,205,213,139,203, 7,180,206,174,232,172, 35, 24,149, 75,135,198,250, 70,227,156,192, 60,154,128, 27,103,180, 14,112, 39, 67, 12, 2,168,125,193, 9,125, 71,150,248,230,178, 56, 80,238,128, 36, 0, 5, 96,189, 88,195,113,240, 9, 0,146,117,228, 58, 6,201, 97,144,138,106, 50, 21,140, 50, 48, 44,184,207,120, 50,202, 71,164,230,248,115, 89, 8,230,131,253,114, 96,159,143, 90, 49, 64,245, 7,255,221, 22,171,106,189, 68,133,136,210,249, 8,143, 62, 63,155,126,244,125,207, 60,247,214,199,127,241,139,255, 27,150, 65, 89,208,194,180, 63,254,201, 31,253,199,255,224,111,135, 94, 89, 44, 95,171,246, 5,220, 62,206,103,119,190, 71,145, 69,159,233,130, 11,172,181, 22, 21,188,122,105,241,224,181,181, 89,103,135,231,148,117, 68,119,163,126, 25,129,199, 48,208,120, 10,208, 97,100,229,211, 32, 74, 16, 15, 64, 35, 92,169, 58,158,226,206,195,161, 53,184, 83, 35,223, 1,105,216,172,150,171,235,171,229,252,106, 41,118, 14,152,166, 14,192,170, 69, 28, 34,227,139,211, 97, 25, 89, 8,106,134,216,200,162, 44,165,229,146,132, 43,150,199,233, 24,241,198,199, 4,146,250, 30,174,124,216,174,247,197,174,180,156,171, 87,128,229,218, 56,188,152, 77,223,253,142,167,190,242,226,156, 6,250,169,191,249,201,159,248,177, 31, 42,119,203, 98,125,141,183, 71,180,167,227,203, 71,158,124,214,112,199,183, 39,246, 29, 74,210,119,174,133, 59, 43, 67,101, 90,167, 53,235, 16, 2, 24,240,185,156, 92,238, 51,205,166, 23,217,248, 50,205,129, 59, 41,190,155,145, 5,246, 91,238,113, 49, 49,184,182,251,244, 92, 60,117,159,128, 29, 90,135,234,209, 26,249,113,113,181, 90, 92, 47, 1, 64,172, 93,118,196,100,171,233,128, 42,120,119,229, 71,122, 43,205, 4, 82, 37,223,129, 11,167, 50, 13,158, 38,201, 38, 17, 9, 87,172,236, 1, 2, 23, 0,209, 14,197,114, 95,108,128,240,181, 49, 18,164, 3,192, 20,147,101,228, 39, 12,133,214, 66,236,108,154, 31,119,203,253,250,186, 42,183,136,159, 40,153,222,122,226,157, 8, 92,161,164,103, 44, 75, 34, 3, 44,190, 44,174, 95,113,214,217,236, 80,239,192,240,102, 29,100, 55, 68, 86, 34, 56, 20,211,201, 70,147, 73, 54,189,204, 39,151,196, 29, 88,103,183,195,179,226, 74,204, 89, 53,126,170,113,193,213,246, 46,100, 81,239,137,252, 34,233,195, 58,197,142, 26, 18, 76, 99,168, 92, 88,100,117,214,129, 31, 4,240, 86, 20,186,227, 73, 62,153,141, 65,178, 24, 89,211, 28, 81, 6,235, 88,238,140,147, 49, 50,102, 20,231, 65, 24,153,117, 0, 87,120,211,195,118,142,139,131, 28,144, 86,182,150, 45,125, 26, 37,244, 66,189,144, 47,174, 71, 3,209,150,219,165, 56,126, 21, 38,147,219, 79, 62,155, 18, 65, 21, 90,173,208, 71,206,163, 18,244,149,229,245,171,178, 14,234,108,137, 93, 53, 37, 11,184, 44, 17,144,214, 73,115,250, 78,150, 79,206,114, 68, 22, 50,122, 62, 13,157,117, 18,220, 30, 87, 1,248,136,229,122,170, 65, 91, 67,192,182,143, 44,211, 65,106,128, 26,172, 3,151,129,105, 8, 61,203,229,230,117,190, 99, 37, 46,173, 51,206,167,179,201,104,146,225,238,176, 20,130, 11,196,130, 32,148,142,226,108,130, 80, 71,104,227,237,197,111,241,214, 97, 5,145,160, 88,128, 74,217, 2, 91,218, 13, 12,103, 67,122,132, 44,212, 90, 95,140, 6, 98, 6, 61, 30,240, 88, 81, 50,129,239,164,217,216,220,198,111,221, 63, 72, 90,199,253,166, 16, 27,132, 38,104, 57,171, 50, 8, 16, 91,141,157,239,164, 46,178,166,192,157, 27,153,203, 89, 25, 0, 16, 22,199,183,177,146,112,190,211, 14, 38,241,205, 74,184,145,217,139,114,161, 34,107,181, 2,224, 0,149,175,151,248, 98,187, 38,216,153,117, 2, 98, 72,144,101, 14,116, 64,255,198,204,146,172, 99,112,247, 76,245,158, 98,106, 12,162, 17, 70, 41,193,172, 58,242,103,130, 8, 97, 0,160,221,111, 22,208, 52,101,157,218, 30,132,100, 11,238,213,202, 84,248,213,212,182,106,202, 98, 32, 17, 77, 5, 51, 95, 62,250, 52,172, 99, 70,241, 29,242,248,124,222,195,134,242,197,245, 43,235,197, 74,214, 57,234,210, 39,168,172,156,133, 71, 68, 82, 7,238,228,176, 14,125,135,214, 41,247,123, 68, 31, 98, 27,184, 3, 80,145,195,180, 70, 26,244,239,150, 85,187, 96, 71,133, 37, 3,185,130,239,108, 25, 89,203,235,245,252,122, 69, 84, 70,221,123, 56, 40,161, 55,146,143,104,157,145,146,192,100, 58, 34,244, 16,119,178, 9,160,103,140, 34,102,194,116, 73,235,228,161, 64,167, 62,150,248,153, 48, 76, 42,214,211,203,237,102,126,216,237,142,164,108,142, 43,194, 38,181,121,132, 62,240, 52, 66,200,129, 7,177,100, 58,191,243,182,241,228,156,174,211,170, 60, 84, 88, 42,180,182,197,242, 62,171,208, 5, 16, 18,214, 57, 28, 75,167,236,152,159, 3, 5,224,206,174,140,152,156,101,211, 27,140,172, 17, 50,122, 14,214,139,235,224,161, 89, 73,212, 71,175, 29,124,167,195,100,131, 56,251,115,151,179,192,193, 32, 66,162,146,128,117, 64, 35, 54,240,157, 45,110, 74,126, 30,240,142, 64,101, 90, 7,166, 25, 79,199,136, 41,221, 29, 48,132,219,143,210,209, 52, 29,205, 34, 84,121,113,142,165, 35, 99,171, 42,154, 52,138,185,210,219,213,158,214,217,150, 18,167,104, 2, 91, 42,169, 75,190,233, 7, 16, 81,160, 76, 82,161,169,125,231, 65,158,127,113,247,233,241,217,101,171,146,199,119,139,235,123, 2,158,237,242,106,115,245,242,122,177, 0,169, 63,128,152,185, 2,157, 37, 37, 81,217,177, 15,248, 78,142,213,204, 38,151,153,234,172, 56, 25,193,135,225, 32, 88, 86,160,114,205, 76, 87, 11,110, 20,222,142,123, 9,139, 72, 60,219,214,249,206,142, 42,237,106,173, 58,107, 77,130,190, 70, 9,122, 80,145, 69,176, 51, 84,206,196,113, 38,103, 19, 56,107, 34, 58, 58,134, 31,201, 58,113,126,198, 92,158, 40, 97, 53,181, 34, 11,232,156,146,248,163,113,176,185,222,111, 55,230, 59, 78,138,213,251,234, 23,255, 45,180,109, 17, 31,148,177,202,163,243,160,241,249, 35,147,179,203,198,148, 5,135,203,180, 14,194,117,183,185,218,204, 95,130,175,163, 92, 70, 57,136, 71, 85,208,182,157,239, 32,134,152,179, 88,163, 51,145, 92,144,242,140,206, 96, 29,124, 27,156, 97, 50, 61,135, 74,140,172, 14, 55, 23,206,156,162,114, 43, 39,149,100, 35,231,145,117,160,122, 1,123, 54,107,168,130, 5,232, 15, 3,171,132, 90, 79, 41, 17, 25,221, 79, 8,190, 49, 2,153,119,131,114, 66,202, 67,235,192,149,192, 36,146, 92,184,147,228,242, 23,122, 12,124, 39, 82, 25, 0,148,216,211, 58,107,176, 83, 70,122,227,248,150,189,175,162,204,171,100, 29, 36, 79,148,190,122, 95, 54,160,144,249, 60,114, 39, 89,207, 50,151,138,103, 94, 29,222,184,185,126, 5,252, 12,223,189,103, 15, 75,214,129, 0,161,202, 88,192,156, 8, 41, 17, 89,227, 92,108, 80, 92, 57,199,133,138,245,114,122,118,142,215, 6, 15, 86,169,213,120, 39,214,161, 19,137, 5, 89,157,229,172,179, 3,252,175,182,197,182,210,210,137,173,152,167, 49, 55, 91,233, 43, 14,145,142, 8,118,180, 14, 51,230, 4, 75, 51,237,228,129, 92,214, 73, 90, 89, 7,151, 96,129,237,121,120, 19, 89,103,121, 60, 28, 42, 43,165, 31, 38,166,188, 17,244, 21, 10, 55, 53,242, 15,186, 47,203,101,177,239, 61,168,227,105,173, 30,136,223,219, 24, 33,156, 67,253,122, 32,245, 11, 57,189,116,214, 17, 55,139,229, 59,150,212,243, 9,242,199,185, 30,145,117, 22,254,126,113,117,111,118,121,147, 21,230,241, 64, 32, 52, 47, 49,151,233,190, 16,216,233,237, 97, 68, 20, 66,176,206,154,106, 9, 30, 63, 35, 27, 38,196,224,226,175,190,116,191, 93, 54, 38,215, 26,227,115,229,139,152, 33,124, 7,230, 73, 71,231,112, 91,164,243, 48, 17,217, 65,135, 3,154,164, 31,144,202,249, 1,233,242,102,142,215,129, 76, 82, 75, 72,243, 78, 98,203,240, 86, 41,130,171, 9,132,133, 55,128,142,206, 87, 91,228, 76,216, 39, 58,225,250,170, 17,185,158, 71,178,234,197,171,171,235,215, 80,245,236, 10, 74,152,104, 96, 53,117, 99, 92,115, 40, 38,152, 79,241,136,168,179, 16, 89, 92, 64, 60, 95,177, 94, 76,102, 23,184, 88,109,197,132,146, 65,235,254,209, 82,181,102,169,214, 96, 25,172,164,220,211,119, 32,182, 31, 15, 71, 22,150, 25, 25,211,244,108,116,126, 57,187,184, 57,123,233,249,251,215,247,175,241,237, 70, 65,199, 19,198,151,106,224,148, 89, 93,100, 2,124, 7,149, 68, 16, 38, 13, 81, 25,122,182, 7,235,224, 97,224,152,101, 49,135,234,112, 60,236,141,151,116,244,130,177,101,202,182,173, 23, 94,208,105,219,176,206,178, 88, 34,182,101,188,222, 64,173,149,208, 52,207,190, 64, 69,182,190,190,103,214, 49,173,165,105, 36, 94,169, 16, 77, 76,117,167, 54,152,103,227,153, 69,150,202,156,100, 91,172,193, 81, 36,158, 34,178, 58, 96,150, 91,118, 46,227, 66,204,150, 2,240,132,219,209, 58, 75,116, 36,246,186, 56, 90,167,145,173, 47,248,221,157,252,214,229,141,243,171, 7,203, 87, 94,124, 13,104, 52,102, 64,141,232, 68, 36,235, 35, 58,206,104, 6,117,201,214, 70, 18, 85, 41, 66,151,193, 88,176,148,138,137,121,185,223, 74,105,104,220, 98,245,241,213,118,194, 86,221, 0,146,241, 0, 72, 11, 80,140,231, 72,155,176,166, 31,203, 64,254,240,125,138,137, 98,183,186,191,185,190,183,152, 47,119, 42,181,104,120,113, 30,103,157, 36,238,244,157,140,105, 11,145, 53,162,117, 16,238, 72,159, 88,168,179,139,155, 36,229, 85,137,197,244,218,190,176,114, 46, 99,126,163,123, 73, 86, 62, 32,179,160,185,200,224,194, 31,193, 35,112,113, 36,101,223, 8,168,214,153,114,109,150,222,188, 57,187,247,218,117,177,218, 58, 9,101,140,212,117,134, 38,145, 8, 33,172, 19, 75, 51,194,170,212,108,144, 68, 9,175,190, 71, 33,138,164,142,218,187,108,154,193, 54,142,176, 27,147, 33, 11, 68,200,128,153, 30, 16,226,139,197,102,177, 65,177, 94, 85,157,242, 21, 13,132, 4,223,137,204,188, 6, 57, 3, 93, 94, 50,103, 73,109,145, 80,231,196, 83,212,253,166, 13, 2, 3, 70, 20, 49, 24,252,113, 58, 65, 49, 81, 83,181, 95,159, 95, 62,130,167,172, 89,220,171, 22,237,128,185, 39,202, 14,166,141, 46,131,242,200,119,214,107,174,240,244, 28,169,123,132, 91,248,210,181,168, 76,119, 63, 16,212, 53,132,156,199,243,116, 45, 99,226,217,181, 68, 84,181,229, 59,177, 53,114, 89, 42, 81, 61, 68,150,168,149,182,230,128,182, 74, 56,200,224,242, 26,215, 98, 24,132, 63, 99, 2,213,193,128, 25,214, 89,109, 87,240,165,166,211,167,250, 16, 51,228,217, 67, 63, 93,188,130, 46, 1,165,229, 45,213,150, 70,124, 65,245, 29, 48, 47, 86,183, 79,121, 29,245,206,248, 28, 26, 24,130,223,164, 88,132,201,217,249, 37,132,180,154, 42,207,209,172,211, 99,179,111, 1,230,224, 72,236,141,229, 34, 82,250, 26, 73, 29,207, 7,162,112, 54,155,162, 0,167,120,161,170,209,115,124,140,198,100, 63,140, 21, 70,120,126, 35,194,221, 81,151, 61,184, 63,207,167, 55, 89,100, 73, 32,135, 19,136,242,192,123,240, 48,173, 18,245,162,220, 46,203,114,175,150, 92,115,170,162,248,157, 64, 39, 56, 7,244, 28,241,190,228,165,120,123,184, 5, 29, 66,101,199, 48,163, 72,243,148,208,222, 9,204,139,249,198,186,125, 72, 91, 29,244, 40,169,199, 29, 48, 35,248,115, 69,214, 12,190, 99,105, 11,201, 14,169,133, 15, 10, 96,174,122,235,180,198, 29,204, 66,109, 87,154,194,121,106, 96, 39, 41, 15,204,179,198,189, 96,253,217,197, 20,132, 27,161,129,119, 12, 56,200, 0, 51,133, 44,169,105,172, 80, 50, 4, 9, 31,254, 22, 34,193, 35,119,110,197,145,255, 59, 95,254,242,122,254, 26,189,181, 34,213, 98, 82,143, 97, 29, 31,221, 17, 88, 7,159,160,113,181,137, 13, 39, 34,138,223,251, 78,195,180, 5,245, 14, 82, 25,212, 91, 4,215, 28, 74, 65,197,202,149, 4, 58,224,103, 23, 98, 4,230,237,118,201, 86, 58,102, 48,216,180, 41,143,131,224, 18,245, 58, 70,170,206, 4,129, 25,109, 44, 82,158,108,132, 85,197,228, 70, 2,215,138, 19, 54,139,225, 59, 72, 12,205, 9, 39,108,219, 62,208,124,165, 45, 38,245,253, 6, 21, 4,235, 94,140,112,180, 30,124,103, 50, 59,131,117,112, 53, 19, 29,204,241,212, 34, 84,114, 69,207,144,207,194, 88,103,179, 36, 76,110,220, 26,197,209,252,127,253,247, 47, 62,254,150,167,238, 62,246, 86,196, 26,194, 28,126,142,139,131,139, 35, 20,112, 11, 42,150, 54,225,224, 13,185,157, 43, 68,213, 24,128,213,224, 37, 9, 61,232,172, 65,171, 68, 34,197,127,243,234,232, 18,251, 25,138, 71,172, 80,237, 69,190,170,249,221,234,193,102,126, 15, 44,118,187, 83, 95,178,180, 74, 93,181,104,223, 56,207, 99,210, 15, 64,227,200,160, 7,116, 62, 2, 4,226,149, 0,174, 6,204, 76, 91, 77,231, 59, 39,233,220,145,102, 70, 60, 58,209, 5,114, 41, 39,133, 54, 48,104,139, 90, 28,233, 28, 38,198, 82, 16,119,124, 85,202,180,166,111, 34,150, 73, 35,158,239, 94, 49,176,162, 41,140,111,220,121, 51, 20,159,235,251, 47,207,206, 47, 46, 39, 23,240, 59, 60,192, 97,183, 34,229,217,109,142,142,184, 53, 86, 64,184,232,234, 30,137, 15,130,110,222,174, 4,203, 67, 77,131,224, 90,130, 23,146,175,195, 62, 62, 22,106, 18,199, 59, 24,170,110,232, 65, 71,182,253,144,212,193, 8, 57,131, 1,174,109,124, 65,218, 59,187, 2,148, 86,128,137,248, 0, 48, 35,173,230, 19, 20, 19,136,127,220, 4, 74,250,236,226, 6,249, 59,151,171,234,173,195,216,244, 6,211,152,140,129,149, 48, 96, 70,108, 97, 32, 6, 47, 0, 90,124,113, 99,134,203,154,117, 2,233, 13, 14, 30,157,117,100, 41,169,106, 98,117, 86, 86, 50,220, 80, 0, 92, 60,242,104, 62,197,130, 77,225, 59, 86,109, 17,122,118, 43,213,198, 77,211, 56,215,245, 78,186, 2,182,100,180,206,225, 72, 96, 38,244, 48,175,239, 5, 84,161,172, 51,142,163, 73,150, 96, 8,201, 59,148, 52, 16, 29,126,185,112,149, 58,210, 86,213,116,192,204,110,186, 99, 61,136, 47, 40, 9,116, 31,112, 86,166, 45,188, 47,116,208,217,249, 77,216, 69, 73,157, 66,143, 61,141,179,206, 73,106,151,121, 74, 64,207,126,203, 66, 11,100, 12,229, 52, 16, 13,190, 51, 57,155, 1, 60,124, 41,125, 22, 80,141,201, 32,126,199, 44,101,103,223,100, 95, 87,115, 83, 17, 98,240, 7,241,228, 66,237, 89,213,213, 40, 38, 0,109,160, 26, 53,129,185,126,152,239,180, 77, 23,246,149, 65, 15,248, 12, 76,115,189,190,222,108,145,215,107,121, 25, 34,124, 20,133, 83, 8,111,227,124,119,128,197, 74, 68,187,143,176,229,236, 23,146, 58,245,199,202, 42,121,138,132, 81,216,151, 20, 96,101, 25,173, 51, 99,180, 75,141, 69,239,110,122, 6,198, 76,181,165, 22, 39,236, 30,166,179,142,119, 66,124,216,188,135,123,174,139, 53, 4,230, 13, 80, 40, 73,163,179,243,233,116, 54,195, 61,104, 28,207,102,254,173, 16,238, 67,193, 9,178, 38,238, 25,133, 17, 65, 34,114, 19,171,144,181, 82, 22, 95, 88, 33,152,166,100,181,181, 21,201,104, 92, 76,182,131,141, 36,243,180, 26,178, 58,226,101,217, 95,131,117,176, 94, 16, 11,172, 31,235,251,121, 20, 78,146, 24, 28,107, 74,157, 32,118, 89,172, 36, 77, 98,191,184,170,106, 19, 67,201,134, 57,245,101,172, 39, 81,112, 77,209, 5, 82, 82,103,218, 66,175, 4, 84, 31, 15,169,180, 85, 26, 99, 86,162, 18, 93, 62,161, 63,124, 40, 9, 3,100,204,107,170, 95, 0,230, 40,137,102,179,233,217, 12, 64,198,171,105,170,197,239,106, 0,171,122, 44, 31, 55,206,147,218,174,121, 96,226, 68, 40,162, 20, 48,202, 80,127,225,190, 48, 61,235,137, 61, 6, 58,143, 67,104,157, 84,126,157, 88, 41,181,114,223, 67,207,122,129, 34, 92, 36, 0,208,150,160, 55,141,224, 66, 25, 72,169, 0,162,127,210,154,129,196,148, 36, 16,233,210, 38, 74,169,107,172,158,186,148, 94,164,173, 84,148, 7, 97, 7,190,132, 85,194,223,213,156, 51, 60, 54,131,243, 10, 87, 95,103, 29, 72,208,132, 30, 52,182,144,212,169,186,227,213,102,231,103,103,231,200,131, 35,165, 45,223,169,187, 3,247,247, 59,220,240,173, 78, 49,159,234, 52, 45,246, 36,204, 58, 8, 46,118,144,202, 45, 41, 15, 8,240,241,208,116, 66, 79, 39,255,123,141, 17, 67,179,142,130, 11, 5,215,114,177,190,158,175,174,139,253,182,170,173,146,134,106, 61,137,195, 41,146,208,132,117, 50, 82, 71,231, 65, 62, 39,215, 52,254,197,238,173, 73, 25, 42, 71,147,180, 11, 46, 40, 9,160,173,104,155, 64,121, 34,255,221,172, 38,148, 50, 80,221,116, 82,134, 91, 99, 91,179, 83,235,176, 61,136, 23, 0,244, 20,152,134,222, 98, 46,179,157, 93,158,161,209,139,235, 34,136, 25, 46,190,129,175,111,250,171,141, 41, 12, 20,161,163, 9, 54, 4, 67, 43, 9,159, 97,154, 56,159,170, 88, 7,235, 89, 30,217,233,220,155,117,134,224,182,120,151,185,155, 70,121,189, 20,235, 89,110,174,175, 80, 49,108, 55,229,177,182,246, 41,130,139,192, 12,232,161,251,140,207,160, 27,143, 96,127,171,103,157, 14, 98,109, 51, 74, 25,131,239,160, 92,206, 69,121,206,216, 84,130,206,210, 54,235,229, 53,164, 12, 75, 73, 2,172,198,108,225,183,167,117, 86,247,133,160, 7, 53,114,177,134,252,133, 94, 88, 59, 6,227,185, 56, 67,122, 54,198, 60,180, 12, 91,142, 31,118, 13, 38,172,122, 31,170,158, 69,153, 41,126,228,139, 32,173,217, 20, 53, 42,236,107, 10, 36,210, 22,104,110, 7, 61,222, 0, 60,157,246,164, 20, 81,155, 78,184, 94,109,217, 68, 90,172, 87,123, 86,104,102,157, 12,192,156,198, 19, 74, 5,244,157,201,148, 93, 0,216,193, 17, 69,205,140,118,109, 51,208,194,132,238,147, 41,181, 35,163,219, 32, 79, 24,103,228,132,171, 5, 74, 48, 43,106, 7,198,236,169,146,240,154, 46,236,251,196, 5,243, 32, 91,160,115, 15, 66,184, 69,222, 5,207,156,206,198,128, 53,145,227,192, 32,151,239,222,139, 52,182, 74, 29,231, 53,217, 92,228, 39, 16, 56,131,195,129, 45,143,145, 73, 1,207,198, 9, 29, 48, 31,157,117, 6,219,116, 0,164,185,216,150,156,112, 95, 22,204,235,171, 57,244, 92,232,133,108,233, 35,113,122, 41,164,149, 36, 6,244, 48,184,232, 59, 48, 16,229,148, 88, 90, 80, 96,225,233,250, 19,166,162,170,177,205, 6, 46, 88,138,164, 22, 60, 20, 44, 7, 53, 23,114, 45,114,254, 73,218,106, 93,206,242, 6,151,246,108,100,206, 20,120,116,254,182, 80, 79,119,200, 29,214, 44, 7,155,242,187,156,213, 77,186,116,239,226,128,120,144, 65, 77,204, 50, 6, 45, 14, 73,231,129,186,130, 72,103, 23,115,183,102,230, 58, 20, 98,204,245, 67,138,110,123, 82,131,183,146,228, 14, 21, 2, 28,173, 71,230,117,146,102, 6, 23, 72, 87, 18,248,163, 36,158, 82,243,207,100, 26,120,208, 72,189, 35, 54,248, 41,102,186,220,160,142,154,230,104, 96, 1, 18, 31,149, 21,103,150,182, 16, 92,176, 8,160,103, 10,233,186,150,198,204,230, 31, 69, 74, 23, 8,162,243,230,203,110, 94,145, 10,252,150, 3,246, 5, 11, 34,246, 63, 71,185,245, 14,125, 35,195,138, 27,206,143,117,100, 14, 67,171,157,161, 58,197, 40,160,188,107,242,171,117, 38,160,204, 97,212,147,156,106,183, 33, 48,179, 88,223,215, 39,208,211,181, 2, 58,243, 88, 94,103,112,237,169,132, 93,175,174,209, 19, 64,169, 96, 45,157, 32,200,227,240, 44, 75, 38, 99, 84,120, 35, 72,116,211, 51,182, 73,164,168, 48,104, 92,136,249, 6, 61, 73,152,136, 52,107,120,144,211, 78,146,193, 8,204,184, 35,152,228,249,141, 91,220, 1,112,148,148,209, 52, 29, 9,116, 3, 97, 78, 24,243,251,114, 20, 59, 13,144,209, 33, 41,161, 39, 21,224,178, 16,121,130,174,131,224,178,185, 27,169, 49, 12,118,178,108,219, 49,187,174,222,240, 88,175, 19,124, 32, 58,157,199,163, 51,181,130, 11,165, 45, 89,167,170, 7, 14,216,233,150, 94, 39, 35,168,131,141, 28, 77, 33,149, 93, 54, 5,215,129, 19, 33, 45,161, 39, 12,166,105,194,118,145, 5, 23,172, 35,157,151, 77, 8,206, 76, 38, 46,196,124, 6, 87,196,122,157,173,254,132, 93,237, 28,194,213,153,171, 0, 3, 31, 25, 26,234, 97,235, 52,151, 33,184,220,184,220, 73, 69,106,242, 28, 36, 33,230,117, 52, 38, 54, 28,156,232, 60,198, 18,145,111,163, 46,202,235,109,199,146,187,252, 71,191,114,165, 70,219, 58, 92, 86,222,130,223, 64,156,187, 8,217, 86,103,243, 3,190, 3,232, 65, 16, 75, 39,236, 20,176,174,154,232, 88, 15, 51, 23, 30, 0,204, 11, 90,207,124,206, 41,184,173,198,244,240, 68,105, 72, 78, 40, 96,206,153,185,240,201, 89, 20, 56, 15,115, 19,146, 0,210,136,243,160,128,238, 51,208, 66,142, 18,178, 82, 31, 19,122,162,184, 36,156, 85,192,174,106,224,132, 77, 15,197,214, 58,182,166,149, 1, 51, 36, 33,229,117,144,102,178, 30,188, 0, 34,215,207,125,255, 97,237, 18, 81,233,113,199, 66,219,118, 36,135, 1,219,201, 54,170,193, 52, 67, 46,235, 96,169, 32,176,128,115,163, 26,197,192, 10, 42, 82, 1,115,217,229,208,129, 94,244, 30,100,252,180, 52,169,112, 73, 90,120,141,233, 21, 20,154, 42,241, 98,229,117,178, 30,117,144, 40,227,118, 58,119,198, 81,144, 89, 44, 13,215, 25, 72,169, 93, 3, 52, 68, 31, 40,227,104,248, 79, 18,230,117,228,209, 3,166, 73,161,162,214,210, 92, 76, 39,236,178,175,115, 1, 39, 98,186,230, 31, 88, 33,146, 11, 77, 3, 90,136,176,199,223,224,202, 12, 73,140,228,184,142, 97,203, 77, 5,112,222,174,212,182, 8,243, 77, 74,119,198, 49,167,147,192,157, 96,193,102,145,160, 7, 58, 97,185,131,208, 83,168,145,109, 58, 97, 63, 17,210,133,171,179, 63,158,183, 54,169, 16, 35,123,215, 11, 12, 73, 57, 49, 12,177, 78,235, 32,184, 70,236, 86,115,222, 97, 34,145, 59,103, 87, 0,174,138,206, 9, 66, 39,144, 20, 23,145, 11,161,230,227,156, 26,131,171,107,251, 27,235,105, 49,185, 52,153, 1,152,143, 38,104, 90, 94, 63,233,139, 14, 13, 11,209,151,198, 5, 23,154,233, 43,125,174, 11, 84, 5, 59,172,204,190, 4,129,104,169,230, 52,226, 57,158, 52, 31, 95,188,221,245,185,109,146,193, 21, 99,129, 21, 92, 17, 69,124, 54,218, 71, 36,180,187,226, 80,172, 40,244,200,169,123, 18,208,246,109,171,238,195,145,102, 14, 82,239, 86,243, 13,161,103,131,110, 60,169,112,200,224, 10, 16, 92, 83, 65, 15,219,106, 99,151,182, 72,107, 82, 58, 7, 38,102, 66, 14,132,132,110, 62, 40,212, 60, 33,220, 71, 83,125, 18,122, 9, 61, 1,172,163, 57,152,198, 88, 79, 39,194,187,161, 3, 87, 33,123, 61,115,198, 67, 97, 86,110,199, 38, 5,194,107,201, 93, 1, 72,240, 28,112,202,232,151,220,177, 50,242, 57,153,129,235,248,166,163,134,190,117,218,204, 95,156,231, 4,238, 51,228, 52, 97,146,162, 88, 31, 11,122, 14,204,235,251, 21,117, 66,181, 46, 28,221,106,134,181,242,187,135, 2,114, 99, 98,122,135,204,181, 18,244, 44, 10, 84,164, 71, 78,231,251,177,180,158, 73,110,164,153, 57, 43,151,251,228, 28, 41, 66,112,141, 89, 48,176,101, 20, 15,243, 65,184,189,226, 11,223, 49,233,102,141,216,162, 0,145, 25, 81, 9, 59, 56,214,211,113,194,161, 88,183,217, 3,199, 10,143,170,215, 17, 92,168,216, 11,149, 93,220,255, 4, 79,200,182,251,116,157,152,104, 53, 26, 75,206,233,119,203, 18,134, 52, 12,221, 21,237,166,177,162, 78,199, 35,226, 65,229,203,177, 77, 99,163, 91,167, 50,176,236,242,250,195, 30,100, 35, 16,125, 94,135, 68,177,222,177, 34,157,111,168, 52, 27,105, 14, 60,214,235, 57, 50, 87,174,200,210,176, 14,200,217,152, 21, 21,176, 37, 76,115, 35,125,129,146,174, 51, 16,100, 21,230,175, 12,213,141,218,254,232,106,113,104, 97, 51,187,188, 37,197,247,200,205, 22,109, 59, 56, 78, 95,112, 25, 96,168,226,114,245,186,115,159, 66,227,203, 84, 8,144,133, 80,254, 96, 1,112,141,138, 31, 53,233, 34, 8, 81, 20, 5, 61, 75,246,180,247, 64,110,131,176, 50,149,151, 51, 89,137, 35, 25, 16,111,152,182,246, 69,205,188, 94, 13, 67,123,237, 16,225, 78, 42,100,112, 65,251, 64,139, 5, 58,252,134, 6,194,147, 48,115, 65,235, 1,105, 14, 39,132,158, 84,192,156,107,132, 50,211,108,129,141, 20, 77, 99,145,190,128,243,157,161,137,215, 46,196, 56,170,150,142, 34, 62, 16,146,191,143,146, 98, 58,187,108,213, 89, 71, 42,232,172,225,220,217, 27,252,185,117, 67, 61,168,215,153,185,182,116, 31,248, 14, 55, 6, 80,186,197, 78, 22,120,131,166, 30, 50, 76,216, 84, 44,136,240,130, 53,197,132,140,219, 15, 2,163, 68,161,109,198,160,117,216,123,131,126,198,230, 99,138,180, 5,163,213,116, 76,114, 66,104,222,206,119, 6,165,169,127, 28,151,215, 27,182, 0,161,115, 74,105,190, 94, 94, 35, 81, 64,123,229,220,140,135, 1,243,177, 35,205,163, 49,103,139, 8, 61, 57,123, 16, 25, 71,138,178, 51,206, 19, 65, 63,137, 6,235,152,129,176, 99, 7,252,144,211,106, 6,221, 24,143,102, 49,201, 22, 69,201, 17,128,102, 72,162,126,151,221,253, 94,102,177,204,133,177,173, 29,162,139, 93,109,206, 31, 20, 59,109,215,114, 35,104,218,122,194, 90, 17,172, 5,148, 31,243, 87,120,129,179, 25, 50,235,152, 35,168,177,242,168, 69, 22,173, 3,180,138,233,228,210,240,213, 7,135,239,200, 58,108, 67, 53,189, 72,121, 66, 53, 92,180,219, 96, 99, 73, 90, 88,152,150, 10,185,167, 84,125, 23, 57,169,144,243,122, 76,237,170,182, 88, 74, 49,121,225,183,137,104, 13,181, 55,186,176, 81,218, 19, 15, 66,253, 62, 50,214,131,215,197,155,158,157,223, 80,177, 46,214,211, 89,228,161,248,242,156,209, 26,237, 15, 40, 93,112,169, 44,213,158, 93,110, 72,168, 93, 35,188, 17,121,140, 90, 18, 88,196, 7,228, 77,232,193, 8,192,201,100,199,249, 48,113,179, 36,165, 60,238,115,211, 92,160,150, 20,192,212,205, 79,150,142,245, 28,156,138,218,115, 82,175, 79,237,180, 79,173, 1, 35, 54,185, 10,182,113, 32,104,204,241, 36,212, 27, 16,183, 30,234,245,137, 35,205, 57,103, 96,187,224, 82,242, 2,233, 67,230,202, 66, 11, 46,195,158,211,173, 8,154, 70, 32, 22,194,219, 23,243, 7,103, 23,151,106,237, 29,220,238, 18,147,153,251,250,230, 4,164,109, 6, 71,212,118,187, 69,209, 14,247, 89,247,214,233, 70, 65,244, 17,104,195, 15,150,178, 60,194, 88, 45,243,208,177,193,160, 23,122,112,156,211,208, 74,106, 20, 10, 37,206, 52,159,222, 32, 6, 5, 33,140,114,216, 35,115, 21,202,235,218,206,219,244,110,243, 58,233, 73, 12, 21,216, 92, 88,205,181,198,118,130,245, 65,230,177,224,138, 99,132,245,216,176,217,225, 14, 43, 42, 80, 30, 13, 62,140, 24, 61,131, 62,101,115,237,109,159,197, 98,149, 20, 17, 54, 52,226, 71,225,235,154, 99,174, 6,103,246, 7, 18,223,137,232, 39, 74, 51,177,103,135,204,181,217,112,231,174, 83,254, 53,163,167,141,169,156, 36,162,188,158, 68, 26,179, 69,223,135,214,195,175,189,155,199, 57, 98, 80, 42, 31,237, 81, 79,227,175,199,231, 48,216,121,196, 17, 44, 4,203, 70, 74, 24,218,121,176,107, 51,176,174, 97, 0,171,237,186, 56,128, 65,202, 61, 70, 11, 33,247, 44, 21, 92,248, 38,104,215,204, 92,110,166, 49,115,192,156,211,119, 20, 92, 26,187,136,160,148,218, 76, 64,208, 29,134,211, 14,123, 53, 12, 26, 85, 37,212, 40,107,197, 9,203,182, 99, 61,174,134,176,194,114,240, 40, 22, 58, 28,214,229,246, 27, 30, 20, 64,232, 89,243,172,128,242,224,172,163,118,126, 96,251, 39,236,147, 34, 65, 85,195,113, 56, 48, 82,169,238,199,198, 48,161, 10,190, 25,172,228,242,206, 99,211, 27,143,194, 58, 54,161,164,130,107,199,146,162,105,218,147,114,207, 33,168,205,196,121,141, 13,205, 81, 75, 45,246,204, 92, 48,144, 50, 23, 92, 78,180, 48,180,138,116,172,193, 34,231, 62, 35, 14, 95,176,127,197,230,112,134,213, 99,229,165, 29,130,126,199, 92,188, 19, 3, 81, 24, 70, 94, 71, 49,198,205,124, 52,144, 43,184,186,186,248,161, 40,147,153,208,214,198,206,173, 29,183,152,152,117, 56,226,205,189, 80,106, 27, 53, 18,141, 53,236, 32,241, 36,209,150, 0,240, 49, 68,115, 53,171, 48,145, 5, 63, 3, 55,240, 37, 96, 98,183,194,205, 91, 55,111,220,125, 98,114,113, 23, 9,149,123, 95,209,159, 3, 48, 83,235, 81, 73, 81, 15, 96,236,196,167, 70,202,172, 19, 52,106,229,117,106,169,172, 42,150, 91, 54, 42,148, 31, 72, 11,147,136,180,176, 47, 71,243, 46,184,148,215, 57,145,134,204, 21, 70, 54,208,198,206, 45, 85, 23,210, 58, 44,146,223, 23,171, 28, 16,169,107,100, 20,155,235,113, 50,179,128,185,199,102,127,152,131, 18,217, 96, 85, 65,178, 3, 62, 6, 15,226,182, 4,219, 63, 81, 27,244,104, 10, 77,211,238,169,141,189,231,250, 34, 79, 97, 35,140,159,113,144, 88,243,167,220, 38, 53, 61,199,134, 85,219,174,128, 37, 60, 30,183,202, 92, 27, 22, 92, 26, 61, 24,210,103,219, 15, 32,168,133, 34,235, 72,238, 97,163, 2,153,235, 26, 85, 5,182,177,106, 94, 39,242, 2, 5, 87, 58,233, 42,245,220,128, 25,238, 67, 35,161,130,201,217,134, 96, 87, 46,180, 77,160, 70, 25, 12, 91,153,193,157,228,218, 52, 72,206, 51, 86,164, 71, 89,174, 30, 70,116, 79,202,156,254, 25, 53,158,129,146, 29, 22,129,202,184,179,170,125,167,205, 98, 98,100,220,205,106,123,216,208,178, 79,181,121,194,170, 13,155, 72, 67, 78, 13, 69,184, 2,147,120,195,196,166, 30, 65,223,177, 86,156,213,129, 24, 70,247, 81,135,171,110,188,129,123,157,204, 60, 89, 14,165,117, 52, 25,102,130,198, 21,107,174,173, 78, 45, 8, 79,229, 30,251, 28, 25,244,176, 79,147,228,110,116, 38,236,104,161,117, 86,220, 75,226,198,100, 21, 7,103,160,253,174,152, 76,207,200,134,249, 64, 85, 55, 93, 57,168,187,254, 32,179,120, 54,188,162,252, 2,112,198, 94, 16, 4,151, 59,109,194, 88, 28, 39,195, 34,202,111,153, 27,241, 76,245, 41, 27,113, 38,108,166,190,254,216,178,134,237, 5,195, 88, 59, 18, 5, 98,210, 99,217, 87, 28, 8, 61, 5,133,221,170, 27, 60,111,250,180,213, 43,222,166,103, 88,163, 66,180, 16,193,133,113, 26,118, 1, 27,101,174, 96,156, 70, 19,101, 46,249, 78,238,124, 71,180,208,172, 3,254, 71, 77, 35, 8,252, 97, 42,207,246,208,236,141,151, 58, 3,161,144, 71, 16, 82,238,209, 92,143,189,100, 87,142,158, 70,150, 21,237, 44,140,180,113,116,191,149, 30, 15, 82,127,216, 15,251, 54, 56,202,172,174,145,219,167, 74,129,210,197, 23,158, 78,195,186, 54, 49,199, 25,248, 86, 84, 11,107,104,219,203, 57, 82,248, 80,112,245,106,247,144,187,250,204,110,109, 28,142, 93, 98,110,103,206,154,171,203, 92,190, 50, 23, 4,141,116, 34,185,135, 53, 23,172, 51, 78,181,253, 49, 87,189, 46,222, 23,147, 76,120,220,133,224, 59, 53,193,198,181, 53,247, 9, 0,233,106, 49, 48, 20, 81,221,150, 51,151,253,236,109,223, 51,113,225,165,241, 87, 87, 41, 51,188, 54,220,119, 44,232, 81, 77, 81, 53,221, 46,222,168, 59, 70,193,181, 70, 50,110, 75,178, 77,224,106, 61, 70, 98, 28, 62, 55, 57,212,140,115,106,241,100, 61, 32, 0,152,202,216, 43,175, 31,143,181,219,210,209,107, 42,174, 35,100,243, 30, 26,207,168,247, 26,187, 92,170,197, 14, 90,184, 85,103, 56, 96, 27, 39, 96, 27, 71,106, 6, 71,133,113,232,197, 72,197, 56, 59, 89, 34,205,162,133, 18,115, 59, 90,216,158,234, 89,216,113, 49,215, 32,185,239, 48,136, 82,161,141,133,245,145, 52,236, 55, 57,237,229,240, 2, 37,205,115, 40, 64, 9,121,148, 11,120, 16,231, 65, 90, 57, 54,234, 24,237, 17,141,156, 56,201,228,197, 22, 27, 81,154,143, 53, 98, 78,197, 55,161,254, 16,186,226,167, 44,214,180, 95,166, 0,244,148, 20, 82, 53,223,216,180,205, 32,118,247, 99,249, 78,227,144,220, 99,106,161,182,176, 46, 11,215, 98,103, 7, 57, 16, 45,204, 44,184, 24, 95, 35, 11,115, 88,103,108,109, 8, 8,242,108,204, 41,125,187, 17, 27,215,153,198, 69, 49, 54, 57, 71,155, 19,105,100, 24,160,162,160,209,214, 67, 59,169,215, 86, 6, 90,232, 38,132, 85, 88, 64, 50,132,166,186, 19, 45, 36, 54, 75,105,244, 68,152,137,205,148,182,115,203, 95,238, 51,209, 22,121, 13,159,194,119, 66, 75, 19,181,118,224, 48,184, 16,106,204, 92, 27, 23, 92, 44,222, 6,226,126,234,200, 67,143, 84, 93, 64, 40, 7, 8,174,235,197, 6,106, 97,169,220,194, 70, 69,196, 14,114, 71, 11, 69, 6, 69, 11,149, 38, 38,246, 24, 82, 11, 66,215, 80,234,238,212, 8,155, 49,124,133,154, 0, 47, 88, 85, 39, 6,194,146,116,135,213,244,187,182, 30,154, 28,113,211,178, 8,122,160, 51,230,231, 54, 64,232,157,104,161, 54, 10, 52, 93,106, 55, 90, 40,199, 17, 48, 39,138, 46, 78, 95,133,137,149,130,161,137, 71,156,102,102,157, 44,123,213,156,193, 45, 85,145,218, 41, 31,167,172, 71,221, 63, 39,172, 88,189, 78, 65, 99,175,224,146, 90, 56, 95,115,116,174,166,160,225,167,236,145,166,146,226,179,209, 80,112,165,106,243,153,218, 69,210,172,113,164,208,134, 33, 92, 26,160, 98,131, 50, 26,156,101,142, 78, 48,120, 26,150,193, 13,113, 90, 66,240,218,225,121,252, 65,133, 26, 6, 49, 73,230,209,153, 87, 78, 5, 50,107, 63,166,245,244,109,142,209,245, 29,211,212,157,227, 98, 36,136,195,121, 18, 82,172, 24,246,116,234, 18,131, 11,131,171, 18,238,216,166,197,196,168,242,122, 37, 58,102, 74,115, 31, 89, 39,162, 92,107, 27, 53,203, 78, 45,164,251, 96, 59, 80,201, 86,148, 5, 23,199, 51,198,169,172,195, 61,171,153,163,133,169,201, 21,212,115, 16,209, 81,215,245,118, 3, 90,146,129,107,155,186,157, 67, 75,231,172,203,193,246,236,216,148,107,215, 87,114,154,240, 31,168,120, 44,249,177, 83,138,228,133,225,212, 98, 39,235,216,177, 46,150,218,125, 55,232,217, 99,179,161, 15, 63,243, 33,184,228, 6, 82,224, 74, 23, 92, 20, 85,246, 71, 86,164, 46,184,212,113,243, 78,197,194, 94, 90,181, 30,233,145, 53, 23,166,212,212,168,192,169, 29,120, 23,109,251,194, 48,225, 40, 98,163, 98, 50, 30,124,135, 59, 87,185,121, 85,169,157,180, 48, 53,226,227, 6,110,186,109,107,173,195,102,108, 37, 91,112, 67, 28,170, 73,194,106,115, 50, 39,173,226,202,133,100, 35,225, 71, 95, 88,153,106, 19,161,116, 31,240, 3,232, 98, 5, 25,144, 77,204, 8, 44, 60, 29, 35,160,182,181,229,175,212,172,163, 13,181,169,219, 96, 18,232,200, 6,162, 88,117, 32,220, 26, 24, 97,221, 72, 11, 55, 36,102,186, 90, 95, 32,155,103,183, 93, 61,193,188,110,131,133,123, 8, 26, 59, 14,165,130, 52, 23, 28,137,215,200,142,151,169,230, 2, 15, 53, 96, 54,153, 89,153,139,157,136,216,237, 2,226,208,132,149, 86, 14,125,140,183,160, 42, 0, 54,175,175, 81,112,179, 30,128, 26,225,230, 62,156, 7,153, 4,222,244, 10,166,127,218,168,180,164, 1,252, 66,246,162,176,177, 83,230, 18, 54,179,139,226,182, 0,218,190,195,196,237,193,150,117, 50, 78,208,132, 42,118, 96, 14,143,135, 48,213,154,162,174, 89,227, 71, 17,147, 53, 24,135,106,174,218,102, 46,187,141, 28,253, 46,205, 94, 93, 53,130,193,138,148, 77,228, 13, 39, 52, 40,104,148,117, 39,104,168, 11,152,118,253, 63,234,132,217,105,112,113, 16,141,180,144,202, 92, 87, 61,121,190, 97,254, 81,189, 6, 64,207,202, 54,166, 28,221,168,212,233,193, 2,110,135,182,231,159, 54,182, 29,186, 51,186,152,221,129,139,230, 62, 59, 26, 72, 39,174,217,145, 7, 60, 16, 66, 83, 15, 17, 75, 83,153,134, 83,231, 4,164,220,100,186,192,176,185, 34,241, 17, 96,145, 7, 41, 33, 50,115, 29, 77, 1,104, 78,217,123,175,205, 89, 19,208,128,139, 77,100,116,147,150,215, 27,168,133,162,133,252, 70,188,244, 56, 14,109,186,199,245,255,156,220,147, 80,138,203, 77,238,201,200,182,196,155,221, 49, 6,134,250,173,228, 80, 4, 23,142,161,211, 28,162,157, 62,215, 63, 74,191, 29,202, 77,143,176, 34,113,123, 72,125, 77, 19,116, 58,248,129,238,179,179,224, 82, 81,106,167, 23, 90,242,178,129,171,196,182,239,187, 79,158,158,132,125,145, 33,183, 22, 0, 31, 24, 32, 38, 81, 2,155,241, 51,140, 89, 97, 51,130,191,235, 32, 55,110,142, 89,199, 5,184,147,145,186,126, 45, 60, 12,160,135, 94, 0,213, 66, 39,104, 80, 34, 2,105,150, 90, 8,235,164,234,255, 73,102,182,250, 70,147,167, 68,192, 56, 67, 85,225,180, 84,171, 40,180,117,167,113,219, 52, 54,194,102, 36,102, 30,190,192, 3,232,122, 76,126, 56,196, 92, 29,216,152,220,210,157,222,100,232,179,231, 68, 58,227,107,207,179,129,142, 34,186, 68,136, 40,178, 29, 46,145, 60, 72,227,248, 20,227, 99, 30,188,197,212,222,145,102,151,218,143,236,149, 18,173,189, 35,199,201,251,254,122, 61, 52,145,213,146, 63,233, 73,182, 58,225, 78, 47, 2, 45, 85, 19, 26,216,204,165,249, 21,101, 46,104,108, 46,184, 70,142,248,140, 83,227,205, 60,254,197,250, 92,160,133, 81,164,170,194, 31,230, 9, 20,180,156,141, 45,208, 54, 91, 64, 50,102,193, 84, 58, 87,238, 39,100,251,205, 44,253,182,156,211,146,217,235,146, 23, 7,221,132, 62,135,189,142,107,107, 42, 59, 30,200,224,153,181,133,157, 33,146,166, 78, 27,195, 47,233, 44,137,117,184, 37, 51,137,248, 72,214,212,192,116, 23, 92,204,209,234,255,233,152, 59,151,212,251, 29, 83,141,138, 71,169,133,107,209, 66, 13,125, 11,123, 90, 88,199, 55, 90, 56,118,245,122,110,140,153,214,201, 83,179, 78,108, 53,151,134, 32,250,157,232,198,108,184,129,126,187, 2, 54,111, 25, 92,101,183,151,181, 57,237,242, 71, 93,123,201,141,224,105,191,127,207, 21, 41, 26,114,196,243,224,146,151, 49, 67,206, 79,217,100, 40,153, 51, 71,133,221, 56,117,146,184,115, 86,210,196,106, 46, 30,201,162,211, 98,196,155, 43, 22, 25,182,171,171,220,209, 58, 84, 11,143,154, 0,107, 84,154, 53,182, 31,180, 27,197, 19,244,232, 71, 9,127, 26,107, 94, 48,115,105, 71, 5, 53, 57,210, 66,104,169, 19,109,214, 31,171, 88, 39,250,144,184, 27, 54, 51,115,249,157,160,161,125, 12,190, 27,235,108,221, 86, 53, 96, 51,133,244,173,206, 73, 16,170,182,205,176, 63, 96,192,160, 62,196, 30, 26, 34,209, 96, 31, 75,158, 29, 13, 4,110,118,216, 29,172,153, 99,141, 62,100, 76,219,125,168, 35, 50,240, 91,164,224,226, 40, 13, 65,209,250, 54,182,233, 82,216,204,126, 41, 12, 65, 60, 43, 64, 14,181,191,214,104,161, 88,134,235,221,116,179,227,178, 80,109, 93,192,221, 97,181, 84, 85,177,210,228,101, 99, 53, 23, 51, 23,207, 68,163,156,154,229, 39,164,153, 70, 98,201,238,212, 66, 21,165,190, 63,208, 60,166,139,163,230, 27,183,235,133,206,216, 56,156,108,133,110, 79,139,245,192, 27,182,187, 13,141, 56, 55,220,172,236,229,220, 7, 6,210, 38,151,254,149,130,110,163,130,243, 32, 77, 54,234,235, 88,160,232, 90, 40,158,198, 61,241,166,190, 70, 53, 52,222, 40,247, 57,238,237,236,204,222,159,253,110, 59, 70, 63,157,223,209,194, 3,213,194,133,171,185,108, 66,195,250, 92,106,177, 3,155,179, 33,115, 89, 97,156, 90,139, 61,211, 12,191,235,228,180,125,201,174, 62, 48,116,149,221,234,154,216,188, 27,218, 48, 39, 83,106,222,160, 73,123,134, 88,167,219, 37, 5,171, 22,252,165,145,195,237,193, 54,205, 11,158, 91, 59, 28,226,148, 28, 18,149, 19, 59, 20, 17,142,148,218,238, 2, 11, 82, 59, 96,202,103, 17,207,102, 36,230,195, 88,115,117, 93, 64, 75, 6, 58,226,193,101, 49, 43,253, 28, 45,100,159,139, 99,205, 10, 46,212, 54,181,230, 87, 52,151,154,137, 22, 2,155, 71, 54,188,226,172,211, 5, 23, 93, 24, 12, 68,157,156,161,110, 82,188, 67,222,195,249,121,160,133, 75,246,199,117, 54,142,109,192,104, 77,130, 58,105,252, 71, 3,241, 24,198, 71,140, 58,179, 77,172,202,139,238,195,242,132,232, 92, 73,214,240,205, 58, 81,226,224, 57, 22,250,196,238,148,167,132,251,220,152,188,130, 70,232, 67, 73,140,125,174,200,206,113,176,137,111,109, 70,107,122, 52,212, 88,141,127,210,200, 17, 45,100, 19,153,125, 46, 22,165, 10,174,202, 38, 52,212, 68, 54, 90,104,153,203,106, 46, 86,164,232,161,163, 34,117,106,161, 89, 39,232,182, 34,180,118, 60, 84, 87, 85, 44,237, 0,155,163,192,167, 23,226,186, 88,106, 7,144,182,164,231,157,156,162,164,228,174,197, 6,250,236,246, 29,117,174, 44,188,250,228,149,216,193, 78,230, 59, 4, 35,218, 75, 6, 66,214, 8,108, 83, 51, 91, 0,236,155,176, 16,179, 1, 7,107, 34,215, 46,157, 14,200,231,247,235,196, 99,156, 28, 45, 52,226,179, 88,178,207,101, 71, 92,225,210, 35, 97,115, 39,247,152,144,106,186, 10, 55,142, 71,152,238, 73, 6,181,208,205,200,250,109, 7,170, 10,174,245,188, 15,174,163, 35, 62,109,219,239,121,105, 31,230, 65, 78,244, 29, 14,239, 49,247, 6,175,151,174,170,228,101, 71,139,244,162,106,167,108, 88,242,138,105, 26,158, 55,170,148, 22, 17, 23,149,179,105,102,143,238,195, 25, 4, 22,169,135,173, 17, 31, 82,213,250,228,161,236,132,138,198,206,248,243, 4,126,181,102, 11,213,201, 65,217,133,119,209,150,119,235,115,185, 38,242, 40,115,135, 62,100,166, 22,146,248,216,137, 47,164,133,126,108, 53,151, 50,164, 19,155,117, 28, 4,166,176, 22, 24, 34,160, 82,108, 69,105, 71,225,187,221, 38,195, 60, 95,143, 65,253,232,254, 80,245, 72,238, 45, 29, 54,247,199,219,245,212, 57, 50, 96,150,105, 44,181, 91,242,210,216,138, 13, 0,213,220, 38,117,212,222, 19,238,173,166, 72, 81,242,240,175,186,234,163,235, 36,111, 54,174,180, 86,112,115, 66, 67,157,156,130,114,170,104,161,218, 37,236,115, 89,112,153,239,140,156, 14, 47,235,176,193, 63,102,201, 30, 73, 45,212, 33, 92,125,227, 83,105, 7, 67, 1, 59,171, 42, 64, 11, 93, 81, 90,247,207,210,246, 82,115,231,217,173,127,194,131,250,195, 17,108, 1,153,188, 88, 91,108,233, 68,118,236, 66,223, 47, 13, 59,108,142, 29,238, 68,108,242,224,223, 32,135,140,252,208,185, 79, 69,237, 66, 36, 45,104,109,108,154,169, 93,155,102,234,166,125,157, 80,216,141,206,217, 54,100,100,134,130,196,135,251,180, 89,115,233, 56, 21,164,235, 17,247,155, 36, 60,184,221,185,143,118,147, 72,117,114,186, 10,166,191, 34,213, 92,195, 14,162,214, 78, 53, 84,233,183, 86,201, 94,168, 13,227,212,136,211, 20,126,170,175,156,252, 95, 17, 76, 72,236, 37, 6,205, 22,115,203,217,142,216,236, 8,120,213, 77,227,227, 52, 62,183,143,172,163,206,105,220, 33, 52, 67,142,249,139,142,141, 59,179,113, 26, 49,157,249,182,165,165,219,149,216,244, 85,177,255,208,241,110,221, 4, 20,176,153,243, 97, 91,238, 98, 39, 45,172, 52,224, 35, 90,152,112,252,201,117,144,213, 98,207, 85,145,218,244,156, 20,159, 68,135, 84,115,195,148, 47,124,118,123, 9, 26, 40, 24,114, 31,244, 57,183,238, 84, 55,162, 96,211,158,206,222,218, 8,221,233, 84, 40,245,243,223,121,254,190, 27,137,178, 83, 0,181,134,208,195,148,188, 14,238, 40,174,202,157,233, 28,213,126,140,189, 80,101,155, 22, 85,114,189, 21,117, 38, 1,138, 72,127, 36, 71,177,182,240,205, 16,190, 44,228,105, 27,187, 20, 31, 53, 63, 92, 89,220, 14, 21,205,176,231,196,206,238,209,182,110,232, 51,144,207, 43,191,100, 67,145,131,122,117, 20, 20,126,212,148, 30, 84,178,251,120,128,213, 62, 77, 86, 78, 99,129,146, 96,170, 83, 71,124,220, 62, 6,199,170, 76,166,213,228,191,206,237, 84,205, 85,247,115,142,237,137, 26,223,167,179, 7,171,157, 59,178,253, 36,199,251,175, 59, 19,229,143,248,159,254,180,175, 63,222,239, 91, 57, 25,253, 91,251,159, 8,249, 39,223,250,186, 3, 22,219,246,143,189,123,251,199,220,216,255, 86, 30,196,239,254, 87, 12,255, 7, 46,242, 10,189,119, 85,123, 80, 0, 0, 0, 0, 73, 69, 78, 68,174, 66, 96,130,0 };
the_stack_data/237642617.c
/* fgetc 和 getc 区别在于前者是函数,后者是宏,getc 由 fgetc 通过宏实现; 宏调用里不能出现有副作用的表达式,因为宏是简单的替换,所以例如 "++i" 的表达式不能出现在宏函数里; #define MACRO_SQRT(x) (x)*(x) int func_sqrt(int x) { return x * x; } ... int i = 2; a = func_sqrt(++i); printf("a = %d, i = %d\n", a, i); ... i = 2; b = MACRO_SQRT(++i); printf("a = %d, i = %d\n", b, i); 上述两个函数的结果是不同的; */ #include <stdio.h> #define MACRO_SQRT(x) (x)*(x) int func_sqrt(int x) { return x * x; } int main(int argc, char *argv[]) { FILE *file_handle; char buf[1024], char_buf; file_handle = fopen("file.out", "r"); while((char_buf = fgetc(file_handle)) != EOF) { printf("%c", char_buf); } fseek(file_handle, 0, SEEK_SET); // getc 是宏函数,不能传入有副作用的参数 while((char_buf = getc(file_handle)) != EOF) { printf("%c", char_buf); } char temp_char = getchar(); printf("%c\n", temp_char); // 测试宏函数和普通函数 int i = 1; int a = func_sqrt(++i); printf("a = %d, i = %d\n", a, i); int j = 2; int b = MACRO_SQRT(++j); printf("a = %d, i = %d\n", b, i); fclose(file_handle); return 0; }
the_stack_data/68015.c
/* * Copyright (C) 1991,1992,1993,1997,1998,2003, 2005 Free Software Foundation, Inc. * This file is part of the GNU C Library. * Copyright (c) 2011 The Chromium OS Authors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ /* From glibc-2.14, sysdeps/i386/memset.c */ #include <stdint.h> #include "string.h" typedef uint32_t op_t; void *memset(void *dstpp, int c, size_t len) { int d0; unsigned long int dstp = (unsigned long int) dstpp; /* This explicit register allocation improves code very much indeed. */ register op_t x asm("ax"); x = (unsigned char) c; /* Clear the direction flag, so filling will move forward. */ asm volatile("cld"); /* This threshold value is optimal. */ if (len >= 12) { /* Fill X with four copies of the char we want to fill with. */ x |= (x << 8); x |= (x << 16); /* Adjust LEN for the bytes handled in the first loop. */ len -= (-dstp) % sizeof(op_t); /* * There are at least some bytes to set. No need to test for * LEN == 0 in this alignment loop. */ /* Fill bytes until DSTP is aligned on a longword boundary. */ asm volatile( "rep\n" "stosb" /* %0, %2, %3 */ : "=D" (dstp), "=c" (d0) : "0" (dstp), "1" ((-dstp) % sizeof(op_t)), "a" (x) : "memory"); /* Fill longwords. */ asm volatile( "rep\n" "stosl" /* %0, %2, %3 */ : "=D" (dstp), "=c" (d0) : "0" (dstp), "1" (len / sizeof(op_t)), "a" (x) : "memory"); len %= sizeof(op_t); } /* Write the last few bytes. */ asm volatile( "rep\n" "stosb" /* %0, %2, %3 */ : "=D" (dstp), "=c" (d0) : "0" (dstp), "1" (len), "a" (x) : "memory"); return dstpp; } void *memcpy(void *dest, const void *src, size_t n) { unsigned long d0, d1, d2; asm volatile( "rep ; movsl\n\t" "movl %4,%%ecx\n\t" "rep ; movsb\n\t" : "=&c" (d0), "=&D" (d1), "=&S" (d2) : "0" (n >> 2), "g" (n & 3), "1" (dest), "2" (src) : "memory" ); return dest; }
the_stack_data/175143598.c
// RUN: test.sh -e -t %t %s // bcmp() with too long value for length of comparison. #include <strings.h> int main() { char s[10] = "string"; char t[10] = "string"; bcmp(s, t, 100); return 0; }
the_stack_data/983107.c
// RUN: %clang_cc1 -triple arm64-linux-gnu -emit-llvm -o - %s | FileCheck --check-prefix=CHECK --check-prefix=CHECK-LE %s // RUN: %clang_cc1 -triple aarch64_be-linux-gnu -emit-llvm -o - %s | FileCheck --check-prefix=CHECK --check-prefix=CHECK-BE %s #include <stdarg.h> // Obviously there's more than one way to implement va_arg. This test should at // least prevent unintentional regressions caused by refactoring. va_list the_list; int simple_int(void) { // CHECK-LABEL: define i32 @simple_int return va_arg(the_list, int); // CHECK: [[GR_OFFS:%[a-z_0-9]+]] = load i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 3) // CHECK: [[EARLY_ONSTACK:%[a-z_0-9]+]] = icmp sge i32 [[GR_OFFS]], 0 // CHECK: br i1 [[EARLY_ONSTACK]], label %[[VAARG_ON_STACK:[a-z_.0-9]+]], label %[[VAARG_MAYBE_REG:[a-z_.0-9]+]] // CHECK: [[VAARG_MAYBE_REG]] // CHECK: [[NEW_REG_OFFS:%[a-z_0-9]+]] = add i32 [[GR_OFFS]], 8 // CHECK: store i32 [[NEW_REG_OFFS]], i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 3) // CHECK: [[INREG:%[a-z_0-9]+]] = icmp sle i32 [[NEW_REG_OFFS]], 0 // CHECK: br i1 [[INREG]], label %[[VAARG_IN_REG:[a-z_.0-9]+]], label %[[VAARG_ON_STACK]] // CHECK: [[VAARG_IN_REG]] // CHECK: [[REG_TOP:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 1) // CHECK: [[REG_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[REG_TOP]], i32 [[GR_OFFS]] // CHECK-BE: [[REG_ADDR_VAL:%[0-9]+]] = ptrtoint i8* [[REG_ADDR]] to i64 // CHECK-BE: [[REG_ADDR_VAL_ALIGNED:%[a-z_0-9]*]] = add i64 [[REG_ADDR_VAL]], 4 // CHECK-BE: [[REG_ADDR:%[0-9]+]] = inttoptr i64 [[REG_ADDR_VAL_ALIGNED]] to i8* // CHECK: [[FROMREG_ADDR:%[a-z_0-9]+]] = bitcast i8* [[REG_ADDR]] to i32* // CHECK: br label %[[VAARG_END:[a-z._0-9]+]] // CHECK: [[VAARG_ON_STACK]] // CHECK: [[STACK:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[NEW_STACK:%[a-z_0-9]+]] = getelementptr i8* [[STACK]], i32 8 // CHECK: store i8* [[NEW_STACK]], i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK-BE: [[STACK_VAL:%[0-9]+]] = ptrtoint i8* [[STACK]] to i64 // CHECK-BE: [[STACK_VAL_ALIGNED:%[a-z_0-9]*]] = add i64 [[STACK_VAL]], 4 // CHECK-BE: [[STACK:%[0-9]+]] = inttoptr i64 [[STACK_VAL_ALIGNED]] to i8* // CHECK: [[FROMSTACK_ADDR:%[a-z_0-9]+]] = bitcast i8* [[STACK]] to i32* // CHECK: br label %[[VAARG_END]] // CHECK: [[VAARG_END]] // CHECK: [[ADDR:%[a-z._0-9]+]] = phi i32* [ [[FROMREG_ADDR]], %[[VAARG_IN_REG]] ], [ [[FROMSTACK_ADDR]], %[[VAARG_ON_STACK]] ] // CHECK: [[RESULT:%[a-z_0-9]+]] = load i32* [[ADDR]] // CHECK: ret i32 [[RESULT]] } __int128 aligned_int(void) { // CHECK-LABEL: define i128 @aligned_int return va_arg(the_list, __int128); // CHECK: [[GR_OFFS:%[a-z_0-9]+]] = load i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 3) // CHECK: [[EARLY_ONSTACK:%[a-z_0-9]+]] = icmp sge i32 [[GR_OFFS]], 0 // CHECK: br i1 [[EARLY_ONSTACK]], label %[[VAARG_ON_STACK:[a-z_.0-9]+]], label %[[VAARG_MAYBE_REG:[a-z_.0-9]+]] // CHECK: [[VAARG_MAYBE_REG]] // CHECK: [[ALIGN_REGOFFS:%[a-z_0-9]+]] = add i32 [[GR_OFFS]], 15 // CHECK: [[ALIGNED_REGOFFS:%[a-z_0-9]+]] = and i32 [[ALIGN_REGOFFS]], -16 // CHECK: [[NEW_REG_OFFS:%[a-z_0-9]+]] = add i32 [[ALIGNED_REGOFFS]], 16 // CHECK: store i32 [[NEW_REG_OFFS]], i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 3) // CHECK: [[INREG:%[a-z_0-9]+]] = icmp sle i32 [[NEW_REG_OFFS]], 0 // CHECK: br i1 [[INREG]], label %[[VAARG_IN_REG:[a-z_.0-9]+]], label %[[VAARG_ON_STACK]] // CHECK: [[VAARG_IN_REG]] // CHECK: [[REG_TOP:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 1) // CHECK: [[REG_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[REG_TOP]], i32 [[ALIGNED_REGOFFS]] // CHECK: [[FROMREG_ADDR:%[a-z_0-9]+]] = bitcast i8* [[REG_ADDR]] to i128* // CHECK: br label %[[VAARG_END:[a-z._0-9]+]] // CHECK: [[VAARG_ON_STACK]] // CHECK: [[STACK:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[STACKINT:%[a-z_0-9]+]] = ptrtoint i8* [[STACK]] to i64 // CHECK: [[ALIGN_STACK:%[a-z_0-9]+]] = add i64 [[STACKINT]], 15 // CHECK: [[ALIGNED_STACK_INT:%[a-z_0-9]+]] = and i64 [[ALIGN_STACK]], -16 // CHECK: [[ALIGNED_STACK_PTR:%[a-z_0-9]+]] = inttoptr i64 [[ALIGNED_STACK_INT]] to i8* // CHECK: [[NEW_STACK:%[a-z_0-9]+]] = getelementptr i8* [[ALIGNED_STACK_PTR]], i32 16 // CHECK: store i8* [[NEW_STACK]], i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[FROMSTACK_ADDR:%[a-z_0-9]+]] = bitcast i8* [[ALIGNED_STACK_PTR]] to i128* // CHECK: br label %[[VAARG_END]] // CHECK: [[VAARG_END]] // CHECK: [[ADDR:%[a-z._0-9]+]] = phi i128* [ [[FROMREG_ADDR]], %[[VAARG_IN_REG]] ], [ [[FROMSTACK_ADDR]], %[[VAARG_ON_STACK]] ] // CHECK: [[RESULT:%[a-z_0-9]+]] = load i128* [[ADDR]] // CHECK: ret i128 [[RESULT]] } struct bigstruct { int a[10]; }; struct bigstruct simple_indirect(void) { // CHECK-LABEL: define void @simple_indirect return va_arg(the_list, struct bigstruct); // CHECK: [[GR_OFFS:%[a-z_0-9]+]] = load i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 3) // CHECK: [[EARLY_ONSTACK:%[a-z_0-9]+]] = icmp sge i32 [[GR_OFFS]], 0 // CHECK: br i1 [[EARLY_ONSTACK]], label %[[VAARG_ON_STACK:[a-z_.0-9]+]], label %[[VAARG_MAYBE_REG:[a-z_.0-9]+]] // CHECK: [[VAARG_MAYBE_REG]] // CHECK-NOT: and i32 // CHECK: [[NEW_REG_OFFS:%[a-z_0-9]+]] = add i32 [[GR_OFFS]], 8 // CHECK: store i32 [[NEW_REG_OFFS]], i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 3) // CHECK: [[INREG:%[a-z_0-9]+]] = icmp sle i32 [[NEW_REG_OFFS]], 0 // CHECK: br i1 [[INREG]], label %[[VAARG_IN_REG:[a-z_.0-9]+]], label %[[VAARG_ON_STACK]] // CHECK: [[VAARG_IN_REG]] // CHECK: [[REG_TOP:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 1) // CHECK: [[REG_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[REG_TOP]], i32 [[GR_OFFS]] // CHECK: [[FROMREG_ADDR:%[a-z_0-9]+]] = bitcast i8* [[REG_ADDR]] to %struct.bigstruct** // CHECK: br label %[[VAARG_END:[a-z._0-9]+]] // CHECK: [[VAARG_ON_STACK]] // CHECK: [[STACK:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK-NOT: and i64 // CHECK: [[NEW_STACK:%[a-z_0-9]+]] = getelementptr i8* [[STACK]], i32 8 // CHECK: store i8* [[NEW_STACK]], i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[FROMSTACK_ADDR:%[a-z_0-9]+]] = bitcast i8* [[STACK]] to %struct.bigstruct** // CHECK: br label %[[VAARG_END]] // CHECK: [[VAARG_END]] // CHECK: [[ADDR:%[a-z._0-9]+]] = phi %struct.bigstruct** [ [[FROMREG_ADDR]], %[[VAARG_IN_REG]] ], [ [[FROMSTACK_ADDR]], %[[VAARG_ON_STACK]] ] // CHECK: load %struct.bigstruct** [[ADDR]] } struct aligned_bigstruct { float a; long double b; }; struct aligned_bigstruct simple_aligned_indirect(void) { // CHECK-LABEL: define void @simple_aligned_indirect return va_arg(the_list, struct aligned_bigstruct); // CHECK: [[GR_OFFS:%[a-z_0-9]+]] = load i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 3) // CHECK: [[EARLY_ONSTACK:%[a-z_0-9]+]] = icmp sge i32 [[GR_OFFS]], 0 // CHECK: br i1 [[EARLY_ONSTACK]], label %[[VAARG_ON_STACK:[a-z_.0-9]+]], label %[[VAARG_MAYBE_REG:[a-z_.0-9]+]] // CHECK: [[VAARG_MAYBE_REG]] // CHECK: [[NEW_REG_OFFS:%[a-z_0-9]+]] = add i32 [[GR_OFFS]], 8 // CHECK: store i32 [[NEW_REG_OFFS]], i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 3) // CHECK: [[INREG:%[a-z_0-9]+]] = icmp sle i32 [[NEW_REG_OFFS]], 0 // CHECK: br i1 [[INREG]], label %[[VAARG_IN_REG:[a-z_.0-9]+]], label %[[VAARG_ON_STACK]] // CHECK: [[VAARG_IN_REG]] // CHECK: [[REG_TOP:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 1) // CHECK: [[REG_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[REG_TOP]], i32 [[GR_OFFS]] // CHECK: [[FROMREG_ADDR:%[a-z_0-9]+]] = bitcast i8* [[REG_ADDR]] to %struct.aligned_bigstruct** // CHECK: br label %[[VAARG_END:[a-z._0-9]+]] // CHECK: [[VAARG_ON_STACK]] // CHECK: [[STACK:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[NEW_STACK:%[a-z_0-9]+]] = getelementptr i8* [[STACK]], i32 8 // CHECK: store i8* [[NEW_STACK]], i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[FROMSTACK_ADDR:%[a-z_0-9]+]] = bitcast i8* [[STACK]] to %struct.aligned_bigstruct** // CHECK: br label %[[VAARG_END]] // CHECK: [[VAARG_END]] // CHECK: [[ADDR:%[a-z._0-9]+]] = phi %struct.aligned_bigstruct** [ [[FROMREG_ADDR]], %[[VAARG_IN_REG]] ], [ [[FROMSTACK_ADDR]], %[[VAARG_ON_STACK]] ] // CHECK: load %struct.aligned_bigstruct** [[ADDR]] } double simple_double(void) { // CHECK-LABEL: define double @simple_double return va_arg(the_list, double); // CHECK: [[VR_OFFS:%[a-z_0-9]+]] = load i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 4) // CHECK: [[EARLY_ONSTACK:%[a-z_0-9]+]] = icmp sge i32 [[VR_OFFS]], 0 // CHECK: br i1 [[EARLY_ONSTACK]], label %[[VAARG_ON_STACK:[a-z_.0-9]+]], label %[[VAARG_MAYBE_REG]] // CHECK: [[VAARG_MAYBE_REG]] // CHECK: [[NEW_REG_OFFS:%[a-z_0-9]+]] = add i32 [[VR_OFFS]], 16 // CHECK: store i32 [[NEW_REG_OFFS]], i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 4) // CHECK: [[INREG:%[a-z_0-9]+]] = icmp sle i32 [[NEW_REG_OFFS]], 0 // CHECK: br i1 [[INREG]], label %[[VAARG_IN_REG:[a-z_.0-9]+]], label %[[VAARG_ON_STACK]] // CHECK: [[VAARG_IN_REG]] // CHECK: [[REG_TOP:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 2) // CHECK: [[REG_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[REG_TOP]], i32 [[VR_OFFS]] // CHECK-BE: [[REG_ADDR_VAL:%[0-9]+]] = ptrtoint i8* [[REG_ADDR]] to i64 // CHECK-BE: [[REG_ADDR_VAL_ALIGNED:%[a-z_0-9]*]] = add i64 [[REG_ADDR_VAL]], 8 // CHECK-BE: [[REG_ADDR:%[0-9]+]] = inttoptr i64 [[REG_ADDR_VAL_ALIGNED]] to i8* // CHECK: [[FROMREG_ADDR:%[a-z_0-9]+]] = bitcast i8* [[REG_ADDR]] to double* // CHECK: br label %[[VAARG_END:[a-z._0-9]+]] // CHECK: [[VAARG_ON_STACK]] // CHECK: [[STACK:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[NEW_STACK:%[a-z_0-9]+]] = getelementptr i8* [[STACK]], i32 8 // CHECK: store i8* [[NEW_STACK]], i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[FROMSTACK_ADDR:%[a-z_0-9]+]] = bitcast i8* [[STACK]] to double* // CHECK: br label %[[VAARG_END]] // CHECK: [[VAARG_END]] // CHECK: [[ADDR:%[a-z._0-9]+]] = phi double* [ [[FROMREG_ADDR]], %[[VAARG_IN_REG]] ], [ [[FROMSTACK_ADDR]], %[[VAARG_ON_STACK]] ] // CHECK: [[RESULT:%[a-z_0-9]+]] = load double* [[ADDR]] // CHECK: ret double [[RESULT]] } struct hfa { float a, b; }; struct hfa simple_hfa(void) { // CHECK-LABEL: define %struct.hfa @simple_hfa return va_arg(the_list, struct hfa); // CHECK: [[VR_OFFS:%[a-z_0-9]+]] = load i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 4) // CHECK: [[EARLY_ONSTACK:%[a-z_0-9]+]] = icmp sge i32 [[VR_OFFS]], 0 // CHECK: br i1 [[EARLY_ONSTACK]], label %[[VAARG_ON_STACK:[a-z_.0-9]+]], label %[[VAARG_MAYBE_REG:[a-z_.0-9]+]] // CHECK: [[VAARG_MAYBE_REG]] // CHECK: [[NEW_REG_OFFS:%[a-z_0-9]+]] = add i32 [[VR_OFFS]], 32 // CHECK: store i32 [[NEW_REG_OFFS]], i32* getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 4) // CHECK: [[INREG:%[a-z_0-9]+]] = icmp sle i32 [[NEW_REG_OFFS]], 0 // CHECK: br i1 [[INREG]], label %[[VAARG_IN_REG:[a-z_.0-9]+]], label %[[VAARG_ON_STACK]] // CHECK: [[VAARG_IN_REG]] // CHECK: [[REG_TOP:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 2) // CHECK: [[FIRST_REG:%[a-z_0-9]+]] = getelementptr i8* [[REG_TOP]], i32 [[VR_OFFS]] // CHECK-LE: [[EL_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[FIRST_REG]], i32 0 // CHECK-BE: [[EL_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[FIRST_REG]], i32 12 // CHECK: [[EL_TYPED:%[a-z_0-9]+]] = bitcast i8* [[EL_ADDR]] to float* // CHECK: [[EL_TMPADDR:%[a-z_0-9]+]] = getelementptr inbounds [2 x float]* %[[TMP_HFA:[a-z_.0-9]+]], i32 0, i32 0 // CHECK: [[EL:%[a-z_0-9]+]] = load float* [[EL_TYPED]] // CHECK: store float [[EL]], float* [[EL_TMPADDR]] // CHECK-LE: [[EL_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[FIRST_REG]], i32 16 // CHECK-BE: [[EL_ADDR:%[a-z_0-9]+]] = getelementptr i8* [[FIRST_REG]], i32 28 // CHECK: [[EL_TYPED:%[a-z_0-9]+]] = bitcast i8* [[EL_ADDR]] to float* // CHECK: [[EL_TMPADDR:%[a-z_0-9]+]] = getelementptr inbounds [2 x float]* %[[TMP_HFA]], i32 0, i32 1 // CHECK: [[EL:%[a-z_0-9]+]] = load float* [[EL_TYPED]] // CHECK: store float [[EL]], float* [[EL_TMPADDR]] // CHECK: [[FROMREG_ADDR:%[a-z_0-9]+]] = bitcast [2 x float]* %[[TMP_HFA]] to %struct.hfa* // CHECK: br label %[[VAARG_END:[a-z_.0-9]+]] // CHECK: [[VAARG_ON_STACK]] // CHECK: [[STACK:%[a-z_0-9]+]] = load i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[NEW_STACK:%[a-z_0-9]+]] = getelementptr i8* [[STACK]], i32 8 // CHECK: store i8* [[NEW_STACK]], i8** getelementptr inbounds (%struct.__va_list* @the_list, i32 0, i32 0) // CHECK: [[FROMSTACK_ADDR:%[a-z_0-9]+]] = bitcast i8* [[STACK]] to %struct.hfa* // CHECK: br label %[[VAARG_END]] // CHECK: [[VAARG_END]] // CHECK: [[ADDR:%[a-z._0-9]+]] = phi %struct.hfa* [ [[FROMREG_ADDR]], %[[VAARG_IN_REG]] ], [ [[FROMSTACK_ADDR]], %[[VAARG_ON_STACK]] ] } void check_start(int n, ...) { // CHECK-LABEL: define void @check_start(i32 %n, ...) va_list the_list; va_start(the_list, n); // CHECK: [[THE_LIST:%[a-z_0-9]+]] = alloca %struct.__va_list // CHECK: [[VOIDP_THE_LIST:%[a-z_0-9]+]] = bitcast %struct.__va_list* [[THE_LIST]] to i8* // CHECK: call void @llvm.va_start(i8* [[VOIDP_THE_LIST]]) }
the_stack_data/9490.c
/* $Id: nsichneu.c,v 1.3 2005/04/15 09:18:42 jgn Exp $ */ /*************************************************************************** * * Copyright (c) 1998/1999, C-LAB, Paderborn * * File generated by Sea2CHaRy * * This file containes a CHaRy description generated from the * file: NSicherNeu.sea * The name of the Pr/T-Net was: NSicherNeu * * Modified and maintained by * Friedhelm Stappert * C-LAB, Paderborn, Germany * [email protected] * * Modifications: * o made the local variables global and volatile, * so the compiler won't optimise everything away. * ***************************************************************************/ // #define DO_TRACING #ifdef DO_TRACING // ON PC #include <stdio.h> #define TRACE(x) trace((x)) #undef TEST /* finished testing! */ void trace(char *s) { printf("%s\n",s); } #else // ON TARGET #define TRACE(x) #undef TEST #endif volatile int P1_is_marked = 3; volatile long P1_marking_member_0[3]; volatile int P2_is_marked = 5; volatile long P2_marking_member_0[5]; volatile int P3_is_marked = 0; volatile long P3_marking_member_0[6]; /**void NSicherNeu()**/ int main() { int dummy_i; /* dummy_i = 17; Takes too much time */ dummy_i = 2; while (dummy_i > 0) { dummy_i--; /* Permutation for Place P1 : 0, 1, 2 */ /* Transition T1 */ if ( (P1_is_marked >= 3) && (P3_is_marked + 3 <= 6) && (P1_marking_member_0[1] == P1_marking_member_0[2]) ) { long x; long y; long z; x = P1_marking_member_0[0]; y = P1_marking_member_0[1]; /* Transition condition */ if (x < y) { /* demarking of input places */ P1_is_marked = P1_is_marked - 3; /* preaction */ z = x - y; /* marking of output places */ P3_marking_member_0[P3_is_marked+0] = x; P3_marking_member_0[P3_is_marked+1] = y; P3_marking_member_0[P3_is_marked+2] = z; P3_is_marked = P3_is_marked + 3; } /* end of if (Transition condition) */ } /* Permutation for Place P1 : 0, 2, 1 */ /* Transition T1 */ if ( (P1_is_marked >= 3) && (P3_is_marked + 3 <= 6) && (P1_marking_member_0[2] == P1_marking_member_0[1]) ) { long x; long y; long z; x = P1_marking_member_0[0]; y = P1_marking_member_0[2]; /* Transition condition */ if ((x < y)) { /* demarking of input places */ P1_is_marked = P1_is_marked - 3; /* preaction */ z = x - y; /* marking of output places */ P3_marking_member_0[P3_is_marked+0] = x; P3_marking_member_0[P3_is_marked+1] = y; P3_marking_member_0[P3_is_marked+2] = z; P3_is_marked = P3_is_marked + 3; } /* end of if (Transition condition) */ } /* Permutation for Place P1 : 1, 0, 2 */ /* Transition T1 */ if ( (P1_is_marked >= 3) && (P3_is_marked + 3 <= 6) && (P1_marking_member_0[0] == P1_marking_member_0[2]) ) { long x; long y; long z; x = P1_marking_member_0[1]; y = P1_marking_member_0[0]; /* Transition condition */ if (x < y) { /* demarking of input places */ P1_is_marked = P1_is_marked - 3; /* preaction */ z = x - y; /* marking of output places */ P3_marking_member_0[P3_is_marked+0] = x; P3_marking_member_0[P3_is_marked+1] = y; P3_marking_member_0[P3_is_marked+2] = z; P3_is_marked = P3_is_marked + 3; } /* end of if (Transition condition) */ } /* Permutation for Place P1 : 1, 2, 0 */ /* Transition T1 */ if ( (P1_is_marked >= 3) && (P3_is_marked + 3 <= 6) && (P1_marking_member_0[2] == P1_marking_member_0[0])) { long x; long y; long z; x = P1_marking_member_0[1]; y = P1_marking_member_0[2]; /* Transition condition */ if ((x < y)) { /* demarking of input places */ P1_is_marked = P1_is_marked - 3; /* preaction */ z = x - y; /* marking of output places */ P3_marking_member_0[P3_is_marked+0] = x; P3_marking_member_0[P3_is_marked+1] = y; P3_marking_member_0[P3_is_marked+2] = z; P3_is_marked = P3_is_marked + 3; } /* end of if (Transition condition) */ } /* Permutation for Place P1 : 2, 0, 1 */ /* Transition T1 */ if ( (P1_is_marked >= 3) && (P3_is_marked + 3 <= 6) && (P1_marking_member_0[0] == P1_marking_member_0[1]) ) { long x; long y; long z; x = P1_marking_member_0[2]; y = P1_marking_member_0[0]; /* Transition condition */ if ((x < y)) { /* demarking of input places */ P1_is_marked = P1_is_marked - 3; /* preaction */ z = x - y; /* marking of output places */ P3_marking_member_0[P3_is_marked+0] = x; P3_marking_member_0[P3_is_marked+1] = y; P3_marking_member_0[P3_is_marked+2] = z; P3_is_marked = P3_is_marked + 3; } /* end of if (Transition condition) */ } /* Permutation for Place P1 : 2, 1, 0 */ /* Transition T1 */ if ( (P1_is_marked >= 3) && (P3_is_marked + 3 <= 6) && (P1_marking_member_0[1] == P1_marking_member_0[0]) ) { long x; long y; long z; x = P1_marking_member_0[2]; y = P1_marking_member_0[1]; /* Transition condition */ if ((x < y)) { /* demarking of input places */ P1_is_marked = P1_is_marked - 3; /* preaction */ z = x - y; /* marking of output places */ P3_marking_member_0[P3_is_marked+0] = x; P3_marking_member_0[P3_is_marked+1] = y; P3_marking_member_0[P3_is_marked+2] = z; P3_is_marked = P3_is_marked + 3; } /* end of if (Transition condition) */ } } dummy_i = 77; return dummy_i; } /*************************************************************************** * * end of file * ***************************************************************************/
the_stack_data/170452272.c
# include <stdio.h> // Sempre que for utilizar uma função struct como parâmetro de uma função // A struct terá que ser declarada como global struct horario{ int horas, minutos, segundos; }; int main(void){ struct horario teste(struct horario x); struct horario agora; agora.horas = 10; agora.minutos = 42; agora.segundos = 58; struct horario proxima; proxima = teste(agora); // ao retornar uma struct, seus valores devem ser armazenados em outra struct de mesmo tipo printf("%i:%i:%i\n", proxima.horas, proxima.minutos, proxima.segundos); return 0; } struct horario teste(struct horario x){ printf("%i:%i:%i\n", x.horas, x.minutos, x.segundos); x.horas = 24; x.minutos = 60; x.segundos = 60; return x; }
the_stack_data/51597.c
/* Qn : Write a C function that takes a 2D array. It will return 1 if there finds a perfect number otherwise it will return 0. Sample Input Sample Output 1 3 7 2 6 9 perfect 5 4 8 */ /* Author : Arnob Mahmud mail : [email protected] */ #include <stdio.h> int perfectQuery(int A[3][3]) { int fctr; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { fctr = 0; for (int k = 1; k < A[i][j]; k++) { if (A[i][j] % k == 0) { fctr += k; } } if (fctr == A[i][j]) { return 1; } } } } int main(int argc, char const *argv[]) { int A[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("A[%d][%d] : ", i, j); scanf("%d", &A[i][j]); } } if (perfectQuery(A) == 1) { printf("Perfect"); } return 0; }