cannam@89: /* blast.c cannam@89: * Copyright (C) 2003 Mark Adler cannam@89: * For conditions of distribution and use, see copyright notice in blast.h cannam@89: * version 1.1, 16 Feb 2003 cannam@89: * cannam@89: * blast.c decompresses data compressed by the PKWare Compression Library. cannam@89: * This function provides functionality similar to the explode() function of cannam@89: * the PKWare library, hence the name "blast". cannam@89: * cannam@89: * This decompressor is based on the excellent format description provided by cannam@89: * Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the cannam@89: * example Ben provided in the post is incorrect. The distance 110001 should cannam@89: * instead be 111000. When corrected, the example byte stream becomes: cannam@89: * cannam@89: * 00 04 82 24 25 8f 80 7f cannam@89: * cannam@89: * which decompresses to "AIAIAIAIAIAIA" (without the quotes). cannam@89: */ cannam@89: cannam@89: /* cannam@89: * Change history: cannam@89: * cannam@89: * 1.0 12 Feb 2003 - First version cannam@89: * 1.1 16 Feb 2003 - Fixed distance check for > 4 GB uncompressed data cannam@89: */ cannam@89: cannam@89: #include /* for setjmp(), longjmp(), and jmp_buf */ cannam@89: #include "blast.h" /* prototype for blast() */ cannam@89: cannam@89: #define local static /* for local function definitions */ cannam@89: #define MAXBITS 13 /* maximum code length */ cannam@89: #define MAXWIN 4096 /* maximum window size */ cannam@89: cannam@89: /* input and output state */ cannam@89: struct state { cannam@89: /* input state */ cannam@89: blast_in infun; /* input function provided by user */ cannam@89: void *inhow; /* opaque information passed to infun() */ cannam@89: unsigned char *in; /* next input location */ cannam@89: unsigned left; /* available input at in */ 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: /* output state */ cannam@89: blast_out outfun; /* output function provided by user */ cannam@89: void *outhow; /* opaque information passed to outfun() */ cannam@89: unsigned next; /* index of next write location in out[] */ cannam@89: int first; /* true to check distances (for first 4K) */ cannam@89: unsigned char out[MAXWIN]; /* output buffer and sliding window */ 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: int val; /* bit accumulator */ 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->left == 0) { cannam@89: s->left = s->infun(s->inhow, &(s->in)); cannam@89: if (s->left == 0) longjmp(s->env, 1); /* out of input */ cannam@89: } cannam@89: val |= (int)(*(s->in)++) << s->bitcnt; /* load eight bits */ cannam@89: s->left--; 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 = val >> need; cannam@89: s->bitcnt -= need; cannam@89: cannam@89: /* return need bits, zeroing the bits above that */ cannam@89: return val & ((1 << need) - 1); 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 -9 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. cannam@89: * cannam@89: * - The first code for the shortest length is all ones. Subsequent codes of cannam@89: * the same length are simply integer decrements of the previous code. When cannam@89: * moving up a length, a one bit is appended to the code. For a complete cannam@89: * code, the last code of the longest length will be all zeros. To support cannam@89: * this ordering, the bits pulled during decoding are inverted to apply the cannam@89: * more "natural" ordering starting with all zeros and incrementing. cannam@89: */ cannam@89: local int decode(struct state *s, 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) ^ 1; /* invert code */ cannam@89: bitbuf >>= 1; cannam@89: count = *next++; cannam@89: if (code < first + count) { /* 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) break; cannam@89: if (s->left == 0) { cannam@89: s->left = s->infun(s->inhow, &(s->in)); cannam@89: if (s->left == 0) longjmp(s->env, 1); /* out of input */ cannam@89: } cannam@89: bitbuf = *(s->in)++; cannam@89: s->left--; cannam@89: if (left > 8) left = 8; cannam@89: } cannam@89: return -9; /* ran out of codes */ cannam@89: } cannam@89: cannam@89: /* cannam@89: * Given a list of repeated code lengths rep[0..n-1], where each byte is a cannam@89: * count (high four bits + 1) and a code length (low four bits), generate the cannam@89: * list of code lengths. This compaction reduces the size of the object code. cannam@89: * Then 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: local int construct(struct huffman *h, const unsigned char *rep, 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: short length[256]; /* code lengths */ cannam@89: cannam@89: /* convert compact repeat counts into symbol bit length list */ cannam@89: symbol = 0; cannam@89: do { cannam@89: len = *rep++; cannam@89: left = (len >> 4) + 1; cannam@89: len &= 15; cannam@89: do { cannam@89: length[symbol++] = len; cannam@89: } while (--left); cannam@89: } while (--n); cannam@89: n = symbol; 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) 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 PKWare Compression Library stream. cannam@89: * cannam@89: * Format notes: cannam@89: * cannam@89: * - First byte is 0 if literals are uncoded or 1 if they are coded. Second cannam@89: * byte is 4, 5, or 6 for the number of extra bits in the distance code. cannam@89: * This is the base-2 logarithm of the dictionary size minus six. cannam@89: * cannam@89: * - Compressed data is a combination of literals and length/distance pairs cannam@89: * terminated by an end code. Literals are either Huffman coded or cannam@89: * uncoded 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: * - A bit preceding a literal or length/distance pair indicates which comes cannam@89: * next, 0 for literals, 1 for length/distance. cannam@89: * cannam@89: * - If literals are uncoded, then the next eight bits are the literal, in the cannam@89: * normal bit order in th stream, i.e. no bit-reversal is needed. Similarly, cannam@89: * no bit reversal is needed for either the length extra bits or the distance cannam@89: * extra bits. 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 518 cannam@89: * simply copies the last byte 518 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. cannam@89: */ cannam@89: local int decomp(struct state *s) cannam@89: { cannam@89: int lit; /* true if literals are coded */ cannam@89: int dict; /* log2(dictionary size) - 6 */ cannam@89: int symbol; /* decoded symbol, extra bits for distance */ cannam@89: int len; /* length for copy */ cannam@89: int dist; /* distance for copy */ cannam@89: int copy; /* copy counter */ cannam@89: unsigned char *from, *to; /* copy pointers */ cannam@89: static int virgin = 1; /* build tables once */ cannam@89: static short litcnt[MAXBITS+1], litsym[256]; /* litcode memory */ cannam@89: static short lencnt[MAXBITS+1], lensym[16]; /* lencode memory */ cannam@89: static short distcnt[MAXBITS+1], distsym[64]; /* distcode memory */ cannam@89: static struct huffman litcode = {litcnt, litsym}; /* length code */ cannam@89: static struct huffman lencode = {lencnt, lensym}; /* length code */ cannam@89: static struct huffman distcode = {distcnt, distsym};/* distance code */ cannam@89: /* bit lengths of literal codes */ cannam@89: static const unsigned char litlen[] = { cannam@89: 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, cannam@89: 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, cannam@89: 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, cannam@89: 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, cannam@89: 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45, cannam@89: 44, 173}; cannam@89: /* bit lengths of length codes 0..15 */ cannam@89: static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23}; cannam@89: /* bit lengths of distance codes 0..63 */ cannam@89: static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248}; cannam@89: static const short base[16] = { /* base for length codes */ cannam@89: 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264}; cannam@89: static const char extra[16] = { /* extra bits for length codes */ cannam@89: 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8}; cannam@89: cannam@89: /* set up decoding tables (once--might not be thread-safe) */ cannam@89: if (virgin) { cannam@89: construct(&litcode, litlen, sizeof(litlen)); cannam@89: construct(&lencode, lenlen, sizeof(lenlen)); cannam@89: construct(&distcode, distlen, sizeof(distlen)); cannam@89: virgin = 0; cannam@89: } cannam@89: cannam@89: /* read header */ cannam@89: lit = bits(s, 8); cannam@89: if (lit > 1) return -1; cannam@89: dict = bits(s, 8); cannam@89: if (dict < 4 || dict > 6) return -2; cannam@89: cannam@89: /* decode literals and length/distance pairs */ cannam@89: do { cannam@89: if (bits(s, 1)) { cannam@89: /* get length */ cannam@89: symbol = decode(s, &lencode); cannam@89: len = base[symbol] + bits(s, extra[symbol]); cannam@89: if (len == 519) break; /* end code */ cannam@89: cannam@89: /* get distance */ cannam@89: symbol = len == 2 ? 2 : dict; cannam@89: dist = decode(s, &distcode) << symbol; cannam@89: dist += bits(s, symbol); cannam@89: dist++; cannam@89: if (s->first && dist > s->next) cannam@89: return -3; /* distance too far back */ cannam@89: cannam@89: /* copy length bytes from distance bytes back */ cannam@89: do { cannam@89: to = s->out + s->next; cannam@89: from = to - dist; cannam@89: copy = MAXWIN; cannam@89: if (s->next < dist) { cannam@89: from += copy; cannam@89: copy = dist; cannam@89: } cannam@89: copy -= s->next; cannam@89: if (copy > len) copy = len; cannam@89: len -= copy; cannam@89: s->next += copy; cannam@89: do { cannam@89: *to++ = *from++; cannam@89: } while (--copy); cannam@89: if (s->next == MAXWIN) { cannam@89: if (s->outfun(s->outhow, s->out, s->next)) return 1; cannam@89: s->next = 0; cannam@89: s->first = 0; cannam@89: } cannam@89: } while (len != 0); cannam@89: } cannam@89: else { cannam@89: /* get literal and write it */ cannam@89: symbol = lit ? decode(s, &litcode) : bits(s, 8); cannam@89: s->out[s->next++] = symbol; cannam@89: if (s->next == MAXWIN) { cannam@89: if (s->outfun(s->outhow, s->out, s->next)) return 1; cannam@89: s->next = 0; cannam@89: s->first = 0; cannam@89: } cannam@89: } cannam@89: } while (1); cannam@89: return 0; cannam@89: } cannam@89: cannam@89: /* See comments in blast.h */ cannam@89: int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow) cannam@89: { cannam@89: struct state s; /* input/output state */ cannam@89: int err; /* return value */ cannam@89: cannam@89: /* initialize input state */ cannam@89: s.infun = infun; cannam@89: s.inhow = inhow; cannam@89: s.left = 0; cannam@89: s.bitbuf = 0; cannam@89: s.bitcnt = 0; cannam@89: cannam@89: /* initialize output state */ cannam@89: s.outfun = outfun; cannam@89: s.outhow = outhow; cannam@89: s.next = 0; cannam@89: s.first = 1; 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 decomp(), return error */ cannam@89: else cannam@89: err = decomp(&s); /* decompress */ cannam@89: cannam@89: /* write any leftover output and update the error code if needed */ cannam@89: if (err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0) cannam@89: err = 1; cannam@89: return err; cannam@89: } cannam@89: cannam@89: #ifdef TEST cannam@89: /* Example of how to use blast() */ cannam@89: #include cannam@89: #include cannam@89: cannam@89: #define CHUNK 16384 cannam@89: cannam@89: local unsigned inf(void *how, unsigned char **buf) cannam@89: { cannam@89: static unsigned char hold[CHUNK]; cannam@89: cannam@89: *buf = hold; cannam@89: return fread(hold, 1, CHUNK, (FILE *)how); cannam@89: } cannam@89: cannam@89: local int outf(void *how, unsigned char *buf, unsigned len) cannam@89: { cannam@89: return fwrite(buf, 1, len, (FILE *)how) != len; cannam@89: } cannam@89: cannam@89: /* Decompress a PKWare Compression Library stream from stdin to stdout */ cannam@89: int main(void) cannam@89: { cannam@89: int ret, n; cannam@89: cannam@89: /* decompress to stdout */ cannam@89: ret = blast(inf, stdin, outf, stdout); cannam@89: if (ret != 0) fprintf(stderr, "blast error: %d\n", ret); cannam@89: cannam@89: /* see if there are any leftover bytes */ cannam@89: n = 0; cannam@89: while (getchar() != EOF) n++; cannam@89: if (n) fprintf(stderr, "blast warning: %d unused bytes of input\n", n); cannam@89: cannam@89: /* return blast() error code */ cannam@89: return ret; cannam@89: } cannam@89: #endif