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