• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* deflate.c -- compress data using the deflation algorithm
2  * Copyright (C) 1995-2016 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 #include "zbuild.h"
51 #include "deflate.h"
52 #include "deflate_p.h"
53 #include "functable.h"
54 
55 const char PREFIX(deflate_copyright)[] = " deflate 1.2.12.f Copyright 1995-2016 Jean-loup Gailly and Mark Adler ";
56 /*
57   If you use the zlib library in a product, an acknowledgment is welcome
58   in the documentation of your product. If for some reason you cannot
59   include such an acknowledgment, I would appreciate that you keep this
60   copyright string in the executable of your product.
61  */
62 
63 /* ===========================================================================
64  *  Architecture-specific hooks.
65  */
66 #ifdef S390_DFLTCC_DEFLATE
67 #  include "arch/s390/dfltcc_deflate.h"
68 #else
69 /* Memory management for the deflate state. Useful for allocating arch-specific extension blocks. */
70 #  define ZALLOC_STATE(strm, items, size) ZALLOC(strm, items, size)
71 #  define ZFREE_STATE(strm, addr) ZFREE(strm, addr)
72 #  define ZCOPY_STATE(dst, src, size) memcpy(dst, src, size)
73 /* Memory management for the window. Useful for allocation the aligned window. */
74 #  define ZALLOC_WINDOW(strm, items, size) ZALLOC(strm, items, size)
75 #  define TRY_FREE_WINDOW(strm, addr) TRY_FREE(strm, addr)
76 /* Invoked at the beginning of deflateSetDictionary(). Useful for checking arch-specific window data. */
77 #  define DEFLATE_SET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
78 /* Invoked at the beginning of deflateGetDictionary(). Useful for adjusting arch-specific window data. */
79 #  define DEFLATE_GET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
80 /* Invoked at the end of deflateResetKeep(). Useful for initializing arch-specific extension blocks. */
81 #  define DEFLATE_RESET_KEEP_HOOK(strm) do {} while (0)
82 /* Invoked at the beginning of deflateParams(). Useful for updating arch-specific compression parameters. */
83 #  define DEFLATE_PARAMS_HOOK(strm, level, strategy, hook_flush) do {} while (0)
84 /* Returns whether the last deflate(flush) operation did everything it's supposed to do. */
85 # define DEFLATE_DONE(strm, flush) 1
86 /* Adjusts the upper bound on compressed data length based on compression parameters and uncompressed data length.
87  * Useful when arch-specific deflation code behaves differently than regular zlib-ng algorithms. */
88 #  define DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen) do {} while (0)
89 /* Returns whether an optimistic upper bound on compressed data length should *not* be used.
90  * Useful when arch-specific deflation code behaves differently than regular zlib-ng algorithms. */
91 #  define DEFLATE_NEED_CONSERVATIVE_BOUND(strm) 0
92 /* Invoked for each deflate() call. Useful for plugging arch-specific deflation code. */
93 #  define DEFLATE_HOOK(strm, flush, bstate) 0
94 /* Returns whether zlib-ng should compute a checksum. Set to 0 if arch-specific deflation code already does that. */
95 #  define DEFLATE_NEED_CHECKSUM(strm) 1
96 /* Returns whether reproducibility parameter can be set to a given value. */
97 #  define DEFLATE_CAN_SET_REPRODUCIBLE(strm, reproducible) 1
98 #endif
99 
100 /* ===========================================================================
101  *  Function prototypes.
102  */
103 typedef block_state (*compress_func) (deflate_state *s, int flush);
104 /* Compression function. Returns the block state after the call. */
105 
106 static int deflateStateCheck      (PREFIX3(stream) *strm);
107 static block_state deflate_stored (deflate_state *s, int flush);
108 Z_INTERNAL block_state deflate_fast         (deflate_state *s, int flush);
109 Z_INTERNAL block_state deflate_quick        (deflate_state *s, int flush);
110 #ifndef NO_MEDIUM_STRATEGY
111 Z_INTERNAL block_state deflate_medium       (deflate_state *s, int flush);
112 #endif
113 Z_INTERNAL block_state deflate_slow         (deflate_state *s, int flush);
114 static block_state deflate_rle   (deflate_state *s, int flush);
115 static block_state deflate_huff  (deflate_state *s, int flush);
116 static void lm_init              (deflate_state *s);
117 Z_INTERNAL unsigned read_buf  (PREFIX3(stream) *strm, unsigned char *buf, unsigned size);
118 
119 extern void crc_reset(deflate_state *const s);
120 #ifdef X86_PCLMULQDQ_CRC
121 extern void crc_finalize(deflate_state *const s);
122 #endif
123 extern void copy_with_crc(PREFIX3(stream) *strm, unsigned char *dst, unsigned long size);
124 
125 /* ===========================================================================
126  * Local data
127  */
128 
129 #define NIL 0
130 /* Tail of hash chains */
131 
132 /* Values for max_lazy_match, good_match and max_chain_length, depending on
133  * the desired pack level (0..9). The values given below have been tuned to
134  * exclude worst case performance for pathological files. Better values may be
135  * found for specific files.
136  */
137 typedef struct config_s {
138     uint16_t good_length; /* reduce lazy search above this match length */
139     uint16_t max_lazy;    /* do not perform lazy search above this match length */
140     uint16_t nice_length; /* quit search above this match length */
141     uint16_t max_chain;
142     compress_func func;
143 } config;
144 
145 static const config configuration_table[10] = {
146 /*      good lazy nice chain */
147 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
148 
149 #ifndef NO_QUICK_STRATEGY
150 /* 1 */ {4,    4,  8,    4, deflate_quick},
151 /* 2 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
152 #else
153 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
154 /* 2 */ {4,    5, 16,    8, deflate_fast},
155 #endif
156 
157 /* 3 */ {4,    6, 32,   32, deflate_fast},
158 
159 #ifdef NO_MEDIUM_STRATEGY
160 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
161 /* 5 */ {8,   16, 32,   32, deflate_slow},
162 /* 6 */ {8,   16, 128, 128, deflate_slow},
163 #else
164 /* 4 */ {4,    4, 16,   16, deflate_medium},  /* lazy matches */
165 /* 5 */ {8,   16, 32,   32, deflate_medium},
166 /* 6 */ {8,   16, 128, 128, deflate_medium},
167 #endif
168 
169 /* 7 */ {8,   32, 128,  256, deflate_slow},
170 /* 8 */ {32, 128, 258, 1024, deflate_slow},
171 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
172 
173 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
174  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
175  * meaning.
176  */
177 
178 /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
179 #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
180 
181 
182 /* ===========================================================================
183  * Initialize the hash table. prev[] will be initialized on the fly.
184  */
185 #define CLEAR_HASH(s) do {                                                                \
186     memset((unsigned char *)s->head, 0, HASH_SIZE * sizeof(*s->head)); \
187   } while (0)
188 
189 /* ===========================================================================
190  * Slide the hash table when sliding the window down (could be avoided with 32
191  * bit values at the expense of memory usage). We slide even when level == 0 to
192  * keep the hash table consistent if we switch back to level > 0 later.
193  */
slide_hash_c(deflate_state * s)194 Z_INTERNAL void slide_hash_c(deflate_state *s) {
195     Pos *p;
196     unsigned n;
197     unsigned int wsize = s->w_size;
198 
199     n = HASH_SIZE;
200     p = &s->head[n];
201 #ifdef NOT_TWEAK_COMPILER
202     do {
203         unsigned m;
204         m = *--p;
205         *p = (Pos)(m >= wsize ? m-wsize : NIL);
206     } while (--n);
207 #else
208     /* As of I make this change, gcc (4.8.*) isn't able to vectorize
209      * this hot loop using saturated-subtraction on x86-64 architecture.
210      * To avoid this defect, we can change the loop such that
211      *    o. the pointer advance forward, and
212      *    o. demote the variable 'm' to be local to the loop, and
213      *       choose type "Pos" (instead of 'unsigned int') for the
214      *       variable to avoid unncessary zero-extension.
215      */
216     {
217         unsigned int i;
218         Pos *q = p - n;
219         for (i = 0; i < n; i++) {
220             Pos m = *q;
221             Pos t = wsize;
222             *q++ = (Pos)(m >= t ? m-t: NIL);
223         }
224     }
225 #endif /* NOT_TWEAK_COMPILER */
226 
227     n = wsize;
228     p = &s->prev[n];
229 #ifdef NOT_TWEAK_COMPILER
230     do {
231         unsigned m;
232         m = *--p;
233         *p = (Pos)(m >= wsize ? m-wsize : NIL);
234         /* If n is not on any hash chain, prev[n] is garbage but
235          * its value will never be used.
236          */
237     } while (--n);
238 #else
239     {
240         unsigned int i;
241         Pos *q = p - n;
242         for (i = 0; i < n; i++) {
243             Pos m = *q;
244             Pos t = wsize;
245             *q++ = (Pos)(m >= t ? m-t: NIL);
246         }
247     }
248 #endif /* NOT_TWEAK_COMPILER */
249 }
250 
251 /* ========================================================================= */
PREFIX(deflateInit_)252 int32_t Z_EXPORT PREFIX(deflateInit_)(PREFIX3(stream) *strm, int32_t level, const char *version, int32_t stream_size) {
253     return PREFIX(deflateInit2_)(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size);
254     /* Todo: ignore strm->next_in if we use it as window */
255 }
256 
257 /* ========================================================================= */
PREFIX(deflateInit2_)258 int32_t Z_EXPORT PREFIX(deflateInit2_)(PREFIX3(stream) *strm, int32_t level, int32_t method, int32_t windowBits,
259                            int32_t memLevel, int32_t strategy, const char *version, int32_t stream_size) {
260     uint32_t window_padding = 0;
261     deflate_state *s;
262     int wrap = 1;
263     static const char my_version[] = PREFIX2(VERSION);
264 
265 #if defined(X86_FEATURES)
266     x86_check_features();
267 #elif defined(ARM_FEATURES)
268     arm_check_features();
269 #endif
270 
271     if (version == NULL || version[0] != my_version[0] || stream_size != sizeof(PREFIX3(stream))) {
272         return Z_VERSION_ERROR;
273     }
274     if (strm == NULL)
275         return Z_STREAM_ERROR;
276 
277     strm->msg = NULL;
278     if (strm->zalloc == NULL) {
279         strm->zalloc = zng_calloc;
280         strm->opaque = NULL;
281     }
282     if (strm->zfree == NULL)
283         strm->zfree = zng_cfree;
284 
285     if (level == Z_DEFAULT_COMPRESSION)
286         level = 6;
287 
288     if (windowBits < 0) { /* suppress zlib wrapper */
289         wrap = 0;
290         windowBits = -windowBits;
291 #ifdef GZIP
292     } else if (windowBits > 15) {
293         wrap = 2;       /* write gzip wrapper instead */
294         windowBits -= 16;
295 #endif
296     }
297     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 8 ||
298         windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED ||
299         (windowBits == 8 && wrap != 1)) {
300         return Z_STREAM_ERROR;
301     }
302     if (windowBits == 8)
303         windowBits = 9;  /* until 256-byte window bug fixed */
304 
305 #if !defined(NO_QUICK_STRATEGY) && !defined(S390_DFLTCC_DEFLATE)
306     if (level == 1)
307         windowBits = 13;
308 #endif
309 
310     s = (deflate_state *) ZALLOC_STATE(strm, 1, sizeof(deflate_state));
311     if (s == NULL)
312         return Z_MEM_ERROR;
313     strm->state = (struct internal_state *)s;
314     s->strm = strm;
315     s->status = INIT_STATE;     /* to pass state test in deflateReset() */
316 
317     s->wrap = wrap;
318     s->gzhead = NULL;
319     s->w_bits = (unsigned int)windowBits;
320     s->w_size = 1 << s->w_bits;
321     s->w_mask = s->w_size - 1;
322 
323 #ifdef X86_PCLMULQDQ_CRC
324     window_padding = 8;
325 #endif
326 
327     s->window = (unsigned char *) ZALLOC_WINDOW(strm, s->w_size + window_padding, 2*sizeof(unsigned char));
328     s->prev   = (Pos *)  ZALLOC(strm, s->w_size, sizeof(Pos));
329     memset(s->prev, 0, s->w_size * sizeof(Pos));
330     s->head   = (Pos *)  ZALLOC(strm, HASH_SIZE, sizeof(Pos));
331 
332     s->high_water = 0;      /* nothing written to s->window yet */
333 
334     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
335 
336     /* We overlay pending_buf and sym_buf. This works since the average size
337      * for length/distance pairs over any compressed block is assured to be 31
338      * bits or less.
339      *
340      * Analysis: The longest fixed codes are a length code of 8 bits plus 5
341      * extra bits, for lengths 131 to 257. The longest fixed distance codes are
342      * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
343      * possible fixed-codes length/distance pair is then 31 bits total.
344      *
345      * sym_buf starts one-fourth of the way into pending_buf. So there are
346      * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
347      * in sym_buf is three bytes -- two for the distance and one for the
348      * literal/length. As each symbol is consumed, the pointer to the next
349      * sym_buf value to read moves forward three bytes. From that symbol, up to
350      * 31 bits are written to pending_buf. The closest the written pending_buf
351      * bits gets to the next sym_buf symbol to read is just before the last
352      * code is written. At that time, 31*(n-2) bits have been written, just
353      * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
354      * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
355      * symbols are written.) The closest the writing gets to what is unread is
356      * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
357      * can range from 128 to 32768.
358      *
359      * Therefore, at a minimum, there are 142 bits of space between what is
360      * written and what is read in the overlain buffers, so the symbols cannot
361      * be overwritten by the compressed data. That space is actually 139 bits,
362      * due to the three-bit fixed-code block header.
363      *
364      * That covers the case where either Z_FIXED is specified, forcing fixed
365      * codes, or when the use of fixed codes is chosen, because that choice
366      * results in a smaller compressed block than dynamic codes. That latter
367      * condition then assures that the above analysis also covers all dynamic
368      * blocks. A dynamic-code block will only be chosen to be emitted if it has
369      * fewer bits than a fixed-code block would for the same set of symbols.
370      * Therefore its average symbol length is assured to be less than 31. So
371      * the compressed data for a dynamic block also cannot overwrite the
372      * symbols from which it is being constructed.
373      */
374 
375     s->pending_buf = (unsigned char *) ZALLOC(strm, s->lit_bufsize, 4);
376     s->pending_buf_size = s->lit_bufsize * 4;
377 
378     if (s->window == NULL || s->prev == NULL || s->head == NULL || s->pending_buf == NULL) {
379         s->status = FINISH_STATE;
380         strm->msg = ERR_MSG(Z_MEM_ERROR);
381         PREFIX(deflateEnd)(strm);
382         return Z_MEM_ERROR;
383     }
384     s->sym_buf = s->pending_buf + s->lit_bufsize;
385     s->sym_end = (s->lit_bufsize - 1) * 3;
386     /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
387      * on 16 bit machines and because stored blocks are restricted to
388      * 64K-1 bytes.
389      */
390 
391     s->level = level;
392     s->strategy = strategy;
393     s->block_open = 0;
394     s->reproducible = 0;
395 
396     return PREFIX(deflateReset)(strm);
397 }
398 
399 /* =========================================================================
400  * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
401  */
deflateStateCheck(PREFIX3 (stream)* strm)402 static int deflateStateCheck (PREFIX3(stream) *strm) {
403     deflate_state *s;
404     if (strm == NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
405         return 1;
406     s = strm->state;
407     if (s == NULL || s->strm != strm || (s->status != INIT_STATE &&
408 #ifdef GZIP
409                                            s->status != GZIP_STATE &&
410 #endif
411                                            s->status != EXTRA_STATE &&
412                                            s->status != NAME_STATE &&
413                                            s->status != COMMENT_STATE &&
414                                            s->status != HCRC_STATE &&
415                                            s->status != BUSY_STATE &&
416                                            s->status != FINISH_STATE))
417         return 1;
418     return 0;
419 }
420 
421 /* ========================================================================= */
PREFIX(deflateSetDictionary)422 int32_t Z_EXPORT PREFIX(deflateSetDictionary)(PREFIX3(stream) *strm, const uint8_t *dictionary, uint32_t dictLength) {
423     deflate_state *s;
424     unsigned int str, n;
425     int wrap;
426     uint32_t avail;
427     const unsigned char *next;
428 
429     if (deflateStateCheck(strm) || dictionary == NULL)
430         return Z_STREAM_ERROR;
431     s = strm->state;
432     wrap = s->wrap;
433     if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
434         return Z_STREAM_ERROR;
435 
436     /* when using zlib wrappers, compute Adler-32 for provided dictionary */
437     if (wrap == 1)
438         strm->adler = functable.adler32(strm->adler, dictionary, dictLength);
439     DEFLATE_SET_DICTIONARY_HOOK(strm, dictionary, dictLength);  /* hook for IBM Z DFLTCC */
440     s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
441 
442     /* if dictionary would fill window, just replace the history */
443     if (dictLength >= s->w_size) {
444         if (wrap == 0) {            /* already empty otherwise */
445             CLEAR_HASH(s);
446             s->strstart = 0;
447             s->block_start = 0;
448             s->insert = 0;
449         }
450         dictionary += dictLength - s->w_size;  /* use the tail */
451         dictLength = s->w_size;
452     }
453 
454     /* insert dictionary into window and hash */
455     avail = strm->avail_in;
456     next = strm->next_in;
457     strm->avail_in = dictLength;
458     strm->next_in = (z_const unsigned char *)dictionary;
459     fill_window(s);
460     while (s->lookahead >= MIN_MATCH) {
461         str = s->strstart;
462         n = s->lookahead - (MIN_MATCH-1);
463         functable.insert_string(s, str, n);
464         s->strstart = str + n;
465         s->lookahead = MIN_MATCH-1;
466         fill_window(s);
467     }
468     s->strstart += s->lookahead;
469     s->block_start = (int)s->strstart;
470     s->insert = s->lookahead;
471     s->lookahead = 0;
472     s->prev_length = MIN_MATCH-1;
473     s->match_available = 0;
474     strm->next_in = (z_const unsigned char *)next;
475     strm->avail_in = avail;
476     s->wrap = wrap;
477     return Z_OK;
478 }
479 
480 /* ========================================================================= */
PREFIX(deflateGetDictionary)481 int32_t Z_EXPORT PREFIX(deflateGetDictionary)(PREFIX3(stream) *strm, uint8_t *dictionary, uint32_t *dictLength) {
482     deflate_state *s;
483     unsigned int len;
484 
485     if (deflateStateCheck(strm))
486         return Z_STREAM_ERROR;
487     DEFLATE_GET_DICTIONARY_HOOK(strm, dictionary, dictLength);  /* hook for IBM Z DFLTCC */
488     s = strm->state;
489     len = s->strstart + s->lookahead;
490     if (len > s->w_size)
491         len = s->w_size;
492     if (dictionary != NULL && len)
493         memcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
494     if (dictLength != NULL)
495         *dictLength = len;
496     return Z_OK;
497 }
498 
499 /* ========================================================================= */
PREFIX(deflateResetKeep)500 int32_t Z_EXPORT PREFIX(deflateResetKeep)(PREFIX3(stream) *strm) {
501     deflate_state *s;
502 
503     if (deflateStateCheck(strm))
504         return Z_STREAM_ERROR;
505 
506     strm->total_in = strm->total_out = 0;
507     strm->msg = NULL; /* use zfree if we ever allocate msg dynamically */
508     strm->data_type = Z_UNKNOWN;
509 
510     s = (deflate_state *)strm->state;
511     s->pending = 0;
512     s->pending_out = s->pending_buf;
513 
514     if (s->wrap < 0)
515         s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
516 
517     s->status =
518 #ifdef GZIP
519         s->wrap == 2 ? GZIP_STATE :
520 #endif
521         INIT_STATE;
522 
523 #ifdef GZIP
524     if (s->wrap == 2)
525         crc_reset(s);
526     else
527 #endif
528         strm->adler = ADLER32_INITIAL_VALUE;
529     s->last_flush = -2;
530 
531     zng_tr_init(s);
532 
533     DEFLATE_RESET_KEEP_HOOK(strm);  /* hook for IBM Z DFLTCC */
534 
535     return Z_OK;
536 }
537 
538 /* ========================================================================= */
PREFIX(deflateReset)539 int32_t Z_EXPORT PREFIX(deflateReset)(PREFIX3(stream) *strm) {
540     int ret;
541 
542     ret = PREFIX(deflateResetKeep)(strm);
543     if (ret == Z_OK)
544         lm_init(strm->state);
545     return ret;
546 }
547 
548 /* ========================================================================= */
PREFIX(deflateSetHeader)549 int32_t Z_EXPORT PREFIX(deflateSetHeader)(PREFIX3(stream) *strm, PREFIX(gz_headerp) head) {
550     if (deflateStateCheck(strm) || strm->state->wrap != 2)
551         return Z_STREAM_ERROR;
552     strm->state->gzhead = head;
553     return Z_OK;
554 }
555 
556 /* ========================================================================= */
PREFIX(deflatePending)557 int32_t Z_EXPORT PREFIX(deflatePending)(PREFIX3(stream) *strm, uint32_t *pending, int32_t *bits) {
558     if (deflateStateCheck(strm))
559         return Z_STREAM_ERROR;
560     if (pending != NULL)
561         *pending = strm->state->pending;
562     if (bits != NULL)
563         *bits = strm->state->bi_valid;
564     return Z_OK;
565 }
566 
567 /* ========================================================================= */
PREFIX(deflatePrime)568 int32_t Z_EXPORT PREFIX(deflatePrime)(PREFIX3(stream) *strm, int32_t bits, int32_t value) {
569     deflate_state *s;
570     uint64_t value64 = (uint64_t)value;
571     int32_t put;
572 
573     if (deflateStateCheck(strm))
574         return Z_STREAM_ERROR;
575     s = strm->state;
576     if (bits < 0 || bits > BIT_BUF_SIZE || bits > (int32_t)(sizeof(value) << 3) ||
577         s->sym_buf < s->pending_out + ((BIT_BUF_SIZE + 7) >> 3))
578         return Z_BUF_ERROR;
579     do {
580         put = BIT_BUF_SIZE - s->bi_valid;
581         if (put > bits)
582             put = bits;
583         if (s->bi_valid == 0)
584             s->bi_buf = value64;
585         else
586             s->bi_buf |= (value64 & ((UINT64_C(1) << put) - 1)) << s->bi_valid;
587         s->bi_valid += put;
588         zng_tr_flush_bits(s);
589         value64 >>= put;
590         bits -= put;
591     } while (bits);
592     return Z_OK;
593 }
594 
595 /* ========================================================================= */
PREFIX(deflateParams)596 int32_t Z_EXPORT PREFIX(deflateParams)(PREFIX3(stream) *strm, int32_t level, int32_t strategy) {
597     deflate_state *s;
598     compress_func func;
599     int hook_flush = Z_NO_FLUSH;
600 
601     if (deflateStateCheck(strm))
602         return Z_STREAM_ERROR;
603     s = strm->state;
604 
605     if (level == Z_DEFAULT_COMPRESSION)
606         level = 6;
607     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED)
608         return Z_STREAM_ERROR;
609     DEFLATE_PARAMS_HOOK(strm, level, strategy, &hook_flush);  /* hook for IBM Z DFLTCC */
610     func = configuration_table[s->level].func;
611 
612     if (((strategy != s->strategy || func != configuration_table[level].func) && s->last_flush != -2)
613         || hook_flush != Z_NO_FLUSH) {
614         /* Flush the last buffer. Use Z_BLOCK mode, unless the hook requests a "stronger" one. */
615         int flush = RANK(hook_flush) > RANK(Z_BLOCK) ? hook_flush : Z_BLOCK;
616         int err = PREFIX(deflate)(strm, flush);
617         if (err == Z_STREAM_ERROR)
618             return err;
619         if (strm->avail_in || ((int)s->strstart - s->block_start) + s->lookahead || !DEFLATE_DONE(strm, flush))
620             return Z_BUF_ERROR;
621     }
622     if (s->level != level) {
623         if (s->level == 0 && s->matches != 0) {
624             if (s->matches == 1) {
625                 functable.slide_hash(s);
626             } else {
627                 CLEAR_HASH(s);
628             }
629             s->matches = 0;
630         }
631         s->level = level;
632         s->max_lazy_match   = configuration_table[level].max_lazy;
633         s->good_match       = configuration_table[level].good_length;
634         s->nice_match       = configuration_table[level].nice_length;
635         s->max_chain_length = configuration_table[level].max_chain;
636     }
637     s->strategy = strategy;
638     return Z_OK;
639 }
640 
641 /* ========================================================================= */
PREFIX(deflateTune)642 int32_t Z_EXPORT PREFIX(deflateTune)(PREFIX3(stream) *strm, int32_t good_length, int32_t max_lazy, int32_t nice_length, int32_t max_chain) {
643     deflate_state *s;
644 
645     if (deflateStateCheck(strm))
646         return Z_STREAM_ERROR;
647     s = strm->state;
648     s->good_match = (unsigned int)good_length;
649     s->max_lazy_match = (unsigned int)max_lazy;
650     s->nice_match = nice_length;
651     s->max_chain_length = (unsigned int)max_chain;
652     return Z_OK;
653 }
654 
655 /* =========================================================================
656  * For the default windowBits of 15 and memLevel of 8, this function returns
657  * a close to exact, as well as small, upper bound on the compressed size.
658  * They are coded as constants here for a reason--if the #define's are
659  * changed, then this function needs to be changed as well.  The return
660  * value for 15 and 8 only works for those exact settings.
661  *
662  * For any setting other than those defaults for windowBits and memLevel,
663  * the value returned is a conservative worst case for the maximum expansion
664  * resulting from using fixed blocks instead of stored blocks, which deflate
665  * can emit on compressed data for some combinations of the parameters.
666  *
667  * This function could be more sophisticated to provide closer upper bounds for
668  * every combination of windowBits and memLevel.  But even the conservative
669  * upper bound of about 14% expansion does not seem onerous for output buffer
670  * allocation.
671  */
PREFIX(deflateBound)672 unsigned long Z_EXPORT PREFIX(deflateBound)(PREFIX3(stream) *strm, unsigned long sourceLen) {
673     deflate_state *s;
674     unsigned long complen, wraplen;
675 
676     /* conservative upper bound for compressed data */
677     complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
678     DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen);  /* hook for IBM Z DFLTCC */
679 
680     /* if can't get parameters, return conservative bound plus zlib wrapper */
681     if (deflateStateCheck(strm))
682         return complen + 6;
683 
684     /* compute wrapper length */
685     s = strm->state;
686     switch (s->wrap) {
687     case 0:                                 /* raw deflate */
688         wraplen = 0;
689         break;
690     case 1:                                 /* zlib wrapper */
691         wraplen = 6 + (s->strstart ? 4 : 0);
692         break;
693 #ifdef GZIP
694     case 2:                                 /* gzip wrapper */
695         wraplen = 18;
696         if (s->gzhead != NULL) {            /* user-supplied gzip header */
697             unsigned char *str;
698             if (s->gzhead->extra != NULL) {
699                 wraplen += 2 + s->gzhead->extra_len;
700             }
701             str = s->gzhead->name;
702             if (str != NULL) {
703                 do {
704                     wraplen++;
705                 } while (*str++);
706             }
707             str = s->gzhead->comment;
708             if (str != NULL) {
709                 do {
710                     wraplen++;
711                 } while (*str++);
712             }
713             if (s->gzhead->hcrc)
714                 wraplen += 2;
715         }
716         break;
717 #endif
718     default:                                /* for compiler happiness */
719         wraplen = 6;
720     }
721 
722     /* if not default parameters, return conservative bound */
723     if (DEFLATE_NEED_CONSERVATIVE_BOUND(strm) ||  /* hook for IBM Z DFLTCC */
724             s->w_bits != 15 || HASH_BITS < 15)
725         return complen + wraplen;
726 
727     /* default settings: return tight bound for that case */
728     return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + (sourceLen >> 25) + 13 - 6 + wraplen;
729 }
730 
731 /* =========================================================================
732  * Flush as much pending output as possible. All deflate() output, except for
733  * some deflate_stored() output, goes through this function so some
734  * applications may wish to modify it to avoid allocating a large
735  * strm->next_out buffer and copying into it. (See also read_buf()).
736  */
flush_pending(PREFIX3 (stream)* strm)737 Z_INTERNAL void flush_pending(PREFIX3(stream) *strm) {
738     uint32_t len;
739     deflate_state *s = strm->state;
740 
741     zng_tr_flush_bits(s);
742     len = s->pending;
743     if (len > strm->avail_out)
744         len = strm->avail_out;
745     if (len == 0)
746         return;
747 
748     Tracev((stderr, "[FLUSH]"));
749     memcpy(strm->next_out, s->pending_out, len);
750     strm->next_out  += len;
751     s->pending_out  += len;
752     strm->total_out += len;
753     strm->avail_out -= len;
754     s->pending      -= len;
755     if (s->pending == 0)
756         s->pending_out = s->pending_buf;
757 }
758 
759 /* ===========================================================================
760  * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
761  */
762 #define HCRC_UPDATE(beg) \
763     do { \
764         if (s->gzhead->hcrc && s->pending > (beg)) \
765             strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf + (beg), s->pending - (beg)); \
766     } while (0)
767 
768 /* ========================================================================= */
PREFIX(deflate)769 int32_t Z_EXPORT PREFIX(deflate)(PREFIX3(stream) *strm, int32_t flush) {
770     int32_t old_flush; /* value of flush param for previous deflate call */
771     deflate_state *s;
772 
773     if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0)
774         return Z_STREAM_ERROR;
775     s = strm->state;
776 
777     if (strm->next_out == NULL || (strm->avail_in != 0 && strm->next_in == NULL)
778         || (s->status == FINISH_STATE && flush != Z_FINISH)) {
779         ERR_RETURN(strm, Z_STREAM_ERROR);
780     }
781     if (strm->avail_out == 0) {
782         ERR_RETURN(strm, Z_BUF_ERROR);
783     }
784 
785     old_flush = s->last_flush;
786     s->last_flush = flush;
787 
788     /* Flush as much pending output as possible */
789     if (s->pending != 0) {
790         flush_pending(strm);
791         if (strm->avail_out == 0) {
792             /* Since avail_out is 0, deflate will be called again with
793              * more output space, but possibly with both pending and
794              * avail_in equal to zero. There won't be anything to do,
795              * but this is not an error situation so make sure we
796              * return OK instead of BUF_ERROR at next call of deflate:
797              */
798             s->last_flush = -1;
799             return Z_OK;
800         }
801 
802         /* Make sure there is something to do and avoid duplicate consecutive
803          * flushes. For repeated and useless calls with Z_FINISH, we keep
804          * returning Z_STREAM_END instead of Z_BUF_ERROR.
805          */
806     } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) {
807         ERR_RETURN(strm, Z_BUF_ERROR);
808     }
809 
810     /* User must not provide more input after the first FINISH: */
811     if (s->status == FINISH_STATE && strm->avail_in != 0)   {
812         ERR_RETURN(strm, Z_BUF_ERROR);
813     }
814 
815     /* Write the header */
816     if (s->status == INIT_STATE && s->wrap == 0)
817         s->status = BUSY_STATE;
818     if (s->status == INIT_STATE) {
819         /* zlib header */
820         unsigned int header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
821         unsigned int level_flags;
822 
823         if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
824             level_flags = 0;
825         else if (s->level < 6)
826             level_flags = 1;
827         else if (s->level == 6)
828             level_flags = 2;
829         else
830             level_flags = 3;
831         header |= (level_flags << 6);
832         if (s->strstart != 0)
833             header |= PRESET_DICT;
834         header += 31 - (header % 31);
835 
836         put_short_msb(s, (uint16_t)header);
837 
838         /* Save the adler32 of the preset dictionary: */
839         if (s->strstart != 0)
840             put_uint32_msb(s, strm->adler);
841         strm->adler = ADLER32_INITIAL_VALUE;
842         s->status = BUSY_STATE;
843 
844         /* Compression must start with an empty pending buffer */
845         flush_pending(strm);
846         if (s->pending != 0) {
847             s->last_flush = -1;
848             return Z_OK;
849         }
850     }
851 #ifdef GZIP
852     if (s->status == GZIP_STATE) {
853         /* gzip header */
854         crc_reset(s);
855         put_byte(s, 31);
856         put_byte(s, 139);
857         put_byte(s, 8);
858         if (s->gzhead == NULL) {
859             put_uint32(s, 0);
860             put_byte(s, 0);
861             put_byte(s, s->level == 9 ? 2 :
862                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
863             put_byte(s, OS_CODE);
864             s->status = BUSY_STATE;
865 
866             /* Compression must start with an empty pending buffer */
867             flush_pending(strm);
868             if (s->pending != 0) {
869                 s->last_flush = -1;
870                 return Z_OK;
871             }
872         } else {
873             put_byte(s, (s->gzhead->text ? 1 : 0) +
874                      (s->gzhead->hcrc ? 2 : 0) +
875                      (s->gzhead->extra == NULL ? 0 : 4) +
876                      (s->gzhead->name == NULL ? 0 : 8) +
877                      (s->gzhead->comment == NULL ? 0 : 16)
878                      );
879             put_uint32(s, s->gzhead->time);
880             put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
881             put_byte(s, s->gzhead->os & 0xff);
882             if (s->gzhead->extra != NULL)
883                 put_short(s, (uint16_t)s->gzhead->extra_len);
884             if (s->gzhead->hcrc)
885                 strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf, s->pending);
886             s->gzindex = 0;
887             s->status = EXTRA_STATE;
888         }
889     }
890     if (s->status == EXTRA_STATE) {
891         if (s->gzhead->extra != NULL) {
892             uint32_t beg = s->pending;   /* start of bytes to update crc */
893             uint32_t left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
894 
895             while (s->pending + left > s->pending_buf_size) {
896                 uint32_t copy = s->pending_buf_size - s->pending;
897                 memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, copy);
898                 s->pending = s->pending_buf_size;
899                 HCRC_UPDATE(beg);
900                 s->gzindex += copy;
901                 flush_pending(strm);
902                 if (s->pending != 0) {
903                     s->last_flush = -1;
904                     return Z_OK;
905                 }
906                 beg = 0;
907                 left -= copy;
908             }
909             memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, left);
910             s->pending += left;
911             HCRC_UPDATE(beg);
912             s->gzindex = 0;
913         }
914         s->status = NAME_STATE;
915     }
916     if (s->status == NAME_STATE) {
917         if (s->gzhead->name != NULL) {
918             uint32_t beg = s->pending;   /* start of bytes to update crc */
919             unsigned char val;
920 
921             do {
922                 if (s->pending == s->pending_buf_size) {
923                     HCRC_UPDATE(beg);
924                     flush_pending(strm);
925                     if (s->pending != 0) {
926                         s->last_flush = -1;
927                         return Z_OK;
928                     }
929                     beg = 0;
930                 }
931                 val = s->gzhead->name[s->gzindex++];
932                 put_byte(s, val);
933             } while (val != 0);
934             HCRC_UPDATE(beg);
935             s->gzindex = 0;
936         }
937         s->status = COMMENT_STATE;
938     }
939     if (s->status == COMMENT_STATE) {
940         if (s->gzhead->comment != NULL) {
941             uint32_t beg = s->pending;  /* start of bytes to update crc */
942             unsigned char val;
943 
944             do {
945                 if (s->pending == s->pending_buf_size) {
946                     HCRC_UPDATE(beg);
947                     flush_pending(strm);
948                     if (s->pending != 0) {
949                         s->last_flush = -1;
950                         return Z_OK;
951                     }
952                     beg = 0;
953                 }
954                 val = s->gzhead->comment[s->gzindex++];
955                 put_byte(s, val);
956             } while (val != 0);
957             HCRC_UPDATE(beg);
958         }
959         s->status = HCRC_STATE;
960     }
961     if (s->status == HCRC_STATE) {
962         if (s->gzhead->hcrc) {
963             if (s->pending + 2 > s->pending_buf_size) {
964                 flush_pending(strm);
965                 if (s->pending != 0) {
966                     s->last_flush = -1;
967                     return Z_OK;
968                 }
969             }
970             put_short(s, (uint16_t)strm->adler);
971             crc_reset(s);
972         }
973         s->status = BUSY_STATE;
974 
975         /* Compression must start with an empty pending buffer */
976         flush_pending(strm);
977         if (s->pending != 0) {
978             s->last_flush = -1;
979             return Z_OK;
980         }
981     }
982 #endif
983 
984     /* Start a new block or continue the current one.
985      */
986     if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
987         block_state bstate;
988 
989         bstate = DEFLATE_HOOK(strm, flush, &bstate) ? bstate :  /* hook for IBM Z DFLTCC */
990                  s->level == 0 ? deflate_stored(s, flush) :
991                  s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
992                  s->strategy == Z_RLE ? deflate_rle(s, flush) :
993                  (*(configuration_table[s->level].func))(s, flush);
994 
995         if (bstate == finish_started || bstate == finish_done) {
996             s->status = FINISH_STATE;
997         }
998         if (bstate == need_more || bstate == finish_started) {
999             if (strm->avail_out == 0) {
1000                 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1001             }
1002             return Z_OK;
1003             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1004              * of deflate should use the same flush parameter to make sure
1005              * that the flush is complete. So we don't have to output an
1006              * empty block here, this will be done at next call. This also
1007              * ensures that for a very small output buffer, we emit at most
1008              * one empty block.
1009              */
1010         }
1011         if (bstate == block_done) {
1012             if (flush == Z_PARTIAL_FLUSH) {
1013                 zng_tr_align(s);
1014             } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
1015                 zng_tr_stored_block(s, (char*)0, 0L, 0);
1016                 /* For a full flush, this empty block will be recognized
1017                  * as a special marker by inflate_sync().
1018                  */
1019                 if (flush == Z_FULL_FLUSH) {
1020                     CLEAR_HASH(s);             /* forget history */
1021                     if (s->lookahead == 0) {
1022                         s->strstart = 0;
1023                         s->block_start = 0;
1024                         s->insert = 0;
1025                     }
1026                 }
1027             }
1028             flush_pending(strm);
1029             if (strm->avail_out == 0) {
1030                 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1031                 return Z_OK;
1032             }
1033         }
1034     }
1035 
1036     if (flush != Z_FINISH)
1037         return Z_OK;
1038 
1039     /* Write the trailer */
1040 #ifdef GZIP
1041     if (s->wrap == 2) {
1042 #  ifdef X86_PCLMULQDQ_CRC
1043         crc_finalize(s);
1044 #  endif
1045         put_uint32(s, strm->adler);
1046         put_uint32(s, (uint32_t)strm->total_in);
1047     } else
1048 #endif
1049     if (s->wrap == 1)
1050         put_uint32_msb(s, strm->adler);
1051     flush_pending(strm);
1052     /* If avail_out is zero, the application will call deflate again
1053      * to flush the rest.
1054      */
1055     if (s->wrap > 0)
1056         s->wrap = -s->wrap; /* write the trailer only once! */
1057     if (s->pending == 0) {
1058         Assert(s->bi_valid == 0, "bi_buf not flushed");
1059         return Z_STREAM_END;
1060     }
1061     return Z_OK;
1062 }
1063 
1064 /* ========================================================================= */
PREFIX(deflateEnd)1065 int32_t Z_EXPORT PREFIX(deflateEnd)(PREFIX3(stream) *strm) {
1066     int32_t status;
1067 
1068     if (deflateStateCheck(strm))
1069         return Z_STREAM_ERROR;
1070 
1071     status = strm->state->status;
1072 
1073     /* Deallocate in reverse order of allocations: */
1074     TRY_FREE(strm, strm->state->pending_buf);
1075     TRY_FREE(strm, strm->state->head);
1076     TRY_FREE(strm, strm->state->prev);
1077     TRY_FREE_WINDOW(strm, strm->state->window);
1078 
1079     ZFREE_STATE(strm, strm->state);
1080     strm->state = NULL;
1081 
1082     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1083 }
1084 
1085 /* =========================================================================
1086  * Copy the source state to the destination state.
1087  */
PREFIX(deflateCopy)1088 int32_t Z_EXPORT PREFIX(deflateCopy)(PREFIX3(stream) *dest, PREFIX3(stream) *source) {
1089     deflate_state *ds;
1090     deflate_state *ss;
1091     uint32_t window_padding = 0;
1092 
1093     if (deflateStateCheck(source) || dest == NULL)
1094         return Z_STREAM_ERROR;
1095 
1096     ss = source->state;
1097 
1098     memcpy((void *)dest, (void *)source, sizeof(PREFIX3(stream)));
1099 
1100     ds = (deflate_state *) ZALLOC_STATE(dest, 1, sizeof(deflate_state));
1101     if (ds == NULL)
1102         return Z_MEM_ERROR;
1103     dest->state = (struct internal_state *) ds;
1104     ZCOPY_STATE((void *)ds, (void *)ss, sizeof(deflate_state));
1105     ds->strm = dest;
1106 
1107 #ifdef X86_PCLMULQDQ_CRC
1108     window_padding = 8;
1109 #endif
1110 
1111     ds->window = (unsigned char *) ZALLOC_WINDOW(dest, ds->w_size + window_padding, 2*sizeof(unsigned char));
1112     ds->prev   = (Pos *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
1113     ds->head   = (Pos *)  ZALLOC(dest, HASH_SIZE, sizeof(Pos));
1114     ds->pending_buf = (unsigned char *) ZALLOC(dest, ds->lit_bufsize, 4);
1115 
1116     if (ds->window == NULL || ds->prev == NULL || ds->head == NULL || ds->pending_buf == NULL) {
1117         PREFIX(deflateEnd)(dest);
1118         return Z_MEM_ERROR;
1119     }
1120 
1121     memcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(unsigned char));
1122     memcpy((void *)ds->prev, (void *)ss->prev, ds->w_size * sizeof(Pos));
1123     memcpy((void *)ds->head, (void *)ss->head, HASH_SIZE * sizeof(Pos));
1124     memcpy(ds->pending_buf, ss->pending_buf, ds->pending_buf_size);
1125 
1126     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1127     ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1128 
1129     ds->l_desc.dyn_tree = ds->dyn_ltree;
1130     ds->d_desc.dyn_tree = ds->dyn_dtree;
1131     ds->bl_desc.dyn_tree = ds->bl_tree;
1132 
1133     return Z_OK;
1134 }
1135 
1136 /* ===========================================================================
1137  * Read a new buffer from the current input stream, update the adler32
1138  * and total number of bytes read.  All deflate() input goes through
1139  * this function so some applications may wish to modify it to avoid
1140  * allocating a large strm->next_in buffer and copying from it.
1141  * (See also flush_pending()).
1142  */
read_buf(PREFIX3 (stream)* strm,unsigned char * buf,unsigned size)1143 Z_INTERNAL unsigned read_buf(PREFIX3(stream) *strm, unsigned char *buf, unsigned size) {
1144     uint32_t len = strm->avail_in;
1145 
1146     if (len > size)
1147         len = size;
1148     if (len == 0)
1149         return 0;
1150 
1151     strm->avail_in  -= len;
1152 
1153     if (!DEFLATE_NEED_CHECKSUM(strm)) {
1154         memcpy(buf, strm->next_in, len);
1155 #ifdef GZIP
1156     } else if (strm->state->wrap == 2) {
1157         copy_with_crc(strm, buf, len);
1158 #endif
1159     } else {
1160         memcpy(buf, strm->next_in, len);
1161         if (strm->state->wrap == 1)
1162             strm->adler = functable.adler32(strm->adler, buf, len);
1163     }
1164     strm->next_in  += len;
1165     strm->total_in += len;
1166 
1167     return len;
1168 }
1169 
1170 /* ===========================================================================
1171  * Initialize the "longest match" routines for a new zlib stream
1172  */
lm_init(deflate_state * s)1173 static void lm_init(deflate_state *s) {
1174     s->window_size = 2 * s->w_size;
1175 
1176     CLEAR_HASH(s);
1177 
1178     /* Set the default configuration parameters:
1179      */
1180     s->max_lazy_match   = configuration_table[s->level].max_lazy;
1181     s->good_match       = configuration_table[s->level].good_length;
1182     s->nice_match       = configuration_table[s->level].nice_length;
1183     s->max_chain_length = configuration_table[s->level].max_chain;
1184 
1185     s->strstart = 0;
1186     s->block_start = 0;
1187     s->lookahead = 0;
1188     s->insert = 0;
1189     s->prev_length = MIN_MATCH-1;
1190     s->match_available = 0;
1191     s->match_start = 0;
1192 }
1193 
1194 #ifdef ZLIB_DEBUG
1195 #define EQUAL 0
1196 /* result of memcmp for equal strings */
1197 
1198 /* ===========================================================================
1199  * Check that the match at match_start is indeed a match.
1200  */
check_match(deflate_state * s,Pos start,Pos match,int length)1201 void check_match(deflate_state *s, Pos start, Pos match, int length) {
1202     /* check that the match length is valid*/
1203     if (length < MIN_MATCH || length > MAX_MATCH) {
1204         fprintf(stderr, " start %u, match %u, length %d\n", start, match, length);
1205         z_error("invalid match length");
1206     }
1207     /* check that the match is indeed a match */
1208     if (memcmp(s->window + match, s->window + start, length) != EQUAL) {
1209         fprintf(stderr, " start %u, match %u, length %d\n", start, match, length);
1210         do {
1211             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1212         } while (--length != 0);
1213         z_error("invalid match");
1214     }
1215     if (z_verbose > 1) {
1216         fprintf(stderr, "\\[%u,%d]", start-match, length);
1217         do {
1218             putc(s->window[start++], stderr);
1219         } while (--length != 0);
1220     }
1221 }
1222 #else
1223 #  define check_match(s, start, match, length)
1224 #endif /* ZLIB_DEBUG */
1225 
1226 /* ===========================================================================
1227  * Fill the window when the lookahead becomes insufficient.
1228  * Updates strstart and lookahead.
1229  *
1230  * IN assertion: lookahead < MIN_LOOKAHEAD
1231  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1232  *    At least one byte has been read, or avail_in == 0; reads are
1233  *    performed for at least two bytes (required for the zip translate_eol
1234  *    option -- not supported here).
1235  */
1236 
fill_window(deflate_state * s)1237 void Z_INTERNAL fill_window(deflate_state *s) {
1238     unsigned n;
1239     unsigned int more;    /* Amount of free space at the end of the window. */
1240     unsigned int wsize = s->w_size;
1241 
1242     Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1243 
1244     do {
1245         more = s->window_size - s->lookahead - s->strstart;
1246 
1247         /* If the window is almost full and there is insufficient lookahead,
1248          * move the upper half to the lower one to make room in the upper half.
1249          */
1250         if (s->strstart >= wsize+MAX_DIST(s)) {
1251             memcpy(s->window, s->window+wsize, (unsigned)wsize);
1252             s->match_start = (s->match_start >= wsize) ? s->match_start - wsize : 0;
1253             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
1254             s->block_start -= (int)wsize;
1255             if (s->insert > s->strstart)
1256                 s->insert = s->strstart;
1257             functable.slide_hash(s);
1258             more += wsize;
1259         }
1260         if (s->strm->avail_in == 0)
1261             break;
1262 
1263         /* If there was no sliding:
1264          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1265          *    more == window_size - lookahead - strstart
1266          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1267          * => more >= window_size - 2*WSIZE + 2
1268          * In the BIG_MEM or MMAP case (not yet supported),
1269          *   window_size == input_size + MIN_LOOKAHEAD  &&
1270          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1271          * Otherwise, window_size == 2*WSIZE so more >= 2.
1272          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1273          */
1274         Assert(more >= 2, "more < 2");
1275 
1276         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1277         s->lookahead += n;
1278 
1279         /* Initialize the hash value now that we have some input: */
1280         if (s->lookahead + s->insert >= MIN_MATCH) {
1281             unsigned int str = s->strstart - s->insert;
1282             if (str >= 1)
1283                 functable.quick_insert_string(s, str + 2 - MIN_MATCH);
1284 #if MIN_MATCH != 3
1285 #error Call insert_string() MIN_MATCH-3 more times
1286             while (s->insert) {
1287                 functable.quick_insert_string(s, str);
1288                 str++;
1289                 s->insert--;
1290                 if (s->lookahead + s->insert < MIN_MATCH)
1291                     break;
1292             }
1293 #else
1294             unsigned int count;
1295             if (UNLIKELY(s->lookahead == 1)) {
1296                 count = s->insert - 1;
1297             } else {
1298                 count = s->insert;
1299             }
1300             if (count > 0) {
1301                 functable.insert_string(s, str, count);
1302                 s->insert -= count;
1303             }
1304 #endif
1305         }
1306         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1307          * but this is not important since only literal bytes will be emitted.
1308          */
1309     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1310 
1311     /* If the WIN_INIT bytes after the end of the current data have never been
1312      * written, then zero those bytes in order to avoid memory check reports of
1313      * the use of uninitialized (or uninitialised as Julian writes) bytes by
1314      * the longest match routines.  Update the high water mark for the next
1315      * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1316      * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1317      */
1318     if (s->high_water < s->window_size) {
1319         unsigned int curr = s->strstart + s->lookahead;
1320         unsigned int init;
1321 
1322         if (s->high_water < curr) {
1323             /* Previous high water mark below current data -- zero WIN_INIT
1324              * bytes or up to end of window, whichever is less.
1325              */
1326             init = s->window_size - curr;
1327             if (init > WIN_INIT)
1328                 init = WIN_INIT;
1329             memset(s->window + curr, 0, init);
1330             s->high_water = curr + init;
1331         } else if (s->high_water < curr + WIN_INIT) {
1332             /* High water mark at or above current data, but below current data
1333              * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1334              * to end of window, whichever is less.
1335              */
1336             init = curr + WIN_INIT - s->high_water;
1337             if (init > s->window_size - s->high_water)
1338                 init = s->window_size - s->high_water;
1339             memset(s->window + s->high_water, 0, init);
1340             s->high_water += init;
1341         }
1342     }
1343 
1344     Assert((unsigned long)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1345            "not enough room for search");
1346 }
1347 
1348 /* ===========================================================================
1349  * Copy without compression as much as possible from the input stream, return
1350  * the current block state.
1351  *
1352  * In case deflateParams() is used to later switch to a non-zero compression
1353  * level, s->matches (otherwise unused when storing) keeps track of the number
1354  * of hash table slides to perform. If s->matches is 1, then one hash table
1355  * slide will be done when switching. If s->matches is 2, the maximum value
1356  * allowed here, then the hash table will be cleared, since two or more slides
1357  * is the same as a clear.
1358  *
1359  * deflate_stored() is written to minimize the number of times an input byte is
1360  * copied. It is most efficient with large input and output buffers, which
1361  * maximizes the opportunites to have a single copy from next_in to next_out.
1362  */
deflate_stored(deflate_state * s,int flush)1363 static block_state deflate_stored(deflate_state *s, int flush) {
1364     /* Smallest worthy block size when not flushing or finishing. By default
1365      * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1366      * large input and output buffers, the stored block size will be larger.
1367      */
1368     unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1369 
1370     /* Copy as many min_block or larger stored blocks directly to next_out as
1371      * possible. If flushing, copy the remaining available input to next_out as
1372      * stored blocks, if there is enough space.
1373      */
1374     unsigned len, left, have, last = 0;
1375     unsigned used = s->strm->avail_in;
1376     do {
1377         /* Set len to the maximum size block that we can copy directly with the
1378          * available input data and output space. Set left to how much of that
1379          * would be copied from what's left in the window.
1380          */
1381         len = MAX_STORED;       /* maximum deflate stored block length */
1382         have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1383         if (s->strm->avail_out < have)          /* need room for header */
1384             break;
1385             /* maximum stored block length that will fit in avail_out: */
1386         have = s->strm->avail_out - have;
1387         left = (int)s->strstart - s->block_start;    /* bytes left in window */
1388         if (len > (unsigned long)left + s->strm->avail_in)
1389             len = left + s->strm->avail_in;     /* limit len to the input */
1390         if (len > have)
1391             len = have;                         /* limit len to the output */
1392 
1393         /* If the stored block would be less than min_block in length, or if
1394          * unable to copy all of the available input when flushing, then try
1395          * copying to the window and the pending buffer instead. Also don't
1396          * write an empty block when flushing -- deflate() does that.
1397          */
1398         if (len < min_block && ((len == 0 && flush != Z_FINISH) || flush == Z_NO_FLUSH || len != left + s->strm->avail_in))
1399             break;
1400 
1401         /* Make a dummy stored block in pending to get the header bytes,
1402          * including any pending bits. This also updates the debugging counts.
1403          */
1404         last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
1405         zng_tr_stored_block(s, (char *)0, 0L, last);
1406 
1407         /* Replace the lengths in the dummy stored block with len. */
1408         s->pending -= 4;
1409         put_short(s, (uint16_t)len);
1410         put_short(s, (uint16_t)~len);
1411 
1412         /* Write the stored block header bytes. */
1413         flush_pending(s->strm);
1414 
1415         /* Update debugging counts for the data about to be copied. */
1416         cmpr_bits_add(s, len << 3);
1417         sent_bits_add(s, len << 3);
1418 
1419         /* Copy uncompressed bytes from the window to next_out. */
1420         if (left) {
1421             if (left > len)
1422                 left = len;
1423             memcpy(s->strm->next_out, s->window + s->block_start, left);
1424             s->strm->next_out += left;
1425             s->strm->avail_out -= left;
1426             s->strm->total_out += left;
1427             s->block_start += (int)left;
1428             len -= left;
1429         }
1430 
1431         /* Copy uncompressed bytes directly from next_in to next_out, updating
1432          * the check value.
1433          */
1434         if (len) {
1435             read_buf(s->strm, s->strm->next_out, len);
1436             s->strm->next_out += len;
1437             s->strm->avail_out -= len;
1438             s->strm->total_out += len;
1439         }
1440     } while (last == 0);
1441 
1442     /* Update the sliding window with the last s->w_size bytes of the copied
1443      * data, or append all of the copied data to the existing window if less
1444      * than s->w_size bytes were copied. Also update the number of bytes to
1445      * insert in the hash tables, in the event that deflateParams() switches to
1446      * a non-zero compression level.
1447      */
1448     used -= s->strm->avail_in;      /* number of input bytes directly copied */
1449     if (used) {
1450         /* If any input was used, then no unused input remains in the window,
1451          * therefore s->block_start == s->strstart.
1452          */
1453         if (used >= s->w_size) {    /* supplant the previous history */
1454             s->matches = 2;         /* clear hash */
1455             memcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1456             s->strstart = s->w_size;
1457             s->insert = s->strstart;
1458         } else {
1459             if (s->window_size - s->strstart <= used) {
1460                 /* Slide the window down. */
1461                 s->strstart -= s->w_size;
1462                 memcpy(s->window, s->window + s->w_size, s->strstart);
1463                 if (s->matches < 2)
1464                     s->matches++;   /* add a pending slide_hash() */
1465                 if (s->insert > s->strstart)
1466                     s->insert = s->strstart;
1467             }
1468             memcpy(s->window + s->strstart, s->strm->next_in - used, used);
1469             s->strstart += used;
1470             s->insert += MIN(used, s->w_size - s->insert);
1471         }
1472         s->block_start = (int)s->strstart;
1473     }
1474     if (s->high_water < s->strstart)
1475         s->high_water = s->strstart;
1476 
1477     /* If the last block was written to next_out, then done. */
1478     if (last)
1479         return finish_done;
1480 
1481     /* If flushing and all input has been consumed, then done. */
1482     if (flush != Z_NO_FLUSH && flush != Z_FINISH && s->strm->avail_in == 0 && (int)s->strstart == s->block_start)
1483         return block_done;
1484 
1485     /* Fill the window with any remaining input. */
1486     have = s->window_size - s->strstart;
1487     if (s->strm->avail_in > have && s->block_start >= (int)s->w_size) {
1488         /* Slide the window down. */
1489         s->block_start -= (int)s->w_size;
1490         s->strstart -= s->w_size;
1491         memcpy(s->window, s->window + s->w_size, s->strstart);
1492         if (s->matches < 2)
1493             s->matches++;           /* add a pending slide_hash() */
1494         have += s->w_size;          /* more space now */
1495         if (s->insert > s->strstart)
1496             s->insert = s->strstart;
1497     }
1498     if (have > s->strm->avail_in)
1499         have = s->strm->avail_in;
1500     if (have) {
1501         read_buf(s->strm, s->window + s->strstart, have);
1502         s->strstart += have;
1503         s->insert += MIN(have, s->w_size - s->insert);
1504     }
1505     if (s->high_water < s->strstart)
1506         s->high_water = s->strstart;
1507 
1508     /* There was not enough avail_out to write a complete worthy or flushed
1509      * stored block to next_out. Write a stored block to pending instead, if we
1510      * have enough input for a worthy block, or if flushing and there is enough
1511      * room for the remaining input as a stored block in the pending buffer.
1512      */
1513     have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1514         /* maximum stored block length that will fit in pending: */
1515     have = MIN(s->pending_buf_size - have, MAX_STORED);
1516     min_block = MIN(have, s->w_size);
1517     left = (int)s->strstart - s->block_start;
1518     if (left >= min_block || ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH && s->strm->avail_in == 0 && left <= have)) {
1519         len = MIN(left, have);
1520         last = flush == Z_FINISH && s->strm->avail_in == 0 && len == left ? 1 : 0;
1521         zng_tr_stored_block(s, (char *)s->window + s->block_start, len, last);
1522         s->block_start += (int)len;
1523         flush_pending(s->strm);
1524     }
1525 
1526     /* We've done all we can with the available input and output. */
1527     return last ? finish_started : need_more;
1528 }
1529 
1530 
1531 /* ===========================================================================
1532  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1533  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
1534  * deflate switches away from Z_RLE.)
1535  */
deflate_rle(deflate_state * s,int flush)1536 static block_state deflate_rle(deflate_state *s, int flush) {
1537     int bflush = 0;                 /* set if current block must be flushed */
1538     unsigned int prev;              /* byte at distance one to match */
1539     unsigned char *scan, *strend;   /* scan goes up to strend for length of run */
1540     uint32_t match_len = 0;
1541 
1542     for (;;) {
1543         /* Make sure that we always have enough lookahead, except
1544          * at the end of the input file. We need MAX_MATCH bytes
1545          * for the longest run, plus one for the unrolled loop.
1546          */
1547         if (s->lookahead <= MAX_MATCH) {
1548             fill_window(s);
1549             if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH)
1550                 return need_more;
1551             if (s->lookahead == 0)
1552                 break; /* flush the current block */
1553         }
1554 
1555         /* See how many times the previous byte repeats */
1556         if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
1557             scan = s->window + s->strstart - 1;
1558             prev = *scan;
1559             if (prev == *++scan && prev == *++scan && prev == *++scan) {
1560                 strend = s->window + s->strstart + MAX_MATCH;
1561                 do {
1562                 } while (prev == *++scan && prev == *++scan &&
1563                          prev == *++scan && prev == *++scan &&
1564                          prev == *++scan && prev == *++scan &&
1565                          prev == *++scan && prev == *++scan &&
1566                          scan < strend);
1567                 match_len = MAX_MATCH - (unsigned int)(strend - scan);
1568                 if (match_len > s->lookahead)
1569                     match_len = s->lookahead;
1570             }
1571             Assert(scan <= s->window + s->window_size - 1, "wild scan");
1572         }
1573 
1574         /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1575         if (match_len >= MIN_MATCH) {
1576             check_match(s, s->strstart, s->strstart - 1, match_len);
1577 
1578             bflush = zng_tr_tally_dist(s, 1, match_len - MIN_MATCH);
1579 
1580             s->lookahead -= match_len;
1581             s->strstart += match_len;
1582             match_len = 0;
1583         } else {
1584             /* No match, output a literal byte */
1585             bflush = zng_tr_tally_lit(s, s->window[s->strstart]);
1586             s->lookahead--;
1587             s->strstart++;
1588         }
1589         if (bflush)
1590             FLUSH_BLOCK(s, 0);
1591     }
1592     s->insert = 0;
1593     if (flush == Z_FINISH) {
1594         FLUSH_BLOCK(s, 1);
1595         return finish_done;
1596     }
1597     if (s->sym_next)
1598         FLUSH_BLOCK(s, 0);
1599     return block_done;
1600 }
1601 
1602 /* ===========================================================================
1603  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
1604  * (It will be regenerated if this run of deflate switches away from Huffman.)
1605  */
deflate_huff(deflate_state * s,int flush)1606 static block_state deflate_huff(deflate_state *s, int flush) {
1607     int bflush = 0;         /* set if current block must be flushed */
1608 
1609     for (;;) {
1610         /* Make sure that we have a literal to write. */
1611         if (s->lookahead == 0) {
1612             fill_window(s);
1613             if (s->lookahead == 0) {
1614                 if (flush == Z_NO_FLUSH)
1615                     return need_more;
1616                 break;      /* flush the current block */
1617             }
1618         }
1619 
1620         /* Output a literal byte */
1621         bflush = zng_tr_tally_lit(s, s->window[s->strstart]);
1622         s->lookahead--;
1623         s->strstart++;
1624         if (bflush)
1625             FLUSH_BLOCK(s, 0);
1626     }
1627     s->insert = 0;
1628     if (flush == Z_FINISH) {
1629         FLUSH_BLOCK(s, 1);
1630         return finish_done;
1631     }
1632     if (s->sym_next)
1633         FLUSH_BLOCK(s, 0);
1634     return block_done;
1635 }
1636 
1637 #ifndef ZLIB_COMPAT
1638 /* =========================================================================
1639  * Checks whether buffer size is sufficient and whether this parameter is a duplicate.
1640  */
deflateSetParamPre(zng_deflate_param_value ** out,size_t min_size,zng_deflate_param_value * param)1641 static int32_t deflateSetParamPre(zng_deflate_param_value **out, size_t min_size, zng_deflate_param_value *param) {
1642     int32_t buf_error = param->size < min_size;
1643 
1644     if (*out != NULL) {
1645         (*out)->status = Z_BUF_ERROR;
1646         buf_error = 1;
1647     }
1648     *out = param;
1649     return buf_error;
1650 }
1651 
1652 /* ========================================================================= */
zng_deflateSetParams(zng_stream * strm,zng_deflate_param_value * params,size_t count)1653 int32_t Z_EXPORT zng_deflateSetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
1654     size_t i;
1655     deflate_state *s;
1656     zng_deflate_param_value *new_level = NULL;
1657     zng_deflate_param_value *new_strategy = NULL;
1658     zng_deflate_param_value *new_reproducible = NULL;
1659     int param_buf_error;
1660     int version_error = 0;
1661     int buf_error = 0;
1662     int stream_error = 0;
1663     int ret;
1664     int val;
1665 
1666     /* Initialize the statuses. */
1667     for (i = 0; i < count; i++)
1668         params[i].status = Z_OK;
1669 
1670     /* Check whether the stream state is consistent. */
1671     if (deflateStateCheck(strm))
1672         return Z_STREAM_ERROR;
1673     s = strm->state;
1674 
1675     /* Check buffer sizes and detect duplicates. */
1676     for (i = 0; i < count; i++) {
1677         switch (params[i].param) {
1678             case Z_DEFLATE_LEVEL:
1679                 param_buf_error = deflateSetParamPre(&new_level, sizeof(int), &params[i]);
1680                 break;
1681             case Z_DEFLATE_STRATEGY:
1682                 param_buf_error = deflateSetParamPre(&new_strategy, sizeof(int), &params[i]);
1683                 break;
1684             case Z_DEFLATE_REPRODUCIBLE:
1685                 param_buf_error = deflateSetParamPre(&new_reproducible, sizeof(int), &params[i]);
1686                 break;
1687             default:
1688                 params[i].status = Z_VERSION_ERROR;
1689                 version_error = 1;
1690                 param_buf_error = 0;
1691                 break;
1692         }
1693         if (param_buf_error) {
1694             params[i].status = Z_BUF_ERROR;
1695             buf_error = 1;
1696         }
1697     }
1698     /* Exit early if small buffers or duplicates are detected. */
1699     if (buf_error)
1700         return Z_BUF_ERROR;
1701 
1702     /* Apply changes, remember if there were errors. */
1703     if (new_level != NULL || new_strategy != NULL) {
1704         ret = PREFIX(deflateParams)(strm, new_level == NULL ? s->level : *(int *)new_level->buf,
1705                                     new_strategy == NULL ? s->strategy : *(int *)new_strategy->buf);
1706         if (ret != Z_OK) {
1707             if (new_level != NULL)
1708                 new_level->status = Z_STREAM_ERROR;
1709             if (new_strategy != NULL)
1710                 new_strategy->status = Z_STREAM_ERROR;
1711             stream_error = 1;
1712         }
1713     }
1714     if (new_reproducible != NULL) {
1715         val = *(int *)new_reproducible->buf;
1716         if (DEFLATE_CAN_SET_REPRODUCIBLE(strm, val)) {
1717             s->reproducible = val;
1718         } else {
1719             new_reproducible->status = Z_STREAM_ERROR;
1720             stream_error = 1;
1721         }
1722     }
1723 
1724     /* Report version errors only if there are no real errors. */
1725     return stream_error ? Z_STREAM_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
1726 }
1727 
1728 /* ========================================================================= */
zng_deflateGetParams(zng_stream * strm,zng_deflate_param_value * params,size_t count)1729 int32_t Z_EXPORT zng_deflateGetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
1730     deflate_state *s;
1731     size_t i;
1732     int32_t buf_error = 0;
1733     int32_t version_error = 0;
1734 
1735     /* Initialize the statuses. */
1736     for (i = 0; i < count; i++)
1737         params[i].status = Z_OK;
1738 
1739     /* Check whether the stream state is consistent. */
1740     if (deflateStateCheck(strm))
1741         return Z_STREAM_ERROR;
1742     s = strm->state;
1743 
1744     for (i = 0; i < count; i++) {
1745         switch (params[i].param) {
1746             case Z_DEFLATE_LEVEL:
1747                 if (params[i].size < sizeof(int))
1748                     params[i].status = Z_BUF_ERROR;
1749                 else
1750                     *(int *)params[i].buf = s->level;
1751                 break;
1752             case Z_DEFLATE_STRATEGY:
1753                 if (params[i].size < sizeof(int))
1754                     params[i].status = Z_BUF_ERROR;
1755                 else
1756                     *(int *)params[i].buf = s->strategy;
1757                 break;
1758             case Z_DEFLATE_REPRODUCIBLE:
1759                 if (params[i].size < sizeof(int))
1760                     params[i].status = Z_BUF_ERROR;
1761                 else
1762                     *(int *)params[i].buf = s->reproducible;
1763                 break;
1764             default:
1765                 params[i].status = Z_VERSION_ERROR;
1766                 version_error = 1;
1767                 break;
1768         }
1769         if (params[i].status == Z_BUF_ERROR)
1770             buf_error = 1;
1771     }
1772     return buf_error ? Z_BUF_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
1773 }
1774 #endif
1775