Coverage Report

Created: 2026-02-14 07:07

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