blast.c 17 KB

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