Coverage Report

Created: 2026-07-16 06:59

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