gzip.c 69 KB

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