1#ifndef DEFLATE_H_
2#define DEFLATE_H_
3/* deflate.h -- internal compression state
4 * Copyright (C) 1995-2016 Jean-loup Gailly
5 * For conditions of distribution and use, see copyright notice in zlib.h
6 */
7
8/* WARNING: this file should *not* be used by applications. It is
9 part of the implementation of the compression library and is
10 subject to change. Applications should only use zlib.h.
11 */
12
13/* @(#) $Id$ */
14
15#include "zutil.h"
16#include "zendian.h"
17
18/* define NO_GZIP when compiling if you want to disable gzip header and
19 trailer creation by deflate(). NO_GZIP would be used to avoid linking in
20 the crc code when it is not needed. For shared libraries, gzip encoding
21 should be left enabled. */
22#ifndef NO_GZIP
23# define GZIP
24#endif
25
26#define NIL 0
27/* Tail of hash chains */
28
29
30/* ===========================================================================
31 * Internal compression state.
32 */
33
34#define LENGTH_CODES 29
35/* number of length codes, not counting the special END_BLOCK code */
36
37#define LITERALS 256
38/* number of literal bytes 0..255 */
39
40#define L_CODES (LITERALS+1+LENGTH_CODES)
41/* number of Literal or Length codes, including the END_BLOCK code */
42
43#define D_CODES 30
44/* number of distance codes */
45
46#define BL_CODES 19
47/* number of codes used to transfer the bit lengths */
48
49#define HEAP_SIZE (2*L_CODES+1)
50/* maximum heap size */
51
52#define MAX_BITS 15
53/* All codes must not exceed MAX_BITS bits */
54
55#define Buf_size 16
56/* size of bit buffer in bi_buf */
57
58#define END_BLOCK 256
59/* end of block literal code */
60
61#define INIT_STATE 42 /* zlib header -> BUSY_STATE */
62#ifdef GZIP
63# define GZIP_STATE 57 /* gzip header -> BUSY_STATE | EXTRA_STATE */
64#endif
65#define EXTRA_STATE 69 /* gzip extra block -> NAME_STATE */
66#define NAME_STATE 73 /* gzip file name -> COMMENT_STATE */
67#define COMMENT_STATE 91 /* gzip comment -> HCRC_STATE */
68#define HCRC_STATE 103 /* gzip header CRC -> BUSY_STATE */
69#define BUSY_STATE 113 /* deflate -> FINISH_STATE */
70#define FINISH_STATE 666 /* stream complete */
71/* Stream status */
72
73
74/* Data structure describing a single value and its code string. */
75typedef struct ct_data_s {
76 union {
77 uint16_t freq; /* frequency count */
78 uint16_t code; /* bit string */
79 } fc;
80 union {
81 uint16_t dad; /* father node in Huffman tree */
82 uint16_t len; /* length of bit string */
83 } dl;
84} ct_data;
85
86#define Freq fc.freq
87#define Code fc.code
88#define Dad dl.dad
89#define Len dl.len
90
91typedef struct static_tree_desc_s static_tree_desc;
92
93typedef struct tree_desc_s {
94 ct_data *dyn_tree; /* the dynamic tree */
95 int max_code; /* largest code with non zero frequency */
96 const static_tree_desc *stat_desc; /* the corresponding static tree */
97} tree_desc;
98
99typedef uint16_t Pos;
100typedef unsigned IPos;
101
102/* A Pos is an index in the character window. We use short instead of int to
103 * save space in the various tables. IPos is used only for parameter passing.
104 */
105
106typedef struct internal_state {
107 PREFIX3(stream) *strm; /* pointer back to this zlib stream */
108 int status; /* as the name implies */
109 unsigned char *pending_buf; /* output still pending */
110 unsigned long pending_buf_size; /* size of pending_buf */
111 unsigned char *pending_out; /* next pending byte to output to the stream */
112 uint32_t pending; /* nb of bytes in the pending buffer */
113 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
114 PREFIX(gz_headerp) gzhead; /* gzip header information to write */
115 uint32_t gzindex; /* where in extra, name, or comment */
116 unsigned char method; /* can only be DEFLATED */
117 int last_flush; /* value of flush param for previous deflate call */
118
119#ifdef X86_PCLMULQDQ_CRC
120 unsigned crc0[4 * 5];
121#endif
122
123 /* used by deflate.c: */
124
125 unsigned int w_size; /* LZ77 window size (32K by default) */
126 unsigned int w_bits; /* log2(w_size) (8..16) */
127 unsigned int w_mask; /* w_size - 1 */
128
129 unsigned char *window;
130 /* Sliding window. Input bytes are read into the second half of the window,
131 * and move to the first half later to keep a dictionary of at least wSize
132 * bytes. With this organization, matches are limited to a distance of
133 * wSize-MAX_MATCH bytes, but this ensures that IO is always
134 * performed with a length multiple of the block size. Also, it limits
135 * the window size to 64K, which is quite useful on MSDOS.
136 * To do: use the user input buffer as sliding window.
137 */
138
139 unsigned long window_size;
140 /* Actual size of window: 2*wSize, except when the user input buffer
141 * is directly used as sliding window.
142 */
143
144 Pos *prev;
145 /* Link to older string with same hash index. To limit the size of this
146 * array to 64K, this link is maintained only for the last 32K strings.
147 * An index in this array is thus a window index modulo 32K.
148 */
149
150 Pos *head; /* Heads of the hash chains or NIL. */
151
152 unsigned int ins_h; /* hash index of string to be inserted */
153 unsigned int hash_size; /* number of elements in hash table */
154 unsigned int hash_bits; /* log2(hash_size) */
155 unsigned int hash_mask; /* hash_size-1 */
156
157 #if !defined(__x86_64__) && !defined(_M_X64) && !defined(__i386) && !defined(_M_IX86)
158 unsigned int hash_shift;
159 #endif
160 /* Number of bits by which ins_h must be shifted at each input
161 * step. It must be such that after MIN_MATCH steps, the oldest
162 * byte no longer takes part in the hash key, that is:
163 * hash_shift * MIN_MATCH >= hash_bits
164 */
165
166 long block_start;
167 /* Window position at the beginning of the current output block. Gets
168 * negative when the window is moved backwards.
169 */
170
171 unsigned int match_length; /* length of best match */
172 IPos prev_match; /* previous match */
173 int match_available; /* set if previous match exists */
174 unsigned int strstart; /* start of string to insert */
175 unsigned int match_start; /* start of matching string */
176 unsigned int lookahead; /* number of valid bytes ahead in window */
177
178 unsigned int prev_length;
179 /* Length of the best match at previous step. Matches not greater than this
180 * are discarded. This is used in the lazy match evaluation.
181 */
182
183 unsigned int max_chain_length;
184 /* To speed up deflation, hash chains are never searched beyond this
185 * length. A higher limit improves compression ratio but degrades the
186 * speed.
187 */
188
189 unsigned int max_lazy_match;
190 /* Attempt to find a better match only when the current match is strictly
191 * smaller than this value. This mechanism is used only for compression
192 * levels >= 4.
193 */
194# define max_insert_length max_lazy_match
195 /* Insert new strings in the hash table only if the match length is not
196 * greater than this length. This saves time but degrades compression.
197 * max_insert_length is used only for compression levels <= 3.
198 */
199
200 int level; /* compression level (1..9) */
201 int strategy; /* favor or force Huffman coding*/
202
203 unsigned int good_match;
204 /* Use a faster search when the previous match is longer than this */
205
206 int nice_match; /* Stop searching when current match exceeds this */
207
208 /* used by trees.c: */
209 /* Didn't use ct_data typedef below to suppress compiler warning */
210 struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
211 struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
212 struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
213
214 struct tree_desc_s l_desc; /* desc. for literal tree */
215 struct tree_desc_s d_desc; /* desc. for distance tree */
216 struct tree_desc_s bl_desc; /* desc. for bit length tree */
217
218 uint16_t bl_count[MAX_BITS+1];
219 /* number of codes at each bit length for an optimal tree */
220
221 int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
222 int heap_len; /* number of elements in the heap */
223 int heap_max; /* element of largest frequency */
224 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
225 * The same heap array is used to build all trees.
226 */
227
228 unsigned char depth[2*L_CODES+1];
229 /* Depth of each subtree used as tie breaker for trees of equal frequency
230 */
231
232 unsigned char *sym_buf; /* buffer for distances and literals/lengths */
233
234 unsigned int lit_bufsize;
235 /* Size of match buffer for literals/lengths. There are 4 reasons for
236 * limiting lit_bufsize to 64K:
237 * - frequencies can be kept in 16 bit counters
238 * - if compression is not successful for the first block, all input
239 * data is still in the window so we can still emit a stored block even
240 * when input comes from standard input. (This can also be done for
241 * all blocks if lit_bufsize is not greater than 32K.)
242 * - if compression is not successful for a file smaller than 64K, we can
243 * even emit a stored file instead of a stored block (saving 5 bytes).
244 * This is applicable only for zip (not gzip or zlib).
245 * - creating new Huffman trees less frequently may not provide fast
246 * adaptation to changes in the input data statistics. (Take for
247 * example a binary file with poorly compressible code followed by
248 * a highly compressible string table.) Smaller buffer sizes give
249 * fast adaptation but have of course the overhead of transmitting
250 * trees more frequently.
251 * - I can't count above 4
252 */
253
254 unsigned int sym_next; /* running index in sym_buf */
255 unsigned int sym_end; /* symbol table full when sym_next reaches this */
256
257 unsigned long opt_len; /* bit length of current block with optimal trees */
258 unsigned long static_len; /* bit length of current block with static trees */
259 unsigned int matches; /* number of string matches in current block */
260 unsigned int insert; /* bytes at end of window left to insert */
261
262#ifdef ZLIB_DEBUG
263 unsigned long compressed_len; /* total bit length of compressed file mod 2^32 */
264 unsigned long bits_sent; /* bit length of compressed data sent mod 2^32 */
265#endif
266
267 uint16_t bi_buf;
268 /* Output buffer. bits are inserted starting at the bottom (least
269 * significant bits).
270 */
271 int bi_valid;
272 /* Number of valid bits in bi_buf. All bits above the last valid bit
273 * are always zero.
274 */
275
276 unsigned long high_water;
277 /* High water mark offset in window for initialized bytes -- bytes above
278 * this are set to zero in order to avoid memory check warnings when
279 * longest match routines access bytes past the input. This is then
280 * updated to the new high water mark.
281 */
282 int block_open;
283 /* Whether or not a block is currently open for the QUICK deflation scheme.
284 * This is set to 1 if there is an active block, or 0 if the block was just
285 * closed.
286 */
287 int reproducible;
288 /* Whether reproducible compression results are required.
289 */
290
291} deflate_state;
292
293typedef enum {
294 need_more, /* block not completed, need more input or more output */
295 block_done, /* block flush performed */
296 finish_started, /* finish started, need only more output at next deflate */
297 finish_done /* finish done, accept no more input or output */
298} block_state;
299
300/* Output a byte on the stream.
301 * IN assertion: there is enough room in pending_buf.
302 */
303#define put_byte(s, c) {s->pending_buf[s->pending++] = (unsigned char)(c);}
304
305/* ===========================================================================
306 * Output a short LSB first on the stream.
307 * IN assertion: there is enough room in pendingBuf.
308 */
309static inline void put_short(deflate_state *s, uint16_t w) {
310#if BYTE_ORDER == BIG_ENDIAN
311 w = ZSWAP16(w);
312#endif
313 memcpy(&(s->pending_buf[s->pending]), &w, sizeof(uint16_t));
314 s->pending += 2;
315}
316
317#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
318/* Minimum amount of lookahead, except at the end of the input file.
319 * See deflate.c for comments about the MIN_MATCH+1.
320 */
321
322#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
323/* In order to simplify the code, particularly on 16 bit machines, match
324 * distances are limited to MAX_DIST instead of WSIZE.
325 */
326
327#define WIN_INIT MAX_MATCH
328/* Number of bytes after end of data in window to initialize in order to avoid
329 memory checker errors from longest match routines */
330
331
332void ZLIB_INTERNAL fill_window_c(deflate_state *s);
333void ZLIB_INTERNAL slide_hash_c(deflate_state *s);
334
335 /* in trees.c */
336void ZLIB_INTERNAL zng_tr_init(deflate_state *s);
337int ZLIB_INTERNAL zng_tr_tally(deflate_state *s, unsigned dist, unsigned lc);
338void ZLIB_INTERNAL zng_tr_flush_block(deflate_state *s, char *buf, unsigned long stored_len, int last);
339void ZLIB_INTERNAL zng_tr_flush_bits(deflate_state *s);
340void ZLIB_INTERNAL zng_tr_align(deflate_state *s);
341void ZLIB_INTERNAL zng_tr_stored_block(deflate_state *s, char *buf, unsigned long stored_len, int last);
342void ZLIB_INTERNAL bi_windup(deflate_state *s);
343unsigned ZLIB_INTERNAL bi_reverse(unsigned code, int len);
344void ZLIB_INTERNAL flush_pending(PREFIX3(streamp) strm);
345
346#define d_code(dist) ((dist) < 256 ? zng_dist_code[dist] : zng_dist_code[256+((dist)>>7)])
347/* Mapping from a distance to a distance code. dist is the distance - 1 and
348 * must not have side effects. zng_dist_code[256] and zng_dist_code[257] are never
349 * used.
350 */
351
352#ifndef ZLIB_DEBUG
353/* Inline versions of _tr_tally for speed: */
354
355 extern const unsigned char ZLIB_INTERNAL zng_length_code[];
356 extern const unsigned char ZLIB_INTERNAL zng_dist_code[];
357
358# define zng_tr_tally_lit(s, c, flush) \
359 { unsigned char cc = (c); \
360 s->sym_buf[s->sym_next++] = 0; \
361 s->sym_buf[s->sym_next++] = 0; \
362 s->sym_buf[s->sym_next++] = cc; \
363 s->dyn_ltree[cc].Freq++; \
364 flush = (s->sym_next == s->sym_end); \
365 }
366# define zng_tr_tally_dist(s, distance, length, flush) \
367 { unsigned char len = (unsigned char)(length); \
368 unsigned dist = (unsigned)(distance); \
369 s->sym_buf[s->sym_next++] = dist; \
370 s->sym_buf[s->sym_next++] = dist >> 8; \
371 s->sym_buf[s->sym_next++] = len; \
372 dist--; \
373 s->dyn_ltree[zng_length_code[len]+LITERALS+1].Freq++; \
374 s->dyn_dtree[d_code(dist)].Freq++; \
375 flush = (s->sym_next == s->sym_end); \
376 }
377#else
378# define zng_tr_tally_lit(s, c, flush) flush = zng_tr_tally(s, 0, c)
379# define zng_tr_tally_dist(s, distance, length, flush) \
380 flush = zng_tr_tally(s, (unsigned)(distance), (unsigned)(length))
381#endif
382
383/* ===========================================================================
384 * Update a hash value with the given input byte
385 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
386 * input characters, so that a running hash key can be computed from the
387 * previous key instead of complete recalculation each time.
388 */
389
390#ifdef NOT_TWEAK_COMPILER
391#define TRIGGER_LEVEL 6
392#else
393#define TRIGGER_LEVEL 5
394#endif
395
396#if defined(__x86_64__) || defined(_M_X64) || defined(__i386) || defined(_M_IX86)
397#define UPDATE_HASH(s, h, i) \
398 do {\
399 if (s->level < TRIGGER_LEVEL) \
400 h = (3483 * (s->window[i]) +\
401 23081* (s->window[i+1]) +\
402 6954 * (s->window[i+2]) +\
403 20947* (s->window[i+3])) & s->hash_mask;\
404 else\
405 h = (25881* (s->window[i]) +\
406 24674* (s->window[i+1]) +\
407 25811* (s->window[i+2])) & s->hash_mask;\
408 } while (0)
409#else
410# define UPDATE_HASH(s, h, i) (h = (((h) << s->hash_shift) ^ (s->window[i + (MIN_MATCH-1)])) & s->hash_mask)
411#endif
412
413#ifdef ZLIB_DEBUG
414 #define send_code(s, c, tree, bit_buf, bits_valid) { \
415 if (z_verbose > 2) { \
416 fprintf(stderr, "\ncd %3d ", (c)); \
417 } \
418 send_bits(s, tree[c].Code, tree[c].Len, bit_buf, bits_valid); \
419 }
420#else /* ZLIB_DEBUG */
421 /* Send a code of the given tree. c and tree must not have side effects */
422 #define send_code(s, c, tree, bit_buf, bits_valid) send_bits(s, tree[c].Code, tree[c].Len, bit_buf, bits_valid)
423#endif
424
425
426#ifdef ZLIB_DEBUG
427 #define send_debug_trace(s, value, length) {\
428 Tracevv((stderr, " l %2d v %4x ", length, value));\
429 Assert(length > 0 && length <= 15, "invalid length");\
430 s->bits_sent += (unsigned long)length;\
431 }
432#else
433 #define send_debug_trace(s, value, length) {}
434#endif
435
436/* If not enough room in bit_buf, use (valid) bits from bit_buf and
437 * (16 - bit_valid) bits from value, leaving (width - (16-bit_valid))
438 * unused bits in value.
439 */
440#define send_bits(s, t_val, t_len, bit_buf, bits_valid) {\
441 int val = t_val;\
442 int len = t_len;\
443 send_debug_trace(s, val, len);\
444 if (bits_valid > (int)Buf_size - len) {\
445 bit_buf |= (uint16_t)val << bits_valid;\
446 put_short(s, bit_buf);\
447 bit_buf = (uint16_t)val >> (Buf_size - bits_valid);\
448 bits_valid += len - Buf_size;\
449 } else {\
450 bit_buf |= (uint16_t)(val) << bits_valid;\
451 bits_valid += len;\
452 }\
453}
454
455#endif /* DEFLATE_H_ */
456