annotate src/zlib-1.2.8/contrib/puff/puff.c @ 169:223a55898ab9 tip default

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