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