gzip.c 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Gzip implementation for busybox
  4. *
  5. * Based on GNU gzip Copyright (C) 1992-1993 Jean-loup Gailly.
  6. *
  7. * Originally adjusted for busybox by Charles P. Wright <cpw@unix.asb.com>
  8. * "this is a stripped down version of gzip I put into busybox, it does
  9. * only standard in to standard out with -9 compression. It also requires
  10. * the zcat module for some important functions."
  11. *
  12. * Adjusted further by Erik Andersen <andersen@codepoet.org> to support
  13. * files as well as stdin/stdout, and to generally behave itself wrt
  14. * command line handling.
  15. *
  16. * This program is free software; you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation; either version 2 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  24. * General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with this program; if not, write to the Free Software
  28. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  29. *
  30. */
  31. /* These defines are very important for BusyBox. Without these,
  32. * huge chunks of ram are pre-allocated making the BusyBox bss
  33. * size Freaking Huge(tm), which is a bad thing.*/
  34. #define SMALL_MEM
  35. #define DYN_ALLOC
  36. #include <stdlib.h>
  37. #include <stdio.h>
  38. #include <string.h>
  39. #include <unistd.h>
  40. #include <errno.h>
  41. #include <sys/types.h>
  42. #include <signal.h>
  43. #include <utime.h>
  44. #include <ctype.h>
  45. #include <sys/types.h>
  46. #include <unistd.h>
  47. #include <dirent.h>
  48. #include <fcntl.h>
  49. #include <time.h>
  50. #include "busybox.h"
  51. typedef unsigned char uch;
  52. typedef unsigned short ush;
  53. typedef unsigned long ulg;
  54. /* Return codes from gzip */
  55. #define OK 0
  56. #define ERROR 1
  57. #define WARNING 2
  58. /* Compression methods (see algorithm.doc) */
  59. /* Only STORED and DEFLATED are supported by this BusyBox module */
  60. #define STORED 0
  61. /* methods 4 to 7 reserved */
  62. #define DEFLATED 8
  63. /* To save memory for 16 bit systems, some arrays are overlaid between
  64. * the various modules:
  65. * deflate: prev+head window d_buf l_buf outbuf
  66. * unlzw: tab_prefix tab_suffix stack inbuf outbuf
  67. * For compression, input is done in window[]. For decompression, output
  68. * is done in window except for unlzw.
  69. */
  70. #ifndef INBUFSIZ
  71. # ifdef SMALL_MEM
  72. # define INBUFSIZ 0x2000 /* input buffer size */
  73. # else
  74. # define INBUFSIZ 0x8000 /* input buffer size */
  75. # endif
  76. #endif
  77. #define INBUF_EXTRA 64 /* required by unlzw() */
  78. #ifndef OUTBUFSIZ
  79. # ifdef SMALL_MEM
  80. # define OUTBUFSIZ 8192 /* output buffer size */
  81. # else
  82. # define OUTBUFSIZ 16384 /* output buffer size */
  83. # endif
  84. #endif
  85. #define OUTBUF_EXTRA 2048 /* required by unlzw() */
  86. #ifndef DIST_BUFSIZE
  87. # ifdef SMALL_MEM
  88. # define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
  89. # else
  90. # define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
  91. # endif
  92. #endif
  93. #ifdef DYN_ALLOC
  94. # define DECLARE(type, array, size) static type * array
  95. # define ALLOC(type, array, size) { \
  96. array = (type*)xcalloc((size_t)(((size)+1L)/2), 2*sizeof(type)); \
  97. }
  98. # define FREE(array) {free(array), array=NULL;}
  99. #else
  100. # define DECLARE(type, array, size) static type array[size]
  101. # define ALLOC(type, array, size)
  102. # define FREE(array)
  103. #endif
  104. #define tab_suffix window
  105. #define tab_prefix prev /* hash link (see deflate.c) */
  106. #define head (prev+WSIZE) /* hash head (see deflate.c) */
  107. static long bytes_in; /* number of input bytes */
  108. #define isize bytes_in
  109. /* for compatibility with old zip sources (to be cleaned) */
  110. typedef int file_t; /* Do not use stdio */
  111. #define NO_FILE (-1) /* in memory compression */
  112. #define PACK_MAGIC "\037\036" /* Magic header for packed files */
  113. #define GZIP_MAGIC "\037\213" /* Magic header for gzip files, 1F 8B */
  114. #define OLD_GZIP_MAGIC "\037\236" /* Magic header for gzip 0.5 = freeze 1.x */
  115. #define LZH_MAGIC "\037\240" /* Magic header for SCO LZH Compress files */
  116. #define PKZIP_MAGIC "\120\113\003\004" /* Magic header for pkzip files */
  117. /* gzip flag byte */
  118. #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
  119. #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
  120. #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
  121. #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
  122. #define COMMENT 0x10 /* bit 4 set: file comment present */
  123. #define RESERVED 0xC0 /* bit 6,7: reserved */
  124. /* internal file attribute */
  125. #define UNKNOWN 0xffff
  126. #define BINARY 0
  127. #define ASCII 1
  128. #ifndef WSIZE
  129. # define WSIZE 0x8000 /* window size--must be a power of two, and */
  130. #endif /* at least 32K for zip's deflate method */
  131. #define MIN_MATCH 3
  132. #define MAX_MATCH 258
  133. /* The minimum and maximum match lengths */
  134. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  135. /* Minimum amount of lookahead, except at the end of the input file.
  136. * See deflate.c for comments about the MIN_MATCH+1.
  137. */
  138. #define MAX_DIST (WSIZE-MIN_LOOKAHEAD)
  139. /* In order to simplify the code, particularly on 16 bit machines, match
  140. * distances are limited to MAX_DIST instead of WSIZE.
  141. */
  142. /* put_byte is used for the compressed output */
  143. #define put_byte(c) {outbuf[outcnt++]=(uch)(c); if (outcnt==OUTBUFSIZ)\
  144. flush_outbuf();}
  145. /* Output a 32 bit value to the bit stream, lsb first */
  146. #if 0
  147. #define put_long(n) { \
  148. put_short((n) & 0xffff); \
  149. put_short(((ulg)(n)) >> 16); \
  150. }
  151. #endif
  152. #define seekable() 0 /* force sequential output */
  153. #define translate_eol 0 /* no option -a yet */
  154. /* Diagnostic functions */
  155. #ifdef DEBUG
  156. # define Assert(cond,msg) {if(!(cond)) bb_error_msg(msg);}
  157. # define Trace(x) fprintf x
  158. # define Tracev(x) {if (verbose) fprintf x ;}
  159. # define Tracevv(x) {if (verbose>1) fprintf x ;}
  160. # define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
  161. # define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
  162. #else
  163. # define Assert(cond,msg)
  164. # define Trace(x)
  165. # define Tracev(x)
  166. # define Tracevv(x)
  167. # define Tracec(c,x)
  168. # define Tracecv(c,x)
  169. #endif
  170. #define WARN(msg) {if (!quiet) fprintf msg ; \
  171. if (exit_code == OK) exit_code = WARNING;}
  172. #ifndef MAX_PATH_LEN
  173. # define MAX_PATH_LEN 1024 /* max pathname length */
  174. #endif
  175. /* from zip.c: */
  176. static int zip(int in, int out);
  177. static int file_read(char *buf, unsigned size);
  178. /* from deflate.c */
  179. static void lm_init(ush * flags);
  180. static ulg deflate(void);
  181. /* from trees.c */
  182. static void ct_init(ush * attr, int *methodp);
  183. static int ct_tally(int dist, int lc);
  184. static ulg flush_block(char *buf, ulg stored_len, int eof);
  185. /* from bits.c */
  186. static void bi_init(file_t zipfile);
  187. static void send_bits(int value, int length);
  188. static unsigned bi_reverse(unsigned value, int length);
  189. static void bi_windup(void);
  190. static void copy_block(char *buf, unsigned len, int header);
  191. static int (*read_buf) (char *buf, unsigned size);
  192. /* from util.c: */
  193. static void flush_outbuf(void);
  194. /* lzw.h -- define the lzw functions.
  195. * Copyright (C) 1992-1993 Jean-loup Gailly.
  196. * This is free software; you can redistribute it and/or modify it under the
  197. * terms of the GNU General Public License, see the file COPYING.
  198. */
  199. #if !defined(OF) && defined(lint)
  200. # include "gzip.h"
  201. #endif
  202. #ifndef BITS
  203. # define BITS 16
  204. #endif
  205. #define INIT_BITS 9 /* Initial number of bits per code */
  206. #define BIT_MASK 0x1f /* Mask for 'number of compression bits' */
  207. /* Mask 0x20 is reserved to mean a fourth header byte, and 0x40 is free.
  208. * It's a pity that old uncompress does not check bit 0x20. That makes
  209. * extension of the format actually undesirable because old compress
  210. * would just crash on the new format instead of giving a meaningful
  211. * error message. It does check the number of bits, but it's more
  212. * helpful to say "unsupported format, get a new version" than
  213. * "can only handle 16 bits".
  214. */
  215. /* tailor.h -- target dependent definitions
  216. * Copyright (C) 1992-1993 Jean-loup Gailly.
  217. * This is free software; you can redistribute it and/or modify it under the
  218. * terms of the GNU General Public License, see the file COPYING.
  219. */
  220. /* The target dependent definitions should be defined here only.
  221. * The target dependent functions should be defined in tailor.c.
  222. */
  223. /* Common defaults */
  224. #ifndef OS_CODE
  225. # define OS_CODE 0x03 /* assume Unix */
  226. #endif
  227. #ifndef PATH_SEP
  228. # define PATH_SEP '/'
  229. #endif
  230. #ifndef OPTIONS_VAR
  231. # define OPTIONS_VAR "GZIP"
  232. #endif
  233. #ifndef Z_SUFFIX
  234. # define Z_SUFFIX ".gz"
  235. #endif
  236. #ifdef MAX_EXT_CHARS
  237. # define MAX_SUFFIX MAX_EXT_CHARS
  238. #else
  239. # define MAX_SUFFIX 30
  240. #endif
  241. /* global buffers */
  242. DECLARE(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
  243. DECLARE(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
  244. DECLARE(ush, d_buf, DIST_BUFSIZE);
  245. DECLARE(uch, window, 2L * WSIZE);
  246. DECLARE(ush, tab_prefix, 1L << BITS);
  247. static int foreground; /* set if program run in foreground */
  248. static int method = DEFLATED; /* compression method */
  249. static int exit_code = OK; /* program exit code */
  250. static int part_nb; /* number of parts in .gz file */
  251. static long time_stamp; /* original time stamp (modification time) */
  252. static long ifile_size; /* input file size, -1 for devices (debug only) */
  253. static char z_suffix[MAX_SUFFIX + 1]; /* default suffix (can be set with --suffix) */
  254. static int z_len; /* strlen(z_suffix) */
  255. static int ifd; /* input file descriptor */
  256. static int ofd; /* output file descriptor */
  257. static unsigned insize; /* valid bytes in inbuf */
  258. static unsigned outcnt; /* bytes in output buffer */
  259. /* Output a 16 bit value, lsb first */
  260. static void put_short(ush w)
  261. {
  262. if (outcnt < OUTBUFSIZ - 2) {
  263. outbuf[outcnt++] = (uch) ((w) & 0xff);
  264. outbuf[outcnt++] = (uch) ((ush) (w) >> 8);
  265. } else {
  266. put_byte((uch) ((w) & 0xff));
  267. put_byte((uch) ((ush) (w) >> 8));
  268. }
  269. }
  270. /* ========================================================================
  271. * Signal and error handler.
  272. */
  273. static void abort_gzip(int ignored)
  274. {
  275. exit(ERROR);
  276. }
  277. /* ===========================================================================
  278. * Clear input and output buffers
  279. */
  280. static void clear_bufs(void)
  281. {
  282. outcnt = 0;
  283. insize = 0;
  284. bytes_in = 0L;
  285. }
  286. /* ===========================================================================
  287. * Does the same as write(), but also handles partial pipe writes and checks
  288. * for error return.
  289. */
  290. static void write_buf(int fd, void *buf, unsigned cnt)
  291. {
  292. unsigned n;
  293. while ((n = write(fd, buf, cnt)) != cnt) {
  294. if (n == (unsigned) (-1)) bb_error_msg_and_die("can't write");
  295. cnt -= n;
  296. buf = (void *) ((char *) buf + n);
  297. }
  298. }
  299. /* ===========================================================================
  300. * Run a set of bytes through the crc shift register. If s is a NULL
  301. * pointer, then initialize the crc shift register contents instead.
  302. * Return the current crc in either case.
  303. */
  304. static ulg updcrc(uch * s, unsigned n)
  305. {
  306. static ulg crc = (ulg) 0xffffffffL; /* shift register contents */
  307. register ulg c; /* temporary variable */
  308. static unsigned long crc_32_tab[256];
  309. if (crc_32_tab[1] == 0x00000000L) {
  310. unsigned long csr; /* crc shift register */
  311. const unsigned long e = 0xedb88320L; /* polynomial exclusive-or pattern */
  312. int i; /* counter for all possible eight bit values */
  313. int k; /* byte being shifted into crc apparatus */
  314. /* Compute table of CRC's. */
  315. for (i = 1; i < 256; i++) {
  316. csr = i;
  317. /* The idea to initialize the register with the byte instead of
  318. * zero was stolen from Haruhiko Okumura's ar002
  319. */
  320. for (k = 8; k; k--)
  321. csr = csr & 1 ? (csr >> 1) ^ e : csr >> 1;
  322. crc_32_tab[i] = csr;
  323. }
  324. }
  325. if (s == NULL) {
  326. c = 0xffffffffL;
  327. } else {
  328. c = crc;
  329. if (n)
  330. do {
  331. c = crc_32_tab[((int) c ^ (*s++)) & 0xff] ^ (c >> 8);
  332. } while (--n);
  333. }
  334. crc = c;
  335. return c ^ 0xffffffffL; /* (instead of ~c for 64-bit machines) */
  336. }
  337. /* bits.c -- output variable-length bit strings
  338. * Copyright (C) 1992-1993 Jean-loup Gailly
  339. * This is free software; you can redistribute it and/or modify it under the
  340. * terms of the GNU General Public License, see the file COPYING.
  341. */
  342. /*
  343. * PURPOSE
  344. *
  345. * Output variable-length bit strings. Compression can be done
  346. * to a file or to memory. (The latter is not supported in this version.)
  347. *
  348. * DISCUSSION
  349. *
  350. * The PKZIP "deflate" file format interprets compressed file data
  351. * as a sequence of bits. Multi-bit strings in the file may cross
  352. * byte boundaries without restriction.
  353. *
  354. * The first bit of each byte is the low-order bit.
  355. *
  356. * The routines in this file allow a variable-length bit value to
  357. * be output right-to-left (useful for literal values). For
  358. * left-to-right output (useful for code strings from the tree routines),
  359. * the bits must have been reversed first with bi_reverse().
  360. *
  361. * For in-memory compression, the compressed bit stream goes directly
  362. * into the requested output buffer. The input data is read in blocks
  363. * by the mem_read() function. The buffer is limited to 64K on 16 bit
  364. * machines.
  365. *
  366. * INTERFACE
  367. *
  368. * void bi_init (FILE *zipfile)
  369. * Initialize the bit string routines.
  370. *
  371. * void send_bits (int value, int length)
  372. * Write out a bit string, taking the source bits right to
  373. * left.
  374. *
  375. * int bi_reverse (int value, int length)
  376. * Reverse the bits of a bit string, taking the source bits left to
  377. * right and emitting them right to left.
  378. *
  379. * void bi_windup (void)
  380. * Write out any remaining bits in an incomplete byte.
  381. *
  382. * void copy_block(char *buf, unsigned len, int header)
  383. * Copy a stored block to the zip file, storing first the length and
  384. * its one's complement if requested.
  385. *
  386. */
  387. /* ===========================================================================
  388. * Local data used by the "bit string" routines.
  389. */
  390. static file_t zfile; /* output gzip file */
  391. static unsigned short bi_buf;
  392. /* Output buffer. bits are inserted starting at the bottom (least significant
  393. * bits).
  394. */
  395. #define Buf_size (8 * 2*sizeof(char))
  396. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  397. * more than 16 bits on some systems.)
  398. */
  399. static int bi_valid;
  400. /* Current input function. Set to mem_read for in-memory compression */
  401. #ifdef DEBUG
  402. ulg bits_sent; /* bit length of the compressed data */
  403. #endif
  404. /* ===========================================================================
  405. * Initialize the bit string routines.
  406. */
  407. static void bi_init(file_t zipfile)
  408. {
  409. zfile = zipfile;
  410. bi_buf = 0;
  411. bi_valid = 0;
  412. #ifdef DEBUG
  413. bits_sent = 0L;
  414. #endif
  415. /* Set the defaults for file compression. They are set by memcompress
  416. * for in-memory compression.
  417. */
  418. if (zfile != NO_FILE) {
  419. read_buf = file_read;
  420. }
  421. }
  422. /* ===========================================================================
  423. * Send a value on a given number of bits.
  424. * IN assertion: length <= 16 and value fits in length bits.
  425. */
  426. static void send_bits(int value, int length)
  427. {
  428. #ifdef DEBUG
  429. Tracev((stderr, " l %2d v %4x ", length, value));
  430. Assert(length > 0 && length <= 15, "invalid length");
  431. bits_sent += (ulg) length;
  432. #endif
  433. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  434. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  435. * unused bits in value.
  436. */
  437. if (bi_valid > (int) Buf_size - length) {
  438. bi_buf |= (value << bi_valid);
  439. put_short(bi_buf);
  440. bi_buf = (ush) value >> (Buf_size - bi_valid);
  441. bi_valid += length - Buf_size;
  442. } else {
  443. bi_buf |= value << bi_valid;
  444. bi_valid += length;
  445. }
  446. }
  447. /* ===========================================================================
  448. * Reverse the first len bits of a code, using straightforward code (a faster
  449. * method would use a table)
  450. * IN assertion: 1 <= len <= 15
  451. */
  452. static unsigned bi_reverse(unsigned code, int len)
  453. {
  454. register unsigned res = 0;
  455. do {
  456. res |= code & 1;
  457. code >>= 1, res <<= 1;
  458. } while (--len > 0);
  459. return res >> 1;
  460. }
  461. /* ===========================================================================
  462. * Write out any remaining bits in an incomplete byte.
  463. */
  464. static void bi_windup(void)
  465. {
  466. if (bi_valid > 8) {
  467. put_short(bi_buf);
  468. } else if (bi_valid > 0) {
  469. put_byte(bi_buf);
  470. }
  471. bi_buf = 0;
  472. bi_valid = 0;
  473. #ifdef DEBUG
  474. bits_sent = (bits_sent + 7) & ~7;
  475. #endif
  476. }
  477. /* ===========================================================================
  478. * Copy a stored block to the zip file, storing first the length and its
  479. * one's complement if requested.
  480. */
  481. static void copy_block(char *buf, unsigned len, int header)
  482. {
  483. bi_windup(); /* align on byte boundary */
  484. if (header) {
  485. put_short((ush) len);
  486. put_short((ush) ~ len);
  487. #ifdef DEBUG
  488. bits_sent += 2 * 16;
  489. #endif
  490. }
  491. #ifdef DEBUG
  492. bits_sent += (ulg) len << 3;
  493. #endif
  494. while (len--) {
  495. put_byte(*buf++);
  496. }
  497. }
  498. /* deflate.c -- compress data using the deflation algorithm
  499. * Copyright (C) 1992-1993 Jean-loup Gailly
  500. * This is free software; you can redistribute it and/or modify it under the
  501. * terms of the GNU General Public License, see the file COPYING.
  502. */
  503. /*
  504. * PURPOSE
  505. *
  506. * Identify new text as repetitions of old text within a fixed-
  507. * length sliding window trailing behind the new text.
  508. *
  509. * DISCUSSION
  510. *
  511. * The "deflation" process depends on being able to identify portions
  512. * of the input text which are identical to earlier input (within a
  513. * sliding window trailing behind the input currently being processed).
  514. *
  515. * The most straightforward technique turns out to be the fastest for
  516. * most input files: try all possible matches and select the longest.
  517. * The key feature of this algorithm is that insertions into the string
  518. * dictionary are very simple and thus fast, and deletions are avoided
  519. * completely. Insertions are performed at each input character, whereas
  520. * string matches are performed only when the previous match ends. So it
  521. * is preferable to spend more time in matches to allow very fast string
  522. * insertions and avoid deletions. The matching algorithm for small
  523. * strings is inspired from that of Rabin & Karp. A brute force approach
  524. * is used to find longer strings when a small match has been found.
  525. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  526. * (by Leonid Broukhis).
  527. * A previous version of this file used a more sophisticated algorithm
  528. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  529. * time, but has a larger average cost, uses more memory and is patented.
  530. * However the F&G algorithm may be faster for some highly redundant
  531. * files if the parameter max_chain_length (described below) is too large.
  532. *
  533. * ACKNOWLEDGMENTS
  534. *
  535. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  536. * I found it in 'freeze' written by Leonid Broukhis.
  537. * Thanks to many info-zippers for bug reports and testing.
  538. *
  539. * REFERENCES
  540. *
  541. * APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
  542. *
  543. * A description of the Rabin and Karp algorithm is given in the book
  544. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  545. *
  546. * Fiala,E.R., and Greene,D.H.
  547. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  548. *
  549. * INTERFACE
  550. *
  551. * void lm_init (int pack_level, ush *flags)
  552. * Initialize the "longest match" routines for a new file
  553. *
  554. * ulg deflate (void)
  555. * Processes a new input file and return its compressed length. Sets
  556. * the compressed length, crc, deflate flags and internal file
  557. * attributes.
  558. */
  559. /* ===========================================================================
  560. * Configuration parameters
  561. */
  562. /* Compile with MEDIUM_MEM to reduce the memory requirements or
  563. * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
  564. * entire input file can be held in memory (not possible on 16 bit systems).
  565. * Warning: defining these symbols affects HASH_BITS (see below) and thus
  566. * affects the compression ratio. The compressed output
  567. * is still correct, and might even be smaller in some cases.
  568. */
  569. #ifdef SMALL_MEM
  570. # define HASH_BITS 13 /* Number of bits used to hash strings */
  571. #endif
  572. #ifdef MEDIUM_MEM
  573. # define HASH_BITS 14
  574. #endif
  575. #ifndef HASH_BITS
  576. # define HASH_BITS 15
  577. /* For portability to 16 bit machines, do not use values above 15. */
  578. #endif
  579. /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
  580. * window with tab_suffix. Check that we can do this:
  581. */
  582. #if (WSIZE<<1) > (1<<BITS)
  583. # error cannot overlay window with tab_suffix and prev with tab_prefix0
  584. #endif
  585. #if HASH_BITS > BITS-1
  586. # error cannot overlay head with tab_prefix1
  587. #endif
  588. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  589. #define HASH_MASK (HASH_SIZE-1)
  590. #define WMASK (WSIZE-1)
  591. /* HASH_SIZE and WSIZE must be powers of two */
  592. #define NIL 0
  593. /* Tail of hash chains */
  594. #define FAST 4
  595. #define SLOW 2
  596. /* speed options for the general purpose bit flag */
  597. #ifndef TOO_FAR
  598. # define TOO_FAR 4096
  599. #endif
  600. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  601. /* ===========================================================================
  602. * Local data used by the "longest match" routines.
  603. */
  604. typedef ush Pos;
  605. typedef unsigned IPos;
  606. /* A Pos is an index in the character window. We use short instead of int to
  607. * save space in the various tables. IPos is used only for parameter passing.
  608. */
  609. /* DECLARE(uch, window, 2L*WSIZE); */
  610. /* Sliding window. Input bytes are read into the second half of the window,
  611. * and move to the first half later to keep a dictionary of at least WSIZE
  612. * bytes. With this organization, matches are limited to a distance of
  613. * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  614. * performed with a length multiple of the block size. Also, it limits
  615. * the window size to 64K, which is quite useful on MSDOS.
  616. * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
  617. * be less efficient).
  618. */
  619. /* DECLARE(Pos, prev, WSIZE); */
  620. /* Link to older string with same hash index. To limit the size of this
  621. * array to 64K, this link is maintained only for the last 32K strings.
  622. * An index in this array is thus a window index modulo 32K.
  623. */
  624. /* DECLARE(Pos, head, 1<<HASH_BITS); */
  625. /* Heads of the hash chains or NIL. */
  626. static const ulg window_size = (ulg) 2 * WSIZE;
  627. /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  628. * input file length plus MIN_LOOKAHEAD.
  629. */
  630. static long block_start;
  631. /* window position at the beginning of the current output block. Gets
  632. * negative when the window is moved backwards.
  633. */
  634. static unsigned ins_h; /* hash index of string to be inserted */
  635. #define H_SHIFT ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
  636. /* Number of bits by which ins_h and del_h must be shifted at each
  637. * input step. It must be such that after MIN_MATCH steps, the oldest
  638. * byte no longer takes part in the hash key, that is:
  639. * H_SHIFT * MIN_MATCH >= HASH_BITS
  640. */
  641. static unsigned int prev_length;
  642. /* Length of the best match at previous step. Matches not greater than this
  643. * are discarded. This is used in the lazy match evaluation.
  644. */
  645. static unsigned strstart; /* start of string to insert */
  646. static unsigned match_start; /* start of matching string */
  647. static int eofile; /* flag set at end of input file */
  648. static unsigned lookahead; /* number of valid bytes ahead in window */
  649. static const unsigned max_chain_length = 4096;
  650. /* To speed up deflation, hash chains are never searched beyond this length.
  651. * A higher limit improves compression ratio but degrades the speed.
  652. */
  653. static const unsigned int max_lazy_match = 258;
  654. /* Attempt to find a better match only when the current match is strictly
  655. * smaller than this value. This mechanism is used only for compression
  656. * levels >= 4.
  657. */
  658. #define max_insert_length max_lazy_match
  659. /* Insert new strings in the hash table only if the match length
  660. * is not greater than this length. This saves time but degrades compression.
  661. * max_insert_length is used only for compression levels <= 3.
  662. */
  663. static const unsigned good_match = 32;
  664. /* Use a faster search when the previous match is longer than this */
  665. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  666. * the desired pack level (0..9). The values given below have been tuned to
  667. * exclude worst case performance for pathological files. Better values may be
  668. * found for specific files.
  669. */
  670. static const int nice_match = 258; /* Stop searching when current match exceeds this */
  671. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  672. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  673. * meaning.
  674. */
  675. #define EQUAL 0
  676. /* result of memcmp for equal strings */
  677. /* ===========================================================================
  678. * Prototypes for local functions.
  679. */
  680. static void fill_window(void);
  681. static int longest_match(IPos cur_match);
  682. #ifdef DEBUG
  683. static void check_match(IPos start, IPos match, int length);
  684. #endif
  685. /* ===========================================================================
  686. * Update a hash value with the given input byte
  687. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  688. * input characters, so that a running hash key can be computed from the
  689. * previous key instead of complete recalculation each time.
  690. */
  691. #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  692. /* ===========================================================================
  693. * Insert string s in the dictionary and set match_head to the previous head
  694. * of the hash chain (the most recent string with same hash key). Return
  695. * the previous length of the hash chain.
  696. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  697. * input characters and the first MIN_MATCH bytes of s are valid
  698. * (except for the last MIN_MATCH-1 bytes of the input file).
  699. */
  700. #define INSERT_STRING(s, match_head) \
  701. (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
  702. prev[(s) & WMASK] = match_head = head[ins_h], \
  703. head[ins_h] = (s))
  704. /* ===========================================================================
  705. * Initialize the "longest match" routines for a new file
  706. */
  707. static void lm_init(ush * flags)
  708. {
  709. register unsigned j;
  710. /* Initialize the hash table. */
  711. memset(head, 0, HASH_SIZE * sizeof(*head));
  712. /* prev will be initialized on the fly */
  713. *flags |= SLOW;
  714. /* ??? reduce max_chain_length for binary files */
  715. strstart = 0;
  716. block_start = 0L;
  717. lookahead = read_buf((char *) window,
  718. sizeof(int) <= 2 ? (unsigned) WSIZE : 2 * WSIZE);
  719. if (lookahead == 0 || lookahead == (unsigned) EOF) {
  720. eofile = 1, lookahead = 0;
  721. return;
  722. }
  723. eofile = 0;
  724. /* Make sure that we always have enough lookahead. This is important
  725. * if input comes from a device such as a tty.
  726. */
  727. while (lookahead < MIN_LOOKAHEAD && !eofile)
  728. fill_window();
  729. ins_h = 0;
  730. for (j = 0; j < MIN_MATCH - 1; j++)
  731. UPDATE_HASH(ins_h, window[j]);
  732. /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  733. * not important since only literal bytes will be emitted.
  734. */
  735. }
  736. /* ===========================================================================
  737. * Set match_start to the longest match starting at the given string and
  738. * return its length. Matches shorter or equal to prev_length are discarded,
  739. * in which case the result is equal to prev_length and match_start is
  740. * garbage.
  741. * IN assertions: cur_match is the head of the hash chain for the current
  742. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  743. */
  744. /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
  745. * match.s. The code is functionally equivalent, so you can use the C version
  746. * if desired.
  747. */
  748. static int longest_match(IPos cur_match)
  749. {
  750. unsigned chain_length = max_chain_length; /* max hash chain length */
  751. register uch *scan = window + strstart; /* current string */
  752. register uch *match; /* matched string */
  753. register int len; /* length of current match */
  754. int best_len = prev_length; /* best match length so far */
  755. IPos limit =
  756. strstart > (IPos) MAX_DIST ? strstart - (IPos) MAX_DIST : NIL;
  757. /* Stop when cur_match becomes <= limit. To simplify the code,
  758. * we prevent matches with the string of window index 0.
  759. */
  760. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  761. * It is easy to get rid of this optimization if necessary.
  762. */
  763. #if HASH_BITS < 8 || MAX_MATCH != 258
  764. # error Code too clever
  765. #endif
  766. register uch *strend = window + strstart + MAX_MATCH;
  767. register uch scan_end1 = scan[best_len - 1];
  768. register uch scan_end = scan[best_len];
  769. /* Do not waste too much time if we already have a good match: */
  770. if (prev_length >= good_match) {
  771. chain_length >>= 2;
  772. }
  773. Assert(strstart <= window_size - MIN_LOOKAHEAD, "insufficient lookahead");
  774. do {
  775. Assert(cur_match < strstart, "no future");
  776. match = window + cur_match;
  777. /* Skip to next match if the match length cannot increase
  778. * or if the match length is less than 2:
  779. */
  780. if (match[best_len] != scan_end ||
  781. match[best_len - 1] != scan_end1 ||
  782. *match != *scan || *++match != scan[1])
  783. continue;
  784. /* The check at best_len-1 can be removed because it will be made
  785. * again later. (This heuristic is not always a win.)
  786. * It is not necessary to compare scan[2] and match[2] since they
  787. * are always equal when the other bytes match, given that
  788. * the hash keys are equal and that HASH_BITS >= 8.
  789. */
  790. scan += 2, match++;
  791. /* We check for insufficient lookahead only every 8th comparison;
  792. * the 256th check will be made at strstart+258.
  793. */
  794. do {
  795. } while (*++scan == *++match && *++scan == *++match &&
  796. *++scan == *++match && *++scan == *++match &&
  797. *++scan == *++match && *++scan == *++match &&
  798. *++scan == *++match && *++scan == *++match && scan < strend);
  799. len = MAX_MATCH - (int) (strend - scan);
  800. scan = strend - MAX_MATCH;
  801. if (len > best_len) {
  802. match_start = cur_match;
  803. best_len = len;
  804. if (len >= nice_match)
  805. break;
  806. scan_end1 = scan[best_len - 1];
  807. scan_end = scan[best_len];
  808. }
  809. } while ((cur_match = prev[cur_match & WMASK]) > limit
  810. && --chain_length != 0);
  811. return best_len;
  812. }
  813. #ifdef DEBUG
  814. /* ===========================================================================
  815. * Check that the match at match_start is indeed a match.
  816. */
  817. static void check_match(IPos start, IPos match, int length)
  818. {
  819. /* check that the match is indeed a match */
  820. if (memcmp((char *) window + match,
  821. (char *) window + start, length) != EQUAL) {
  822. bb_error_msg(" start %d, match %d, length %d", start, match, length);
  823. bb_error_msg("invalid match");
  824. }
  825. if (verbose > 1) {
  826. bb_error_msg("\\[%d,%d]", start - match, length);
  827. do {
  828. putc(window[start++], stderr);
  829. } while (--length != 0);
  830. }
  831. }
  832. #else
  833. # define check_match(start, match, length)
  834. #endif
  835. /* ===========================================================================
  836. * Fill the window when the lookahead becomes insufficient.
  837. * Updates strstart and lookahead, and sets eofile if end of input file.
  838. * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  839. * OUT assertions: at least one byte has been read, or eofile is set;
  840. * file reads are performed for at least two bytes (required for the
  841. * translate_eol option).
  842. */
  843. static void fill_window(void)
  844. {
  845. register unsigned n, m;
  846. unsigned more =
  847. (unsigned) (window_size - (ulg) lookahead - (ulg) strstart);
  848. /* Amount of free space at the end of the window. */
  849. /* If the window is almost full and there is insufficient lookahead,
  850. * move the upper half to the lower one to make room in the upper half.
  851. */
  852. if (more == (unsigned) EOF) {
  853. /* Very unlikely, but possible on 16 bit machine if strstart == 0
  854. * and lookahead == 1 (input done one byte at time)
  855. */
  856. more--;
  857. } else if (strstart >= WSIZE + MAX_DIST) {
  858. /* By the IN assertion, the window is not empty so we can't confuse
  859. * more == 0 with more == 64K on a 16 bit machine.
  860. */
  861. Assert(window_size == (ulg) 2 * WSIZE, "no sliding with BIG_MEM");
  862. memcpy((char *) window, (char *) window + WSIZE, (unsigned) WSIZE);
  863. match_start -= WSIZE;
  864. strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
  865. block_start -= (long) WSIZE;
  866. for (n = 0; n < HASH_SIZE; n++) {
  867. m = head[n];
  868. head[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
  869. }
  870. for (n = 0; n < WSIZE; n++) {
  871. m = prev[n];
  872. prev[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
  873. /* If n is not on any hash chain, prev[n] is garbage but
  874. * its value will never be used.
  875. */
  876. }
  877. more += WSIZE;
  878. }
  879. /* At this point, more >= 2 */
  880. if (!eofile) {
  881. n = read_buf((char *) window + strstart + lookahead, more);
  882. if (n == 0 || n == (unsigned) EOF) {
  883. eofile = 1;
  884. } else {
  885. lookahead += n;
  886. }
  887. }
  888. }
  889. /* ===========================================================================
  890. * Flush the current block, with given end-of-file flag.
  891. * IN assertion: strstart is set to the end of the current match.
  892. */
  893. #define FLUSH_BLOCK(eof) \
  894. flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
  895. (char*)NULL, (long)strstart - block_start, (eof))
  896. /* ===========================================================================
  897. * Same as above, but achieves better compression. We use a lazy
  898. * evaluation for matches: a match is finally adopted only if there is
  899. * no better match at the next window position.
  900. */
  901. static ulg deflate(void)
  902. {
  903. IPos hash_head; /* head of hash chain */
  904. IPos prev_match; /* previous match */
  905. int flush; /* set if current block must be flushed */
  906. int match_available = 0; /* set if previous match exists */
  907. register unsigned match_length = MIN_MATCH - 1; /* length of best match */
  908. /* Process the input block. */
  909. while (lookahead != 0) {
  910. /* Insert the string window[strstart .. strstart+2] in the
  911. * dictionary, and set hash_head to the head of the hash chain:
  912. */
  913. INSERT_STRING(strstart, hash_head);
  914. /* Find the longest match, discarding those <= prev_length.
  915. */
  916. prev_length = match_length, prev_match = match_start;
  917. match_length = MIN_MATCH - 1;
  918. if (hash_head != NIL && prev_length < max_lazy_match &&
  919. strstart - hash_head <= MAX_DIST) {
  920. /* To simplify the code, we prevent matches with the string
  921. * of window index 0 (in particular we have to avoid a match
  922. * of the string with itself at the start of the input file).
  923. */
  924. match_length = longest_match(hash_head);
  925. /* longest_match() sets match_start */
  926. if (match_length > lookahead)
  927. match_length = lookahead;
  928. /* Ignore a length 3 match if it is too distant: */
  929. if (match_length == MIN_MATCH && strstart - match_start > TOO_FAR) {
  930. /* If prev_match is also MIN_MATCH, match_start is garbage
  931. * but we will ignore the current match anyway.
  932. */
  933. match_length--;
  934. }
  935. }
  936. /* If there was a match at the previous step and the current
  937. * match is not better, output the previous match:
  938. */
  939. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  940. check_match(strstart - 1, prev_match, prev_length);
  941. flush =
  942. ct_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  943. /* Insert in hash table all strings up to the end of the match.
  944. * strstart-1 and strstart are already inserted.
  945. */
  946. lookahead -= prev_length - 1;
  947. prev_length -= 2;
  948. do {
  949. strstart++;
  950. INSERT_STRING(strstart, hash_head);
  951. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  952. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  953. * these bytes are garbage, but it does not matter since the
  954. * next lookahead bytes will always be emitted as literals.
  955. */
  956. } while (--prev_length != 0);
  957. match_available = 0;
  958. match_length = MIN_MATCH - 1;
  959. strstart++;
  960. if (flush)
  961. FLUSH_BLOCK(0), block_start = strstart;
  962. } else if (match_available) {
  963. /* If there was no match at the previous position, output a
  964. * single literal. If there was a match but the current match
  965. * is longer, truncate the previous match to a single literal.
  966. */
  967. Tracevv((stderr, "%c", window[strstart - 1]));
  968. if (ct_tally(0, window[strstart - 1])) {
  969. FLUSH_BLOCK(0), block_start = strstart;
  970. }
  971. strstart++;
  972. lookahead--;
  973. } else {
  974. /* There is no previous match to compare with, wait for
  975. * the next step to decide.
  976. */
  977. match_available = 1;
  978. strstart++;
  979. lookahead--;
  980. }
  981. Assert(strstart <= isize && lookahead <= isize, "a bit too far");
  982. /* Make sure that we always have enough lookahead, except
  983. * at the end of the input file. We need MAX_MATCH bytes
  984. * for the next match, plus MIN_MATCH bytes to insert the
  985. * string following the next match.
  986. */
  987. while (lookahead < MIN_LOOKAHEAD && !eofile)
  988. fill_window();
  989. }
  990. if (match_available)
  991. ct_tally(0, window[strstart - 1]);
  992. return FLUSH_BLOCK(1); /* eof */
  993. }
  994. /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
  995. * Copyright (C) 1992-1993 Jean-loup Gailly
  996. * The unzip code was written and put in the public domain by Mark Adler.
  997. * Portions of the lzw code are derived from the public domain 'compress'
  998. * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
  999. * Ken Turkowski, Dave Mack and Peter Jannesen.
  1000. *
  1001. * See the license_msg below and the file COPYING for the software license.
  1002. * See the file algorithm.doc for the compression algorithms and file formats.
  1003. */
  1004. /* Compress files with zip algorithm and 'compress' interface.
  1005. * See usage() and help() functions below for all options.
  1006. * Outputs:
  1007. * file.gz: compressed file with same mode, owner, and utimes
  1008. * or stdout with -c option or if stdin used as input.
  1009. * If the output file name had to be truncated, the original name is kept
  1010. * in the compressed file.
  1011. */
  1012. /* configuration */
  1013. typedef struct dirent dir_type;
  1014. /* ======================================================================== */
  1015. int gzip_main(int argc, char **argv)
  1016. {
  1017. int result;
  1018. int inFileNum;
  1019. int outFileNum;
  1020. struct stat statBuf;
  1021. char *delFileName;
  1022. int tostdout = 0;
  1023. int force = 0;
  1024. int opt;
  1025. while ((opt = getopt(argc, argv, "cf123456789dq")) != -1) {
  1026. switch (opt) {
  1027. case 'c':
  1028. tostdout = 1;
  1029. break;
  1030. case 'f':
  1031. force = 1;
  1032. break;
  1033. /* Ignore 1-9 (compression level) options */
  1034. case '1':
  1035. case '2':
  1036. case '3':
  1037. case '4':
  1038. case '5':
  1039. case '6':
  1040. case '7':
  1041. case '8':
  1042. case '9':
  1043. break;
  1044. case 'q':
  1045. break;
  1046. #ifdef CONFIG_GUNZIP
  1047. case 'd':
  1048. optind = 1;
  1049. return gunzip_main(argc, argv);
  1050. #endif
  1051. default:
  1052. bb_show_usage();
  1053. }
  1054. }
  1055. foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
  1056. if (foreground) {
  1057. (void) signal(SIGINT, abort_gzip);
  1058. }
  1059. #ifdef SIGTERM
  1060. if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
  1061. (void) signal(SIGTERM, abort_gzip);
  1062. }
  1063. #endif
  1064. #ifdef SIGHUP
  1065. if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
  1066. (void) signal(SIGHUP, abort_gzip);
  1067. }
  1068. #endif
  1069. strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix) - 1);
  1070. z_len = strlen(z_suffix);
  1071. /* Allocate all global buffers (for DYN_ALLOC option) */
  1072. ALLOC(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
  1073. ALLOC(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
  1074. ALLOC(ush, d_buf, DIST_BUFSIZE);
  1075. ALLOC(uch, window, 2L * WSIZE);
  1076. ALLOC(ush, tab_prefix, 1L << BITS);
  1077. clear_bufs();
  1078. part_nb = 0;
  1079. if (optind == argc) {
  1080. time_stamp = 0;
  1081. ifile_size = -1L;
  1082. zip(STDIN_FILENO, STDOUT_FILENO);
  1083. } else {
  1084. int i;
  1085. for (i = optind; i < argc; i++) {
  1086. char *path = NULL;
  1087. clear_bufs();
  1088. if (strcmp(argv[i], "-") == 0) {
  1089. time_stamp = 0;
  1090. ifile_size = -1L;
  1091. inFileNum = STDIN_FILENO;
  1092. outFileNum = STDOUT_FILENO;
  1093. } else {
  1094. inFileNum = open(argv[i], O_RDONLY);
  1095. if (inFileNum < 0 || fstat(inFileNum, &statBuf) < 0)
  1096. bb_perror_msg_and_die("%s", argv[i]);
  1097. time_stamp = statBuf.st_ctime;
  1098. ifile_size = statBuf.st_size;
  1099. if (!tostdout) {
  1100. path = xmalloc(strlen(argv[i]) + 4);
  1101. strcpy(path, argv[i]);
  1102. strcat(path, ".gz");
  1103. /* Open output file */
  1104. #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
  1105. outFileNum =
  1106. open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
  1107. #else
  1108. outFileNum = open(path, O_RDWR | O_CREAT | O_EXCL);
  1109. #endif
  1110. if (outFileNum < 0) {
  1111. bb_perror_msg("%s", path);
  1112. free(path);
  1113. continue;
  1114. }
  1115. /* Set permissions on the file */
  1116. fchmod(outFileNum, statBuf.st_mode);
  1117. } else
  1118. outFileNum = STDOUT_FILENO;
  1119. }
  1120. if (path == NULL && isatty(outFileNum) && force == 0) {
  1121. bb_error_msg
  1122. ("compressed data not written to a terminal. Use -f to force compression.");
  1123. free(path);
  1124. continue;
  1125. }
  1126. result = zip(inFileNum, outFileNum);
  1127. if (path != NULL) {
  1128. close(inFileNum);
  1129. close(outFileNum);
  1130. /* Delete the original file */
  1131. if (result == OK)
  1132. delFileName = argv[i];
  1133. else
  1134. delFileName = path;
  1135. if (unlink(delFileName) < 0)
  1136. bb_perror_msg("%s", delFileName);
  1137. }
  1138. free(path);
  1139. }
  1140. }
  1141. return (exit_code);
  1142. }
  1143. /* trees.c -- output deflated data using Huffman coding
  1144. * Copyright (C) 1992-1993 Jean-loup Gailly
  1145. * This is free software; you can redistribute it and/or modify it under the
  1146. * terms of the GNU General Public License, see the file COPYING.
  1147. */
  1148. /*
  1149. * PURPOSE
  1150. *
  1151. * Encode various sets of source values using variable-length
  1152. * binary code trees.
  1153. *
  1154. * DISCUSSION
  1155. *
  1156. * The PKZIP "deflation" process uses several Huffman trees. The more
  1157. * common source values are represented by shorter bit sequences.
  1158. *
  1159. * Each code tree is stored in the ZIP file in a compressed form
  1160. * which is itself a Huffman encoding of the lengths of
  1161. * all the code strings (in ascending order by source values).
  1162. * The actual code strings are reconstructed from the lengths in
  1163. * the UNZIP process, as described in the "application note"
  1164. * (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
  1165. *
  1166. * REFERENCES
  1167. *
  1168. * Lynch, Thomas J.
  1169. * Data Compression: Techniques and Applications, pp. 53-55.
  1170. * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
  1171. *
  1172. * Storer, James A.
  1173. * Data Compression: Methods and Theory, pp. 49-50.
  1174. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  1175. *
  1176. * Sedgewick, R.
  1177. * Algorithms, p290.
  1178. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  1179. *
  1180. * INTERFACE
  1181. *
  1182. * void ct_init (ush *attr, int *methodp)
  1183. * Allocate the match buffer, initialize the various tables and save
  1184. * the location of the internal file attribute (ascii/binary) and
  1185. * method (DEFLATE/STORE)
  1186. *
  1187. * void ct_tally (int dist, int lc);
  1188. * Save the match info and tally the frequency counts.
  1189. *
  1190. * long flush_block (char *buf, ulg stored_len, int eof)
  1191. * Determine the best encoding for the current block: dynamic trees,
  1192. * static trees or store, and output the encoded block to the zip
  1193. * file. Returns the total compressed length for the file so far.
  1194. *
  1195. */
  1196. /* ===========================================================================
  1197. * Constants
  1198. */
  1199. #define MAX_BITS 15
  1200. /* All codes must not exceed MAX_BITS bits */
  1201. #define MAX_BL_BITS 7
  1202. /* Bit length codes must not exceed MAX_BL_BITS bits */
  1203. #define LENGTH_CODES 29
  1204. /* number of length codes, not counting the special END_BLOCK code */
  1205. #define LITERALS 256
  1206. /* number of literal bytes 0..255 */
  1207. #define END_BLOCK 256
  1208. /* end of block literal code */
  1209. #define L_CODES (LITERALS+1+LENGTH_CODES)
  1210. /* number of Literal or Length codes, including the END_BLOCK code */
  1211. #define D_CODES 30
  1212. /* number of distance codes */
  1213. #define BL_CODES 19
  1214. /* number of codes used to transfer the bit lengths */
  1215. typedef uch extra_bits_t;
  1216. /* extra bits for each length code */
  1217. static const extra_bits_t extra_lbits[LENGTH_CODES]
  1218. = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
  1219. 4, 4, 5, 5, 5, 5, 0
  1220. };
  1221. /* extra bits for each distance code */
  1222. static const extra_bits_t extra_dbits[D_CODES]
  1223. = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,
  1224. 10, 10, 11, 11, 12, 12, 13, 13
  1225. };
  1226. /* extra bits for each bit length code */
  1227. static const extra_bits_t extra_blbits[BL_CODES]
  1228. = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 };
  1229. #define STORED_BLOCK 0
  1230. #define STATIC_TREES 1
  1231. #define DYN_TREES 2
  1232. /* The three kinds of block type */
  1233. #ifndef LIT_BUFSIZE
  1234. # ifdef SMALL_MEM
  1235. # define LIT_BUFSIZE 0x2000
  1236. # else
  1237. # ifdef MEDIUM_MEM
  1238. # define LIT_BUFSIZE 0x4000
  1239. # else
  1240. # define LIT_BUFSIZE 0x8000
  1241. # endif
  1242. # endif
  1243. #endif
  1244. #ifndef DIST_BUFSIZE
  1245. # define DIST_BUFSIZE LIT_BUFSIZE
  1246. #endif
  1247. /* Sizes of match buffers for literals/lengths and distances. There are
  1248. * 4 reasons for limiting LIT_BUFSIZE to 64K:
  1249. * - frequencies can be kept in 16 bit counters
  1250. * - if compression is not successful for the first block, all input data is
  1251. * still in the window so we can still emit a stored block even when input
  1252. * comes from standard input. (This can also be done for all blocks if
  1253. * LIT_BUFSIZE is not greater than 32K.)
  1254. * - if compression is not successful for a file smaller than 64K, we can
  1255. * even emit a stored file instead of a stored block (saving 5 bytes).
  1256. * - creating new Huffman trees less frequently may not provide fast
  1257. * adaptation to changes in the input data statistics. (Take for
  1258. * example a binary file with poorly compressible code followed by
  1259. * a highly compressible string table.) Smaller buffer sizes give
  1260. * fast adaptation but have of course the overhead of transmitting trees
  1261. * more frequently.
  1262. * - I can't count above 4
  1263. * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
  1264. * memory at the expense of compression). Some optimizations would be possible
  1265. * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
  1266. */
  1267. #if LIT_BUFSIZE > INBUFSIZ
  1268. #error cannot overlay l_buf and inbuf
  1269. #endif
  1270. #define REP_3_6 16
  1271. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  1272. #define REPZ_3_10 17
  1273. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  1274. #define REPZ_11_138 18
  1275. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  1276. /* ===========================================================================
  1277. * Local data
  1278. */
  1279. /* Data structure describing a single value and its code string. */
  1280. typedef struct ct_data {
  1281. union {
  1282. ush freq; /* frequency count */
  1283. ush code; /* bit string */
  1284. } fc;
  1285. union {
  1286. ush dad; /* father node in Huffman tree */
  1287. ush len; /* length of bit string */
  1288. } dl;
  1289. } ct_data;
  1290. #define Freq fc.freq
  1291. #define Code fc.code
  1292. #define Dad dl.dad
  1293. #define Len dl.len
  1294. #define HEAP_SIZE (2*L_CODES+1)
  1295. /* maximum heap size */
  1296. static ct_data dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  1297. static ct_data dyn_dtree[2 * D_CODES + 1]; /* distance tree */
  1298. static ct_data static_ltree[L_CODES + 2];
  1299. /* The static literal tree. Since the bit lengths are imposed, there is no
  1300. * need for the L_CODES extra codes used during heap construction. However
  1301. * The codes 286 and 287 are needed to build a canonical tree (see ct_init
  1302. * below).
  1303. */
  1304. static ct_data static_dtree[D_CODES];
  1305. /* The static distance tree. (Actually a trivial tree since all codes use
  1306. * 5 bits.)
  1307. */
  1308. static ct_data bl_tree[2 * BL_CODES + 1];
  1309. /* Huffman tree for the bit lengths */
  1310. typedef struct tree_desc {
  1311. ct_data *dyn_tree; /* the dynamic tree */
  1312. ct_data *static_tree; /* corresponding static tree or NULL */
  1313. const extra_bits_t *extra_bits; /* extra bits for each code or NULL */
  1314. int extra_base; /* base index for extra_bits */
  1315. int elems; /* max number of elements in the tree */
  1316. int max_length; /* max bit length for the codes */
  1317. int max_code; /* largest code with non zero frequency */
  1318. } tree_desc;
  1319. static tree_desc l_desc =
  1320. { dyn_ltree, static_ltree, extra_lbits, LITERALS + 1, L_CODES,
  1321. MAX_BITS, 0
  1322. };
  1323. static tree_desc d_desc =
  1324. { dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0 };
  1325. static tree_desc bl_desc =
  1326. { bl_tree, (ct_data *) 0, extra_blbits, 0, BL_CODES, MAX_BL_BITS,
  1327. 0
  1328. };
  1329. static ush bl_count[MAX_BITS + 1];
  1330. /* number of codes at each bit length for an optimal tree */
  1331. static const uch bl_order[BL_CODES]
  1332. = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
  1333. /* The lengths of the bit length codes are sent in order of decreasing
  1334. * probability, to avoid transmitting the lengths for unused bit length codes.
  1335. */
  1336. static int heap[2 * L_CODES + 1]; /* heap used to build the Huffman trees */
  1337. static int heap_len; /* number of elements in the heap */
  1338. static int heap_max; /* element of largest frequency */
  1339. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  1340. * The same heap array is used to build all trees.
  1341. */
  1342. static uch depth[2 * L_CODES + 1];
  1343. /* Depth of each subtree used as tie breaker for trees of equal frequency */
  1344. static uch length_code[MAX_MATCH - MIN_MATCH + 1];
  1345. /* length code for each normalized match length (0 == MIN_MATCH) */
  1346. static uch dist_code[512];
  1347. /* distance codes. The first 256 values correspond to the distances
  1348. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  1349. * the 15 bit distances.
  1350. */
  1351. static int base_length[LENGTH_CODES];
  1352. /* First normalized length for each code (0 = MIN_MATCH) */
  1353. static int base_dist[D_CODES];
  1354. /* First normalized distance for each code (0 = distance of 1) */
  1355. #define l_buf inbuf
  1356. /* DECLARE(uch, l_buf, LIT_BUFSIZE); buffer for literals or lengths */
  1357. /* DECLARE(ush, d_buf, DIST_BUFSIZE); buffer for distances */
  1358. static uch flag_buf[(LIT_BUFSIZE / 8)];
  1359. /* flag_buf is a bit array distinguishing literals from lengths in
  1360. * l_buf, thus indicating the presence or absence of a distance.
  1361. */
  1362. static unsigned last_lit; /* running index in l_buf */
  1363. static unsigned last_dist; /* running index in d_buf */
  1364. static unsigned last_flags; /* running index in flag_buf */
  1365. static uch flags; /* current flags not yet saved in flag_buf */
  1366. static uch flag_bit; /* current bit used in flags */
  1367. /* bits are filled in flags starting at bit 0 (least significant).
  1368. * Note: these flags are overkill in the current code since we don't
  1369. * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
  1370. */
  1371. static ulg opt_len; /* bit length of current block with optimal trees */
  1372. static ulg static_len; /* bit length of current block with static trees */
  1373. static ulg compressed_len; /* total bit length of compressed file */
  1374. static ush *file_type; /* pointer to UNKNOWN, BINARY or ASCII */
  1375. static int *file_method; /* pointer to DEFLATE or STORE */
  1376. /* ===========================================================================
  1377. * Local (static) routines in this file.
  1378. */
  1379. static void init_block(void);
  1380. static void pqdownheap(ct_data * tree, int k);
  1381. static void gen_bitlen(tree_desc * desc);
  1382. static void gen_codes(ct_data * tree, int max_code);
  1383. static void build_tree(tree_desc * desc);
  1384. static void scan_tree(ct_data * tree, int max_code);
  1385. static void send_tree(ct_data * tree, int max_code);
  1386. static int build_bl_tree(void);
  1387. static void send_all_trees(int lcodes, int dcodes, int blcodes);
  1388. static void compress_block(ct_data * ltree, ct_data * dtree);
  1389. static void set_file_type(void);
  1390. #ifndef DEBUG
  1391. # define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
  1392. /* Send a code of the given tree. c and tree must not have side effects */
  1393. #else /* DEBUG */
  1394. # define send_code(c, tree) \
  1395. { if (verbose>1) bb_error_msg("\ncd %3d ",(c)); \
  1396. send_bits(tree[c].Code, tree[c].Len); }
  1397. #endif
  1398. #define d_code(dist) \
  1399. ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
  1400. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  1401. * must not have side effects. dist_code[256] and dist_code[257] are never
  1402. * used.
  1403. */
  1404. /* the arguments must not have side effects */
  1405. /* ===========================================================================
  1406. * Allocate the match buffer, initialize the various tables and save the
  1407. * location of the internal file attribute (ascii/binary) and method
  1408. * (DEFLATE/STORE).
  1409. */
  1410. static void ct_init(ush * attr, int *methodp)
  1411. {
  1412. int n; /* iterates over tree elements */
  1413. int bits; /* bit counter */
  1414. int length; /* length value */
  1415. int code; /* code value */
  1416. int dist; /* distance index */
  1417. file_type = attr;
  1418. file_method = methodp;
  1419. compressed_len = 0L;
  1420. if (static_dtree[0].Len != 0)
  1421. return; /* ct_init already called */
  1422. /* Initialize the mapping length (0..255) -> length code (0..28) */
  1423. length = 0;
  1424. for (code = 0; code < LENGTH_CODES - 1; code++) {
  1425. base_length[code] = length;
  1426. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  1427. length_code[length++] = (uch) code;
  1428. }
  1429. }
  1430. Assert(length == 256, "ct_init: length != 256");
  1431. /* Note that the length 255 (match length 258) can be represented
  1432. * in two different ways: code 284 + 5 bits or code 285, so we
  1433. * overwrite length_code[255] to use the best encoding:
  1434. */
  1435. length_code[length - 1] = (uch) code;
  1436. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  1437. dist = 0;
  1438. for (code = 0; code < 16; code++) {
  1439. base_dist[code] = dist;
  1440. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  1441. dist_code[dist++] = (uch) code;
  1442. }
  1443. }
  1444. Assert(dist == 256, "ct_init: dist != 256");
  1445. dist >>= 7; /* from now on, all distances are divided by 128 */
  1446. for (; code < D_CODES; code++) {
  1447. base_dist[code] = dist << 7;
  1448. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  1449. dist_code[256 + dist++] = (uch) code;
  1450. }
  1451. }
  1452. Assert(dist == 256, "ct_init: 256+dist != 512");
  1453. /* Construct the codes of the static literal tree */
  1454. for (bits = 0; bits <= MAX_BITS; bits++)
  1455. bl_count[bits] = 0;
  1456. n = 0;
  1457. while (n <= 143)
  1458. static_ltree[n++].Len = 8, bl_count[8]++;
  1459. while (n <= 255)
  1460. static_ltree[n++].Len = 9, bl_count[9]++;
  1461. while (n <= 279)
  1462. static_ltree[n++].Len = 7, bl_count[7]++;
  1463. while (n <= 287)
  1464. static_ltree[n++].Len = 8, bl_count[8]++;
  1465. /* Codes 286 and 287 do not exist, but we must include them in the
  1466. * tree construction to get a canonical Huffman tree (longest code
  1467. * all ones)
  1468. */
  1469. gen_codes((ct_data *) static_ltree, L_CODES + 1);
  1470. /* The static distance tree is trivial: */
  1471. for (n = 0; n < D_CODES; n++) {
  1472. static_dtree[n].Len = 5;
  1473. static_dtree[n].Code = bi_reverse(n, 5);
  1474. }
  1475. /* Initialize the first block of the first file: */
  1476. init_block();
  1477. }
  1478. /* ===========================================================================
  1479. * Initialize a new block.
  1480. */
  1481. static void init_block(void)
  1482. {
  1483. int n; /* iterates over tree elements */
  1484. /* Initialize the trees. */
  1485. for (n = 0; n < L_CODES; n++)
  1486. dyn_ltree[n].Freq = 0;
  1487. for (n = 0; n < D_CODES; n++)
  1488. dyn_dtree[n].Freq = 0;
  1489. for (n = 0; n < BL_CODES; n++)
  1490. bl_tree[n].Freq = 0;
  1491. dyn_ltree[END_BLOCK].Freq = 1;
  1492. opt_len = static_len = 0L;
  1493. last_lit = last_dist = last_flags = 0;
  1494. flags = 0;
  1495. flag_bit = 1;
  1496. }
  1497. #define SMALLEST 1
  1498. /* Index within the heap array of least frequent node in the Huffman tree */
  1499. /* ===========================================================================
  1500. * Remove the smallest element from the heap and recreate the heap with
  1501. * one less element. Updates heap and heap_len.
  1502. */
  1503. #define pqremove(tree, top) \
  1504. {\
  1505. top = heap[SMALLEST]; \
  1506. heap[SMALLEST] = heap[heap_len--]; \
  1507. pqdownheap(tree, SMALLEST); \
  1508. }
  1509. /* ===========================================================================
  1510. * Compares to subtrees, using the tree depth as tie breaker when
  1511. * the subtrees have equal frequency. This minimizes the worst case length.
  1512. */
  1513. #define smaller(tree, n, m) \
  1514. (tree[n].Freq < tree[m].Freq || \
  1515. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  1516. /* ===========================================================================
  1517. * Restore the heap property by moving down the tree starting at node k,
  1518. * exchanging a node with the smallest of its two sons if necessary, stopping
  1519. * when the heap property is re-established (each father smaller than its
  1520. * two sons).
  1521. */
  1522. static void pqdownheap(ct_data * tree, int k)
  1523. {
  1524. int v = heap[k];
  1525. int j = k << 1; /* left son of k */
  1526. while (j <= heap_len) {
  1527. /* Set j to the smallest of the two sons: */
  1528. if (j < heap_len && smaller(tree, heap[j + 1], heap[j]))
  1529. j++;
  1530. /* Exit if v is smaller than both sons */
  1531. if (smaller(tree, v, heap[j]))
  1532. break;
  1533. /* Exchange v with the smallest son */
  1534. heap[k] = heap[j];
  1535. k = j;
  1536. /* And continue down the tree, setting j to the left son of k */
  1537. j <<= 1;
  1538. }
  1539. heap[k] = v;
  1540. }
  1541. /* ===========================================================================
  1542. * Compute the optimal bit lengths for a tree and update the total bit length
  1543. * for the current block.
  1544. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  1545. * above are the tree nodes sorted by increasing frequency.
  1546. * OUT assertions: the field len is set to the optimal bit length, the
  1547. * array bl_count contains the frequencies for each bit length.
  1548. * The length opt_len is updated; static_len is also updated if stree is
  1549. * not null.
  1550. */
  1551. static void gen_bitlen(tree_desc * desc)
  1552. {
  1553. ct_data *tree = desc->dyn_tree;
  1554. const extra_bits_t *extra = desc->extra_bits;
  1555. int base = desc->extra_base;
  1556. int max_code = desc->max_code;
  1557. int max_length = desc->max_length;
  1558. ct_data *stree = desc->static_tree;
  1559. int h; /* heap index */
  1560. int n, m; /* iterate over the tree elements */
  1561. int bits; /* bit length */
  1562. int xbits; /* extra bits */
  1563. ush f; /* frequency */
  1564. int overflow = 0; /* number of elements with bit length too large */
  1565. for (bits = 0; bits <= MAX_BITS; bits++)
  1566. bl_count[bits] = 0;
  1567. /* In a first pass, compute the optimal bit lengths (which may
  1568. * overflow in the case of the bit length tree).
  1569. */
  1570. tree[heap[heap_max]].Len = 0; /* root of the heap */
  1571. for (h = heap_max + 1; h < HEAP_SIZE; h++) {
  1572. n = heap[h];
  1573. bits = tree[tree[n].Dad].Len + 1;
  1574. if (bits > max_length)
  1575. bits = max_length, overflow++;
  1576. tree[n].Len = (ush) bits;
  1577. /* We overwrite tree[n].Dad which is no longer needed */
  1578. if (n > max_code)
  1579. continue; /* not a leaf node */
  1580. bl_count[bits]++;
  1581. xbits = 0;
  1582. if (n >= base)
  1583. xbits = extra[n - base];
  1584. f = tree[n].Freq;
  1585. opt_len += (ulg) f *(bits + xbits);
  1586. if (stree)
  1587. static_len += (ulg) f *(stree[n].Len + xbits);
  1588. }
  1589. if (overflow == 0)
  1590. return;
  1591. Trace((stderr, "\nbit length overflow\n"));
  1592. /* This happens for example on obj2 and pic of the Calgary corpus */
  1593. /* Find the first bit length which could increase: */
  1594. do {
  1595. bits = max_length - 1;
  1596. while (bl_count[bits] == 0)
  1597. bits--;
  1598. bl_count[bits]--; /* move one leaf down the tree */
  1599. bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  1600. bl_count[max_length]--;
  1601. /* The brother of the overflow item also moves one step up,
  1602. * but this does not affect bl_count[max_length]
  1603. */
  1604. overflow -= 2;
  1605. } while (overflow > 0);
  1606. /* Now recompute all bit lengths, scanning in increasing frequency.
  1607. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  1608. * lengths instead of fixing only the wrong ones. This idea is taken
  1609. * from 'ar' written by Haruhiko Okumura.)
  1610. */
  1611. for (bits = max_length; bits != 0; bits--) {
  1612. n = bl_count[bits];
  1613. while (n != 0) {
  1614. m = heap[--h];
  1615. if (m > max_code)
  1616. continue;
  1617. if (tree[m].Len != (unsigned) bits) {
  1618. Trace((stderr, "code %d bits %d->%d\n", m, tree[m].Len,
  1619. bits));
  1620. opt_len +=
  1621. ((long) bits - (long) tree[m].Len) * (long) tree[m].Freq;
  1622. tree[m].Len = (ush) bits;
  1623. }
  1624. n--;
  1625. }
  1626. }
  1627. }
  1628. /* ===========================================================================
  1629. * Generate the codes for a given tree and bit counts (which need not be
  1630. * optimal).
  1631. * IN assertion: the array bl_count contains the bit length statistics for
  1632. * the given tree and the field len is set for all tree elements.
  1633. * OUT assertion: the field code is set for all tree elements of non
  1634. * zero code length.
  1635. */
  1636. static void gen_codes(ct_data * tree, int max_code)
  1637. {
  1638. ush next_code[MAX_BITS + 1]; /* next code value for each bit length */
  1639. ush code = 0; /* running code value */
  1640. int bits; /* bit index */
  1641. int n; /* code index */
  1642. /* The distribution counts are first used to generate the code values
  1643. * without bit reversal.
  1644. */
  1645. for (bits = 1; bits <= MAX_BITS; bits++) {
  1646. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  1647. }
  1648. /* Check that the bit counts in bl_count are consistent. The last code
  1649. * must be all ones.
  1650. */
  1651. Assert(code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
  1652. "inconsistent bit counts");
  1653. Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
  1654. for (n = 0; n <= max_code; n++) {
  1655. int len = tree[n].Len;
  1656. if (len == 0)
  1657. continue;
  1658. /* Now reverse the bits */
  1659. tree[n].Code = bi_reverse(next_code[len]++, len);
  1660. Tracec(tree != static_ltree,
  1661. (stderr, "\nn %3d %c l %2d c %4x (%x) ", n,
  1662. (isgraph(n) ? n : ' '), len, tree[n].Code,
  1663. next_code[len] - 1));
  1664. }
  1665. }
  1666. /* ===========================================================================
  1667. * Construct one Huffman tree and assigns the code bit strings and lengths.
  1668. * Update the total bit length for the current block.
  1669. * IN assertion: the field freq is set for all tree elements.
  1670. * OUT assertions: the fields len and code are set to the optimal bit length
  1671. * and corresponding code. The length opt_len is updated; static_len is
  1672. * also updated if stree is not null. The field max_code is set.
  1673. */
  1674. static void build_tree(tree_desc * desc)
  1675. {
  1676. ct_data *tree = desc->dyn_tree;
  1677. ct_data *stree = desc->static_tree;
  1678. int elems = desc->elems;
  1679. int n, m; /* iterate over heap elements */
  1680. int max_code = -1; /* largest code with non zero frequency */
  1681. int node = elems; /* next internal node of the tree */
  1682. /* Construct the initial heap, with least frequent element in
  1683. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  1684. * heap[0] is not used.
  1685. */
  1686. heap_len = 0, heap_max = HEAP_SIZE;
  1687. for (n = 0; n < elems; n++) {
  1688. if (tree[n].Freq != 0) {
  1689. heap[++heap_len] = max_code = n;
  1690. depth[n] = 0;
  1691. } else {
  1692. tree[n].Len = 0;
  1693. }
  1694. }
  1695. /* The pkzip format requires that at least one distance code exists,
  1696. * and that at least one bit should be sent even if there is only one
  1697. * possible code. So to avoid special checks later on we force at least
  1698. * two codes of non zero frequency.
  1699. */
  1700. while (heap_len < 2) {
  1701. int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
  1702. tree[new].Freq = 1;
  1703. depth[new] = 0;
  1704. opt_len--;
  1705. if (stree)
  1706. static_len -= stree[new].Len;
  1707. /* new is 0 or 1 so it does not have extra bits */
  1708. }
  1709. desc->max_code = max_code;
  1710. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  1711. * establish sub-heaps of increasing lengths:
  1712. */
  1713. for (n = heap_len / 2; n >= 1; n--)
  1714. pqdownheap(tree, n);
  1715. /* Construct the Huffman tree by repeatedly combining the least two
  1716. * frequent nodes.
  1717. */
  1718. do {
  1719. pqremove(tree, n); /* n = node of least frequency */
  1720. m = heap[SMALLEST]; /* m = node of next least frequency */
  1721. heap[--heap_max] = n; /* keep the nodes sorted by frequency */
  1722. heap[--heap_max] = m;
  1723. /* Create a new node father of n and m */
  1724. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  1725. depth[node] = (uch) (MAX(depth[n], depth[m]) + 1);
  1726. tree[n].Dad = tree[m].Dad = (ush) node;
  1727. #ifdef DUMP_BL_TREE
  1728. if (tree == bl_tree) {
  1729. bb_error_msg("\nnode %d(%d), sons %d(%d) %d(%d)",
  1730. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  1731. }
  1732. #endif
  1733. /* and insert the new node in the heap */
  1734. heap[SMALLEST] = node++;
  1735. pqdownheap(tree, SMALLEST);
  1736. } while (heap_len >= 2);
  1737. heap[--heap_max] = heap[SMALLEST];
  1738. /* At this point, the fields freq and dad are set. We can now
  1739. * generate the bit lengths.
  1740. */
  1741. gen_bitlen((tree_desc *) desc);
  1742. /* The field len is now set, we can generate the bit codes */
  1743. gen_codes((ct_data *) tree, max_code);
  1744. }
  1745. /* ===========================================================================
  1746. * Scan a literal or distance tree to determine the frequencies of the codes
  1747. * in the bit length tree. Updates opt_len to take into account the repeat
  1748. * counts. (The contribution of the bit length codes will be added later
  1749. * during the construction of bl_tree.)
  1750. */
  1751. static void scan_tree(ct_data * tree, int max_code)
  1752. {
  1753. int n; /* iterates over all tree elements */
  1754. int prevlen = -1; /* last emitted length */
  1755. int curlen; /* length of current code */
  1756. int nextlen = tree[0].Len; /* length of next code */
  1757. int count = 0; /* repeat count of the current code */
  1758. int max_count = 7; /* max repeat count */
  1759. int min_count = 4; /* min repeat count */
  1760. if (nextlen == 0)
  1761. max_count = 138, min_count = 3;
  1762. tree[max_code + 1].Len = (ush) 0xffff; /* guard */
  1763. for (n = 0; n <= max_code; n++) {
  1764. curlen = nextlen;
  1765. nextlen = tree[n + 1].Len;
  1766. if (++count < max_count && curlen == nextlen) {
  1767. continue;
  1768. } else if (count < min_count) {
  1769. bl_tree[curlen].Freq += count;
  1770. } else if (curlen != 0) {
  1771. if (curlen != prevlen)
  1772. bl_tree[curlen].Freq++;
  1773. bl_tree[REP_3_6].Freq++;
  1774. } else if (count <= 10) {
  1775. bl_tree[REPZ_3_10].Freq++;
  1776. } else {
  1777. bl_tree[REPZ_11_138].Freq++;
  1778. }
  1779. count = 0;
  1780. prevlen = curlen;
  1781. if (nextlen == 0) {
  1782. max_count = 138, min_count = 3;
  1783. } else if (curlen == nextlen) {
  1784. max_count = 6, min_count = 3;
  1785. } else {
  1786. max_count = 7, min_count = 4;
  1787. }
  1788. }
  1789. }
  1790. /* ===========================================================================
  1791. * Send a literal or distance tree in compressed form, using the codes in
  1792. * bl_tree.
  1793. */
  1794. static void send_tree(ct_data * tree, int max_code)
  1795. {
  1796. int n; /* iterates over all tree elements */
  1797. int prevlen = -1; /* last emitted length */
  1798. int curlen; /* length of current code */
  1799. int nextlen = tree[0].Len; /* length of next code */
  1800. int count = 0; /* repeat count of the current code */
  1801. int max_count = 7; /* max repeat count */
  1802. int min_count = 4; /* min repeat count */
  1803. /* tree[max_code+1].Len = -1; *//* guard already set */
  1804. if (nextlen == 0)
  1805. max_count = 138, min_count = 3;
  1806. for (n = 0; n <= max_code; n++) {
  1807. curlen = nextlen;
  1808. nextlen = tree[n + 1].Len;
  1809. if (++count < max_count && curlen == nextlen) {
  1810. continue;
  1811. } else if (count < min_count) {
  1812. do {
  1813. send_code(curlen, bl_tree);
  1814. } while (--count != 0);
  1815. } else if (curlen != 0) {
  1816. if (curlen != prevlen) {
  1817. send_code(curlen, bl_tree);
  1818. count--;
  1819. }
  1820. Assert(count >= 3 && count <= 6, " 3_6?");
  1821. send_code(REP_3_6, bl_tree);
  1822. send_bits(count - 3, 2);
  1823. } else if (count <= 10) {
  1824. send_code(REPZ_3_10, bl_tree);
  1825. send_bits(count - 3, 3);
  1826. } else {
  1827. send_code(REPZ_11_138, bl_tree);
  1828. send_bits(count - 11, 7);
  1829. }
  1830. count = 0;
  1831. prevlen = curlen;
  1832. if (nextlen == 0) {
  1833. max_count = 138, min_count = 3;
  1834. } else if (curlen == nextlen) {
  1835. max_count = 6, min_count = 3;
  1836. } else {
  1837. max_count = 7, min_count = 4;
  1838. }
  1839. }
  1840. }
  1841. /* ===========================================================================
  1842. * Construct the Huffman tree for the bit lengths and return the index in
  1843. * bl_order of the last bit length code to send.
  1844. */
  1845. static int build_bl_tree(void)
  1846. {
  1847. int max_blindex; /* index of last bit length code of non zero freq */
  1848. /* Determine the bit length frequencies for literal and distance trees */
  1849. scan_tree((ct_data *) dyn_ltree, l_desc.max_code);
  1850. scan_tree((ct_data *) dyn_dtree, d_desc.max_code);
  1851. /* Build the bit length tree: */
  1852. build_tree((tree_desc *) (&bl_desc));
  1853. /* opt_len now includes the length of the tree representations, except
  1854. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  1855. */
  1856. /* Determine the number of bit length codes to send. The pkzip format
  1857. * requires that at least 4 bit length codes be sent. (appnote.txt says
  1858. * 3 but the actual value used is 4.)
  1859. */
  1860. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  1861. if (bl_tree[bl_order[max_blindex]].Len != 0)
  1862. break;
  1863. }
  1864. /* Update opt_len to include the bit length tree and counts */
  1865. opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  1866. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len, static_len));
  1867. return max_blindex;
  1868. }
  1869. /* ===========================================================================
  1870. * Send the header for a block using dynamic Huffman trees: the counts, the
  1871. * lengths of the bit length codes, the literal tree and the distance tree.
  1872. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  1873. */
  1874. static void send_all_trees(int lcodes, int dcodes, int blcodes)
  1875. {
  1876. int rank; /* index in bl_order */
  1877. Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  1878. Assert(lcodes <= L_CODES && dcodes <= D_CODES
  1879. && blcodes <= BL_CODES, "too many codes");
  1880. Tracev((stderr, "\nbl counts: "));
  1881. send_bits(lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  1882. send_bits(dcodes - 1, 5);
  1883. send_bits(blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  1884. for (rank = 0; rank < blcodes; rank++) {
  1885. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  1886. send_bits(bl_tree[bl_order[rank]].Len, 3);
  1887. }
  1888. Tracev((stderr, "\nbl tree: sent %ld", bits_sent));
  1889. send_tree((ct_data *) dyn_ltree, lcodes - 1); /* send the literal tree */
  1890. Tracev((stderr, "\nlit tree: sent %ld", bits_sent));
  1891. send_tree((ct_data *) dyn_dtree, dcodes - 1); /* send the distance tree */
  1892. Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
  1893. }
  1894. /* ===========================================================================
  1895. * Determine the best encoding for the current block: dynamic trees, static
  1896. * trees or store, and output the encoded block to the zip file. This function
  1897. * returns the total compressed length for the file so far.
  1898. */
  1899. static ulg flush_block(char *buf, ulg stored_len, int eof)
  1900. {
  1901. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  1902. int max_blindex; /* index of last bit length code of non zero freq */
  1903. flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
  1904. /* Check if the file is ascii or binary */
  1905. if (*file_type == (ush) UNKNOWN)
  1906. set_file_type();
  1907. /* Construct the literal and distance trees */
  1908. build_tree((tree_desc *) (&l_desc));
  1909. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
  1910. build_tree((tree_desc *) (&d_desc));
  1911. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", opt_len, static_len));
  1912. /* At this point, opt_len and static_len are the total bit lengths of
  1913. * the compressed block data, excluding the tree representations.
  1914. */
  1915. /* Build the bit length tree for the above two trees, and get the index
  1916. * in bl_order of the last bit length code to send.
  1917. */
  1918. max_blindex = build_bl_tree();
  1919. /* Determine the best encoding. Compute first the block length in bytes */
  1920. opt_lenb = (opt_len + 3 + 7) >> 3;
  1921. static_lenb = (static_len + 3 + 7) >> 3;
  1922. Trace((stderr,
  1923. "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
  1924. opt_lenb, opt_len, static_lenb, static_len, stored_len,
  1925. last_lit, last_dist));
  1926. if (static_lenb <= opt_lenb)
  1927. opt_lenb = static_lenb;
  1928. /* If compression failed and this is the first and last block,
  1929. * and if the zip file can be seeked (to rewrite the local header),
  1930. * the whole file is transformed into a stored file:
  1931. */
  1932. if (stored_len <= opt_lenb && eof && compressed_len == 0L && seekable()) {
  1933. /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  1934. if (buf == (char *) 0)
  1935. bb_error_msg("block vanished");
  1936. copy_block(buf, (unsigned) stored_len, 0); /* without header */
  1937. compressed_len = stored_len << 3;
  1938. *file_method = STORED;
  1939. } else if (stored_len + 4 <= opt_lenb && buf != (char *) 0) {
  1940. /* 4: two words for the lengths */
  1941. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  1942. * Otherwise we can't have processed more than WSIZE input bytes since
  1943. * the last block flush, because compression would have been
  1944. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  1945. * transform a block into a stored block.
  1946. */
  1947. send_bits((STORED_BLOCK << 1) + eof, 3); /* send block type */
  1948. compressed_len = (compressed_len + 3 + 7) & ~7L;
  1949. compressed_len += (stored_len + 4) << 3;
  1950. copy_block(buf, (unsigned) stored_len, 1); /* with header */
  1951. } else if (static_lenb == opt_lenb) {
  1952. send_bits((STATIC_TREES << 1) + eof, 3);
  1953. compress_block((ct_data *) static_ltree, (ct_data *) static_dtree);
  1954. compressed_len += 3 + static_len;
  1955. } else {
  1956. send_bits((DYN_TREES << 1) + eof, 3);
  1957. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1,
  1958. max_blindex + 1);
  1959. compress_block((ct_data *) dyn_ltree, (ct_data *) dyn_dtree);
  1960. compressed_len += 3 + opt_len;
  1961. }
  1962. Assert(compressed_len == bits_sent, "bad compressed size");
  1963. init_block();
  1964. if (eof) {
  1965. bi_windup();
  1966. compressed_len += 7; /* align on byte boundary */
  1967. }
  1968. Tracev((stderr, "\ncomprlen %lu(%lu) ", compressed_len >> 3,
  1969. compressed_len - 7 * eof));
  1970. return compressed_len >> 3;
  1971. }
  1972. /* ===========================================================================
  1973. * Save the match info and tally the frequency counts. Return true if
  1974. * the current block must be flushed.
  1975. */
  1976. static int ct_tally(int dist, int lc)
  1977. {
  1978. l_buf[last_lit++] = (uch) lc;
  1979. if (dist == 0) {
  1980. /* lc is the unmatched char */
  1981. dyn_ltree[lc].Freq++;
  1982. } else {
  1983. /* Here, lc is the match length - MIN_MATCH */
  1984. dist--; /* dist = match distance - 1 */
  1985. Assert((ush) dist < (ush) MAX_DIST &&
  1986. (ush) lc <= (ush) (MAX_MATCH - MIN_MATCH) &&
  1987. (ush) d_code(dist) < (ush) D_CODES, "ct_tally: bad match");
  1988. dyn_ltree[length_code[lc] + LITERALS + 1].Freq++;
  1989. dyn_dtree[d_code(dist)].Freq++;
  1990. d_buf[last_dist++] = (ush) dist;
  1991. flags |= flag_bit;
  1992. }
  1993. flag_bit <<= 1;
  1994. /* Output the flags if they fill a byte: */
  1995. if ((last_lit & 7) == 0) {
  1996. flag_buf[last_flags++] = flags;
  1997. flags = 0, flag_bit = 1;
  1998. }
  1999. /* Try to guess if it is profitable to stop the current block here */
  2000. if ((last_lit & 0xfff) == 0) {
  2001. /* Compute an upper bound for the compressed length */
  2002. ulg out_length = (ulg) last_lit * 8L;
  2003. ulg in_length = (ulg) strstart - block_start;
  2004. int dcode;
  2005. for (dcode = 0; dcode < D_CODES; dcode++) {
  2006. out_length +=
  2007. (ulg) dyn_dtree[dcode].Freq * (5L + extra_dbits[dcode]);
  2008. }
  2009. out_length >>= 3;
  2010. Trace((stderr,
  2011. "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
  2012. last_lit, last_dist, in_length, out_length,
  2013. 100L - out_length * 100L / in_length));
  2014. if (last_dist < last_lit / 2 && out_length < in_length / 2)
  2015. return 1;
  2016. }
  2017. return (last_lit == LIT_BUFSIZE - 1 || last_dist == DIST_BUFSIZE);
  2018. /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
  2019. * on 16 bit machines and because stored blocks are restricted to
  2020. * 64K-1 bytes.
  2021. */
  2022. }
  2023. /* ===========================================================================
  2024. * Send the block data compressed using the given Huffman trees
  2025. */
  2026. static void compress_block(ct_data * ltree, ct_data * dtree)
  2027. {
  2028. unsigned dist; /* distance of matched string */
  2029. int lc; /* match length or unmatched char (if dist == 0) */
  2030. unsigned lx = 0; /* running index in l_buf */
  2031. unsigned dx = 0; /* running index in d_buf */
  2032. unsigned fx = 0; /* running index in flag_buf */
  2033. uch flag = 0; /* current flags */
  2034. unsigned code; /* the code to send */
  2035. int extra; /* number of extra bits to send */
  2036. if (last_lit != 0)
  2037. do {
  2038. if ((lx & 7) == 0)
  2039. flag = flag_buf[fx++];
  2040. lc = l_buf[lx++];
  2041. if ((flag & 1) == 0) {
  2042. send_code(lc, ltree); /* send a literal byte */
  2043. Tracecv(isgraph(lc), (stderr, " '%c' ", lc));
  2044. } else {
  2045. /* Here, lc is the match length - MIN_MATCH */
  2046. code = length_code[lc];
  2047. send_code(code + LITERALS + 1, ltree); /* send the length code */
  2048. extra = extra_lbits[code];
  2049. if (extra != 0) {
  2050. lc -= base_length[code];
  2051. send_bits(lc, extra); /* send the extra length bits */
  2052. }
  2053. dist = d_buf[dx++];
  2054. /* Here, dist is the match distance - 1 */
  2055. code = d_code(dist);
  2056. Assert(code < D_CODES, "bad d_code");
  2057. send_code(code, dtree); /* send the distance code */
  2058. extra = extra_dbits[code];
  2059. if (extra != 0) {
  2060. dist -= base_dist[code];
  2061. send_bits(dist, extra); /* send the extra distance bits */
  2062. }
  2063. } /* literal or match pair ? */
  2064. flag >>= 1;
  2065. } while (lx < last_lit);
  2066. send_code(END_BLOCK, ltree);
  2067. }
  2068. /* ===========================================================================
  2069. * Set the file type to ASCII or BINARY, using a crude approximation:
  2070. * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  2071. * IN assertion: the fields freq of dyn_ltree are set and the total of all
  2072. * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  2073. */
  2074. static void set_file_type(void)
  2075. {
  2076. int n = 0;
  2077. unsigned ascii_freq = 0;
  2078. unsigned bin_freq = 0;
  2079. while (n < 7)
  2080. bin_freq += dyn_ltree[n++].Freq;
  2081. while (n < 128)
  2082. ascii_freq += dyn_ltree[n++].Freq;
  2083. while (n < LITERALS)
  2084. bin_freq += dyn_ltree[n++].Freq;
  2085. *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
  2086. if (*file_type == BINARY && translate_eol) {
  2087. bb_error_msg("-l used on binary file");
  2088. }
  2089. }
  2090. /* zip.c -- compress files to the gzip or pkzip format
  2091. * Copyright (C) 1992-1993 Jean-loup Gailly
  2092. * This is free software; you can redistribute it and/or modify it under the
  2093. * terms of the GNU General Public License, see the file COPYING.
  2094. */
  2095. static ulg crc; /* crc on uncompressed file data */
  2096. static long header_bytes; /* number of bytes in gzip header */
  2097. static void put_long(ulg n)
  2098. {
  2099. put_short((n) & 0xffff);
  2100. put_short(((ulg) (n)) >> 16);
  2101. }
  2102. /* put_header_byte is used for the compressed output
  2103. * - for the initial 4 bytes that can't overflow the buffer.
  2104. */
  2105. #define put_header_byte(c) {outbuf[outcnt++]=(uch)(c);}
  2106. /* ===========================================================================
  2107. * Deflate in to out.
  2108. * IN assertions: the input and output buffers are cleared.
  2109. * The variables time_stamp and save_orig_name are initialized.
  2110. */
  2111. static int zip(int in, int out)
  2112. {
  2113. uch my_flags = 0; /* general purpose bit flags */
  2114. ush attr = 0; /* ascii/binary flag */
  2115. ush deflate_flags = 0; /* pkzip -es, -en or -ex equivalent */
  2116. ifd = in;
  2117. ofd = out;
  2118. outcnt = 0;
  2119. /* Write the header to the gzip file. See algorithm.doc for the format */
  2120. method = DEFLATED;
  2121. put_header_byte(GZIP_MAGIC[0]); /* magic header */
  2122. put_header_byte(GZIP_MAGIC[1]);
  2123. put_header_byte(DEFLATED); /* compression method */
  2124. put_header_byte(my_flags); /* general flags */
  2125. put_long(time_stamp);
  2126. /* Write deflated file to zip file */
  2127. crc = updcrc(0, 0);
  2128. bi_init(out);
  2129. ct_init(&attr, &method);
  2130. lm_init(&deflate_flags);
  2131. put_byte((uch) deflate_flags); /* extra flags */
  2132. put_byte(OS_CODE); /* OS identifier */
  2133. header_bytes = (long) outcnt;
  2134. (void) deflate();
  2135. /* Write the crc and uncompressed size */
  2136. put_long(crc);
  2137. put_long(isize);
  2138. header_bytes += 2 * sizeof(long);
  2139. flush_outbuf();
  2140. return OK;
  2141. }
  2142. /* ===========================================================================
  2143. * Read a new buffer from the current input file, perform end-of-line
  2144. * translation, and update the crc and input file size.
  2145. * IN assertion: size >= 2 (for end-of-line translation)
  2146. */
  2147. static int file_read(char *buf, unsigned size)
  2148. {
  2149. unsigned len;
  2150. Assert(insize == 0, "inbuf not empty");
  2151. len = read(ifd, buf, size);
  2152. if (len == (unsigned) (-1) || len == 0)
  2153. return (int) len;
  2154. crc = updcrc((uch *) buf, len);
  2155. isize += (ulg) len;
  2156. return (int) len;
  2157. }
  2158. /* ===========================================================================
  2159. * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
  2160. * (used for the compressed data only)
  2161. */
  2162. static void flush_outbuf(void)
  2163. {
  2164. if (outcnt == 0)
  2165. return;
  2166. write_buf(ofd, (char *) outbuf, outcnt);
  2167. outcnt = 0;
  2168. }