1 /* inffast.c -- fast decoding
2 * Copyright (C) 1995-2017 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6 #include "zbuild.h"
7 #include "zutil.h"
8 #include "inftrees.h"
9 #include "inflate.h"
10 #include "inffast.h"
11 #include "inflate_p.h"
12 #include "functable.h"
13
14
15 /* Load 64 bits from IN and place the bytes at offset BITS in the result. */
load_64_bits(const unsigned char * in,unsigned bits)16 static inline uint64_t load_64_bits(const unsigned char *in, unsigned bits) {
17 uint64_t chunk;
18 memcpy(&chunk, in, sizeof(chunk));
19
20 #if BYTE_ORDER == LITTLE_ENDIAN
21 return chunk << bits;
22 #else
23 return ZSWAP64(chunk) << bits;
24 #endif
25 }
26 /*
27 Decode literal, length, and distance codes and write out the resulting
28 literal and match bytes until either not enough input or output is
29 available, an end-of-block is encountered, or a data error is encountered.
30 When large enough input and output buffers are supplied to inflate(), for
31 example, a 16K input buffer and a 64K output buffer, more than 95% of the
32 inflate execution time is spent in this routine.
33
34 Entry assumptions:
35
36 state->mode == LEN
37 strm->avail_in >= INFLATE_FAST_MIN_HAVE
38 strm->avail_out >= INFLATE_FAST_MIN_LEFT
39 start >= strm->avail_out
40 state->bits < 8
41
42 On return, state->mode is one of:
43
44 LEN -- ran out of enough output space or enough available input
45 TYPE -- reached end of block code, inflate() to interpret next block
46 BAD -- error in block data
47
48 Notes:
49
50 - The maximum input bits used by a length/distance pair is 15 bits for the
51 length code, 5 bits for the length extra, 15 bits for the distance code,
52 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
53 Therefore if strm->avail_in >= 6, then there is enough input to avoid
54 checking for available input while decoding.
55
56 - On some architectures, it can be significantly faster (e.g. up to 1.2x
57 faster on x86_64) to load from strm->next_in 64 bits, or 8 bytes, at a
58 time, so INFLATE_FAST_MIN_HAVE == 8.
59
60 - The maximum bytes that a single length/distance pair can output is 258
61 bytes, which is the maximum length that can be coded. inflate_fast()
62 requires strm->avail_out >= 258 for each loop to avoid checking for
63 output space.
64 */
zng_inflate_fast(PREFIX3 (stream)* strm,unsigned long start)65 void Z_INTERNAL zng_inflate_fast(PREFIX3(stream) *strm, unsigned long start) {
66 /* start: inflate()'s starting value for strm->avail_out */
67 struct inflate_state *state;
68 z_const unsigned char *in; /* local strm->next_in */
69 const unsigned char *last; /* have enough input while in < last */
70 unsigned char *out; /* local strm->next_out */
71 unsigned char *beg; /* inflate()'s initial strm->next_out */
72 unsigned char *end; /* while out < end, enough space available */
73 unsigned char *safe; /* can use chunkcopy provided out < safe */
74 #ifdef INFLATE_STRICT
75 unsigned dmax; /* maximum distance from zlib header */
76 #endif
77 unsigned wsize; /* window size or zero if not using window */
78 unsigned whave; /* valid bytes in the window */
79 unsigned wnext; /* window write index */
80 unsigned char *window; /* allocated sliding window, if wsize != 0 */
81
82 /* hold is a local copy of strm->hold. By default, hold satisfies the same
83 invariants that strm->hold does, namely that (hold >> bits) == 0. This
84 invariant is kept by loading bits into hold one byte at a time, like:
85
86 hold |= next_byte_of_input << bits; in++; bits += 8;
87
88 If we need to ensure that bits >= 15 then this code snippet is simply
89 repeated. Over one iteration of the outermost do/while loop, this
90 happens up to six times (48 bits of input), as described in the NOTES
91 above.
92
93 However, on some little endian architectures, it can be significantly
94 faster to load 64 bits once instead of 8 bits six times:
95
96 if (bits <= 16) {
97 hold |= next_8_bytes_of_input << bits; in += 6; bits += 48;
98 }
99
100 Unlike the simpler one byte load, shifting the next_8_bytes_of_input
101 by bits will overflow and lose those high bits, up to 2 bytes' worth.
102 The conservative estimate is therefore that we have read only 6 bytes
103 (48 bits). Again, as per the NOTES above, 48 bits is sufficient for the
104 rest of the iteration, and we will not need to load another 8 bytes.
105
106 Inside this function, we no longer satisfy (hold >> bits) == 0, but
107 this is not problematic, even if that overflow does not land on an 8 bit
108 byte boundary. Those excess bits will eventually shift down lower as the
109 Huffman decoder consumes input, and when new input bits need to be loaded
110 into the bits variable, the same input bits will be or'ed over those
111 existing bits. A bitwise or is idempotent: (a | b | b) equals (a | b).
112 Note that we therefore write that load operation as "hold |= etc" and not
113 "hold += etc".
114
115 Outside that loop, at the end of the function, hold is bitwise and'ed
116 with (1<<bits)-1 to drop those excess bits so that, on function exit, we
117 keep the invariant that (state->hold >> state->bits) == 0.
118 */
119 uint64_t hold; /* local strm->hold */
120 unsigned bits; /* local strm->bits */
121 code const *lcode; /* local strm->lencode */
122 code const *dcode; /* local strm->distcode */
123 unsigned lmask; /* mask for first level of length codes */
124 unsigned dmask; /* mask for first level of distance codes */
125 const code *here; /* retrieved table entry */
126 unsigned op; /* code bits, operation, extra bits, or */
127 /* window position, window bytes to copy */
128 unsigned len; /* match length, unused bytes */
129 unsigned dist; /* match distance */
130 unsigned char *from; /* where to copy match from */
131
132 /* copy state to local variables */
133 state = (struct inflate_state *)strm->state;
134 in = strm->next_in;
135 last = in + (strm->avail_in - (INFLATE_FAST_MIN_HAVE - 1));
136 out = strm->next_out;
137 beg = out - (start - strm->avail_out);
138 end = out + (strm->avail_out - (INFLATE_FAST_MIN_LEFT - 1));
139 safe = out + strm->avail_out;
140 #ifdef INFLATE_STRICT
141 dmax = state->dmax;
142 #endif
143 wsize = state->wsize;
144 whave = state->whave;
145 wnext = state->wnext;
146 window = state->window;
147 hold = state->hold;
148 bits = state->bits;
149 lcode = state->lencode;
150 dcode = state->distcode;
151 lmask = (1U << state->lenbits) - 1;
152 dmask = (1U << state->distbits) - 1;
153
154 /* decode literals and length/distances until end-of-block or not enough
155 input data or output space */
156 do {
157 if (bits < 15) {
158 hold |= load_64_bits(in, bits);
159 in += 6;
160 bits += 48;
161 }
162 here = lcode + (hold & lmask);
163 dolen:
164 DROPBITS(here->bits);
165 op = here->op;
166 if (op == 0) { /* literal */
167 Tracevv((stderr, here->val >= 0x20 && here->val < 0x7f ?
168 "inflate: literal '%c'\n" :
169 "inflate: literal 0x%02x\n", here->val));
170 *out++ = (unsigned char)(here->val);
171 } else if (op & 16) { /* length base */
172 len = here->val;
173 op &= 15; /* number of extra bits */
174 if (bits < op) {
175 hold |= load_64_bits(in, bits);
176 in += 6;
177 bits += 48;
178 }
179 len += BITS(op);
180 DROPBITS(op);
181 Tracevv((stderr, "inflate: length %u\n", len));
182 if (bits < 15) {
183 hold |= load_64_bits(in, bits);
184 in += 6;
185 bits += 48;
186 }
187 here = dcode + (hold & dmask);
188 dodist:
189 DROPBITS(here->bits);
190 op = here->op;
191 if (op & 16) { /* distance base */
192 dist = here->val;
193 op &= 15; /* number of extra bits */
194 if (bits < op) {
195 hold |= load_64_bits(in, bits);
196 in += 6;
197 bits += 48;
198 }
199 dist += BITS(op);
200 #ifdef INFLATE_STRICT
201 if (dist > dmax) {
202 strm->msg = (char *)"invalid distance too far back";
203 state->mode = BAD;
204 break;
205 }
206 #endif
207 DROPBITS(op);
208 Tracevv((stderr, "inflate: distance %u\n", dist));
209 op = (unsigned)(out - beg); /* max distance in output */
210 if (dist > op) { /* see if copy from window */
211 op = dist - op; /* distance back in window */
212 if (op > whave) {
213 if (state->sane) {
214 strm->msg = (char *)"invalid distance too far back";
215 state->mode = BAD;
216 break;
217 }
218 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
219 if (len <= op - whave) {
220 do {
221 *out++ = 0;
222 } while (--len);
223 continue;
224 }
225 len -= op - whave;
226 do {
227 *out++ = 0;
228 } while (--op > whave);
229 if (op == 0) {
230 from = out - dist;
231 do {
232 *out++ = *from++;
233 } while (--len);
234 continue;
235 }
236 #endif
237 }
238 from = window;
239 if (wnext == 0) { /* very common case */
240 from += wsize - op;
241 } else if (wnext >= op) { /* contiguous in window */
242 from += wnext - op;
243 } else { /* wrap around window */
244 op -= wnext;
245 from += wsize - op;
246 if (op < len) { /* some from end of window */
247 len -= op;
248 out = functable.chunkcopy_safe(out, from, op, safe);
249 from = window; /* more from start of window */
250 op = wnext;
251 /* This (rare) case can create a situation where
252 the first chunkcopy below must be checked.
253 */
254 }
255 }
256 if (op < len) { /* still need some from output */
257 len -= op;
258 out = functable.chunkcopy_safe(out, from, op, safe);
259 out = functable.chunkunroll(out, &dist, &len);
260 out = functable.chunkcopy_safe(out, out - dist, len, safe);
261 } else {
262 out = functable.chunkcopy_safe(out, from, len, safe);
263 }
264 } else {
265 /* Whole reference is in range of current output. No
266 range checks are necessary because we start with room
267 for at least 258 bytes of output, so unroll and roundoff
268 operations can write beyond `out+len` so long as they
269 stay within 258 bytes of `out`.
270 */
271 if (dist >= len || dist >= state->chunksize)
272 out = functable.chunkcopy(out, out - dist, len);
273 else
274 out = functable.chunkmemset(out, dist, len);
275 }
276 } else if ((op & 64) == 0) { /* 2nd level distance code */
277 here = dcode + here->val + BITS(op);
278 goto dodist;
279 } else {
280 strm->msg = (char *)"invalid distance code";
281 state->mode = BAD;
282 break;
283 }
284 } else if ((op & 64) == 0) { /* 2nd level length code */
285 here = lcode + here->val + BITS(op);
286 goto dolen;
287 } else if (op & 32) { /* end-of-block */
288 Tracevv((stderr, "inflate: end of block\n"));
289 state->mode = TYPE;
290 break;
291 } else {
292 strm->msg = (char *)"invalid literal/length code";
293 state->mode = BAD;
294 break;
295 }
296 } while (in < last && out < end);
297
298 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
299 len = bits >> 3;
300 in -= len;
301 bits -= len << 3;
302 hold &= (UINT64_C(1) << bits) - 1;
303
304 /* update state and return */
305 strm->next_in = in;
306 strm->next_out = out;
307 strm->avail_in =
308 (unsigned)(in < last ? (INFLATE_FAST_MIN_HAVE - 1) + (last - in)
309 : (INFLATE_FAST_MIN_HAVE - 1) - (in - last));
310 strm->avail_out =
311 (unsigned)(out < end ? (INFLATE_FAST_MIN_LEFT - 1) + (end - out)
312 : (INFLATE_FAST_MIN_LEFT - 1) - (out - end));
313
314 Assert(bits <= 32, "Remaining bits greater than 32");
315 state->hold = (uint32_t)hold;
316 state->bits = bits;
317 return;
318 }
319
320 /*
321 inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
322 - Using bit fields for code structure
323 - Different op definition to avoid & for extra bits (do & for table bits)
324 - Three separate decoding do-loops for direct, window, and wnext == 0
325 - Special case for distance > 1 copies to do overlapped load and store copy
326 - Explicit branch predictions (based on measured branch probabilities)
327 - Deferring match copy and interspersed it with decoding subsequent codes
328 - Swapping literal/length else
329 - Swapping window/direct else
330 - Larger unrolled copy loops (three is about right)
331 - Moving len -= 3 statement into middle of loop
332 */
333