annotate src/zlib-1.2.8/contrib/blast/blast.c @ 43:5ea0608b923f

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