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