gzip.c 66 KB

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