1 /* inflate.c -- zlib decompression
2 * Copyright (C) 1995-2022 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
9 * 1.2.beta0 24 Nov 2002
10 * - First version -- complete rewrite of inflate to simplify code, avoid
11 * creation of window when not needed, minimize use of window when it is
12 * needed, make inffast.c even faster, implement gzip decoding, and to
13 * improve code readability and style over the previous zlib inflate code
15 * 1.2.beta1 25 Nov 2002
16 * - Use pointers for available input and output checking in inffast.c
17 * - Remove input and output counters in inffast.c
18 * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
19 * - Remove unnecessary second byte pull from length extra in inffast.c
20 * - Unroll direct copy to three copies per loop in inffast.c
22 * 1.2.beta2 4 Dec 2002
23 * - Change external routine names to reduce potential conflicts
24 * - Correct filename to inffixed.h for fixed tables in inflate.c
25 * - Make hbuf[] unsigned char to match parameter type in inflate.c
26 * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
27 * to avoid negation problem on Alphas (64 bit) in inflate.c
29 * 1.2.beta3 22 Dec 2002
30 * - Add comments on state->bits assertion in inffast.c
31 * - Add comments on op field in inftrees.h
32 * - Fix bug in reuse of allocated window after inflateReset()
33 * - Remove bit fields--back to byte structure for speed
34 * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
35 * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
36 * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
37 * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
38 * - Use local copies of stream next and avail values, as well as local bit
39 * buffer and bit count in inflate()--for speed when inflate_fast() not used
41 * 1.2.beta4 1 Jan 2003
42 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
43 * - Move a comment on output buffer sizes from inffast.c to inflate.c
44 * - Add comments in inffast.c to introduce the inflate_fast() routine
45 * - Rearrange window copies in inflate_fast() for speed and simplification
46 * - Unroll last copy for window match in inflate_fast()
47 * - Use local copies of window variables in inflate_fast() for speed
48 * - Pull out common wnext == 0 case for speed in inflate_fast()
49 * - Make op and len in inflate_fast() unsigned for consistency
50 * - Add FAR to lcode and dcode declarations in inflate_fast()
51 * - Simplified bad distance check in inflate_fast()
52 * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
53 * source file infback.c to provide a call-back interface to inflate for
54 * programs like gzip and unzip -- uses window as output buffer to avoid
57 * 1.2.beta5 1 Jan 2003
58 * - Improved inflateBack() interface to allow the caller to provide initial
60 * - Fixed stored blocks bug in inflateBack()
62 * 1.2.beta6 4 Jan 2003
63 * - Added comments in inffast.c on effectiveness of POSTINC
64 * - Typecasting all around to reduce compiler warnings
65 * - Changed loops from while (1) or do {} while (1) to for (;;), again to
66 * make compilers happy
67 * - Changed type of window in inflateBackInit() to unsigned char *
69 * 1.2.beta7 27 Jan 2003
70 * - Changed many types to unsigned or unsigned short to avoid warnings
71 * - Added inflateCopy() function
74 * - Changed inflateBack() interface to provide separate opaque descriptors
75 * for the in() and out() functions
76 * - Changed inflateBack() argument and in_func typedef to swap the length
77 * and buffer address return values for the input function
78 * - Check next_in and next_out for Z_NULL on entry to inflate()
80 * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
94 /* function prototypes */
95 local int inflateStateCheck OF((z_streamp strm));
96 local void fixedtables OF((struct inflate_state FAR *state));
97 local int updatewindow OF((z_streamp strm, const unsigned char FAR *end,
100 void makefixed OF((void));
103 local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,
107 local int inflateStateCheck(
110 struct inflate_state FAR *state;
111 if (strm == Z_NULL ||
112 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
114 state = (struct inflate_state FAR *)strm->state;
115 if (state == Z_NULL || state->strm != strm ||
116 state->mode < HEAD || state->mode > SYNC)
121 int ZEXPORT inflateResetKeep(
124 struct inflate_state FAR *state;
126 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
127 state = (struct inflate_state FAR *)strm->state;
128 strm->total_in = strm->total_out = state->total = 0;
130 if (state->wrap) /* to support ill-conceived Java test suite */
131 strm->adler = state->wrap & 1;
136 state->dmax = 32768U;
137 state->head = Z_NULL;
140 state->lencode = state->distcode = state->next = state->codes;
143 Tracev((stderr, "inflate: reset\n"));
147 int ZEXPORT inflateReset(
150 struct inflate_state FAR *state;
152 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
153 state = (struct inflate_state FAR *)strm->state;
157 return inflateResetKeep(strm);
160 int ZEXPORT inflateReset2(
165 struct inflate_state FAR *state;
168 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
169 state = (struct inflate_state FAR *)strm->state;
171 /* extract wrap request from windowBits parameter */
172 if (windowBits < 0) {
173 if (windowBits < -15)
174 return Z_STREAM_ERROR;
176 windowBits = -windowBits;
179 wrap = (windowBits >> 4) + 5;
186 /* set number of window bits, free window if different */
187 if (windowBits && (windowBits < 8 || windowBits > 15))
188 return Z_STREAM_ERROR;
189 if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
190 ZFREE(strm, state->window);
191 state->window = Z_NULL;
194 /* update state and reset the rest of it */
196 state->wbits = (unsigned)windowBits;
197 return inflateReset(strm);
200 int ZEXPORT inflateInit2_(
207 struct inflate_state FAR *state;
209 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
210 stream_size != (int)(sizeof(z_stream)))
211 return Z_VERSION_ERROR;
212 if (strm == Z_NULL) return Z_STREAM_ERROR;
213 strm->msg = Z_NULL; /* in case we return an error */
214 if (strm->zalloc == (alloc_func)0) {
216 return Z_STREAM_ERROR;
218 strm->zalloc = zcalloc;
219 strm->opaque = (voidpf)0;
222 if (strm->zfree == (free_func)0)
224 return Z_STREAM_ERROR;
226 strm->zfree = zcfree;
228 state = (struct inflate_state FAR *)
229 ZALLOC(strm, 1, sizeof(struct inflate_state));
230 if (state == Z_NULL) return Z_MEM_ERROR;
231 Tracev((stderr, "inflate: allocated\n"));
232 strm->state = (struct internal_state FAR *)state;
234 state->window = Z_NULL;
235 state->mode = HEAD; /* to pass state test in inflateReset2() */
236 ret = inflateReset2(strm, windowBits);
239 strm->state = Z_NULL;
246 int ZEXPORT inflateInit_(
251 return inflateInit2_(strm, DEF_WBITS, version, stream_size);
254 int ZEXPORT inflatePrime(
259 struct inflate_state FAR *state;
261 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
262 state = (struct inflate_state FAR *)strm->state;
268 if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;
269 value &= (1L << bits) - 1;
270 state->hold += (unsigned)value << state->bits;
271 state->bits += (uInt)bits;
275 #endif /* !Z_FREETYPE */
278 Return state with length and distance decoding tables and index sizes set to
279 fixed code decoding. Normally this returns fixed tables from inffixed.h.
280 If BUILDFIXED is defined, then instead this routine builds the tables the
281 first time it's called, and returns those tables the first time and
282 thereafter. This reduces the size of the code by about 2K bytes, in
283 exchange for a little execution time. However, BUILDFIXED should not be
284 used for threaded applications, since the rewriting of the tables and virgin
285 may not be thread-safe.
287 local void fixedtables(
288 struct inflate_state FAR *state)
291 static int virgin = 1;
292 static code *lenfix, *distfix;
293 static code fixed[544];
295 /* build fixed huffman tables if first call (may not be thread safe) */
300 /* literal/length table */
302 while (sym < 144) state->lens[sym++] = 8;
303 while (sym < 256) state->lens[sym++] = 9;
304 while (sym < 280) state->lens[sym++] = 7;
305 while (sym < 288) state->lens[sym++] = 8;
309 inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
313 while (sym < 32) state->lens[sym++] = 5;
316 inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
318 /* do this just once */
321 #else /* !BUILDFIXED */
322 # include "inffixed.h"
323 #endif /* BUILDFIXED */
324 state->lencode = lenfix;
326 state->distcode = distfix;
334 Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
335 defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
336 those tables to stdout, which would be piped to inffixed.h. A small program
337 can simply call makefixed to do this:
339 void makefixed(void);
347 Then that can be linked with zlib built with MAKEFIXED defined and run:
354 struct inflate_state state;
357 puts(" /* inffixed.h -- table for decoding fixed codes");
358 puts(" * Generated automatically by makefixed().");
361 puts(" /* WARNING: this file should *not* be used by applications.");
362 puts(" It is part of the implementation of this library and is");
363 puts(" subject to change. Applications should only use zlib.h.");
367 printf(" static const code lenfix[%u] = {", size);
370 if ((low % 7) == 0) printf("\n ");
371 printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
372 state.lencode[low].bits, state.lencode[low].val);
373 if (++low == size) break;
378 printf("\n static const code distfix[%u] = {", size);
381 if ((low % 6) == 0) printf("\n ");
382 printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
383 state.distcode[low].val);
384 if (++low == size) break;
389 #endif /* MAKEFIXED */
392 Update the window with the last wsize (normally 32K) bytes written before
393 returning. If window does not exist yet, create it. This is only called
394 when a window is already in use, or when output has been written during this
395 inflate call, but the end of the deflate stream has not been reached yet.
396 It is also called to create a window for dictionary data when a dictionary
399 Providing output buffers larger than 32K to inflate() should provide a speed
400 advantage, since only the last 32K of output is copied to the sliding window
401 upon return from inflate(), and since all distances after the first 32K of
402 output will fall in the output data, making match copies simpler and faster.
403 The advantage may be dependent on the size of the processor's data caches.
405 local int updatewindow(
410 struct inflate_state FAR *state;
413 state = (struct inflate_state FAR *)strm->state;
415 /* if it hasn't been done already, allocate space for the window */
416 if (state->window == Z_NULL) {
417 state->window = (unsigned char FAR *)
418 ZALLOC(strm, 1U << state->wbits,
419 sizeof(unsigned char));
420 if (state->window == Z_NULL) return 1;
423 /* if window not in use yet, initialize */
424 if (state->wsize == 0) {
425 state->wsize = 1U << state->wbits;
430 /* copy state->wsize or less output bytes into the circular window */
431 if (copy >= state->wsize) {
432 zmemcpy(state->window, end - state->wsize, state->wsize);
434 state->whave = state->wsize;
437 dist = state->wsize - state->wnext;
438 if (dist > copy) dist = copy;
439 zmemcpy(state->window + state->wnext, end - copy, dist);
442 zmemcpy(state->window, end - copy, copy);
444 state->whave = state->wsize;
447 state->wnext += dist;
448 if (state->wnext == state->wsize) state->wnext = 0;
449 if (state->whave < state->wsize) state->whave += dist;
455 /* Macros for inflate(): */
457 /* check function to use adler32() for zlib or crc32() for gzip */
459 # define UPDATE_CHECK(check, buf, len) \
460 (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
462 # define UPDATE_CHECK(check, buf, len) adler32(check, buf, len)
465 /* check macros for header crc */
467 # define CRC2(check, word) \
469 hbuf[0] = (unsigned char)(word); \
470 hbuf[1] = (unsigned char)((word) >> 8); \
471 check = crc32(check, hbuf, 2); \
474 # define CRC4(check, word) \
476 hbuf[0] = (unsigned char)(word); \
477 hbuf[1] = (unsigned char)((word) >> 8); \
478 hbuf[2] = (unsigned char)((word) >> 16); \
479 hbuf[3] = (unsigned char)((word) >> 24); \
480 check = crc32(check, hbuf, 4); \
484 /* Load registers with state in inflate() for speed */
487 put = strm->next_out; \
488 left = strm->avail_out; \
489 next = strm->next_in; \
490 have = strm->avail_in; \
491 hold = state->hold; \
492 bits = state->bits; \
495 /* Restore state from registers in inflate() */
498 strm->next_out = put; \
499 strm->avail_out = left; \
500 strm->next_in = next; \
501 strm->avail_in = have; \
502 state->hold = hold; \
503 state->bits = bits; \
506 /* Clear the input bit accumulator */
513 /* Get a byte of input into the bit accumulator, or return from inflate()
514 if there is no input available. */
517 if (have == 0) goto inf_leave; \
519 hold += (unsigned long)(*next++) << bits; \
523 /* Assure that there are at least n bits in the bit accumulator. If there is
524 not enough available input to do that, then return from inflate(). */
525 #define NEEDBITS(n) \
527 while (bits < (unsigned)(n)) \
531 /* Return the low n bits of the bit accumulator (n < 16) */
533 ((unsigned)hold & ((1U << (n)) - 1))
535 /* Remove n bits from the bit accumulator */
536 #define DROPBITS(n) \
539 bits -= (unsigned)(n); \
542 /* Remove zero to seven bits as needed to go to a byte boundary */
550 inflate() uses a state machine to process as much input data and generate as
551 much output data as possible before returning. The state machine is
552 structured roughly as follows:
554 for (;;) switch (state) {
557 if (not enough input data or output space to make progress)
559 ... make progress ...
565 so when inflate() is called again, the same case is attempted again, and
566 if the appropriate resources are provided, the machine proceeds to the
567 next state. The NEEDBITS() macro is usually the way the state evaluates
568 whether it can proceed or should return. NEEDBITS() does the return if
569 the requested bits are not available. The typical use of the BITS macros
573 ... do something with BITS(n) ...
576 where NEEDBITS(n) either returns from inflate() if there isn't enough
577 input left to load n bits into the accumulator, or it continues. BITS(n)
578 gives the low n bits in the accumulator. When done, DROPBITS(n) drops
579 the low n bits off the accumulator. INITBITS() clears the accumulator
580 and sets the number of available bits to zero. BYTEBITS() discards just
581 enough bits to put the accumulator on a byte boundary. After BYTEBITS()
582 and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
584 NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
585 if there is no input available. The decoding of variable length codes uses
586 PULLBYTE() directly in order to pull just enough bytes to decode the next
589 Some states loop until they get enough input, making sure that enough
590 state information is maintained to continue the loop where it left off
591 if NEEDBITS() returns in the loop. For example, want, need, and keep
592 would all have to actually be part of the saved state in case NEEDBITS()
596 while (want < need) {
598 keep[want++] = BITS(n);
604 As shown above, if the next state is also the next case, then the break
607 A state may also return if there is not enough output space available to
608 complete that state. Those states are copying stored data, writing a
609 literal byte, and copying a matching string.
611 When returning, a "goto inf_leave" is used to update the total counters,
612 update the check value, and determine whether any progress has been made
613 during that inflate() call in order to return the proper return code.
614 Progress is defined as a change in either strm->avail_in or strm->avail_out.
615 When there is a window, goto inf_leave will update the window with the last
616 output written. If a goto inf_leave occurs in the middle of decompression
617 and there is no window currently, goto inf_leave will create one and copy
618 output to the window for the next call of inflate().
620 In this implementation, the flush parameter of inflate() only affects the
621 return code (per zlib.h). inflate() always writes as much as possible to
622 strm->next_out, given the space available and the provided input--the effect
623 documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
624 the allocation of and copying into a sliding window until necessary, which
625 provides the effect documented in zlib.h for Z_FINISH when the entire input
626 stream available. So the only thing the flush parameter actually does is:
627 when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
628 will return Z_BUF_ERROR if it has not reached the end of the stream.
635 struct inflate_state FAR *state;
636 z_const unsigned char FAR *next; /* next input */
637 unsigned char FAR *put; /* next output */
638 unsigned have, left; /* available input and output */
639 unsigned long hold; /* bit buffer */
640 unsigned bits; /* bits in bit buffer */
641 unsigned in, out; /* save starting available input and output */
642 unsigned copy; /* number of stored or match bytes to copy */
643 unsigned char FAR *from; /* where to copy match bytes from */
644 code here; /* current decoding table entry */
645 code last; /* parent table entry */
646 unsigned len; /* length to copy for repeats, bits to drop */
647 int ret; /* return code */
649 unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
651 static const unsigned short order[19] = /* permutation of code lengths */
652 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
654 if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||
655 (strm->next_in == Z_NULL && strm->avail_in != 0))
656 return Z_STREAM_ERROR;
658 state = (struct inflate_state FAR *)strm->state;
659 if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
665 switch (state->mode) {
667 if (state->wrap == 0) {
668 state->mode = TYPEDO;
673 if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
674 if (state->wbits == 0)
676 state->check = crc32(0L, Z_NULL, 0);
677 CRC2(state->check, hold);
682 if (state->head != Z_NULL)
683 state->head->done = -1;
684 if (!(state->wrap & 1) || /* check if zlib header allowed */
688 ((BITS(8) << 8) + (hold >> 8)) % 31) {
689 strm->msg = (char *)"incorrect header check";
693 if (BITS(4) != Z_DEFLATED) {
694 strm->msg = (char *)"unknown compression method";
700 if (state->wbits == 0)
702 if (len > 15 || len > state->wbits) {
703 strm->msg = (char *)"invalid window size";
707 state->dmax = 1U << len;
708 state->flags = 0; /* indicate zlib header */
709 Tracev((stderr, "inflate: zlib header ok\n"));
710 strm->adler = state->check = adler32(0L, Z_NULL, 0);
711 state->mode = hold & 0x200 ? DICTID : TYPE;
717 state->flags = (int)(hold);
718 if ((state->flags & 0xff) != Z_DEFLATED) {
719 strm->msg = (char *)"unknown compression method";
723 if (state->flags & 0xe000) {
724 strm->msg = (char *)"unknown header flags set";
728 if (state->head != Z_NULL)
729 state->head->text = (int)((hold >> 8) & 1);
730 if ((state->flags & 0x0200) && (state->wrap & 4))
731 CRC2(state->check, hold);
737 if (state->head != Z_NULL)
738 state->head->time = hold;
739 if ((state->flags & 0x0200) && (state->wrap & 4))
740 CRC4(state->check, hold);
746 if (state->head != Z_NULL) {
747 state->head->xflags = (int)(hold & 0xff);
748 state->head->os = (int)(hold >> 8);
750 if ((state->flags & 0x0200) && (state->wrap & 4))
751 CRC2(state->check, hold);
756 if (state->flags & 0x0400) {
758 state->length = (unsigned)(hold);
759 if (state->head != Z_NULL)
760 state->head->extra_len = (unsigned)hold;
761 if ((state->flags & 0x0200) && (state->wrap & 4))
762 CRC2(state->check, hold);
765 else if (state->head != Z_NULL)
766 state->head->extra = Z_NULL;
770 if (state->flags & 0x0400) {
771 copy = state->length;
772 if (copy > have) copy = have;
774 if (state->head != Z_NULL &&
775 state->head->extra != Z_NULL &&
776 (len = state->head->extra_len - state->length) <
777 state->head->extra_max) {
778 zmemcpy(state->head->extra + len, next,
779 len + copy > state->head->extra_max ?
780 state->head->extra_max - len : copy);
782 if ((state->flags & 0x0200) && (state->wrap & 4))
783 state->check = crc32(state->check, next, copy);
786 state->length -= copy;
788 if (state->length) goto inf_leave;
794 if (state->flags & 0x0800) {
795 if (have == 0) goto inf_leave;
798 len = (unsigned)(next[copy++]);
799 if (state->head != Z_NULL &&
800 state->head->name != Z_NULL &&
801 state->length < state->head->name_max)
802 state->head->name[state->length++] = (Bytef)len;
803 } while (len && copy < have);
804 if ((state->flags & 0x0200) && (state->wrap & 4))
805 state->check = crc32(state->check, next, copy);
808 if (len) goto inf_leave;
810 else if (state->head != Z_NULL)
811 state->head->name = Z_NULL;
813 state->mode = COMMENT;
816 if (state->flags & 0x1000) {
817 if (have == 0) goto inf_leave;
820 len = (unsigned)(next[copy++]);
821 if (state->head != Z_NULL &&
822 state->head->comment != Z_NULL &&
823 state->length < state->head->comm_max)
824 state->head->comment[state->length++] = (Bytef)len;
825 } while (len && copy < have);
826 if ((state->flags & 0x0200) && (state->wrap & 4))
827 state->check = crc32(state->check, next, copy);
830 if (len) goto inf_leave;
832 else if (state->head != Z_NULL)
833 state->head->comment = Z_NULL;
837 if (state->flags & 0x0200) {
839 if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
840 strm->msg = (char *)"header crc mismatch";
846 if (state->head != Z_NULL) {
847 state->head->hcrc = (int)((state->flags >> 9) & 1);
848 state->head->done = 1;
850 strm->adler = state->check = crc32(0L, Z_NULL, 0);
856 strm->adler = state->check = ZSWAP32(hold);
861 if (state->havedict == 0) {
865 strm->adler = state->check = adler32(0L, Z_NULL, 0);
869 if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
878 state->last = BITS(1);
881 case 0: /* stored block */
882 Tracev((stderr, "inflate: stored block%s\n",
883 state->last ? " (last)" : ""));
884 state->mode = STORED;
886 case 1: /* fixed block */
888 Tracev((stderr, "inflate: fixed codes block%s\n",
889 state->last ? " (last)" : ""));
890 state->mode = LEN_; /* decode codes */
891 if (flush == Z_TREES) {
896 case 2: /* dynamic block */
897 Tracev((stderr, "inflate: dynamic codes block%s\n",
898 state->last ? " (last)" : ""));
902 strm->msg = (char *)"invalid block type";
908 BYTEBITS(); /* go to byte boundary */
910 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
911 strm->msg = (char *)"invalid stored block lengths";
915 state->length = (unsigned)hold & 0xffff;
916 Tracev((stderr, "inflate: stored length %u\n",
920 if (flush == Z_TREES) goto inf_leave;
926 copy = state->length;
928 if (copy > have) copy = have;
929 if (copy > left) copy = left;
930 if (copy == 0) goto inf_leave;
931 zmemcpy(put, next, copy);
936 state->length -= copy;
939 Tracev((stderr, "inflate: stored end\n"));
944 state->nlen = BITS(5) + 257;
946 state->ndist = BITS(5) + 1;
948 state->ncode = BITS(4) + 4;
950 #ifndef PKZIP_BUG_WORKAROUND
951 if (state->nlen > 286 || state->ndist > 30) {
952 strm->msg = (char *)"too many length or distance symbols";
957 Tracev((stderr, "inflate: table sizes ok\n"));
959 state->mode = LENLENS;
962 while (state->have < state->ncode) {
964 state->lens[order[state->have++]] = (unsigned short)BITS(3);
967 while (state->have < 19)
968 state->lens[order[state->have++]] = 0;
969 state->next = state->codes;
970 state->lencode = (const code FAR *)(state->next);
972 ret = inflate_table(CODES, state->lens, 19, &(state->next),
973 &(state->lenbits), state->work);
975 strm->msg = (char *)"invalid code lengths set";
979 Tracev((stderr, "inflate: code lengths ok\n"));
981 state->mode = CODELENS;
984 while (state->have < state->nlen + state->ndist) {
986 here = state->lencode[BITS(state->lenbits)];
987 if ((unsigned)(here.bits) <= bits) break;
992 state->lens[state->have++] = here.val;
995 if (here.val == 16) {
996 NEEDBITS(here.bits + 2);
998 if (state->have == 0) {
999 strm->msg = (char *)"invalid bit length repeat";
1003 len = state->lens[state->have - 1];
1007 else if (here.val == 17) {
1008 NEEDBITS(here.bits + 3);
1009 DROPBITS(here.bits);
1015 NEEDBITS(here.bits + 7);
1016 DROPBITS(here.bits);
1018 copy = 11 + BITS(7);
1021 if (state->have + copy > state->nlen + state->ndist) {
1022 strm->msg = (char *)"invalid bit length repeat";
1027 state->lens[state->have++] = (unsigned short)len;
1031 /* handle error breaks in while */
1032 if (state->mode == BAD) break;
1034 /* check for end-of-block code (better have one) */
1035 if (state->lens[256] == 0) {
1036 strm->msg = (char *)"invalid code -- missing end-of-block";
1041 /* build code tables -- note: do not change the lenbits or distbits
1042 values here (9 and 6) without reading the comments in inftrees.h
1043 concerning the ENOUGH constants, which depend on those values */
1044 state->next = state->codes;
1045 state->lencode = (const code FAR *)(state->next);
1047 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
1048 &(state->lenbits), state->work);
1050 strm->msg = (char *)"invalid literal/lengths set";
1054 state->distcode = (const code FAR *)(state->next);
1055 state->distbits = 6;
1056 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
1057 &(state->next), &(state->distbits), state->work);
1059 strm->msg = (char *)"invalid distances set";
1063 Tracev((stderr, "inflate: codes ok\n"));
1065 if (flush == Z_TREES) goto inf_leave;
1071 if (have >= 6 && left >= 258) {
1073 inflate_fast(strm, out);
1075 if (state->mode == TYPE)
1081 here = state->lencode[BITS(state->lenbits)];
1082 if ((unsigned)(here.bits) <= bits) break;
1085 if (here.op && (here.op & 0xf0) == 0) {
1088 here = state->lencode[last.val +
1089 (BITS(last.bits + last.op) >> last.bits)];
1090 if ((unsigned)(last.bits + here.bits) <= bits) break;
1093 DROPBITS(last.bits);
1094 state->back += last.bits;
1096 DROPBITS(here.bits);
1097 state->back += here.bits;
1098 state->length = (unsigned)here.val;
1099 if ((int)(here.op) == 0) {
1100 Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
1101 "inflate: literal '%c'\n" :
1102 "inflate: literal 0x%02x\n", here.val));
1107 Tracevv((stderr, "inflate: end of block\n"));
1113 strm->msg = (char *)"invalid literal/length code";
1117 state->extra = (unsigned)(here.op) & 15;
1118 state->mode = LENEXT;
1122 NEEDBITS(state->extra);
1123 state->length += BITS(state->extra);
1124 DROPBITS(state->extra);
1125 state->back += state->extra;
1127 Tracevv((stderr, "inflate: length %u\n", state->length));
1128 state->was = state->length;
1133 here = state->distcode[BITS(state->distbits)];
1134 if ((unsigned)(here.bits) <= bits) break;
1137 if ((here.op & 0xf0) == 0) {
1140 here = state->distcode[last.val +
1141 (BITS(last.bits + last.op) >> last.bits)];
1142 if ((unsigned)(last.bits + here.bits) <= bits) break;
1145 DROPBITS(last.bits);
1146 state->back += last.bits;
1148 DROPBITS(here.bits);
1149 state->back += here.bits;
1151 strm->msg = (char *)"invalid distance code";
1155 state->offset = (unsigned)here.val;
1156 state->extra = (unsigned)(here.op) & 15;
1157 state->mode = DISTEXT;
1161 NEEDBITS(state->extra);
1162 state->offset += BITS(state->extra);
1163 DROPBITS(state->extra);
1164 state->back += state->extra;
1166 #ifdef INFLATE_STRICT
1167 if (state->offset > state->dmax) {
1168 strm->msg = (char *)"invalid distance too far back";
1173 Tracevv((stderr, "inflate: distance %u\n", state->offset));
1174 state->mode = MATCH;
1177 if (left == 0) goto inf_leave;
1179 if (state->offset > copy) { /* copy from window */
1180 copy = state->offset - copy;
1181 if (copy > state->whave) {
1183 strm->msg = (char *)"invalid distance too far back";
1187 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1188 Trace((stderr, "inflate.c too far\n"));
1189 copy -= state->whave;
1190 if (copy > state->length) copy = state->length;
1191 if (copy > left) copy = left;
1193 state->length -= copy;
1197 if (state->length == 0) state->mode = LEN;
1201 if (copy > state->wnext) {
1202 copy -= state->wnext;
1203 from = state->window + (state->wsize - copy);
1206 from = state->window + (state->wnext - copy);
1207 if (copy > state->length) copy = state->length;
1209 else { /* copy from output */
1210 from = put - state->offset;
1211 copy = state->length;
1213 if (copy > left) copy = left;
1215 state->length -= copy;
1219 if (state->length == 0) state->mode = LEN;
1222 if (left == 0) goto inf_leave;
1223 *put++ = (unsigned char)(state->length);
1231 strm->total_out += out;
1232 state->total += out;
1233 if ((state->wrap & 4) && out)
1234 strm->adler = state->check =
1235 UPDATE_CHECK(state->check, put - out, out);
1237 if ((state->wrap & 4) && (
1239 state->flags ? hold :
1241 ZSWAP32(hold)) != state->check) {
1242 strm->msg = (char *)"incorrect data check";
1247 Tracev((stderr, "inflate: check matches trailer\n"));
1250 state->mode = LENGTH;
1253 if (state->wrap && state->flags) {
1255 if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {
1256 strm->msg = (char *)"incorrect length check";
1261 Tracev((stderr, "inflate: length matches trailer\n"));
1277 return Z_STREAM_ERROR;
1281 Return from inflate(), updating the total counts and the check value.
1282 If there was no progress during the inflate() call, return a buffer
1283 error. Call updatewindow() to create and/or update the window state.
1284 Note: a memory error from inflate() is non-recoverable.
1288 if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
1289 (state->mode < CHECK || flush != Z_FINISH)))
1290 if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
1294 in -= strm->avail_in;
1295 out -= strm->avail_out;
1296 strm->total_in += in;
1297 strm->total_out += out;
1298 state->total += out;
1299 if ((state->wrap & 4) && out)
1300 strm->adler = state->check =
1301 UPDATE_CHECK(state->check, strm->next_out - out, out);
1302 strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
1303 (state->mode == TYPE ? 128 : 0) +
1304 (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
1305 if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
1310 int ZEXPORT inflateEnd(
1313 struct inflate_state FAR *state;
1314 if (inflateStateCheck(strm))
1315 return Z_STREAM_ERROR;
1316 state = (struct inflate_state FAR *)strm->state;
1317 if (state->window != Z_NULL) ZFREE(strm, state->window);
1318 ZFREE(strm, strm->state);
1319 strm->state = Z_NULL;
1320 Tracev((stderr, "inflate: end\n"));
1326 int ZEXPORT inflateGetDictionary(
1331 struct inflate_state FAR *state;
1334 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1335 state = (struct inflate_state FAR *)strm->state;
1337 /* copy dictionary */
1338 if (state->whave && dictionary != Z_NULL) {
1339 zmemcpy(dictionary, state->window + state->wnext,
1340 state->whave - state->wnext);
1341 zmemcpy(dictionary + state->whave - state->wnext,
1342 state->window, state->wnext);
1344 if (dictLength != Z_NULL)
1345 *dictLength = state->whave;
1349 int ZEXPORT inflateSetDictionary(
1351 const Bytef *dictionary,
1354 struct inflate_state FAR *state;
1355 unsigned long dictid;
1359 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1360 state = (struct inflate_state FAR *)strm->state;
1361 if (state->wrap != 0 && state->mode != DICT)
1362 return Z_STREAM_ERROR;
1364 /* check for correct dictionary identifier */
1365 if (state->mode == DICT) {
1366 dictid = adler32(0L, Z_NULL, 0);
1367 dictid = adler32(dictid, dictionary, dictLength);
1368 if (dictid != state->check)
1369 return Z_DATA_ERROR;
1372 /* copy dictionary to window using updatewindow(), which will amend the
1373 existing dictionary if appropriate */
1374 ret = updatewindow(strm, dictionary + dictLength, dictLength);
1379 state->havedict = 1;
1380 Tracev((stderr, "inflate: dictionary set\n"));
1384 int ZEXPORT inflateGetHeader(
1388 struct inflate_state FAR *state;
1391 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1392 state = (struct inflate_state FAR *)strm->state;
1393 if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
1395 /* save header structure */
1402 Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
1403 or when out of input. When called, *have is the number of pattern bytes
1404 found in order so far, in 0..3. On return *have is updated to the new
1405 state. If on return *have equals four, then the pattern was found and the
1406 return value is how many bytes were read including the last byte of the
1407 pattern. If *have is less than four, then the pattern has not been found
1408 yet and the return value is len. In the latter case, syncsearch() can be
1409 called again with more data and the *have state. *have is initialized to
1410 zero for the first call.
1412 local unsigned syncsearch(
1414 const unsigned char FAR *buf,
1422 while (next < len && got < 4) {
1423 if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
1435 int ZEXPORT inflateSync(
1438 unsigned len; /* number of bytes to look at or looked at */
1439 int flags; /* temporary to save header status */
1440 unsigned long in, out; /* temporary to save total_in and total_out */
1441 unsigned char buf[4]; /* to restore bit buffer to byte string */
1442 struct inflate_state FAR *state;
1444 /* check parameters */
1445 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1446 state = (struct inflate_state FAR *)strm->state;
1447 if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
1449 /* if first time, start search in bit buffer */
1450 if (state->mode != SYNC) {
1452 state->hold <<= state->bits & 7;
1453 state->bits -= state->bits & 7;
1455 while (state->bits >= 8) {
1456 buf[len++] = (unsigned char)(state->hold);
1461 syncsearch(&(state->have), buf, len);
1464 /* search available input */
1465 len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
1466 strm->avail_in -= len;
1467 strm->next_in += len;
1468 strm->total_in += len;
1470 /* return no joy or set up to restart inflate() on a new block */
1471 if (state->have != 4) return Z_DATA_ERROR;
1472 if (state->flags == -1)
1473 state->wrap = 0; /* if no header yet, treat as raw */
1475 state->wrap &= ~4; /* no point in computing a check value now */
1476 flags = state->flags;
1477 in = strm->total_in; out = strm->total_out;
1479 strm->total_in = in; strm->total_out = out;
1480 state->flags = flags;
1486 Returns true if inflate is currently at the end of a block generated by
1487 Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
1488 implementation to provide an additional safety check. PPP uses
1489 Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
1490 block. When decompressing, PPP checks that at the end of input packet,
1491 inflate is waiting for these length bytes.
1493 int ZEXPORT inflateSyncPoint(
1496 struct inflate_state FAR *state;
1498 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1499 state = (struct inflate_state FAR *)strm->state;
1500 return state->mode == STORED && state->bits == 0;
1503 int ZEXPORT inflateCopy(
1507 struct inflate_state FAR *state;
1508 struct inflate_state FAR *copy;
1509 unsigned char FAR *window;
1513 if (inflateStateCheck(source) || dest == Z_NULL)
1514 return Z_STREAM_ERROR;
1515 state = (struct inflate_state FAR *)source->state;
1517 /* allocate space */
1518 copy = (struct inflate_state FAR *)
1519 ZALLOC(source, 1, sizeof(struct inflate_state));
1520 if (copy == Z_NULL) return Z_MEM_ERROR;
1522 if (state->window != Z_NULL) {
1523 window = (unsigned char FAR *)
1524 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
1525 if (window == Z_NULL) {
1526 ZFREE(source, copy);
1532 zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1533 zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
1535 if (state->lencode >= state->codes &&
1536 state->lencode <= state->codes + ENOUGH - 1) {
1537 copy->lencode = copy->codes + (state->lencode - state->codes);
1538 copy->distcode = copy->codes + (state->distcode - state->codes);
1540 copy->next = copy->codes + (state->next - state->codes);
1541 if (window != Z_NULL) {
1542 wsize = 1U << state->wbits;
1543 zmemcpy(window, state->window, wsize);
1545 copy->window = window;
1546 dest->state = (struct internal_state FAR *)copy;
1550 int ZEXPORT inflateUndermine(
1554 struct inflate_state FAR *state;
1556 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1557 state = (struct inflate_state FAR *)strm->state;
1558 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1559 state->sane = !subvert;
1564 return Z_DATA_ERROR;
1568 int ZEXPORT inflateValidate(
1572 struct inflate_state FAR *state;
1574 if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1575 state = (struct inflate_state FAR *)strm->state;
1576 if (check && state->wrap)
1583 long ZEXPORT inflateMark(
1586 struct inflate_state FAR *state;
1588 if (inflateStateCheck(strm))
1590 state = (struct inflate_state FAR *)strm->state;
1591 return (long)(((unsigned long)((long)state->back)) << 16) +
1592 (state->mode == COPY ? state->length :
1593 (state->mode == MATCH ? state->was - state->length : 0));
1596 unsigned long ZEXPORT inflateCodesUsed(
1599 struct inflate_state FAR *state;
1600 if (inflateStateCheck(strm)) return (unsigned long)-1;
1601 state = (struct inflate_state FAR *)strm->state;
1602 return (unsigned long)(state->next - state->codes);
1605 #endif /* !Z_FREETYPE */