blast.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /* blast.c
  2. * Copyright (C) 2003 Mark Adler
  3. * For conditions of distribution and use, see copyright notice in blast.h
  4. * version 1.1, 16 Feb 2003
  5. *
  6. * blast.c decompresses data compressed by the PKWare Compression Library.
  7. * This function provides functionality similar to the explode() function of
  8. * the PKWare library, hence the name "blast".
  9. *
  10. * This decompressor is based on the excellent format description provided by
  11. * Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the
  12. * example Ben provided in the post is incorrect. The distance 110001 should
  13. * instead be 111000. When corrected, the example byte stream becomes:
  14. *
  15. * 00 04 82 24 25 8f 80 7f
  16. *
  17. * which decompresses to "AIAIAIAIAIAIA" (without the quotes).
  18. */
  19. /*
  20. * Change history:
  21. *
  22. * 1.0 12 Feb 2003 - First version
  23. * 1.1 16 Feb 2003 - Fixed distance check for > 4 GB uncompressed data
  24. */
  25. #include <setjmp.h> /* for setjmp(), longjmp(), and jmp_buf */
  26. #include "blast.h" /* prototype for blast() */
  27. #define local static /* for local function definitions */
  28. #define MAXBITS 13 /* maximum code length */
  29. #define MAXWIN 4096 /* maximum window size */
  30. /* input and output state */
  31. struct state {
  32. /* input state */
  33. blast_in infun; /* input function provided by user */
  34. void *inhow; /* opaque information passed to infun() */
  35. unsigned char *in; /* next input location */
  36. unsigned left; /* available input at in */
  37. int bitbuf; /* bit buffer */
  38. int bitcnt; /* number of bits in bit buffer */
  39. /* input limit error return state for bits() and decode() */
  40. jmp_buf env;
  41. /* output state */
  42. blast_out outfun; /* output function provided by user */
  43. void *outhow; /* opaque information passed to outfun() */
  44. unsigned next; /* index of next write location in out[] */
  45. int first; /* true to check distances (for first 4K) */
  46. unsigned char out[MAXWIN]; /* output buffer and sliding window */
  47. };
  48. /*
  49. * Return need bits from the input stream. This always leaves less than
  50. * eight bits in the buffer. bits() works properly for need == 0.
  51. *
  52. * Format notes:
  53. *
  54. * - Bits are stored in bytes from the least significant bit to the most
  55. * significant bit. Therefore bits are dropped from the bottom of the bit
  56. * buffer, using shift right, and new bytes are appended to the top of the
  57. * bit buffer, using shift left.
  58. */
  59. local int bits(struct state *s, int need)
  60. {
  61. int val; /* bit accumulator */
  62. /* load at least need bits into val */
  63. val = s->bitbuf;
  64. while (s->bitcnt < need) {
  65. if (s->left == 0) {
  66. s->left = s->infun(s->inhow, &(s->in));
  67. if (s->left == 0) longjmp(s->env, 1); /* out of input */
  68. }
  69. val |= (int)(*(s->in)++) << s->bitcnt; /* load eight bits */
  70. s->left--;
  71. s->bitcnt += 8;
  72. }
  73. /* drop need bits and update buffer, always zero to seven bits left */
  74. s->bitbuf = val >> need;
  75. s->bitcnt -= need;
  76. /* return need bits, zeroing the bits above that */
  77. return val & ((1 << need) - 1);
  78. }
  79. /*
  80. * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of
  81. * each length, which for a canonical code are stepped through in order.
  82. * symbol[] are the symbol values in canonical order, where the number of
  83. * entries is the sum of the counts in count[]. The decoding process can be
  84. * seen in the function decode() below.
  85. */
  86. struct huffman {
  87. short *count; /* number of symbols of each length */
  88. short *symbol; /* canonically ordered symbols */
  89. };
  90. /*
  91. * Decode a code from the stream s using huffman table h. Return the symbol or
  92. * a negative value if there is an error. If all of the lengths are zero, i.e.
  93. * an empty code, or if the code is incomplete and an invalid code is received,
  94. * then -9 is returned after reading MAXBITS bits.
  95. *
  96. * Format notes:
  97. *
  98. * - The codes as stored in the compressed data are bit-reversed relative to
  99. * a simple integer ordering of codes of the same lengths. Hence below the
  100. * bits are pulled from the compressed data one at a time and used to
  101. * build the code value reversed from what is in the stream in order to
  102. * permit simple integer comparisons for decoding.
  103. *
  104. * - The first code for the shortest length is all ones. Subsequent codes of
  105. * the same length are simply integer decrements of the previous code. When
  106. * moving up a length, a one bit is appended to the code. For a complete
  107. * code, the last code of the longest length will be all zeros. To support
  108. * this ordering, the bits pulled during decoding are inverted to apply the
  109. * more "natural" ordering starting with all zeros and incrementing.
  110. */
  111. local int decode(struct state *s, struct huffman *h)
  112. {
  113. int len; /* current number of bits in code */
  114. int code; /* len bits being decoded */
  115. int first; /* first code of length len */
  116. int count; /* number of codes of length len */
  117. int index; /* index of first code of length len in symbol table */
  118. int bitbuf; /* bits from stream */
  119. int left; /* bits left in next or left to process */
  120. short *next; /* next number of codes */
  121. bitbuf = s->bitbuf;
  122. left = s->bitcnt;
  123. code = first = index = 0;
  124. len = 1;
  125. next = h->count + 1;
  126. while (1) {
  127. while (left--) {
  128. code |= (bitbuf & 1) ^ 1; /* invert code */
  129. bitbuf >>= 1;
  130. count = *next++;
  131. if (code < first + count) { /* if length len, return symbol */
  132. s->bitbuf = bitbuf;
  133. s->bitcnt = (s->bitcnt - len) & 7;
  134. return h->symbol[index + (code - first)];
  135. }
  136. index += count; /* else update for next length */
  137. first += count;
  138. first <<= 1;
  139. code <<= 1;
  140. len++;
  141. }
  142. left = (MAXBITS+1) - len;
  143. if (left == 0) break;
  144. if (s->left == 0) {
  145. s->left = s->infun(s->inhow, &(s->in));
  146. if (s->left == 0) longjmp(s->env, 1); /* out of input */
  147. }
  148. bitbuf = *(s->in)++;
  149. s->left--;
  150. if (left > 8) left = 8;
  151. }
  152. return -9; /* ran out of codes */
  153. }
  154. /*
  155. * Given a list of repeated code lengths rep[0..n-1], where each byte is a
  156. * count (high four bits + 1) and a code length (low four bits), generate the
  157. * list of code lengths. This compaction reduces the size of the object code.
  158. * Then given the list of code lengths length[0..n-1] representing a canonical
  159. * Huffman code for n symbols, construct the tables required to decode those
  160. * codes. Those tables are the number of codes of each length, and the symbols
  161. * sorted by length, retaining their original order within each length. The
  162. * return value is zero for a complete code set, negative for an over-
  163. * subscribed code set, and positive for an incomplete code set. The tables
  164. * can be used if the return value is zero or positive, but they cannot be used
  165. * if the return value is negative. If the return value is zero, it is not
  166. * possible for decode() using that table to return an error--any stream of
  167. * enough bits will resolve to a symbol. If the return value is positive, then
  168. * it is possible for decode() using that table to return an error for received
  169. * codes past the end of the incomplete lengths.
  170. */
  171. local int construct(struct huffman *h, const unsigned char *rep, int n)
  172. {
  173. int symbol; /* current symbol when stepping through length[] */
  174. int len; /* current length when stepping through h->count[] */
  175. int left; /* number of possible codes left of current length */
  176. short offs[MAXBITS+1]; /* offsets in symbol table for each length */
  177. short length[256]; /* code lengths */
  178. /* convert compact repeat counts into symbol bit length list */
  179. symbol = 0;
  180. do {
  181. len = *rep++;
  182. left = (len >> 4) + 1;
  183. len &= 15;
  184. do {
  185. length[symbol++] = len;
  186. } while (--left);
  187. } while (--n);
  188. n = symbol;
  189. /* count number of codes of each length */
  190. for (len = 0; len <= MAXBITS; len++)
  191. h->count[len] = 0;
  192. for (symbol = 0; symbol < n; symbol++)
  193. (h->count[length[symbol]])++; /* assumes lengths are within bounds */
  194. if (h->count[0] == n) /* no codes! */
  195. return 0; /* complete, but decode() will fail */
  196. /* check for an over-subscribed or incomplete set of lengths */
  197. left = 1; /* one possible code of zero length */
  198. for (len = 1; len <= MAXBITS; len++) {
  199. left <<= 1; /* one more bit, double codes left */
  200. left -= h->count[len]; /* deduct count from possible codes */
  201. if (left < 0) return left; /* over-subscribed--return negative */
  202. } /* left > 0 means incomplete */
  203. /* generate offsets into symbol table for each length for sorting */
  204. offs[1] = 0;
  205. for (len = 1; len < MAXBITS; len++)
  206. offs[len + 1] = offs[len] + h->count[len];
  207. /*
  208. * put symbols in table sorted by length, by symbol order within each
  209. * length
  210. */
  211. for (symbol = 0; symbol < n; symbol++)
  212. if (length[symbol] != 0)
  213. h->symbol[offs[length[symbol]]++] = symbol;
  214. /* return zero for complete set, positive for incomplete set */
  215. return left;
  216. }
  217. /*
  218. * Decode PKWare Compression Library stream.
  219. *
  220. * Format notes:
  221. *
  222. * - First byte is 0 if literals are uncoded or 1 if they are coded. Second
  223. * byte is 4, 5, or 6 for the number of extra bits in the distance code.
  224. * This is the base-2 logarithm of the dictionary size minus six.
  225. *
  226. * - Compressed data is a combination of literals and length/distance pairs
  227. * terminated by an end code. Literals are either Huffman coded or
  228. * uncoded bytes. A length/distance pair is a coded length followed by a
  229. * coded distance to represent a string that occurs earlier in the
  230. * uncompressed data that occurs again at the current location.
  231. *
  232. * - A bit preceding a literal or length/distance pair indicates which comes
  233. * next, 0 for literals, 1 for length/distance.
  234. *
  235. * - If literals are uncoded, then the next eight bits are the literal, in the
  236. * normal bit order in th stream, i.e. no bit-reversal is needed. Similarly,
  237. * no bit reversal is needed for either the length extra bits or the distance
  238. * extra bits.
  239. *
  240. * - Literal bytes are simply written to the output. A length/distance pair is
  241. * an instruction to copy previously uncompressed bytes to the output. The
  242. * copy is from distance bytes back in the output stream, copying for length
  243. * bytes.
  244. *
  245. * - Distances pointing before the beginning of the output data are not
  246. * permitted.
  247. *
  248. * - Overlapped copies, where the length is greater than the distance, are
  249. * allowed and common. For example, a distance of one and a length of 518
  250. * simply copies the last byte 518 times. A distance of four and a length of
  251. * twelve copies the last four bytes three times. A simple forward copy
  252. * ignoring whether the length is greater than the distance or not implements
  253. * this correctly.
  254. */
  255. local int decomp(struct state *s)
  256. {
  257. int lit; /* true if literals are coded */
  258. int dict; /* log2(dictionary size) - 6 */
  259. int symbol; /* decoded symbol, extra bits for distance */
  260. int len; /* length for copy */
  261. int dist; /* distance for copy */
  262. int copy; /* copy counter */
  263. unsigned char *from, *to; /* copy pointers */
  264. static int virgin = 1; /* build tables once */
  265. static short litcnt[MAXBITS+1], litsym[256]; /* litcode memory */
  266. static short lencnt[MAXBITS+1], lensym[16]; /* lencode memory */
  267. static short distcnt[MAXBITS+1], distsym[64]; /* distcode memory */
  268. static struct huffman litcode = {litcnt, litsym}; /* length code */
  269. static struct huffman lencode = {lencnt, lensym}; /* length code */
  270. static struct huffman distcode = {distcnt, distsym};/* distance code */
  271. /* bit lengths of literal codes */
  272. static const unsigned char litlen[] = {
  273. 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8,
  274. 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5,
  275. 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12,
  276. 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27,
  277. 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45,
  278. 44, 173};
  279. /* bit lengths of length codes 0..15 */
  280. static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23};
  281. /* bit lengths of distance codes 0..63 */
  282. static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248};
  283. static const short base[16] = { /* base for length codes */
  284. 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264};
  285. static const char extra[16] = { /* extra bits for length codes */
  286. 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8};
  287. /* set up decoding tables (once--might not be thread-safe) */
  288. if (virgin) {
  289. construct(&litcode, litlen, sizeof(litlen));
  290. construct(&lencode, lenlen, sizeof(lenlen));
  291. construct(&distcode, distlen, sizeof(distlen));
  292. virgin = 0;
  293. }
  294. /* read header */
  295. lit = bits(s, 8);
  296. if (lit > 1) return -1;
  297. dict = bits(s, 8);
  298. if (dict < 4 || dict > 6) return -2;
  299. /* decode literals and length/distance pairs */
  300. do {
  301. if (bits(s, 1)) {
  302. /* get length */
  303. symbol = decode(s, &lencode);
  304. len = base[symbol] + bits(s, extra[symbol]);
  305. if (len == 519) break; /* end code */
  306. /* get distance */
  307. symbol = len == 2 ? 2 : dict;
  308. dist = decode(s, &distcode) << symbol;
  309. dist += bits(s, symbol);
  310. dist++;
  311. if (s->first && dist > s->next)
  312. return -3; /* distance too far back */
  313. /* copy length bytes from distance bytes back */
  314. do {
  315. to = s->out + s->next;
  316. from = to - dist;
  317. copy = MAXWIN;
  318. if (s->next < dist) {
  319. from += copy;
  320. copy = dist;
  321. }
  322. copy -= s->next;
  323. if (copy > len) copy = len;
  324. len -= copy;
  325. s->next += copy;
  326. do {
  327. *to++ = *from++;
  328. } while (--copy);
  329. if (s->next == MAXWIN) {
  330. if (s->outfun(s->outhow, s->out, s->next)) return 1;
  331. s->next = 0;
  332. s->first = 0;
  333. }
  334. } while (len != 0);
  335. }
  336. else {
  337. /* get literal and write it */
  338. symbol = lit ? decode(s, &litcode) : bits(s, 8);
  339. s->out[s->next++] = symbol;
  340. if (s->next == MAXWIN) {
  341. if (s->outfun(s->outhow, s->out, s->next)) return 1;
  342. s->next = 0;
  343. s->first = 0;
  344. }
  345. }
  346. } while (1);
  347. return 0;
  348. }
  349. /* See comments in blast.h */
  350. int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow)
  351. {
  352. struct state s; /* input/output state */
  353. int err; /* return value */
  354. /* initialize input state */
  355. s.infun = infun;
  356. s.inhow = inhow;
  357. s.left = 0;
  358. s.bitbuf = 0;
  359. s.bitcnt = 0;
  360. /* initialize output state */
  361. s.outfun = outfun;
  362. s.outhow = outhow;
  363. s.next = 0;
  364. s.first = 1;
  365. /* return if bits() or decode() tries to read past available input */
  366. if (setjmp(s.env) != 0) /* if came back here via longjmp(), */
  367. err = 2; /* then skip decomp(), return error */
  368. else
  369. err = decomp(&s); /* decompress */
  370. /* write any leftover output and update the error code if needed */
  371. if (err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0)
  372. err = 1;
  373. return err;
  374. }
  375. #ifdef TEST
  376. /* Example of how to use blast() */
  377. #include <stdio.h>
  378. #include <stdlib.h>
  379. #define CHUNK 16384
  380. local unsigned inf(void *how, unsigned char **buf)
  381. {
  382. static unsigned char hold[CHUNK];
  383. *buf = hold;
  384. return fread(hold, 1, CHUNK, (FILE *)how);
  385. }
  386. local int outf(void *how, unsigned char *buf, unsigned len)
  387. {
  388. return fwrite(buf, 1, len, (FILE *)how) != len;
  389. }
  390. /* Decompress a PKWare Compression Library stream from stdin to stdout */
  391. int main(void)
  392. {
  393. int ret, n;
  394. /* decompress to stdout */
  395. ret = blast(inf, stdin, outf, stdout);
  396. if (ret != 0) fprintf(stderr, "blast error: %d\n", ret);
  397. /* see if there are any leftover bytes */
  398. n = 0;
  399. while (getchar() != EOF) n++;
  400. if (n) fprintf(stderr, "blast warning: %d unused bytes of input\n", n);
  401. /* return blast() error code */
  402. return ret;
  403. }
  404. #endif