Coverage Report

Created: 2026-07-25 06:58

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