gzip.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115
  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. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  17. */
  18. /* big objects in bss:
  19. * 00000020 b bl_count
  20. * 00000074 b base_length
  21. * 00000078 b base_dist
  22. * 00000078 b static_dtree
  23. * 0000009c b bl_tree
  24. * 000000f4 b dyn_dtree
  25. * 00000100 b length_code
  26. * 00000200 b dist_code
  27. * 0000023d b depth
  28. * 00000400 b flag_buf
  29. * 0000047a b heap
  30. * 00000480 b static_ltree
  31. * 000008f4 b dyn_ltree
  32. */
  33. /* TODO: full support for -v for DESKTOP
  34. * "/usr/bin/gzip -v a bogus aa" should say:
  35. a: 85.1% -- replaced with a.gz
  36. gzip: bogus: No such file or directory
  37. aa: 85.1% -- replaced with aa.gz
  38. */
  39. #include "libbb.h"
  40. #include "unarchive.h"
  41. /* ===========================================================================
  42. */
  43. //#define DEBUG 1
  44. /* Diagnostic functions */
  45. #ifdef DEBUG
  46. # define Assert(cond,msg) { if (!(cond)) bb_error_msg(msg); }
  47. # define Trace(x) fprintf x
  48. # define Tracev(x) {if (verbose) fprintf x; }
  49. # define Tracevv(x) {if (verbose > 1) fprintf x; }
  50. # define Tracec(c,x) {if (verbose && (c)) fprintf x; }
  51. # define Tracecv(c,x) {if (verbose > 1 && (c)) fprintf x; }
  52. #else
  53. # define Assert(cond,msg)
  54. # define Trace(x)
  55. # define Tracev(x)
  56. # define Tracevv(x)
  57. # define Tracec(c,x)
  58. # define Tracecv(c,x)
  59. #endif
  60. /* ===========================================================================
  61. */
  62. #define SMALL_MEM
  63. #ifndef INBUFSIZ
  64. # ifdef SMALL_MEM
  65. # define INBUFSIZ 0x2000 /* input buffer size */
  66. # else
  67. # define INBUFSIZ 0x8000 /* input buffer size */
  68. # endif
  69. #endif
  70. #ifndef OUTBUFSIZ
  71. # ifdef SMALL_MEM
  72. # define OUTBUFSIZ 8192 /* output buffer size */
  73. # else
  74. # define OUTBUFSIZ 16384 /* output buffer size */
  75. # endif
  76. #endif
  77. #ifndef DIST_BUFSIZE
  78. # ifdef SMALL_MEM
  79. # define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
  80. # else
  81. # define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
  82. # endif
  83. #endif
  84. /* gzip flag byte */
  85. #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
  86. #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
  87. #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
  88. #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
  89. #define COMMENT 0x10 /* bit 4 set: file comment present */
  90. #define RESERVED 0xC0 /* bit 6,7: reserved */
  91. /* internal file attribute */
  92. #define UNKNOWN 0xffff
  93. #define BINARY 0
  94. #define ASCII 1
  95. #ifndef WSIZE
  96. # define WSIZE 0x8000 /* window size--must be a power of two, and */
  97. #endif /* at least 32K for zip's deflate method */
  98. #define MIN_MATCH 3
  99. #define MAX_MATCH 258
  100. /* The minimum and maximum match lengths */
  101. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  102. /* Minimum amount of lookahead, except at the end of the input file.
  103. * See deflate.c for comments about the MIN_MATCH+1.
  104. */
  105. #define MAX_DIST (WSIZE-MIN_LOOKAHEAD)
  106. /* In order to simplify the code, particularly on 16 bit machines, match
  107. * distances are limited to MAX_DIST instead of WSIZE.
  108. */
  109. #ifndef MAX_PATH_LEN
  110. # define MAX_PATH_LEN 1024 /* max pathname length */
  111. #endif
  112. #define seekable() 0 /* force sequential output */
  113. #define translate_eol 0 /* no option -a yet */
  114. #ifndef BITS
  115. # define BITS 16
  116. #endif
  117. #define INIT_BITS 9 /* Initial number of bits per code */
  118. #define BIT_MASK 0x1f /* Mask for 'number of compression bits' */
  119. /* Mask 0x20 is reserved to mean a fourth header byte, and 0x40 is free.
  120. * It's a pity that old uncompress does not check bit 0x20. That makes
  121. * extension of the format actually undesirable because old compress
  122. * would just crash on the new format instead of giving a meaningful
  123. * error message. It does check the number of bits, but it's more
  124. * helpful to say "unsupported format, get a new version" than
  125. * "can only handle 16 bits".
  126. */
  127. #ifdef MAX_EXT_CHARS
  128. # define MAX_SUFFIX MAX_EXT_CHARS
  129. #else
  130. # define MAX_SUFFIX 30
  131. #endif
  132. /* ===========================================================================
  133. * Compile with MEDIUM_MEM to reduce the memory requirements or
  134. * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
  135. * entire input file can be held in memory (not possible on 16 bit systems).
  136. * Warning: defining these symbols affects HASH_BITS (see below) and thus
  137. * affects the compression ratio. The compressed output
  138. * is still correct, and might even be smaller in some cases.
  139. */
  140. #ifdef SMALL_MEM
  141. # define HASH_BITS 13 /* Number of bits used to hash strings */
  142. #endif
  143. #ifdef MEDIUM_MEM
  144. # define HASH_BITS 14
  145. #endif
  146. #ifndef HASH_BITS
  147. # define HASH_BITS 15
  148. /* For portability to 16 bit machines, do not use values above 15. */
  149. #endif
  150. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  151. #define HASH_MASK (HASH_SIZE-1)
  152. #define WMASK (WSIZE-1)
  153. /* HASH_SIZE and WSIZE must be powers of two */
  154. #ifndef TOO_FAR
  155. # define TOO_FAR 4096
  156. #endif
  157. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  158. /* ===========================================================================
  159. * These types are not really 'char', 'short' and 'long'
  160. */
  161. typedef uint8_t uch;
  162. typedef uint16_t ush;
  163. typedef uint32_t ulg;
  164. typedef int32_t lng;
  165. typedef ush Pos;
  166. typedef unsigned IPos;
  167. /* A Pos is an index in the character window. We use short instead of int to
  168. * save space in the various tables. IPos is used only for parameter passing.
  169. */
  170. enum {
  171. WINDOW_SIZE = 2 * WSIZE,
  172. /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  173. * input file length plus MIN_LOOKAHEAD.
  174. */
  175. max_chain_length = 4096,
  176. /* To speed up deflation, hash chains are never searched beyond this length.
  177. * A higher limit improves compression ratio but degrades the speed.
  178. */
  179. max_lazy_match = 258,
  180. /* Attempt to find a better match only when the current match is strictly
  181. * smaller than this value. This mechanism is used only for compression
  182. * levels >= 4.
  183. */
  184. max_insert_length = max_lazy_match,
  185. /* Insert new strings in the hash table only if the match length
  186. * is not greater than this length. This saves time but degrades compression.
  187. * max_insert_length is used only for compression levels <= 3.
  188. */
  189. good_match = 32,
  190. /* Use a faster search when the previous match is longer than this */
  191. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  192. * the desired pack level (0..9). The values given below have been tuned to
  193. * exclude worst case performance for pathological files. Better values may be
  194. * found for specific files.
  195. */
  196. nice_match = 258, /* Stop searching when current match exceeds this */
  197. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  198. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  199. * meaning.
  200. */
  201. };
  202. struct globals {
  203. lng block_start;
  204. /* window position at the beginning of the current output block. Gets
  205. * negative when the window is moved backwards.
  206. */
  207. unsigned ins_h; /* hash index of string to be inserted */
  208. #define H_SHIFT ((HASH_BITS+MIN_MATCH-1) / MIN_MATCH)
  209. /* Number of bits by which ins_h and del_h must be shifted at each
  210. * input step. It must be such that after MIN_MATCH steps, the oldest
  211. * byte no longer takes part in the hash key, that is:
  212. * H_SHIFT * MIN_MATCH >= HASH_BITS
  213. */
  214. unsigned prev_length;
  215. /* Length of the best match at previous step. Matches not greater than this
  216. * are discarded. This is used in the lazy match evaluation.
  217. */
  218. unsigned strstart; /* start of string to insert */
  219. unsigned match_start; /* start of matching string */
  220. unsigned lookahead; /* number of valid bytes ahead in window */
  221. /* ===========================================================================
  222. */
  223. #define DECLARE(type, array, size) \
  224. type * array
  225. #define ALLOC(type, array, size) \
  226. array = xzalloc((size_t)(((size)+1L)/2) * 2*sizeof(type))
  227. #define FREE(array) \
  228. do { free(array); array = NULL; } while (0)
  229. /* global buffers */
  230. /* buffer for literals or lengths */
  231. /* DECLARE(uch, l_buf, LIT_BUFSIZE); */
  232. DECLARE(uch, l_buf, INBUFSIZ);
  233. DECLARE(ush, d_buf, DIST_BUFSIZE);
  234. DECLARE(uch, outbuf, OUTBUFSIZ);
  235. /* Sliding window. Input bytes are read into the second half of the window,
  236. * and move to the first half later to keep a dictionary of at least WSIZE
  237. * bytes. With this organization, matches are limited to a distance of
  238. * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  239. * performed with a length multiple of the block size. Also, it limits
  240. * the window size to 64K, which is quite useful on MSDOS.
  241. * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
  242. * be less efficient).
  243. */
  244. DECLARE(uch, window, 2L * WSIZE);
  245. /* Link to older string with same hash index. To limit the size of this
  246. * array to 64K, this link is maintained only for the last 32K strings.
  247. * An index in this array is thus a window index modulo 32K.
  248. */
  249. /* DECLARE(Pos, prev, WSIZE); */
  250. DECLARE(ush, prev, 1L << BITS);
  251. /* Heads of the hash chains or 0. */
  252. /* DECLARE(Pos, head, 1<<HASH_BITS); */
  253. #define head (G1.prev + WSIZE) /* hash head (see deflate.c) */
  254. /* number of input bytes */
  255. ulg isize; /* only 32 bits stored in .gz file */
  256. /* bbox always use stdin/stdout */
  257. #define ifd STDIN_FILENO /* input file descriptor */
  258. #define ofd STDOUT_FILENO /* output file descriptor */
  259. #ifdef DEBUG
  260. unsigned insize; /* valid bytes in l_buf */
  261. #endif
  262. unsigned outcnt; /* bytes in output buffer */
  263. smallint eofile; /* flag set at end of input file */
  264. /* ===========================================================================
  265. * Local data used by the "bit string" routines.
  266. */
  267. unsigned short bi_buf;
  268. /* Output buffer. bits are inserted starting at the bottom (least significant
  269. * bits).
  270. */
  271. #undef BUF_SIZE
  272. #define BUF_SIZE (8 * sizeof(G1.bi_buf))
  273. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  274. * more than 16 bits on some systems.)
  275. */
  276. int bi_valid;
  277. /* Current input function. Set to mem_read for in-memory compression */
  278. #ifdef DEBUG
  279. ulg bits_sent; /* bit length of the compressed data */
  280. #endif
  281. uint32_t *crc_32_tab;
  282. uint32_t crc; /* shift register contents */
  283. };
  284. #define G1 (*(ptr_to_globals - 1))
  285. /* ===========================================================================
  286. * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
  287. * (used for the compressed data only)
  288. */
  289. static void flush_outbuf(void)
  290. {
  291. if (G1.outcnt == 0)
  292. return;
  293. xwrite(ofd, (char *) G1.outbuf, G1.outcnt);
  294. G1.outcnt = 0;
  295. }
  296. /* ===========================================================================
  297. */
  298. /* put_8bit is used for the compressed output */
  299. #define put_8bit(c) \
  300. do { \
  301. G1.outbuf[G1.outcnt++] = (c); \
  302. if (G1.outcnt == OUTBUFSIZ) flush_outbuf(); \
  303. } while (0)
  304. /* Output a 16 bit value, lsb first */
  305. static void put_16bit(ush w)
  306. {
  307. if (G1.outcnt < OUTBUFSIZ - 2) {
  308. G1.outbuf[G1.outcnt++] = w;
  309. G1.outbuf[G1.outcnt++] = w >> 8;
  310. } else {
  311. put_8bit(w);
  312. put_8bit(w >> 8);
  313. }
  314. }
  315. static void put_32bit(ulg n)
  316. {
  317. put_16bit(n);
  318. put_16bit(n >> 16);
  319. }
  320. /* ===========================================================================
  321. * Run a set of bytes through the crc shift register. If s is a NULL
  322. * pointer, then initialize the crc shift register contents instead.
  323. * Return the current crc in either case.
  324. */
  325. static uint32_t updcrc(uch * s, unsigned n)
  326. {
  327. uint32_t c = G1.crc;
  328. while (n) {
  329. c = G1.crc_32_tab[(uch)(c ^ *s++)] ^ (c >> 8);
  330. n--;
  331. }
  332. G1.crc = c;
  333. return c;
  334. }
  335. /* ===========================================================================
  336. * Read a new buffer from the current input file, perform end-of-line
  337. * translation, and update the crc and input file size.
  338. * IN assertion: size >= 2 (for end-of-line translation)
  339. */
  340. static unsigned file_read(void *buf, unsigned size)
  341. {
  342. unsigned len;
  343. Assert(G1.insize == 0, "l_buf not empty");
  344. len = safe_read(ifd, buf, size);
  345. if (len == (unsigned)(-1) || len == 0)
  346. return len;
  347. updcrc(buf, len);
  348. G1.isize += len;
  349. return len;
  350. }
  351. /* ===========================================================================
  352. * Send a value on a given number of bits.
  353. * IN assertion: length <= 16 and value fits in length bits.
  354. */
  355. static void send_bits(int value, int length)
  356. {
  357. #ifdef DEBUG
  358. Tracev((stderr, " l %2d v %4x ", length, value));
  359. Assert(length > 0 && length <= 15, "invalid length");
  360. G1.bits_sent += length;
  361. #endif
  362. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  363. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  364. * unused bits in value.
  365. */
  366. if (G1.bi_valid > (int) BUF_SIZE - length) {
  367. G1.bi_buf |= (value << G1.bi_valid);
  368. put_16bit(G1.bi_buf);
  369. G1.bi_buf = (ush) value >> (BUF_SIZE - G1.bi_valid);
  370. G1.bi_valid += length - BUF_SIZE;
  371. } else {
  372. G1.bi_buf |= value << G1.bi_valid;
  373. G1.bi_valid += length;
  374. }
  375. }
  376. /* ===========================================================================
  377. * Reverse the first len bits of a code, using straightforward code (a faster
  378. * method would use a table)
  379. * IN assertion: 1 <= len <= 15
  380. */
  381. static unsigned bi_reverse(unsigned code, int len)
  382. {
  383. unsigned res = 0;
  384. while (1) {
  385. res |= code & 1;
  386. if (--len <= 0) return res;
  387. code >>= 1;
  388. res <<= 1;
  389. }
  390. }
  391. /* ===========================================================================
  392. * Write out any remaining bits in an incomplete byte.
  393. */
  394. static void bi_windup(void)
  395. {
  396. if (G1.bi_valid > 8) {
  397. put_16bit(G1.bi_buf);
  398. } else if (G1.bi_valid > 0) {
  399. put_8bit(G1.bi_buf);
  400. }
  401. G1.bi_buf = 0;
  402. G1.bi_valid = 0;
  403. #ifdef DEBUG
  404. G1.bits_sent = (G1.bits_sent + 7) & ~7;
  405. #endif
  406. }
  407. /* ===========================================================================
  408. * Copy a stored block to the zip file, storing first the length and its
  409. * one's complement if requested.
  410. */
  411. static void copy_block(char *buf, unsigned len, int header)
  412. {
  413. bi_windup(); /* align on byte boundary */
  414. if (header) {
  415. put_16bit(len);
  416. put_16bit(~len);
  417. #ifdef DEBUG
  418. G1.bits_sent += 2 * 16;
  419. #endif
  420. }
  421. #ifdef DEBUG
  422. G1.bits_sent += (ulg) len << 3;
  423. #endif
  424. while (len--) {
  425. put_8bit(*buf++);
  426. }
  427. }
  428. /* ===========================================================================
  429. * Fill the window when the lookahead becomes insufficient.
  430. * Updates strstart and lookahead, and sets eofile if end of input file.
  431. * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  432. * OUT assertions: at least one byte has been read, or eofile is set;
  433. * file reads are performed for at least two bytes (required for the
  434. * translate_eol option).
  435. */
  436. static void fill_window(void)
  437. {
  438. unsigned n, m;
  439. unsigned more = WINDOW_SIZE - G1.lookahead - G1.strstart;
  440. /* Amount of free space at the end of the window. */
  441. /* If the window is almost full and there is insufficient lookahead,
  442. * move the upper half to the lower one to make room in the upper half.
  443. */
  444. if (more == (unsigned) -1) {
  445. /* Very unlikely, but possible on 16 bit machine if strstart == 0
  446. * and lookahead == 1 (input done one byte at time)
  447. */
  448. more--;
  449. } else if (G1.strstart >= WSIZE + MAX_DIST) {
  450. /* By the IN assertion, the window is not empty so we can't confuse
  451. * more == 0 with more == 64K on a 16 bit machine.
  452. */
  453. Assert(WINDOW_SIZE == 2 * WSIZE, "no sliding with BIG_MEM");
  454. memcpy(G1.window, G1.window + WSIZE, WSIZE);
  455. G1.match_start -= WSIZE;
  456. G1.strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
  457. G1.block_start -= WSIZE;
  458. for (n = 0; n < HASH_SIZE; n++) {
  459. m = head[n];
  460. head[n] = (Pos) (m >= WSIZE ? m - WSIZE : 0);
  461. }
  462. for (n = 0; n < WSIZE; n++) {
  463. m = G1.prev[n];
  464. G1.prev[n] = (Pos) (m >= WSIZE ? m - WSIZE : 0);
  465. /* If n is not on any hash chain, prev[n] is garbage but
  466. * its value will never be used.
  467. */
  468. }
  469. more += WSIZE;
  470. }
  471. /* At this point, more >= 2 */
  472. if (!G1.eofile) {
  473. n = file_read(G1.window + G1.strstart + G1.lookahead, more);
  474. if (n == 0 || n == (unsigned) -1) {
  475. G1.eofile = 1;
  476. } else {
  477. G1.lookahead += n;
  478. }
  479. }
  480. }
  481. /* ===========================================================================
  482. * Set match_start to the longest match starting at the given string and
  483. * return its length. Matches shorter or equal to prev_length are discarded,
  484. * in which case the result is equal to prev_length and match_start is
  485. * garbage.
  486. * IN assertions: cur_match is the head of the hash chain for the current
  487. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  488. */
  489. /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
  490. * match.s. The code is functionally equivalent, so you can use the C version
  491. * if desired.
  492. */
  493. static int longest_match(IPos cur_match)
  494. {
  495. unsigned chain_length = max_chain_length; /* max hash chain length */
  496. uch *scan = G1.window + G1.strstart; /* current string */
  497. uch *match; /* matched string */
  498. int len; /* length of current match */
  499. int best_len = G1.prev_length; /* best match length so far */
  500. IPos limit = G1.strstart > (IPos) MAX_DIST ? G1.strstart - (IPos) MAX_DIST : 0;
  501. /* Stop when cur_match becomes <= limit. To simplify the code,
  502. * we prevent matches with the string of window index 0.
  503. */
  504. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  505. * It is easy to get rid of this optimization if necessary.
  506. */
  507. #if HASH_BITS < 8 || MAX_MATCH != 258
  508. # error Code too clever
  509. #endif
  510. uch *strend = G1.window + G1.strstart + MAX_MATCH;
  511. uch scan_end1 = scan[best_len - 1];
  512. uch scan_end = scan[best_len];
  513. /* Do not waste too much time if we already have a good match: */
  514. if (G1.prev_length >= good_match) {
  515. chain_length >>= 2;
  516. }
  517. Assert(G1.strstart <= WINDOW_SIZE - MIN_LOOKAHEAD, "insufficient lookahead");
  518. do {
  519. Assert(cur_match < G1.strstart, "no future");
  520. match = G1.window + cur_match;
  521. /* Skip to next match if the match length cannot increase
  522. * or if the match length is less than 2:
  523. */
  524. if (match[best_len] != scan_end ||
  525. match[best_len - 1] != scan_end1 ||
  526. *match != *scan || *++match != scan[1])
  527. continue;
  528. /* The check at best_len-1 can be removed because it will be made
  529. * again later. (This heuristic is not always a win.)
  530. * It is not necessary to compare scan[2] and match[2] since they
  531. * are always equal when the other bytes match, given that
  532. * the hash keys are equal and that HASH_BITS >= 8.
  533. */
  534. scan += 2, match++;
  535. /* We check for insufficient lookahead only every 8th comparison;
  536. * the 256th check will be made at strstart+258.
  537. */
  538. do {
  539. } while (*++scan == *++match && *++scan == *++match &&
  540. *++scan == *++match && *++scan == *++match &&
  541. *++scan == *++match && *++scan == *++match &&
  542. *++scan == *++match && *++scan == *++match && scan < strend);
  543. len = MAX_MATCH - (int) (strend - scan);
  544. scan = strend - MAX_MATCH;
  545. if (len > best_len) {
  546. G1.match_start = cur_match;
  547. best_len = len;
  548. if (len >= nice_match)
  549. break;
  550. scan_end1 = scan[best_len - 1];
  551. scan_end = scan[best_len];
  552. }
  553. } while ((cur_match = G1.prev[cur_match & WMASK]) > limit
  554. && --chain_length != 0);
  555. return best_len;
  556. }
  557. #ifdef DEBUG
  558. /* ===========================================================================
  559. * Check that the match at match_start is indeed a match.
  560. */
  561. static void check_match(IPos start, IPos match, int length)
  562. {
  563. /* check that the match is indeed a match */
  564. if (memcmp(G1.window + match, G1.window + start, length) != 0) {
  565. bb_error_msg(" start %d, match %d, length %d", start, match, length);
  566. bb_error_msg("invalid match");
  567. }
  568. if (verbose > 1) {
  569. bb_error_msg("\\[%d,%d]", start - match, length);
  570. do {
  571. fputc(G1.window[start++], stderr);
  572. } while (--length != 0);
  573. }
  574. }
  575. #else
  576. # define check_match(start, match, length) ((void)0)
  577. #endif
  578. /* trees.c -- output deflated data using Huffman coding
  579. * Copyright (C) 1992-1993 Jean-loup Gailly
  580. * This is free software; you can redistribute it and/or modify it under the
  581. * terms of the GNU General Public License, see the file COPYING.
  582. */
  583. /* PURPOSE
  584. * Encode various sets of source values using variable-length
  585. * binary code trees.
  586. *
  587. * DISCUSSION
  588. * The PKZIP "deflation" process uses several Huffman trees. The more
  589. * common source values are represented by shorter bit sequences.
  590. *
  591. * Each code tree is stored in the ZIP file in a compressed form
  592. * which is itself a Huffman encoding of the lengths of
  593. * all the code strings (in ascending order by source values).
  594. * The actual code strings are reconstructed from the lengths in
  595. * the UNZIP process, as described in the "application note"
  596. * (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
  597. *
  598. * REFERENCES
  599. * Lynch, Thomas J.
  600. * Data Compression: Techniques and Applications, pp. 53-55.
  601. * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
  602. *
  603. * Storer, James A.
  604. * Data Compression: Methods and Theory, pp. 49-50.
  605. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  606. *
  607. * Sedgewick, R.
  608. * Algorithms, p290.
  609. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  610. *
  611. * INTERFACE
  612. * void ct_init()
  613. * Allocate the match buffer, initialize the various tables [and save
  614. * the location of the internal file attribute (ascii/binary) and
  615. * method (DEFLATE/STORE) -- deleted in bbox]
  616. *
  617. * void ct_tally(int dist, int lc);
  618. * Save the match info and tally the frequency counts.
  619. *
  620. * ulg flush_block(char *buf, ulg stored_len, int eof)
  621. * Determine the best encoding for the current block: dynamic trees,
  622. * static trees or store, and output the encoded block to the zip
  623. * file. Returns the total compressed length for the file so far.
  624. */
  625. #define MAX_BITS 15
  626. /* All codes must not exceed MAX_BITS bits */
  627. #define MAX_BL_BITS 7
  628. /* Bit length codes must not exceed MAX_BL_BITS bits */
  629. #define LENGTH_CODES 29
  630. /* number of length codes, not counting the special END_BLOCK code */
  631. #define LITERALS 256
  632. /* number of literal bytes 0..255 */
  633. #define END_BLOCK 256
  634. /* end of block literal code */
  635. #define L_CODES (LITERALS+1+LENGTH_CODES)
  636. /* number of Literal or Length codes, including the END_BLOCK code */
  637. #define D_CODES 30
  638. /* number of distance codes */
  639. #define BL_CODES 19
  640. /* number of codes used to transfer the bit lengths */
  641. /* extra bits for each length code */
  642. static const uint8_t extra_lbits[LENGTH_CODES] ALIGN1 = {
  643. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
  644. 4, 4, 5, 5, 5, 5, 0
  645. };
  646. /* extra bits for each distance code */
  647. static const uint8_t extra_dbits[D_CODES] ALIGN1 = {
  648. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,
  649. 10, 10, 11, 11, 12, 12, 13, 13
  650. };
  651. /* extra bits for each bit length code */
  652. static const uint8_t extra_blbits[BL_CODES] ALIGN1 = {
  653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 };
  654. /* number of codes at each bit length for an optimal tree */
  655. static const uint8_t bl_order[BL_CODES] ALIGN1 = {
  656. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
  657. #define STORED_BLOCK 0
  658. #define STATIC_TREES 1
  659. #define DYN_TREES 2
  660. /* The three kinds of block type */
  661. #ifndef LIT_BUFSIZE
  662. # ifdef SMALL_MEM
  663. # define LIT_BUFSIZE 0x2000
  664. # else
  665. # ifdef MEDIUM_MEM
  666. # define LIT_BUFSIZE 0x4000
  667. # else
  668. # define LIT_BUFSIZE 0x8000
  669. # endif
  670. # endif
  671. #endif
  672. #ifndef DIST_BUFSIZE
  673. # define DIST_BUFSIZE LIT_BUFSIZE
  674. #endif
  675. /* Sizes of match buffers for literals/lengths and distances. There are
  676. * 4 reasons for limiting LIT_BUFSIZE to 64K:
  677. * - frequencies can be kept in 16 bit counters
  678. * - if compression is not successful for the first block, all input data is
  679. * still in the window so we can still emit a stored block even when input
  680. * comes from standard input. (This can also be done for all blocks if
  681. * LIT_BUFSIZE is not greater than 32K.)
  682. * - if compression is not successful for a file smaller than 64K, we can
  683. * even emit a stored file instead of a stored block (saving 5 bytes).
  684. * - creating new Huffman trees less frequently may not provide fast
  685. * adaptation to changes in the input data statistics. (Take for
  686. * example a binary file with poorly compressible code followed by
  687. * a highly compressible string table.) Smaller buffer sizes give
  688. * fast adaptation but have of course the overhead of transmitting trees
  689. * more frequently.
  690. * - I can't count above 4
  691. * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
  692. * memory at the expense of compression). Some optimizations would be possible
  693. * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
  694. */
  695. #define REP_3_6 16
  696. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  697. #define REPZ_3_10 17
  698. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  699. #define REPZ_11_138 18
  700. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  701. /* ===========================================================================
  702. */
  703. /* Data structure describing a single value and its code string. */
  704. typedef struct ct_data {
  705. union {
  706. ush freq; /* frequency count */
  707. ush code; /* bit string */
  708. } fc;
  709. union {
  710. ush dad; /* father node in Huffman tree */
  711. ush len; /* length of bit string */
  712. } dl;
  713. } ct_data;
  714. #define Freq fc.freq
  715. #define Code fc.code
  716. #define Dad dl.dad
  717. #define Len dl.len
  718. #define HEAP_SIZE (2*L_CODES + 1)
  719. /* maximum heap size */
  720. typedef struct tree_desc {
  721. ct_data *dyn_tree; /* the dynamic tree */
  722. ct_data *static_tree; /* corresponding static tree or NULL */
  723. const uint8_t *extra_bits; /* extra bits for each code or NULL */
  724. int extra_base; /* base index for extra_bits */
  725. int elems; /* max number of elements in the tree */
  726. int max_length; /* max bit length for the codes */
  727. int max_code; /* largest code with non zero frequency */
  728. } tree_desc;
  729. struct globals2 {
  730. ush heap[HEAP_SIZE]; /* heap used to build the Huffman trees */
  731. int heap_len; /* number of elements in the heap */
  732. int heap_max; /* element of largest frequency */
  733. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  734. * The same heap array is used to build all trees.
  735. */
  736. ct_data dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  737. ct_data dyn_dtree[2 * D_CODES + 1]; /* distance tree */
  738. ct_data static_ltree[L_CODES + 2];
  739. /* The static literal tree. Since the bit lengths are imposed, there is no
  740. * need for the L_CODES extra codes used during heap construction. However
  741. * The codes 286 and 287 are needed to build a canonical tree (see ct_init
  742. * below).
  743. */
  744. ct_data static_dtree[D_CODES];
  745. /* The static distance tree. (Actually a trivial tree since all codes use
  746. * 5 bits.)
  747. */
  748. ct_data bl_tree[2 * BL_CODES + 1];
  749. /* Huffman tree for the bit lengths */
  750. tree_desc l_desc;
  751. tree_desc d_desc;
  752. tree_desc bl_desc;
  753. ush bl_count[MAX_BITS + 1];
  754. /* The lengths of the bit length codes are sent in order of decreasing
  755. * probability, to avoid transmitting the lengths for unused bit length codes.
  756. */
  757. uch depth[2 * L_CODES + 1];
  758. /* Depth of each subtree used as tie breaker for trees of equal frequency */
  759. uch length_code[MAX_MATCH - MIN_MATCH + 1];
  760. /* length code for each normalized match length (0 == MIN_MATCH) */
  761. uch dist_code[512];
  762. /* distance codes. The first 256 values correspond to the distances
  763. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  764. * the 15 bit distances.
  765. */
  766. int base_length[LENGTH_CODES];
  767. /* First normalized length for each code (0 = MIN_MATCH) */
  768. int base_dist[D_CODES];
  769. /* First normalized distance for each code (0 = distance of 1) */
  770. uch flag_buf[LIT_BUFSIZE / 8];
  771. /* flag_buf is a bit array distinguishing literals from lengths in
  772. * l_buf, thus indicating the presence or absence of a distance.
  773. */
  774. unsigned last_lit; /* running index in l_buf */
  775. unsigned last_dist; /* running index in d_buf */
  776. unsigned last_flags; /* running index in flag_buf */
  777. uch flags; /* current flags not yet saved in flag_buf */
  778. uch flag_bit; /* current bit used in flags */
  779. /* bits are filled in flags starting at bit 0 (least significant).
  780. * Note: these flags are overkill in the current code since we don't
  781. * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
  782. */
  783. ulg opt_len; /* bit length of current block with optimal trees */
  784. ulg static_len; /* bit length of current block with static trees */
  785. ulg compressed_len; /* total bit length of compressed file */
  786. };
  787. #define G2ptr ((struct globals2*)(ptr_to_globals))
  788. #define G2 (*G2ptr)
  789. /* ===========================================================================
  790. */
  791. static void gen_codes(ct_data * tree, int max_code);
  792. static void build_tree(tree_desc * desc);
  793. static void scan_tree(ct_data * tree, int max_code);
  794. static void send_tree(ct_data * tree, int max_code);
  795. static int build_bl_tree(void);
  796. static void send_all_trees(int lcodes, int dcodes, int blcodes);
  797. static void compress_block(ct_data * ltree, ct_data * dtree);
  798. #ifndef DEBUG
  799. /* Send a code of the given tree. c and tree must not have side effects */
  800. # define SEND_CODE(c, tree) send_bits(tree[c].Code, tree[c].Len)
  801. #else
  802. # define SEND_CODE(c, tree) \
  803. { \
  804. if (verbose > 1) bb_error_msg("\ncd %3d ",(c)); \
  805. send_bits(tree[c].Code, tree[c].Len); \
  806. }
  807. #endif
  808. #define D_CODE(dist) \
  809. ((dist) < 256 ? G2.dist_code[dist] : G2.dist_code[256 + ((dist)>>7)])
  810. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  811. * must not have side effects. dist_code[256] and dist_code[257] are never
  812. * used.
  813. * The arguments must not have side effects.
  814. */
  815. /* ===========================================================================
  816. * Initialize a new block.
  817. */
  818. static void init_block(void)
  819. {
  820. int n; /* iterates over tree elements */
  821. /* Initialize the trees. */
  822. for (n = 0; n < L_CODES; n++)
  823. G2.dyn_ltree[n].Freq = 0;
  824. for (n = 0; n < D_CODES; n++)
  825. G2.dyn_dtree[n].Freq = 0;
  826. for (n = 0; n < BL_CODES; n++)
  827. G2.bl_tree[n].Freq = 0;
  828. G2.dyn_ltree[END_BLOCK].Freq = 1;
  829. G2.opt_len = G2.static_len = 0;
  830. G2.last_lit = G2.last_dist = G2.last_flags = 0;
  831. G2.flags = 0;
  832. G2.flag_bit = 1;
  833. }
  834. /* ===========================================================================
  835. * Restore the heap property by moving down the tree starting at node k,
  836. * exchanging a node with the smallest of its two sons if necessary, stopping
  837. * when the heap property is re-established (each father smaller than its
  838. * two sons).
  839. */
  840. /* Compares to subtrees, using the tree depth as tie breaker when
  841. * the subtrees have equal frequency. This minimizes the worst case length. */
  842. #define SMALLER(tree, n, m) \
  843. (tree[n].Freq < tree[m].Freq \
  844. || (tree[n].Freq == tree[m].Freq && G2.depth[n] <= G2.depth[m]))
  845. static void pqdownheap(ct_data * tree, int k)
  846. {
  847. int v = G2.heap[k];
  848. int j = k << 1; /* left son of k */
  849. while (j <= G2.heap_len) {
  850. /* Set j to the smallest of the two sons: */
  851. if (j < G2.heap_len && SMALLER(tree, G2.heap[j + 1], G2.heap[j]))
  852. j++;
  853. /* Exit if v is smaller than both sons */
  854. if (SMALLER(tree, v, G2.heap[j]))
  855. break;
  856. /* Exchange v with the smallest son */
  857. G2.heap[k] = G2.heap[j];
  858. k = j;
  859. /* And continue down the tree, setting j to the left son of k */
  860. j <<= 1;
  861. }
  862. G2.heap[k] = v;
  863. }
  864. /* ===========================================================================
  865. * Compute the optimal bit lengths for a tree and update the total bit length
  866. * for the current block.
  867. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  868. * above are the tree nodes sorted by increasing frequency.
  869. * OUT assertions: the field len is set to the optimal bit length, the
  870. * array bl_count contains the frequencies for each bit length.
  871. * The length opt_len is updated; static_len is also updated if stree is
  872. * not null.
  873. */
  874. static void gen_bitlen(tree_desc * desc)
  875. {
  876. ct_data *tree = desc->dyn_tree;
  877. const uint8_t *extra = desc->extra_bits;
  878. int base = desc->extra_base;
  879. int max_code = desc->max_code;
  880. int max_length = desc->max_length;
  881. ct_data *stree = desc->static_tree;
  882. int h; /* heap index */
  883. int n, m; /* iterate over the tree elements */
  884. int bits; /* bit length */
  885. int xbits; /* extra bits */
  886. ush f; /* frequency */
  887. int overflow = 0; /* number of elements with bit length too large */
  888. for (bits = 0; bits <= MAX_BITS; bits++)
  889. G2.bl_count[bits] = 0;
  890. /* In a first pass, compute the optimal bit lengths (which may
  891. * overflow in the case of the bit length tree).
  892. */
  893. tree[G2.heap[G2.heap_max]].Len = 0; /* root of the heap */
  894. for (h = G2.heap_max + 1; h < HEAP_SIZE; h++) {
  895. n = G2.heap[h];
  896. bits = tree[tree[n].Dad].Len + 1;
  897. if (bits > max_length) {
  898. bits = max_length;
  899. overflow++;
  900. }
  901. tree[n].Len = (ush) bits;
  902. /* We overwrite tree[n].Dad which is no longer needed */
  903. if (n > max_code)
  904. continue; /* not a leaf node */
  905. G2.bl_count[bits]++;
  906. xbits = 0;
  907. if (n >= base)
  908. xbits = extra[n - base];
  909. f = tree[n].Freq;
  910. G2.opt_len += (ulg) f *(bits + xbits);
  911. if (stree)
  912. G2.static_len += (ulg) f * (stree[n].Len + xbits);
  913. }
  914. if (overflow == 0)
  915. return;
  916. Trace((stderr, "\nbit length overflow\n"));
  917. /* This happens for example on obj2 and pic of the Calgary corpus */
  918. /* Find the first bit length which could increase: */
  919. do {
  920. bits = max_length - 1;
  921. while (G2.bl_count[bits] == 0)
  922. bits--;
  923. G2.bl_count[bits]--; /* move one leaf down the tree */
  924. G2.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  925. G2.bl_count[max_length]--;
  926. /* The brother of the overflow item also moves one step up,
  927. * but this does not affect bl_count[max_length]
  928. */
  929. overflow -= 2;
  930. } while (overflow > 0);
  931. /* Now recompute all bit lengths, scanning in increasing frequency.
  932. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  933. * lengths instead of fixing only the wrong ones. This idea is taken
  934. * from 'ar' written by Haruhiko Okumura.)
  935. */
  936. for (bits = max_length; bits != 0; bits--) {
  937. n = G2.bl_count[bits];
  938. while (n != 0) {
  939. m = G2.heap[--h];
  940. if (m > max_code)
  941. continue;
  942. if (tree[m].Len != (unsigned) bits) {
  943. Trace((stderr, "code %d bits %d->%d\n", m, tree[m].Len, bits));
  944. G2.opt_len += ((int32_t) bits - tree[m].Len) * tree[m].Freq;
  945. tree[m].Len = bits;
  946. }
  947. n--;
  948. }
  949. }
  950. }
  951. /* ===========================================================================
  952. * Generate the codes for a given tree and bit counts (which need not be
  953. * optimal).
  954. * IN assertion: the array bl_count contains the bit length statistics for
  955. * the given tree and the field len is set for all tree elements.
  956. * OUT assertion: the field code is set for all tree elements of non
  957. * zero code length.
  958. */
  959. static void gen_codes(ct_data * tree, int max_code)
  960. {
  961. ush next_code[MAX_BITS + 1]; /* next code value for each bit length */
  962. ush code = 0; /* running code value */
  963. int bits; /* bit index */
  964. int n; /* code index */
  965. /* The distribution counts are first used to generate the code values
  966. * without bit reversal.
  967. */
  968. for (bits = 1; bits <= MAX_BITS; bits++) {
  969. next_code[bits] = code = (code + G2.bl_count[bits - 1]) << 1;
  970. }
  971. /* Check that the bit counts in bl_count are consistent. The last code
  972. * must be all ones.
  973. */
  974. Assert(code + G2.bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
  975. "inconsistent bit counts");
  976. Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
  977. for (n = 0; n <= max_code; n++) {
  978. int len = tree[n].Len;
  979. if (len == 0)
  980. continue;
  981. /* Now reverse the bits */
  982. tree[n].Code = bi_reverse(next_code[len]++, len);
  983. Tracec(tree != G2.static_ltree,
  984. (stderr, "\nn %3d %c l %2d c %4x (%x) ", n,
  985. (n > ' ' ? n : ' '), len, tree[n].Code,
  986. next_code[len] - 1));
  987. }
  988. }
  989. /* ===========================================================================
  990. * Construct one Huffman tree and assigns the code bit strings and lengths.
  991. * Update the total bit length for the current block.
  992. * IN assertion: the field freq is set for all tree elements.
  993. * OUT assertions: the fields len and code are set to the optimal bit length
  994. * and corresponding code. The length opt_len is updated; static_len is
  995. * also updated if stree is not null. The field max_code is set.
  996. */
  997. /* Remove the smallest element from the heap and recreate the heap with
  998. * one less element. Updates heap and heap_len. */
  999. #define SMALLEST 1
  1000. /* Index within the heap array of least frequent node in the Huffman tree */
  1001. #define PQREMOVE(tree, top) \
  1002. do { \
  1003. top = G2.heap[SMALLEST]; \
  1004. G2.heap[SMALLEST] = G2.heap[G2.heap_len--]; \
  1005. pqdownheap(tree, SMALLEST); \
  1006. } while (0)
  1007. static void build_tree(tree_desc * desc)
  1008. {
  1009. ct_data *tree = desc->dyn_tree;
  1010. ct_data *stree = desc->static_tree;
  1011. int elems = desc->elems;
  1012. int n, m; /* iterate over heap elements */
  1013. int max_code = -1; /* largest code with non zero frequency */
  1014. int node = elems; /* next internal node of the tree */
  1015. /* Construct the initial heap, with least frequent element in
  1016. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  1017. * heap[0] is not used.
  1018. */
  1019. G2.heap_len = 0;
  1020. G2.heap_max = HEAP_SIZE;
  1021. for (n = 0; n < elems; n++) {
  1022. if (tree[n].Freq != 0) {
  1023. G2.heap[++G2.heap_len] = max_code = n;
  1024. G2.depth[n] = 0;
  1025. } else {
  1026. tree[n].Len = 0;
  1027. }
  1028. }
  1029. /* The pkzip format requires that at least one distance code exists,
  1030. * and that at least one bit should be sent even if there is only one
  1031. * possible code. So to avoid special checks later on we force at least
  1032. * two codes of non zero frequency.
  1033. */
  1034. while (G2.heap_len < 2) {
  1035. int new = G2.heap[++G2.heap_len] = (max_code < 2 ? ++max_code : 0);
  1036. tree[new].Freq = 1;
  1037. G2.depth[new] = 0;
  1038. G2.opt_len--;
  1039. if (stree)
  1040. G2.static_len -= stree[new].Len;
  1041. /* new is 0 or 1 so it does not have extra bits */
  1042. }
  1043. desc->max_code = max_code;
  1044. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  1045. * establish sub-heaps of increasing lengths:
  1046. */
  1047. for (n = G2.heap_len / 2; n >= 1; n--)
  1048. pqdownheap(tree, n);
  1049. /* Construct the Huffman tree by repeatedly combining the least two
  1050. * frequent nodes.
  1051. */
  1052. do {
  1053. PQREMOVE(tree, n); /* n = node of least frequency */
  1054. m = G2.heap[SMALLEST]; /* m = node of next least frequency */
  1055. G2.heap[--G2.heap_max] = n; /* keep the nodes sorted by frequency */
  1056. G2.heap[--G2.heap_max] = m;
  1057. /* Create a new node father of n and m */
  1058. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  1059. G2.depth[node] = MAX(G2.depth[n], G2.depth[m]) + 1;
  1060. tree[n].Dad = tree[m].Dad = (ush) node;
  1061. #ifdef DUMP_BL_TREE
  1062. if (tree == G2.bl_tree) {
  1063. bb_error_msg("\nnode %d(%d), sons %d(%d) %d(%d)",
  1064. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  1065. }
  1066. #endif
  1067. /* and insert the new node in the heap */
  1068. G2.heap[SMALLEST] = node++;
  1069. pqdownheap(tree, SMALLEST);
  1070. } while (G2.heap_len >= 2);
  1071. G2.heap[--G2.heap_max] = G2.heap[SMALLEST];
  1072. /* At this point, the fields freq and dad are set. We can now
  1073. * generate the bit lengths.
  1074. */
  1075. gen_bitlen((tree_desc *) desc);
  1076. /* The field len is now set, we can generate the bit codes */
  1077. gen_codes((ct_data *) tree, max_code);
  1078. }
  1079. /* ===========================================================================
  1080. * Scan a literal or distance tree to determine the frequencies of the codes
  1081. * in the bit length tree. Updates opt_len to take into account the repeat
  1082. * counts. (The contribution of the bit length codes will be added later
  1083. * during the construction of bl_tree.)
  1084. */
  1085. static void scan_tree(ct_data * tree, int max_code)
  1086. {
  1087. int n; /* iterates over all tree elements */
  1088. int prevlen = -1; /* last emitted length */
  1089. int curlen; /* length of current code */
  1090. int nextlen = tree[0].Len; /* length of next code */
  1091. int count = 0; /* repeat count of the current code */
  1092. int max_count = 7; /* max repeat count */
  1093. int min_count = 4; /* min repeat count */
  1094. if (nextlen == 0) {
  1095. max_count = 138;
  1096. min_count = 3;
  1097. }
  1098. tree[max_code + 1].Len = 0xffff; /* guard */
  1099. for (n = 0; n <= max_code; n++) {
  1100. curlen = nextlen;
  1101. nextlen = tree[n + 1].Len;
  1102. if (++count < max_count && curlen == nextlen)
  1103. continue;
  1104. if (count < min_count) {
  1105. G2.bl_tree[curlen].Freq += count;
  1106. } else if (curlen != 0) {
  1107. if (curlen != prevlen)
  1108. G2.bl_tree[curlen].Freq++;
  1109. G2.bl_tree[REP_3_6].Freq++;
  1110. } else if (count <= 10) {
  1111. G2.bl_tree[REPZ_3_10].Freq++;
  1112. } else {
  1113. G2.bl_tree[REPZ_11_138].Freq++;
  1114. }
  1115. count = 0;
  1116. prevlen = curlen;
  1117. max_count = 7;
  1118. min_count = 4;
  1119. if (nextlen == 0) {
  1120. max_count = 138;
  1121. min_count = 3;
  1122. } else if (curlen == nextlen) {
  1123. max_count = 6;
  1124. min_count = 3;
  1125. }
  1126. }
  1127. }
  1128. /* ===========================================================================
  1129. * Send a literal or distance tree in compressed form, using the codes in
  1130. * bl_tree.
  1131. */
  1132. static void send_tree(ct_data * tree, int max_code)
  1133. {
  1134. int n; /* iterates over all tree elements */
  1135. int prevlen = -1; /* last emitted length */
  1136. int curlen; /* length of current code */
  1137. int nextlen = tree[0].Len; /* length of next code */
  1138. int count = 0; /* repeat count of the current code */
  1139. int max_count = 7; /* max repeat count */
  1140. int min_count = 4; /* min repeat count */
  1141. /* tree[max_code+1].Len = -1; *//* guard already set */
  1142. if (nextlen == 0)
  1143. max_count = 138, min_count = 3;
  1144. for (n = 0; n <= max_code; n++) {
  1145. curlen = nextlen;
  1146. nextlen = tree[n + 1].Len;
  1147. if (++count < max_count && curlen == nextlen) {
  1148. continue;
  1149. } else if (count < min_count) {
  1150. do {
  1151. SEND_CODE(curlen, G2.bl_tree);
  1152. } while (--count);
  1153. } else if (curlen != 0) {
  1154. if (curlen != prevlen) {
  1155. SEND_CODE(curlen, G2.bl_tree);
  1156. count--;
  1157. }
  1158. Assert(count >= 3 && count <= 6, " 3_6?");
  1159. SEND_CODE(REP_3_6, G2.bl_tree);
  1160. send_bits(count - 3, 2);
  1161. } else if (count <= 10) {
  1162. SEND_CODE(REPZ_3_10, G2.bl_tree);
  1163. send_bits(count - 3, 3);
  1164. } else {
  1165. SEND_CODE(REPZ_11_138, G2.bl_tree);
  1166. send_bits(count - 11, 7);
  1167. }
  1168. count = 0;
  1169. prevlen = curlen;
  1170. if (nextlen == 0) {
  1171. max_count = 138;
  1172. min_count = 3;
  1173. } else if (curlen == nextlen) {
  1174. max_count = 6;
  1175. min_count = 3;
  1176. } else {
  1177. max_count = 7;
  1178. min_count = 4;
  1179. }
  1180. }
  1181. }
  1182. /* ===========================================================================
  1183. * Construct the Huffman tree for the bit lengths and return the index in
  1184. * bl_order of the last bit length code to send.
  1185. */
  1186. static int build_bl_tree(void)
  1187. {
  1188. int max_blindex; /* index of last bit length code of non zero freq */
  1189. /* Determine the bit length frequencies for literal and distance trees */
  1190. scan_tree(G2.dyn_ltree, G2.l_desc.max_code);
  1191. scan_tree(G2.dyn_dtree, G2.d_desc.max_code);
  1192. /* Build the bit length tree: */
  1193. build_tree(&G2.bl_desc);
  1194. /* opt_len now includes the length of the tree representations, except
  1195. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  1196. */
  1197. /* Determine the number of bit length codes to send. The pkzip format
  1198. * requires that at least 4 bit length codes be sent. (appnote.txt says
  1199. * 3 but the actual value used is 4.)
  1200. */
  1201. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  1202. if (G2.bl_tree[bl_order[max_blindex]].Len != 0)
  1203. break;
  1204. }
  1205. /* Update opt_len to include the bit length tree and counts */
  1206. G2.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  1207. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", G2.opt_len, G2.static_len));
  1208. return max_blindex;
  1209. }
  1210. /* ===========================================================================
  1211. * Send the header for a block using dynamic Huffman trees: the counts, the
  1212. * lengths of the bit length codes, the literal tree and the distance tree.
  1213. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  1214. */
  1215. static void send_all_trees(int lcodes, int dcodes, int blcodes)
  1216. {
  1217. int rank; /* index in bl_order */
  1218. Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  1219. Assert(lcodes <= L_CODES && dcodes <= D_CODES
  1220. && blcodes <= BL_CODES, "too many codes");
  1221. Tracev((stderr, "\nbl counts: "));
  1222. send_bits(lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  1223. send_bits(dcodes - 1, 5);
  1224. send_bits(blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  1225. for (rank = 0; rank < blcodes; rank++) {
  1226. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  1227. send_bits(G2.bl_tree[bl_order[rank]].Len, 3);
  1228. }
  1229. Tracev((stderr, "\nbl tree: sent %ld", G1.bits_sent));
  1230. send_tree((ct_data *) G2.dyn_ltree, lcodes - 1); /* send the literal tree */
  1231. Tracev((stderr, "\nlit tree: sent %ld", G1.bits_sent));
  1232. send_tree((ct_data *) G2.dyn_dtree, dcodes - 1); /* send the distance tree */
  1233. Tracev((stderr, "\ndist tree: sent %ld", G1.bits_sent));
  1234. }
  1235. /* ===========================================================================
  1236. * Save the match info and tally the frequency counts. Return true if
  1237. * the current block must be flushed.
  1238. */
  1239. static int ct_tally(int dist, int lc)
  1240. {
  1241. G1.l_buf[G2.last_lit++] = lc;
  1242. if (dist == 0) {
  1243. /* lc is the unmatched char */
  1244. G2.dyn_ltree[lc].Freq++;
  1245. } else {
  1246. /* Here, lc is the match length - MIN_MATCH */
  1247. dist--; /* dist = match distance - 1 */
  1248. Assert((ush) dist < (ush) MAX_DIST
  1249. && (ush) lc <= (ush) (MAX_MATCH - MIN_MATCH)
  1250. && (ush) D_CODE(dist) < (ush) D_CODES, "ct_tally: bad match"
  1251. );
  1252. G2.dyn_ltree[G2.length_code[lc] + LITERALS + 1].Freq++;
  1253. G2.dyn_dtree[D_CODE(dist)].Freq++;
  1254. G1.d_buf[G2.last_dist++] = dist;
  1255. G2.flags |= G2.flag_bit;
  1256. }
  1257. G2.flag_bit <<= 1;
  1258. /* Output the flags if they fill a byte: */
  1259. if ((G2.last_lit & 7) == 0) {
  1260. G2.flag_buf[G2.last_flags++] = G2.flags;
  1261. G2.flags = 0;
  1262. G2.flag_bit = 1;
  1263. }
  1264. /* Try to guess if it is profitable to stop the current block here */
  1265. if ((G2.last_lit & 0xfff) == 0) {
  1266. /* Compute an upper bound for the compressed length */
  1267. ulg out_length = G2.last_lit * 8L;
  1268. ulg in_length = (ulg) G1.strstart - G1.block_start;
  1269. int dcode;
  1270. for (dcode = 0; dcode < D_CODES; dcode++) {
  1271. out_length += G2.dyn_dtree[dcode].Freq * (5L + extra_dbits[dcode]);
  1272. }
  1273. out_length >>= 3;
  1274. Trace((stderr,
  1275. "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
  1276. G2.last_lit, G2.last_dist, in_length, out_length,
  1277. 100L - out_length * 100L / in_length));
  1278. if (G2.last_dist < G2.last_lit / 2 && out_length < in_length / 2)
  1279. return 1;
  1280. }
  1281. return (G2.last_lit == LIT_BUFSIZE - 1 || G2.last_dist == DIST_BUFSIZE);
  1282. /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
  1283. * on 16 bit machines and because stored blocks are restricted to
  1284. * 64K-1 bytes.
  1285. */
  1286. }
  1287. /* ===========================================================================
  1288. * Send the block data compressed using the given Huffman trees
  1289. */
  1290. static void compress_block(ct_data * ltree, ct_data * dtree)
  1291. {
  1292. unsigned dist; /* distance of matched string */
  1293. int lc; /* match length or unmatched char (if dist == 0) */
  1294. unsigned lx = 0; /* running index in l_buf */
  1295. unsigned dx = 0; /* running index in d_buf */
  1296. unsigned fx = 0; /* running index in flag_buf */
  1297. uch flag = 0; /* current flags */
  1298. unsigned code; /* the code to send */
  1299. int extra; /* number of extra bits to send */
  1300. if (G2.last_lit != 0) do {
  1301. if ((lx & 7) == 0)
  1302. flag = G2.flag_buf[fx++];
  1303. lc = G1.l_buf[lx++];
  1304. if ((flag & 1) == 0) {
  1305. SEND_CODE(lc, ltree); /* send a literal byte */
  1306. Tracecv(lc > ' ', (stderr, " '%c' ", lc));
  1307. } else {
  1308. /* Here, lc is the match length - MIN_MATCH */
  1309. code = G2.length_code[lc];
  1310. SEND_CODE(code + LITERALS + 1, ltree); /* send the length code */
  1311. extra = extra_lbits[code];
  1312. if (extra != 0) {
  1313. lc -= G2.base_length[code];
  1314. send_bits(lc, extra); /* send the extra length bits */
  1315. }
  1316. dist = G1.d_buf[dx++];
  1317. /* Here, dist is the match distance - 1 */
  1318. code = D_CODE(dist);
  1319. Assert(code < D_CODES, "bad d_code");
  1320. SEND_CODE(code, dtree); /* send the distance code */
  1321. extra = extra_dbits[code];
  1322. if (extra != 0) {
  1323. dist -= G2.base_dist[code];
  1324. send_bits(dist, extra); /* send the extra distance bits */
  1325. }
  1326. } /* literal or match pair ? */
  1327. flag >>= 1;
  1328. } while (lx < G2.last_lit);
  1329. SEND_CODE(END_BLOCK, ltree);
  1330. }
  1331. /* ===========================================================================
  1332. * Determine the best encoding for the current block: dynamic trees, static
  1333. * trees or store, and output the encoded block to the zip file. This function
  1334. * returns the total compressed length for the file so far.
  1335. */
  1336. static ulg flush_block(char *buf, ulg stored_len, int eof)
  1337. {
  1338. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  1339. int max_blindex; /* index of last bit length code of non zero freq */
  1340. G2.flag_buf[G2.last_flags] = G2.flags; /* Save the flags for the last 8 items */
  1341. /* Construct the literal and distance trees */
  1342. build_tree(&G2.l_desc);
  1343. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", G2.opt_len, G2.static_len));
  1344. build_tree(&G2.d_desc);
  1345. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", G2.opt_len, G2.static_len));
  1346. /* At this point, opt_len and static_len are the total bit lengths of
  1347. * the compressed block data, excluding the tree representations.
  1348. */
  1349. /* Build the bit length tree for the above two trees, and get the index
  1350. * in bl_order of the last bit length code to send.
  1351. */
  1352. max_blindex = build_bl_tree();
  1353. /* Determine the best encoding. Compute first the block length in bytes */
  1354. opt_lenb = (G2.opt_len + 3 + 7) >> 3;
  1355. static_lenb = (G2.static_len + 3 + 7) >> 3;
  1356. Trace((stderr,
  1357. "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
  1358. opt_lenb, G2.opt_len, static_lenb, G2.static_len, stored_len,
  1359. G2.last_lit, G2.last_dist));
  1360. if (static_lenb <= opt_lenb)
  1361. opt_lenb = static_lenb;
  1362. /* If compression failed and this is the first and last block,
  1363. * and if the zip file can be seeked (to rewrite the local header),
  1364. * the whole file is transformed into a stored file:
  1365. */
  1366. if (stored_len <= opt_lenb && eof && G2.compressed_len == 0L && seekable()) {
  1367. /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  1368. if (buf == NULL)
  1369. bb_error_msg("block vanished");
  1370. copy_block(buf, (unsigned) stored_len, 0); /* without header */
  1371. G2.compressed_len = stored_len << 3;
  1372. } else if (stored_len + 4 <= opt_lenb && buf != NULL) {
  1373. /* 4: two words for the lengths */
  1374. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  1375. * Otherwise we can't have processed more than WSIZE input bytes since
  1376. * the last block flush, because compression would have been
  1377. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  1378. * transform a block into a stored block.
  1379. */
  1380. send_bits((STORED_BLOCK << 1) + eof, 3); /* send block type */
  1381. G2.compressed_len = (G2.compressed_len + 3 + 7) & ~7L;
  1382. G2.compressed_len += (stored_len + 4) << 3;
  1383. copy_block(buf, (unsigned) stored_len, 1); /* with header */
  1384. } else if (static_lenb == opt_lenb) {
  1385. send_bits((STATIC_TREES << 1) + eof, 3);
  1386. compress_block((ct_data *) G2.static_ltree, (ct_data *) G2.static_dtree);
  1387. G2.compressed_len += 3 + G2.static_len;
  1388. } else {
  1389. send_bits((DYN_TREES << 1) + eof, 3);
  1390. send_all_trees(G2.l_desc.max_code + 1, G2.d_desc.max_code + 1,
  1391. max_blindex + 1);
  1392. compress_block((ct_data *) G2.dyn_ltree, (ct_data *) G2.dyn_dtree);
  1393. G2.compressed_len += 3 + G2.opt_len;
  1394. }
  1395. Assert(G2.compressed_len == G1.bits_sent, "bad compressed size");
  1396. init_block();
  1397. if (eof) {
  1398. bi_windup();
  1399. G2.compressed_len += 7; /* align on byte boundary */
  1400. }
  1401. Tracev((stderr, "\ncomprlen %lu(%lu) ", G2.compressed_len >> 3,
  1402. G2.compressed_len - 7 * eof));
  1403. return G2.compressed_len >> 3;
  1404. }
  1405. /* ===========================================================================
  1406. * Update a hash value with the given input byte
  1407. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  1408. * input characters, so that a running hash key can be computed from the
  1409. * previous key instead of complete recalculation each time.
  1410. */
  1411. #define UPDATE_HASH(h, c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  1412. /* ===========================================================================
  1413. * Same as above, but achieves better compression. We use a lazy
  1414. * evaluation for matches: a match is finally adopted only if there is
  1415. * no better match at the next window position.
  1416. *
  1417. * Processes a new input file and return its compressed length. Sets
  1418. * the compressed length, crc, deflate flags and internal file
  1419. * attributes.
  1420. */
  1421. /* Flush the current block, with given end-of-file flag.
  1422. * IN assertion: strstart is set to the end of the current match. */
  1423. #define FLUSH_BLOCK(eof) \
  1424. flush_block( \
  1425. G1.block_start >= 0L \
  1426. ? (char*)&G1.window[(unsigned)G1.block_start] \
  1427. : (char*)NULL, \
  1428. (ulg)G1.strstart - G1.block_start, \
  1429. (eof) \
  1430. )
  1431. /* Insert string s in the dictionary and set match_head to the previous head
  1432. * of the hash chain (the most recent string with same hash key). Return
  1433. * the previous length of the hash chain.
  1434. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  1435. * input characters and the first MIN_MATCH bytes of s are valid
  1436. * (except for the last MIN_MATCH-1 bytes of the input file). */
  1437. #define INSERT_STRING(s, match_head) \
  1438. do { \
  1439. UPDATE_HASH(G1.ins_h, G1.window[(s) + MIN_MATCH-1]); \
  1440. G1.prev[(s) & WMASK] = match_head = head[G1.ins_h]; \
  1441. head[G1.ins_h] = (s); \
  1442. } while (0)
  1443. static ulg deflate(void)
  1444. {
  1445. IPos hash_head; /* head of hash chain */
  1446. IPos prev_match; /* previous match */
  1447. int flush; /* set if current block must be flushed */
  1448. int match_available = 0; /* set if previous match exists */
  1449. unsigned match_length = MIN_MATCH - 1; /* length of best match */
  1450. /* Process the input block. */
  1451. while (G1.lookahead != 0) {
  1452. /* Insert the string window[strstart .. strstart+2] in the
  1453. * dictionary, and set hash_head to the head of the hash chain:
  1454. */
  1455. INSERT_STRING(G1.strstart, hash_head);
  1456. /* Find the longest match, discarding those <= prev_length.
  1457. */
  1458. G1.prev_length = match_length;
  1459. prev_match = G1.match_start;
  1460. match_length = MIN_MATCH - 1;
  1461. if (hash_head != 0 && G1.prev_length < max_lazy_match
  1462. && G1.strstart - hash_head <= MAX_DIST
  1463. ) {
  1464. /* To simplify the code, we prevent matches with the string
  1465. * of window index 0 (in particular we have to avoid a match
  1466. * of the string with itself at the start of the input file).
  1467. */
  1468. match_length = longest_match(hash_head);
  1469. /* longest_match() sets match_start */
  1470. if (match_length > G1.lookahead)
  1471. match_length = G1.lookahead;
  1472. /* Ignore a length 3 match if it is too distant: */
  1473. if (match_length == MIN_MATCH && G1.strstart - G1.match_start > TOO_FAR) {
  1474. /* If prev_match is also MIN_MATCH, G1.match_start is garbage
  1475. * but we will ignore the current match anyway.
  1476. */
  1477. match_length--;
  1478. }
  1479. }
  1480. /* If there was a match at the previous step and the current
  1481. * match is not better, output the previous match:
  1482. */
  1483. if (G1.prev_length >= MIN_MATCH && match_length <= G1.prev_length) {
  1484. check_match(G1.strstart - 1, prev_match, G1.prev_length);
  1485. flush = ct_tally(G1.strstart - 1 - prev_match, G1.prev_length - MIN_MATCH);
  1486. /* Insert in hash table all strings up to the end of the match.
  1487. * strstart-1 and strstart are already inserted.
  1488. */
  1489. G1.lookahead -= G1.prev_length - 1;
  1490. G1.prev_length -= 2;
  1491. do {
  1492. G1.strstart++;
  1493. INSERT_STRING(G1.strstart, hash_head);
  1494. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1495. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  1496. * these bytes are garbage, but it does not matter since the
  1497. * next lookahead bytes will always be emitted as literals.
  1498. */
  1499. } while (--G1.prev_length != 0);
  1500. match_available = 0;
  1501. match_length = MIN_MATCH - 1;
  1502. G1.strstart++;
  1503. if (flush) {
  1504. FLUSH_BLOCK(0);
  1505. G1.block_start = G1.strstart;
  1506. }
  1507. } else if (match_available) {
  1508. /* If there was no match at the previous position, output a
  1509. * single literal. If there was a match but the current match
  1510. * is longer, truncate the previous match to a single literal.
  1511. */
  1512. Tracevv((stderr, "%c", G1.window[G1.strstart - 1]));
  1513. if (ct_tally(0, G1.window[G1.strstart - 1])) {
  1514. FLUSH_BLOCK(0);
  1515. G1.block_start = G1.strstart;
  1516. }
  1517. G1.strstart++;
  1518. G1.lookahead--;
  1519. } else {
  1520. /* There is no previous match to compare with, wait for
  1521. * the next step to decide.
  1522. */
  1523. match_available = 1;
  1524. G1.strstart++;
  1525. G1.lookahead--;
  1526. }
  1527. Assert(G1.strstart <= G1.isize && lookahead <= G1.isize, "a bit too far");
  1528. /* Make sure that we always have enough lookahead, except
  1529. * at the end of the input file. We need MAX_MATCH bytes
  1530. * for the next match, plus MIN_MATCH bytes to insert the
  1531. * string following the next match.
  1532. */
  1533. while (G1.lookahead < MIN_LOOKAHEAD && !G1.eofile)
  1534. fill_window();
  1535. }
  1536. if (match_available)
  1537. ct_tally(0, G1.window[G1.strstart - 1]);
  1538. return FLUSH_BLOCK(1); /* eof */
  1539. }
  1540. /* ===========================================================================
  1541. * Initialize the bit string routines.
  1542. */
  1543. static void bi_init(void)
  1544. {
  1545. G1.bi_buf = 0;
  1546. G1.bi_valid = 0;
  1547. #ifdef DEBUG
  1548. G1.bits_sent = 0L;
  1549. #endif
  1550. }
  1551. /* ===========================================================================
  1552. * Initialize the "longest match" routines for a new file
  1553. */
  1554. static void lm_init(ush * flagsp)
  1555. {
  1556. unsigned j;
  1557. /* Initialize the hash table. */
  1558. memset(head, 0, HASH_SIZE * sizeof(*head));
  1559. /* prev will be initialized on the fly */
  1560. /* speed options for the general purpose bit flag */
  1561. *flagsp |= 2; /* FAST 4, SLOW 2 */
  1562. /* ??? reduce max_chain_length for binary files */
  1563. G1.strstart = 0;
  1564. G1.block_start = 0L;
  1565. G1.lookahead = file_read(G1.window,
  1566. sizeof(int) <= 2 ? (unsigned) WSIZE : 2 * WSIZE);
  1567. if (G1.lookahead == 0 || G1.lookahead == (unsigned) -1) {
  1568. G1.eofile = 1;
  1569. G1.lookahead = 0;
  1570. return;
  1571. }
  1572. G1.eofile = 0;
  1573. /* Make sure that we always have enough lookahead. This is important
  1574. * if input comes from a device such as a tty.
  1575. */
  1576. while (G1.lookahead < MIN_LOOKAHEAD && !G1.eofile)
  1577. fill_window();
  1578. G1.ins_h = 0;
  1579. for (j = 0; j < MIN_MATCH - 1; j++)
  1580. UPDATE_HASH(G1.ins_h, G1.window[j]);
  1581. /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  1582. * not important since only literal bytes will be emitted.
  1583. */
  1584. }
  1585. /* ===========================================================================
  1586. * Allocate the match buffer, initialize the various tables and save the
  1587. * location of the internal file attribute (ascii/binary) and method
  1588. * (DEFLATE/STORE).
  1589. * One callsite in zip()
  1590. */
  1591. static void ct_init(void)
  1592. {
  1593. int n; /* iterates over tree elements */
  1594. int length; /* length value */
  1595. int code; /* code value */
  1596. int dist; /* distance index */
  1597. G2.compressed_len = 0L;
  1598. #ifdef NOT_NEEDED
  1599. if (G2.static_dtree[0].Len != 0)
  1600. return; /* ct_init already called */
  1601. #endif
  1602. /* Initialize the mapping length (0..255) -> length code (0..28) */
  1603. length = 0;
  1604. for (code = 0; code < LENGTH_CODES - 1; code++) {
  1605. G2.base_length[code] = length;
  1606. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  1607. G2.length_code[length++] = code;
  1608. }
  1609. }
  1610. Assert(length == 256, "ct_init: length != 256");
  1611. /* Note that the length 255 (match length 258) can be represented
  1612. * in two different ways: code 284 + 5 bits or code 285, so we
  1613. * overwrite length_code[255] to use the best encoding:
  1614. */
  1615. G2.length_code[length - 1] = code;
  1616. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  1617. dist = 0;
  1618. for (code = 0; code < 16; code++) {
  1619. G2.base_dist[code] = dist;
  1620. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  1621. G2.dist_code[dist++] = code;
  1622. }
  1623. }
  1624. Assert(dist == 256, "ct_init: dist != 256");
  1625. dist >>= 7; /* from now on, all distances are divided by 128 */
  1626. for (; code < D_CODES; code++) {
  1627. G2.base_dist[code] = dist << 7;
  1628. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  1629. G2.dist_code[256 + dist++] = code;
  1630. }
  1631. }
  1632. Assert(dist == 256, "ct_init: 256+dist != 512");
  1633. /* Construct the codes of the static literal tree */
  1634. /* already zeroed - it's in bss
  1635. for (n = 0; n <= MAX_BITS; n++)
  1636. G2.bl_count[n] = 0; */
  1637. n = 0;
  1638. while (n <= 143) {
  1639. G2.static_ltree[n++].Len = 8;
  1640. G2.bl_count[8]++;
  1641. }
  1642. while (n <= 255) {
  1643. G2.static_ltree[n++].Len = 9;
  1644. G2.bl_count[9]++;
  1645. }
  1646. while (n <= 279) {
  1647. G2.static_ltree[n++].Len = 7;
  1648. G2.bl_count[7]++;
  1649. }
  1650. while (n <= 287) {
  1651. G2.static_ltree[n++].Len = 8;
  1652. G2.bl_count[8]++;
  1653. }
  1654. /* Codes 286 and 287 do not exist, but we must include them in the
  1655. * tree construction to get a canonical Huffman tree (longest code
  1656. * all ones)
  1657. */
  1658. gen_codes((ct_data *) G2.static_ltree, L_CODES + 1);
  1659. /* The static distance tree is trivial: */
  1660. for (n = 0; n < D_CODES; n++) {
  1661. G2.static_dtree[n].Len = 5;
  1662. G2.static_dtree[n].Code = bi_reverse(n, 5);
  1663. }
  1664. /* Initialize the first block of the first file: */
  1665. init_block();
  1666. }
  1667. /* ===========================================================================
  1668. * Deflate in to out.
  1669. * IN assertions: the input and output buffers are cleared.
  1670. */
  1671. static void zip(ulg time_stamp)
  1672. {
  1673. ush deflate_flags = 0; /* pkzip -es, -en or -ex equivalent */
  1674. G1.outcnt = 0;
  1675. /* Write the header to the gzip file. See algorithm.doc for the format */
  1676. /* magic header for gzip files: 1F 8B */
  1677. /* compression method: 8 (DEFLATED) */
  1678. /* general flags: 0 */
  1679. put_32bit(0x00088b1f);
  1680. put_32bit(time_stamp);
  1681. /* Write deflated file to zip file */
  1682. G1.crc = ~0;
  1683. bi_init();
  1684. ct_init();
  1685. lm_init(&deflate_flags);
  1686. put_8bit(deflate_flags); /* extra flags */
  1687. put_8bit(3); /* OS identifier = 3 (Unix) */
  1688. deflate();
  1689. /* Write the crc and uncompressed size */
  1690. put_32bit(~G1.crc);
  1691. put_32bit(G1.isize);
  1692. flush_outbuf();
  1693. }
  1694. /* ======================================================================== */
  1695. static
  1696. char* make_new_name_gzip(char *filename)
  1697. {
  1698. return xasprintf("%s.gz", filename);
  1699. }
  1700. static
  1701. IF_DESKTOP(long long) int pack_gzip(unpack_info_t *info UNUSED_PARAM)
  1702. {
  1703. struct stat s;
  1704. /* Clear input and output buffers */
  1705. G1.outcnt = 0;
  1706. #ifdef DEBUG
  1707. G1.insize = 0;
  1708. #endif
  1709. G1.isize = 0;
  1710. /* Reinit G2.xxx */
  1711. memset(&G2, 0, sizeof(G2));
  1712. G2.l_desc.dyn_tree = G2.dyn_ltree;
  1713. G2.l_desc.static_tree = G2.static_ltree;
  1714. G2.l_desc.extra_bits = extra_lbits;
  1715. G2.l_desc.extra_base = LITERALS + 1;
  1716. G2.l_desc.elems = L_CODES;
  1717. G2.l_desc.max_length = MAX_BITS;
  1718. //G2.l_desc.max_code = 0;
  1719. G2.d_desc.dyn_tree = G2.dyn_dtree;
  1720. G2.d_desc.static_tree = G2.static_dtree;
  1721. G2.d_desc.extra_bits = extra_dbits;
  1722. //G2.d_desc.extra_base = 0;
  1723. G2.d_desc.elems = D_CODES;
  1724. G2.d_desc.max_length = MAX_BITS;
  1725. //G2.d_desc.max_code = 0;
  1726. G2.bl_desc.dyn_tree = G2.bl_tree;
  1727. //G2.bl_desc.static_tree = NULL;
  1728. G2.bl_desc.extra_bits = extra_blbits,
  1729. //G2.bl_desc.extra_base = 0;
  1730. G2.bl_desc.elems = BL_CODES;
  1731. G2.bl_desc.max_length = MAX_BL_BITS;
  1732. //G2.bl_desc.max_code = 0;
  1733. s.st_ctime = 0;
  1734. fstat(STDIN_FILENO, &s);
  1735. zip(s.st_ctime);
  1736. return 0;
  1737. }
  1738. #if ENABLE_FEATURE_GZIP_LONG_OPTIONS
  1739. static const char gzip_longopts[] ALIGN1 =
  1740. "stdout\0" No_argument "c"
  1741. "to-stdout\0" No_argument "c"
  1742. "force\0" No_argument "f"
  1743. "verbose\0" No_argument "v"
  1744. #if ENABLE_GUNZIP
  1745. "decompress\0" No_argument "d"
  1746. "uncompress\0" No_argument "d"
  1747. "test\0" No_argument "t"
  1748. #endif
  1749. "quiet\0" No_argument "q"
  1750. "fast\0" No_argument "1"
  1751. "best\0" No_argument "9"
  1752. ;
  1753. #endif
  1754. /*
  1755. * Linux kernel build uses gzip -d -n. We accept and ignore it.
  1756. * Man page says:
  1757. * -n --no-name
  1758. * gzip: do not save the original file name and time stamp.
  1759. * (The original name is always saved if the name had to be truncated.)
  1760. * gunzip: do not restore the original file name/time even if present
  1761. * (remove only the gzip suffix from the compressed file name).
  1762. * This option is the default when decompressing.
  1763. * -N --name
  1764. * gzip: always save the original file name and time stamp (this is the default)
  1765. * gunzip: restore the original file name and time stamp if present.
  1766. */
  1767. int gzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1768. #if ENABLE_GUNZIP
  1769. int gzip_main(int argc, char **argv)
  1770. #else
  1771. int gzip_main(int argc UNUSED_PARAM, char **argv)
  1772. #endif
  1773. {
  1774. unsigned opt;
  1775. #if ENABLE_FEATURE_GZIP_LONG_OPTIONS
  1776. applet_long_options = gzip_longopts;
  1777. #endif
  1778. /* Must match bbunzip's constants OPT_STDOUT, OPT_FORCE! */
  1779. opt = getopt32(argv, "cfv" IF_GUNZIP("dt") "q123456789n");
  1780. #if ENABLE_GUNZIP /* gunzip_main may not be visible... */
  1781. if (opt & 0x18) // -d and/or -t
  1782. return gunzip_main(argc, argv);
  1783. #endif
  1784. option_mask32 &= 0x7; /* ignore -q, -0..9 */
  1785. //if (opt & 0x1) // -c
  1786. //if (opt & 0x2) // -f
  1787. //if (opt & 0x4) // -v
  1788. argv += optind;
  1789. SET_PTR_TO_GLOBALS((char *)xzalloc(sizeof(struct globals)+sizeof(struct globals2))
  1790. + sizeof(struct globals));
  1791. /* Allocate all global buffers (for DYN_ALLOC option) */
  1792. ALLOC(uch, G1.l_buf, INBUFSIZ);
  1793. ALLOC(uch, G1.outbuf, OUTBUFSIZ);
  1794. ALLOC(ush, G1.d_buf, DIST_BUFSIZE);
  1795. ALLOC(uch, G1.window, 2L * WSIZE);
  1796. ALLOC(ush, G1.prev, 1L << BITS);
  1797. /* Initialise the CRC32 table */
  1798. G1.crc_32_tab = crc32_filltable(NULL, 0);
  1799. return bbunpack(argv, make_new_name_gzip, pack_gzip);
  1800. }