trees.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. /*
  2. trees.h - Zip 3
  3. Copyright (c) 1990-2007 Info-ZIP. All rights reserved.
  4. See the accompanying file LICENSE, version 2005-Feb-10 or later
  5. (the contents of which are also included in zip.h) for terms of use.
  6. If, for some reason, all these files are missing, the Info-ZIP license
  7. also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html
  8. */
  9. /*
  10. * trees.c by Jean-loup Gailly
  11. *
  12. * This is a new version of im_ctree.c originally written by Richard B. Wales
  13. * for the defunct implosion method.
  14. * The low level bit string handling routines from bits.c (originally
  15. * im_bits.c written by Richard B. Wales) have been merged into this version
  16. * of trees.c.
  17. *
  18. * PURPOSE
  19. *
  20. * Encode various sets of source values using variable-length
  21. * binary code trees.
  22. * Output the resulting variable-length bit strings.
  23. * Compression can be done to a file or to memory.
  24. *
  25. * DISCUSSION
  26. *
  27. * The PKZIP "deflation" process uses several Huffman trees. The more
  28. * common source values are represented by shorter bit sequences.
  29. *
  30. * Each code tree is stored in the ZIP file in a compressed form
  31. * which is itself a Huffman encoding of the lengths of
  32. * all the code strings (in ascending order by source values).
  33. * The actual code strings are reconstructed from the lengths in
  34. * the UNZIP process, as described in the "application note"
  35. * (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
  36. *
  37. * The PKZIP "deflate" file format interprets compressed file data
  38. * as a sequence of bits. Multi-bit strings in the file may cross
  39. * byte boundaries without restriction.
  40. * The first bit of each byte is the low-order bit.
  41. *
  42. * The routines in this file allow a variable-length bit value to
  43. * be output right-to-left (useful for literal values). For
  44. * left-to-right output (useful for code strings from the tree routines),
  45. * the bits must have been reversed first with bi_reverse().
  46. *
  47. * For in-memory compression, the compressed bit stream goes directly
  48. * into the requested output buffer. The buffer is limited to 64K on
  49. * 16 bit machines; flushing of the output buffer during compression
  50. * process is not supported.
  51. * The input data is read in blocks by the (*read_buf)() function.
  52. *
  53. * For more details about input to and output from the deflation routines,
  54. * see the actual input functions for (*read_buf)(), flush_outbuf(), and
  55. * the filecompress() resp. memcompress() wrapper functions which handle
  56. * the I/O setup.
  57. *
  58. * REFERENCES
  59. *
  60. * Lynch, Thomas J.
  61. * Data Compression: Techniques and Applications, pp. 53-55.
  62. * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
  63. *
  64. * Storer, James A.
  65. * Data Compression: Methods and Theory, pp. 49-50.
  66. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  67. *
  68. * Sedgewick, R.
  69. * Algorithms, p290.
  70. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  71. *
  72. * INTERFACE
  73. *
  74. * void ct_init (ush *attr, int *method)
  75. * Allocate the match buffer, initialize the various tables and save
  76. * the location of the internal file attribute (ascii/binary) and
  77. * method (DEFLATE/STORE)
  78. *
  79. * void ct_tally (int dist, int lc);
  80. * Save the match info and tally the frequency counts.
  81. *
  82. * uzoff_t flush_block (char *buf, ulg stored_len, int eof)
  83. * Determine the best encoding for the current block: dynamic trees,
  84. * static trees or store, and output the encoded block to the zip
  85. * file. Returns the total compressed length for the file so far.
  86. *
  87. * void bi_init (char *tgt_buf, unsigned tgt_size, int flsh_allowed)
  88. * Initialize the bit string routines.
  89. *
  90. * Most of the bit string output functions are only used internally
  91. * in this source file, they are normally declared as "local" routines:
  92. *
  93. * local void send_bits (int value, int length)
  94. * Write out a bit string, taking the source bits right to
  95. * left.
  96. *
  97. * local unsigned bi_reverse (unsigned code, int len)
  98. * Reverse the bits of a bit string, taking the source bits left to
  99. * right and emitting them right to left.
  100. *
  101. * local void bi_windup (void)
  102. * Write out any remaining bits in an incomplete byte.
  103. *
  104. * local void copy_block(char *buf, unsigned len, int header)
  105. * Copy a stored block to the zip file, storing first the length and
  106. * its one's complement if requested.
  107. *
  108. * All output that exceeds the bitstring output buffer size (as initialized
  109. * by bi_init() is fed through an externally provided transfer routine
  110. * which flushes the bitstring output buffer on request and resets the
  111. * buffer fill counter:
  112. *
  113. * extern void flush_outbuf(char *o_buf, unsigned *o_idx);
  114. *
  115. */
  116. #define __TREES_C
  117. /* Put zip.h first as when using 64-bit file environment in unix ctype.h
  118. defines off_t and then while other files are using an 8-byte off_t this
  119. file gets a 4-byte off_t. Once zip.h sets the large file defines can
  120. then include ctype.h and get 8-byte off_t. 8/14/04 EG */
  121. #include "zip.h"
  122. #include <ctype.h>
  123. #ifndef USE_ZLIB
  124. /* ===========================================================================
  125. * Constants
  126. */
  127. #define MAX_BITS 15
  128. /* All codes must not exceed MAX_BITS bits */
  129. #define MAX_BL_BITS 7
  130. /* Bit length codes must not exceed MAX_BL_BITS bits */
  131. #define LENGTH_CODES 29
  132. /* number of length codes, not counting the special END_BLOCK code */
  133. #define LITERALS 256
  134. /* number of literal bytes 0..255 */
  135. #define END_BLOCK 256
  136. /* end of block literal code */
  137. #define L_CODES (LITERALS+1+LENGTH_CODES)
  138. /* number of Literal or Length codes, including the END_BLOCK code */
  139. #define D_CODES 30
  140. /* number of distance codes */
  141. #define BL_CODES 19
  142. /* number of codes used to transfer the bit lengths */
  143. local int near extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  144. = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  145. local int near extra_dbits[D_CODES] /* extra bits for each distance code */
  146. = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  147. local int near extra_blbits[BL_CODES]/* extra bits for each bit length code */
  148. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  149. #define STORED_BLOCK 0
  150. #define STATIC_TREES 1
  151. #define DYN_TREES 2
  152. /* The three kinds of block type */
  153. #ifndef LIT_BUFSIZE
  154. # ifdef SMALL_MEM
  155. # define LIT_BUFSIZE 0x2000
  156. # else
  157. # ifdef MEDIUM_MEM
  158. # define LIT_BUFSIZE 0x4000
  159. # else
  160. # define LIT_BUFSIZE 0x8000
  161. # endif
  162. # endif
  163. #endif
  164. #define DIST_BUFSIZE LIT_BUFSIZE
  165. /* Sizes of match buffers for literals/lengths and distances. There are
  166. * 4 reasons for limiting LIT_BUFSIZE to 64K:
  167. * - frequencies can be kept in 16 bit counters
  168. * - if compression is not successful for the first block, all input data is
  169. * still in the window so we can still emit a stored block even when input
  170. * comes from standard input. (This can also be done for all blocks if
  171. * LIT_BUFSIZE is not greater than 32K.)
  172. * - if compression is not successful for a file smaller than 64K, we can
  173. * even emit a stored file instead of a stored block (saving 5 bytes).
  174. * - creating new Huffman trees less frequently may not provide fast
  175. * adaptation to changes in the input data statistics. (Take for
  176. * example a binary file with poorly compressible code followed by
  177. * a highly compressible string table.) Smaller buffer sizes give
  178. * fast adaptation but have of course the overhead of transmitting trees
  179. * more frequently.
  180. * - I can't count above 4
  181. * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
  182. * memory at the expense of compression). Some optimizations would be possible
  183. * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
  184. */
  185. #define REP_3_6 16
  186. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  187. #define REPZ_3_10 17
  188. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  189. #define REPZ_11_138 18
  190. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  191. /* ===========================================================================
  192. * Local data
  193. */
  194. /* Data structure describing a single value and its code string. */
  195. typedef struct ct_data {
  196. union {
  197. ush freq; /* frequency count */
  198. ush code; /* bit string */
  199. } fc;
  200. union {
  201. ush dad; /* father node in Huffman tree */
  202. ush len; /* length of bit string */
  203. } dl;
  204. } ct_data;
  205. #define Freq fc.freq
  206. #define Code fc.code
  207. #define Dad dl.dad
  208. #define Len dl.len
  209. #define HEAP_SIZE (2*L_CODES+1)
  210. /* maximum heap size */
  211. local ct_data near dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  212. local ct_data near dyn_dtree[2*D_CODES+1]; /* distance tree */
  213. local ct_data near static_ltree[L_CODES+2];
  214. /* The static literal tree. Since the bit lengths are imposed, there is no
  215. * need for the L_CODES extra codes used during heap construction. However
  216. * The codes 286 and 287 are needed to build a canonical tree (see ct_init
  217. * below).
  218. */
  219. local ct_data near static_dtree[D_CODES];
  220. /* The static distance tree. (Actually a trivial tree since all codes use
  221. * 5 bits.)
  222. */
  223. local ct_data near bl_tree[2*BL_CODES+1];
  224. /* Huffman tree for the bit lengths */
  225. typedef struct tree_desc {
  226. ct_data near *dyn_tree; /* the dynamic tree */
  227. ct_data near *static_tree; /* corresponding static tree or NULL */
  228. int near *extra_bits; /* extra bits for each code or NULL */
  229. int extra_base; /* base index for extra_bits */
  230. int elems; /* max number of elements in the tree */
  231. int max_length; /* max bit length for the codes */
  232. int max_code; /* largest code with non zero frequency */
  233. } tree_desc;
  234. local tree_desc near l_desc =
  235. {dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0};
  236. local tree_desc near d_desc =
  237. {dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0};
  238. local tree_desc near bl_desc =
  239. {bl_tree, NULL, extra_blbits, 0, BL_CODES, MAX_BL_BITS, 0};
  240. local ush near bl_count[MAX_BITS+1];
  241. /* number of codes at each bit length for an optimal tree */
  242. local uch near bl_order[BL_CODES]
  243. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  244. /* The lengths of the bit length codes are sent in order of decreasing
  245. * probability, to avoid transmitting the lengths for unused bit length codes.
  246. */
  247. local int near heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  248. local int heap_len; /* number of elements in the heap */
  249. local int heap_max; /* element of largest frequency */
  250. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  251. * The same heap array is used to build all trees.
  252. */
  253. local uch near depth[2*L_CODES+1];
  254. /* Depth of each subtree used as tie breaker for trees of equal frequency */
  255. local uch length_code[MAX_MATCH-MIN_MATCH+1];
  256. /* length code for each normalized match length (0 == MIN_MATCH) */
  257. local uch dist_code[512];
  258. /* distance codes. The first 256 values correspond to the distances
  259. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  260. * the 15 bit distances.
  261. */
  262. local int near base_length[LENGTH_CODES];
  263. /* First normalized length for each code (0 = MIN_MATCH) */
  264. local int near base_dist[D_CODES];
  265. /* First normalized distance for each code (0 = distance of 1) */
  266. #ifndef DYN_ALLOC
  267. local uch far l_buf[LIT_BUFSIZE]; /* buffer for literals/lengths */
  268. local ush far d_buf[DIST_BUFSIZE]; /* buffer for distances */
  269. #else
  270. local uch far *l_buf;
  271. local ush far *d_buf;
  272. #endif
  273. local uch near flag_buf[(LIT_BUFSIZE/8)];
  274. /* flag_buf is a bit array distinguishing literals from lengths in
  275. * l_buf, and thus indicating the presence or absence of a distance.
  276. */
  277. local unsigned last_lit; /* running index in l_buf */
  278. local unsigned last_dist; /* running index in d_buf */
  279. local unsigned last_flags; /* running index in flag_buf */
  280. local uch flags; /* current flags not yet saved in flag_buf */
  281. local uch flag_bit; /* current bit used in flags */
  282. /* bits are filled in flags starting at bit 0 (least significant).
  283. * Note: these flags are overkill in the current code since we don't
  284. * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
  285. */
  286. local ulg opt_len; /* bit length of current block with optimal trees */
  287. local ulg static_len; /* bit length of current block with static trees */
  288. /* zip64 support 08/29/2003 R.Nausedat */
  289. /* now all file sizes and offsets are zoff_t 7/24/04 EG */
  290. local uzoff_t cmpr_bytelen; /* total byte length of compressed file */
  291. local ulg cmpr_len_bits; /* number of bits past 'cmpr_bytelen' */
  292. #ifdef DEBUG
  293. local uzoff_t input_len; /* total byte length of input file */
  294. /* input_len is for debugging only since we can get it by other means. */
  295. #endif
  296. local ush *file_type; /* pointer to UNKNOWN, BINARY or ASCII */
  297. local int *file_method; /* pointer to DEFLATE or STORE */
  298. /* ===========================================================================
  299. * Local data used by the "bit string" routines.
  300. */
  301. local int flush_flg;
  302. #if (!defined(ASMV) || !defined(RISCOS))
  303. local unsigned bi_buf;
  304. #else
  305. unsigned bi_buf;
  306. #endif
  307. /* Output buffer. bits are inserted starting at the bottom (least significant
  308. * bits). The width of bi_buf must be at least 16 bits.
  309. */
  310. #define Buf_size (8 * 2*sizeof(char))
  311. /* Number of bits used within bi_buf. (bi_buf may be implemented on
  312. * more than 16 bits on some systems.)
  313. */
  314. #if (!defined(ASMV) || !defined(RISCOS))
  315. local int bi_valid;
  316. #else
  317. int bi_valid;
  318. #endif
  319. /* Number of valid bits in bi_buf. All bits above the last valid bit
  320. * are always zero.
  321. */
  322. #if (!defined(ASMV) || !defined(RISCOS))
  323. local char *out_buf;
  324. #else
  325. char *out_buf;
  326. #endif
  327. /* Current output buffer. */
  328. #if (!defined(ASMV) || !defined(RISCOS))
  329. local unsigned out_offset;
  330. #else
  331. unsigned out_offset;
  332. #endif
  333. /* Current offset in output buffer.
  334. * On 16 bit machines, the buffer is limited to 64K.
  335. */
  336. #if !defined(ASMV) || !defined(RISCOS)
  337. local unsigned out_size;
  338. #else
  339. unsigned out_size;
  340. #endif
  341. /* Size of current output buffer */
  342. /* Output a 16 bit value to the bit stream, lower (oldest) byte first */
  343. #define PUTSHORT(w) \
  344. { if (out_offset >= out_size-1) \
  345. flush_outbuf(out_buf, &out_offset); \
  346. out_buf[out_offset++] = (char) ((w) & 0xff); \
  347. out_buf[out_offset++] = (char) ((ush)(w) >> 8); \
  348. }
  349. #define PUTBYTE(b) \
  350. { if (out_offset >= out_size) \
  351. flush_outbuf(out_buf, &out_offset); \
  352. out_buf[out_offset++] = (char) (b); \
  353. }
  354. #ifdef DEBUG
  355. local uzoff_t bits_sent; /* bit length of the compressed data */
  356. extern uzoff_t isize; /* byte length of input file */
  357. #endif
  358. extern long block_start; /* window offset of current block */
  359. extern unsigned near strstart; /* window offset of current string */
  360. /* ===========================================================================
  361. * Local (static) routines in this file.
  362. */
  363. local void init_block OF((void));
  364. local void pqdownheap OF((ct_data near *tree, int k));
  365. local void gen_bitlen OF((tree_desc near *desc));
  366. local void gen_codes OF((ct_data near *tree, int max_code));
  367. local void build_tree OF((tree_desc near *desc));
  368. local void scan_tree OF((ct_data near *tree, int max_code));
  369. local void send_tree OF((ct_data near *tree, int max_code));
  370. local int build_bl_tree OF((void));
  371. local void send_all_trees OF((int lcodes, int dcodes, int blcodes));
  372. local void compress_block OF((ct_data near *ltree, ct_data near *dtree));
  373. local void set_file_type OF((void));
  374. #if (!defined(ASMV) || !defined(RISCOS))
  375. local void send_bits OF((int value, int length));
  376. local unsigned bi_reverse OF((unsigned code, int len));
  377. #endif
  378. local void bi_windup OF((void));
  379. local void copy_block OF((char *buf, unsigned len, int header));
  380. #ifndef DEBUG
  381. # define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
  382. /* Send a code of the given tree. c and tree must not have side effects */
  383. #else /* DEBUG */
  384. # define send_code(c, tree) \
  385. { if (verbose>1) fprintf(mesg,"\ncd %3d ",(c)); \
  386. send_bits(tree[c].Code, tree[c].Len); }
  387. #endif
  388. #define d_code(dist) \
  389. ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
  390. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  391. * must not have side effects. dist_code[256] and dist_code[257] are never
  392. * used.
  393. */
  394. #define Max(a,b) (a >= b ? a : b)
  395. /* the arguments must not have side effects */
  396. /* ===========================================================================
  397. * Allocate the match buffer, initialize the various tables and save the
  398. * location of the internal file attribute (ascii/binary) and method
  399. * (DEFLATE/STORE).
  400. */
  401. void ct_init(attr, method)
  402. ush *attr; /* pointer to internal file attribute */
  403. int *method; /* pointer to compression method */
  404. {
  405. int n; /* iterates over tree elements */
  406. int bits; /* bit counter */
  407. int length; /* length value */
  408. int code; /* code value */
  409. int dist; /* distance index */
  410. file_type = attr;
  411. file_method = method;
  412. cmpr_len_bits = 0L;
  413. cmpr_bytelen = (uzoff_t)0;
  414. #ifdef DEBUG
  415. input_len = (uzoff_t)0;
  416. #endif
  417. if (static_dtree[0].Len != 0) return; /* ct_init already called */
  418. #ifdef DYN_ALLOC
  419. d_buf = (ush far *) zcalloc(DIST_BUFSIZE, sizeof(ush));
  420. l_buf = (uch far *) zcalloc(LIT_BUFSIZE/2, 2);
  421. /* Avoid using the value 64K on 16 bit machines */
  422. if (l_buf == NULL || d_buf == NULL)
  423. ziperr(ZE_MEM, "ct_init: out of memory");
  424. #endif
  425. /* Initialize the mapping length (0..255) -> length code (0..28) */
  426. length = 0;
  427. for (code = 0; code < LENGTH_CODES-1; code++) {
  428. base_length[code] = length;
  429. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  430. length_code[length++] = (uch)code;
  431. }
  432. }
  433. Assert(length == 256, "ct_init: length != 256");
  434. /* Note that the length 255 (match length 258) can be represented
  435. * in two different ways: code 284 + 5 bits or code 285, so we
  436. * overwrite length_code[255] to use the best encoding:
  437. */
  438. length_code[length-1] = (uch)code;
  439. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  440. dist = 0;
  441. for (code = 0 ; code < 16; code++) {
  442. base_dist[code] = dist;
  443. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  444. dist_code[dist++] = (uch)code;
  445. }
  446. }
  447. Assert(dist == 256, "ct_init: dist != 256");
  448. dist >>= 7; /* from now on, all distances are divided by 128 */
  449. for ( ; code < D_CODES; code++) {
  450. base_dist[code] = dist << 7;
  451. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  452. dist_code[256 + dist++] = (uch)code;
  453. }
  454. }
  455. Assert(dist == 256, "ct_init: 256+dist != 512");
  456. /* Construct the codes of the static literal tree */
  457. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  458. n = 0;
  459. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  460. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  461. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  462. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  463. /* Codes 286 and 287 do not exist, but we must include them in the
  464. * tree construction to get a canonical Huffman tree (longest code
  465. * all ones)
  466. */
  467. gen_codes((ct_data near *)static_ltree, L_CODES+1);
  468. /* The static distance tree is trivial: */
  469. for (n = 0; n < D_CODES; n++) {
  470. static_dtree[n].Len = 5;
  471. static_dtree[n].Code = (ush)bi_reverse(n, 5);
  472. }
  473. /* Initialize the first block of the first file: */
  474. init_block();
  475. }
  476. /* ===========================================================================
  477. * Initialize a new block.
  478. */
  479. local void init_block()
  480. {
  481. int n; /* iterates over tree elements */
  482. /* Initialize the trees. */
  483. for (n = 0; n < L_CODES; n++) dyn_ltree[n].Freq = 0;
  484. for (n = 0; n < D_CODES; n++) dyn_dtree[n].Freq = 0;
  485. for (n = 0; n < BL_CODES; n++) bl_tree[n].Freq = 0;
  486. dyn_ltree[END_BLOCK].Freq = 1;
  487. opt_len = static_len = 0L;
  488. last_lit = last_dist = last_flags = 0;
  489. flags = 0; flag_bit = 1;
  490. }
  491. #define SMALLEST 1
  492. /* Index within the heap array of least frequent node in the Huffman tree */
  493. /* ===========================================================================
  494. * Remove the smallest element from the heap and recreate the heap with
  495. * one less element. Updates heap and heap_len.
  496. */
  497. #define pqremove(tree, top) \
  498. {\
  499. top = heap[SMALLEST]; \
  500. heap[SMALLEST] = heap[heap_len--]; \
  501. pqdownheap(tree, SMALLEST); \
  502. }
  503. /* ===========================================================================
  504. * Compares to subtrees, using the tree depth as tie breaker when
  505. * the subtrees have equal frequency. This minimizes the worst case length.
  506. */
  507. #define smaller(tree, n, m) \
  508. (tree[n].Freq < tree[m].Freq || \
  509. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  510. /* ===========================================================================
  511. * Restore the heap property by moving down the tree starting at node k,
  512. * exchanging a node with the smallest of its two sons if necessary, stopping
  513. * when the heap property is re-established (each father smaller than its
  514. * two sons).
  515. */
  516. local void pqdownheap(tree, k)
  517. ct_data near *tree; /* the tree to restore */
  518. int k; /* node to move down */
  519. {
  520. int v = heap[k];
  521. int j = k << 1; /* left son of k */
  522. int htemp; /* required because of bug in SASC compiler */
  523. while (j <= heap_len) {
  524. /* Set j to the smallest of the two sons: */
  525. if (j < heap_len && smaller(tree, heap[j+1], heap[j])) j++;
  526. /* Exit if v is smaller than both sons */
  527. htemp = heap[j];
  528. if (smaller(tree, v, htemp)) break;
  529. /* Exchange v with the smallest son */
  530. heap[k] = htemp;
  531. k = j;
  532. /* And continue down the tree, setting j to the left son of k */
  533. j <<= 1;
  534. }
  535. heap[k] = v;
  536. }
  537. /* ===========================================================================
  538. * Compute the optimal bit lengths for a tree and update the total bit length
  539. * for the current block.
  540. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  541. * above are the tree nodes sorted by increasing frequency.
  542. * OUT assertions: the field len is set to the optimal bit length, the
  543. * array bl_count contains the frequencies for each bit length.
  544. * The length opt_len is updated; static_len is also updated if stree is
  545. * not null.
  546. */
  547. local void gen_bitlen(desc)
  548. tree_desc near *desc; /* the tree descriptor */
  549. {
  550. ct_data near *tree = desc->dyn_tree;
  551. int near *extra = desc->extra_bits;
  552. int base = desc->extra_base;
  553. int max_code = desc->max_code;
  554. int max_length = desc->max_length;
  555. ct_data near *stree = desc->static_tree;
  556. int h; /* heap index */
  557. int n, m; /* iterate over the tree elements */
  558. int bits; /* bit length */
  559. int xbits; /* extra bits */
  560. ush f; /* frequency */
  561. int overflow = 0; /* number of elements with bit length too large */
  562. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  563. /* In a first pass, compute the optimal bit lengths (which may
  564. * overflow in the case of the bit length tree).
  565. */
  566. tree[heap[heap_max]].Len = 0; /* root of the heap */
  567. for (h = heap_max+1; h < HEAP_SIZE; h++) {
  568. n = heap[h];
  569. bits = tree[tree[n].Dad].Len + 1;
  570. if (bits > max_length) bits = max_length, overflow++;
  571. tree[n].Len = (ush)bits;
  572. /* We overwrite tree[n].Dad which is no longer needed */
  573. if (n > max_code) continue; /* not a leaf node */
  574. bl_count[bits]++;
  575. xbits = 0;
  576. if (n >= base) xbits = extra[n-base];
  577. f = tree[n].Freq;
  578. opt_len += (ulg)f * (bits + xbits);
  579. if (stree) static_len += (ulg)f * (stree[n].Len + xbits);
  580. }
  581. if (overflow == 0) return;
  582. Trace((stderr,"\nbit length overflow\n"));
  583. /* This happens for example on obj2 and pic of the Calgary corpus */
  584. /* Find the first bit length which could increase: */
  585. do {
  586. bits = max_length-1;
  587. while (bl_count[bits] == 0) bits--;
  588. bl_count[bits]--; /* move one leaf down the tree */
  589. bl_count[bits+1] += (ush)2; /* move one overflow item as its brother */
  590. bl_count[max_length]--;
  591. /* The brother of the overflow item also moves one step up,
  592. * but this does not affect bl_count[max_length]
  593. */
  594. overflow -= 2;
  595. } while (overflow > 0);
  596. /* Now recompute all bit lengths, scanning in increasing frequency.
  597. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  598. * lengths instead of fixing only the wrong ones. This idea is taken
  599. * from 'ar' written by Haruhiko Okumura.)
  600. */
  601. for (bits = max_length; bits != 0; bits--) {
  602. n = bl_count[bits];
  603. while (n != 0) {
  604. m = heap[--h];
  605. if (m > max_code) continue;
  606. if (tree[m].Len != (ush)bits) {
  607. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  608. opt_len += ((long)bits-(long)tree[m].Len)*(long)tree[m].Freq;
  609. tree[m].Len = (ush)bits;
  610. }
  611. n--;
  612. }
  613. }
  614. }
  615. /* ===========================================================================
  616. * Generate the codes for a given tree and bit counts (which need not be
  617. * optimal).
  618. * IN assertion: the array bl_count contains the bit length statistics for
  619. * the given tree and the field len is set for all tree elements.
  620. * OUT assertion: the field code is set for all tree elements of non
  621. * zero code length.
  622. */
  623. local void gen_codes (tree, max_code)
  624. ct_data near *tree; /* the tree to decorate */
  625. int max_code; /* largest code with non zero frequency */
  626. {
  627. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  628. ush code = 0; /* running code value */
  629. int bits; /* bit index */
  630. int n; /* code index */
  631. /* The distribution counts are first used to generate the code values
  632. * without bit reversal.
  633. */
  634. for (bits = 1; bits <= MAX_BITS; bits++) {
  635. next_code[bits] = code = (ush)((code + bl_count[bits-1]) << 1);
  636. }
  637. /* Check that the bit counts in bl_count are consistent. The last code
  638. * must be all ones.
  639. */
  640. Assert(code + bl_count[MAX_BITS]-1 == (1<< ((ush) MAX_BITS)) - 1,
  641. "inconsistent bit counts");
  642. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  643. for (n = 0; n <= max_code; n++) {
  644. int len = tree[n].Len;
  645. if (len == 0) continue;
  646. /* Now reverse the bits */
  647. tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
  648. Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  649. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  650. }
  651. }
  652. /* ===========================================================================
  653. * Construct one Huffman tree and assigns the code bit strings and lengths.
  654. * Update the total bit length for the current block.
  655. * IN assertion: the field freq is set for all tree elements.
  656. * OUT assertions: the fields len and code are set to the optimal bit length
  657. * and corresponding code. The length opt_len is updated; static_len is
  658. * also updated if stree is not null. The field max_code is set.
  659. */
  660. local void build_tree(desc)
  661. tree_desc near *desc; /* the tree descriptor */
  662. {
  663. ct_data near *tree = desc->dyn_tree;
  664. ct_data near *stree = desc->static_tree;
  665. int elems = desc->elems;
  666. int n, m; /* iterate over heap elements */
  667. int max_code = -1; /* largest code with non zero frequency */
  668. int node = elems; /* next internal node of the tree */
  669. /* Construct the initial heap, with least frequent element in
  670. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  671. * heap[0] is not used.
  672. */
  673. heap_len = 0, heap_max = HEAP_SIZE;
  674. for (n = 0; n < elems; n++) {
  675. if (tree[n].Freq != 0) {
  676. heap[++heap_len] = max_code = n;
  677. depth[n] = 0;
  678. } else {
  679. tree[n].Len = 0;
  680. }
  681. }
  682. /* The pkzip format requires that at least one distance code exists,
  683. * and that at least one bit should be sent even if there is only one
  684. * possible code. So to avoid special checks later on we force at least
  685. * two codes of non zero frequency.
  686. */
  687. while (heap_len < 2) {
  688. int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
  689. tree[new].Freq = 1;
  690. depth[new] = 0;
  691. opt_len--; if (stree) static_len -= stree[new].Len;
  692. /* new is 0 or 1 so it does not have extra bits */
  693. }
  694. desc->max_code = max_code;
  695. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  696. * establish sub-heaps of increasing lengths:
  697. */
  698. for (n = heap_len/2; n >= 1; n--) pqdownheap(tree, n);
  699. /* Construct the Huffman tree by repeatedly combining the least two
  700. * frequent nodes.
  701. */
  702. do {
  703. pqremove(tree, n); /* n = node of least frequency */
  704. m = heap[SMALLEST]; /* m = node of next least frequency */
  705. heap[--heap_max] = n; /* keep the nodes sorted by frequency */
  706. heap[--heap_max] = m;
  707. /* Create a new node father of n and m */
  708. tree[node].Freq = (ush)(tree[n].Freq + tree[m].Freq);
  709. depth[node] = (uch) (Max(depth[n], depth[m]) + 1);
  710. tree[n].Dad = tree[m].Dad = (ush)node;
  711. #ifdef DUMP_BL_TREE
  712. if (tree == bl_tree) {
  713. fprintf(mesg,"\nnode %d(%d), sons %d(%d) %d(%d)",
  714. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  715. }
  716. #endif
  717. /* and insert the new node in the heap */
  718. heap[SMALLEST] = node++;
  719. pqdownheap(tree, SMALLEST);
  720. } while (heap_len >= 2);
  721. heap[--heap_max] = heap[SMALLEST];
  722. /* At this point, the fields freq and dad are set. We can now
  723. * generate the bit lengths.
  724. */
  725. gen_bitlen((tree_desc near *)desc);
  726. /* The field len is now set, we can generate the bit codes */
  727. gen_codes ((ct_data near *)tree, max_code);
  728. }
  729. /* ===========================================================================
  730. * Scan a literal or distance tree to determine the frequencies of the codes
  731. * in the bit length tree. Updates opt_len to take into account the repeat
  732. * counts. (The contribution of the bit length codes will be added later
  733. * during the construction of bl_tree.)
  734. */
  735. local void scan_tree (tree, max_code)
  736. ct_data near *tree; /* the tree to be scanned */
  737. int max_code; /* and its largest code of non zero frequency */
  738. {
  739. int n; /* iterates over all tree elements */
  740. int prevlen = -1; /* last emitted length */
  741. int curlen; /* length of current code */
  742. int nextlen = tree[0].Len; /* length of next code */
  743. int count = 0; /* repeat count of the current code */
  744. int max_count = 7; /* max repeat count */
  745. int min_count = 4; /* min repeat count */
  746. if (nextlen == 0) max_count = 138, min_count = 3;
  747. tree[max_code+1].Len = (ush)-1; /* guard */
  748. for (n = 0; n <= max_code; n++) {
  749. curlen = nextlen; nextlen = tree[n+1].Len;
  750. if (++count < max_count && curlen == nextlen) {
  751. continue;
  752. } else if (count < min_count) {
  753. bl_tree[curlen].Freq += (ush)count;
  754. } else if (curlen != 0) {
  755. if (curlen != prevlen) bl_tree[curlen].Freq++;
  756. bl_tree[REP_3_6].Freq++;
  757. } else if (count <= 10) {
  758. bl_tree[REPZ_3_10].Freq++;
  759. } else {
  760. bl_tree[REPZ_11_138].Freq++;
  761. }
  762. count = 0; prevlen = curlen;
  763. if (nextlen == 0) {
  764. max_count = 138, min_count = 3;
  765. } else if (curlen == nextlen) {
  766. max_count = 6, min_count = 3;
  767. } else {
  768. max_count = 7, min_count = 4;
  769. }
  770. }
  771. }
  772. /* ===========================================================================
  773. * Send a literal or distance tree in compressed form, using the codes in
  774. * bl_tree.
  775. */
  776. local void send_tree (tree, max_code)
  777. ct_data near *tree; /* the tree to be scanned */
  778. int max_code; /* and its largest code of non zero frequency */
  779. {
  780. int n; /* iterates over all tree elements */
  781. int prevlen = -1; /* last emitted length */
  782. int curlen; /* length of current code */
  783. int nextlen = tree[0].Len; /* length of next code */
  784. int count = 0; /* repeat count of the current code */
  785. int max_count = 7; /* max repeat count */
  786. int min_count = 4; /* min repeat count */
  787. /* tree[max_code+1].Len = -1; */ /* guard already set */
  788. if (nextlen == 0) max_count = 138, min_count = 3;
  789. for (n = 0; n <= max_code; n++) {
  790. curlen = nextlen; nextlen = tree[n+1].Len;
  791. if (++count < max_count && curlen == nextlen) {
  792. continue;
  793. } else if (count < min_count) {
  794. do { send_code(curlen, bl_tree); } while (--count != 0);
  795. } else if (curlen != 0) {
  796. if (curlen != prevlen) {
  797. send_code(curlen, bl_tree); count--;
  798. }
  799. Assert(count >= 3 && count <= 6, " 3_6?");
  800. send_code(REP_3_6, bl_tree); send_bits(count-3, 2);
  801. } else if (count <= 10) {
  802. send_code(REPZ_3_10, bl_tree); send_bits(count-3, 3);
  803. } else {
  804. send_code(REPZ_11_138, bl_tree); send_bits(count-11, 7);
  805. }
  806. count = 0; prevlen = curlen;
  807. if (nextlen == 0) {
  808. max_count = 138, min_count = 3;
  809. } else if (curlen == nextlen) {
  810. max_count = 6, min_count = 3;
  811. } else {
  812. max_count = 7, min_count = 4;
  813. }
  814. }
  815. }
  816. /* ===========================================================================
  817. * Construct the Huffman tree for the bit lengths and return the index in
  818. * bl_order of the last bit length code to send.
  819. */
  820. local int build_bl_tree()
  821. {
  822. int max_blindex; /* index of last bit length code of non zero freq */
  823. /* Determine the bit length frequencies for literal and distance trees */
  824. scan_tree((ct_data near *)dyn_ltree, l_desc.max_code);
  825. scan_tree((ct_data near *)dyn_dtree, d_desc.max_code);
  826. /* Build the bit length tree: */
  827. build_tree((tree_desc near *)(&bl_desc));
  828. /* opt_len now includes the length of the tree representations, except
  829. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  830. */
  831. /* Determine the number of bit length codes to send. The pkzip format
  832. * requires that at least 4 bit length codes be sent. (appnote.txt says
  833. * 3 but the actual value used is 4.)
  834. */
  835. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  836. if (bl_tree[bl_order[max_blindex]].Len != 0) break;
  837. }
  838. /* Update opt_len to include the bit length tree and counts */
  839. opt_len += 3*(max_blindex+1) + 5+5+4;
  840. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len, static_len));
  841. return max_blindex;
  842. }
  843. /* ===========================================================================
  844. * Send the header for a block using dynamic Huffman trees: the counts, the
  845. * lengths of the bit length codes, the literal tree and the distance tree.
  846. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  847. */
  848. local void send_all_trees(lcodes, dcodes, blcodes)
  849. int lcodes, dcodes, blcodes; /* number of codes for each tree */
  850. {
  851. int rank; /* index in bl_order */
  852. Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  853. Assert(lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  854. "too many codes");
  855. Tracev((stderr, "\nbl counts: "));
  856. send_bits(lcodes-257, 5);
  857. /* not +255 as stated in appnote.txt 1.93a or -256 in 2.04c */
  858. send_bits(dcodes-1, 5);
  859. send_bits(blcodes-4, 4); /* not -3 as stated in appnote.txt */
  860. for (rank = 0; rank < blcodes; rank++) {
  861. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  862. send_bits(bl_tree[bl_order[rank]].Len, 3);
  863. }
  864. Tracev((stderr, "\nbl tree: sent %s",
  865. zip_fuzofft(bits_sent, NULL, NULL)));
  866. send_tree((ct_data near *)dyn_ltree, lcodes-1); /* send the literal tree */
  867. Tracev((stderr, "\nlit tree: sent %s",
  868. zip_fuzofft(bits_sent, NULL, NULL)));
  869. send_tree((ct_data near *)dyn_dtree, dcodes-1); /* send the distance tree */
  870. Tracev((stderr, "\ndist tree: sent %ld",
  871. zip_fuzofft(bits_sent, NULL, NULL)));
  872. }
  873. /* ===========================================================================
  874. * Determine the best encoding for the current block: dynamic trees, static
  875. * trees or store, and output the encoded block to the zip file. This function
  876. * returns the total compressed length (in bytes) for the file so far.
  877. */
  878. /* zip64 support 08/29/2003 R.Nausedat */
  879. uzoff_t flush_block(buf, stored_len, eof)
  880. char *buf; /* input block, or NULL if too old */
  881. ulg stored_len; /* length of input block */
  882. int eof; /* true if this is the last block for a file */
  883. {
  884. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  885. int max_blindex; /* index of last bit length code of non zero freq */
  886. flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
  887. /* Check if the file is ascii or binary */
  888. if (*file_type == (ush)UNKNOWN) set_file_type();
  889. /* Construct the literal and distance trees */
  890. build_tree((tree_desc near *)(&l_desc));
  891. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
  892. build_tree((tree_desc near *)(&d_desc));
  893. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", opt_len, static_len));
  894. /* At this point, opt_len and static_len are the total bit lengths of
  895. * the compressed block data, excluding the tree representations.
  896. */
  897. /* Build the bit length tree for the above two trees, and get the index
  898. * in bl_order of the last bit length code to send.
  899. */
  900. max_blindex = build_bl_tree();
  901. /* Determine the best encoding. Compute first the block length in bytes */
  902. opt_lenb = (opt_len+3+7)>>3;
  903. static_lenb = (static_len+3+7)>>3;
  904. #ifdef DEBUG
  905. input_len += stored_len; /* for debugging only */
  906. #endif
  907. Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
  908. opt_lenb, opt_len, static_lenb, static_len, stored_len,
  909. last_lit, last_dist));
  910. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  911. #ifndef PGP /* PGP can't handle stored blocks */
  912. /* If compression failed and this is the first and last block,
  913. * the whole file is transformed into a stored file:
  914. */
  915. #ifdef FORCE_METHOD
  916. if (level == 1 && eof && file_method != NULL &&
  917. cmpr_bytelen == (uzoff_t)0 && cmpr_len_bits == 0L
  918. ) { /* force stored file */
  919. #else
  920. if (stored_len <= opt_lenb && eof && file_method != NULL &&
  921. cmpr_bytelen == (uzoff_t)0 && cmpr_len_bits == 0L &&
  922. seekable() && !use_descriptors) {
  923. #endif
  924. /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  925. if (buf == NULL) error ("block vanished");
  926. copy_block(buf, (unsigned)stored_len, 0); /* without header */
  927. cmpr_bytelen = stored_len;
  928. *file_method = STORE;
  929. } else
  930. #endif /* PGP */
  931. #ifdef FORCE_METHOD
  932. if (level <= 2 && buf != (char*)NULL) { /* force stored block */
  933. #else
  934. if (stored_len+4 <= opt_lenb && buf != (char*)NULL) {
  935. /* 4: two words for the lengths */
  936. #endif
  937. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  938. * Otherwise we can't have processed more than WSIZE input bytes since
  939. * the last block flush, because compression would have been
  940. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  941. * transform a block into a stored block.
  942. */
  943. send_bits((STORED_BLOCK<<1)+eof, 3); /* send block type */
  944. cmpr_bytelen += ((cmpr_len_bits + 3 + 7) >> 3) + stored_len + 4;
  945. cmpr_len_bits = 0L;
  946. copy_block(buf, (unsigned)stored_len, 1); /* with header */
  947. #ifdef FORCE_METHOD
  948. } else if (level == 3) { /* force static trees */
  949. #else
  950. } else if (static_lenb == opt_lenb) {
  951. #endif
  952. send_bits((STATIC_TREES<<1)+eof, 3);
  953. compress_block((ct_data near *)static_ltree, (ct_data near *)static_dtree);
  954. cmpr_len_bits += 3 + static_len;
  955. cmpr_bytelen += cmpr_len_bits >> 3;
  956. cmpr_len_bits &= 7L;
  957. } else {
  958. send_bits((DYN_TREES<<1)+eof, 3);
  959. send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1);
  960. compress_block((ct_data near *)dyn_ltree, (ct_data near *)dyn_dtree);
  961. cmpr_len_bits += 3 + opt_len;
  962. cmpr_bytelen += cmpr_len_bits >> 3;
  963. cmpr_len_bits &= 7L;
  964. }
  965. Assert(((cmpr_bytelen << 3) + cmpr_len_bits) == bits_sent,
  966. "bad compressed size");
  967. init_block();
  968. if (eof) {
  969. #if defined(PGP) && !defined(MMAP)
  970. /* Wipe out sensitive data for pgp */
  971. # ifdef DYN_ALLOC
  972. extern uch *window;
  973. # else
  974. extern uch window[];
  975. # endif
  976. memset(window, 0, (unsigned)(2*WSIZE-1)); /* -1 needed if WSIZE=32K */
  977. #else /* !PGP */
  978. Assert(input_len == isize, "bad input size");
  979. #endif
  980. bi_windup();
  981. cmpr_len_bits += 7; /* align on byte boundary */
  982. }
  983. Tracev((stderr,"\ncomprlen %s(%s) ",
  984. zip_fuzofft( cmpr_bytelen + (cmpr_len_bits>>3), NULL, NULL),
  985. zip_fuzofft( (cmpr_bytelen << 3) + cmpr_len_bits - 7*eof, NULL, NULL)));
  986. Trace((stderr, "\n"));
  987. return cmpr_bytelen + (cmpr_len_bits >> 3);
  988. }
  989. /* ===========================================================================
  990. * Save the match info and tally the frequency counts. Return true if
  991. * the current block must be flushed.
  992. */
  993. int ct_tally (dist, lc)
  994. int dist; /* distance of matched string */
  995. int lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  996. {
  997. l_buf[last_lit++] = (uch)lc;
  998. if (dist == 0) {
  999. /* lc is the unmatched char */
  1000. dyn_ltree[lc].Freq++;
  1001. } else {
  1002. /* Here, lc is the match length - MIN_MATCH */
  1003. dist--; /* dist = match distance - 1 */
  1004. Assert((ush)dist < (ush)MAX_DIST &&
  1005. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  1006. (ush)d_code(dist) < (ush)D_CODES, "ct_tally: bad match");
  1007. dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
  1008. dyn_dtree[d_code(dist)].Freq++;
  1009. d_buf[last_dist++] = (ush)dist;
  1010. flags |= flag_bit;
  1011. }
  1012. flag_bit <<= 1;
  1013. /* Output the flags if they fill a byte: */
  1014. if ((last_lit & 7) == 0) {
  1015. flag_buf[last_flags++] = flags;
  1016. flags = 0, flag_bit = 1;
  1017. }
  1018. /* Try to guess if it is profitable to stop the current block here */
  1019. if (level > 2 && (last_lit & 0xfff) == 0) {
  1020. /* Compute an upper bound for the compressed length */
  1021. ulg out_length = (ulg)last_lit*8L;
  1022. ulg in_length = (ulg)strstart-block_start;
  1023. int dcode;
  1024. for (dcode = 0; dcode < D_CODES; dcode++) {
  1025. out_length += (ulg)dyn_dtree[dcode].Freq*(5L+extra_dbits[dcode]);
  1026. }
  1027. out_length >>= 3;
  1028. Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
  1029. last_lit, last_dist, in_length, out_length,
  1030. 100L - out_length*100L/in_length));
  1031. if (last_dist < last_lit/2 && out_length < in_length/2) return 1;
  1032. }
  1033. return (last_lit == LIT_BUFSIZE-1 || last_dist == DIST_BUFSIZE);
  1034. /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
  1035. * on 16 bit machines and because stored blocks are restricted to
  1036. * 64K-1 bytes.
  1037. */
  1038. }
  1039. /* ===========================================================================
  1040. * Send the block data compressed using the given Huffman trees
  1041. */
  1042. local void compress_block(ltree, dtree)
  1043. ct_data near *ltree; /* literal tree */
  1044. ct_data near *dtree; /* distance tree */
  1045. {
  1046. unsigned dist; /* distance of matched string */
  1047. int lc; /* match length or unmatched char (if dist == 0) */
  1048. unsigned lx = 0; /* running index in l_buf */
  1049. unsigned dx = 0; /* running index in d_buf */
  1050. unsigned fx = 0; /* running index in flag_buf */
  1051. uch flag = 0; /* current flags */
  1052. unsigned code; /* the code to send */
  1053. int extra; /* number of extra bits to send */
  1054. if (last_lit != 0) do {
  1055. if ((lx & 7) == 0) flag = flag_buf[fx++];
  1056. lc = l_buf[lx++];
  1057. if ((flag & 1) == 0) {
  1058. send_code(lc, ltree); /* send a literal byte */
  1059. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  1060. } else {
  1061. /* Here, lc is the match length - MIN_MATCH */
  1062. code = length_code[lc];
  1063. send_code(code+LITERALS+1, ltree); /* send the length code */
  1064. extra = extra_lbits[code];
  1065. if (extra != 0) {
  1066. lc -= base_length[code];
  1067. send_bits(lc, extra); /* send the extra length bits */
  1068. }
  1069. dist = d_buf[dx++];
  1070. /* Here, dist is the match distance - 1 */
  1071. code = d_code(dist);
  1072. Assert(code < D_CODES, "bad d_code");
  1073. send_code(code, dtree); /* send the distance code */
  1074. extra = extra_dbits[code];
  1075. if (extra != 0) {
  1076. dist -= base_dist[code];
  1077. send_bits(dist, extra); /* send the extra distance bits */
  1078. }
  1079. } /* literal or match pair ? */
  1080. flag >>= 1;
  1081. } while (lx < last_lit);
  1082. send_code(END_BLOCK, ltree);
  1083. }
  1084. /* ===========================================================================
  1085. * Set the file type to TEXT (ASCII) or BINARY, using following algorithm:
  1086. * - TEXT, either ASCII or an ASCII-compatible extension such as ISO-8859,
  1087. * UTF-8, etc., when the following two conditions are satisfied:
  1088. * a) There are no non-portable control characters belonging to the
  1089. * "black list" (0..6, 14..25, 28..31).
  1090. * b) There is at least one printable character belonging to the
  1091. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  1092. * - BINARY otherwise.
  1093. *
  1094. * Note that the following partially-portable control characters form a
  1095. * "gray list" that is ignored in this detection algorithm:
  1096. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  1097. *
  1098. * Also note that, unlike in the previous 20% binary detection algorithm,
  1099. * any control characters in the black list will set the file type to
  1100. * BINARY. If a text file contains a single accidental black character,
  1101. * the file will be flagged as BINARY in the archive.
  1102. *
  1103. * IN assertion: the fields freq of dyn_ltree are set.
  1104. */
  1105. local void set_file_type()
  1106. {
  1107. /* bit-mask of black-listed bytes
  1108. * bit is set if byte is black-listed
  1109. * set bits 0..6, 14..25, and 28..31
  1110. * 0xf3ffc07f = binary 11110011111111111100000001111111
  1111. */
  1112. unsigned long mask = 0xf3ffc07fL;
  1113. int n;
  1114. /* Check for non-textual ("black-listed") bytes. */
  1115. for (n = 0; n <= 31; n++, mask >>= 1)
  1116. if ((mask & 1) && (dyn_ltree[n].Freq != 0))
  1117. {
  1118. *file_type = BINARY;
  1119. return;
  1120. }
  1121. /* Check for textual ("white-listed") bytes. */
  1122. *file_type = ASCII;
  1123. if (dyn_ltree[9].Freq != 0 || dyn_ltree[10].Freq != 0
  1124. || dyn_ltree[13].Freq != 0)
  1125. return;
  1126. for (n = 32; n < LITERALS; n++)
  1127. if (dyn_ltree[n].Freq != 0)
  1128. return;
  1129. /* This deflate stream is either empty, or
  1130. * it has tolerated ("gray-listed") bytes only.
  1131. */
  1132. *file_type = BINARY;
  1133. }
  1134. /* ===========================================================================
  1135. * Initialize the bit string routines.
  1136. */
  1137. void bi_init (tgt_buf, tgt_size, flsh_allowed)
  1138. char *tgt_buf;
  1139. unsigned tgt_size;
  1140. int flsh_allowed;
  1141. {
  1142. out_buf = tgt_buf;
  1143. out_size = tgt_size;
  1144. out_offset = 0;
  1145. flush_flg = flsh_allowed;
  1146. bi_buf = 0;
  1147. bi_valid = 0;
  1148. #ifdef DEBUG
  1149. bits_sent = (uzoff_t)0;
  1150. #endif
  1151. }
  1152. #if (!defined(ASMV) || !defined(RISCOS))
  1153. /* ===========================================================================
  1154. * Send a value on a given number of bits.
  1155. * IN assertion: length <= 16 and value fits in length bits.
  1156. */
  1157. local void send_bits(value, length)
  1158. int value; /* value to send */
  1159. int length; /* number of bits */
  1160. {
  1161. #ifdef DEBUG
  1162. Tracevv((stderr," l %2d v %4x ", length, value));
  1163. Assert(length > 0 && length <= 15, "invalid length");
  1164. bits_sent += (uzoff_t)length;
  1165. #endif
  1166. /* If not enough room in bi_buf, use (bi_valid) bits from bi_buf and
  1167. * (Buf_size - bi_valid) bits from value to flush the filled bi_buf,
  1168. * then fill in the rest of (value), leaving (length - (Buf_size-bi_valid))
  1169. * unused bits in bi_buf.
  1170. */
  1171. bi_buf |= (value << bi_valid);
  1172. bi_valid += length;
  1173. if (bi_valid > (int)Buf_size) {
  1174. PUTSHORT(bi_buf);
  1175. bi_valid -= Buf_size;
  1176. bi_buf = (unsigned)value >> (length - bi_valid);
  1177. }
  1178. }
  1179. /* ===========================================================================
  1180. * Reverse the first len bits of a code, using straightforward code (a faster
  1181. * method would use a table)
  1182. * IN assertion: 1 <= len <= 15
  1183. */
  1184. local unsigned bi_reverse(code, len)
  1185. unsigned code; /* the value to invert */
  1186. int len; /* its bit length */
  1187. {
  1188. register unsigned res = 0;
  1189. do {
  1190. res |= code & 1;
  1191. code >>= 1, res <<= 1;
  1192. } while (--len > 0);
  1193. return res >> 1;
  1194. }
  1195. #endif /* !ASMV || !RISCOS */
  1196. /* ===========================================================================
  1197. * Write out any remaining bits in an incomplete byte.
  1198. */
  1199. local void bi_windup()
  1200. {
  1201. if (bi_valid > 8) {
  1202. PUTSHORT(bi_buf);
  1203. } else if (bi_valid > 0) {
  1204. PUTBYTE(bi_buf);
  1205. }
  1206. if (flush_flg) {
  1207. flush_outbuf(out_buf, &out_offset);
  1208. }
  1209. bi_buf = 0;
  1210. bi_valid = 0;
  1211. #ifdef DEBUG
  1212. bits_sent = (bits_sent+7) & ~7;
  1213. #endif
  1214. }
  1215. /* ===========================================================================
  1216. * Copy a stored block to the zip file, storing first the length and its
  1217. * one's complement if requested.
  1218. *
  1219. * Buffer Overwrite fix
  1220. *
  1221. * A buffer flush has been added to fix a bug when encrypting deflated files
  1222. * with embedded "copied blocks". When encrypting, the flush_out() routine
  1223. * modifies its data buffer because encryption is done "in-place" in
  1224. * zfwrite(), whereas without encryption, the flush_out() data buffer is
  1225. * left unaltered. This can be a problem as noted below by the submitter.
  1226. *
  1227. * "But an exception comes when a block of stored data (data that could not
  1228. * be compressed) is being encrypted. In this case, the data that is passed
  1229. * to zfwrite (and is therefore encrypted-in-place) is actually a block of
  1230. * data from within the sliding input window that is being managed by
  1231. * deflate.c.
  1232. *
  1233. * "Since part of the sliding input window has now been overwritten by
  1234. * encrypted (and essentially random) data, deflate.c's search for previous
  1235. * text that matches the current text will usually fail but on rare
  1236. * occasions will find a match with something in the encrypted data. This
  1237. * incorrect match then causes incorrect information to be placed in the
  1238. * ZIP file."
  1239. *
  1240. * The problem results in the zip file having bad data and so a bad CRC.
  1241. * This does not happen often and to recreate the problem a large file
  1242. * with non-compressable data is needed so that deflate chooses to store the
  1243. * data. A test file of 400 MB seems large enough to recreate the problem
  1244. * using a command such as
  1245. * zip -1 -e crcerror.zip testfile.dat
  1246. * maybe half the time.
  1247. *
  1248. * This problem has been fixed by copying the data into the deflate output
  1249. * buffer before calling flush_outbuf(), when encryption is enabled.
  1250. *
  1251. * Thanks to the nice people at WinZip for identifying the problem and
  1252. * passing it on. Also see Changes.
  1253. *
  1254. * 2006-03-06 EG, CS
  1255. */
  1256. local void copy_block(block, len, header)
  1257. char *block; /* the input data */
  1258. unsigned len; /* its length */
  1259. int header; /* true if block header must be written */
  1260. {
  1261. bi_windup(); /* align on byte boundary */
  1262. if (header) {
  1263. PUTSHORT((ush)len);
  1264. PUTSHORT((ush)~len);
  1265. #ifdef DEBUG
  1266. bits_sent += 2*16;
  1267. #endif
  1268. }
  1269. if (flush_flg) {
  1270. flush_outbuf(out_buf, &out_offset);
  1271. if (key != (char *)NULL) { /* key is the global password pointer */
  1272. /* Encryption modifies the data in the output buffer. But the
  1273. * copied input data must remain intact for further deflate
  1274. * string matching lookups. Therefore, the input data is
  1275. * copied into the compression output buffer for flushing
  1276. * to the compressed/encrypted output stream.
  1277. */
  1278. while(len > 0) {
  1279. out_offset = (len < out_size ? len : out_size);
  1280. memcpy(out_buf, block, out_offset);
  1281. block += out_offset;
  1282. len -= out_offset;
  1283. flush_outbuf(out_buf, &out_offset);
  1284. }
  1285. } else {
  1286. /* Without encryption, the output routines do not touch the
  1287. * written data, so there is no need for an additional copy
  1288. * operation.
  1289. */
  1290. out_offset = len;
  1291. flush_outbuf(block, &out_offset);
  1292. }
  1293. } else if (out_offset + len > out_size) {
  1294. error("output buffer too small for in-memory compression");
  1295. } else {
  1296. memcpy(out_buf + out_offset, block, len);
  1297. out_offset += len;
  1298. }
  1299. #ifdef DEBUG
  1300. bits_sent += (ulg)len<<3;
  1301. #endif
  1302. }
  1303. #endif /* !USE_ZLIB */