annotate src/zlib-1.2.7/contrib/puff/puff.c @ 89:8a15ff55d9af

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