Chris@4: /* blast.c Chris@4: * Copyright (C) 2003 Mark Adler Chris@4: * For conditions of distribution and use, see copyright notice in blast.h Chris@4: * version 1.1, 16 Feb 2003 Chris@4: * Chris@4: * blast.c decompresses data compressed by the PKWare Compression Library. Chris@4: * This function provides functionality similar to the explode() function of Chris@4: * the PKWare library, hence the name "blast". Chris@4: * Chris@4: * This decompressor is based on the excellent format description provided by Chris@4: * Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the Chris@4: * example Ben provided in the post is incorrect. The distance 110001 should Chris@4: * instead be 111000. When corrected, the example byte stream becomes: Chris@4: * Chris@4: * 00 04 82 24 25 8f 80 7f Chris@4: * Chris@4: * which decompresses to "AIAIAIAIAIAIA" (without the quotes). Chris@4: */ Chris@4: Chris@4: /* Chris@4: * Change history: Chris@4: * Chris@4: * 1.0 12 Feb 2003 - First version Chris@4: * 1.1 16 Feb 2003 - Fixed distance check for > 4 GB uncompressed data Chris@4: */ Chris@4: Chris@4: #include /* for setjmp(), longjmp(), and jmp_buf */ Chris@4: #include "blast.h" /* prototype for blast() */ Chris@4: Chris@4: #define local static /* for local function definitions */ Chris@4: #define MAXBITS 13 /* maximum code length */ Chris@4: #define MAXWIN 4096 /* maximum window size */ Chris@4: Chris@4: /* input and output state */ Chris@4: struct state { Chris@4: /* input state */ Chris@4: blast_in infun; /* input function provided by user */ Chris@4: void *inhow; /* opaque information passed to infun() */ Chris@4: unsigned char *in; /* next input location */ Chris@4: unsigned left; /* available input at in */ Chris@4: int bitbuf; /* bit buffer */ Chris@4: int bitcnt; /* number of bits in bit buffer */ Chris@4: Chris@4: /* input limit error return state for bits() and decode() */ Chris@4: jmp_buf env; Chris@4: Chris@4: /* output state */ Chris@4: blast_out outfun; /* output function provided by user */ Chris@4: void *outhow; /* opaque information passed to outfun() */ Chris@4: unsigned next; /* index of next write location in out[] */ Chris@4: int first; /* true to check distances (for first 4K) */ Chris@4: unsigned char out[MAXWIN]; /* output buffer and sliding window */ Chris@4: }; Chris@4: Chris@4: /* Chris@4: * Return need bits from the input stream. This always leaves less than Chris@4: * eight bits in the buffer. bits() works properly for need == 0. Chris@4: * Chris@4: * Format notes: Chris@4: * Chris@4: * - Bits are stored in bytes from the least significant bit to the most Chris@4: * significant bit. Therefore bits are dropped from the bottom of the bit Chris@4: * buffer, using shift right, and new bytes are appended to the top of the Chris@4: * bit buffer, using shift left. Chris@4: */ Chris@4: local int bits(struct state *s, int need) Chris@4: { Chris@4: int val; /* bit accumulator */ Chris@4: Chris@4: /* load at least need bits into val */ Chris@4: val = s->bitbuf; Chris@4: while (s->bitcnt < need) { Chris@4: if (s->left == 0) { Chris@4: s->left = s->infun(s->inhow, &(s->in)); Chris@4: if (s->left == 0) longjmp(s->env, 1); /* out of input */ Chris@4: } Chris@4: val |= (int)(*(s->in)++) << s->bitcnt; /* load eight bits */ Chris@4: s->left--; Chris@4: s->bitcnt += 8; Chris@4: } Chris@4: Chris@4: /* drop need bits and update buffer, always zero to seven bits left */ Chris@4: s->bitbuf = val >> need; Chris@4: s->bitcnt -= need; Chris@4: Chris@4: /* return need bits, zeroing the bits above that */ Chris@4: return val & ((1 << need) - 1); Chris@4: } Chris@4: Chris@4: /* Chris@4: * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of Chris@4: * each length, which for a canonical code are stepped through in order. Chris@4: * symbol[] are the symbol values in canonical order, where the number of Chris@4: * entries is the sum of the counts in count[]. The decoding process can be Chris@4: * seen in the function decode() below. Chris@4: */ Chris@4: struct huffman { Chris@4: short *count; /* number of symbols of each length */ Chris@4: short *symbol; /* canonically ordered symbols */ Chris@4: }; Chris@4: Chris@4: /* Chris@4: * Decode a code from the stream s using huffman table h. Return the symbol or Chris@4: * a negative value if there is an error. If all of the lengths are zero, i.e. Chris@4: * an empty code, or if the code is incomplete and an invalid code is received, Chris@4: * then -9 is returned after reading MAXBITS bits. Chris@4: * Chris@4: * Format notes: Chris@4: * Chris@4: * - The codes as stored in the compressed data are bit-reversed relative to Chris@4: * a simple integer ordering of codes of the same lengths. Hence below the Chris@4: * bits are pulled from the compressed data one at a time and used to Chris@4: * build the code value reversed from what is in the stream in order to Chris@4: * permit simple integer comparisons for decoding. Chris@4: * Chris@4: * - The first code for the shortest length is all ones. Subsequent codes of Chris@4: * the same length are simply integer decrements of the previous code. When Chris@4: * moving up a length, a one bit is appended to the code. For a complete Chris@4: * code, the last code of the longest length will be all zeros. To support Chris@4: * this ordering, the bits pulled during decoding are inverted to apply the Chris@4: * more "natural" ordering starting with all zeros and incrementing. Chris@4: */ Chris@4: local int decode(struct state *s, struct huffman *h) Chris@4: { Chris@4: int len; /* current number of bits in code */ Chris@4: int code; /* len bits being decoded */ Chris@4: int first; /* first code of length len */ Chris@4: int count; /* number of codes of length len */ Chris@4: int index; /* index of first code of length len in symbol table */ Chris@4: int bitbuf; /* bits from stream */ Chris@4: int left; /* bits left in next or left to process */ Chris@4: short *next; /* next number of codes */ Chris@4: Chris@4: bitbuf = s->bitbuf; Chris@4: left = s->bitcnt; Chris@4: code = first = index = 0; Chris@4: len = 1; Chris@4: next = h->count + 1; Chris@4: while (1) { Chris@4: while (left--) { Chris@4: code |= (bitbuf & 1) ^ 1; /* invert code */ Chris@4: bitbuf >>= 1; Chris@4: count = *next++; Chris@4: if (code < first + count) { /* if length len, return symbol */ Chris@4: s->bitbuf = bitbuf; Chris@4: s->bitcnt = (s->bitcnt - len) & 7; Chris@4: return h->symbol[index + (code - first)]; Chris@4: } Chris@4: index += count; /* else update for next length */ Chris@4: first += count; Chris@4: first <<= 1; Chris@4: code <<= 1; Chris@4: len++; Chris@4: } Chris@4: left = (MAXBITS+1) - len; Chris@4: if (left == 0) break; Chris@4: if (s->left == 0) { Chris@4: s->left = s->infun(s->inhow, &(s->in)); Chris@4: if (s->left == 0) longjmp(s->env, 1); /* out of input */ Chris@4: } Chris@4: bitbuf = *(s->in)++; Chris@4: s->left--; Chris@4: if (left > 8) left = 8; Chris@4: } Chris@4: return -9; /* ran out of codes */ Chris@4: } Chris@4: Chris@4: /* Chris@4: * Given a list of repeated code lengths rep[0..n-1], where each byte is a Chris@4: * count (high four bits + 1) and a code length (low four bits), generate the Chris@4: * list of code lengths. This compaction reduces the size of the object code. Chris@4: * Then given the list of code lengths length[0..n-1] representing a canonical Chris@4: * Huffman code for n symbols, construct the tables required to decode those Chris@4: * codes. Those tables are the number of codes of each length, and the symbols Chris@4: * sorted by length, retaining their original order within each length. The Chris@4: * return value is zero for a complete code set, negative for an over- Chris@4: * subscribed code set, and positive for an incomplete code set. The tables Chris@4: * can be used if the return value is zero or positive, but they cannot be used Chris@4: * if the return value is negative. If the return value is zero, it is not Chris@4: * possible for decode() using that table to return an error--any stream of Chris@4: * enough bits will resolve to a symbol. If the return value is positive, then Chris@4: * it is possible for decode() using that table to return an error for received Chris@4: * codes past the end of the incomplete lengths. Chris@4: */ Chris@4: local int construct(struct huffman *h, const unsigned char *rep, int n) Chris@4: { Chris@4: int symbol; /* current symbol when stepping through length[] */ Chris@4: int len; /* current length when stepping through h->count[] */ Chris@4: int left; /* number of possible codes left of current length */ Chris@4: short offs[MAXBITS+1]; /* offsets in symbol table for each length */ Chris@4: short length[256]; /* code lengths */ Chris@4: Chris@4: /* convert compact repeat counts into symbol bit length list */ Chris@4: symbol = 0; Chris@4: do { Chris@4: len = *rep++; Chris@4: left = (len >> 4) + 1; Chris@4: len &= 15; Chris@4: do { Chris@4: length[symbol++] = len; Chris@4: } while (--left); Chris@4: } while (--n); Chris@4: n = symbol; Chris@4: Chris@4: /* count number of codes of each length */ Chris@4: for (len = 0; len <= MAXBITS; len++) Chris@4: h->count[len] = 0; Chris@4: for (symbol = 0; symbol < n; symbol++) Chris@4: (h->count[length[symbol]])++; /* assumes lengths are within bounds */ Chris@4: if (h->count[0] == n) /* no codes! */ Chris@4: return 0; /* complete, but decode() will fail */ Chris@4: Chris@4: /* check for an over-subscribed or incomplete set of lengths */ Chris@4: left = 1; /* one possible code of zero length */ Chris@4: for (len = 1; len <= MAXBITS; len++) { Chris@4: left <<= 1; /* one more bit, double codes left */ Chris@4: left -= h->count[len]; /* deduct count from possible codes */ Chris@4: if (left < 0) return left; /* over-subscribed--return negative */ Chris@4: } /* left > 0 means incomplete */ Chris@4: Chris@4: /* generate offsets into symbol table for each length for sorting */ Chris@4: offs[1] = 0; Chris@4: for (len = 1; len < MAXBITS; len++) Chris@4: offs[len + 1] = offs[len] + h->count[len]; Chris@4: Chris@4: /* Chris@4: * put symbols in table sorted by length, by symbol order within each Chris@4: * length Chris@4: */ Chris@4: for (symbol = 0; symbol < n; symbol++) Chris@4: if (length[symbol] != 0) Chris@4: h->symbol[offs[length[symbol]]++] = symbol; Chris@4: Chris@4: /* return zero for complete set, positive for incomplete set */ Chris@4: return left; Chris@4: } Chris@4: Chris@4: /* Chris@4: * Decode PKWare Compression Library stream. Chris@4: * Chris@4: * Format notes: Chris@4: * Chris@4: * - First byte is 0 if literals are uncoded or 1 if they are coded. Second Chris@4: * byte is 4, 5, or 6 for the number of extra bits in the distance code. Chris@4: * This is the base-2 logarithm of the dictionary size minus six. Chris@4: * Chris@4: * - Compressed data is a combination of literals and length/distance pairs Chris@4: * terminated by an end code. Literals are either Huffman coded or Chris@4: * uncoded bytes. A length/distance pair is a coded length followed by a Chris@4: * coded distance to represent a string that occurs earlier in the Chris@4: * uncompressed data that occurs again at the current location. Chris@4: * Chris@4: * - A bit preceding a literal or length/distance pair indicates which comes Chris@4: * next, 0 for literals, 1 for length/distance. Chris@4: * Chris@4: * - If literals are uncoded, then the next eight bits are the literal, in the Chris@4: * normal bit order in th stream, i.e. no bit-reversal is needed. Similarly, Chris@4: * no bit reversal is needed for either the length extra bits or the distance Chris@4: * extra bits. Chris@4: * Chris@4: * - Literal bytes are simply written to the output. A length/distance pair is Chris@4: * an instruction to copy previously uncompressed bytes to the output. The Chris@4: * copy is from distance bytes back in the output stream, copying for length Chris@4: * bytes. Chris@4: * Chris@4: * - Distances pointing before the beginning of the output data are not Chris@4: * permitted. Chris@4: * Chris@4: * - Overlapped copies, where the length is greater than the distance, are Chris@4: * allowed and common. For example, a distance of one and a length of 518 Chris@4: * simply copies the last byte 518 times. A distance of four and a length of Chris@4: * twelve copies the last four bytes three times. A simple forward copy Chris@4: * ignoring whether the length is greater than the distance or not implements Chris@4: * this correctly. Chris@4: */ Chris@4: local int decomp(struct state *s) Chris@4: { Chris@4: int lit; /* true if literals are coded */ Chris@4: int dict; /* log2(dictionary size) - 6 */ Chris@4: int symbol; /* decoded symbol, extra bits for distance */ Chris@4: int len; /* length for copy */ Chris@4: int dist; /* distance for copy */ Chris@4: int copy; /* copy counter */ Chris@4: unsigned char *from, *to; /* copy pointers */ Chris@4: static int virgin = 1; /* build tables once */ Chris@4: static short litcnt[MAXBITS+1], litsym[256]; /* litcode memory */ Chris@4: static short lencnt[MAXBITS+1], lensym[16]; /* lencode memory */ Chris@4: static short distcnt[MAXBITS+1], distsym[64]; /* distcode memory */ Chris@4: static struct huffman litcode = {litcnt, litsym}; /* length code */ Chris@4: static struct huffman lencode = {lencnt, lensym}; /* length code */ Chris@4: static struct huffman distcode = {distcnt, distsym};/* distance code */ Chris@4: /* bit lengths of literal codes */ Chris@4: static const unsigned char litlen[] = { Chris@4: 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, Chris@4: 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, Chris@4: 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, Chris@4: 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, Chris@4: 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45, Chris@4: 44, 173}; Chris@4: /* bit lengths of length codes 0..15 */ Chris@4: static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23}; Chris@4: /* bit lengths of distance codes 0..63 */ Chris@4: static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248}; Chris@4: static const short base[16] = { /* base for length codes */ Chris@4: 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264}; Chris@4: static const char extra[16] = { /* extra bits for length codes */ Chris@4: 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8}; Chris@4: Chris@4: /* set up decoding tables (once--might not be thread-safe) */ Chris@4: if (virgin) { Chris@4: construct(&litcode, litlen, sizeof(litlen)); Chris@4: construct(&lencode, lenlen, sizeof(lenlen)); Chris@4: construct(&distcode, distlen, sizeof(distlen)); Chris@4: virgin = 0; Chris@4: } Chris@4: Chris@4: /* read header */ Chris@4: lit = bits(s, 8); Chris@4: if (lit > 1) return -1; Chris@4: dict = bits(s, 8); Chris@4: if (dict < 4 || dict > 6) return -2; Chris@4: Chris@4: /* decode literals and length/distance pairs */ Chris@4: do { Chris@4: if (bits(s, 1)) { Chris@4: /* get length */ Chris@4: symbol = decode(s, &lencode); Chris@4: len = base[symbol] + bits(s, extra[symbol]); Chris@4: if (len == 519) break; /* end code */ Chris@4: Chris@4: /* get distance */ Chris@4: symbol = len == 2 ? 2 : dict; Chris@4: dist = decode(s, &distcode) << symbol; Chris@4: dist += bits(s, symbol); Chris@4: dist++; Chris@4: if (s->first && dist > s->next) Chris@4: return -3; /* distance too far back */ Chris@4: Chris@4: /* copy length bytes from distance bytes back */ Chris@4: do { Chris@4: to = s->out + s->next; Chris@4: from = to - dist; Chris@4: copy = MAXWIN; Chris@4: if (s->next < dist) { Chris@4: from += copy; Chris@4: copy = dist; Chris@4: } Chris@4: copy -= s->next; Chris@4: if (copy > len) copy = len; Chris@4: len -= copy; Chris@4: s->next += copy; Chris@4: do { Chris@4: *to++ = *from++; Chris@4: } while (--copy); Chris@4: if (s->next == MAXWIN) { Chris@4: if (s->outfun(s->outhow, s->out, s->next)) return 1; Chris@4: s->next = 0; Chris@4: s->first = 0; Chris@4: } Chris@4: } while (len != 0); Chris@4: } Chris@4: else { Chris@4: /* get literal and write it */ Chris@4: symbol = lit ? decode(s, &litcode) : bits(s, 8); Chris@4: s->out[s->next++] = symbol; Chris@4: if (s->next == MAXWIN) { Chris@4: if (s->outfun(s->outhow, s->out, s->next)) return 1; Chris@4: s->next = 0; Chris@4: s->first = 0; Chris@4: } Chris@4: } Chris@4: } while (1); Chris@4: return 0; Chris@4: } Chris@4: Chris@4: /* See comments in blast.h */ Chris@4: int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow) Chris@4: { Chris@4: struct state s; /* input/output state */ Chris@4: int err; /* return value */ Chris@4: Chris@4: /* initialize input state */ Chris@4: s.infun = infun; Chris@4: s.inhow = inhow; Chris@4: s.left = 0; Chris@4: s.bitbuf = 0; Chris@4: s.bitcnt = 0; Chris@4: Chris@4: /* initialize output state */ Chris@4: s.outfun = outfun; Chris@4: s.outhow = outhow; Chris@4: s.next = 0; Chris@4: s.first = 1; Chris@4: Chris@4: /* return if bits() or decode() tries to read past available input */ Chris@4: if (setjmp(s.env) != 0) /* if came back here via longjmp(), */ Chris@4: err = 2; /* then skip decomp(), return error */ Chris@4: else Chris@4: err = decomp(&s); /* decompress */ Chris@4: Chris@4: /* write any leftover output and update the error code if needed */ Chris@4: if (err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0) Chris@4: err = 1; Chris@4: return err; Chris@4: } Chris@4: Chris@4: #ifdef TEST Chris@4: /* Example of how to use blast() */ Chris@4: #include Chris@4: #include Chris@4: Chris@4: #define CHUNK 16384 Chris@4: Chris@4: local unsigned inf(void *how, unsigned char **buf) Chris@4: { Chris@4: static unsigned char hold[CHUNK]; Chris@4: Chris@4: *buf = hold; Chris@4: return fread(hold, 1, CHUNK, (FILE *)how); Chris@4: } Chris@4: Chris@4: local int outf(void *how, unsigned char *buf, unsigned len) Chris@4: { Chris@4: return fwrite(buf, 1, len, (FILE *)how) != len; Chris@4: } Chris@4: Chris@4: /* Decompress a PKWare Compression Library stream from stdin to stdout */ Chris@4: int main(void) Chris@4: { Chris@4: int ret, n; Chris@4: Chris@4: /* decompress to stdout */ Chris@4: ret = blast(inf, stdin, outf, stdout); Chris@4: if (ret != 0) fprintf(stderr, "blast error: %d\n", ret); Chris@4: Chris@4: /* see if there are any leftover bytes */ Chris@4: n = 0; Chris@4: while (getchar() != EOF) n++; Chris@4: if (n) fprintf(stderr, "blast warning: %d unused bytes of input\n", n); Chris@4: Chris@4: /* return blast() error code */ Chris@4: return ret; Chris@4: } Chris@4: #endif