1 /* deflate.c -- compress data using the deflation algorithm
2  * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
3  * For conditions of distribution and use, see copyright notice in zlib.h
4  */
5 
6 /*
7  *  ALGORITHM
8  *
9  *      The "deflation" process depends on being able to identify portions
10  *      of the input text which are identical to earlier input (within a
11  *      sliding window trailing behind the input currently being processed).
12  *
13  *      The most straightforward technique turns out to be the fastest for
14  *      most input files: try all possible matches and select the longest.
15  *      The key feature of this algorithm is that insertions into the string
16  *      dictionary are very simple and thus fast, and deletions are avoided
17  *      completely. Insertions are performed at each input character, whereas
18  *      string matches are performed only when the previous match ends. So it
19  *      is preferable to spend more time in matches to allow very fast string
20  *      insertions and avoid deletions. The matching algorithm for small
21  *      strings is inspired from that of Rabin & Karp. A brute force approach
22  *      is used to find longer strings when a small match has been found.
23  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24  *      (by Leonid Broukhis).
25  *         A previous version of this file used a more sophisticated algorithm
26  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
27  *      time, but has a larger average cost, uses more memory and is patented.
28  *      However the F&G algorithm may be faster for some highly redundant
29  *      files if the parameter max_chain_length (described below) is too large.
30  *
31  *  ACKNOWLEDGEMENTS
32  *
33  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34  *      I found it in 'freeze' written by Leonid Broukhis.
35  *      Thanks to many people for bug reports and testing.
36  *
37  *  REFERENCES
38  *
39  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40  *      Available in http://tools.ietf.org/html/rfc1951
41  *
42  *      A description of the Rabin and Karp algorithm is given in the book
43  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44  *
45  *      Fiala,E.R., and Greene,D.H.
46  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47  *
48  */
49 
50 /* @(#) $Id$ */
51 #include <assert.h>
52 #include "deflate.h"
53 #include "cpu_features.h"
54 #include "contrib/optimizations/insert_string.h"
55 
56 #if (defined(__ARM_NEON__) || defined(__ARM_NEON))
57 #include "contrib/optimizations/slide_hash_neon.h"
58 #endif
59 #if defined(CRC32_ARMV8_CRC32)
60 #include "crc32_simd.h"
61 #endif
62 
63 #ifdef FASTEST
64 /* See http://crbug.com/1113596 */
65 #error "FASTEST is not supported in Chromium's zlib."
66 #endif
67 
68 const char deflate_copyright[] =
69    " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler ";
70 /*
71   If you use the zlib library in a product, an acknowledgment is welcome
72   in the documentation of your product. If for some reason you cannot
73   include such an acknowledgment, I would appreciate that you keep this
74   copyright string in the executable of your product.
75  */
76 
77 /* ===========================================================================
78  *  Function prototypes.
79  */
80 typedef enum {
81     need_more,      /* block not completed, need more input or more output */
82     block_done,     /* block flush performed */
83     finish_started, /* finish started, need only more output at next deflate */
84     finish_done     /* finish done, accept no more input or output */
85 } block_state;
86 
87 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
88 /* Compression function. Returns the block state after the call. */
89 
90 local int deflateStateCheck      OF((z_streamp strm));
91 local void slide_hash     OF((deflate_state *s));
92 local void fill_window    OF((deflate_state *s));
93 local block_state deflate_stored OF((deflate_state *s, int flush));
94 local block_state deflate_fast   OF((deflate_state *s, int flush));
95 #ifndef FASTEST
96 local block_state deflate_slow   OF((deflate_state *s, int flush));
97 #endif
98 local block_state deflate_rle    OF((deflate_state *s, int flush));
99 local block_state deflate_huff   OF((deflate_state *s, int flush));
100 local void lm_init        OF((deflate_state *s));
101 local void putShortMSB    OF((deflate_state *s, uInt b));
102 local void flush_pending  OF((z_streamp strm));
103 unsigned ZLIB_INTERNAL deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
104 #ifdef ASMV
105 #  pragma message("Assembler code may have bugs -- use at your own risk")
106       void match_init OF((void)); /* asm code initialization */
107       uInt longest_match  OF((deflate_state *s, IPos cur_match));
108 #else
109 local uInt longest_match  OF((deflate_state *s, IPos cur_match));
110 #endif
111 
112 #ifdef ZLIB_DEBUG
113 local  void check_match OF((deflate_state *s, IPos start, IPos match,
114                             int length));
115 #endif
116 
117 /* From crc32.c */
118 extern void ZLIB_INTERNAL crc_reset(deflate_state *const s);
119 extern void ZLIB_INTERNAL crc_finalize(deflate_state *const s);
120 extern void ZLIB_INTERNAL copy_with_crc(z_streamp strm, Bytef *dst, long size);
121 
122 /* ===========================================================================
123  * Local data
124  */
125 
126 #define NIL 0
127 /* Tail of hash chains */
128 
129 #ifndef TOO_FAR
130 #  define TOO_FAR 4096
131 #endif
132 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
133 
134 /* Values for max_lazy_match, good_match and max_chain_length, depending on
135  * the desired pack level (0..9). The values given below have been tuned to
136  * exclude worst case performance for pathological files. Better values may be
137  * found for specific files.
138  */
139 typedef struct config_s {
140    ush good_length; /* reduce lazy search above this match length */
141    ush max_lazy;    /* do not perform lazy search above this match length */
142    ush nice_length; /* quit search above this match length */
143    ush max_chain;
144    compress_func func;
145 } config;
146 
147 #ifdef FASTEST
148 local const config configuration_table[2] = {
149 /*      good lazy nice chain */
150 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
151 /* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
152 #else
153 local const config configuration_table[10] = {
154 /*      good lazy nice chain */
155 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
156 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
157 /* 2 */ {4,    5, 16,    8, deflate_fast},
158 /* 3 */ {4,    6, 32,   32, deflate_fast},
159 
160 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
161 /* 5 */ {8,   16, 32,   32, deflate_slow},
162 /* 6 */ {8,   16, 128, 128, deflate_slow},
163 /* 7 */ {8,   32, 128, 256, deflate_slow},
164 /* 8 */ {32, 128, 258, 1024, deflate_slow},
165 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
166 #endif
167 
168 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
169  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
170  * meaning.
171  */
172 
173 /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
174 #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
175 
176 /* ===========================================================================
177  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
178  * prev[] will be initialized on the fly.
179  */
180 #define CLEAR_HASH(s) \
181     s->head[s->hash_size-1] = NIL; \
182     zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
183 
184 /* ===========================================================================
185  * Slide the hash table when sliding the window down (could be avoided with 32
186  * bit values at the expense of memory usage). We slide even when level == 0 to
187  * keep the hash table consistent if we switch back to level > 0 later.
188  */
slide_hash(s)189 local void slide_hash(s)
190     deflate_state *s;
191 {
192 #if (defined(__ARM_NEON__) || defined(__ARM_NEON))
193     /* NEON based hash table rebase. */
194     return neon_slide_hash(s->head, s->prev, s->w_size, s->hash_size);
195 #endif
196     unsigned n, m;
197     Posf *p;
198     uInt wsize = s->w_size;
199 
200     n = s->hash_size;
201     p = &s->head[n];
202     do {
203         m = *--p;
204         *p = (Pos)(m >= wsize ? m - wsize : NIL);
205     } while (--n);
206     n = wsize;
207 #ifndef FASTEST
208     p = &s->prev[n];
209     do {
210         m = *--p;
211         *p = (Pos)(m >= wsize ? m - wsize : NIL);
212         /* If n is not on any hash chain, prev[n] is garbage but
213          * its value will never be used.
214          */
215     } while (--n);
216 #endif
217 }
218 
219 /* ========================================================================= */
deflateInit_(strm,level,version,stream_size)220 int ZEXPORT deflateInit_(strm, level, version, stream_size)
221     z_streamp strm;
222     int level;
223     const char *version;
224     int stream_size;
225 {
226     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
227                          Z_DEFAULT_STRATEGY, version, stream_size);
228     /* To do: ignore strm->next_in if we use it as window */
229 }
230 
231 /* ========================================================================= */
deflateInit2_(strm,level,method,windowBits,memLevel,strategy,version,stream_size)232 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
233                   version, stream_size)
234     z_streamp strm;
235     int  level;
236     int  method;
237     int  windowBits;
238     int  memLevel;
239     int  strategy;
240     const char *version;
241     int stream_size;
242 {
243     unsigned window_padding = 8;
244     deflate_state *s;
245     int wrap = 1;
246     static const char my_version[] = ZLIB_VERSION;
247 
248     // Needed to activate optimized insert_string() that helps compression
249     // for all wrapper formats (e.g. RAW, ZLIB, GZIP).
250     // Feature detection is not triggered while using RAW mode (i.e. we never
251     // call crc32() with a NULL buffer).
252 #if defined(CRC32_ARMV8_CRC32) || defined(CRC32_SIMD_SSE42_PCLMUL)
253     cpu_check_features();
254 #endif
255 
256     if (version == Z_NULL || version[0] != my_version[0] ||
257         stream_size != sizeof(z_stream)) {
258         return Z_VERSION_ERROR;
259     }
260     if (strm == Z_NULL) return Z_STREAM_ERROR;
261 
262     strm->msg = Z_NULL;
263     if (strm->zalloc == (alloc_func)0) {
264 #ifdef Z_SOLO
265         return Z_STREAM_ERROR;
266 #else
267         strm->zalloc = zcalloc;
268         strm->opaque = (voidpf)0;
269 #endif
270     }
271     if (strm->zfree == (free_func)0)
272 #ifdef Z_SOLO
273         return Z_STREAM_ERROR;
274 #else
275         strm->zfree = zcfree;
276 #endif
277 
278 #ifdef FASTEST
279     if (level != 0) level = 1;
280 #else
281     if (level == Z_DEFAULT_COMPRESSION) level = 6;
282 #endif
283 
284     if (windowBits < 0) { /* suppress zlib wrapper */
285         wrap = 0;
286         windowBits = -windowBits;
287     }
288 #ifdef GZIP
289     else if (windowBits > 15) {
290         wrap = 2;       /* write gzip wrapper instead */
291         windowBits -= 16;
292     }
293 #endif
294     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
295         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
296         strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
297         return Z_STREAM_ERROR;
298     }
299     if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
300     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
301     if (s == Z_NULL) return Z_MEM_ERROR;
302     strm->state = (struct internal_state FAR *)s;
303     s->strm = strm;
304     s->status = INIT_STATE;     /* to pass state test in deflateReset() */
305 
306     s->wrap = wrap;
307     s->gzhead = Z_NULL;
308     s->w_bits = (uInt)windowBits;
309     s->w_size = 1 << s->w_bits;
310     s->w_mask = s->w_size - 1;
311 
312     s->hash_bits = memLevel + 7;
313     if ((x86_cpu_enable_simd || arm_cpu_enable_crc32) && s->hash_bits < 15) {
314         s->hash_bits = 15;
315     }
316 
317     s->hash_size = 1 << s->hash_bits;
318     s->hash_mask = s->hash_size - 1;
319     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
320 
321     s->window = (Bytef *) ZALLOC(strm,
322                                  s->w_size + window_padding,
323                                  2*sizeof(Byte));
324     /* Avoid use of unitialized values in the window, see crbug.com/1137613 and
325      * crbug.com/1144420 */
326     zmemzero(s->window, (s->w_size + window_padding) * (2 * sizeof(Byte)));
327     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
328     /* Avoid use of uninitialized value, see:
329      * https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=11360
330      */
331     zmemzero(s->prev, s->w_size * sizeof(Pos));
332     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
333 
334     s->high_water = 0;      /* nothing written to s->window yet */
335 
336     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
337 
338     /* We overlay pending_buf and sym_buf. This works since the average size
339      * for length/distance pairs over any compressed block is assured to be 31
340      * bits or less.
341      *
342      * Analysis: The longest fixed codes are a length code of 8 bits plus 5
343      * extra bits, for lengths 131 to 257. The longest fixed distance codes are
344      * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
345      * possible fixed-codes length/distance pair is then 31 bits total.
346      *
347      * sym_buf starts one-fourth of the way into pending_buf. So there are
348      * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
349      * in sym_buf is three bytes -- two for the distance and one for the
350      * literal/length. As each symbol is consumed, the pointer to the next
351      * sym_buf value to read moves forward three bytes. From that symbol, up to
352      * 31 bits are written to pending_buf. The closest the written pending_buf
353      * bits gets to the next sym_buf symbol to read is just before the last
354      * code is written. At that time, 31*(n-2) bits have been written, just
355      * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
356      * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
357      * symbols are written.) The closest the writing gets to what is unread is
358      * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
359      * can range from 128 to 32768.
360      *
361      * Therefore, at a minimum, there are 142 bits of space between what is
362      * written and what is read in the overlain buffers, so the symbols cannot
363      * be overwritten by the compressed data. That space is actually 139 bits,
364      * due to the three-bit fixed-code block header.
365      *
366      * That covers the case where either Z_FIXED is specified, forcing fixed
367      * codes, or when the use of fixed codes is chosen, because that choice
368      * results in a smaller compressed block than dynamic codes. That latter
369      * condition then assures that the above analysis also covers all dynamic
370      * blocks. A dynamic-code block will only be chosen to be emitted if it has
371      * fewer bits than a fixed-code block would for the same set of symbols.
372      * Therefore its average symbol length is assured to be less than 31. So
373      * the compressed data for a dynamic block also cannot overwrite the
374      * symbols from which it is being constructed.
375      */
376     s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);
377     s->pending_buf_size = (ulg)s->lit_bufsize * 4;
378 
379     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
380         s->pending_buf == Z_NULL) {
381         s->status = FINISH_STATE;
382         strm->msg = ERR_MSG(Z_MEM_ERROR);
383         deflateEnd (strm);
384         return Z_MEM_ERROR;
385     }
386     s->sym_buf = s->pending_buf + s->lit_bufsize;
387     s->sym_end = (s->lit_bufsize - 1) * 3;
388     /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
389      * on 16 bit machines and because stored blocks are restricted to
390      * 64K-1 bytes.
391      */
392 
393     s->level = level;
394     s->strategy = strategy;
395     s->method = (Byte)method;
396 
397     return deflateReset(strm);
398 }
399 
400 /* =========================================================================
401  * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
402  */
deflateStateCheck(strm)403 local int deflateStateCheck (strm)
404     z_streamp strm;
405 {
406     deflate_state *s;
407     if (strm == Z_NULL ||
408         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
409         return 1;
410     s = strm->state;
411     if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
412 #ifdef GZIP
413                                            s->status != GZIP_STATE &&
414 #endif
415                                            s->status != EXTRA_STATE &&
416                                            s->status != NAME_STATE &&
417                                            s->status != COMMENT_STATE &&
418                                            s->status != HCRC_STATE &&
419                                            s->status != BUSY_STATE &&
420                                            s->status != FINISH_STATE))
421         return 1;
422     return 0;
423 }
424 
425 /* ========================================================================= */
deflateSetDictionary(strm,dictionary,dictLength)426 int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
427     z_streamp strm;
428     const Bytef *dictionary;
429     uInt  dictLength;
430 {
431     deflate_state *s;
432     uInt str, n;
433     int wrap;
434     unsigned avail;
435     z_const unsigned char *next;
436 
437     if (deflateStateCheck(strm) || dictionary == Z_NULL)
438         return Z_STREAM_ERROR;
439     s = strm->state;
440     wrap = s->wrap;
441     if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
442         return Z_STREAM_ERROR;
443 
444     /* when using zlib wrappers, compute Adler-32 for provided dictionary */
445     if (wrap == 1)
446         strm->adler = adler32(strm->adler, dictionary, dictLength);
447     s->wrap = 0;                    /* avoid computing Adler-32 in deflate_read_buf */
448 
449     /* if dictionary would fill window, just replace the history */
450     if (dictLength >= s->w_size) {
451         if (wrap == 0) {            /* already empty otherwise */
452             CLEAR_HASH(s);
453             s->strstart = 0;
454             s->block_start = 0L;
455             s->insert = 0;
456         }
457         dictionary += dictLength - s->w_size;  /* use the tail */
458         dictLength = s->w_size;
459     }
460 
461     /* insert dictionary into window and hash */
462     avail = strm->avail_in;
463     next = strm->next_in;
464     strm->avail_in = dictLength;
465     strm->next_in = (z_const Bytef *)dictionary;
466     fill_window(s);
467     while (s->lookahead >= MIN_MATCH) {
468         str = s->strstart;
469         n = s->lookahead - (MIN_MATCH-1);
470         do {
471             insert_string(s, str);
472             str++;
473         } while (--n);
474         s->strstart = str;
475         s->lookahead = MIN_MATCH-1;
476         fill_window(s);
477     }
478     s->strstart += s->lookahead;
479     s->block_start = (long)s->strstart;
480     s->insert = s->lookahead;
481     s->lookahead = 0;
482     s->match_length = s->prev_length = MIN_MATCH-1;
483     s->match_available = 0;
484     strm->next_in = next;
485     strm->avail_in = avail;
486     s->wrap = wrap;
487     return Z_OK;
488 }
489 
490 /* ========================================================================= */
deflateGetDictionary(strm,dictionary,dictLength)491 int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength)
492     z_streamp strm;
493     Bytef *dictionary;
494     uInt  *dictLength;
495 {
496     deflate_state *s;
497     uInt len;
498 
499     if (deflateStateCheck(strm))
500         return Z_STREAM_ERROR;
501     s = strm->state;
502     len = s->strstart + s->lookahead;
503     if (len > s->w_size)
504         len = s->w_size;
505     if (dictionary != Z_NULL && len)
506         zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
507     if (dictLength != Z_NULL)
508         *dictLength = len;
509     return Z_OK;
510 }
511 
512 /* ========================================================================= */
deflateResetKeep(strm)513 int ZEXPORT deflateResetKeep (strm)
514     z_streamp strm;
515 {
516     deflate_state *s;
517 
518     if (deflateStateCheck(strm)) {
519         return Z_STREAM_ERROR;
520     }
521 
522     strm->total_in = strm->total_out = 0;
523     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
524     strm->data_type = Z_UNKNOWN;
525 
526     s = (deflate_state *)strm->state;
527     s->pending = 0;
528     s->pending_out = s->pending_buf;
529 
530     if (s->wrap < 0) {
531         s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
532     }
533     s->status =
534 #ifdef GZIP
535         s->wrap == 2 ? GZIP_STATE :
536 #endif
537         s->wrap ? INIT_STATE : BUSY_STATE;
538     strm->adler =
539 #ifdef GZIP
540         s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
541 #endif
542         adler32(0L, Z_NULL, 0);
543     s->last_flush = Z_NO_FLUSH;
544 
545     _tr_init(s);
546 
547     return Z_OK;
548 }
549 
550 /* ========================================================================= */
deflateReset(strm)551 int ZEXPORT deflateReset (strm)
552     z_streamp strm;
553 {
554     int ret;
555 
556     ret = deflateResetKeep(strm);
557     if (ret == Z_OK)
558         lm_init(strm->state);
559     return ret;
560 }
561 
562 /* ========================================================================= */
deflateSetHeader(strm,head)563 int ZEXPORT deflateSetHeader (strm, head)
564     z_streamp strm;
565     gz_headerp head;
566 {
567     if (deflateStateCheck(strm) || strm->state->wrap != 2)
568         return Z_STREAM_ERROR;
569     strm->state->gzhead = head;
570     return Z_OK;
571 }
572 
573 /* ========================================================================= */
deflatePending(strm,pending,bits)574 int ZEXPORT deflatePending (strm, pending, bits)
575     unsigned *pending;
576     int *bits;
577     z_streamp strm;
578 {
579     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
580     if (pending != Z_NULL)
581         *pending = strm->state->pending;
582     if (bits != Z_NULL)
583         *bits = strm->state->bi_valid;
584     return Z_OK;
585 }
586 
587 /* ========================================================================= */
deflatePrime(strm,bits,value)588 int ZEXPORT deflatePrime (strm, bits, value)
589     z_streamp strm;
590     int bits;
591     int value;
592 {
593     deflate_state *s;
594     int put;
595 
596     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
597     s = strm->state;
598     if (s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
599         return Z_BUF_ERROR;
600     do {
601         put = Buf_size - s->bi_valid;
602         if (put > bits)
603             put = bits;
604         s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
605         s->bi_valid += put;
606         _tr_flush_bits(s);
607         value >>= put;
608         bits -= put;
609     } while (bits);
610     return Z_OK;
611 }
612 
613 /* ========================================================================= */
deflateParams(strm,level,strategy)614 int ZEXPORT deflateParams(strm, level, strategy)
615     z_streamp strm;
616     int level;
617     int strategy;
618 {
619     deflate_state *s;
620     compress_func func;
621 
622     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
623     s = strm->state;
624 
625 #ifdef FASTEST
626     if (level != 0) level = 1;
627 #else
628     if (level == Z_DEFAULT_COMPRESSION) level = 6;
629 #endif
630     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
631         return Z_STREAM_ERROR;
632     }
633     func = configuration_table[s->level].func;
634 
635     if ((strategy != s->strategy || func != configuration_table[level].func) &&
636         s->high_water) {
637         /* Flush the last buffer: */
638         int err = deflate(strm, Z_BLOCK);
639         if (err == Z_STREAM_ERROR)
640             return err;
641         if (strm->avail_out == 0)
642             return Z_BUF_ERROR;
643     }
644     if (s->level != level) {
645         if (s->level == 0 && s->matches != 0) {
646             if (s->matches == 1)
647                 slide_hash(s);
648             else
649                 CLEAR_HASH(s);
650             s->matches = 0;
651         }
652         s->level = level;
653         s->max_lazy_match   = configuration_table[level].max_lazy;
654         s->good_match       = configuration_table[level].good_length;
655         s->nice_match       = configuration_table[level].nice_length;
656         s->max_chain_length = configuration_table[level].max_chain;
657     }
658     s->strategy = strategy;
659     return Z_OK;
660 }
661 
662 /* ========================================================================= */
deflateTune(strm,good_length,max_lazy,nice_length,max_chain)663 int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
664     z_streamp strm;
665     int good_length;
666     int max_lazy;
667     int nice_length;
668     int max_chain;
669 {
670     deflate_state *s;
671 
672     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
673     s = strm->state;
674     s->good_match = (uInt)good_length;
675     s->max_lazy_match = (uInt)max_lazy;
676     s->nice_match = nice_length;
677     s->max_chain_length = (uInt)max_chain;
678     return Z_OK;
679 }
680 
681 /* =========================================================================
682  * For the default windowBits of 15 and memLevel of 8, this function returns
683  * a close to exact, as well as small, upper bound on the compressed size.
684  * They are coded as constants here for a reason--if the #define's are
685  * changed, then this function needs to be changed as well.  The return
686  * value for 15 and 8 only works for those exact settings.
687  *
688  * For any setting other than those defaults for windowBits and memLevel,
689  * the value returned is a conservative worst case for the maximum expansion
690  * resulting from using fixed blocks instead of stored blocks, which deflate
691  * can emit on compressed data for some combinations of the parameters.
692  *
693  * This function could be more sophisticated to provide closer upper bounds for
694  * every combination of windowBits and memLevel.  But even the conservative
695  * upper bound of about 14% expansion does not seem onerous for output buffer
696  * allocation.
697  */
deflateBound(strm,sourceLen)698 uLong ZEXPORT deflateBound(strm, sourceLen)
699     z_streamp strm;
700     uLong sourceLen;
701 {
702     deflate_state *s;
703     uLong complen, wraplen;
704 
705     /* conservative upper bound for compressed data */
706     complen = sourceLen +
707               ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
708 
709     /* if can't get parameters, return conservative bound plus zlib wrapper */
710     if (deflateStateCheck(strm))
711         return complen + 6;
712 
713     /* compute wrapper length */
714     s = strm->state;
715     switch (s->wrap) {
716     case 0:                                 /* raw deflate */
717         wraplen = 0;
718         break;
719     case 1:                                 /* zlib wrapper */
720         wraplen = 6 + (s->strstart ? 4 : 0);
721         break;
722 #ifdef GZIP
723     case 2:                                 /* gzip wrapper */
724         wraplen = 18;
725         if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
726             Bytef *str;
727             if (s->gzhead->extra != Z_NULL)
728                 wraplen += 2 + s->gzhead->extra_len;
729             str = s->gzhead->name;
730             if (str != Z_NULL)
731                 do {
732                     wraplen++;
733                 } while (*str++);
734             str = s->gzhead->comment;
735             if (str != Z_NULL)
736                 do {
737                     wraplen++;
738                 } while (*str++);
739             if (s->gzhead->hcrc)
740                 wraplen += 2;
741         }
742         break;
743 #endif
744     default:                                /* for compiler happiness */
745         wraplen = 6;
746     }
747 
748     /* if not default parameters, return conservative bound */
749     if (s->w_bits != 15 || s->hash_bits != 8 + 7)
750         return complen + wraplen;
751 
752     /* default settings: return tight bound for that case */
753     return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
754            (sourceLen >> 25) + 13 - 6 + wraplen;
755 }
756 
757 /* =========================================================================
758  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
759  * IN assertion: the stream state is correct and there is enough room in
760  * pending_buf.
761  */
putShortMSB(s,b)762 local void putShortMSB (s, b)
763     deflate_state *s;
764     uInt b;
765 {
766     put_byte(s, (Byte)(b >> 8));
767     put_byte(s, (Byte)(b & 0xff));
768 }
769 
770 /* =========================================================================
771  * Flush as much pending output as possible. All deflate() output, except for
772  * some deflate_stored() output, goes through this function so some
773  * applications may wish to modify it to avoid allocating a large
774  * strm->next_out buffer and copying into it. (See also deflate_read_buf()).
775  */
flush_pending(strm)776 local void flush_pending(strm)
777     z_streamp strm;
778 {
779     unsigned len;
780     deflate_state *s = strm->state;
781 
782     _tr_flush_bits(s);
783     len = s->pending;
784     if (len > strm->avail_out) len = strm->avail_out;
785     if (len == 0) return;
786 
787     zmemcpy(strm->next_out, s->pending_out, len);
788     strm->next_out  += len;
789     s->pending_out  += len;
790     strm->total_out += len;
791     strm->avail_out -= len;
792     s->pending      -= len;
793     if (s->pending == 0) {
794         s->pending_out = s->pending_buf;
795     }
796 }
797 
798 /* ===========================================================================
799  * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
800  */
801 #define HCRC_UPDATE(beg) \
802     do { \
803         if (s->gzhead->hcrc && s->pending > (beg)) \
804             strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
805                                 s->pending - (beg)); \
806     } while (0)
807 
808 /* ========================================================================= */
deflate(strm,flush)809 int ZEXPORT deflate (strm, flush)
810     z_streamp strm;
811     int flush;
812 {
813     int old_flush; /* value of flush param for previous deflate call */
814     deflate_state *s;
815 
816     if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
817         return Z_STREAM_ERROR;
818     }
819     s = strm->state;
820 
821     if (strm->next_out == Z_NULL ||
822         (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
823         (s->status == FINISH_STATE && flush != Z_FINISH)) {
824         ERR_RETURN(strm, Z_STREAM_ERROR);
825     }
826     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
827 
828     old_flush = s->last_flush;
829     s->last_flush = flush;
830 
831     /* Flush as much pending output as possible */
832     if (s->pending != 0) {
833         flush_pending(strm);
834         if (strm->avail_out == 0) {
835             /* Since avail_out is 0, deflate will be called again with
836              * more output space, but possibly with both pending and
837              * avail_in equal to zero. There won't be anything to do,
838              * but this is not an error situation so make sure we
839              * return OK instead of BUF_ERROR at next call of deflate:
840              */
841             s->last_flush = -1;
842             return Z_OK;
843         }
844 
845     /* Make sure there is something to do and avoid duplicate consecutive
846      * flushes. For repeated and useless calls with Z_FINISH, we keep
847      * returning Z_STREAM_END instead of Z_BUF_ERROR.
848      */
849     } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
850                flush != Z_FINISH) {
851         ERR_RETURN(strm, Z_BUF_ERROR);
852     }
853 
854     /* User must not provide more input after the first FINISH: */
855     if (s->status == FINISH_STATE && strm->avail_in != 0) {
856         ERR_RETURN(strm, Z_BUF_ERROR);
857     }
858 
859     /* Write the header */
860     if (s->status == INIT_STATE) {
861         /* zlib header */
862         uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
863         uInt level_flags;
864 
865         if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
866             level_flags = 0;
867         else if (s->level < 6)
868             level_flags = 1;
869         else if (s->level == 6)
870             level_flags = 2;
871         else
872             level_flags = 3;
873         header |= (level_flags << 6);
874         if (s->strstart != 0) header |= PRESET_DICT;
875         header += 31 - (header % 31);
876 
877         putShortMSB(s, header);
878 
879         /* Save the adler32 of the preset dictionary: */
880         if (s->strstart != 0) {
881             putShortMSB(s, (uInt)(strm->adler >> 16));
882             putShortMSB(s, (uInt)(strm->adler & 0xffff));
883         }
884         strm->adler = adler32(0L, Z_NULL, 0);
885         s->status = BUSY_STATE;
886 
887         /* Compression must start with an empty pending buffer */
888         flush_pending(strm);
889         if (s->pending != 0) {
890             s->last_flush = -1;
891             return Z_OK;
892         }
893     }
894 #ifdef GZIP
895     if (s->status == GZIP_STATE) {
896         /* gzip header */
897         crc_reset(s);
898         put_byte(s, 31);
899         put_byte(s, 139);
900         put_byte(s, 8);
901         if (s->gzhead == Z_NULL) {
902             put_byte(s, 0);
903             put_byte(s, 0);
904             put_byte(s, 0);
905             put_byte(s, 0);
906             put_byte(s, 0);
907             put_byte(s, s->level == 9 ? 2 :
908                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
909                       4 : 0));
910             put_byte(s, OS_CODE);
911             s->status = BUSY_STATE;
912 
913             /* Compression must start with an empty pending buffer */
914             flush_pending(strm);
915             if (s->pending != 0) {
916                 s->last_flush = -1;
917                 return Z_OK;
918             }
919         }
920         else {
921             put_byte(s, (s->gzhead->text ? 1 : 0) +
922                      (s->gzhead->hcrc ? 2 : 0) +
923                      (s->gzhead->extra == Z_NULL ? 0 : 4) +
924                      (s->gzhead->name == Z_NULL ? 0 : 8) +
925                      (s->gzhead->comment == Z_NULL ? 0 : 16)
926                      );
927             put_byte(s, (Byte)(s->gzhead->time & 0xff));
928             put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
929             put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
930             put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
931             put_byte(s, s->level == 9 ? 2 :
932                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
933                       4 : 0));
934             put_byte(s, s->gzhead->os & 0xff);
935             if (s->gzhead->extra != Z_NULL) {
936                 put_byte(s, s->gzhead->extra_len & 0xff);
937                 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
938             }
939             if (s->gzhead->hcrc)
940                 strm->adler = crc32(strm->adler, s->pending_buf,
941                                     s->pending);
942             s->gzindex = 0;
943             s->status = EXTRA_STATE;
944         }
945     }
946     if (s->status == EXTRA_STATE) {
947         if (s->gzhead->extra != Z_NULL) {
948             ulg beg = s->pending;   /* start of bytes to update crc */
949             uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
950             while (s->pending + left > s->pending_buf_size) {
951                 uInt copy = s->pending_buf_size - s->pending;
952                 zmemcpy(s->pending_buf + s->pending,
953                         s->gzhead->extra + s->gzindex, copy);
954                 s->pending = s->pending_buf_size;
955                 HCRC_UPDATE(beg);
956                 s->gzindex += copy;
957                 flush_pending(strm);
958                 if (s->pending != 0) {
959                     s->last_flush = -1;
960                     return Z_OK;
961                 }
962                 beg = 0;
963                 left -= copy;
964             }
965             zmemcpy(s->pending_buf + s->pending,
966                     s->gzhead->extra + s->gzindex, left);
967             s->pending += left;
968             HCRC_UPDATE(beg);
969             s->gzindex = 0;
970         }
971         s->status = NAME_STATE;
972     }
973     if (s->status == NAME_STATE) {
974         if (s->gzhead->name != Z_NULL) {
975             ulg beg = s->pending;   /* start of bytes to update crc */
976             int val;
977             do {
978                 if (s->pending == s->pending_buf_size) {
979                     HCRC_UPDATE(beg);
980                     flush_pending(strm);
981                     if (s->pending != 0) {
982                         s->last_flush = -1;
983                         return Z_OK;
984                     }
985                     beg = 0;
986                 }
987                 val = s->gzhead->name[s->gzindex++];
988                 put_byte(s, val);
989             } while (val != 0);
990             HCRC_UPDATE(beg);
991             s->gzindex = 0;
992         }
993         s->status = COMMENT_STATE;
994     }
995     if (s->status == COMMENT_STATE) {
996         if (s->gzhead->comment != Z_NULL) {
997             ulg beg = s->pending;   /* start of bytes to update crc */
998             int val;
999             do {
1000                 if (s->pending == s->pending_buf_size) {
1001                     HCRC_UPDATE(beg);
1002                     flush_pending(strm);
1003                     if (s->pending != 0) {
1004                         s->last_flush = -1;
1005                         return Z_OK;
1006                     }
1007                     beg = 0;
1008                 }
1009                 val = s->gzhead->comment[s->gzindex++];
1010                 put_byte(s, val);
1011             } while (val != 0);
1012             HCRC_UPDATE(beg);
1013         }
1014         s->status = HCRC_STATE;
1015     }
1016     if (s->status == HCRC_STATE) {
1017         if (s->gzhead->hcrc) {
1018             if (s->pending + 2 > s->pending_buf_size) {
1019                 flush_pending(strm);
1020                 if (s->pending != 0) {
1021                     s->last_flush = -1;
1022                     return Z_OK;
1023                 }
1024             }
1025             put_byte(s, (Byte)(strm->adler & 0xff));
1026             put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1027             strm->adler = crc32(0L, Z_NULL, 0);
1028         }
1029         s->status = BUSY_STATE;
1030 
1031         /* Compression must start with an empty pending buffer */
1032         flush_pending(strm);
1033         if (s->pending != 0) {
1034             s->last_flush = -1;
1035             return Z_OK;
1036         }
1037     }
1038 #endif
1039 
1040     /* Start a new block or continue the current one.
1041      */
1042     if (strm->avail_in != 0 || s->lookahead != 0 ||
1043         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
1044         block_state bstate;
1045 
1046         bstate = s->level == 0 ? deflate_stored(s, flush) :
1047                  s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
1048                  s->strategy == Z_RLE ? deflate_rle(s, flush) :
1049                  (*(configuration_table[s->level].func))(s, flush);
1050 
1051         if (bstate == finish_started || bstate == finish_done) {
1052             s->status = FINISH_STATE;
1053         }
1054         if (bstate == need_more || bstate == finish_started) {
1055             if (strm->avail_out == 0) {
1056                 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1057             }
1058             return Z_OK;
1059             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1060              * of deflate should use the same flush parameter to make sure
1061              * that the flush is complete. So we don't have to output an
1062              * empty block here, this will be done at next call. This also
1063              * ensures that for a very small output buffer, we emit at most
1064              * one empty block.
1065              */
1066         }
1067         if (bstate == block_done) {
1068             if (flush == Z_PARTIAL_FLUSH) {
1069                 _tr_align(s);
1070             } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
1071                 _tr_stored_block(s, (char*)0, 0L, 0);
1072                 /* For a full flush, this empty block will be recognized
1073                  * as a special marker by inflate_sync().
1074                  */
1075                 if (flush == Z_FULL_FLUSH) {
1076                     CLEAR_HASH(s);             /* forget history */
1077                     if (s->lookahead == 0) {
1078                         s->strstart = 0;
1079                         s->block_start = 0L;
1080                         s->insert = 0;
1081                     }
1082                 }
1083             }
1084             flush_pending(strm);
1085             if (strm->avail_out == 0) {
1086               s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1087               return Z_OK;
1088             }
1089         }
1090     }
1091 
1092     if (flush != Z_FINISH) return Z_OK;
1093     if (s->wrap <= 0) return Z_STREAM_END;
1094 
1095     /* Write the trailer */
1096 #ifdef GZIP
1097     if (s->wrap == 2) {
1098         crc_finalize(s);
1099         put_byte(s, (Byte)(strm->adler & 0xff));
1100         put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1101         put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
1102         put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
1103         put_byte(s, (Byte)(strm->total_in & 0xff));
1104         put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1105         put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1106         put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1107     }
1108     else
1109 #endif
1110     {
1111         putShortMSB(s, (uInt)(strm->adler >> 16));
1112         putShortMSB(s, (uInt)(strm->adler & 0xffff));
1113     }
1114     flush_pending(strm);
1115     /* If avail_out is zero, the application will call deflate again
1116      * to flush the rest.
1117      */
1118     if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1119     return s->pending != 0 ? Z_OK : Z_STREAM_END;
1120 }
1121 
1122 /* ========================================================================= */
deflateEnd(strm)1123 int ZEXPORT deflateEnd (strm)
1124     z_streamp strm;
1125 {
1126     int status;
1127 
1128     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
1129 
1130     status = strm->state->status;
1131 
1132     /* Deallocate in reverse order of allocations: */
1133     TRY_FREE(strm, strm->state->pending_buf);
1134     TRY_FREE(strm, strm->state->head);
1135     TRY_FREE(strm, strm->state->prev);
1136     TRY_FREE(strm, strm->state->window);
1137 
1138     ZFREE(strm, strm->state);
1139     strm->state = Z_NULL;
1140 
1141     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1142 }
1143 
1144 /* =========================================================================
1145  * Copy the source state to the destination state.
1146  * To simplify the source, this is not supported for 16-bit MSDOS (which
1147  * doesn't have enough memory anyway to duplicate compression states).
1148  */
deflateCopy(dest,source)1149 int ZEXPORT deflateCopy (dest, source)
1150     z_streamp dest;
1151     z_streamp source;
1152 {
1153 #ifdef MAXSEG_64K
1154     return Z_STREAM_ERROR;
1155 #else
1156     deflate_state *ds;
1157     deflate_state *ss;
1158 
1159 
1160     if (deflateStateCheck(source) || dest == Z_NULL) {
1161         return Z_STREAM_ERROR;
1162     }
1163 
1164     ss = source->state;
1165 
1166     zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1167 
1168     ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1169     if (ds == Z_NULL) return Z_MEM_ERROR;
1170     dest->state = (struct internal_state FAR *) ds;
1171     zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1172     ds->strm = dest;
1173 
1174     ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1175     ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
1176     ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
1177     ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);
1178 
1179     if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1180         ds->pending_buf == Z_NULL) {
1181         deflateEnd (dest);
1182         return Z_MEM_ERROR;
1183     }
1184     /* following zmemcpy do not work for 16-bit MSDOS */
1185     zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1186     zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1187     zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1188     zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1189 
1190     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1191     ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1192 
1193     ds->l_desc.dyn_tree = ds->dyn_ltree;
1194     ds->d_desc.dyn_tree = ds->dyn_dtree;
1195     ds->bl_desc.dyn_tree = ds->bl_tree;
1196 
1197     return Z_OK;
1198 #endif /* MAXSEG_64K */
1199 }
1200 
1201 /* ===========================================================================
1202  * Read a new buffer from the current input stream, update the adler32
1203  * and total number of bytes read.  All deflate() input goes through
1204  * this function so some applications may wish to modify it to avoid
1205  * allocating a large strm->next_in buffer and copying from it.
1206  * (See also flush_pending()).
1207  */
deflate_read_buf(strm,buf,size)1208 ZLIB_INTERNAL unsigned deflate_read_buf(strm, buf, size)
1209     z_streamp strm;
1210     Bytef *buf;
1211     unsigned size;
1212 {
1213     unsigned len = strm->avail_in;
1214 
1215     if (len > size) len = size;
1216     if (len == 0) return 0;
1217 
1218     strm->avail_in  -= len;
1219 
1220 #ifdef GZIP
1221     if (strm->state->wrap == 2)
1222         copy_with_crc(strm, buf, len);
1223     else
1224 #endif
1225     {
1226         zmemcpy(buf, strm->next_in, len);
1227         if (strm->state->wrap == 1)
1228             strm->adler = adler32(strm->adler, buf, len);
1229     }
1230     strm->next_in  += len;
1231     strm->total_in += len;
1232 
1233     return len;
1234 }
1235 
1236 /* ===========================================================================
1237  * Initialize the "longest match" routines for a new zlib stream
1238  */
lm_init(s)1239 local void lm_init (s)
1240     deflate_state *s;
1241 {
1242     s->window_size = (ulg)2L*s->w_size;
1243 
1244     CLEAR_HASH(s);
1245 
1246     /* Set the default configuration parameters:
1247      */
1248     s->max_lazy_match   = configuration_table[s->level].max_lazy;
1249     s->good_match       = configuration_table[s->level].good_length;
1250     s->nice_match       = configuration_table[s->level].nice_length;
1251     s->max_chain_length = configuration_table[s->level].max_chain;
1252 
1253     s->strstart = 0;
1254     s->block_start = 0L;
1255     s->lookahead = 0;
1256     s->insert = 0;
1257     s->match_length = s->prev_length = MIN_MATCH-1;
1258     s->match_available = 0;
1259     s->ins_h = 0;
1260 #ifndef FASTEST
1261 #ifdef ASMV
1262     match_init(); /* initialize the asm code */
1263 #endif
1264 #endif
1265 }
1266 
1267 #ifndef FASTEST
1268 /* ===========================================================================
1269  * Set match_start to the longest match starting at the given string and
1270  * return its length. Matches shorter or equal to prev_length are discarded,
1271  * in which case the result is equal to prev_length and match_start is
1272  * garbage.
1273  * IN assertions: cur_match is the head of the hash chain for the current
1274  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1275  * OUT assertion: the match length is not greater than s->lookahead.
1276  */
1277 #ifndef ASMV
1278 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1279  * match.S. The code will be functionally equivalent.
1280  */
longest_match(s,cur_match)1281 local uInt longest_match(s, cur_match)
1282     deflate_state *s;
1283     IPos cur_match;                             /* current match */
1284 {
1285     unsigned chain_length = s->max_chain_length;/* max hash chain length */
1286     register Bytef *scan = s->window + s->strstart; /* current string */
1287     register Bytef *match;                      /* matched string */
1288     register int len;                           /* length of current match */
1289     int best_len = (int)s->prev_length;         /* best match length so far */
1290     int nice_match = s->nice_match;             /* stop if match long enough */
1291     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1292         s->strstart - (IPos)MAX_DIST(s) : NIL;
1293     /* Stop when cur_match becomes <= limit. To simplify the code,
1294      * we prevent matches with the string of window index 0.
1295      */
1296     Posf *prev = s->prev;
1297     uInt wmask = s->w_mask;
1298 
1299 #ifdef UNALIGNED_OK
1300     /* Compare two bytes at a time. Note: this is not always beneficial.
1301      * Try with and without -DUNALIGNED_OK to check.
1302      */
1303     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1304     register ush scan_start = *(ushf*)scan;
1305     register ush scan_end   = *(ushf*)(scan+best_len-1);
1306 #else
1307     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1308     register Byte scan_end1  = scan[best_len-1];
1309     register Byte scan_end   = scan[best_len];
1310 #endif
1311 
1312     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1313      * It is easy to get rid of this optimization if necessary.
1314      */
1315     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1316 
1317     /* Do not waste too much time if we already have a good match: */
1318     if (s->prev_length >= s->good_match) {
1319         chain_length >>= 2;
1320     }
1321     /* Do not look for matches beyond the end of the input. This is necessary
1322      * to make deflate deterministic.
1323      */
1324     if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
1325 
1326     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1327 
1328     do {
1329         Assert(cur_match < s->strstart, "no future");
1330         match = s->window + cur_match;
1331 
1332         /* Skip to next match if the match length cannot increase
1333          * or if the match length is less than 2.  Note that the checks below
1334          * for insufficient lookahead only occur occasionally for performance
1335          * reasons.  Therefore uninitialized memory will be accessed, and
1336          * conditional jumps will be made that depend on those values.
1337          * However the length of the match is limited to the lookahead, so
1338          * the output of deflate is not affected by the uninitialized values.
1339          */
1340 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1341         /* This code assumes sizeof(unsigned short) == 2. Do not use
1342          * UNALIGNED_OK if your compiler uses a different size.
1343          */
1344         if (*(ushf*)(match+best_len-1) != scan_end ||
1345             *(ushf*)match != scan_start) continue;
1346 
1347         /* It is not necessary to compare scan[2] and match[2] since they are
1348          * always equal when the other bytes match, given that the hash keys
1349          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1350          * strstart+3, +5, ... up to strstart+257. We check for insufficient
1351          * lookahead only every 4th comparison; the 128th check will be made
1352          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1353          * necessary to put more guard bytes at the end of the window, or
1354          * to check more often for insufficient lookahead.
1355          */
1356         if (!x86_cpu_enable_simd && !arm_cpu_enable_crc32) {
1357           Assert(scan[2] == match[2], "scan[2]?");
1358         } else {
1359           /* When using CRC hashing, scan[2] and match[2] may mismatch, but in
1360            * that case at least one of the other hashed bytes will mismatch
1361            * also. Bytes 0 and 1 were already checked above, and we know there
1362            * are at least four bytes to check otherwise the mismatch would have
1363            * been found by the scan_end comparison above, so: */
1364           Assert(scan[2] == match[2] || scan[3] != match[3], "scan[2]??");
1365         }
1366         scan++, match++;
1367         do {
1368         } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1369                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1370                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1371                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1372                  scan < strend);
1373         /* The funny "do {}" generates better code on most compilers */
1374 
1375         /* Here, scan <= window+strstart+257 */
1376         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1377         if (*scan == *match) scan++;
1378 
1379         len = (MAX_MATCH - 1) - (int)(strend-scan);
1380         scan = strend - (MAX_MATCH-1);
1381 
1382 #else /* UNALIGNED_OK */
1383 
1384         if (match[best_len]   != scan_end  ||
1385             match[best_len-1] != scan_end1 ||
1386             *match            != *scan     ||
1387             *++match          != scan[1])      continue;
1388 
1389         /* The check at best_len-1 can be removed because it will be made
1390          * again later. (This heuristic is not always a win.)
1391          * It is not necessary to compare scan[2] and match[2] since they
1392          * are always equal when the other bytes match, given that
1393          * the hash keys are equal and that HASH_BITS >= 8.
1394          */
1395         scan += 2, match++;
1396         if (!x86_cpu_enable_simd && !arm_cpu_enable_crc32) {
1397           Assert(*scan == *match, "match[2]?");
1398         } else {
1399           /* When using CRC hashing, scan[2] and match[2] may mismatch, but in
1400            * that case at least one of the other hashed bytes will mismatch
1401            * also. Bytes 0 and 1 were already checked above, and we know there
1402            * are at least four bytes to check otherwise the mismatch would have
1403            * been found by the scan_end comparison above, so: */
1404           Assert(*scan == *match || scan[1] != match[1], "match[2]??");
1405         }
1406 
1407         /* We check for insufficient lookahead only every 8th comparison;
1408          * the 256th check will be made at strstart+258.
1409          */
1410         do {
1411         } while (*++scan == *++match && *++scan == *++match &&
1412                  *++scan == *++match && *++scan == *++match &&
1413                  *++scan == *++match && *++scan == *++match &&
1414                  *++scan == *++match && *++scan == *++match &&
1415                  scan < strend);
1416 
1417         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1418 
1419         len = MAX_MATCH - (int)(strend - scan);
1420         scan = strend - MAX_MATCH;
1421 
1422 #endif /* UNALIGNED_OK */
1423 
1424         if (len > best_len) {
1425             s->match_start = cur_match;
1426             best_len = len;
1427             if (len >= nice_match) break;
1428 #ifdef UNALIGNED_OK
1429             scan_end = *(ushf*)(scan+best_len-1);
1430 #else
1431             scan_end1  = scan[best_len-1];
1432             scan_end   = scan[best_len];
1433 #endif
1434         }
1435     } while ((cur_match = prev[cur_match & wmask]) > limit
1436              && --chain_length != 0);
1437 
1438     if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1439     return s->lookahead;
1440 }
1441 #endif /* ASMV */
1442 
1443 #else /* FASTEST */
1444 
1445 /* ---------------------------------------------------------------------------
1446  * Optimized version for FASTEST only
1447  */
longest_match(s,cur_match)1448 local uInt longest_match(s, cur_match)
1449     deflate_state *s;
1450     IPos cur_match;                             /* current match */
1451 {
1452     register Bytef *scan = s->window + s->strstart; /* current string */
1453     register Bytef *match;                       /* matched string */
1454     register int len;                           /* length of current match */
1455     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1456 
1457     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1458      * It is easy to get rid of this optimization if necessary.
1459      */
1460     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1461 
1462     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1463 
1464     Assert(cur_match < s->strstart, "no future");
1465 
1466     match = s->window + cur_match;
1467 
1468     /* Return failure if the match length is less than 2:
1469      */
1470     if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1471 
1472     /* The check at best_len-1 can be removed because it will be made
1473      * again later. (This heuristic is not always a win.)
1474      * It is not necessary to compare scan[2] and match[2] since they
1475      * are always equal when the other bytes match, given that
1476      * the hash keys are equal and that HASH_BITS >= 8.
1477      */
1478     scan += 2, match += 2;
1479     Assert(*scan == *match, "match[2]?");
1480 
1481     /* We check for insufficient lookahead only every 8th comparison;
1482      * the 256th check will be made at strstart+258.
1483      */
1484     do {
1485     } while (*++scan == *++match && *++scan == *++match &&
1486              *++scan == *++match && *++scan == *++match &&
1487              *++scan == *++match && *++scan == *++match &&
1488              *++scan == *++match && *++scan == *++match &&
1489              scan < strend);
1490 
1491     Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1492 
1493     len = MAX_MATCH - (int)(strend - scan);
1494 
1495     if (len < MIN_MATCH) return MIN_MATCH - 1;
1496 
1497     s->match_start = cur_match;
1498     return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1499 }
1500 
1501 #endif /* FASTEST */
1502 
1503 #ifdef ZLIB_DEBUG
1504 
1505 #define EQUAL 0
1506 /* result of memcmp for equal strings */
1507 
1508 /* ===========================================================================
1509  * Check that the match at match_start is indeed a match.
1510  */
check_match(s,start,match,length)1511 local void check_match(s, start, match, length)
1512     deflate_state *s;
1513     IPos start, match;
1514     int length;
1515 {
1516     /* check that the match is indeed a match */
1517     if (zmemcmp(s->window + match,
1518                 s->window + start, length) != EQUAL) {
1519         fprintf(stderr, " start %u, match %u, length %d\n",
1520                 start, match, length);
1521         do {
1522             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1523         } while (--length != 0);
1524         z_error("invalid match");
1525     }
1526     if (z_verbose > 1) {
1527         fprintf(stderr,"\\[%d,%d]", start-match, length);
1528         do { putc(s->window[start++], stderr); } while (--length != 0);
1529     }
1530 }
1531 #else
1532 #  define check_match(s, start, match, length)
1533 #endif /* ZLIB_DEBUG */
1534 
1535 /* ===========================================================================
1536  * Fill the window when the lookahead becomes insufficient.
1537  * Updates strstart and lookahead.
1538  *
1539  * IN assertion: lookahead < MIN_LOOKAHEAD
1540  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1541  *    At least one byte has been read, or avail_in == 0; reads are
1542  *    performed for at least two bytes (required for the zip translate_eol
1543  *    option -- not supported here).
1544  */
1545 local void fill_window_c(deflate_state *s);
1546 
fill_window(deflate_state * s)1547 local void fill_window(deflate_state *s)
1548 {
1549 #ifdef DEFLATE_FILL_WINDOW_SSE2
1550     if (x86_cpu_enable_simd) {
1551         fill_window_sse(s);
1552         return;
1553     }
1554 #endif
1555     fill_window_c(s);
1556 }
1557 
fill_window_c(s)1558 local void fill_window_c(s)
1559     deflate_state *s;
1560 {
1561     unsigned n;
1562     unsigned more;    /* Amount of free space at the end of the window. */
1563     uInt wsize = s->w_size;
1564 
1565     Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1566 
1567     do {
1568         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1569 
1570         /* Deal with !@#$% 64K limit: */
1571         if (sizeof(int) <= 2) {
1572             if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1573                 more = wsize;
1574 
1575             } else if (more == (unsigned)(-1)) {
1576                 /* Very unlikely, but possible on 16 bit machine if
1577                  * strstart == 0 && lookahead == 1 (input done a byte at time)
1578                  */
1579                 more--;
1580             }
1581         }
1582 
1583         /* If the window is almost full and there is insufficient lookahead,
1584          * move the upper half to the lower one to make room in the upper half.
1585          */
1586         if (s->strstart >= wsize+MAX_DIST(s)) {
1587 
1588             zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);
1589             s->match_start -= wsize;
1590             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
1591             s->block_start -= (long) wsize;
1592             slide_hash(s);
1593             more += wsize;
1594         }
1595         if (s->strm->avail_in == 0) break;
1596 
1597         /* If there was no sliding:
1598          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1599          *    more == window_size - lookahead - strstart
1600          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1601          * => more >= window_size - 2*WSIZE + 2
1602          * In the BIG_MEM or MMAP case (not yet supported),
1603          *   window_size == input_size + MIN_LOOKAHEAD  &&
1604          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1605          * Otherwise, window_size == 2*WSIZE so more >= 2.
1606          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1607          */
1608         Assert(more >= 2, "more < 2");
1609 
1610         n = deflate_read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1611         s->lookahead += n;
1612 
1613         /* Initialize the hash value now that we have some input: */
1614         if (s->lookahead + s->insert >= MIN_MATCH) {
1615             uInt str = s->strstart - s->insert;
1616             s->ins_h = s->window[str];
1617             UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
1618 #if MIN_MATCH != 3
1619             Call UPDATE_HASH() MIN_MATCH-3 more times
1620 #endif
1621             while (s->insert) {
1622                 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1623 #ifndef FASTEST
1624                 s->prev[str & s->w_mask] = s->head[s->ins_h];
1625 #endif
1626                 s->head[s->ins_h] = (Pos)str;
1627                 str++;
1628                 s->insert--;
1629                 if (s->lookahead + s->insert < MIN_MATCH)
1630                     break;
1631             }
1632         }
1633         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1634          * but this is not important since only literal bytes will be emitted.
1635          */
1636 
1637     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1638 
1639     /* If the WIN_INIT bytes after the end of the current data have never been
1640      * written, then zero those bytes in order to avoid memory check reports of
1641      * the use of uninitialized (or uninitialised as Julian writes) bytes by
1642      * the longest match routines.  Update the high water mark for the next
1643      * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1644      * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1645      */
1646     if (s->high_water < s->window_size) {
1647         ulg curr = s->strstart + (ulg)(s->lookahead);
1648         ulg init;
1649 
1650         if (s->high_water < curr) {
1651             /* Previous high water mark below current data -- zero WIN_INIT
1652              * bytes or up to end of window, whichever is less.
1653              */
1654             init = s->window_size - curr;
1655             if (init > WIN_INIT)
1656                 init = WIN_INIT;
1657             zmemzero(s->window + curr, (unsigned)init);
1658             s->high_water = curr + init;
1659         }
1660         else if (s->high_water < (ulg)curr + WIN_INIT) {
1661             /* High water mark at or above current data, but below current data
1662              * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1663              * to end of window, whichever is less.
1664              */
1665             init = (ulg)curr + WIN_INIT - s->high_water;
1666             if (init > s->window_size - s->high_water)
1667                 init = s->window_size - s->high_water;
1668             zmemzero(s->window + s->high_water, (unsigned)init);
1669             s->high_water += init;
1670         }
1671     }
1672 
1673     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1674            "not enough room for search");
1675 }
1676 
1677 /* ===========================================================================
1678  * Flush the current block, with given end-of-file flag.
1679  * IN assertion: strstart is set to the end of the current match.
1680  */
1681 #define FLUSH_BLOCK_ONLY(s, last) { \
1682    _tr_flush_block(s, (s->block_start >= 0L ? \
1683                    (charf *)&s->window[(unsigned)s->block_start] : \
1684                    (charf *)Z_NULL), \
1685                 (ulg)((long)s->strstart - s->block_start), \
1686                 (last)); \
1687    s->block_start = s->strstart; \
1688    flush_pending(s->strm); \
1689    Tracev((stderr,"[FLUSH]")); \
1690 }
1691 
1692 /* Same but force premature exit if necessary. */
1693 #define FLUSH_BLOCK(s, last) { \
1694    FLUSH_BLOCK_ONLY(s, last); \
1695    if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1696 }
1697 
1698 /* Maximum stored block length in deflate format (not including header). */
1699 #define MAX_STORED 65535
1700 
1701 /* Minimum of a and b. */
1702 #define MIN(a, b) ((a) > (b) ? (b) : (a))
1703 
1704 /* ===========================================================================
1705  * Copy without compression as much as possible from the input stream, return
1706  * the current block state.
1707  *
1708  * In case deflateParams() is used to later switch to a non-zero compression
1709  * level, s->matches (otherwise unused when storing) keeps track of the number
1710  * of hash table slides to perform. If s->matches is 1, then one hash table
1711  * slide will be done when switching. If s->matches is 2, the maximum value
1712  * allowed here, then the hash table will be cleared, since two or more slides
1713  * is the same as a clear.
1714  *
1715  * deflate_stored() is written to minimize the number of times an input byte is
1716  * copied. It is most efficient with large input and output buffers, which
1717  * maximizes the opportunites to have a single copy from next_in to next_out.
1718  */
deflate_stored(s,flush)1719 local block_state deflate_stored(s, flush)
1720     deflate_state *s;
1721     int flush;
1722 {
1723     /* Smallest worthy block size when not flushing or finishing. By default
1724      * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1725      * large input and output buffers, the stored block size will be larger.
1726      */
1727     unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1728 
1729     /* Copy as many min_block or larger stored blocks directly to next_out as
1730      * possible. If flushing, copy the remaining available input to next_out as
1731      * stored blocks, if there is enough space.
1732      */
1733     unsigned len, left, have, last = 0;
1734     unsigned used = s->strm->avail_in;
1735     do {
1736         /* Set len to the maximum size block that we can copy directly with the
1737          * available input data and output space. Set left to how much of that
1738          * would be copied from what's left in the window.
1739          */
1740         len = MAX_STORED;       /* maximum deflate stored block length */
1741         have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1742         if (s->strm->avail_out < have)          /* need room for header */
1743             break;
1744             /* maximum stored block length that will fit in avail_out: */
1745         have = s->strm->avail_out - have;
1746         left = s->strstart - s->block_start;    /* bytes left in window */
1747         if (len > (ulg)left + s->strm->avail_in)
1748             len = left + s->strm->avail_in;     /* limit len to the input */
1749         if (len > have)
1750             len = have;                         /* limit len to the output */
1751 
1752         /* If the stored block would be less than min_block in length, or if
1753          * unable to copy all of the available input when flushing, then try
1754          * copying to the window and the pending buffer instead. Also don't
1755          * write an empty block when flushing -- deflate() does that.
1756          */
1757         if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
1758                                 flush == Z_NO_FLUSH ||
1759                                 len != left + s->strm->avail_in))
1760             break;
1761 
1762         /* Make a dummy stored block in pending to get the header bytes,
1763          * including any pending bits. This also updates the debugging counts.
1764          */
1765         last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
1766         _tr_stored_block(s, (char *)0, 0L, last);
1767 
1768         /* Replace the lengths in the dummy stored block with len. */
1769         s->pending_buf[s->pending - 4] = len;
1770         s->pending_buf[s->pending - 3] = len >> 8;
1771         s->pending_buf[s->pending - 2] = ~len;
1772         s->pending_buf[s->pending - 1] = ~len >> 8;
1773 
1774         /* Write the stored block header bytes. */
1775         flush_pending(s->strm);
1776 
1777 #ifdef ZLIB_DEBUG
1778         /* Update debugging counts for the data about to be copied. */
1779         s->compressed_len += len << 3;
1780         s->bits_sent += len << 3;
1781 #endif
1782 
1783         /* Copy uncompressed bytes from the window to next_out. */
1784         if (left) {
1785             if (left > len)
1786                 left = len;
1787             zmemcpy(s->strm->next_out, s->window + s->block_start, left);
1788             s->strm->next_out += left;
1789             s->strm->avail_out -= left;
1790             s->strm->total_out += left;
1791             s->block_start += left;
1792             len -= left;
1793         }
1794 
1795         /* Copy uncompressed bytes directly from next_in to next_out, updating
1796          * the check value.
1797          */
1798         if (len) {
1799             deflate_read_buf(s->strm, s->strm->next_out, len);
1800             s->strm->next_out += len;
1801             s->strm->avail_out -= len;
1802             s->strm->total_out += len;
1803         }
1804     } while (last == 0);
1805 
1806     /* Update the sliding window with the last s->w_size bytes of the copied
1807      * data, or append all of the copied data to the existing window if less
1808      * than s->w_size bytes were copied. Also update the number of bytes to
1809      * insert in the hash tables, in the event that deflateParams() switches to
1810      * a non-zero compression level.
1811      */
1812     used -= s->strm->avail_in;      /* number of input bytes directly copied */
1813     if (used) {
1814         /* If any input was used, then no unused input remains in the window,
1815          * therefore s->block_start == s->strstart.
1816          */
1817         if (used >= s->w_size) {    /* supplant the previous history */
1818             s->matches = 2;         /* clear hash */
1819             zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1820             s->strstart = s->w_size;
1821         }
1822         else {
1823             if (s->window_size - s->strstart <= used) {
1824                 /* Slide the window down. */
1825                 s->strstart -= s->w_size;
1826                 zmemcpy(s->window, s->window + s->w_size, s->strstart);
1827                 if (s->matches < 2)
1828                     s->matches++;   /* add a pending slide_hash() */
1829             }
1830             zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
1831             s->strstart += used;
1832         }
1833         s->block_start = s->strstart;
1834         s->insert += MIN(used, s->w_size - s->insert);
1835     }
1836     if (s->high_water < s->strstart)
1837         s->high_water = s->strstart;
1838 
1839     /* If the last block was written to next_out, then done. */
1840     if (last)
1841         return finish_done;
1842 
1843     /* If flushing and all input has been consumed, then done. */
1844     if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
1845         s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
1846         return block_done;
1847 
1848     /* Fill the window with any remaining input. */
1849     have = s->window_size - s->strstart - 1;
1850     if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
1851         /* Slide the window down. */
1852         s->block_start -= s->w_size;
1853         s->strstart -= s->w_size;
1854         zmemcpy(s->window, s->window + s->w_size, s->strstart);
1855         if (s->matches < 2)
1856             s->matches++;           /* add a pending slide_hash() */
1857         have += s->w_size;          /* more space now */
1858     }
1859     if (have > s->strm->avail_in)
1860         have = s->strm->avail_in;
1861     if (have) {
1862         deflate_read_buf(s->strm, s->window + s->strstart, have);
1863         s->strstart += have;
1864     }
1865     if (s->high_water < s->strstart)
1866         s->high_water = s->strstart;
1867 
1868     /* There was not enough avail_out to write a complete worthy or flushed
1869      * stored block to next_out. Write a stored block to pending instead, if we
1870      * have enough input for a worthy block, or if flushing and there is enough
1871      * room for the remaining input as a stored block in the pending buffer.
1872      */
1873     have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1874         /* maximum stored block length that will fit in pending: */
1875     have = MIN(s->pending_buf_size - have, MAX_STORED);
1876     min_block = MIN(have, s->w_size);
1877     left = s->strstart - s->block_start;
1878     if (left >= min_block ||
1879         ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
1880          s->strm->avail_in == 0 && left <= have)) {
1881         len = MIN(left, have);
1882         last = flush == Z_FINISH && s->strm->avail_in == 0 &&
1883                len == left ? 1 : 0;
1884         _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
1885         s->block_start += len;
1886         flush_pending(s->strm);
1887     }
1888 
1889     /* We've done all we can with the available input and output. */
1890     return last ? finish_started : need_more;
1891 }
1892 
1893 /* ===========================================================================
1894  * Compress as much as possible from the input stream, return the current
1895  * block state.
1896  * This function does not perform lazy evaluation of matches and inserts
1897  * new strings in the dictionary only for unmatched strings or for short
1898  * matches. It is used only for the fast compression options.
1899  */
deflate_fast(s,flush)1900 local block_state deflate_fast(s, flush)
1901     deflate_state *s;
1902     int flush;
1903 {
1904     IPos hash_head;       /* head of the hash chain */
1905     int bflush;           /* set if current block must be flushed */
1906 
1907     for (;;) {
1908         /* Make sure that we always have enough lookahead, except
1909          * at the end of the input file. We need MAX_MATCH bytes
1910          * for the next match, plus MIN_MATCH bytes to insert the
1911          * string following the next match.
1912          */
1913         if (s->lookahead < MIN_LOOKAHEAD) {
1914             fill_window(s);
1915             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1916                 return need_more;
1917             }
1918             if (s->lookahead == 0) break; /* flush the current block */
1919         }
1920 
1921         /* Insert the string window[strstart .. strstart+2] in the
1922          * dictionary, and set hash_head to the head of the hash chain:
1923          */
1924         hash_head = NIL;
1925         if (s->lookahead >= MIN_MATCH) {
1926             hash_head = insert_string(s, s->strstart);
1927         }
1928 
1929         /* Find the longest match, discarding those <= prev_length.
1930          * At this point we have always match_length < MIN_MATCH
1931          */
1932         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1933             /* To simplify the code, we prevent matches with the string
1934              * of window index 0 (in particular we have to avoid a match
1935              * of the string with itself at the start of the input file).
1936              */
1937             s->match_length = longest_match (s, hash_head);
1938             /* longest_match() sets match_start */
1939         }
1940         if (s->match_length >= MIN_MATCH) {
1941             check_match(s, s->strstart, s->match_start, s->match_length);
1942 
1943             _tr_tally_dist(s, s->strstart - s->match_start,
1944                            s->match_length - MIN_MATCH, bflush);
1945 
1946             s->lookahead -= s->match_length;
1947 
1948             /* Insert new strings in the hash table only if the match length
1949              * is not too large. This saves time but degrades compression.
1950              */
1951 #ifndef FASTEST
1952             if (s->match_length <= s->max_insert_length &&
1953                 s->lookahead >= MIN_MATCH) {
1954                 s->match_length--; /* string at strstart already in table */
1955                 do {
1956                     s->strstart++;
1957                     hash_head = insert_string(s, s->strstart);
1958                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1959                      * always MIN_MATCH bytes ahead.
1960                      */
1961                 } while (--s->match_length != 0);
1962                 s->strstart++;
1963             } else
1964 #endif
1965             {
1966                 s->strstart += s->match_length;
1967                 s->match_length = 0;
1968                 s->ins_h = s->window[s->strstart];
1969                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1970 #if MIN_MATCH != 3
1971                 Call UPDATE_HASH() MIN_MATCH-3 more times
1972 #endif
1973                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1974                  * matter since it will be recomputed at next deflate call.
1975                  */
1976             }
1977         } else {
1978             /* No match, output a literal byte */
1979             Tracevv((stderr,"%c", s->window[s->strstart]));
1980             _tr_tally_lit (s, s->window[s->strstart], bflush);
1981             s->lookahead--;
1982             s->strstart++;
1983         }
1984         if (bflush) FLUSH_BLOCK(s, 0);
1985     }
1986     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1987     if (flush == Z_FINISH) {
1988         FLUSH_BLOCK(s, 1);
1989         return finish_done;
1990     }
1991     if (s->sym_next)
1992         FLUSH_BLOCK(s, 0);
1993     return block_done;
1994 }
1995 
1996 #ifndef FASTEST
1997 /* ===========================================================================
1998  * Same as above, but achieves better compression. We use a lazy
1999  * evaluation for matches: a match is finally adopted only if there is
2000  * no better match at the next window position.
2001  */
deflate_slow(s,flush)2002 local block_state deflate_slow(s, flush)
2003     deflate_state *s;
2004     int flush;
2005 {
2006     IPos hash_head;          /* head of hash chain */
2007     int bflush;              /* set if current block must be flushed */
2008 
2009     /* Process the input block. */
2010     for (;;) {
2011         /* Make sure that we always have enough lookahead, except
2012          * at the end of the input file. We need MAX_MATCH bytes
2013          * for the next match, plus MIN_MATCH bytes to insert the
2014          * string following the next match.
2015          */
2016         if (s->lookahead < MIN_LOOKAHEAD) {
2017             fill_window(s);
2018             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
2019                 return need_more;
2020             }
2021             if (s->lookahead == 0) break; /* flush the current block */
2022         }
2023 
2024         /* Insert the string window[strstart .. strstart+2] in the
2025          * dictionary, and set hash_head to the head of the hash chain:
2026          */
2027         hash_head = NIL;
2028         if (s->lookahead >= MIN_MATCH) {
2029             hash_head = insert_string(s, s->strstart);
2030         }
2031 
2032         /* Find the longest match, discarding those <= prev_length.
2033          */
2034         s->prev_length = s->match_length, s->prev_match = s->match_start;
2035         s->match_length = MIN_MATCH-1;
2036 
2037         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
2038             s->strstart - hash_head <= MAX_DIST(s)) {
2039             /* To simplify the code, we prevent matches with the string
2040              * of window index 0 (in particular we have to avoid a match
2041              * of the string with itself at the start of the input file).
2042              */
2043             s->match_length = longest_match (s, hash_head);
2044             /* longest_match() sets match_start */
2045 
2046             if (s->match_length <= 5 && (s->strategy == Z_FILTERED
2047 #if TOO_FAR <= 32767
2048                 || (s->match_length == MIN_MATCH &&
2049                     s->strstart - s->match_start > TOO_FAR)
2050 #endif
2051                 )) {
2052 
2053                 /* If prev_match is also MIN_MATCH, match_start is garbage
2054                  * but we will ignore the current match anyway.
2055                  */
2056                 s->match_length = MIN_MATCH-1;
2057             }
2058         }
2059         /* If there was a match at the previous step and the current
2060          * match is not better, output the previous match:
2061          */
2062         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
2063             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
2064             /* Do not insert strings in hash table beyond this. */
2065 
2066             if (s->prev_match == -1) {
2067                 /* The window has slid one byte past the previous match,
2068                  * so the first byte cannot be compared. */
2069                 check_match(s, s->strstart, s->prev_match+1, s->prev_length-1);
2070             } else {
2071                 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
2072             }
2073 
2074             _tr_tally_dist(s, s->strstart -1 - s->prev_match,
2075                            s->prev_length - MIN_MATCH, bflush);
2076 
2077             /* Insert in hash table all strings up to the end of the match.
2078              * strstart-1 and strstart are already inserted. If there is not
2079              * enough lookahead, the last two strings are not inserted in
2080              * the hash table.
2081              */
2082             s->lookahead -= s->prev_length-1;
2083             s->prev_length -= 2;
2084             do {
2085                 if (++s->strstart <= max_insert) {
2086                     hash_head = insert_string(s, s->strstart);
2087                 }
2088             } while (--s->prev_length != 0);
2089             s->match_available = 0;
2090             s->match_length = MIN_MATCH-1;
2091             s->strstart++;
2092 
2093             if (bflush) FLUSH_BLOCK(s, 0);
2094 
2095         } else if (s->match_available) {
2096             /* If there was no match at the previous position, output a
2097              * single literal. If there was a match but the current match
2098              * is longer, truncate the previous match to a single literal.
2099              */
2100             Tracevv((stderr,"%c", s->window[s->strstart-1]));
2101             _tr_tally_lit(s, s->window[s->strstart-1], bflush);
2102             if (bflush) {
2103                 FLUSH_BLOCK_ONLY(s, 0);
2104             }
2105             s->strstart++;
2106             s->lookahead--;
2107             if (s->strm->avail_out == 0) return need_more;
2108         } else {
2109             /* There is no previous match to compare with, wait for
2110              * the next step to decide.
2111              */
2112             s->match_available = 1;
2113             s->strstart++;
2114             s->lookahead--;
2115         }
2116     }
2117     Assert (flush != Z_NO_FLUSH, "no flush?");
2118     if (s->match_available) {
2119         Tracevv((stderr,"%c", s->window[s->strstart-1]));
2120         _tr_tally_lit(s, s->window[s->strstart-1], bflush);
2121         s->match_available = 0;
2122     }
2123     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
2124     if (flush == Z_FINISH) {
2125         FLUSH_BLOCK(s, 1);
2126         return finish_done;
2127     }
2128     if (s->sym_next)
2129         FLUSH_BLOCK(s, 0);
2130     return block_done;
2131 }
2132 #endif /* FASTEST */
2133 
2134 /* ===========================================================================
2135  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2136  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
2137  * deflate switches away from Z_RLE.)
2138  */
deflate_rle(s,flush)2139 local block_state deflate_rle(s, flush)
2140     deflate_state *s;
2141     int flush;
2142 {
2143     int bflush;             /* set if current block must be flushed */
2144     uInt prev;              /* byte at distance one to match */
2145     Bytef *scan, *strend;   /* scan goes up to strend for length of run */
2146 
2147     for (;;) {
2148         /* Make sure that we always have enough lookahead, except
2149          * at the end of the input file. We need MAX_MATCH bytes
2150          * for the longest run, plus one for the unrolled loop.
2151          */
2152         if (s->lookahead <= MAX_MATCH) {
2153             fill_window(s);
2154             if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
2155                 return need_more;
2156             }
2157             if (s->lookahead == 0) break; /* flush the current block */
2158         }
2159 
2160         /* See how many times the previous byte repeats */
2161         s->match_length = 0;
2162         if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
2163             scan = s->window + s->strstart - 1;
2164             prev = *scan;
2165             if (prev == *++scan && prev == *++scan && prev == *++scan) {
2166                 strend = s->window + s->strstart + MAX_MATCH;
2167                 do {
2168                 } while (prev == *++scan && prev == *++scan &&
2169                          prev == *++scan && prev == *++scan &&
2170                          prev == *++scan && prev == *++scan &&
2171                          prev == *++scan && prev == *++scan &&
2172                          scan < strend);
2173                 s->match_length = MAX_MATCH - (uInt)(strend - scan);
2174                 if (s->match_length > s->lookahead)
2175                     s->match_length = s->lookahead;
2176             }
2177             Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
2178         }
2179 
2180         /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2181         if (s->match_length >= MIN_MATCH) {
2182             check_match(s, s->strstart, s->strstart - 1, s->match_length);
2183 
2184             _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
2185 
2186             s->lookahead -= s->match_length;
2187             s->strstart += s->match_length;
2188             s->match_length = 0;
2189         } else {
2190             /* No match, output a literal byte */
2191             Tracevv((stderr,"%c", s->window[s->strstart]));
2192             _tr_tally_lit (s, s->window[s->strstart], bflush);
2193             s->lookahead--;
2194             s->strstart++;
2195         }
2196         if (bflush) FLUSH_BLOCK(s, 0);
2197     }
2198     s->insert = 0;
2199     if (flush == Z_FINISH) {
2200         FLUSH_BLOCK(s, 1);
2201         return finish_done;
2202     }
2203     if (s->sym_next)
2204         FLUSH_BLOCK(s, 0);
2205     return block_done;
2206 }
2207 
2208 /* ===========================================================================
2209  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
2210  * (It will be regenerated if this run of deflate switches away from Huffman.)
2211  */
deflate_huff(s,flush)2212 local block_state deflate_huff(s, flush)
2213     deflate_state *s;
2214     int flush;
2215 {
2216     int bflush;             /* set if current block must be flushed */
2217 
2218     for (;;) {
2219         /* Make sure that we have a literal to write. */
2220         if (s->lookahead == 0) {
2221             fill_window(s);
2222             if (s->lookahead == 0) {
2223                 if (flush == Z_NO_FLUSH)
2224                     return need_more;
2225                 break;      /* flush the current block */
2226             }
2227         }
2228 
2229         /* Output a literal byte */
2230         s->match_length = 0;
2231         Tracevv((stderr,"%c", s->window[s->strstart]));
2232         _tr_tally_lit (s, s->window[s->strstart], bflush);
2233         s->lookahead--;
2234         s->strstart++;
2235         if (bflush) FLUSH_BLOCK(s, 0);
2236     }
2237     s->insert = 0;
2238     if (flush == Z_FINISH) {
2239         FLUSH_BLOCK(s, 1);
2240         return finish_done;
2241     }
2242     if (s->sym_next)
2243         FLUSH_BLOCK(s, 0);
2244     return block_done;
2245 }
2246