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