blast.c 18 KB

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