puff.c revision 1.1.1.2 1 1.1 christos /*
2 1.1 christos * puff.c
3 1.1.1.2 christos * Copyright (C) 2002-2013 Mark Adler
4 1.1 christos * For conditions of distribution and use, see copyright notice in puff.h
5 1.1.1.2 christos * version 2.3, 21 Jan 2013
6 1.1 christos *
7 1.1 christos * puff.c is a simple inflate written to be an unambiguous way to specify the
8 1.1 christos * deflate format. It is not written for speed but rather simplicity. As a
9 1.1 christos * side benefit, this code might actually be useful when small code is more
10 1.1 christos * important than speed, such as bootstrap applications. For typical deflate
11 1.1 christos * data, zlib's inflate() is about four times as fast as puff(). zlib's
12 1.1 christos * inflate compiles to around 20K on my machine, whereas puff.c compiles to
13 1.1 christos * around 4K on my machine (a PowerPC using GNU cc). If the faster decode()
14 1.1 christos * function here is used, then puff() is only twice as slow as zlib's
15 1.1 christos * inflate().
16 1.1 christos *
17 1.1 christos * All dynamically allocated memory comes from the stack. The stack required
18 1.1 christos * is less than 2K bytes. This code is compatible with 16-bit int's and
19 1.1 christos * assumes that long's are at least 32 bits. puff.c uses the short data type,
20 1.1 christos * assumed to be 16 bits, for arrays in order to to conserve memory. The code
21 1.1 christos * works whether integers are stored big endian or little endian.
22 1.1 christos *
23 1.1 christos * In the comments below are "Format notes" that describe the inflate process
24 1.1 christos * and document some of the less obvious aspects of the format. This source
25 1.1 christos * code is meant to supplement RFC 1951, which formally describes the deflate
26 1.1 christos * format:
27 1.1 christos *
28 1.1 christos * http://www.zlib.org/rfc-deflate.html
29 1.1 christos */
30 1.1 christos
31 1.1 christos /*
32 1.1 christos * Change history:
33 1.1 christos *
34 1.1 christos * 1.0 10 Feb 2002 - First version
35 1.1 christos * 1.1 17 Feb 2002 - Clarifications of some comments and notes
36 1.1 christos * - Update puff() dest and source pointers on negative
37 1.1 christos * errors to facilitate debugging deflators
38 1.1 christos * - Remove longest from struct huffman -- not needed
39 1.1 christos * - Simplify offs[] index in construct()
40 1.1 christos * - Add input size and checking, using longjmp() to
41 1.1 christos * maintain easy readability
42 1.1 christos * - Use short data type for large arrays
43 1.1 christos * - Use pointers instead of long to specify source and
44 1.1 christos * destination sizes to avoid arbitrary 4 GB limits
45 1.1 christos * 1.2 17 Mar 2002 - Add faster version of decode(), doubles speed (!),
46 1.1 christos * but leave simple version for readabilty
47 1.1 christos * - Make sure invalid distances detected if pointers
48 1.1 christos * are 16 bits
49 1.1 christos * - Fix fixed codes table error
50 1.1 christos * - Provide a scanning mode for determining size of
51 1.1 christos * uncompressed data
52 1.1 christos * 1.3 20 Mar 2002 - Go back to lengths for puff() parameters [Gailly]
53 1.1 christos * - Add a puff.h file for the interface
54 1.1 christos * - Add braces in puff() for else do [Gailly]
55 1.1 christos * - Use indexes instead of pointers for readability
56 1.1 christos * 1.4 31 Mar 2002 - Simplify construct() code set check
57 1.1 christos * - Fix some comments
58 1.1 christos * - Add FIXLCODES #define
59 1.1 christos * 1.5 6 Apr 2002 - Minor comment fixes
60 1.1 christos * 1.6 7 Aug 2002 - Minor format changes
61 1.1 christos * 1.7 3 Mar 2003 - Added test code for distribution
62 1.1 christos * - Added zlib-like license
63 1.1 christos * 1.8 9 Jan 2004 - Added some comments on no distance codes case
64 1.1 christos * 1.9 21 Feb 2008 - Fix bug on 16-bit integer architectures [Pohland]
65 1.1 christos * - Catch missing end-of-block symbol error
66 1.1 christos * 2.0 25 Jul 2008 - Add #define to permit distance too far back
67 1.1 christos * - Add option in TEST code for puff to write the data
68 1.1 christos * - Add option in TEST code to skip input bytes
69 1.1 christos * - Allow TEST code to read from piped stdin
70 1.1 christos * 2.1 4 Apr 2010 - Avoid variable initialization for happier compilers
71 1.1 christos * - Avoid unsigned comparisons for even happier compilers
72 1.1 christos * 2.2 25 Apr 2010 - Fix bug in variable initializations [Oberhumer]
73 1.1 christos * - Add const where appropriate [Oberhumer]
74 1.1 christos * - Split if's and ?'s for coverage testing
75 1.1 christos * - Break out test code to separate file
76 1.1 christos * - Move NIL to puff.h
77 1.1 christos * - Allow incomplete code only if single code length is 1
78 1.1 christos * - Add full code coverage test to Makefile
79 1.1.1.2 christos * 2.3 21 Jan 2013 - Check for invalid code length codes in dynamic blocks
80 1.1 christos */
81 1.1 christos
82 1.1 christos #include <setjmp.h> /* for setjmp(), longjmp(), and jmp_buf */
83 1.1 christos #include "puff.h" /* prototype for puff() */
84 1.1 christos
85 1.1 christos #define local static /* for local function definitions */
86 1.1 christos
87 1.1 christos /*
88 1.1 christos * Maximums for allocations and loops. It is not useful to change these --
89 1.1 christos * they are fixed by the deflate format.
90 1.1 christos */
91 1.1 christos #define MAXBITS 15 /* maximum bits in a code */
92 1.1 christos #define MAXLCODES 286 /* maximum number of literal/length codes */
93 1.1 christos #define MAXDCODES 30 /* maximum number of distance codes */
94 1.1 christos #define MAXCODES (MAXLCODES+MAXDCODES) /* maximum codes lengths to read */
95 1.1 christos #define FIXLCODES 288 /* number of fixed literal/length codes */
96 1.1 christos
97 1.1 christos /* input and output state */
98 1.1 christos struct state {
99 1.1 christos /* output state */
100 1.1 christos unsigned char *out; /* output buffer */
101 1.1 christos unsigned long outlen; /* available space at out */
102 1.1 christos unsigned long outcnt; /* bytes written to out so far */
103 1.1 christos
104 1.1 christos /* input state */
105 1.1 christos const unsigned char *in; /* input buffer */
106 1.1 christos unsigned long inlen; /* available input at in */
107 1.1 christos unsigned long incnt; /* bytes read so far */
108 1.1 christos int bitbuf; /* bit buffer */
109 1.1 christos int bitcnt; /* number of bits in bit buffer */
110 1.1 christos
111 1.1 christos /* input limit error return state for bits() and decode() */
112 1.1 christos jmp_buf env;
113 1.1 christos };
114 1.1 christos
115 1.1 christos /*
116 1.1 christos * Return need bits from the input stream. This always leaves less than
117 1.1 christos * eight bits in the buffer. bits() works properly for need == 0.
118 1.1 christos *
119 1.1 christos * Format notes:
120 1.1 christos *
121 1.1 christos * - Bits are stored in bytes from the least significant bit to the most
122 1.1 christos * significant bit. Therefore bits are dropped from the bottom of the bit
123 1.1 christos * buffer, using shift right, and new bytes are appended to the top of the
124 1.1 christos * bit buffer, using shift left.
125 1.1 christos */
126 1.1 christos local int bits(struct state *s, int need)
127 1.1 christos {
128 1.1 christos long val; /* bit accumulator (can use up to 20 bits) */
129 1.1 christos
130 1.1 christos /* load at least need bits into val */
131 1.1 christos val = s->bitbuf;
132 1.1 christos while (s->bitcnt < need) {
133 1.1 christos if (s->incnt == s->inlen)
134 1.1 christos longjmp(s->env, 1); /* out of input */
135 1.1 christos val |= (long)(s->in[s->incnt++]) << s->bitcnt; /* load eight bits */
136 1.1 christos s->bitcnt += 8;
137 1.1 christos }
138 1.1 christos
139 1.1 christos /* drop need bits and update buffer, always zero to seven bits left */
140 1.1 christos s->bitbuf = (int)(val >> need);
141 1.1 christos s->bitcnt -= need;
142 1.1 christos
143 1.1 christos /* return need bits, zeroing the bits above that */
144 1.1 christos return (int)(val & ((1L << need) - 1));
145 1.1 christos }
146 1.1 christos
147 1.1 christos /*
148 1.1 christos * Process a stored block.
149 1.1 christos *
150 1.1 christos * Format notes:
151 1.1 christos *
152 1.1 christos * - After the two-bit stored block type (00), the stored block length and
153 1.1 christos * stored bytes are byte-aligned for fast copying. Therefore any leftover
154 1.1 christos * bits in the byte that has the last bit of the type, as many as seven, are
155 1.1 christos * discarded. The value of the discarded bits are not defined and should not
156 1.1 christos * be checked against any expectation.
157 1.1 christos *
158 1.1 christos * - The second inverted copy of the stored block length does not have to be
159 1.1 christos * checked, but it's probably a good idea to do so anyway.
160 1.1 christos *
161 1.1 christos * - A stored block can have zero length. This is sometimes used to byte-align
162 1.1 christos * subsets of the compressed data for random access or partial recovery.
163 1.1 christos */
164 1.1 christos local int stored(struct state *s)
165 1.1 christos {
166 1.1 christos unsigned len; /* length of stored block */
167 1.1 christos
168 1.1 christos /* discard leftover bits from current byte (assumes s->bitcnt < 8) */
169 1.1 christos s->bitbuf = 0;
170 1.1 christos s->bitcnt = 0;
171 1.1 christos
172 1.1 christos /* get length and check against its one's complement */
173 1.1 christos if (s->incnt + 4 > s->inlen)
174 1.1 christos return 2; /* not enough input */
175 1.1 christos len = s->in[s->incnt++];
176 1.1 christos len |= s->in[s->incnt++] << 8;
177 1.1 christos if (s->in[s->incnt++] != (~len & 0xff) ||
178 1.1 christos s->in[s->incnt++] != ((~len >> 8) & 0xff))
179 1.1 christos return -2; /* didn't match complement! */
180 1.1 christos
181 1.1 christos /* copy len bytes from in to out */
182 1.1 christos if (s->incnt + len > s->inlen)
183 1.1 christos return 2; /* not enough input */
184 1.1 christos if (s->out != NIL) {
185 1.1 christos if (s->outcnt + len > s->outlen)
186 1.1 christos return 1; /* not enough output space */
187 1.1 christos while (len--)
188 1.1 christos s->out[s->outcnt++] = s->in[s->incnt++];
189 1.1 christos }
190 1.1 christos else { /* just scanning */
191 1.1 christos s->outcnt += len;
192 1.1 christos s->incnt += len;
193 1.1 christos }
194 1.1 christos
195 1.1 christos /* done with a valid stored block */
196 1.1 christos return 0;
197 1.1 christos }
198 1.1 christos
199 1.1 christos /*
200 1.1 christos * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of
201 1.1 christos * each length, which for a canonical code are stepped through in order.
202 1.1 christos * symbol[] are the symbol values in canonical order, where the number of
203 1.1 christos * entries is the sum of the counts in count[]. The decoding process can be
204 1.1 christos * seen in the function decode() below.
205 1.1 christos */
206 1.1 christos struct huffman {
207 1.1 christos short *count; /* number of symbols of each length */
208 1.1 christos short *symbol; /* canonically ordered symbols */
209 1.1 christos };
210 1.1 christos
211 1.1 christos /*
212 1.1 christos * Decode a code from the stream s using huffman table h. Return the symbol or
213 1.1 christos * a negative value if there is an error. If all of the lengths are zero, i.e.
214 1.1 christos * an empty code, or if the code is incomplete and an invalid code is received,
215 1.1 christos * then -10 is returned after reading MAXBITS bits.
216 1.1 christos *
217 1.1 christos * Format notes:
218 1.1 christos *
219 1.1 christos * - The codes as stored in the compressed data are bit-reversed relative to
220 1.1 christos * a simple integer ordering of codes of the same lengths. Hence below the
221 1.1 christos * bits are pulled from the compressed data one at a time and used to
222 1.1 christos * build the code value reversed from what is in the stream in order to
223 1.1 christos * permit simple integer comparisons for decoding. A table-based decoding
224 1.1 christos * scheme (as used in zlib) does not need to do this reversal.
225 1.1 christos *
226 1.1 christos * - The first code for the shortest length is all zeros. Subsequent codes of
227 1.1 christos * the same length are simply integer increments of the previous code. When
228 1.1 christos * moving up a length, a zero bit is appended to the code. For a complete
229 1.1 christos * code, the last code of the longest length will be all ones.
230 1.1 christos *
231 1.1 christos * - Incomplete codes are handled by this decoder, since they are permitted
232 1.1 christos * in the deflate format. See the format notes for fixed() and dynamic().
233 1.1 christos */
234 1.1 christos #ifdef SLOW
235 1.1 christos local int decode(struct state *s, const struct huffman *h)
236 1.1 christos {
237 1.1 christos int len; /* current number of bits in code */
238 1.1 christos int code; /* len bits being decoded */
239 1.1 christos int first; /* first code of length len */
240 1.1 christos int count; /* number of codes of length len */
241 1.1 christos int index; /* index of first code of length len in symbol table */
242 1.1 christos
243 1.1 christos code = first = index = 0;
244 1.1 christos for (len = 1; len <= MAXBITS; len++) {
245 1.1 christos code |= bits(s, 1); /* get next bit */
246 1.1 christos count = h->count[len];
247 1.1 christos if (code - count < first) /* if length len, return symbol */
248 1.1 christos return h->symbol[index + (code - first)];
249 1.1 christos index += count; /* else update for next length */
250 1.1 christos first += count;
251 1.1 christos first <<= 1;
252 1.1 christos code <<= 1;
253 1.1 christos }
254 1.1 christos return -10; /* ran out of codes */
255 1.1 christos }
256 1.1 christos
257 1.1 christos /*
258 1.1 christos * A faster version of decode() for real applications of this code. It's not
259 1.1 christos * as readable, but it makes puff() twice as fast. And it only makes the code
260 1.1 christos * a few percent larger.
261 1.1 christos */
262 1.1 christos #else /* !SLOW */
263 1.1 christos local int decode(struct state *s, const struct huffman *h)
264 1.1 christos {
265 1.1 christos int len; /* current number of bits in code */
266 1.1 christos int code; /* len bits being decoded */
267 1.1 christos int first; /* first code of length len */
268 1.1 christos int count; /* number of codes of length len */
269 1.1 christos int index; /* index of first code of length len in symbol table */
270 1.1 christos int bitbuf; /* bits from stream */
271 1.1 christos int left; /* bits left in next or left to process */
272 1.1 christos short *next; /* next number of codes */
273 1.1 christos
274 1.1 christos bitbuf = s->bitbuf;
275 1.1 christos left = s->bitcnt;
276 1.1 christos code = first = index = 0;
277 1.1 christos len = 1;
278 1.1 christos next = h->count + 1;
279 1.1 christos while (1) {
280 1.1 christos while (left--) {
281 1.1 christos code |= bitbuf & 1;
282 1.1 christos bitbuf >>= 1;
283 1.1 christos count = *next++;
284 1.1 christos if (code - count < first) { /* if length len, return symbol */
285 1.1 christos s->bitbuf = bitbuf;
286 1.1 christos s->bitcnt = (s->bitcnt - len) & 7;
287 1.1 christos return h->symbol[index + (code - first)];
288 1.1 christos }
289 1.1 christos index += count; /* else update for next length */
290 1.1 christos first += count;
291 1.1 christos first <<= 1;
292 1.1 christos code <<= 1;
293 1.1 christos len++;
294 1.1 christos }
295 1.1 christos left = (MAXBITS+1) - len;
296 1.1 christos if (left == 0)
297 1.1 christos break;
298 1.1 christos if (s->incnt == s->inlen)
299 1.1 christos longjmp(s->env, 1); /* out of input */
300 1.1 christos bitbuf = s->in[s->incnt++];
301 1.1 christos if (left > 8)
302 1.1 christos left = 8;
303 1.1 christos }
304 1.1 christos return -10; /* ran out of codes */
305 1.1 christos }
306 1.1 christos #endif /* SLOW */
307 1.1 christos
308 1.1 christos /*
309 1.1 christos * Given the list of code lengths length[0..n-1] representing a canonical
310 1.1 christos * Huffman code for n symbols, construct the tables required to decode those
311 1.1 christos * codes. Those tables are the number of codes of each length, and the symbols
312 1.1 christos * sorted by length, retaining their original order within each length. The
313 1.1 christos * return value is zero for a complete code set, negative for an over-
314 1.1 christos * subscribed code set, and positive for an incomplete code set. The tables
315 1.1 christos * can be used if the return value is zero or positive, but they cannot be used
316 1.1 christos * if the return value is negative. If the return value is zero, it is not
317 1.1 christos * possible for decode() using that table to return an error--any stream of
318 1.1 christos * enough bits will resolve to a symbol. If the return value is positive, then
319 1.1 christos * it is possible for decode() using that table to return an error for received
320 1.1 christos * codes past the end of the incomplete lengths.
321 1.1 christos *
322 1.1 christos * Not used by decode(), but used for error checking, h->count[0] is the number
323 1.1 christos * of the n symbols not in the code. So n - h->count[0] is the number of
324 1.1 christos * codes. This is useful for checking for incomplete codes that have more than
325 1.1 christos * one symbol, which is an error in a dynamic block.
326 1.1 christos *
327 1.1 christos * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS
328 1.1 christos * This is assured by the construction of the length arrays in dynamic() and
329 1.1 christos * fixed() and is not verified by construct().
330 1.1 christos *
331 1.1 christos * Format notes:
332 1.1 christos *
333 1.1 christos * - Permitted and expected examples of incomplete codes are one of the fixed
334 1.1 christos * codes and any code with a single symbol which in deflate is coded as one
335 1.1 christos * bit instead of zero bits. See the format notes for fixed() and dynamic().
336 1.1 christos *
337 1.1 christos * - Within a given code length, the symbols are kept in ascending order for
338 1.1 christos * the code bits definition.
339 1.1 christos */
340 1.1 christos local int construct(struct huffman *h, const short *length, int n)
341 1.1 christos {
342 1.1 christos int symbol; /* current symbol when stepping through length[] */
343 1.1 christos int len; /* current length when stepping through h->count[] */
344 1.1 christos int left; /* number of possible codes left of current length */
345 1.1 christos short offs[MAXBITS+1]; /* offsets in symbol table for each length */
346 1.1 christos
347 1.1 christos /* count number of codes of each length */
348 1.1 christos for (len = 0; len <= MAXBITS; len++)
349 1.1 christos h->count[len] = 0;
350 1.1 christos for (symbol = 0; symbol < n; symbol++)
351 1.1 christos (h->count[length[symbol]])++; /* assumes lengths are within bounds */
352 1.1 christos if (h->count[0] == n) /* no codes! */
353 1.1 christos return 0; /* complete, but decode() will fail */
354 1.1 christos
355 1.1 christos /* check for an over-subscribed or incomplete set of lengths */
356 1.1 christos left = 1; /* one possible code of zero length */
357 1.1 christos for (len = 1; len <= MAXBITS; len++) {
358 1.1 christos left <<= 1; /* one more bit, double codes left */
359 1.1 christos left -= h->count[len]; /* deduct count from possible codes */
360 1.1 christos if (left < 0)
361 1.1 christos return left; /* over-subscribed--return negative */
362 1.1 christos } /* left > 0 means incomplete */
363 1.1 christos
364 1.1 christos /* generate offsets into symbol table for each length for sorting */
365 1.1 christos offs[1] = 0;
366 1.1 christos for (len = 1; len < MAXBITS; len++)
367 1.1 christos offs[len + 1] = offs[len] + h->count[len];
368 1.1 christos
369 1.1 christos /*
370 1.1 christos * put symbols in table sorted by length, by symbol order within each
371 1.1 christos * length
372 1.1 christos */
373 1.1 christos for (symbol = 0; symbol < n; symbol++)
374 1.1 christos if (length[symbol] != 0)
375 1.1 christos h->symbol[offs[length[symbol]]++] = symbol;
376 1.1 christos
377 1.1 christos /* return zero for complete set, positive for incomplete set */
378 1.1 christos return left;
379 1.1 christos }
380 1.1 christos
381 1.1 christos /*
382 1.1 christos * Decode literal/length and distance codes until an end-of-block code.
383 1.1 christos *
384 1.1 christos * Format notes:
385 1.1 christos *
386 1.1 christos * - Compressed data that is after the block type if fixed or after the code
387 1.1 christos * description if dynamic is a combination of literals and length/distance
388 1.1 christos * pairs terminated by and end-of-block code. Literals are simply Huffman
389 1.1 christos * coded bytes. A length/distance pair is a coded length followed by a
390 1.1 christos * coded distance to represent a string that occurs earlier in the
391 1.1 christos * uncompressed data that occurs again at the current location.
392 1.1 christos *
393 1.1 christos * - Literals, lengths, and the end-of-block code are combined into a single
394 1.1 christos * code of up to 286 symbols. They are 256 literals (0..255), 29 length
395 1.1 christos * symbols (257..285), and the end-of-block symbol (256).
396 1.1 christos *
397 1.1 christos * - There are 256 possible lengths (3..258), and so 29 symbols are not enough
398 1.1 christos * to represent all of those. Lengths 3..10 and 258 are in fact represented
399 1.1 christos * by just a length symbol. Lengths 11..257 are represented as a symbol and
400 1.1 christos * some number of extra bits that are added as an integer to the base length
401 1.1 christos * of the length symbol. The number of extra bits is determined by the base
402 1.1 christos * length symbol. These are in the static arrays below, lens[] for the base
403 1.1 christos * lengths and lext[] for the corresponding number of extra bits.
404 1.1 christos *
405 1.1 christos * - The reason that 258 gets its own symbol is that the longest length is used
406 1.1 christos * often in highly redundant files. Note that 258 can also be coded as the
407 1.1 christos * base value 227 plus the maximum extra value of 31. While a good deflate
408 1.1 christos * should never do this, it is not an error, and should be decoded properly.
409 1.1 christos *
410 1.1 christos * - If a length is decoded, including its extra bits if any, then it is
411 1.1 christos * followed a distance code. There are up to 30 distance symbols. Again
412 1.1 christos * there are many more possible distances (1..32768), so extra bits are added
413 1.1 christos * to a base value represented by the symbol. The distances 1..4 get their
414 1.1 christos * own symbol, but the rest require extra bits. The base distances and
415 1.1 christos * corresponding number of extra bits are below in the static arrays dist[]
416 1.1 christos * and dext[].
417 1.1 christos *
418 1.1 christos * - Literal bytes are simply written to the output. A length/distance pair is
419 1.1 christos * an instruction to copy previously uncompressed bytes to the output. The
420 1.1 christos * copy is from distance bytes back in the output stream, copying for length
421 1.1 christos * bytes.
422 1.1 christos *
423 1.1 christos * - Distances pointing before the beginning of the output data are not
424 1.1 christos * permitted.
425 1.1 christos *
426 1.1 christos * - Overlapped copies, where the length is greater than the distance, are
427 1.1 christos * allowed and common. For example, a distance of one and a length of 258
428 1.1 christos * simply copies the last byte 258 times. A distance of four and a length of
429 1.1 christos * twelve copies the last four bytes three times. A simple forward copy
430 1.1 christos * ignoring whether the length is greater than the distance or not implements
431 1.1 christos * this correctly. You should not use memcpy() since its behavior is not
432 1.1 christos * defined for overlapped arrays. You should not use memmove() or bcopy()
433 1.1 christos * since though their behavior -is- defined for overlapping arrays, it is
434 1.1 christos * defined to do the wrong thing in this case.
435 1.1 christos */
436 1.1 christos local int codes(struct state *s,
437 1.1 christos const struct huffman *lencode,
438 1.1 christos const struct huffman *distcode)
439 1.1 christos {
440 1.1 christos int symbol; /* decoded symbol */
441 1.1 christos int len; /* length for copy */
442 1.1 christos unsigned dist; /* distance for copy */
443 1.1 christos static const short lens[29] = { /* Size base for length codes 257..285 */
444 1.1 christos 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
445 1.1 christos 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
446 1.1 christos static const short lext[29] = { /* Extra bits for length codes 257..285 */
447 1.1 christos 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
448 1.1 christos 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
449 1.1 christos static const short dists[30] = { /* Offset base for distance codes 0..29 */
450 1.1 christos 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
451 1.1 christos 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
452 1.1 christos 8193, 12289, 16385, 24577};
453 1.1 christos static const short dext[30] = { /* Extra bits for distance codes 0..29 */
454 1.1 christos 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
455 1.1 christos 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
456 1.1 christos 12, 12, 13, 13};
457 1.1 christos
458 1.1 christos /* decode literals and length/distance pairs */
459 1.1 christos do {
460 1.1 christos symbol = decode(s, lencode);
461 1.1 christos if (symbol < 0)
462 1.1 christos return symbol; /* invalid symbol */
463 1.1 christos if (symbol < 256) { /* literal: symbol is the byte */
464 1.1 christos /* write out the literal */
465 1.1 christos if (s->out != NIL) {
466 1.1 christos if (s->outcnt == s->outlen)
467 1.1 christos return 1;
468 1.1 christos s->out[s->outcnt] = symbol;
469 1.1 christos }
470 1.1 christos s->outcnt++;
471 1.1 christos }
472 1.1 christos else if (symbol > 256) { /* length */
473 1.1 christos /* get and compute length */
474 1.1 christos symbol -= 257;
475 1.1 christos if (symbol >= 29)
476 1.1 christos return -10; /* invalid fixed code */
477 1.1 christos len = lens[symbol] + bits(s, lext[symbol]);
478 1.1 christos
479 1.1 christos /* get and check distance */
480 1.1 christos symbol = decode(s, distcode);
481 1.1 christos if (symbol < 0)
482 1.1 christos return symbol; /* invalid symbol */
483 1.1 christos dist = dists[symbol] + bits(s, dext[symbol]);
484 1.1 christos #ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
485 1.1 christos if (dist > s->outcnt)
486 1.1 christos return -11; /* distance too far back */
487 1.1 christos #endif
488 1.1 christos
489 1.1 christos /* copy length bytes from distance bytes back */
490 1.1 christos if (s->out != NIL) {
491 1.1 christos if (s->outcnt + len > s->outlen)
492 1.1 christos return 1;
493 1.1 christos while (len--) {
494 1.1 christos s->out[s->outcnt] =
495 1.1 christos #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
496 1.1 christos dist > s->outcnt ?
497 1.1 christos 0 :
498 1.1 christos #endif
499 1.1 christos s->out[s->outcnt - dist];
500 1.1 christos s->outcnt++;
501 1.1 christos }
502 1.1 christos }
503 1.1 christos else
504 1.1 christos s->outcnt += len;
505 1.1 christos }
506 1.1 christos } while (symbol != 256); /* end of block symbol */
507 1.1 christos
508 1.1 christos /* done with a valid fixed or dynamic block */
509 1.1 christos return 0;
510 1.1 christos }
511 1.1 christos
512 1.1 christos /*
513 1.1 christos * Process a fixed codes block.
514 1.1 christos *
515 1.1 christos * Format notes:
516 1.1 christos *
517 1.1 christos * - This block type can be useful for compressing small amounts of data for
518 1.1 christos * which the size of the code descriptions in a dynamic block exceeds the
519 1.1 christos * benefit of custom codes for that block. For fixed codes, no bits are
520 1.1 christos * spent on code descriptions. Instead the code lengths for literal/length
521 1.1 christos * codes and distance codes are fixed. The specific lengths for each symbol
522 1.1 christos * can be seen in the "for" loops below.
523 1.1 christos *
524 1.1 christos * - The literal/length code is complete, but has two symbols that are invalid
525 1.1 christos * and should result in an error if received. This cannot be implemented
526 1.1 christos * simply as an incomplete code since those two symbols are in the "middle"
527 1.1 christos * of the code. They are eight bits long and the longest literal/length\
528 1.1 christos * code is nine bits. Therefore the code must be constructed with those
529 1.1 christos * symbols, and the invalid symbols must be detected after decoding.
530 1.1 christos *
531 1.1 christos * - The fixed distance codes also have two invalid symbols that should result
532 1.1 christos * in an error if received. Since all of the distance codes are the same
533 1.1 christos * length, this can be implemented as an incomplete code. Then the invalid
534 1.1 christos * codes are detected while decoding.
535 1.1 christos */
536 1.1 christos local int fixed(struct state *s)
537 1.1 christos {
538 1.1 christos static int virgin = 1;
539 1.1 christos static short lencnt[MAXBITS+1], lensym[FIXLCODES];
540 1.1 christos static short distcnt[MAXBITS+1], distsym[MAXDCODES];
541 1.1 christos static struct huffman lencode, distcode;
542 1.1 christos
543 1.1 christos /* build fixed huffman tables if first call (may not be thread safe) */
544 1.1 christos if (virgin) {
545 1.1 christos int symbol;
546 1.1 christos short lengths[FIXLCODES];
547 1.1 christos
548 1.1 christos /* construct lencode and distcode */
549 1.1 christos lencode.count = lencnt;
550 1.1 christos lencode.symbol = lensym;
551 1.1 christos distcode.count = distcnt;
552 1.1 christos distcode.symbol = distsym;
553 1.1 christos
554 1.1 christos /* literal/length table */
555 1.1 christos for (symbol = 0; symbol < 144; symbol++)
556 1.1 christos lengths[symbol] = 8;
557 1.1 christos for (; symbol < 256; symbol++)
558 1.1 christos lengths[symbol] = 9;
559 1.1 christos for (; symbol < 280; symbol++)
560 1.1 christos lengths[symbol] = 7;
561 1.1 christos for (; symbol < FIXLCODES; symbol++)
562 1.1 christos lengths[symbol] = 8;
563 1.1 christos construct(&lencode, lengths, FIXLCODES);
564 1.1 christos
565 1.1 christos /* distance table */
566 1.1 christos for (symbol = 0; symbol < MAXDCODES; symbol++)
567 1.1 christos lengths[symbol] = 5;
568 1.1 christos construct(&distcode, lengths, MAXDCODES);
569 1.1 christos
570 1.1 christos /* do this just once */
571 1.1 christos virgin = 0;
572 1.1 christos }
573 1.1 christos
574 1.1 christos /* decode data until end-of-block code */
575 1.1 christos return codes(s, &lencode, &distcode);
576 1.1 christos }
577 1.1 christos
578 1.1 christos /*
579 1.1 christos * Process a dynamic codes block.
580 1.1 christos *
581 1.1 christos * Format notes:
582 1.1 christos *
583 1.1 christos * - A dynamic block starts with a description of the literal/length and
584 1.1 christos * distance codes for that block. New dynamic blocks allow the compressor to
585 1.1 christos * rapidly adapt to changing data with new codes optimized for that data.
586 1.1 christos *
587 1.1 christos * - The codes used by the deflate format are "canonical", which means that
588 1.1 christos * the actual bits of the codes are generated in an unambiguous way simply
589 1.1 christos * from the number of bits in each code. Therefore the code descriptions
590 1.1 christos * are simply a list of code lengths for each symbol.
591 1.1 christos *
592 1.1 christos * - The code lengths are stored in order for the symbols, so lengths are
593 1.1 christos * provided for each of the literal/length symbols, and for each of the
594 1.1 christos * distance symbols.
595 1.1 christos *
596 1.1 christos * - If a symbol is not used in the block, this is represented by a zero as
597 1.1 christos * as the code length. This does not mean a zero-length code, but rather
598 1.1 christos * that no code should be created for this symbol. There is no way in the
599 1.1 christos * deflate format to represent a zero-length code.
600 1.1 christos *
601 1.1 christos * - The maximum number of bits in a code is 15, so the possible lengths for
602 1.1 christos * any code are 1..15.
603 1.1 christos *
604 1.1 christos * - The fact that a length of zero is not permitted for a code has an
605 1.1 christos * interesting consequence. Normally if only one symbol is used for a given
606 1.1 christos * code, then in fact that code could be represented with zero bits. However
607 1.1 christos * in deflate, that code has to be at least one bit. So for example, if
608 1.1 christos * only a single distance base symbol appears in a block, then it will be
609 1.1 christos * represented by a single code of length one, in particular one 0 bit. This
610 1.1 christos * is an incomplete code, since if a 1 bit is received, it has no meaning,
611 1.1 christos * and should result in an error. So incomplete distance codes of one symbol
612 1.1 christos * should be permitted, and the receipt of invalid codes should be handled.
613 1.1 christos *
614 1.1 christos * - It is also possible to have a single literal/length code, but that code
615 1.1 christos * must be the end-of-block code, since every dynamic block has one. This
616 1.1 christos * is not the most efficient way to create an empty block (an empty fixed
617 1.1 christos * block is fewer bits), but it is allowed by the format. So incomplete
618 1.1 christos * literal/length codes of one symbol should also be permitted.
619 1.1 christos *
620 1.1 christos * - If there are only literal codes and no lengths, then there are no distance
621 1.1 christos * codes. This is represented by one distance code with zero bits.
622 1.1 christos *
623 1.1 christos * - The list of up to 286 length/literal lengths and up to 30 distance lengths
624 1.1 christos * are themselves compressed using Huffman codes and run-length encoding. In
625 1.1 christos * the list of code lengths, a 0 symbol means no code, a 1..15 symbol means
626 1.1 christos * that length, and the symbols 16, 17, and 18 are run-length instructions.
627 1.1 christos * Each of 16, 17, and 18 are follwed by extra bits to define the length of
628 1.1 christos * the run. 16 copies the last length 3 to 6 times. 17 represents 3 to 10
629 1.1 christos * zero lengths, and 18 represents 11 to 138 zero lengths. Unused symbols
630 1.1 christos * are common, hence the special coding for zero lengths.
631 1.1 christos *
632 1.1 christos * - The symbols for 0..18 are Huffman coded, and so that code must be
633 1.1 christos * described first. This is simply a sequence of up to 19 three-bit values
634 1.1 christos * representing no code (0) or the code length for that symbol (1..7).
635 1.1 christos *
636 1.1 christos * - A dynamic block starts with three fixed-size counts from which is computed
637 1.1 christos * the number of literal/length code lengths, the number of distance code
638 1.1 christos * lengths, and the number of code length code lengths (ok, you come up with
639 1.1 christos * a better name!) in the code descriptions. For the literal/length and
640 1.1 christos * distance codes, lengths after those provided are considered zero, i.e. no
641 1.1 christos * code. The code length code lengths are received in a permuted order (see
642 1.1 christos * the order[] array below) to make a short code length code length list more
643 1.1 christos * likely. As it turns out, very short and very long codes are less likely
644 1.1 christos * to be seen in a dynamic code description, hence what may appear initially
645 1.1 christos * to be a peculiar ordering.
646 1.1 christos *
647 1.1 christos * - Given the number of literal/length code lengths (nlen) and distance code
648 1.1 christos * lengths (ndist), then they are treated as one long list of nlen + ndist
649 1.1 christos * code lengths. Therefore run-length coding can and often does cross the
650 1.1 christos * boundary between the two sets of lengths.
651 1.1 christos *
652 1.1 christos * - So to summarize, the code description at the start of a dynamic block is
653 1.1 christos * three counts for the number of code lengths for the literal/length codes,
654 1.1 christos * the distance codes, and the code length codes. This is followed by the
655 1.1 christos * code length code lengths, three bits each. This is used to construct the
656 1.1 christos * code length code which is used to read the remainder of the lengths. Then
657 1.1 christos * the literal/length code lengths and distance lengths are read as a single
658 1.1 christos * set of lengths using the code length codes. Codes are constructed from
659 1.1 christos * the resulting two sets of lengths, and then finally you can start
660 1.1 christos * decoding actual compressed data in the block.
661 1.1 christos *
662 1.1 christos * - For reference, a "typical" size for the code description in a dynamic
663 1.1 christos * block is around 80 bytes.
664 1.1 christos */
665 1.1 christos local int dynamic(struct state *s)
666 1.1 christos {
667 1.1 christos int nlen, ndist, ncode; /* number of lengths in descriptor */
668 1.1 christos int index; /* index of lengths[] */
669 1.1 christos int err; /* construct() return value */
670 1.1 christos short lengths[MAXCODES]; /* descriptor code lengths */
671 1.1 christos short lencnt[MAXBITS+1], lensym[MAXLCODES]; /* lencode memory */
672 1.1 christos short distcnt[MAXBITS+1], distsym[MAXDCODES]; /* distcode memory */
673 1.1 christos struct huffman lencode, distcode; /* length and distance codes */
674 1.1 christos static const short order[19] = /* permutation of code length codes */
675 1.1 christos {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
676 1.1 christos
677 1.1 christos /* construct lencode and distcode */
678 1.1 christos lencode.count = lencnt;
679 1.1 christos lencode.symbol = lensym;
680 1.1 christos distcode.count = distcnt;
681 1.1 christos distcode.symbol = distsym;
682 1.1 christos
683 1.1 christos /* get number of lengths in each table, check lengths */
684 1.1 christos nlen = bits(s, 5) + 257;
685 1.1 christos ndist = bits(s, 5) + 1;
686 1.1 christos ncode = bits(s, 4) + 4;
687 1.1 christos if (nlen > MAXLCODES || ndist > MAXDCODES)
688 1.1 christos return -3; /* bad counts */
689 1.1 christos
690 1.1 christos /* read code length code lengths (really), missing lengths are zero */
691 1.1 christos for (index = 0; index < ncode; index++)
692 1.1 christos lengths[order[index]] = bits(s, 3);
693 1.1 christos for (; index < 19; index++)
694 1.1 christos lengths[order[index]] = 0;
695 1.1 christos
696 1.1 christos /* build huffman table for code lengths codes (use lencode temporarily) */
697 1.1 christos err = construct(&lencode, lengths, 19);
698 1.1 christos if (err != 0) /* require complete code set here */
699 1.1 christos return -4;
700 1.1 christos
701 1.1 christos /* read length/literal and distance code length tables */
702 1.1 christos index = 0;
703 1.1 christos while (index < nlen + ndist) {
704 1.1 christos int symbol; /* decoded value */
705 1.1 christos int len; /* last length to repeat */
706 1.1 christos
707 1.1 christos symbol = decode(s, &lencode);
708 1.1.1.2 christos if (symbol < 0)
709 1.1.1.2 christos return symbol; /* invalid symbol */
710 1.1 christos if (symbol < 16) /* length in 0..15 */
711 1.1 christos lengths[index++] = symbol;
712 1.1 christos else { /* repeat instruction */
713 1.1 christos len = 0; /* assume repeating zeros */
714 1.1 christos if (symbol == 16) { /* repeat last length 3..6 times */
715 1.1 christos if (index == 0)
716 1.1 christos return -5; /* no last length! */
717 1.1 christos len = lengths[index - 1]; /* last length */
718 1.1 christos symbol = 3 + bits(s, 2);
719 1.1 christos }
720 1.1 christos else if (symbol == 17) /* repeat zero 3..10 times */
721 1.1 christos symbol = 3 + bits(s, 3);
722 1.1 christos else /* == 18, repeat zero 11..138 times */
723 1.1 christos symbol = 11 + bits(s, 7);
724 1.1 christos if (index + symbol > nlen + ndist)
725 1.1 christos return -6; /* too many lengths! */
726 1.1 christos while (symbol--) /* repeat last or zero symbol times */
727 1.1 christos lengths[index++] = len;
728 1.1 christos }
729 1.1 christos }
730 1.1 christos
731 1.1 christos /* check for end-of-block code -- there better be one! */
732 1.1 christos if (lengths[256] == 0)
733 1.1 christos return -9;
734 1.1 christos
735 1.1 christos /* build huffman table for literal/length codes */
736 1.1 christos err = construct(&lencode, lengths, nlen);
737 1.1 christos if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1]))
738 1.1 christos return -7; /* incomplete code ok only for single length 1 code */
739 1.1 christos
740 1.1 christos /* build huffman table for distance codes */
741 1.1 christos err = construct(&distcode, lengths + nlen, ndist);
742 1.1 christos if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1]))
743 1.1 christos return -8; /* incomplete code ok only for single length 1 code */
744 1.1 christos
745 1.1 christos /* decode data until end-of-block code */
746 1.1 christos return codes(s, &lencode, &distcode);
747 1.1 christos }
748 1.1 christos
749 1.1 christos /*
750 1.1 christos * Inflate source to dest. On return, destlen and sourcelen are updated to the
751 1.1 christos * size of the uncompressed data and the size of the deflate data respectively.
752 1.1 christos * On success, the return value of puff() is zero. If there is an error in the
753 1.1 christos * source data, i.e. it is not in the deflate format, then a negative value is
754 1.1 christos * returned. If there is not enough input available or there is not enough
755 1.1 christos * output space, then a positive error is returned. In that case, destlen and
756 1.1 christos * sourcelen are not updated to facilitate retrying from the beginning with the
757 1.1 christos * provision of more input data or more output space. In the case of invalid
758 1.1 christos * inflate data (a negative error), the dest and source pointers are updated to
759 1.1 christos * facilitate the debugging of deflators.
760 1.1 christos *
761 1.1 christos * puff() also has a mode to determine the size of the uncompressed output with
762 1.1 christos * no output written. For this dest must be (unsigned char *)0. In this case,
763 1.1 christos * the input value of *destlen is ignored, and on return *destlen is set to the
764 1.1 christos * size of the uncompressed output.
765 1.1 christos *
766 1.1 christos * The return codes are:
767 1.1 christos *
768 1.1 christos * 2: available inflate data did not terminate
769 1.1 christos * 1: output space exhausted before completing inflate
770 1.1 christos * 0: successful inflate
771 1.1 christos * -1: invalid block type (type == 3)
772 1.1 christos * -2: stored block length did not match one's complement
773 1.1 christos * -3: dynamic block code description: too many length or distance codes
774 1.1 christos * -4: dynamic block code description: code lengths codes incomplete
775 1.1 christos * -5: dynamic block code description: repeat lengths with no first length
776 1.1 christos * -6: dynamic block code description: repeat more than specified lengths
777 1.1 christos * -7: dynamic block code description: invalid literal/length code lengths
778 1.1 christos * -8: dynamic block code description: invalid distance code lengths
779 1.1 christos * -9: dynamic block code description: missing end-of-block code
780 1.1 christos * -10: invalid literal/length or distance code in fixed or dynamic block
781 1.1 christos * -11: distance is too far back in fixed or dynamic block
782 1.1 christos *
783 1.1 christos * Format notes:
784 1.1 christos *
785 1.1 christos * - Three bits are read for each block to determine the kind of block and
786 1.1 christos * whether or not it is the last block. Then the block is decoded and the
787 1.1 christos * process repeated if it was not the last block.
788 1.1 christos *
789 1.1 christos * - The leftover bits in the last byte of the deflate data after the last
790 1.1 christos * block (if it was a fixed or dynamic block) are undefined and have no
791 1.1 christos * expected values to check.
792 1.1 christos */
793 1.1 christos int puff(unsigned char *dest, /* pointer to destination pointer */
794 1.1 christos unsigned long *destlen, /* amount of output space */
795 1.1 christos const unsigned char *source, /* pointer to source data pointer */
796 1.1 christos unsigned long *sourcelen) /* amount of input available */
797 1.1 christos {
798 1.1 christos struct state s; /* input/output state */
799 1.1 christos int last, type; /* block information */
800 1.1 christos int err; /* return value */
801 1.1 christos
802 1.1 christos /* initialize output state */
803 1.1 christos s.out = dest;
804 1.1 christos s.outlen = *destlen; /* ignored if dest is NIL */
805 1.1 christos s.outcnt = 0;
806 1.1 christos
807 1.1 christos /* initialize input state */
808 1.1 christos s.in = source;
809 1.1 christos s.inlen = *sourcelen;
810 1.1 christos s.incnt = 0;
811 1.1 christos s.bitbuf = 0;
812 1.1 christos s.bitcnt = 0;
813 1.1 christos
814 1.1 christos /* return if bits() or decode() tries to read past available input */
815 1.1 christos if (setjmp(s.env) != 0) /* if came back here via longjmp() */
816 1.1 christos err = 2; /* then skip do-loop, return error */
817 1.1 christos else {
818 1.1 christos /* process blocks until last block or error */
819 1.1 christos do {
820 1.1 christos last = bits(&s, 1); /* one if last block */
821 1.1 christos type = bits(&s, 2); /* block type 0..3 */
822 1.1 christos err = type == 0 ?
823 1.1 christos stored(&s) :
824 1.1 christos (type == 1 ?
825 1.1 christos fixed(&s) :
826 1.1 christos (type == 2 ?
827 1.1 christos dynamic(&s) :
828 1.1 christos -1)); /* type == 3, invalid */
829 1.1 christos if (err != 0)
830 1.1 christos break; /* return with error */
831 1.1 christos } while (!last);
832 1.1 christos }
833 1.1 christos
834 1.1 christos /* update the lengths and return */
835 1.1 christos if (err <= 0) {
836 1.1 christos *destlen = s.outcnt;
837 1.1 christos *sourcelen = s.incnt;
838 1.1 christos }
839 1.1 christos return err;
840 1.1 christos }
841