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