build: silence lex(1) statistics output
[unleashed.git] / kernel / zmod / inflate.c
blob023e7a121ce76f99921eba6d42c21c7a80f2ff18
1 /*
2 * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
3 * Use is subject to license terms.
4 */
6 /* inflate.c -- zlib decompression
7 * Copyright (C) 1995-2005 Mark Adler
8 * For conditions of distribution and use, see copyright notice in zlib.h
9 */
11 #pragma ident "%Z%%M% %I% %E% SMI"
14 * Change history:
16 * 1.2.beta0 24 Nov 2002
17 * - First version -- complete rewrite of inflate to simplify code, avoid
18 * creation of window when not needed, minimize use of window when it is
19 * needed, make inffast.c even faster, implement gzip decoding, and to
20 * improve code readability and style over the previous zlib inflate code
22 * 1.2.beta1 25 Nov 2002
23 * - Use pointers for available input and output checking in inffast.c
24 * - Remove input and output counters in inffast.c
25 * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
26 * - Remove unnecessary second byte pull from length extra in inffast.c
27 * - Unroll direct copy to three copies per loop in inffast.c
29 * 1.2.beta2 4 Dec 2002
30 * - Change external routine names to reduce potential conflicts
31 * - Correct filename to inffixed.h for fixed tables in inflate.c
32 * - Make hbuf[] unsigned char to match parameter type in inflate.c
33 * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
34 * to avoid negation problem on Alphas (64 bit) in inflate.c
36 * 1.2.beta3 22 Dec 2002
37 * - Add comments on state->bits assertion in inffast.c
38 * - Add comments on op field in inftrees.h
39 * - Fix bug in reuse of allocated window after inflateReset()
40 * - Remove bit fields--back to byte structure for speed
41 * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
42 * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
43 * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
44 * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
45 * - Use local copies of stream next and avail values, as well as local bit
46 * buffer and bit count in inflate()--for speed when inflate_fast() not used
48 * 1.2.beta4 1 Jan 2003
49 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
50 * - Move a comment on output buffer sizes from inffast.c to inflate.c
51 * - Add comments in inffast.c to introduce the inflate_fast() routine
52 * - Rearrange window copies in inflate_fast() for speed and simplification
53 * - Unroll last copy for window match in inflate_fast()
54 * - Use local copies of window variables in inflate_fast() for speed
55 * - Pull out common write == 0 case for speed in inflate_fast()
56 * - Make op and len in inflate_fast() unsigned for consistency
57 * - Add FAR to lcode and dcode declarations in inflate_fast()
58 * - Simplified bad distance check in inflate_fast()
59 * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
60 * source file infback.c to provide a call-back interface to inflate for
61 * programs like gzip and unzip -- uses window as output buffer to avoid
62 * window copying
64 * 1.2.beta5 1 Jan 2003
65 * - Improved inflateBack() interface to allow the caller to provide initial
66 * input in strm.
67 * - Fixed stored blocks bug in inflateBack()
69 * 1.2.beta6 4 Jan 2003
70 * - Added comments in inffast.c on effectiveness of POSTINC
71 * - Typecasting all around to reduce compiler warnings
72 * - Changed loops from while (1) or do {} while (1) to for (;;), again to
73 * make compilers happy
74 * - Changed type of window in inflateBackInit() to unsigned char *
76 * 1.2.beta7 27 Jan 2003
77 * - Changed many types to unsigned or unsigned short to avoid warnings
78 * - Added inflateCopy() function
80 * 1.2.0 9 Mar 2003
81 * - Changed inflateBack() interface to provide separate opaque descriptors
82 * for the in() and out() functions
83 * - Changed inflateBack() argument and in_func typedef to swap the length
84 * and buffer address return values for the input function
85 * - Check next_in and next_out for Z_NULL on entry to inflate()
87 * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
90 #include "zutil.h"
91 #include "inftrees.h"
92 #include "inflate.h"
93 #include "inffast.h"
95 #ifdef MAKEFIXED
96 # ifndef BUILDFIXED
97 # define BUILDFIXED
98 # endif
99 #endif
101 /* function prototypes */
102 local void fixedtables OF((struct inflate_state FAR *state));
103 local int updatewindow OF((z_streamp strm, unsigned out));
104 #ifdef BUILDFIXED
105 void makefixed OF((void));
106 #endif
107 local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
108 unsigned len));
110 int ZEXPORT inflateReset(strm)
111 z_streamp strm;
113 struct inflate_state FAR *state;
115 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
116 state = (struct inflate_state FAR *)strm->state;
117 strm->total_in = strm->total_out = state->total = 0;
118 strm->msg = Z_NULL;
119 strm->adler = 1; /* to support ill-conceived Java test suite */
120 state->mode = HEAD;
121 state->last = 0;
122 state->havedict = 0;
123 state->dmax = 32768U;
124 state->head = Z_NULL;
125 state->wsize = 0;
126 state->whave = 0;
127 state->write = 0;
128 state->hold = 0;
129 state->bits = 0;
130 state->lencode = state->distcode = state->next = state->codes;
131 Tracev((stderr, "inflate: reset\n"));
132 return Z_OK;
135 int ZEXPORT inflatePrime(strm, bits, value)
136 z_streamp strm;
137 int bits;
138 int value;
140 struct inflate_state FAR *state;
142 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
143 state = (struct inflate_state FAR *)strm->state;
144 if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
145 value &= (1L << bits) - 1;
146 state->hold += value << state->bits;
147 state->bits += bits;
148 return Z_OK;
151 int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
152 z_streamp strm;
153 int windowBits;
154 const char *version;
155 int stream_size;
157 struct inflate_state FAR *state;
159 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
160 stream_size != (int)(sizeof(z_stream)))
161 return Z_VERSION_ERROR;
162 if (strm == Z_NULL) return Z_STREAM_ERROR;
163 strm->msg = Z_NULL; /* in case we return an error */
164 if (strm->zalloc == (alloc_func)0) {
165 strm->zalloc = zcalloc;
166 strm->opaque = (voidpf)0;
168 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
169 state = (struct inflate_state FAR *)
170 ZALLOC(strm, 1, sizeof(struct inflate_state));
171 if (state == Z_NULL) return Z_MEM_ERROR;
172 Tracev((stderr, "inflate: allocated\n"));
173 strm->state = (struct internal_state FAR *)state;
174 if (windowBits < 0) {
175 state->wrap = 0;
176 windowBits = -windowBits;
178 else {
179 state->wrap = (windowBits >> 4) + 1;
180 #ifdef GUNZIP
181 if (windowBits < 48) windowBits &= 15;
182 #endif
184 if (windowBits < 8 || windowBits > 15) {
185 ZFREE(strm, state);
186 strm->state = Z_NULL;
187 return Z_STREAM_ERROR;
189 state->wbits = (unsigned)windowBits;
190 state->window = Z_NULL;
191 return inflateReset(strm);
194 int ZEXPORT inflateInit_(strm, version, stream_size)
195 z_streamp strm;
196 const char *version;
197 int stream_size;
199 return inflateInit2_(strm, DEF_WBITS, version, stream_size);
203 Return state with length and distance decoding tables and index sizes set to
204 fixed code decoding. Normally this returns fixed tables from inffixed.h.
205 If BUILDFIXED is defined, then instead this routine builds the tables the
206 first time it's called, and returns those tables the first time and
207 thereafter. This reduces the size of the code by about 2K bytes, in
208 exchange for a little execution time. However, BUILDFIXED should not be
209 used for threaded applications, since the rewriting of the tables and virgin
210 may not be thread-safe.
212 local void fixedtables(state)
213 struct inflate_state FAR *state;
215 #ifdef BUILDFIXED
216 static int virgin = 1;
217 static code *lenfix, *distfix;
218 static code fixed[544];
220 /* build fixed huffman tables if first call (may not be thread safe) */
221 if (virgin) {
222 unsigned sym, bits;
223 static code *next;
225 /* literal/length table */
226 sym = 0;
227 while (sym < 144) state->lens[sym++] = 8;
228 while (sym < 256) state->lens[sym++] = 9;
229 while (sym < 280) state->lens[sym++] = 7;
230 while (sym < 288) state->lens[sym++] = 8;
231 next = fixed;
232 lenfix = next;
233 bits = 9;
234 inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
236 /* distance table */
237 sym = 0;
238 while (sym < 32) state->lens[sym++] = 5;
239 distfix = next;
240 bits = 5;
241 inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
243 /* do this just once */
244 virgin = 0;
246 #else /* !BUILDFIXED */
247 # include "inffixed.h"
248 #endif /* BUILDFIXED */
249 state->lencode = lenfix;
250 state->lenbits = 9;
251 state->distcode = distfix;
252 state->distbits = 5;
255 #ifdef MAKEFIXED
256 #include <stdio.h>
259 Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
260 defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
261 those tables to stdout, which would be piped to inffixed.h. A small program
262 can simply call makefixed to do this:
264 void makefixed(void);
266 int main(void)
268 makefixed();
269 return 0;
272 Then that can be linked with zlib built with MAKEFIXED defined and run:
274 a.out > inffixed.h
276 void makefixed()
278 unsigned low, size;
279 struct inflate_state state;
281 fixedtables(&state);
282 puts(" /* inffixed.h -- table for decoding fixed codes");
283 puts(" * Generated automatically by makefixed().");
284 puts(" */");
285 puts("");
286 puts(" /* WARNING: this file should *not* be used by applications.");
287 puts(" It is part of the implementation of this library and is");
288 puts(" subject to change. Applications should only use zlib.h.");
289 puts(" */");
290 puts("");
291 size = 1U << 9;
292 printf(" static const code lenfix[%u] = {", size);
293 low = 0;
294 for (;;) {
295 if ((low % 7) == 0) printf("\n ");
296 printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
297 state.lencode[low].val);
298 if (++low == size) break;
299 putchar(',');
301 puts("\n };");
302 size = 1U << 5;
303 printf("\n static const code distfix[%u] = {", size);
304 low = 0;
305 for (;;) {
306 if ((low % 6) == 0) printf("\n ");
307 printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
308 state.distcode[low].val);
309 if (++low == size) break;
310 putchar(',');
312 puts("\n };");
314 #endif /* MAKEFIXED */
317 Update the window with the last wsize (normally 32K) bytes written before
318 returning. If window does not exist yet, create it. This is only called
319 when a window is already in use, or when output has been written during this
320 inflate call, but the end of the deflate stream has not been reached yet.
321 It is also called to create a window for dictionary data when a dictionary
322 is loaded.
324 Providing output buffers larger than 32K to inflate() should provide a speed
325 advantage, since only the last 32K of output is copied to the sliding window
326 upon return from inflate(), and since all distances after the first 32K of
327 output will fall in the output data, making match copies simpler and faster.
328 The advantage may be dependent on the size of the processor's data caches.
330 local int updatewindow(strm, out)
331 z_streamp strm;
332 unsigned out;
334 struct inflate_state FAR *state;
335 unsigned copy, dist;
337 state = (struct inflate_state FAR *)strm->state;
339 /* if it hasn't been done already, allocate space for the window */
340 if (state->window == Z_NULL) {
341 state->window = (unsigned char FAR *)
342 ZALLOC(strm, 1U << state->wbits,
343 sizeof(unsigned char));
344 if (state->window == Z_NULL) return 1;
347 /* if window not in use yet, initialize */
348 if (state->wsize == 0) {
349 state->wsize = 1U << state->wbits;
350 state->write = 0;
351 state->whave = 0;
354 /* copy state->wsize or less output bytes into the circular window */
355 copy = out - strm->avail_out;
356 if (copy >= state->wsize) {
357 zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
358 state->write = 0;
359 state->whave = state->wsize;
361 else {
362 dist = state->wsize - state->write;
363 if (dist > copy) dist = copy;
364 zmemcpy(state->window + state->write, strm->next_out - copy, dist);
365 copy -= dist;
366 if (copy) {
367 zmemcpy(state->window, strm->next_out - copy, copy);
368 state->write = copy;
369 state->whave = state->wsize;
371 else {
372 state->write += dist;
373 if (state->write == state->wsize) state->write = 0;
374 if (state->whave < state->wsize) state->whave += dist;
377 return 0;
380 /* Macros for inflate(): */
382 /* check function to use adler32() for zlib or crc32() for gzip */
383 #ifdef GUNZIP
384 # define UPDATE(check, buf, len) \
385 (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
386 #else
387 # define UPDATE(check, buf, len) adler32(check, buf, len)
388 #endif
390 /* check macros for header crc */
391 #ifdef GUNZIP
392 # define CRC2(check, word) \
393 do { \
394 hbuf[0] = (unsigned char)(word); \
395 hbuf[1] = (unsigned char)((word) >> 8); \
396 check = crc32(check, hbuf, 2); \
397 } while (0)
399 # define CRC4(check, word) \
400 do { \
401 hbuf[0] = (unsigned char)(word); \
402 hbuf[1] = (unsigned char)((word) >> 8); \
403 hbuf[2] = (unsigned char)((word) >> 16); \
404 hbuf[3] = (unsigned char)((word) >> 24); \
405 check = crc32(check, hbuf, 4); \
406 } while (0)
407 #endif
409 /* Load registers with state in inflate() for speed */
410 #define LOAD() \
411 do { \
412 put = strm->next_out; \
413 left = strm->avail_out; \
414 next = strm->next_in; \
415 have = strm->avail_in; \
416 hold = state->hold; \
417 bits = state->bits; \
418 } while (0)
420 /* Restore state from registers in inflate() */
421 #define RESTORE() \
422 do { \
423 strm->next_out = put; \
424 strm->avail_out = left; \
425 strm->next_in = next; \
426 strm->avail_in = have; \
427 state->hold = hold; \
428 state->bits = bits; \
429 } while (0)
431 /* Clear the input bit accumulator */
432 #define INITBITS() \
433 do { \
434 hold = 0; \
435 bits = 0; \
436 } while (0)
438 /* Get a byte of input into the bit accumulator, or return from inflate()
439 if there is no input available. */
440 #define PULLBYTE() \
441 do { \
442 if (have == 0) goto inf_leave; \
443 have--; \
444 hold += (unsigned long)(*next++) << bits; \
445 bits += 8; \
446 } while (0)
448 /* Assure that there are at least n bits in the bit accumulator. If there is
449 not enough available input to do that, then return from inflate(). */
450 #define NEEDBITS(n) \
451 do { \
452 while (bits < (unsigned)(n)) \
453 PULLBYTE(); \
454 } while (0)
456 /* Return the low n bits of the bit accumulator (n < 16) */
457 #define BITS(n) \
458 ((unsigned)hold & ((1U << (n)) - 1))
460 /* Remove n bits from the bit accumulator */
461 #define DROPBITS(n) \
462 do { \
463 hold >>= (n); \
464 bits -= (unsigned)(n); \
465 } while (0)
467 /* Remove zero to seven bits as needed to go to a byte boundary */
468 #define BYTEBITS() \
469 do { \
470 hold >>= bits & 7; \
471 bits -= bits & 7; \
472 } while (0)
474 /* Reverse the bytes in a 32-bit value */
475 #define REVERSE(q) \
476 ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
477 (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
480 inflate() uses a state machine to process as much input data and generate as
481 much output data as possible before returning. The state machine is
482 structured roughly as follows:
484 for (;;) switch (state) {
486 case STATEn:
487 if (not enough input data or output space to make progress)
488 return;
489 ... make progress ...
490 state = STATEm;
491 break;
495 so when inflate() is called again, the same case is attempted again, and
496 if the appropriate resources are provided, the machine proceeds to the
497 next state. The NEEDBITS() macro is usually the way the state evaluates
498 whether it can proceed or should return. NEEDBITS() does the return if
499 the requested bits are not available. The typical use of the BITS macros
502 NEEDBITS(n);
503 ... do something with BITS(n) ...
504 DROPBITS(n);
506 where NEEDBITS(n) either returns from inflate() if there isn't enough
507 input left to load n bits into the accumulator, or it continues. BITS(n)
508 gives the low n bits in the accumulator. When done, DROPBITS(n) drops
509 the low n bits off the accumulator. INITBITS() clears the accumulator
510 and sets the number of available bits to zero. BYTEBITS() discards just
511 enough bits to put the accumulator on a byte boundary. After BYTEBITS()
512 and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
514 NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
515 if there is no input available. The decoding of variable length codes uses
516 PULLBYTE() directly in order to pull just enough bytes to decode the next
517 code, and no more.
519 Some states loop until they get enough input, making sure that enough
520 state information is maintained to continue the loop where it left off
521 if NEEDBITS() returns in the loop. For example, want, need, and keep
522 would all have to actually be part of the saved state in case NEEDBITS()
523 returns:
525 case STATEw:
526 while (want < need) {
527 NEEDBITS(n);
528 keep[want++] = BITS(n);
529 DROPBITS(n);
531 state = STATEx;
532 case STATEx:
534 As shown above, if the next state is also the next case, then the break
535 is omitted.
537 A state may also return if there is not enough output space available to
538 complete that state. Those states are copying stored data, writing a
539 literal byte, and copying a matching string.
541 When returning, a "goto inf_leave" is used to update the total counters,
542 update the check value, and determine whether any progress has been made
543 during that inflate() call in order to return the proper return code.
544 Progress is defined as a change in either strm->avail_in or strm->avail_out.
545 When there is a window, goto inf_leave will update the window with the last
546 output written. If a goto inf_leave occurs in the middle of decompression
547 and there is no window currently, goto inf_leave will create one and copy
548 output to the window for the next call of inflate().
550 In this implementation, the flush parameter of inflate() only affects the
551 return code (per zlib.h). inflate() always writes as much as possible to
552 strm->next_out, given the space available and the provided input--the effect
553 documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
554 the allocation of and copying into a sliding window until necessary, which
555 provides the effect documented in zlib.h for Z_FINISH when the entire input
556 stream available. So the only thing the flush parameter actually does is:
557 when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
558 will return Z_BUF_ERROR if it has not reached the end of the stream.
561 int ZEXPORT inflate(strm, flush)
562 z_streamp strm;
563 int flush;
565 struct inflate_state FAR *state;
566 unsigned char FAR *next; /* next input */
567 unsigned char FAR *put; /* next output */
568 unsigned have, left; /* available input and output */
569 unsigned long hold; /* bit buffer */
570 unsigned bits; /* bits in bit buffer */
571 unsigned in, out; /* save starting available input and output */
572 unsigned copy; /* number of stored or match bytes to copy */
573 unsigned char FAR *from; /* where to copy match bytes from */
574 code this; /* current decoding table entry */
575 code last; /* parent table entry */
576 unsigned len; /* length to copy for repeats, bits to drop */
577 int ret; /* return code */
578 #ifdef GUNZIP
579 unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
580 #endif
581 static const unsigned short order[19] = /* permutation of code lengths */
582 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
584 if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
585 (strm->next_in == Z_NULL && strm->avail_in != 0))
586 return Z_STREAM_ERROR;
588 state = (struct inflate_state FAR *)strm->state;
589 if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
590 LOAD();
591 in = have;
592 out = left;
593 ret = Z_OK;
594 for (;;)
595 switch (state->mode) {
596 case HEAD:
597 if (state->wrap == 0) {
598 state->mode = TYPEDO;
599 break;
601 NEEDBITS(16);
602 #ifdef GUNZIP
603 if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
604 state->check = crc32(0L, Z_NULL, 0);
605 CRC2(state->check, hold);
606 INITBITS();
607 state->mode = FLAGS;
608 break;
610 state->flags = 0; /* expect zlib header */
611 if (state->head != Z_NULL)
612 state->head->done = -1;
613 if (!(state->wrap & 1) || /* check if zlib header allowed */
614 #else
615 if (
616 #endif
617 ((BITS(8) << 8) + (hold >> 8)) % 31) {
618 strm->msg = (char *)"incorrect header check";
619 state->mode = BAD;
620 break;
622 if (BITS(4) != Z_DEFLATED) {
623 strm->msg = (char *)"unknown compression method";
624 state->mode = BAD;
625 break;
627 DROPBITS(4);
628 len = BITS(4) + 8;
629 if (len > state->wbits) {
630 strm->msg = (char *)"invalid window size";
631 state->mode = BAD;
632 break;
634 state->dmax = 1U << len;
635 Tracev((stderr, "inflate: zlib header ok\n"));
636 strm->adler = state->check = adler32(0L, Z_NULL, 0);
637 state->mode = hold & 0x200 ? DICTID : TYPE;
638 INITBITS();
639 break;
640 #ifdef GUNZIP
641 case FLAGS:
642 NEEDBITS(16);
643 state->flags = (int)(hold);
644 if ((state->flags & 0xff) != Z_DEFLATED) {
645 strm->msg = (char *)"unknown compression method";
646 state->mode = BAD;
647 break;
649 if (state->flags & 0xe000) {
650 strm->msg = (char *)"unknown header flags set";
651 state->mode = BAD;
652 break;
654 if (state->head != Z_NULL)
655 state->head->text = (int)((hold >> 8) & 1);
656 if (state->flags & 0x0200) CRC2(state->check, hold);
657 INITBITS();
658 state->mode = TIME;
659 /*FALLTHRU*/
660 case TIME:
661 NEEDBITS(32);
662 if (state->head != Z_NULL)
663 state->head->time = hold;
664 if (state->flags & 0x0200) CRC4(state->check, hold);
665 INITBITS();
666 state->mode = OS;
667 /*FALLTHRU*/
668 case OS:
669 NEEDBITS(16);
670 if (state->head != Z_NULL) {
671 state->head->xflags = (int)(hold & 0xff);
672 state->head->os = (int)(hold >> 8);
674 if (state->flags & 0x0200) CRC2(state->check, hold);
675 INITBITS();
676 state->mode = EXLEN;
677 /*FALLTHRU*/
678 case EXLEN:
679 if (state->flags & 0x0400) {
680 NEEDBITS(16);
681 state->length = (unsigned)(hold);
682 if (state->head != Z_NULL)
683 state->head->extra_len = (unsigned)hold;
684 if (state->flags & 0x0200) CRC2(state->check, hold);
685 INITBITS();
687 else if (state->head != Z_NULL)
688 state->head->extra = Z_NULL;
689 state->mode = EXTRA;
690 /*FALLTHRU*/
691 case EXTRA:
692 if (state->flags & 0x0400) {
693 copy = state->length;
694 if (copy > have) copy = have;
695 if (copy) {
696 if (state->head != Z_NULL &&
697 state->head->extra != Z_NULL) {
698 len = state->head->extra_len - state->length;
699 zmemcpy(state->head->extra + len, next,
700 len + copy > state->head->extra_max ?
701 state->head->extra_max - len : copy);
703 if (state->flags & 0x0200)
704 state->check = crc32(state->check, next, copy);
705 have -= copy;
706 next += copy;
707 state->length -= copy;
709 if (state->length) goto inf_leave;
711 state->length = 0;
712 state->mode = NAME;
713 /*FALLTHRU*/
714 case NAME:
715 if (state->flags & 0x0800) {
716 if (have == 0) goto inf_leave;
717 copy = 0;
718 do {
719 len = (unsigned)(next[copy++]);
720 if (state->head != Z_NULL &&
721 state->head->name != Z_NULL &&
722 state->length < state->head->name_max)
723 state->head->name[state->length++] = len;
724 } while (len && copy < have);
725 if (state->flags & 0x0200)
726 state->check = crc32(state->check, next, copy);
727 have -= copy;
728 next += copy;
729 if (len) goto inf_leave;
731 else if (state->head != Z_NULL)
732 state->head->name = Z_NULL;
733 state->length = 0;
734 state->mode = COMMENT;
735 /*FALLTHRU*/
736 case COMMENT:
737 if (state->flags & 0x1000) {
738 if (have == 0) goto inf_leave;
739 copy = 0;
740 do {
741 len = (unsigned)(next[copy++]);
742 if (state->head != Z_NULL &&
743 state->head->comment != Z_NULL &&
744 state->length < state->head->comm_max)
745 state->head->comment[state->length++] = len;
746 } while (len && copy < have);
747 if (state->flags & 0x0200)
748 state->check = crc32(state->check, next, copy);
749 have -= copy;
750 next += copy;
751 if (len) goto inf_leave;
753 else if (state->head != Z_NULL)
754 state->head->comment = Z_NULL;
755 state->mode = HCRC;
756 /*FALLTHRU*/
757 case HCRC:
758 if (state->flags & 0x0200) {
759 NEEDBITS(16);
760 if (hold != (state->check & 0xffff)) {
761 strm->msg = (char *)"header crc mismatch";
762 state->mode = BAD;
763 break;
765 INITBITS();
767 if (state->head != Z_NULL) {
768 state->head->hcrc = (int)((state->flags >> 9) & 1);
769 state->head->done = 1;
771 strm->adler = state->check = crc32(0L, Z_NULL, 0);
772 state->mode = TYPE;
773 break;
774 #endif
775 case DICTID:
776 NEEDBITS(32);
777 strm->adler = state->check = REVERSE(hold);
778 INITBITS();
779 state->mode = DICT;
780 /*FALLTHRU*/
781 case DICT:
782 if (state->havedict == 0) {
783 RESTORE();
784 return Z_NEED_DICT;
786 strm->adler = state->check = adler32(0L, Z_NULL, 0);
787 state->mode = TYPE;
788 /*FALLTHRU*/
789 case TYPE:
790 if (flush == Z_BLOCK) goto inf_leave;
791 /*FALLTHRU*/
792 case TYPEDO:
793 if (state->last) {
794 BYTEBITS();
795 state->mode = CHECK;
796 break;
798 NEEDBITS(3);
799 state->last = BITS(1);
800 DROPBITS(1);
801 switch (BITS(2)) {
802 case 0: /* stored block */
803 Tracev((stderr, "inflate: stored block%s\n",
804 state->last ? " (last)" : ""));
805 state->mode = STORED;
806 break;
807 case 1: /* fixed block */
808 fixedtables(state);
809 Tracev((stderr, "inflate: fixed codes block%s\n",
810 state->last ? " (last)" : ""));
811 state->mode = LEN; /* decode codes */
812 break;
813 case 2: /* dynamic block */
814 Tracev((stderr, "inflate: dynamic codes block%s\n",
815 state->last ? " (last)" : ""));
816 state->mode = TABLE;
817 break;
818 case 3:
819 strm->msg = (char *)"invalid block type";
820 state->mode = BAD;
822 DROPBITS(2);
823 break;
824 case STORED:
825 BYTEBITS(); /* go to byte boundary */
826 NEEDBITS(32);
827 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
828 strm->msg = (char *)"invalid stored block lengths";
829 state->mode = BAD;
830 break;
832 state->length = (unsigned)hold & 0xffff;
833 Tracev((stderr, "inflate: stored length %u\n",
834 state->length));
835 INITBITS();
836 state->mode = COPY;
837 /*FALLTHRU*/
838 case COPY:
839 copy = state->length;
840 if (copy) {
841 if (copy > have) copy = have;
842 if (copy > left) copy = left;
843 if (copy == 0) goto inf_leave;
844 zmemcpy(put, next, copy);
845 have -= copy;
846 next += copy;
847 left -= copy;
848 put += copy;
849 state->length -= copy;
850 break;
852 Tracev((stderr, "inflate: stored end\n"));
853 state->mode = TYPE;
854 break;
855 case TABLE:
856 NEEDBITS(14);
857 state->nlen = BITS(5) + 257;
858 DROPBITS(5);
859 state->ndist = BITS(5) + 1;
860 DROPBITS(5);
861 state->ncode = BITS(4) + 4;
862 DROPBITS(4);
863 #ifndef PKZIP_BUG_WORKAROUND
864 if (state->nlen > 286 || state->ndist > 30) {
865 strm->msg = (char *)"too many length or distance symbols";
866 state->mode = BAD;
867 break;
869 #endif
870 Tracev((stderr, "inflate: table sizes ok\n"));
871 state->have = 0;
872 state->mode = LENLENS;
873 /*FALLTHRU*/
874 case LENLENS:
875 while (state->have < state->ncode) {
876 NEEDBITS(3);
877 state->lens[order[state->have++]] = (unsigned short)BITS(3);
878 DROPBITS(3);
880 while (state->have < 19)
881 state->lens[order[state->have++]] = 0;
882 state->next = state->codes;
883 state->lencode = (code const FAR *)(state->next);
884 state->lenbits = 7;
885 ret = inflate_table(CODES, state->lens, 19, &(state->next),
886 &(state->lenbits), state->work);
887 if (ret) {
888 strm->msg = (char *)"invalid code lengths set";
889 state->mode = BAD;
890 break;
892 Tracev((stderr, "inflate: code lengths ok\n"));
893 state->have = 0;
894 state->mode = CODELENS;
895 /*FALLTHRU*/
896 case CODELENS:
897 while (state->have < state->nlen + state->ndist) {
898 for (;;) {
899 this = state->lencode[BITS(state->lenbits)];
900 if ((unsigned)(this.bits) <= bits) break;
901 PULLBYTE();
903 if (this.val < 16) {
904 NEEDBITS(this.bits);
905 DROPBITS(this.bits);
906 state->lens[state->have++] = this.val;
908 else {
909 if (this.val == 16) {
910 NEEDBITS(this.bits + 2);
911 DROPBITS(this.bits);
912 if (state->have == 0) {
913 strm->msg = (char *)"invalid bit length repeat";
914 state->mode = BAD;
915 break;
917 len = state->lens[state->have - 1];
918 copy = 3 + BITS(2);
919 DROPBITS(2);
921 else if (this.val == 17) {
922 NEEDBITS(this.bits + 3);
923 DROPBITS(this.bits);
924 len = 0;
925 copy = 3 + BITS(3);
926 DROPBITS(3);
928 else {
929 NEEDBITS(this.bits + 7);
930 DROPBITS(this.bits);
931 len = 0;
932 copy = 11 + BITS(7);
933 DROPBITS(7);
935 if (state->have + copy > state->nlen + state->ndist) {
936 strm->msg = (char *)"invalid bit length repeat";
937 state->mode = BAD;
938 break;
940 while (copy--)
941 state->lens[state->have++] = (unsigned short)len;
945 /* handle error breaks in while */
946 if (state->mode == BAD) break;
948 /* build code tables */
949 state->next = state->codes;
950 state->lencode = (code const FAR *)(state->next);
951 state->lenbits = 9;
952 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
953 &(state->lenbits), state->work);
954 if (ret) {
955 strm->msg = (char *)"invalid literal/lengths set";
956 state->mode = BAD;
957 break;
959 state->distcode = (code const FAR *)(state->next);
960 state->distbits = 6;
961 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
962 &(state->next), &(state->distbits), state->work);
963 if (ret) {
964 strm->msg = (char *)"invalid distances set";
965 state->mode = BAD;
966 break;
968 Tracev((stderr, "inflate: codes ok\n"));
969 state->mode = LEN;
970 /*FALLTHRU*/
971 case LEN:
972 if (have >= 6 && left >= 258) {
973 RESTORE();
974 inflate_fast(strm, out);
975 LOAD();
976 break;
978 for (;;) {
979 this = state->lencode[BITS(state->lenbits)];
980 if ((unsigned)(this.bits) <= bits) break;
981 PULLBYTE();
983 if (this.op && (this.op & 0xf0) == 0) {
984 last = this;
985 for (;;) {
986 this = state->lencode[last.val +
987 (BITS(last.bits + last.op) >> last.bits)];
988 if ((unsigned)(last.bits + this.bits) <= bits) break;
989 PULLBYTE();
991 DROPBITS(last.bits);
993 DROPBITS(this.bits);
994 state->length = (unsigned)this.val;
995 if ((int)(this.op) == 0) {
996 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
997 "inflate: literal '%c'\n" :
998 "inflate: literal 0x%02x\n", this.val));
999 state->mode = LIT;
1000 break;
1002 if (this.op & 32) {
1003 Tracevv((stderr, "inflate: end of block\n"));
1004 state->mode = TYPE;
1005 break;
1007 if (this.op & 64) {
1008 strm->msg = (char *)"invalid literal/length code";
1009 state->mode = BAD;
1010 break;
1012 state->extra = (unsigned)(this.op) & 15;
1013 state->mode = LENEXT;
1014 /*FALLTHRU*/
1015 case LENEXT:
1016 if (state->extra) {
1017 NEEDBITS(state->extra);
1018 state->length += BITS(state->extra);
1019 DROPBITS(state->extra);
1021 Tracevv((stderr, "inflate: length %u\n", state->length));
1022 state->mode = DIST;
1023 /*FALLTHRU*/
1024 case DIST:
1025 for (;;) {
1026 this = state->distcode[BITS(state->distbits)];
1027 if ((unsigned)(this.bits) <= bits) break;
1028 PULLBYTE();
1030 if ((this.op & 0xf0) == 0) {
1031 last = this;
1032 for (;;) {
1033 this = state->distcode[last.val +
1034 (BITS(last.bits + last.op) >> last.bits)];
1035 if ((unsigned)(last.bits + this.bits) <= bits) break;
1036 PULLBYTE();
1038 DROPBITS(last.bits);
1040 DROPBITS(this.bits);
1041 if (this.op & 64) {
1042 strm->msg = (char *)"invalid distance code";
1043 state->mode = BAD;
1044 break;
1046 state->offset = (unsigned)this.val;
1047 state->extra = (unsigned)(this.op) & 15;
1048 state->mode = DISTEXT;
1049 /*FALLTHRU*/
1050 case DISTEXT:
1051 if (state->extra) {
1052 NEEDBITS(state->extra);
1053 state->offset += BITS(state->extra);
1054 DROPBITS(state->extra);
1056 #ifdef INFLATE_STRICT
1057 if (state->offset > state->dmax) {
1058 strm->msg = (char *)"invalid distance too far back";
1059 state->mode = BAD;
1060 break;
1062 #endif
1063 if (state->offset > state->whave + out - left) {
1064 strm->msg = (char *)"invalid distance too far back";
1065 state->mode = BAD;
1066 break;
1068 Tracevv((stderr, "inflate: distance %u\n", state->offset));
1069 state->mode = MATCH;
1070 /*FALLTHRU*/
1071 case MATCH:
1072 if (left == 0) goto inf_leave;
1073 copy = out - left;
1074 if (state->offset > copy) { /* copy from window */
1075 copy = state->offset - copy;
1076 if (copy > state->write) {
1077 copy -= state->write;
1078 from = state->window + (state->wsize - copy);
1080 else
1081 from = state->window + (state->write - copy);
1082 if (copy > state->length) copy = state->length;
1084 else { /* copy from output */
1085 from = put - state->offset;
1086 copy = state->length;
1088 if (copy > left) copy = left;
1089 left -= copy;
1090 state->length -= copy;
1091 do {
1092 *put++ = *from++;
1093 } while (--copy);
1094 if (state->length == 0) state->mode = LEN;
1095 break;
1096 case LIT:
1097 if (left == 0) goto inf_leave;
1098 *put++ = (unsigned char)(state->length);
1099 left--;
1100 state->mode = LEN;
1101 break;
1102 case CHECK:
1103 if (state->wrap) {
1104 NEEDBITS(32);
1105 out -= left;
1106 strm->total_out += out;
1107 state->total += out;
1108 if (out)
1109 strm->adler = state->check =
1110 UPDATE(state->check, put - out, out);
1111 out = left;
1112 if ((
1113 #ifdef GUNZIP
1114 state->flags ? hold :
1115 #endif
1116 REVERSE(hold)) != state->check) {
1117 strm->msg = (char *)"incorrect data check";
1118 state->mode = BAD;
1119 break;
1121 INITBITS();
1122 Tracev((stderr, "inflate: check matches trailer\n"));
1124 #ifdef GUNZIP
1125 state->mode = LENGTH;
1126 /*FALLTHRU*/
1127 case LENGTH:
1128 if (state->wrap && state->flags) {
1129 NEEDBITS(32);
1130 if (hold != (state->total & 0xffffffffUL)) {
1131 strm->msg = (char *)"incorrect length check";
1132 state->mode = BAD;
1133 break;
1135 INITBITS();
1136 Tracev((stderr, "inflate: length matches trailer\n"));
1138 #endif
1139 state->mode = DONE;
1140 /*FALLTHRU*/
1141 case DONE:
1142 ret = Z_STREAM_END;
1143 goto inf_leave;
1144 case BAD:
1145 ret = Z_DATA_ERROR;
1146 goto inf_leave;
1147 case MEM:
1148 return Z_MEM_ERROR;
1149 case SYNC:
1150 default:
1151 return Z_STREAM_ERROR;
1155 Return from inflate(), updating the total counts and the check value.
1156 If there was no progress during the inflate() call, return a buffer
1157 error. Call updatewindow() to create and/or update the window state.
1158 Note: a memory error from inflate() is non-recoverable.
1160 inf_leave:
1161 RESTORE();
1162 if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
1163 if (updatewindow(strm, out)) {
1164 state->mode = MEM;
1165 return Z_MEM_ERROR;
1167 in -= strm->avail_in;
1168 out -= strm->avail_out;
1169 strm->total_in += in;
1170 strm->total_out += out;
1171 state->total += out;
1172 if (state->wrap && out)
1173 strm->adler = state->check =
1174 UPDATE(state->check, strm->next_out - out, out);
1175 strm->data_type = state->bits + (state->last ? 64 : 0) +
1176 (state->mode == TYPE ? 128 : 0);
1177 if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
1178 ret = Z_BUF_ERROR;
1179 return ret;
1182 int ZEXPORT inflateEnd(strm)
1183 z_streamp strm;
1185 struct inflate_state FAR *state;
1186 if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
1187 return Z_STREAM_ERROR;
1188 state = (struct inflate_state FAR *)strm->state;
1189 if (state->window != Z_NULL) ZFREE(strm, state->window);
1190 ZFREE(strm, strm->state);
1191 strm->state = Z_NULL;
1192 Tracev((stderr, "inflate: end\n"));
1193 return Z_OK;
1196 int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
1197 z_streamp strm;
1198 const Bytef *dictionary;
1199 uInt dictLength;
1201 struct inflate_state FAR *state;
1202 unsigned long id;
1204 /* check state */
1205 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1206 state = (struct inflate_state FAR *)strm->state;
1207 if (state->wrap != 0 && state->mode != DICT)
1208 return Z_STREAM_ERROR;
1210 /* check for correct dictionary id */
1211 if (state->mode == DICT) {
1212 id = adler32(0L, Z_NULL, 0);
1213 id = adler32(id, dictionary, dictLength);
1214 if (id != state->check)
1215 return Z_DATA_ERROR;
1218 /* copy dictionary to window */
1219 if (updatewindow(strm, strm->avail_out)) {
1220 state->mode = MEM;
1221 return Z_MEM_ERROR;
1223 if (dictLength > state->wsize) {
1224 zmemcpy(state->window, dictionary + dictLength - state->wsize,
1225 state->wsize);
1226 state->whave = state->wsize;
1228 else {
1229 zmemcpy(state->window + state->wsize - dictLength, dictionary,
1230 dictLength);
1231 state->whave = dictLength;
1233 state->havedict = 1;
1234 Tracev((stderr, "inflate: dictionary set\n"));
1235 return Z_OK;
1238 int ZEXPORT inflateGetHeader(strm, head)
1239 z_streamp strm;
1240 gz_headerp head;
1242 struct inflate_state FAR *state;
1244 /* check state */
1245 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1246 state = (struct inflate_state FAR *)strm->state;
1247 if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
1249 /* save header structure */
1250 state->head = head;
1251 head->done = 0;
1252 return Z_OK;
1256 Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
1257 or when out of input. When called, *have is the number of pattern bytes
1258 found in order so far, in 0..3. On return *have is updated to the new
1259 state. If on return *have equals four, then the pattern was found and the
1260 return value is how many bytes were read including the last byte of the
1261 pattern. If *have is less than four, then the pattern has not been found
1262 yet and the return value is len. In the latter case, syncsearch() can be
1263 called again with more data and the *have state. *have is initialized to
1264 zero for the first call.
1266 local unsigned syncsearch(have, buf, len)
1267 unsigned FAR *have;
1268 unsigned char FAR *buf;
1269 unsigned len;
1271 unsigned got;
1272 unsigned next;
1274 got = *have;
1275 next = 0;
1276 while (next < len && got < 4) {
1277 if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
1278 got++;
1279 else if (buf[next])
1280 got = 0;
1281 else
1282 got = 4 - got;
1283 next++;
1285 *have = got;
1286 return next;
1289 int ZEXPORT inflateSync(strm)
1290 z_streamp strm;
1292 unsigned len; /* number of bytes to look at or looked at */
1293 unsigned long in, out; /* temporary to save total_in and total_out */
1294 unsigned char buf[4]; /* to restore bit buffer to byte string */
1295 struct inflate_state FAR *state;
1297 /* check parameters */
1298 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1299 state = (struct inflate_state FAR *)strm->state;
1300 if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
1302 /* if first time, start search in bit buffer */
1303 if (state->mode != SYNC) {
1304 state->mode = SYNC;
1305 state->hold <<= state->bits & 7;
1306 state->bits -= state->bits & 7;
1307 len = 0;
1308 while (state->bits >= 8) {
1309 buf[len++] = (unsigned char)(state->hold);
1310 state->hold >>= 8;
1311 state->bits -= 8;
1313 state->have = 0;
1314 (void) syncsearch(&(state->have), buf, len);
1317 /* search available input */
1318 len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
1319 strm->avail_in -= len;
1320 strm->next_in += len;
1321 strm->total_in += len;
1323 /* return no joy or set up to restart inflate() on a new block */
1324 if (state->have != 4) return Z_DATA_ERROR;
1325 in = strm->total_in; out = strm->total_out;
1326 (void) inflateReset(strm);
1327 strm->total_in = in; strm->total_out = out;
1328 state->mode = TYPE;
1329 return Z_OK;
1333 Returns true if inflate is currently at the end of a block generated by
1334 Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
1335 implementation to provide an additional safety check. PPP uses
1336 Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
1337 block. When decompressing, PPP checks that at the end of input packet,
1338 inflate is waiting for these length bytes.
1340 int ZEXPORT inflateSyncPoint(strm)
1341 z_streamp strm;
1343 struct inflate_state FAR *state;
1345 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1346 state = (struct inflate_state FAR *)strm->state;
1347 return state->mode == STORED && state->bits == 0;
1350 int ZEXPORT inflateCopy(dest, source)
1351 z_streamp dest;
1352 z_streamp source;
1354 struct inflate_state FAR *state;
1355 struct inflate_state FAR *copy;
1356 unsigned char FAR *window;
1357 unsigned wsize;
1359 /* check input */
1360 if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
1361 source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
1362 return Z_STREAM_ERROR;
1363 state = (struct inflate_state FAR *)source->state;
1365 /* allocate space */
1366 copy = (struct inflate_state FAR *)
1367 ZALLOC(source, 1, sizeof(struct inflate_state));
1368 if (copy == Z_NULL) return Z_MEM_ERROR;
1369 window = Z_NULL;
1370 if (state->window != Z_NULL) {
1371 window = (unsigned char FAR *)
1372 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
1373 if (window == Z_NULL) {
1374 ZFREE(source, copy);
1375 return Z_MEM_ERROR;
1379 /* copy state */
1380 zmemcpy(dest, source, sizeof(z_stream));
1381 zmemcpy(copy, state, sizeof(struct inflate_state));
1382 if (state->lencode >= state->codes &&
1383 state->lencode <= state->codes + ENOUGH - 1) {
1384 copy->lencode = copy->codes + (state->lencode - state->codes);
1385 copy->distcode = copy->codes + (state->distcode - state->codes);
1387 copy->next = copy->codes + (state->next - state->codes);
1388 if (window != Z_NULL) {
1389 wsize = 1U << state->wbits;
1390 zmemcpy(window, state->window, wsize);
1392 copy->window = window;
1393 dest->state = (struct internal_state FAR *)copy;
1394 return Z_OK;