blast.c 17 KB

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