cannam@128: /* cannam@128: * puff.c cannam@128: * Copyright (C) 2002-2013 Mark Adler cannam@128: * For conditions of distribution and use, see copyright notice in puff.h cannam@128: * version 2.3, 21 Jan 2013 cannam@128: * cannam@128: * puff.c is a simple inflate written to be an unambiguous way to specify the cannam@128: * deflate format. It is not written for speed but rather simplicity. As a cannam@128: * side benefit, this code might actually be useful when small code is more cannam@128: * important than speed, such as bootstrap applications. For typical deflate cannam@128: * data, zlib's inflate() is about four times as fast as puff(). zlib's cannam@128: * inflate compiles to around 20K on my machine, whereas puff.c compiles to cannam@128: * around 4K on my machine (a PowerPC using GNU cc). If the faster decode() cannam@128: * function here is used, then puff() is only twice as slow as zlib's cannam@128: * inflate(). cannam@128: * cannam@128: * All dynamically allocated memory comes from the stack. The stack required cannam@128: * is less than 2K bytes. This code is compatible with 16-bit int's and cannam@128: * assumes that long's are at least 32 bits. puff.c uses the short data type, cannam@128: * assumed to be 16 bits, for arrays in order to to conserve memory. The code cannam@128: * works whether integers are stored big endian or little endian. cannam@128: * cannam@128: * In the comments below are "Format notes" that describe the inflate process cannam@128: * and document some of the less obvious aspects of the format. This source cannam@128: * code is meant to supplement RFC 1951, which formally describes the deflate cannam@128: * format: cannam@128: * cannam@128: * http://www.zlib.org/rfc-deflate.html cannam@128: */ cannam@128: cannam@128: /* cannam@128: * Change history: cannam@128: * cannam@128: * 1.0 10 Feb 2002 - First version cannam@128: * 1.1 17 Feb 2002 - Clarifications of some comments and notes cannam@128: * - Update puff() dest and source pointers on negative cannam@128: * errors to facilitate debugging deflators cannam@128: * - Remove longest from struct huffman -- not needed cannam@128: * - Simplify offs[] index in construct() cannam@128: * - Add input size and checking, using longjmp() to cannam@128: * maintain easy readability cannam@128: * - Use short data type for large arrays cannam@128: * - Use pointers instead of long to specify source and cannam@128: * destination sizes to avoid arbitrary 4 GB limits cannam@128: * 1.2 17 Mar 2002 - Add faster version of decode(), doubles speed (!), cannam@128: * but leave simple version for readabilty cannam@128: * - Make sure invalid distances detected if pointers cannam@128: * are 16 bits cannam@128: * - Fix fixed codes table error cannam@128: * - Provide a scanning mode for determining size of cannam@128: * uncompressed data cannam@128: * 1.3 20 Mar 2002 - Go back to lengths for puff() parameters [Gailly] cannam@128: * - Add a puff.h file for the interface cannam@128: * - Add braces in puff() for else do [Gailly] cannam@128: * - Use indexes instead of pointers for readability cannam@128: * 1.4 31 Mar 2002 - Simplify construct() code set check cannam@128: * - Fix some comments cannam@128: * - Add FIXLCODES #define cannam@128: * 1.5 6 Apr 2002 - Minor comment fixes cannam@128: * 1.6 7 Aug 2002 - Minor format changes cannam@128: * 1.7 3 Mar 2003 - Added test code for distribution cannam@128: * - Added zlib-like license cannam@128: * 1.8 9 Jan 2004 - Added some comments on no distance codes case cannam@128: * 1.9 21 Feb 2008 - Fix bug on 16-bit integer architectures [Pohland] cannam@128: * - Catch missing end-of-block symbol error cannam@128: * 2.0 25 Jul 2008 - Add #define to permit distance too far back cannam@128: * - Add option in TEST code for puff to write the data cannam@128: * - Add option in TEST code to skip input bytes cannam@128: * - Allow TEST code to read from piped stdin cannam@128: * 2.1 4 Apr 2010 - Avoid variable initialization for happier compilers cannam@128: * - Avoid unsigned comparisons for even happier compilers cannam@128: * 2.2 25 Apr 2010 - Fix bug in variable initializations [Oberhumer] cannam@128: * - Add const where appropriate [Oberhumer] cannam@128: * - Split if's and ?'s for coverage testing cannam@128: * - Break out test code to separate file cannam@128: * - Move NIL to puff.h cannam@128: * - Allow incomplete code only if single code length is 1 cannam@128: * - Add full code coverage test to Makefile cannam@128: * 2.3 21 Jan 2013 - Check for invalid code length codes in dynamic blocks cannam@128: */ cannam@128: cannam@128: #include /* for setjmp(), longjmp(), and jmp_buf */ cannam@128: #include "puff.h" /* prototype for puff() */ cannam@128: cannam@128: #define local static /* for local function definitions */ cannam@128: cannam@128: /* cannam@128: * Maximums for allocations and loops. It is not useful to change these -- cannam@128: * they are fixed by the deflate format. cannam@128: */ cannam@128: #define MAXBITS 15 /* maximum bits in a code */ cannam@128: #define MAXLCODES 286 /* maximum number of literal/length codes */ cannam@128: #define MAXDCODES 30 /* maximum number of distance codes */ cannam@128: #define MAXCODES (MAXLCODES+MAXDCODES) /* maximum codes lengths to read */ cannam@128: #define FIXLCODES 288 /* number of fixed literal/length codes */ cannam@128: cannam@128: /* input and output state */ cannam@128: struct state { cannam@128: /* output state */ cannam@128: unsigned char *out; /* output buffer */ cannam@128: unsigned long outlen; /* available space at out */ cannam@128: unsigned long outcnt; /* bytes written to out so far */ cannam@128: cannam@128: /* input state */ cannam@128: const unsigned char *in; /* input buffer */ cannam@128: unsigned long inlen; /* available input at in */ cannam@128: unsigned long incnt; /* bytes read so far */ cannam@128: int bitbuf; /* bit buffer */ cannam@128: int bitcnt; /* number of bits in bit buffer */ cannam@128: cannam@128: /* input limit error return state for bits() and decode() */ cannam@128: jmp_buf env; cannam@128: }; cannam@128: cannam@128: /* cannam@128: * Return need bits from the input stream. This always leaves less than cannam@128: * eight bits in the buffer. bits() works properly for need == 0. cannam@128: * cannam@128: * Format notes: cannam@128: * cannam@128: * - Bits are stored in bytes from the least significant bit to the most cannam@128: * significant bit. Therefore bits are dropped from the bottom of the bit cannam@128: * buffer, using shift right, and new bytes are appended to the top of the cannam@128: * bit buffer, using shift left. cannam@128: */ cannam@128: local int bits(struct state *s, int need) cannam@128: { cannam@128: long val; /* bit accumulator (can use up to 20 bits) */ cannam@128: cannam@128: /* load at least need bits into val */ cannam@128: val = s->bitbuf; cannam@128: while (s->bitcnt < need) { cannam@128: if (s->incnt == s->inlen) cannam@128: longjmp(s->env, 1); /* out of input */ cannam@128: val |= (long)(s->in[s->incnt++]) << s->bitcnt; /* load eight bits */ cannam@128: s->bitcnt += 8; cannam@128: } cannam@128: cannam@128: /* drop need bits and update buffer, always zero to seven bits left */ cannam@128: s->bitbuf = (int)(val >> need); cannam@128: s->bitcnt -= need; cannam@128: cannam@128: /* return need bits, zeroing the bits above that */ cannam@128: return (int)(val & ((1L << need) - 1)); cannam@128: } cannam@128: cannam@128: /* cannam@128: * Process a stored block. cannam@128: * cannam@128: * Format notes: cannam@128: * cannam@128: * - After the two-bit stored block type (00), the stored block length and cannam@128: * stored bytes are byte-aligned for fast copying. Therefore any leftover cannam@128: * bits in the byte that has the last bit of the type, as many as seven, are cannam@128: * discarded. The value of the discarded bits are not defined and should not cannam@128: * be checked against any expectation. cannam@128: * cannam@128: * - The second inverted copy of the stored block length does not have to be cannam@128: * checked, but it's probably a good idea to do so anyway. cannam@128: * cannam@128: * - A stored block can have zero length. This is sometimes used to byte-align cannam@128: * subsets of the compressed data for random access or partial recovery. cannam@128: */ cannam@128: local int stored(struct state *s) cannam@128: { cannam@128: unsigned len; /* length of stored block */ cannam@128: cannam@128: /* discard leftover bits from current byte (assumes s->bitcnt < 8) */ cannam@128: s->bitbuf = 0; cannam@128: s->bitcnt = 0; cannam@128: cannam@128: /* get length and check against its one's complement */ cannam@128: if (s->incnt + 4 > s->inlen) cannam@128: return 2; /* not enough input */ cannam@128: len = s->in[s->incnt++]; cannam@128: len |= s->in[s->incnt++] << 8; cannam@128: if (s->in[s->incnt++] != (~len & 0xff) || cannam@128: s->in[s->incnt++] != ((~len >> 8) & 0xff)) cannam@128: return -2; /* didn't match complement! */ cannam@128: cannam@128: /* copy len bytes from in to out */ cannam@128: if (s->incnt + len > s->inlen) cannam@128: return 2; /* not enough input */ cannam@128: if (s->out != NIL) { cannam@128: if (s->outcnt + len > s->outlen) cannam@128: return 1; /* not enough output space */ cannam@128: while (len--) cannam@128: s->out[s->outcnt++] = s->in[s->incnt++]; cannam@128: } cannam@128: else { /* just scanning */ cannam@128: s->outcnt += len; cannam@128: s->incnt += len; cannam@128: } cannam@128: cannam@128: /* done with a valid stored block */ cannam@128: return 0; cannam@128: } cannam@128: cannam@128: /* cannam@128: * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of cannam@128: * each length, which for a canonical code are stepped through in order. cannam@128: * symbol[] are the symbol values in canonical order, where the number of cannam@128: * entries is the sum of the counts in count[]. The decoding process can be cannam@128: * seen in the function decode() below. cannam@128: */ cannam@128: struct huffman { cannam@128: short *count; /* number of symbols of each length */ cannam@128: short *symbol; /* canonically ordered symbols */ cannam@128: }; cannam@128: cannam@128: /* cannam@128: * Decode a code from the stream s using huffman table h. Return the symbol or cannam@128: * a negative value if there is an error. If all of the lengths are zero, i.e. cannam@128: * an empty code, or if the code is incomplete and an invalid code is received, cannam@128: * then -10 is returned after reading MAXBITS bits. cannam@128: * cannam@128: * Format notes: cannam@128: * cannam@128: * - The codes as stored in the compressed data are bit-reversed relative to cannam@128: * a simple integer ordering of codes of the same lengths. Hence below the cannam@128: * bits are pulled from the compressed data one at a time and used to cannam@128: * build the code value reversed from what is in the stream in order to cannam@128: * permit simple integer comparisons for decoding. A table-based decoding cannam@128: * scheme (as used in zlib) does not need to do this reversal. cannam@128: * cannam@128: * - The first code for the shortest length is all zeros. Subsequent codes of cannam@128: * the same length are simply integer increments of the previous code. When cannam@128: * moving up a length, a zero bit is appended to the code. For a complete cannam@128: * code, the last code of the longest length will be all ones. cannam@128: * cannam@128: * - Incomplete codes are handled by this decoder, since they are permitted cannam@128: * in the deflate format. See the format notes for fixed() and dynamic(). cannam@128: */ cannam@128: #ifdef SLOW cannam@128: local int decode(struct state *s, const struct huffman *h) cannam@128: { cannam@128: int len; /* current number of bits in code */ cannam@128: int code; /* len bits being decoded */ cannam@128: int first; /* first code of length len */ cannam@128: int count; /* number of codes of length len */ cannam@128: int index; /* index of first code of length len in symbol table */ cannam@128: cannam@128: code = first = index = 0; cannam@128: for (len = 1; len <= MAXBITS; len++) { cannam@128: code |= bits(s, 1); /* get next bit */ cannam@128: count = h->count[len]; cannam@128: if (code - count < first) /* if length len, return symbol */ cannam@128: return h->symbol[index + (code - first)]; cannam@128: index += count; /* else update for next length */ cannam@128: first += count; cannam@128: first <<= 1; cannam@128: code <<= 1; cannam@128: } cannam@128: return -10; /* ran out of codes */ cannam@128: } cannam@128: cannam@128: /* cannam@128: * A faster version of decode() for real applications of this code. It's not cannam@128: * as readable, but it makes puff() twice as fast. And it only makes the code cannam@128: * a few percent larger. cannam@128: */ cannam@128: #else /* !SLOW */ cannam@128: local int decode(struct state *s, const struct huffman *h) cannam@128: { cannam@128: int len; /* current number of bits in code */ cannam@128: int code; /* len bits being decoded */ cannam@128: int first; /* first code of length len */ cannam@128: int count; /* number of codes of length len */ cannam@128: int index; /* index of first code of length len in symbol table */ cannam@128: int bitbuf; /* bits from stream */ cannam@128: int left; /* bits left in next or left to process */ cannam@128: short *next; /* next number of codes */ cannam@128: cannam@128: bitbuf = s->bitbuf; cannam@128: left = s->bitcnt; cannam@128: code = first = index = 0; cannam@128: len = 1; cannam@128: next = h->count + 1; cannam@128: while (1) { cannam@128: while (left--) { cannam@128: code |= bitbuf & 1; cannam@128: bitbuf >>= 1; cannam@128: count = *next++; cannam@128: if (code - count < first) { /* if length len, return symbol */ cannam@128: s->bitbuf = bitbuf; cannam@128: s->bitcnt = (s->bitcnt - len) & 7; cannam@128: return h->symbol[index + (code - first)]; cannam@128: } cannam@128: index += count; /* else update for next length */ cannam@128: first += count; cannam@128: first <<= 1; cannam@128: code <<= 1; cannam@128: len++; cannam@128: } cannam@128: left = (MAXBITS+1) - len; cannam@128: if (left == 0) cannam@128: break; cannam@128: if (s->incnt == s->inlen) cannam@128: longjmp(s->env, 1); /* out of input */ cannam@128: bitbuf = s->in[s->incnt++]; cannam@128: if (left > 8) cannam@128: left = 8; cannam@128: } cannam@128: return -10; /* ran out of codes */ cannam@128: } cannam@128: #endif /* SLOW */ cannam@128: cannam@128: /* cannam@128: * Given the list of code lengths length[0..n-1] representing a canonical cannam@128: * Huffman code for n symbols, construct the tables required to decode those cannam@128: * codes. Those tables are the number of codes of each length, and the symbols cannam@128: * sorted by length, retaining their original order within each length. The cannam@128: * return value is zero for a complete code set, negative for an over- cannam@128: * subscribed code set, and positive for an incomplete code set. The tables cannam@128: * can be used if the return value is zero or positive, but they cannot be used cannam@128: * if the return value is negative. If the return value is zero, it is not cannam@128: * possible for decode() using that table to return an error--any stream of cannam@128: * enough bits will resolve to a symbol. If the return value is positive, then cannam@128: * it is possible for decode() using that table to return an error for received cannam@128: * codes past the end of the incomplete lengths. cannam@128: * cannam@128: * Not used by decode(), but used for error checking, h->count[0] is the number cannam@128: * of the n symbols not in the code. So n - h->count[0] is the number of cannam@128: * codes. This is useful for checking for incomplete codes that have more than cannam@128: * one symbol, which is an error in a dynamic block. cannam@128: * cannam@128: * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS cannam@128: * This is assured by the construction of the length arrays in dynamic() and cannam@128: * fixed() and is not verified by construct(). cannam@128: * cannam@128: * Format notes: cannam@128: * cannam@128: * - Permitted and expected examples of incomplete codes are one of the fixed cannam@128: * codes and any code with a single symbol which in deflate is coded as one cannam@128: * bit instead of zero bits. See the format notes for fixed() and dynamic(). cannam@128: * cannam@128: * - Within a given code length, the symbols are kept in ascending order for cannam@128: * the code bits definition. cannam@128: */ cannam@128: local int construct(struct huffman *h, const short *length, int n) cannam@128: { cannam@128: int symbol; /* current symbol when stepping through length[] */ cannam@128: int len; /* current length when stepping through h->count[] */ cannam@128: int left; /* number of possible codes left of current length */ cannam@128: short offs[MAXBITS+1]; /* offsets in symbol table for each length */ cannam@128: cannam@128: /* count number of codes of each length */ cannam@128: for (len = 0; len <= MAXBITS; len++) cannam@128: h->count[len] = 0; cannam@128: for (symbol = 0; symbol < n; symbol++) cannam@128: (h->count[length[symbol]])++; /* assumes lengths are within bounds */ cannam@128: if (h->count[0] == n) /* no codes! */ cannam@128: return 0; /* complete, but decode() will fail */ cannam@128: cannam@128: /* check for an over-subscribed or incomplete set of lengths */ cannam@128: left = 1; /* one possible code of zero length */ cannam@128: for (len = 1; len <= MAXBITS; len++) { cannam@128: left <<= 1; /* one more bit, double codes left */ cannam@128: left -= h->count[len]; /* deduct count from possible codes */ cannam@128: if (left < 0) cannam@128: return left; /* over-subscribed--return negative */ cannam@128: } /* left > 0 means incomplete */ cannam@128: cannam@128: /* generate offsets into symbol table for each length for sorting */ cannam@128: offs[1] = 0; cannam@128: for (len = 1; len < MAXBITS; len++) cannam@128: offs[len + 1] = offs[len] + h->count[len]; cannam@128: cannam@128: /* cannam@128: * put symbols in table sorted by length, by symbol order within each cannam@128: * length cannam@128: */ cannam@128: for (symbol = 0; symbol < n; symbol++) cannam@128: if (length[symbol] != 0) cannam@128: h->symbol[offs[length[symbol]]++] = symbol; cannam@128: cannam@128: /* return zero for complete set, positive for incomplete set */ cannam@128: return left; cannam@128: } cannam@128: cannam@128: /* cannam@128: * Decode literal/length and distance codes until an end-of-block code. cannam@128: * cannam@128: * Format notes: cannam@128: * cannam@128: * - Compressed data that is after the block type if fixed or after the code cannam@128: * description if dynamic is a combination of literals and length/distance cannam@128: * pairs terminated by and end-of-block code. Literals are simply Huffman cannam@128: * coded bytes. A length/distance pair is a coded length followed by a cannam@128: * coded distance to represent a string that occurs earlier in the cannam@128: * uncompressed data that occurs again at the current location. cannam@128: * cannam@128: * - Literals, lengths, and the end-of-block code are combined into a single cannam@128: * code of up to 286 symbols. They are 256 literals (0..255), 29 length cannam@128: * symbols (257..285), and the end-of-block symbol (256). cannam@128: * cannam@128: * - There are 256 possible lengths (3..258), and so 29 symbols are not enough cannam@128: * to represent all of those. Lengths 3..10 and 258 are in fact represented cannam@128: * by just a length symbol. Lengths 11..257 are represented as a symbol and cannam@128: * some number of extra bits that are added as an integer to the base length cannam@128: * of the length symbol. The number of extra bits is determined by the base cannam@128: * length symbol. These are in the static arrays below, lens[] for the base cannam@128: * lengths and lext[] for the corresponding number of extra bits. cannam@128: * cannam@128: * - The reason that 258 gets its own symbol is that the longest length is used cannam@128: * often in highly redundant files. Note that 258 can also be coded as the cannam@128: * base value 227 plus the maximum extra value of 31. While a good deflate cannam@128: * should never do this, it is not an error, and should be decoded properly. cannam@128: * cannam@128: * - If a length is decoded, including its extra bits if any, then it is cannam@128: * followed a distance code. There are up to 30 distance symbols. Again cannam@128: * there are many more possible distances (1..32768), so extra bits are added cannam@128: * to a base value represented by the symbol. The distances 1..4 get their cannam@128: * own symbol, but the rest require extra bits. The base distances and cannam@128: * corresponding number of extra bits are below in the static arrays dist[] cannam@128: * and dext[]. cannam@128: * cannam@128: * - Literal bytes are simply written to the output. A length/distance pair is cannam@128: * an instruction to copy previously uncompressed bytes to the output. The cannam@128: * copy is from distance bytes back in the output stream, copying for length cannam@128: * bytes. cannam@128: * cannam@128: * - Distances pointing before the beginning of the output data are not cannam@128: * permitted. cannam@128: * cannam@128: * - Overlapped copies, where the length is greater than the distance, are cannam@128: * allowed and common. For example, a distance of one and a length of 258 cannam@128: * simply copies the last byte 258 times. A distance of four and a length of cannam@128: * twelve copies the last four bytes three times. A simple forward copy cannam@128: * ignoring whether the length is greater than the distance or not implements cannam@128: * this correctly. You should not use memcpy() since its behavior is not cannam@128: * defined for overlapped arrays. You should not use memmove() or bcopy() cannam@128: * since though their behavior -is- defined for overlapping arrays, it is cannam@128: * defined to do the wrong thing in this case. cannam@128: */ cannam@128: local int codes(struct state *s, cannam@128: const struct huffman *lencode, cannam@128: const struct huffman *distcode) cannam@128: { cannam@128: int symbol; /* decoded symbol */ cannam@128: int len; /* length for copy */ cannam@128: unsigned dist; /* distance for copy */ cannam@128: static const short lens[29] = { /* Size base for length codes 257..285 */ cannam@128: 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, cannam@128: 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; cannam@128: static const short lext[29] = { /* Extra bits for length codes 257..285 */ cannam@128: 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, cannam@128: 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; cannam@128: static const short dists[30] = { /* Offset base for distance codes 0..29 */ cannam@128: 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, cannam@128: 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, cannam@128: 8193, 12289, 16385, 24577}; cannam@128: static const short dext[30] = { /* Extra bits for distance codes 0..29 */ cannam@128: 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, cannam@128: 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, cannam@128: 12, 12, 13, 13}; cannam@128: cannam@128: /* decode literals and length/distance pairs */ cannam@128: do { cannam@128: symbol = decode(s, lencode); cannam@128: if (symbol < 0) cannam@128: return symbol; /* invalid symbol */ cannam@128: if (symbol < 256) { /* literal: symbol is the byte */ cannam@128: /* write out the literal */ cannam@128: if (s->out != NIL) { cannam@128: if (s->outcnt == s->outlen) cannam@128: return 1; cannam@128: s->out[s->outcnt] = symbol; cannam@128: } cannam@128: s->outcnt++; cannam@128: } cannam@128: else if (symbol > 256) { /* length */ cannam@128: /* get and compute length */ cannam@128: symbol -= 257; cannam@128: if (symbol >= 29) cannam@128: return -10; /* invalid fixed code */ cannam@128: len = lens[symbol] + bits(s, lext[symbol]); cannam@128: cannam@128: /* get and check distance */ cannam@128: symbol = decode(s, distcode); cannam@128: if (symbol < 0) cannam@128: return symbol; /* invalid symbol */ cannam@128: dist = dists[symbol] + bits(s, dext[symbol]); cannam@128: #ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR cannam@128: if (dist > s->outcnt) cannam@128: return -11; /* distance too far back */ cannam@128: #endif cannam@128: cannam@128: /* copy length bytes from distance bytes back */ cannam@128: if (s->out != NIL) { cannam@128: if (s->outcnt + len > s->outlen) cannam@128: return 1; cannam@128: while (len--) { cannam@128: s->out[s->outcnt] = cannam@128: #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR cannam@128: dist > s->outcnt ? cannam@128: 0 : cannam@128: #endif cannam@128: s->out[s->outcnt - dist]; cannam@128: s->outcnt++; cannam@128: } cannam@128: } cannam@128: else cannam@128: s->outcnt += len; cannam@128: } cannam@128: } while (symbol != 256); /* end of block symbol */ cannam@128: cannam@128: /* done with a valid fixed or dynamic block */ cannam@128: return 0; cannam@128: } cannam@128: cannam@128: /* cannam@128: * Process a fixed codes block. cannam@128: * cannam@128: * Format notes: cannam@128: * cannam@128: * - This block type can be useful for compressing small amounts of data for cannam@128: * which the size of the code descriptions in a dynamic block exceeds the cannam@128: * benefit of custom codes for that block. For fixed codes, no bits are cannam@128: * spent on code descriptions. Instead the code lengths for literal/length cannam@128: * codes and distance codes are fixed. The specific lengths for each symbol cannam@128: * can be seen in the "for" loops below. cannam@128: * cannam@128: * - The literal/length code is complete, but has two symbols that are invalid cannam@128: * and should result in an error if received. This cannot be implemented cannam@128: * simply as an incomplete code since those two symbols are in the "middle" cannam@128: * of the code. They are eight bits long and the longest literal/length\ cannam@128: * code is nine bits. Therefore the code must be constructed with those cannam@128: * symbols, and the invalid symbols must be detected after decoding. cannam@128: * cannam@128: * - The fixed distance codes also have two invalid symbols that should result cannam@128: * in an error if received. Since all of the distance codes are the same cannam@128: * length, this can be implemented as an incomplete code. Then the invalid cannam@128: * codes are detected while decoding. cannam@128: */ cannam@128: local int fixed(struct state *s) cannam@128: { cannam@128: static int virgin = 1; cannam@128: static short lencnt[MAXBITS+1], lensym[FIXLCODES]; cannam@128: static short distcnt[MAXBITS+1], distsym[MAXDCODES]; cannam@128: static struct huffman lencode, distcode; cannam@128: cannam@128: /* build fixed huffman tables if first call (may not be thread safe) */ cannam@128: if (virgin) { cannam@128: int symbol; cannam@128: short lengths[FIXLCODES]; cannam@128: cannam@128: /* construct lencode and distcode */ cannam@128: lencode.count = lencnt; cannam@128: lencode.symbol = lensym; cannam@128: distcode.count = distcnt; cannam@128: distcode.symbol = distsym; cannam@128: cannam@128: /* literal/length table */ cannam@128: for (symbol = 0; symbol < 144; symbol++) cannam@128: lengths[symbol] = 8; cannam@128: for (; symbol < 256; symbol++) cannam@128: lengths[symbol] = 9; cannam@128: for (; symbol < 280; symbol++) cannam@128: lengths[symbol] = 7; cannam@128: for (; symbol < FIXLCODES; symbol++) cannam@128: lengths[symbol] = 8; cannam@128: construct(&lencode, lengths, FIXLCODES); cannam@128: cannam@128: /* distance table */ cannam@128: for (symbol = 0; symbol < MAXDCODES; symbol++) cannam@128: lengths[symbol] = 5; cannam@128: construct(&distcode, lengths, MAXDCODES); cannam@128: cannam@128: /* do this just once */ cannam@128: virgin = 0; cannam@128: } cannam@128: cannam@128: /* decode data until end-of-block code */ cannam@128: return codes(s, &lencode, &distcode); cannam@128: } cannam@128: cannam@128: /* cannam@128: * Process a dynamic codes block. cannam@128: * cannam@128: * Format notes: cannam@128: * cannam@128: * - A dynamic block starts with a description of the literal/length and cannam@128: * distance codes for that block. New dynamic blocks allow the compressor to cannam@128: * rapidly adapt to changing data with new codes optimized for that data. cannam@128: * cannam@128: * - The codes used by the deflate format are "canonical", which means that cannam@128: * the actual bits of the codes are generated in an unambiguous way simply cannam@128: * from the number of bits in each code. Therefore the code descriptions cannam@128: * are simply a list of code lengths for each symbol. cannam@128: * cannam@128: * - The code lengths are stored in order for the symbols, so lengths are cannam@128: * provided for each of the literal/length symbols, and for each of the cannam@128: * distance symbols. cannam@128: * cannam@128: * - If a symbol is not used in the block, this is represented by a zero as cannam@128: * as the code length. This does not mean a zero-length code, but rather cannam@128: * that no code should be created for this symbol. There is no way in the cannam@128: * deflate format to represent a zero-length code. cannam@128: * cannam@128: * - The maximum number of bits in a code is 15, so the possible lengths for cannam@128: * any code are 1..15. cannam@128: * cannam@128: * - The fact that a length of zero is not permitted for a code has an cannam@128: * interesting consequence. Normally if only one symbol is used for a given cannam@128: * code, then in fact that code could be represented with zero bits. However cannam@128: * in deflate, that code has to be at least one bit. So for example, if cannam@128: * only a single distance base symbol appears in a block, then it will be cannam@128: * represented by a single code of length one, in particular one 0 bit. This cannam@128: * is an incomplete code, since if a 1 bit is received, it has no meaning, cannam@128: * and should result in an error. So incomplete distance codes of one symbol cannam@128: * should be permitted, and the receipt of invalid codes should be handled. cannam@128: * cannam@128: * - It is also possible to have a single literal/length code, but that code cannam@128: * must be the end-of-block code, since every dynamic block has one. This cannam@128: * is not the most efficient way to create an empty block (an empty fixed cannam@128: * block is fewer bits), but it is allowed by the format. So incomplete cannam@128: * literal/length codes of one symbol should also be permitted. cannam@128: * cannam@128: * - If there are only literal codes and no lengths, then there are no distance cannam@128: * codes. This is represented by one distance code with zero bits. cannam@128: * cannam@128: * - The list of up to 286 length/literal lengths and up to 30 distance lengths cannam@128: * are themselves compressed using Huffman codes and run-length encoding. In cannam@128: * the list of code lengths, a 0 symbol means no code, a 1..15 symbol means cannam@128: * that length, and the symbols 16, 17, and 18 are run-length instructions. cannam@128: * Each of 16, 17, and 18 are follwed by extra bits to define the length of cannam@128: * the run. 16 copies the last length 3 to 6 times. 17 represents 3 to 10 cannam@128: * zero lengths, and 18 represents 11 to 138 zero lengths. Unused symbols cannam@128: * are common, hence the special coding for zero lengths. cannam@128: * cannam@128: * - The symbols for 0..18 are Huffman coded, and so that code must be cannam@128: * described first. This is simply a sequence of up to 19 three-bit values cannam@128: * representing no code (0) or the code length for that symbol (1..7). cannam@128: * cannam@128: * - A dynamic block starts with three fixed-size counts from which is computed cannam@128: * the number of literal/length code lengths, the number of distance code cannam@128: * lengths, and the number of code length code lengths (ok, you come up with cannam@128: * a better name!) in the code descriptions. For the literal/length and cannam@128: * distance codes, lengths after those provided are considered zero, i.e. no cannam@128: * code. The code length code lengths are received in a permuted order (see cannam@128: * the order[] array below) to make a short code length code length list more cannam@128: * likely. As it turns out, very short and very long codes are less likely cannam@128: * to be seen in a dynamic code description, hence what may appear initially cannam@128: * to be a peculiar ordering. cannam@128: * cannam@128: * - Given the number of literal/length code lengths (nlen) and distance code cannam@128: * lengths (ndist), then they are treated as one long list of nlen + ndist cannam@128: * code lengths. Therefore run-length coding can and often does cross the cannam@128: * boundary between the two sets of lengths. cannam@128: * cannam@128: * - So to summarize, the code description at the start of a dynamic block is cannam@128: * three counts for the number of code lengths for the literal/length codes, cannam@128: * the distance codes, and the code length codes. This is followed by the cannam@128: * code length code lengths, three bits each. This is used to construct the cannam@128: * code length code which is used to read the remainder of the lengths. Then cannam@128: * the literal/length code lengths and distance lengths are read as a single cannam@128: * set of lengths using the code length codes. Codes are constructed from cannam@128: * the resulting two sets of lengths, and then finally you can start cannam@128: * decoding actual compressed data in the block. cannam@128: * cannam@128: * - For reference, a "typical" size for the code description in a dynamic cannam@128: * block is around 80 bytes. cannam@128: */ cannam@128: local int dynamic(struct state *s) cannam@128: { cannam@128: int nlen, ndist, ncode; /* number of lengths in descriptor */ cannam@128: int index; /* index of lengths[] */ cannam@128: int err; /* construct() return value */ cannam@128: short lengths[MAXCODES]; /* descriptor code lengths */ cannam@128: short lencnt[MAXBITS+1], lensym[MAXLCODES]; /* lencode memory */ cannam@128: short distcnt[MAXBITS+1], distsym[MAXDCODES]; /* distcode memory */ cannam@128: struct huffman lencode, distcode; /* length and distance codes */ cannam@128: static const short order[19] = /* permutation of code length codes */ cannam@128: {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; cannam@128: cannam@128: /* construct lencode and distcode */ cannam@128: lencode.count = lencnt; cannam@128: lencode.symbol = lensym; cannam@128: distcode.count = distcnt; cannam@128: distcode.symbol = distsym; cannam@128: cannam@128: /* get number of lengths in each table, check lengths */ cannam@128: nlen = bits(s, 5) + 257; cannam@128: ndist = bits(s, 5) + 1; cannam@128: ncode = bits(s, 4) + 4; cannam@128: if (nlen > MAXLCODES || ndist > MAXDCODES) cannam@128: return -3; /* bad counts */ cannam@128: cannam@128: /* read code length code lengths (really), missing lengths are zero */ cannam@128: for (index = 0; index < ncode; index++) cannam@128: lengths[order[index]] = bits(s, 3); cannam@128: for (; index < 19; index++) cannam@128: lengths[order[index]] = 0; cannam@128: cannam@128: /* build huffman table for code lengths codes (use lencode temporarily) */ cannam@128: err = construct(&lencode, lengths, 19); cannam@128: if (err != 0) /* require complete code set here */ cannam@128: return -4; cannam@128: cannam@128: /* read length/literal and distance code length tables */ cannam@128: index = 0; cannam@128: while (index < nlen + ndist) { cannam@128: int symbol; /* decoded value */ cannam@128: int len; /* last length to repeat */ cannam@128: cannam@128: symbol = decode(s, &lencode); cannam@128: if (symbol < 0) cannam@128: return symbol; /* invalid symbol */ cannam@128: if (symbol < 16) /* length in 0..15 */ cannam@128: lengths[index++] = symbol; cannam@128: else { /* repeat instruction */ cannam@128: len = 0; /* assume repeating zeros */ cannam@128: if (symbol == 16) { /* repeat last length 3..6 times */ cannam@128: if (index == 0) cannam@128: return -5; /* no last length! */ cannam@128: len = lengths[index - 1]; /* last length */ cannam@128: symbol = 3 + bits(s, 2); cannam@128: } cannam@128: else if (symbol == 17) /* repeat zero 3..10 times */ cannam@128: symbol = 3 + bits(s, 3); cannam@128: else /* == 18, repeat zero 11..138 times */ cannam@128: symbol = 11 + bits(s, 7); cannam@128: if (index + symbol > nlen + ndist) cannam@128: return -6; /* too many lengths! */ cannam@128: while (symbol--) /* repeat last or zero symbol times */ cannam@128: lengths[index++] = len; cannam@128: } cannam@128: } cannam@128: cannam@128: /* check for end-of-block code -- there better be one! */ cannam@128: if (lengths[256] == 0) cannam@128: return -9; cannam@128: cannam@128: /* build huffman table for literal/length codes */ cannam@128: err = construct(&lencode, lengths, nlen); cannam@128: if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1])) cannam@128: return -7; /* incomplete code ok only for single length 1 code */ cannam@128: cannam@128: /* build huffman table for distance codes */ cannam@128: err = construct(&distcode, lengths + nlen, ndist); cannam@128: if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1])) cannam@128: return -8; /* incomplete code ok only for single length 1 code */ cannam@128: cannam@128: /* decode data until end-of-block code */ cannam@128: return codes(s, &lencode, &distcode); cannam@128: } cannam@128: cannam@128: /* cannam@128: * Inflate source to dest. On return, destlen and sourcelen are updated to the cannam@128: * size of the uncompressed data and the size of the deflate data respectively. cannam@128: * On success, the return value of puff() is zero. If there is an error in the cannam@128: * source data, i.e. it is not in the deflate format, then a negative value is cannam@128: * returned. If there is not enough input available or there is not enough cannam@128: * output space, then a positive error is returned. In that case, destlen and cannam@128: * sourcelen are not updated to facilitate retrying from the beginning with the cannam@128: * provision of more input data or more output space. In the case of invalid cannam@128: * inflate data (a negative error), the dest and source pointers are updated to cannam@128: * facilitate the debugging of deflators. cannam@128: * cannam@128: * puff() also has a mode to determine the size of the uncompressed output with cannam@128: * no output written. For this dest must be (unsigned char *)0. In this case, cannam@128: * the input value of *destlen is ignored, and on return *destlen is set to the cannam@128: * size of the uncompressed output. cannam@128: * cannam@128: * The return codes are: cannam@128: * cannam@128: * 2: available inflate data did not terminate cannam@128: * 1: output space exhausted before completing inflate cannam@128: * 0: successful inflate cannam@128: * -1: invalid block type (type == 3) cannam@128: * -2: stored block length did not match one's complement cannam@128: * -3: dynamic block code description: too many length or distance codes cannam@128: * -4: dynamic block code description: code lengths codes incomplete cannam@128: * -5: dynamic block code description: repeat lengths with no first length cannam@128: * -6: dynamic block code description: repeat more than specified lengths cannam@128: * -7: dynamic block code description: invalid literal/length code lengths cannam@128: * -8: dynamic block code description: invalid distance code lengths cannam@128: * -9: dynamic block code description: missing end-of-block code cannam@128: * -10: invalid literal/length or distance code in fixed or dynamic block cannam@128: * -11: distance is too far back in fixed or dynamic block cannam@128: * cannam@128: * Format notes: cannam@128: * cannam@128: * - Three bits are read for each block to determine the kind of block and cannam@128: * whether or not it is the last block. Then the block is decoded and the cannam@128: * process repeated if it was not the last block. cannam@128: * cannam@128: * - The leftover bits in the last byte of the deflate data after the last cannam@128: * block (if it was a fixed or dynamic block) are undefined and have no cannam@128: * expected values to check. cannam@128: */ cannam@128: int puff(unsigned char *dest, /* pointer to destination pointer */ cannam@128: unsigned long *destlen, /* amount of output space */ cannam@128: const unsigned char *source, /* pointer to source data pointer */ cannam@128: unsigned long *sourcelen) /* amount of input available */ cannam@128: { cannam@128: struct state s; /* input/output state */ cannam@128: int last, type; /* block information */ cannam@128: int err; /* return value */ cannam@128: cannam@128: /* initialize output state */ cannam@128: s.out = dest; cannam@128: s.outlen = *destlen; /* ignored if dest is NIL */ cannam@128: s.outcnt = 0; cannam@128: cannam@128: /* initialize input state */ cannam@128: s.in = source; cannam@128: s.inlen = *sourcelen; cannam@128: s.incnt = 0; cannam@128: s.bitbuf = 0; cannam@128: s.bitcnt = 0; cannam@128: cannam@128: /* return if bits() or decode() tries to read past available input */ cannam@128: if (setjmp(s.env) != 0) /* if came back here via longjmp() */ cannam@128: err = 2; /* then skip do-loop, return error */ cannam@128: else { cannam@128: /* process blocks until last block or error */ cannam@128: do { cannam@128: last = bits(&s, 1); /* one if last block */ cannam@128: type = bits(&s, 2); /* block type 0..3 */ cannam@128: err = type == 0 ? cannam@128: stored(&s) : cannam@128: (type == 1 ? cannam@128: fixed(&s) : cannam@128: (type == 2 ? cannam@128: dynamic(&s) : cannam@128: -1)); /* type == 3, invalid */ cannam@128: if (err != 0) cannam@128: break; /* return with error */ cannam@128: } while (!last); cannam@128: } cannam@128: cannam@128: /* update the lengths and return */ cannam@128: if (err <= 0) { cannam@128: *destlen = s.outcnt; cannam@128: *sourcelen = s.incnt; cannam@128: } cannam@128: return err; cannam@128: }