annotate src/zlib-1.2.8/contrib/puff/puff.c @ 84:08ae793730bd

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