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