3
0

gzip.c 71 KB

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