gzip.c 64 KB

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