Debian Codegraph @

ext/zlib-ng/deflate.c

raw symbols SCIP
1 /* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2022 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 https://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 "cpu_features.h"
52 #include "deflate.h"
53 #include "deflate_p.h"
54 #include "functable.h"
55
56 /* Avoid conflicts with zlib.h macros */
57 #ifdef ZLIB_COMPAT
58 # undef deflateInit
59 # undef deflateInit2
60 #endif
61
62 const char PREFIX(deflate_copyright)[] = " deflate 1.2.12 Copyright 1995-2022 Jean-loup Gailly and Mark Adler ";
63 /*
64 If you use the zlib library in a product, an acknowledgment is welcome
65 in the documentation of your product. If for some reason you cannot
66 include such an acknowledgment, I would appreciate that you keep this
67 copyright string in the executable of your product.
68 */
69
70 /* ===========================================================================
71 * Architecture-specific hooks.
72 */
73 #ifdef S390_DFLTCC_DEFLATE
74 # include "arch/s390/dfltcc_deflate.h"
75 #else
76 /* Memory management for the deflate state. Useful for allocating arch-specific extension blocks. */
77 # define ZALLOC_DEFLATE_STATE(strm) ((deflate_state *)ZALLOC(strm, 1, sizeof(deflate_state)))
78 # define ZFREE_STATE(strm, addr) ZFREE(strm, addr)
79 # define ZCOPY_DEFLATE_STATE(dst, src) memcpy(dst, src, sizeof(deflate_state))
80 /* Memory management for the window. Useful for allocation the aligned window. */
81 # define ZALLOC_WINDOW(strm, items, size) ZALLOC(strm, items, size)
82 # define TRY_FREE_WINDOW(strm, addr) TRY_FREE(strm, addr)
83 /* Invoked at the beginning of deflateSetDictionary(). Useful for checking arch-specific window data. */
84 # define DEFLATE_SET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
85 /* Invoked at the beginning of deflateGetDictionary(). Useful for adjusting arch-specific window data. */
86 # define DEFLATE_GET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
87 /* Invoked at the end of deflateResetKeep(). Useful for initializing arch-specific extension blocks. */
88 # define DEFLATE_RESET_KEEP_HOOK(strm) do {} while (0)
89 /* Invoked at the beginning of deflateParams(). Useful for updating arch-specific compression parameters. */
90 # define DEFLATE_PARAMS_HOOK(strm, level, strategy, hook_flush) do {} while (0)
91 /* Returns whether the last deflate(flush) operation did everything it's supposed to do. */
92 # define DEFLATE_DONE(strm, flush) 1
93 /* Adjusts the upper bound on compressed data length based on compression parameters and uncompressed data length.
94 * Useful when arch-specific deflation code behaves differently than regular zlib-ng algorithms. */
95 # define DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen) do {} while (0)
96 /* Returns whether an optimistic upper bound on compressed data length should *not* be used.
97 * Useful when arch-specific deflation code behaves differently than regular zlib-ng algorithms. */
98 # define DEFLATE_NEED_CONSERVATIVE_BOUND(strm) 0
99 /* Invoked for each deflate() call. Useful for plugging arch-specific deflation code. */
100 # define DEFLATE_HOOK(strm, flush, bstate) 0
101 /* Returns whether zlib-ng should compute a checksum. Set to 0 if arch-specific deflation code already does that. */
102 # define DEFLATE_NEED_CHECKSUM(strm) 1
103 /* Returns whether reproducibility parameter can be set to a given value. */
104 # define DEFLATE_CAN_SET_REPRODUCIBLE(strm, reproducible) 1
105 #endif
106
107 /* ===========================================================================
108 * Function prototypes.
109 */
110 static int deflateStateCheck (PREFIX3(stream) *strm);
111 Z_INTERNAL block_state deflate_stored(deflate_state *s, int flush);
112 Z_INTERNAL block_state deflate_fast (deflate_state *s, int flush);
113 Z_INTERNAL block_state deflate_quick (deflate_state *s, int flush);
114 #ifndef NO_MEDIUM_STRATEGY
115 Z_INTERNAL block_state deflate_medium(deflate_state *s, int flush);
116 #endif
117 Z_INTERNAL block_state deflate_slow (deflate_state *s, int flush);
118 Z_INTERNAL block_state deflate_rle (deflate_state *s, int flush);
119 Z_INTERNAL block_state deflate_huff (deflate_state *s, int flush);
120 static void lm_set_level (deflate_state *s, int level);
121 static void lm_init (deflate_state *s);
122 Z_INTERNAL unsigned read_buf (PREFIX3(stream) *strm, unsigned char *buf, unsigned size);
123
124 extern uint32_t update_hash_roll (deflate_state *const s, uint32_t h, uint32_t val);
125 extern void insert_string_roll (deflate_state *const s, uint32_t str, uint32_t count);
126 extern Pos quick_insert_string_roll(deflate_state *const s, uint32_t str);
127
128 /* ===========================================================================
129 * Local data
130 */
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 #ifdef NO_QUICK_STRATEGY
150 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
151 /* 2 */ {4, 5, 16, 8, deflate_fast},
152 #else
153 /* 1 */ {0, 0, 0, 0, deflate_quick},
154 /* 2 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
155 #endif
156
157 #ifdef NO_MEDIUM_STRATEGY
158 /* 3 */ {4, 6, 32, 32, deflate_fast},
159 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
160 /* 5 */ {8, 16, 32, 32, deflate_slow},
161 /* 6 */ {8, 16, 128, 128, deflate_slow},
162 #else
163 /* 3 */ {4, 6, 16, 6, deflate_medium},
164 /* 4 */ {4, 12, 32, 24, 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 >= STD_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 /* This function is hidden in ZLIB_COMPAT builds. */
191 int32_t ZNG_CONDEXPORT PREFIX(deflateInit2)(PREFIX3(stream) *strm, int32_t level, int32_t method, int32_t windowBits,
192 int32_t memLevel, int32_t strategy) {
193 /* Todo: ignore strm->next_in if we use it as window */
194 uint32_t window_padding = 0;
195 deflate_state *s;
196 int wrap = 1;
197
198 cpu_check_features();
199
200 if (strm == NULL)
201 return Z_STREAM_ERROR;
202
203 strm->msg = NULL;
204 if (strm->zalloc == NULL) {
205 strm->zalloc = zng_calloc;
206 strm->opaque = NULL;
207 }
208 if (strm->zfree == NULL)
209 strm->zfree = zng_cfree;
210
211 if (level == Z_DEFAULT_COMPRESSION)
212 level = 6;
213
214 if (windowBits < 0) { /* suppress zlib wrapper */
215 wrap = 0;
216 if (windowBits < -15)
217 return Z_STREAM_ERROR;
218 windowBits = -windowBits;
219 #ifdef GZIP
220 } else if (windowBits > 15) {
221 wrap = 2; /* write gzip wrapper instead */
222 windowBits -= 16;
223 #endif
224 }
225 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 8 ||
226 windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED ||
227 (windowBits == 8 && wrap != 1)) {
228 return Z_STREAM_ERROR;
229 }
230 if (windowBits == 8)
231 windowBits = 9; /* until 256-byte window bug fixed */
232
233 s = ZALLOC_DEFLATE_STATE(strm);
234 if (s == NULL)
235 return Z_MEM_ERROR;
236 strm->state = (struct internal_state *)s;
237 s->strm = strm;
238 s->status = INIT_STATE; /* to pass state test in deflateReset() */
239
240 s->wrap = wrap;
241 s->gzhead = NULL;
242 s->w_bits = (unsigned int)windowBits;
243 s->w_size = 1 << s->w_bits;
244 s->w_mask = s->w_size - 1;
245
246 #ifdef X86_PCLMULQDQ_CRC
247 window_padding = 8;
248 #endif
249
250 s->window = (unsigned char *) ZALLOC_WINDOW(strm, s->w_size + window_padding, 2*sizeof(unsigned char));
251 s->prev = (Pos *) ZALLOC(strm, s->w_size, sizeof(Pos));
252 memset(s->prev, 0, s->w_size * sizeof(Pos));
253 s->head = (Pos *) ZALLOC(strm, HASH_SIZE, sizeof(Pos));
254
255 s->high_water = 0; /* nothing written to s->window yet */
256
257 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
258
259 /* We overlay pending_buf and sym_buf. This works since the average size
260 * for length/distance pairs over any compressed block is assured to be 31
261 * bits or less.
262 *
263 * Analysis: The longest fixed codes are a length code of 8 bits plus 5
264 * extra bits, for lengths 131 to 257. The longest fixed distance codes are
265 * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
266 * possible fixed-codes length/distance pair is then 31 bits total.
267 *
268 * sym_buf starts one-fourth of the way into pending_buf. So there are
269 * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
270 * in sym_buf is three bytes -- two for the distance and one for the
271 * literal/length. As each symbol is consumed, the pointer to the next
272 * sym_buf value to read moves forward three bytes. From that symbol, up to
273 * 31 bits are written to pending_buf. The closest the written pending_buf
274 * bits gets to the next sym_buf symbol to read is just before the last
275 * code is written. At that time, 31*(n-2) bits have been written, just
276 * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
277 * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
278 * symbols are written.) The closest the writing gets to what is unread is
279 * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
280 * can range from 128 to 32768.
281 *
282 * Therefore, at a minimum, there are 142 bits of space between what is
283 * written and what is read in the overlain buffers, so the symbols cannot
284 * be overwritten by the compressed data. That space is actually 139 bits,
285 * due to the three-bit fixed-code block header.
286 *
287 * That covers the case where either Z_FIXED is specified, forcing fixed
288 * codes, or when the use of fixed codes is chosen, because that choice
289 * results in a smaller compressed block than dynamic codes. That latter
290 * condition then assures that the above analysis also covers all dynamic
291 * blocks. A dynamic-code block will only be chosen to be emitted if it has
292 * fewer bits than a fixed-code block would for the same set of symbols.
293 * Therefore its average symbol length is assured to be less than 31. So
294 * the compressed data for a dynamic block also cannot overwrite the
295 * symbols from which it is being constructed.
296 */
297
298 s->pending_buf = (unsigned char *) ZALLOC(strm, s->lit_bufsize, 4);
299 s->pending_buf_size = s->lit_bufsize * 4;
300
301 if (s->window == NULL || s->prev == NULL || s->head == NULL || s->pending_buf == NULL) {
302 s->status = FINISH_STATE;
303 strm->msg = ERR_MSG(Z_MEM_ERROR);
304 PREFIX(deflateEnd)(strm);
305 return Z_MEM_ERROR;
306 }
307 s->sym_buf = s->pending_buf + s->lit_bufsize;
308 s->sym_end = (s->lit_bufsize - 1) * 3;
309 /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
310 * on 16 bit machines and because stored blocks are restricted to
311 * 64K-1 bytes.
312 */
313
314 s->level = level;
315 s->strategy = strategy;
316 s->block_open = 0;
317 s->reproducible = 0;
318
319 return PREFIX(deflateReset)(strm);
320 }
321
322 #ifndef ZLIB_COMPAT
323 int32_t Z_EXPORT PREFIX(deflateInit)(PREFIX3(stream) *strm, int32_t level) {
324 return PREFIX(deflateInit2)(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
325 }
326 #endif
327
328 /* Function used by zlib.h and zlib-ng version 2.0 macros */
329 int32_t Z_EXPORT PREFIX(deflateInit_)(PREFIX3(stream) *strm, int32_t level, const char *version, int32_t stream_size) {
330 if (CHECK_VER_STSIZE(version, stream_size))
331 return Z_VERSION_ERROR;
332 return PREFIX(deflateInit2)(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
333 }
334
335 /* Function used by zlib.h and zlib-ng version 2.0 macros */
336 int32_t Z_EXPORT PREFIX(deflateInit2_)(PREFIX3(stream) *strm, int32_t level, int32_t method, int32_t windowBits,
337 int32_t memLevel, int32_t strategy, const char *version, int32_t stream_size) {
338 if (CHECK_VER_STSIZE(version, stream_size))
339 return Z_VERSION_ERROR;
340 return PREFIX(deflateInit2)(strm, level, method, windowBits, memLevel, strategy);
341 }
342
343 /* =========================================================================
344 * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
345 */
346 static int deflateStateCheck (PREFIX3(stream) *strm) {
347 deflate_state *s;
348 if (strm == NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
349 return 1;
350 s = strm->state;
351 if (s == NULL || s->strm != strm || (s->status != INIT_STATE &&
352 #ifdef GZIP
353 s->status != GZIP_STATE &&
354 s->status != EXTRA_STATE &&
355 s->status != NAME_STATE &&
356 s->status != COMMENT_STATE &&
357 s->status != HCRC_STATE &&
358 #endif
359 s->status != BUSY_STATE &&
360 s->status != FINISH_STATE))
361 return 1;
362 return 0;
363 }
364
365 /* ========================================================================= */
366 int32_t Z_EXPORT PREFIX(deflateSetDictionary)(PREFIX3(stream) *strm, const uint8_t *dictionary, uint32_t dictLength) {
367 deflate_state *s;
368 unsigned int str, n;
369 int wrap;
370 uint32_t avail;
371 const unsigned char *next;
372
373 if (deflateStateCheck(strm) || dictionary == NULL)
374 return Z_STREAM_ERROR;
375 s = strm->state;
376 wrap = s->wrap;
377 if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
378 return Z_STREAM_ERROR;
379
380 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
381 if (wrap == 1)
382 strm->adler = functable.adler32(strm->adler, dictionary, dictLength);
383 DEFLATE_SET_DICTIONARY_HOOK(strm, dictionary, dictLength); /* hook for IBM Z DFLTCC */
384 s->wrap = 0; /* avoid computing Adler-32 in read_buf */
385
386 /* if dictionary would fill window, just replace the history */
387 if (dictLength >= s->w_size) {
388 if (wrap == 0) { /* already empty otherwise */
389 CLEAR_HASH(s);
390 s->strstart = 0;
391 s->block_start = 0;
392 s->insert = 0;
393 }
394 dictionary += dictLength - s->w_size; /* use the tail */
395 dictLength = s->w_size;
396 }
397
398 /* insert dictionary into window and hash */
399 avail = strm->avail_in;
400 next = strm->next_in;
401 strm->avail_in = dictLength;
402 strm->next_in = (z_const unsigned char *)dictionary;
403 fill_window(s);
404 while (s->lookahead >= STD_MIN_MATCH) {
405 str = s->strstart;
406 n = s->lookahead - (STD_MIN_MATCH - 1);
407 functable.insert_string(s, str, n);
408 s->strstart = str + n;
409 s->lookahead = STD_MIN_MATCH - 1;
410 fill_window(s);
411 }
412 s->strstart += s->lookahead;
413 s->block_start = (int)s->strstart;
414 s->insert = s->lookahead;
415 s->lookahead = 0;
416 s->prev_length = 0;
417 s->match_available = 0;
418 strm->next_in = (z_const unsigned char *)next;
419 strm->avail_in = avail;
420 s->wrap = wrap;
421 return Z_OK;
422 }
423
424 /* ========================================================================= */
425 int32_t Z_EXPORT PREFIX(deflateGetDictionary)(PREFIX3(stream) *strm, uint8_t *dictionary, uint32_t *dictLength) {
426 deflate_state *s;
427 unsigned int len;
428
429 if (deflateStateCheck(strm))
430 return Z_STREAM_ERROR;
431 DEFLATE_GET_DICTIONARY_HOOK(strm, dictionary, dictLength); /* hook for IBM Z DFLTCC */
432 s = strm->state;
433 len = s->strstart + s->lookahead;
434 if (len > s->w_size)
435 len = s->w_size;
436 if (dictionary != NULL && len)
437 memcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
438 if (dictLength != NULL)
439 *dictLength = len;
440 return Z_OK;
441 }
442
443 /* ========================================================================= */
444 int32_t Z_EXPORT PREFIX(deflateResetKeep)(PREFIX3(stream) *strm) {
445 deflate_state *s;
446
447 if (deflateStateCheck(strm))
448 return Z_STREAM_ERROR;
449
450 strm->total_in = strm->total_out = 0;
451 strm->msg = NULL; /* use zfree if we ever allocate msg dynamically */
452 strm->data_type = Z_UNKNOWN;
453
454 s = (deflate_state *)strm->state;
455 s->pending = 0;
456 s->pending_out = s->pending_buf;
457
458 if (s->wrap < 0)
459 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
460
461 s->status =
462 #ifdef GZIP
463 s->wrap == 2 ? GZIP_STATE :
464 #endif
465 INIT_STATE;
466
467 #ifdef GZIP
468 if (s->wrap == 2) {
469 strm->adler = functable.crc32_fold_reset(&s->crc_fold);
470 } else
471 #endif
472 strm->adler = ADLER32_INITIAL_VALUE;
473 s->last_flush = -2;
474
475 zng_tr_init(s);
476
477 DEFLATE_RESET_KEEP_HOOK(strm); /* hook for IBM Z DFLTCC */
478
479 return Z_OK;
480 }
481
482 /* ========================================================================= */
483 int32_t Z_EXPORT PREFIX(deflateReset)(PREFIX3(stream) *strm) {
484 int ret;
485
486 ret = PREFIX(deflateResetKeep)(strm);
487 if (ret == Z_OK)
488 lm_init(strm->state);
489 return ret;
490 }
491
492 /* ========================================================================= */
493 int32_t Z_EXPORT PREFIX(deflateSetHeader)(PREFIX3(stream) *strm, PREFIX(gz_headerp) head) {
494 if (deflateStateCheck(strm) || strm->state->wrap != 2)
495 return Z_STREAM_ERROR;
496 strm->state->gzhead = head;
497 return Z_OK;
498 }
499
500 /* ========================================================================= */
501 int32_t Z_EXPORT PREFIX(deflatePending)(PREFIX3(stream) *strm, uint32_t *pending, int32_t *bits) {
502 if (deflateStateCheck(strm))
503 return Z_STREAM_ERROR;
504 if (pending != NULL)
505 *pending = strm->state->pending;
506 if (bits != NULL)
507 *bits = strm->state->bi_valid;
508 return Z_OK;
509 }
510
511 /* ========================================================================= */
512 int32_t Z_EXPORT PREFIX(deflatePrime)(PREFIX3(stream) *strm, int32_t bits, int32_t value) {
513 deflate_state *s;
514 uint64_t value64 = (uint64_t)value;
515 int32_t put;
516
517 if (deflateStateCheck(strm))
518 return Z_STREAM_ERROR;
519 s = strm->state;
520 if (bits < 0 || bits > BIT_BUF_SIZE || bits > (int32_t)(sizeof(value) << 3) ||
521 s->sym_buf < s->pending_out + ((BIT_BUF_SIZE + 7) >> 3))
522 return Z_BUF_ERROR;
523 do {
524 put = BIT_BUF_SIZE - s->bi_valid;
525 put = MIN(put, bits);
526
527 if (s->bi_valid == 0)
528 s->bi_buf = value64;
529 else
530 s->bi_buf |= (value64 & ((UINT64_C(1) << put) - 1)) << s->bi_valid;
531 s->bi_valid += put;
532 zng_tr_flush_bits(s);
533 value64 >>= put;
534 bits -= put;
535 } while (bits);
536 return Z_OK;
537 }
538
539 /* ========================================================================= */
540 int32_t Z_EXPORT PREFIX(deflateParams)(PREFIX3(stream) *strm, int32_t level, int32_t strategy) {
541 deflate_state *s;
542 compress_func func;
543 int hook_flush = Z_NO_FLUSH;
544
545 if (deflateStateCheck(strm))
546 return Z_STREAM_ERROR;
547 s = strm->state;
548
549 if (level == Z_DEFAULT_COMPRESSION)
550 level = 6;
551 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED)
552 return Z_STREAM_ERROR;
553 DEFLATE_PARAMS_HOOK(strm, level, strategy, &hook_flush); /* hook for IBM Z DFLTCC */
554 func = configuration_table[s->level].func;
555
556 if (((strategy != s->strategy || func != configuration_table[level].func) && s->last_flush != -2)
557 || hook_flush != Z_NO_FLUSH) {
558 /* Flush the last buffer. Use Z_BLOCK mode, unless the hook requests a "stronger" one. */
559 int flush = RANK(hook_flush) > RANK(Z_BLOCK) ? hook_flush : Z_BLOCK;
560 int err = PREFIX(deflate)(strm, flush);
561 if (err == Z_STREAM_ERROR)
562 return err;
563 if (strm->avail_in || ((int)s->strstart - s->block_start) + s->lookahead || !DEFLATE_DONE(strm, flush))
564 return Z_BUF_ERROR;
565 }
566 if (s->level != level) {
567 if (s->level == 0 && s->matches != 0) {
568 if (s->matches == 1) {
569 functable.slide_hash(s);
570 } else {
571 CLEAR_HASH(s);
572 }
573 s->matches = 0;
574 }
575
576 lm_set_level(s, level);
577 }
578 s->strategy = strategy;
579 return Z_OK;
580 }
581
582 /* ========================================================================= */
583 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) {
584 deflate_state *s;
585
586 if (deflateStateCheck(strm))
587 return Z_STREAM_ERROR;
588 s = strm->state;
589 s->good_match = (unsigned int)good_length;
590 s->max_lazy_match = (unsigned int)max_lazy;
591 s->nice_match = nice_length;
592 s->max_chain_length = (unsigned int)max_chain;
593 return Z_OK;
594 }
595
596 /* =========================================================================
597 * For the default windowBits of 15 and memLevel of 8, this function returns
598 * a close to exact, as well as small, upper bound on the compressed size.
599 * They are coded as constants here for a reason--if the #define's are
600 * changed, then this function needs to be changed as well. The return
601 * value for 15 and 8 only works for those exact settings.
602 *
603 * For any setting other than those defaults for windowBits and memLevel,
604 * the value returned is a conservative worst case for the maximum expansion
605 * resulting from using fixed blocks instead of stored blocks, which deflate
606 * can emit on compressed data for some combinations of the parameters.
607 *
608 * This function could be more sophisticated to provide closer upper bounds for
609 * every combination of windowBits and memLevel. But even the conservative
610 * upper bound of about 14% expansion does not seem onerous for output buffer
611 * allocation.
612 */
613 unsigned long Z_EXPORT PREFIX(deflateBound)(PREFIX3(stream) *strm, unsigned long sourceLen) {
614 deflate_state *s;
615 unsigned long complen, wraplen;
616
617 /* conservative upper bound for compressed data */
618 complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
619 DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen); /* hook for IBM Z DFLTCC */
620
621 /* if can't get parameters, return conservative bound plus zlib wrapper */
622 if (deflateStateCheck(strm))
623 return complen + 6;
624
625 /* compute wrapper length */
626 s = strm->state;
627 switch (s->wrap) {
628 case 0: /* raw deflate */
629 wraplen = 0;
630 break;
631 case 1: /* zlib wrapper */
632 wraplen = ZLIB_WRAPLEN + (s->strstart ? 4 : 0);
633 break;
634 #ifdef GZIP
635 case 2: /* gzip wrapper */
636 wraplen = GZIP_WRAPLEN;
637 if (s->gzhead != NULL) { /* user-supplied gzip header */
638 unsigned char *str;
639 if (s->gzhead->extra != NULL) {
640 wraplen += 2 + s->gzhead->extra_len;
641 }
642 str = s->gzhead->name;
643 if (str != NULL) {
644 do {
645 wraplen++;
646 } while (*str++);
647 }
648 str = s->gzhead->comment;
649 if (str != NULL) {
650 do {
651 wraplen++;
652 } while (*str++);
653 }
654 if (s->gzhead->hcrc)
655 wraplen += 2;
656 }
657 break;
658 #endif
659 default: /* for compiler happiness */
660 wraplen = ZLIB_WRAPLEN;
661 }
662
663 /* if not default parameters, return conservative bound */
664 if (DEFLATE_NEED_CONSERVATIVE_BOUND(strm) || /* hook for IBM Z DFLTCC */
665 s->w_bits != 15 || HASH_BITS < 15)
666 return complen + wraplen;
667
668 #ifndef NO_QUICK_STRATEGY
669 return sourceLen /* The source size itself */
670 + (sourceLen == 0 ? 1 : 0) /* Always at least one byte for any input */
671 + (sourceLen < 9 ? 1 : 0) /* One extra byte for lengths less than 9 */
672 + DEFLATE_QUICK_OVERHEAD(sourceLen) /* Source encoding overhead, padded to next full byte */
673 + DEFLATE_BLOCK_OVERHEAD /* Deflate block overhead bytes */
674 + wraplen; /* none, zlib or gzip wrapper */
675 #else
676 return sourceLen + (sourceLen >> 4) + 7 + wraplen;
677 #endif
678 }
679
680 /* =========================================================================
681 * Flush as much pending output as possible. All deflate() output, except for
682 * some deflate_stored() output, goes through this function so some
683 * applications may wish to modify it to avoid allocating a large
684 * strm->next_out buffer and copying into it. (See also read_buf()).
685 */
686 Z_INTERNAL void PREFIX(flush_pending)(PREFIX3(stream) *strm) {
687 uint32_t len;
688 deflate_state *s = strm->state;
689
690 zng_tr_flush_bits(s);
691 len = s->pending;
692 if (len > strm->avail_out)
693 len = strm->avail_out;
694 if (len == 0)
695 return;
696
697 Tracev((stderr, "[FLUSH]"));
698 memcpy(strm->next_out, s->pending_out, len);
699 strm->next_out += len;
700 s->pending_out += len;
701 strm->total_out += len;
702 strm->avail_out -= len;
703 s->pending -= len;
704 if (s->pending == 0)
705 s->pending_out = s->pending_buf;
706 }
707
708 /* ===========================================================================
709 * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
710 */
711 #define HCRC_UPDATE(beg) \
712 do { \
713 if (s->gzhead->hcrc && s->pending > (beg)) \
714 strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf + (beg), s->pending - (beg)); \
715 } while (0)
716
717 /* ========================================================================= */
718 int32_t Z_EXPORT PREFIX(deflate)(PREFIX3(stream) *strm, int32_t flush) {
719 int32_t old_flush; /* value of flush param for previous deflate call */
720 deflate_state *s;
721
722 if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0)
723 return Z_STREAM_ERROR;
724 s = strm->state;
725
726 if (strm->next_out == NULL || (strm->avail_in != 0 && strm->next_in == NULL)
727 || (s->status == FINISH_STATE && flush != Z_FINISH)) {
728 ERR_RETURN(strm, Z_STREAM_ERROR);
729 }
730 if (strm->avail_out == 0) {
731 ERR_RETURN(strm, Z_BUF_ERROR);
732 }
733
734 old_flush = s->last_flush;
735 s->last_flush = flush;
736
737 /* Flush as much pending output as possible */
738 if (s->pending != 0) {
739 PREFIX(flush_pending)(strm);
740 if (strm->avail_out == 0) {
741 /* Since avail_out is 0, deflate will be called again with
742 * more output space, but possibly with both pending and
743 * avail_in equal to zero. There won't be anything to do,
744 * but this is not an error situation so make sure we
745 * return OK instead of BUF_ERROR at next call of deflate:
746 */
747 s->last_flush = -1;
748 return Z_OK;
749 }
750
751 /* Make sure there is something to do and avoid duplicate consecutive
752 * flushes. For repeated and useless calls with Z_FINISH, we keep
753 * returning Z_STREAM_END instead of Z_BUF_ERROR.
754 */
755 } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) {
756 ERR_RETURN(strm, Z_BUF_ERROR);
757 }
758
759 /* User must not provide more input after the first FINISH: */
760 if (s->status == FINISH_STATE && strm->avail_in != 0) {
761 ERR_RETURN(strm, Z_BUF_ERROR);
762 }
763
764 /* Write the header */
765 if (s->status == INIT_STATE && s->wrap == 0)
766 s->status = BUSY_STATE;
767 if (s->status == INIT_STATE) {
768 /* zlib header */
769 unsigned int header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
770 unsigned int level_flags;
771
772 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
773 level_flags = 0;
774 else if (s->level < 6)
775 level_flags = 1;
776 else if (s->level == 6)
777 level_flags = 2;
778 else
779 level_flags = 3;
780 header |= (level_flags << 6);
781 if (s->strstart != 0)
782 header |= PRESET_DICT;
783 header += 31 - (header % 31);
784
785 put_short_msb(s, (uint16_t)header);
786
787 /* Save the adler32 of the preset dictionary: */
788 if (s->strstart != 0)
789 put_uint32_msb(s, strm->adler);
790 strm->adler = ADLER32_INITIAL_VALUE;
791 s->status = BUSY_STATE;
792
793 /* Compression must start with an empty pending buffer */
794 PREFIX(flush_pending)(strm);
795 if (s->pending != 0) {
796 s->last_flush = -1;
797 return Z_OK;
798 }
799 }
800 #ifdef GZIP
801 if (s->status == GZIP_STATE) {
802 /* gzip header */
803 functable.crc32_fold_reset(&s->crc_fold);
804 put_byte(s, 31);
805 put_byte(s, 139);
806 put_byte(s, 8);
807 if (s->gzhead == NULL) {
808 put_uint32(s, 0);
809 put_byte(s, 0);
810 put_byte(s, s->level == 9 ? 2 :
811 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
812 put_byte(s, OS_CODE);
813 s->status = BUSY_STATE;
814
815 /* Compression must start with an empty pending buffer */
816 PREFIX(flush_pending)(strm);
817 if (s->pending != 0) {
818 s->last_flush = -1;
819 return Z_OK;
820 }
821 } else {
822 put_byte(s, (s->gzhead->text ? 1 : 0) +
823 (s->gzhead->hcrc ? 2 : 0) +
824 (s->gzhead->extra == NULL ? 0 : 4) +
825 (s->gzhead->name == NULL ? 0 : 8) +
826 (s->gzhead->comment == NULL ? 0 : 16)
827 );
828 put_uint32(s, s->gzhead->time);
829 put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
830 put_byte(s, s->gzhead->os & 0xff);
831 if (s->gzhead->extra != NULL)
832 put_short(s, (uint16_t)s->gzhead->extra_len);
833 if (s->gzhead->hcrc)
834 strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf, s->pending);
835 s->gzindex = 0;
836 s->status = EXTRA_STATE;
837 }
838 }
839 if (s->status == EXTRA_STATE) {
840 if (s->gzhead->extra != NULL) {
841 uint32_t beg = s->pending; /* start of bytes to update crc */
842 uint32_t left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
843
844 while (s->pending + left > s->pending_buf_size) {
845 uint32_t copy = s->pending_buf_size - s->pending;
846 memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, copy);
847 s->pending = s->pending_buf_size;
848 HCRC_UPDATE(beg);
849 s->gzindex += copy;
850 PREFIX(flush_pending)(strm);
851 if (s->pending != 0) {
852 s->last_flush = -1;
853 return Z_OK;
854 }
855 beg = 0;
856 left -= copy;
857 }
858 memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, left);
859 s->pending += left;
860 HCRC_UPDATE(beg);
861 s->gzindex = 0;
862 }
863 s->status = NAME_STATE;
864 }
865 if (s->status == NAME_STATE) {
866 if (s->gzhead->name != NULL) {
867 uint32_t beg = s->pending; /* start of bytes to update crc */
868 unsigned char val;
869
870 do {
871 if (s->pending == s->pending_buf_size) {
872 HCRC_UPDATE(beg);
873 PREFIX(flush_pending)(strm);
874 if (s->pending != 0) {
875 s->last_flush = -1;
876 return Z_OK;
877 }
878 beg = 0;
879 }
880 val = s->gzhead->name[s->gzindex++];
881 put_byte(s, val);
882 } while (val != 0);
883 HCRC_UPDATE(beg);
884 s->gzindex = 0;
885 }
886 s->status = COMMENT_STATE;
887 }
888 if (s->status == COMMENT_STATE) {
889 if (s->gzhead->comment != NULL) {
890 uint32_t beg = s->pending; /* start of bytes to update crc */
891 unsigned char val;
892
893 do {
894 if (s->pending == s->pending_buf_size) {
895 HCRC_UPDATE(beg);
896 PREFIX(flush_pending)(strm);
897 if (s->pending != 0) {
898 s->last_flush = -1;
899 return Z_OK;
900 }
901 beg = 0;
902 }
903 val = s->gzhead->comment[s->gzindex++];
904 put_byte(s, val);
905 } while (val != 0);
906 HCRC_UPDATE(beg);
907 }
908 s->status = HCRC_STATE;
909 }
910 if (s->status == HCRC_STATE) {
911 if (s->gzhead->hcrc) {
912 if (s->pending + 2 > s->pending_buf_size) {
913 PREFIX(flush_pending)(strm);
914 if (s->pending != 0) {
915 s->last_flush = -1;
916 return Z_OK;
917 }
918 }
919 put_short(s, (uint16_t)strm->adler);
920 functable.crc32_fold_reset(&s->crc_fold);
921 }
922 s->status = BUSY_STATE;
923
924 /* Compression must start with an empty pending buffer */
925 PREFIX(flush_pending)(strm);
926 if (s->pending != 0) {
927 s->last_flush = -1;
928 return Z_OK;
929 }
930 }
931 #endif
932
933 /* Start a new block or continue the current one.
934 */
935 if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
936 block_state bstate;
937
938 bstate = DEFLATE_HOOK(strm, flush, &bstate) ? bstate : /* hook for IBM Z DFLTCC */
939 s->level == 0 ? deflate_stored(s, flush) :
940 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
941 s->strategy == Z_RLE ? deflate_rle(s, flush) :
942 (*(configuration_table[s->level].func))(s, flush);
943
944 if (bstate == finish_started || bstate == finish_done) {
945 s->status = FINISH_STATE;
946 }
947 if (bstate == need_more || bstate == finish_started) {
948 if (strm->avail_out == 0) {
949 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
950 }
951 return Z_OK;
952 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
953 * of deflate should use the same flush parameter to make sure
954 * that the flush is complete. So we don't have to output an
955 * empty block here, this will be done at next call. This also
956 * ensures that for a very small output buffer, we emit at most
957 * one empty block.
958 */
959 }
960 if (bstate == block_done) {
961 if (flush == Z_PARTIAL_FLUSH) {
962 zng_tr_align(s);
963 } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
964 zng_tr_stored_block(s, (char*)0, 0L, 0);
965 /* For a full flush, this empty block will be recognized
966 * as a special marker by inflate_sync().
967 */
968 if (flush == Z_FULL_FLUSH) {
969 CLEAR_HASH(s); /* forget history */
970 if (s->lookahead == 0) {
971 s->strstart = 0;
972 s->block_start = 0;
973 s->insert = 0;
974 }
975 }
976 }
977 PREFIX(flush_pending)(strm);
978 if (strm->avail_out == 0) {
979 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
980 return Z_OK;
981 }
982 }
983 }
984
985 if (flush != Z_FINISH)
986 return Z_OK;
987
988 /* Write the trailer */
989 #ifdef GZIP
990 if (s->wrap == 2) {
991 strm->adler = functable.crc32_fold_final(&s->crc_fold);
992
993 put_uint32(s, strm->adler);
994 put_uint32(s, (uint32_t)strm->total_in);
995 } else
996 #endif
997 {
998 if (s->wrap == 1)
999 put_uint32_msb(s, strm->adler);
1000 }
1001 PREFIX(flush_pending)(strm);
1002 /* If avail_out is zero, the application will call deflate again
1003 * to flush the rest.
1004 */
1005 if (s->wrap > 0)
1006 s->wrap = -s->wrap; /* write the trailer only once! */
1007 if (s->pending == 0) {
1008 Assert(s->bi_valid == 0, "bi_buf not flushed");
1009 return Z_STREAM_END;
1010 }
1011 return Z_OK;
1012 }
1013
1014 /* ========================================================================= */
1015 int32_t Z_EXPORT PREFIX(deflateEnd)(PREFIX3(stream) *strm) {
1016 int32_t status;
1017
1018 if (deflateStateCheck(strm))
1019 return Z_STREAM_ERROR;
1020
1021 status = strm->state->status;
1022
1023 /* Deallocate in reverse order of allocations: */
1024 TRY_FREE(strm, strm->state->pending_buf);
1025 TRY_FREE(strm, strm->state->head);
1026 TRY_FREE(strm, strm->state->prev);
1027 TRY_FREE_WINDOW(strm, strm->state->window);
1028
1029 ZFREE_STATE(strm, strm->state);
1030 strm->state = NULL;
1031
1032 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1033 }
1034
1035 /* =========================================================================
1036 * Copy the source state to the destination state.
1037 */
1038 int32_t Z_EXPORT PREFIX(deflateCopy)(PREFIX3(stream) *dest, PREFIX3(stream) *source) {
1039 deflate_state *ds;
1040 deflate_state *ss;
1041 uint32_t window_padding = 0;
1042
1043 if (deflateStateCheck(source) || dest == NULL)
1044 return Z_STREAM_ERROR;
1045
1046 ss = source->state;
1047
1048 memcpy((void *)dest, (void *)source, sizeof(PREFIX3(stream)));
1049
1050 ds = ZALLOC_DEFLATE_STATE(dest);
1051 if (ds == NULL)
1052 return Z_MEM_ERROR;
1053 dest->state = (struct internal_state *) ds;
1054 ZCOPY_DEFLATE_STATE(ds, ss);
1055 ds->strm = dest;
1056
1057 #ifdef X86_PCLMULQDQ_CRC
1058 window_padding = 8;
1059 #endif
1060
1061 ds->window = (unsigned char *) ZALLOC_WINDOW(dest, ds->w_size + window_padding, 2*sizeof(unsigned char));
1062 ds->prev = (Pos *) ZALLOC(dest, ds->w_size, sizeof(Pos));
1063 ds->head = (Pos *) ZALLOC(dest, HASH_SIZE, sizeof(Pos));
1064 ds->pending_buf = (unsigned char *) ZALLOC(dest, ds->lit_bufsize, 4);
1065
1066 if (ds->window == NULL || ds->prev == NULL || ds->head == NULL || ds->pending_buf == NULL) {
1067 PREFIX(deflateEnd)(dest);
1068 return Z_MEM_ERROR;
1069 }
1070
1071 memcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(unsigned char));
1072 memcpy((void *)ds->prev, (void *)ss->prev, ds->w_size * sizeof(Pos));
1073 memcpy((void *)ds->head, (void *)ss->head, HASH_SIZE * sizeof(Pos));
1074 memcpy(ds->pending_buf, ss->pending_buf, ds->pending_buf_size);
1075
1076 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1077 ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1078
1079 ds->l_desc.dyn_tree = ds->dyn_ltree;
1080 ds->d_desc.dyn_tree = ds->dyn_dtree;
1081 ds->bl_desc.dyn_tree = ds->bl_tree;
1082
1083 return Z_OK;
1084 }
1085
1086 /* ===========================================================================
1087 * Read a new buffer from the current input stream, update the adler32
1088 * and total number of bytes read. All deflate() input goes through
1089 * this function so some applications may wish to modify it to avoid
1090 * allocating a large strm->next_in buffer and copying from it.
1091 * (See also flush_pending()).
1092 */
1093 Z_INTERNAL unsigned read_buf(PREFIX3(stream) *strm, unsigned char *buf, unsigned size) {
1094 uint32_t len = strm->avail_in;
1095
1096 len = MIN(len, size);
1097 if (len == 0)
1098 return 0;
1099
1100 strm->avail_in -= len;
1101
1102 if (!DEFLATE_NEED_CHECKSUM(strm)) {
1103 memcpy(buf, strm->next_in, len);
1104 #ifdef GZIP
1105 } else if (strm->state->wrap == 2) {
1106 functable.crc32_fold_copy(&strm->state->crc_fold, buf, strm->next_in, len);
1107 #endif
1108 } else {
1109 if (strm->state->wrap == 1)
1110 strm->adler = functable.adler32_fold_copy(strm->adler, buf, strm->next_in, len);
1111 else
1112 memcpy(buf, strm->next_in, len);
1113 }
1114 strm->next_in += len;
1115 strm->total_in += len;
1116
1117 return len;
1118 }
1119
1120 /* ===========================================================================
1121 * Set longest match variables based on level configuration
1122 */
1123 static void lm_set_level(deflate_state *s, int level) {
1124 s->max_lazy_match = configuration_table[level].max_lazy;
1125 s->good_match = configuration_table[level].good_length;
1126 s->nice_match = configuration_table[level].nice_length;
1127 s->max_chain_length = configuration_table[level].max_chain;
1128
1129 /* Use rolling hash for deflate_slow algorithm with level 9. It allows us to
1130 * properly lookup different hash chains to speed up longest_match search. Since hashing
1131 * method changes depending on the level we cannot put this into functable. */
1132 if (s->max_chain_length > 1024) {
1133 s->update_hash = &update_hash_roll;
1134 s->insert_string = &insert_string_roll;
1135 s->quick_insert_string = &quick_insert_string_roll;
1136 } else {
1137 s->update_hash = functable.update_hash;
1138 s->insert_string = functable.insert_string;
1139 s->quick_insert_string = functable.quick_insert_string;
1140 }
1141
1142 s->level = level;
1143 }
1144
1145 /* ===========================================================================
1146 * Initialize the "longest match" routines for a new zlib stream
1147 */
1148 static void lm_init(deflate_state *s) {
1149 s->window_size = 2 * s->w_size;
1150
1151 CLEAR_HASH(s);
1152
1153 /* Set the default configuration parameters:
1154 */
1155 lm_set_level(s, s->level);
1156
1157 s->strstart = 0;
1158 s->block_start = 0;
1159 s->lookahead = 0;
1160 s->insert = 0;
1161 s->prev_length = 0;
1162 s->match_available = 0;
1163 s->match_start = 0;
1164 s->ins_h = 0;
1165 }
1166
1167 /* ===========================================================================
1168 * Fill the window when the lookahead becomes insufficient.
1169 * Updates strstart and lookahead.
1170 *
1171 * IN assertion: lookahead < MIN_LOOKAHEAD
1172 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1173 * At least one byte has been read, or avail_in == 0; reads are
1174 * performed for at least two bytes (required for the zip translate_eol
1175 * option -- not supported here).
1176 */
1177
1178 void Z_INTERNAL fill_window(deflate_state *s) {
1179 unsigned n;
1180 unsigned int more; /* Amount of free space at the end of the window. */
1181 unsigned int wsize = s->w_size;
1182
1183 Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1184
1185 do {
1186 more = s->window_size - s->lookahead - s->strstart;
1187
1188 /* If the window is almost full and there is insufficient lookahead,
1189 * move the upper half to the lower one to make room in the upper half.
1190 */
1191 if (s->strstart >= wsize+MAX_DIST(s)) {
1192 memcpy(s->window, s->window+wsize, (unsigned)wsize);
1193 if (s->match_start >= wsize) {
1194 s->match_start -= wsize;
1195 } else {
1196 s->match_start = 0;
1197 s->prev_length = 0;
1198 }
1199 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1200 s->block_start -= (int)wsize;
1201 if (s->insert > s->strstart)
1202 s->insert = s->strstart;
1203 functable.slide_hash(s);
1204 more += wsize;
1205 }
1206 if (s->strm->avail_in == 0)
1207 break;
1208
1209 /* If there was no sliding:
1210 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1211 * more == window_size - lookahead - strstart
1212 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1213 * => more >= window_size - 2*WSIZE + 2
1214 * In the BIG_MEM or MMAP case (not yet supported),
1215 * window_size == input_size + MIN_LOOKAHEAD &&
1216 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1217 * Otherwise, window_size == 2*WSIZE so more >= 2.
1218 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1219 */
1220 Assert(more >= 2, "more < 2");
1221
1222 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1223 s->lookahead += n;
1224
1225 /* Initialize the hash value now that we have some input: */
1226 if (s->lookahead + s->insert >= STD_MIN_MATCH) {
1227 unsigned int str = s->strstart - s->insert;
1228 if (UNLIKELY(s->max_chain_length > 1024)) {
1229 s->ins_h = s->update_hash(s, s->window[str], s->window[str+1]);
1230 } else if (str >= 1) {
1231 s->quick_insert_string(s, str + 2 - STD_MIN_MATCH);
1232 }
1233 unsigned int count;
1234 if (UNLIKELY(s->lookahead == 1)) {
1235 count = s->insert - 1;
1236 } else {
1237 count = s->insert;
1238 }
1239 if (count > 0) {
1240 s->insert_string(s, str, count);
1241 s->insert -= count;
1242 }
1243 }
1244 /* If the whole input has less than STD_MIN_MATCH bytes, ins_h is garbage,
1245 * but this is not important since only literal bytes will be emitted.
1246 */
1247 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1248
1249 /* If the WIN_INIT bytes after the end of the current data have never been
1250 * written, then zero those bytes in order to avoid memory check reports of
1251 * the use of uninitialized (or uninitialised as Julian writes) bytes by
1252 * the longest match routines. Update the high water mark for the next
1253 * time through here. WIN_INIT is set to STD_MAX_MATCH since the longest match
1254 * routines allow scanning to strstart + STD_MAX_MATCH, ignoring lookahead.
1255 */
1256 if (s->high_water < s->window_size) {
1257 unsigned int curr = s->strstart + s->lookahead;
1258 unsigned int init;
1259
1260 if (s->high_water < curr) {
1261 /* Previous high water mark below current data -- zero WIN_INIT
1262 * bytes or up to end of window, whichever is less.
1263 */
1264 init = s->window_size - curr;
1265 if (init > WIN_INIT)
1266 init = WIN_INIT;
1267 memset(s->window + curr, 0, init);
1268 s->high_water = curr + init;
1269 } else if (s->high_water < curr + WIN_INIT) {
1270 /* High water mark at or above current data, but below current data
1271 * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1272 * to end of window, whichever is less.
1273 */
1274 init = curr + WIN_INIT - s->high_water;
1275 if (init > s->window_size - s->high_water)
1276 init = s->window_size - s->high_water;
1277 memset(s->window + s->high_water, 0, init);
1278 s->high_water += init;
1279 }
1280 }
1281
1282 Assert((unsigned long)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1283 "not enough room for search");
1284 }
1285
1286 #ifndef ZLIB_COMPAT
1287 /* =========================================================================
1288 * Checks whether buffer size is sufficient and whether this parameter is a duplicate.
1289 */
1290 static int32_t deflateSetParamPre(zng_deflate_param_value **out, size_t min_size, zng_deflate_param_value *param) {
1291 int32_t buf_error = param->size < min_size;
1292
1293 if (*out != NULL) {
1294 (*out)->status = Z_BUF_ERROR;
1295 buf_error = 1;
1296 }
1297 *out = param;
1298 return buf_error;
1299 }
1300
1301 /* ========================================================================= */
1302 int32_t Z_EXPORT zng_deflateSetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
1303 size_t i;
1304 deflate_state *s;
1305 zng_deflate_param_value *new_level = NULL;
1306 zng_deflate_param_value *new_strategy = NULL;
1307 zng_deflate_param_value *new_reproducible = NULL;
1308 int param_buf_error;
1309 int version_error = 0;
1310 int buf_error = 0;
1311 int stream_error = 0;
1312 int ret;
1313 int val;
1314
1315 /* Initialize the statuses. */
1316 for (i = 0; i < count; i++)
1317 params[i].status = Z_OK;
1318
1319 /* Check whether the stream state is consistent. */
1320 if (deflateStateCheck(strm))
1321 return Z_STREAM_ERROR;
1322 s = strm->state;
1323
1324 /* Check buffer sizes and detect duplicates. */
1325 for (i = 0; i < count; i++) {
1326 switch (params[i].param) {
1327 case Z_DEFLATE_LEVEL:
1328 param_buf_error = deflateSetParamPre(&new_level, sizeof(int), &params[i]);
1329 break;
1330 case Z_DEFLATE_STRATEGY:
1331 param_buf_error = deflateSetParamPre(&new_strategy, sizeof(int), &params[i]);
1332 break;
1333 case Z_DEFLATE_REPRODUCIBLE:
1334 param_buf_error = deflateSetParamPre(&new_reproducible, sizeof(int), &params[i]);
1335 break;
1336 default:
1337 params[i].status = Z_VERSION_ERROR;
1338 version_error = 1;
1339 param_buf_error = 0;
1340 break;
1341 }
1342 if (param_buf_error) {
1343 params[i].status = Z_BUF_ERROR;
1344 buf_error = 1;
1345 }
1346 }
1347 /* Exit early if small buffers or duplicates are detected. */
1348 if (buf_error)
1349 return Z_BUF_ERROR;
1350
1351 /* Apply changes, remember if there were errors. */
1352 if (new_level != NULL || new_strategy != NULL) {
1353 ret = PREFIX(deflateParams)(strm, new_level == NULL ? s->level : *(int *)new_level->buf,
1354 new_strategy == NULL ? s->strategy : *(int *)new_strategy->buf);
1355 if (ret != Z_OK) {
1356 if (new_level != NULL)
1357 new_level->status = Z_STREAM_ERROR;
1358 if (new_strategy != NULL)
1359 new_strategy->status = Z_STREAM_ERROR;
1360 stream_error = 1;
1361 }
1362 }
1363 if (new_reproducible != NULL) {
1364 val = *(int *)new_reproducible->buf;
1365 if (DEFLATE_CAN_SET_REPRODUCIBLE(strm, val)) {
1366 s->reproducible = val;
1367 } else {
1368 new_reproducible->status = Z_STREAM_ERROR;
1369 stream_error = 1;
1370 }
1371 }
1372
1373 /* Report version errors only if there are no real errors. */
1374 return stream_error ? Z_STREAM_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
1375 }
1376
1377 /* ========================================================================= */
1378 int32_t Z_EXPORT zng_deflateGetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
1379 deflate_state *s;
1380 size_t i;
1381 int32_t buf_error = 0;
1382 int32_t version_error = 0;
1383
1384 /* Initialize the statuses. */
1385 for (i = 0; i < count; i++)
1386 params[i].status = Z_OK;
1387
1388 /* Check whether the stream state is consistent. */
1389 if (deflateStateCheck(strm))
1390 return Z_STREAM_ERROR;
1391 s = strm->state;
1392
1393 for (i = 0; i < count; i++) {
1394 switch (params[i].param) {
1395 case Z_DEFLATE_LEVEL:
1396 if (params[i].size < sizeof(int))
1397 params[i].status = Z_BUF_ERROR;
1398 else
1399 *(int *)params[i].buf = s->level;
1400 break;
1401 case Z_DEFLATE_STRATEGY:
1402 if (params[i].size < sizeof(int))
1403 params[i].status = Z_BUF_ERROR;
1404 else
1405 *(int *)params[i].buf = s->strategy;
1406 break;
1407 case Z_DEFLATE_REPRODUCIBLE:
1408 if (params[i].size < sizeof(int))
1409 params[i].status = Z_BUF_ERROR;
1410 else
1411 *(int *)params[i].buf = s->reproducible;
1412 break;
1413 default:
1414 params[i].status = Z_VERSION_ERROR;
1415 version_error = 1;
1416 break;
1417 }
1418 if (params[i].status == Z_BUF_ERROR)
1419 buf_error = 1;
1420 }
1421 return buf_error ? Z_BUF_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
1422 }
1423 #endif