Coverage Report

Created: 2025-08-29 06:27

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