1 /* inflate.c -- zlib decompression
2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
5 local void fixedtables OF((struct inflate_state FAR *state));
6 local int updatewindow OF((z_streamp strm, unsigned out));
8 int ZEXPORT inflateReset(z_streamp strm)
10 struct inflate_state FAR *state;
12 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
13 state = (struct inflate_state FAR *)strm->state;
14 strm->total_in = strm->total_out = state->total = 0;
16 strm->adler = 1; /* to support ill-conceived Java test suite */
27 state->lencode = state->distcode = state->next = state->codes;
29 Tracev((stderr, "inflate: reset\n"));
33 int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version,
36 struct inflate_state FAR *state;
38 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
39 stream_size != (int)(sizeof(z_stream)))
40 return Z_VERSION_ERROR;
41 if (strm == Z_NULL) return Z_STREAM_ERROR;
42 strm->msg = Z_NULL; /* in case we return an error */
43 if (strm->zalloc == (alloc_func)0) {
44 strm->zalloc = zcalloc;
45 strm->opaque = (voidpf)0;
47 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
48 state = (struct inflate_state FAR *)
49 ZALLOC(strm, 1, sizeof(struct inflate_state));
50 if (state == Z_NULL) return Z_MEM_ERROR;
51 Tracev((stderr, "inflate: allocated\n"));
52 strm->state = (struct internal_state FAR *)state;
55 windowBits = -windowBits;
58 state->wrap = (windowBits >> 4) + 1;
60 if (windowBits < 48) windowBits &= 15;
63 if (windowBits < 8 || windowBits > 15) {
66 return Z_STREAM_ERROR;
68 state->wbits = (unsigned)windowBits;
69 state->window = Z_NULL;
70 return inflateReset(strm);
73 int ZEXPORT inflateInit_(z_streamp strm, const char *version, int stream_size)
75 return inflateInit2_(strm, DEF_WBITS, version, stream_size);
78 local void fixedtables(struct inflate_state FAR *state)
80 state->lencode = lenfix;
82 state->distcode = distfix;
87 Update the window with the last wsize (normally 32K) bytes written before
88 returning. If window does not exist yet, create it. This is only called
89 when a window is already in use, or when output has been written during this
90 inflate call, but the end of the deflate stream has not been reached yet.
91 It is also called to create a window for dictionary data when a dictionary
94 Providing output buffers larger than 32K to inflate() should provide a speed
95 advantage, since only the last 32K of output is copied to the sliding window
96 upon return from inflate(), and since all distances after the first 32K of
97 output will fall in the output data, making match copies simpler and faster.
98 The advantage may be dependent on the size of the processor's data caches.
100 local int updatewindow(z_streamp strm, unsigned out)
102 struct inflate_state FAR *state;
105 state = (struct inflate_state FAR *)strm->state;
107 /* if it hasn't been done already, allocate space for the window */
108 if (state->window == Z_NULL) {
109 state->window = (unsigned char FAR *)
110 ZALLOC(strm, 1U << state->wbits,
111 sizeof(unsigned char));
112 if (state->window == Z_NULL) return 1;
115 /* if window not in use yet, initialize */
116 if (state->wsize == 0) {
117 state->wsize = 1U << state->wbits;
122 /* copy state->wsize or less output bytes into the circular window */
123 copy = out - strm->avail_out;
124 if (copy >= state->wsize) {
125 zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
127 state->whave = state->wsize;
130 dist = state->wsize - state->write;
131 if (dist > copy) dist = copy;
132 zmemcpy(state->window + state->write, strm->next_out - copy, dist);
135 zmemcpy(state->window, strm->next_out - copy, copy);
137 state->whave = state->wsize;
140 state->write += dist;
141 if (state->write == state->wsize) state->write = 0;
142 if (state->whave < state->wsize) state->whave += dist;
148 /* Macros for inflate(): */
150 /* check function to use adler32() for zlib or crc32() for gzip */
152 # define UPDATE(check, buf, len) \
153 (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
155 # define UPDATE(check, buf, len) adler32(check, buf, len)
158 /* check macros for header crc */
160 # define CRC2(check, word) \
162 hbuf[0] = (unsigned char)(word); \
163 hbuf[1] = (unsigned char)((word) >> 8); \
164 check = crc32(check, hbuf, 2); \
167 # define CRC4(check, word) \
169 hbuf[0] = (unsigned char)(word); \
170 hbuf[1] = (unsigned char)((word) >> 8); \
171 hbuf[2] = (unsigned char)((word) >> 16); \
172 hbuf[3] = (unsigned char)((word) >> 24); \
173 check = crc32(check, hbuf, 4); \
177 /* Load registers with state in inflate() for speed */
180 put = strm->next_out; \
181 left = strm->avail_out; \
182 next = strm->next_in; \
183 have = strm->avail_in; \
184 hold = state->hold; \
185 bits = state->bits; \
188 /* Restore state from registers in inflate() */
191 strm->next_out = put; \
192 strm->avail_out = left; \
193 strm->next_in = next; \
194 strm->avail_in = have; \
195 state->hold = hold; \
196 state->bits = bits; \
199 /* Clear the input bit accumulator */
206 /* Get a byte of input into the bit accumulator, or return from inflate()
207 if there is no input available. */
210 if (have == 0) goto inf_leave; \
212 hold += (unsigned long)(*next++) << bits; \
216 /* Assure that there are at least n bits in the bit accumulator. If there is
217 not enough available input to do that, then return from inflate(). */
218 #define NEEDBITS(n) \
220 while (bits < (unsigned)(n)) \
224 /* Return the low n bits of the bit accumulator (n < 16) */
226 ((unsigned)hold & ((1U << (n)) - 1))
228 /* Remove n bits from the bit accumulator */
229 #define DROPBITS(n) \
232 bits -= (unsigned)(n); \
235 /* Remove zero to seven bits as needed to go to a byte boundary */
242 /* Reverse the bytes in a 32-bit value */
244 ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
245 (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
248 inflate() uses a state machine to process as much input data and generate as
249 much output data as possible before returning. The state machine is
250 structured roughly as follows:
252 for (;;) switch (state) {
255 if (not enough input data or output space to make progress)
257 ... make progress ...
263 so when inflate() is called again, the same case is attempted again, and
264 if the appropriate resources are provided, the machine proceeds to the
265 next state. The NEEDBITS() macro is usually the way the state evaluates
266 whether it can proceed or should return. NEEDBITS() does the return if
267 the requested bits are not available. The typical use of the BITS macros
271 ... do something with BITS(n) ...
274 where NEEDBITS(n) either returns from inflate() if there isn't enough
275 input left to load n bits into the accumulator, or it continues. BITS(n)
276 gives the low n bits in the accumulator. When done, DROPBITS(n) drops
277 the low n bits off the accumulator. INITBITS() clears the accumulator
278 and sets the number of available bits to zero. BYTEBITS() discards just
279 enough bits to put the accumulator on a byte boundary. After BYTEBITS()
280 and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
282 NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
283 if there is no input available. The decoding of variable length codes uses
284 PULLBYTE() directly in order to pull just enough bytes to decode the next
287 Some states loop until they get enough input, making sure that enough
288 state information is maintained to continue the loop where it left off
289 if NEEDBITS() returns in the loop. For example, want, need, and keep
290 would all have to actually be part of the saved state in case NEEDBITS()
294 while (want < need) {
296 keep[want++] = BITS(n);
302 As shown above, if the next state is also the next case, then the break
305 A state may also return if there is not enough output space available to
306 complete that state. Those states are copying stored data, writing a
307 literal byte, and copying a matching string.
309 When returning, a "goto inf_leave" is used to update the total counters,
310 update the check value, and determine whether any progress has been made
311 during that inflate() call in order to return the proper return code.
312 Progress is defined as a change in either strm->avail_in or strm->avail_out.
313 When there is a window, goto inf_leave will update the window with the last
314 output written. If a goto inf_leave occurs in the middle of decompression
315 and there is no window currently, goto inf_leave will create one and copy
316 output to the window for the next call of inflate().
318 In this implementation, the flush parameter of inflate() only affects the
319 return code (per zlib.h). inflate() always writes as much as possible to
320 strm->next_out, given the space available and the provided input--the effect
321 documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
322 the allocation of and copying into a sliding window until necessary, which
323 provides the effect documented in zlib.h for Z_FINISH when the entire input
324 stream available. So the only thing the flush parameter actually does is:
325 when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
326 will return Z_BUF_ERROR if it has not reached the end of the stream.
328 int ZEXPORT inflate(z_streamp strm, int flush)
330 struct inflate_state FAR *state;
331 unsigned char FAR *next; /* next input */
332 unsigned char FAR *put; /* next output */
333 unsigned have, left; /* available input and output */
334 unsigned long hold; /* bit buffer */
335 unsigned bits; /* bits in bit buffer */
336 unsigned in, out; /* save starting available input and output */
337 unsigned copy; /* number of stored or match bytes to copy */
338 unsigned char FAR *from; /* where to copy match bytes from */
339 code this; /* current decoding table entry */
340 code last; /* parent table entry */
341 unsigned len; /* length to copy for repeats, bits to drop */
342 int ret; /* return code */
344 unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
346 static const unsigned short order[19] = /* permutation of code lengths */
347 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
349 if (strm == Z_NULL || strm->state == Z_NULL ||
350 (strm->next_in == Z_NULL && strm->avail_in != 0))
351 return Z_STREAM_ERROR;
353 state = (struct inflate_state FAR *)strm->state;
354 if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
360 switch (state->mode) {
362 if (state->wrap == 0) {
363 state->mode = TYPEDO;
368 if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
369 state->check = crc32(0L, Z_NULL, 0);
370 CRC2(state->check, hold);
375 state->flags = 0; /* expect zlib header */
376 if (state->head != Z_NULL)
377 state->head->done = -1;
378 if (!(state->wrap & 1) || /* check if zlib header allowed */
382 ((BITS(8) << 8) + (hold >> 8)) % 31) {
383 strm->msg = (char *)"incorrect header check";
387 if (BITS(4) != Z_DEFLATED) {
388 strm->msg = (char *)"unknown compression method";
394 if (len > state->wbits) {
395 strm->msg = (char *)"invalid window size";
399 state->dmax = 1U << len;
400 Tracev((stderr, "inflate: zlib header ok\n"));
401 strm->adler = state->check = adler32(0L, Z_NULL, 0);
402 state->mode = hold & 0x200 ? DICTID : TYPE;
408 state->flags = (int)(hold);
409 if ((state->flags & 0xff) != Z_DEFLATED) {
410 strm->msg = (char *)"unknown compression method";
414 if (state->flags & 0xe000) {
415 strm->msg = (char *)"unknown header flags set";
419 if (state->head != Z_NULL)
420 state->head->text = (int)((hold >> 8) & 1);
421 if (state->flags & 0x0200) CRC2(state->check, hold);
426 if (state->head != Z_NULL)
427 state->head->time = hold;
428 if (state->flags & 0x0200) CRC4(state->check, hold);
433 if (state->head != Z_NULL) {
434 state->head->xflags = (int)(hold & 0xff);
435 state->head->os = (int)(hold >> 8);
437 if (state->flags & 0x0200) CRC2(state->check, hold);
441 if (state->flags & 0x0400) {
443 state->length = (unsigned)(hold);
444 if (state->head != Z_NULL)
445 state->head->extra_len = (unsigned)hold;
446 if (state->flags & 0x0200) CRC2(state->check, hold);
449 else if (state->head != Z_NULL)
450 state->head->extra = Z_NULL;
453 if (state->flags & 0x0400) {
454 copy = state->length;
455 if (copy > have) copy = have;
457 if (state->head != Z_NULL &&
458 state->head->extra != Z_NULL) {
459 len = state->head->extra_len - state->length;
460 zmemcpy(state->head->extra + len, next,
461 len + copy > state->head->extra_max ?
462 state->head->extra_max - len : copy);
464 if (state->flags & 0x0200)
465 state->check = crc32(state->check, next, copy);
468 state->length -= copy;
470 if (state->length) goto inf_leave;
475 if (state->flags & 0x0800) {
476 if (have == 0) goto inf_leave;
479 len = (unsigned)(next[copy++]);
480 if (state->head != Z_NULL &&
481 state->head->name != Z_NULL &&
482 state->length < state->head->name_max)
483 state->head->name[state->length++] = len;
484 } while (len && copy < have);
485 if (state->flags & 0x0200)
486 state->check = crc32(state->check, next, copy);
489 if (len) goto inf_leave;
491 else if (state->head != Z_NULL)
492 state->head->name = Z_NULL;
494 state->mode = COMMENT;
496 if (state->flags & 0x1000) {
497 if (have == 0) goto inf_leave;
500 len = (unsigned)(next[copy++]);
501 if (state->head != Z_NULL &&
502 state->head->comment != Z_NULL &&
503 state->length < state->head->comm_max)
504 state->head->comment[state->length++] = len;
505 } while (len && copy < have);
506 if (state->flags & 0x0200)
507 state->check = crc32(state->check, next, copy);
510 if (len) goto inf_leave;
512 else if (state->head != Z_NULL)
513 state->head->comment = Z_NULL;
516 if (state->flags & 0x0200) {
518 if (hold != (state->check & 0xffff)) {
519 strm->msg = (char *)"header crc mismatch";
525 if (state->head != Z_NULL) {
526 state->head->hcrc = (int)((state->flags >> 9) & 1);
527 state->head->done = 1;
529 strm->adler = state->check = crc32(0L, Z_NULL, 0);
535 strm->adler = state->check = REVERSE(hold);
539 if (state->havedict == 0) {
543 strm->adler = state->check = adler32(0L, Z_NULL, 0);
547 if (flush == Z_BLOCK) goto inf_leave;
555 state->last = BITS(1);
558 case 0: /* stored block */
559 Tracev((stderr, "inflate: stored block%s\n",
560 state->last ? " (last)" : ""));
561 state->mode = STORED;
563 case 1: /* fixed block */
565 Tracev((stderr, "inflate: fixed codes block%s\n",
566 state->last ? " (last)" : ""));
567 state->mode = LEN; /* decode codes */
569 case 2: /* dynamic block */
570 Tracev((stderr, "inflate: dynamic codes block%s\n",
571 state->last ? " (last)" : ""));
575 strm->msg = (char *)"invalid block type";
581 BYTEBITS(); /* go to byte boundary */
583 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
584 strm->msg = (char *)"invalid stored block lengths";
588 state->length = (unsigned)hold & 0xffff;
589 Tracev((stderr, "inflate: stored length %u\n",
594 copy = state->length;
596 if (copy > have) copy = have;
597 if (copy > left) copy = left;
598 if (copy == 0) goto inf_leave;
599 zmemcpy(put, next, copy);
604 state->length -= copy;
607 Tracev((stderr, "inflate: stored end\n"));
612 state->nlen = BITS(5) + 257;
614 state->ndist = BITS(5) + 1;
616 state->ncode = BITS(4) + 4;
618 #ifndef PKZIP_BUG_WORKAROUND
619 if (state->nlen > 286 || state->ndist > 30) {
620 strm->msg = (char *)"too many length or distance symbols";
625 Tracev((stderr, "inflate: table sizes ok\n"));
627 state->mode = LENLENS;
629 while (state->have < state->ncode) {
631 state->lens[order[state->have++]] = (unsigned short)BITS(3);
634 while (state->have < 19)
635 state->lens[order[state->have++]] = 0;
636 state->next = state->codes;
637 state->lencode = (code const FAR *)(state->next);
639 ret = inflate_table(CODES, state->lens, 19, &(state->next),
640 &(state->lenbits), state->work);
642 strm->msg = (char *)"invalid code lengths set";
646 Tracev((stderr, "inflate: code lengths ok\n"));
648 state->mode = CODELENS;
650 while (state->have < state->nlen + state->ndist) {
652 this = state->lencode[BITS(state->lenbits)];
653 if ((unsigned)(this.bits) <= bits) break;
659 state->lens[state->have++] = this.val;
662 if (this.val == 16) {
663 NEEDBITS(this.bits + 2);
665 if (state->have == 0) {
666 strm->msg = (char *)"invalid bit length repeat";
670 len = state->lens[state->have - 1];
674 else if (this.val == 17) {
675 NEEDBITS(this.bits + 3);
682 NEEDBITS(this.bits + 7);
688 if (state->have + copy > state->nlen + state->ndist) {
689 strm->msg = (char *)"invalid bit length repeat";
694 state->lens[state->have++] = (unsigned short)len;
698 /* handle error breaks in while */
699 if (state->mode == BAD) break;
701 /* build code tables */
702 state->next = state->codes;
703 state->lencode = (code const FAR *)(state->next);
705 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
706 &(state->lenbits), state->work);
708 strm->msg = (char *)"invalid literal/lengths set";
712 state->distcode = (code const FAR *)(state->next);
714 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
715 &(state->next), &(state->distbits), state->work);
717 strm->msg = (char *)"invalid distances set";
721 Tracev((stderr, "inflate: codes ok\n"));
725 if (have >= 6 && left >= 258) {
727 inflate_fast(strm, out);
732 this = state->lencode[BITS(state->lenbits)];
733 if ((unsigned)(this.bits) <= bits) break;
736 if (this.op && (this.op & 0xf0) == 0) {
739 this = state->lencode[last.val +
740 (BITS(last.bits + last.op) >> last.bits)];
741 if ((unsigned)(last.bits + this.bits) <= bits) break;
747 state->length = (unsigned)this.val;
748 if ((int)(this.op) == 0) {
749 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
750 "inflate: literal '%c'\n" :
751 "inflate: literal 0x%02x\n", this.val));
756 Tracevv((stderr, "inflate: end of block\n"));
761 strm->msg = (char *)"invalid literal/length code";
765 state->extra = (unsigned)(this.op) & 15;
766 state->mode = LENEXT;
769 NEEDBITS(state->extra);
770 state->length += BITS(state->extra);
771 DROPBITS(state->extra);
773 Tracevv((stderr, "inflate: length %u\n", state->length));
777 this = state->distcode[BITS(state->distbits)];
778 if ((unsigned)(this.bits) <= bits) break;
781 if ((this.op & 0xf0) == 0) {
784 this = state->distcode[last.val +
785 (BITS(last.bits + last.op) >> last.bits)];
786 if ((unsigned)(last.bits + this.bits) <= bits) break;
793 strm->msg = (char *)"invalid distance code";
797 state->offset = (unsigned)this.val;
798 state->extra = (unsigned)(this.op) & 15;
799 state->mode = DISTEXT;
802 NEEDBITS(state->extra);
803 state->offset += BITS(state->extra);
804 DROPBITS(state->extra);
806 #ifdef INFLATE_STRICT
807 if (state->offset > state->dmax) {
808 strm->msg = (char *)"invalid distance too far back";
813 if (state->offset > state->whave + out - left) {
814 strm->msg = (char *)"invalid distance too far back";
818 Tracevv((stderr, "inflate: distance %u\n", state->offset));
821 if (left == 0) goto inf_leave;
823 if (state->offset > copy) { /* copy from window */
824 copy = state->offset - copy;
825 if (copy > state->write) {
826 copy -= state->write;
827 from = state->window + (state->wsize - copy);
830 from = state->window + (state->write - copy);
831 if (copy > state->length) copy = state->length;
833 else { /* copy from output */
834 from = put - state->offset;
835 copy = state->length;
837 if (copy > left) copy = left;
839 state->length -= copy;
843 if (state->length == 0) state->mode = LEN;
846 if (left == 0) goto inf_leave;
847 *put++ = (unsigned char)(state->length);
855 strm->total_out += out;
858 strm->adler = state->check =
859 UPDATE(state->check, put - out, out);
863 state->flags ? hold :
865 REVERSE(hold)) != state->check) {
866 strm->msg = (char *)"incorrect data check";
871 Tracev((stderr, "inflate: check matches trailer\n"));
874 state->mode = LENGTH;
876 if (state->wrap && state->flags) {
878 if (hold != (state->total & 0xffffffffUL)) {
879 strm->msg = (char *)"incorrect length check";
884 Tracev((stderr, "inflate: length matches trailer\n"));
898 return Z_STREAM_ERROR;
902 Return from inflate(), updating the total counts and the check value.
903 If there was no progress during the inflate() call, return a buffer
904 error. Call updatewindow() to create and/or update the window state.
905 Note: a memory error from inflate() is non-recoverable.
909 if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
910 if (updatewindow(strm, out)) {
914 in -= strm->avail_in;
915 out -= strm->avail_out;
916 strm->total_in += in;
917 strm->total_out += out;
919 if (state->wrap && out)
920 strm->adler = state->check =
921 UPDATE(state->check, strm->next_out - out, out);
922 strm->data_type = state->bits + (state->last ? 64 : 0) +
923 (state->mode == TYPE ? 128 : 0);
924 if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
929 int ZEXPORT inflateEnd(z_streamp strm)
931 struct inflate_state FAR *state;
932 if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
933 return Z_STREAM_ERROR;
934 state = (struct inflate_state FAR *)strm->state;
935 if (state->window != Z_NULL) {
937 ZFREE(strm, state->window);
939 ZFREE(strm, strm->state);
940 strm->state = Z_NULL;
941 Tracev((stderr, "inflate: end\n"));