2 * inflate.c - inflate decompression routine
8 * Copyright (C) 1995, Edward B. Hamrick
10 * Permission to use, copy, modify, and distribute this software and
11 * its documentation for any purpose and without fee is hereby granted,
12 * provided that the above copyright notice appear in all copies and
13 * that both that copyright notice and this permission notice appear in
14 * supporting documentation, and that the name of the copyright holders
15 * not be used in advertising or publicity pertaining to distribution of
16 * the software without specific, written prior permission. The copyright
17 * holders makes no representations about the suitability of this software
18 * for any purpose. It is provided "as is" without express or implied warranty.
20 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
21 * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
22 * IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
23 * OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
24 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
25 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
30 * Changes from 1.1 to 1.1.2:
31 * Relicensed under the MIT license, with consent of the copyright holders.
32 * Claudio Matsuoka (Jan 11 2011)
36 * inflate.c is based on the public-domain (non-copyrighted) version
37 * written by Mark Adler, version c14o, 23 August 1994. It has been
38 * modified to be reentrant, more portable, and to be data driven.
42 * 1) All file i/o is done externally to these routines
43 * 2) Routines are symmetrical so inflate can feed into deflate
44 * 3) Routines can be easily integrated into wide range of applications
45 * 4) Routines are very portable, and use only ANSI C
46 * 5) No #defines in inflate.h to conflict with external #defines
47 * 6) No external routines need be called by these routines
48 * 7) Buffers are owned by the calling routine
49 * 8) No static non-constant variables are allowed
53 * Note that for each call to InflatePutBuffer, there will be
54 * 0 or more calls to (*putbuffer_ptr). Before InflatePutBuffer
55 * returns, it will have output as much uncompressed data as
66 * Macros for constants
70 #define NULL ((void *) 0)
82 #define WINDOWSIZE 0x8000
86 #define WINDOWMASK 0x7fff
90 #define BUFFERSIZE 0x4000
94 #define BUFFERMASK 0x3fff
97 #ifndef INFLATESTATETYPE
98 #define INFLATESTATETYPE 0xabcdabcdL
105 typedef unsigned long ulg
;
106 typedef unsigned short ush
;
107 typedef unsigned char uch
;
109 /* Structure to hold state for inflating zip files */
110 struct InflateState
{
112 unsigned long runtimetypeid1
; /* to detect run-time errors */
113 int errorencountered
; /* error encountered flag */
116 int state
; /* -1 -> need block type */
117 /* 0 -> need stored setup */
118 /* 1 -> need fixed setup */
119 /* 2 -> need dynamic setup */
120 /* 10 -> need stored data */
121 /* 11 -> need fixed data */
122 /* 12 -> need dynamic data */
124 /* State for decoding fixed & dynamic data */
125 struct huft
*tl
; /* literal/length decoder tbl */
126 struct huft
*td
; /* distance decoder table */
127 int bl
; /* bits decoded by tl */
128 int bd
; /* bits decoded by td */
130 /* State for decoding stored data */
131 unsigned int storelength
;
133 /* State to keep track that last block has been encountered */
134 int lastblock
; /* current block is last */
136 /* Input buffer state (circular) */
137 ulg bb
; /* input buffer bits */
138 unsigned int bk
; /* input buffer count of bits */
139 unsigned int bp
; /* input buffer pointer */
140 unsigned int bs
; /* input buffer size */
141 unsigned char buffer
[BUFFERSIZE
]; /* input buffer data */
143 /* Storage for try/catch */
144 ulg catch_bb
; /* bit buffer */
145 unsigned int catch_bk
; /* bits in bit buffer */
146 unsigned int catch_bp
; /* buffer pointer */
147 unsigned int catch_bs
; /* buffer size */
149 /* Output window state (circular) */
150 unsigned int wp
; /* output window pointer */
151 unsigned int wf
; /* output window flush-from */
152 unsigned char window
[WINDOWSIZE
]; /* output window data */
154 /* Application state */
155 void *AppState
; /* opaque ptr for callout */
157 /* pointers to call-outs */
158 int (*putbuffer_ptr
)( /* returns 0 on success */
159 void *AppState
, /* opaque ptr from Initialize */
160 unsigned char *buffer
, /* buffer to put */
161 long length
/* length of buffer */
164 void *(*malloc_ptr
)(long length
); /* utility routine */
166 void (*free_ptr
)(void *buffer
); /* utility routine */
168 unsigned long runtimetypeid2
; /* to detect run-time errors */
172 * Error handling macro
175 #define ERROREXIT(is) {(is)->errorencountered = TRUE; return TRUE;}
178 * Macros for handling data in the input buffer
180 * Note that the NEEDBITS and DUMPBITS macros
181 * need to be bracketed by the TRY/CATCH macros
188 * x = b & mask_bits[j];
195 * Note that there can only be one TRY/CATCH pair per routine
196 * because of the use of goto in the implementation of the macros.
198 * NEEDBITS makes sure that b has at least j bits in it, and
199 * DUMPBITS removes the bits from b. The macros use the variable k
200 * for the number of bits in b. Normally, b and k are register
201 * variables for speed, and are initialized at the beginning of a
202 * routine that uses these macros from a global bit buffer and count.
204 * In order to not ask for more bits than there are in the compressed
205 * stream, the Huffman tables are constructed to only ask for just
206 * enough bits to make up the end-of-block code (value 256). Then no
207 * bytes need to be "returned" to the buffer at the end of the last
208 * block. See the huft_build() routine.
214 is->catch_bp = is->bp; \
215 is->catch_bs = is->bs;
217 #define CATCH_BEGIN \
224 is->bp = is->catch_bp; \
225 is->bs = is->catch_bs;
230 #define NEEDBITS(n) \
238 b |= ((ulg) (is->buffer[is->bp & BUFFERMASK])) << k; \
245 #define DUMPBITS(n) \
252 * Macro for flushing the output window to the putbuffer callout.
254 * Note that the window is always flushed when it fills to 32K,
255 * and before returning to the application.
258 #define FLUSHWINDOW(w, now) \
259 if ((now && (is->wp > is->wf)) || ((w) >= WINDOWSIZE)) \
262 if ((*(is->putbuffer_ptr)) \
263 (is->AppState, is->window+is->wf, is->wp-is->wf)) \
265 is->wp &= WINDOWMASK; \
271 * Inflate deflated (PKZIP's method 8 compressed) data. The compression
272 * method searches for as much of the current string of bytes (up to a
273 * length of 258) in the previous 32K bytes. If it doesn't find any
274 * matches (of at least length 3), it codes the next byte. Otherwise, it
275 * codes the length of the matched string and its distance backwards from
276 * the current position. There is a single Huffman code that codes both
277 * single bytes (called "literals") and match lengths. A second Huffman
278 * code codes the distance information, which follows a length code. Each
279 * length or distance code actually represents a base value and a number
280 * of "extra" (sometimes zero) bits to get to add to the base value. At
281 * the end of each deflated block is a special end-of-block (EOB) literal/
282 * length code. The decoding process is basically: get a literal/length
283 * code; if EOB then done; if a literal, emit the decoded byte; if a
284 * length then get the distance and emit the referred-to bytes from the
285 * sliding window of previously emitted data.
287 * There are (currently) three kinds of inflate blocks: stored, fixed, and
288 * dynamic. The compressor outputs a chunk of data at a time and decides
289 * which method to use on a chunk-by-chunk basis. A chunk might typically
290 * be 32K to 64K, uncompressed. If the chunk is uncompressible, then the
291 * "stored" method is used. In this case, the bytes are simply stored as
292 * is, eight bits per byte, with none of the above coding. The bytes are
293 * preceded by a count, since there is no longer an EOB code.
295 * If the data is compressible, then either the fixed or dynamic methods
296 * are used. In the dynamic method, the compressed data is preceded by
297 * an encoding of the literal/length and distance Huffman codes that are
298 * to be used to decode this block. The representation is itself Huffman
299 * coded, and so is preceded by a description of that code. These code
300 * descriptions take up a little space, and so for small blocks, there is
301 * a predefined set of codes, called the fixed codes. The fixed method is
302 * used if the block ends up smaller that way (usually for quite small
303 * chunks); otherwise the dynamic method is used. In the latter case, the
304 * codes are customized to the probabilities in the current block and so
305 * can code it much better than the pre-determined fixed codes can.
307 * The Huffman codes themselves are decoded using a mutli-level table
308 * lookup, in order to maximize the speed of decoding plus the speed of
309 * building the decoding tables. See the comments below that precede the
310 * lbits and dbits tuning parameters.
314 * Notes beyond the 1.93a appnote.txt:
316 * 1. Distance pointers never point before the beginning of the output
318 * 2. Distance pointers can point back across blocks, up to 32k away.
319 * 3. There is an implied maximum of 7 bits for the bit length table and
320 * 15 bits for the actual data.
321 * 4. If only one code exists, then it is encoded using one bit. (Zero
322 * would be more efficient, but perhaps a little confusing.) If two
323 * codes exist, they are coded using one bit each (0 and 1).
324 * 5. There is no way of sending zero distance codes--a dummy must be
325 * sent if there are none. (History: a pre 2.0 version of PKZIP would
326 * store blocks with no distance codes, but this was discovered to be
327 * too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
328 * zero distance codes, which is sent as one code of zero bits in
330 * 6. There are up to 286 literal/length codes. Code 256 represents the
331 * end-of-block. Note however that the static length tree defines
332 * 288 codes just to fill out the Huffman codes. Codes 286 and 287
333 * cannot be used though, since there is no length base or extra bits
334 * defined for them. Similarly, there are up to 30 distance codes.
335 * However, static trees define 32 codes (all 5 bits) to fill out the
336 * Huffman codes, but the last two had better not show up in the data.
337 * 7. Unzip can check dynamic Huffman blocks for complete code sets.
338 * The exception is that a single code would not be complete (see #4).
339 * 8. The five bits following the block type is really the number of
340 * literal codes sent minus 257.
341 * 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
342 * (1+6+6). Therefore, to output three times the length, you output
343 * three codes (1+1+1), whereas to output four times the same length,
344 * you only need two codes (1+3). Hmm.
345 *10. In the tree reconstruction algorithm, Code = Code + Increment
346 * only if BitLength(i) is not zero. (Pretty obvious.)
347 *11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
348 *12. Note: length code 284 can represent 227-258, but length code 285
349 * really is 258. The last length deserves its own, short code
350 * since it gets used a lot in very redundant files. The length
351 * 258 is special since 258 - 3 (the min match length) is 255.
352 *13. The literal/length and distance code bit lengths are read as a
353 * single stream of lengths. It is possible (and advantageous) for
354 * a repeat code (16, 17, or 18) to go across the boundary between
355 * the two sets of lengths.
359 * Huffman code lookup table entry--this entry is four bytes for machines
360 * that have 16-bit pointers (e.g. PC's in the small or medium model).
361 * Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16
362 * means that v is a literal, 16 < e < 32 means that v is a pointer to
363 * the next table, which codes e - 16 bits, and lastly e == 99 indicates
364 * an unused code. If a code with e == 99 is looked up, this implies an
369 uch e
; /* number of extra bits or operation */
370 uch b
; /* number of bits in this code or subcode */
372 ush n
; /* literal, length base, or distance base */
373 struct huft
*t
; /* pointer to next level of table */
378 * Tables for deflate from PKZIP's appnote.txt.
381 static const unsigned border
[] = { /* Order of the bit length code lengths */
382 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
384 static const ush cplens
[] = { /* Copy lengths for literal codes 257..285 */
385 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
386 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
387 /* note: see note #13 above about the 258 in this list. */
389 static const ush cplext
[] = { /* Extra bits for literal codes 257..285 */
390 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
391 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
393 static const ush cpdist
[] = { /* Copy offsets for distance codes 0..29 */
394 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
395 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
396 8193, 12289, 16385, 24577};
398 static const ush cpdext
[] = { /* Extra bits for distance codes */
399 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
400 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
404 * Constants for run-time computation of mask
407 static const ush mask_bits
[] = {
409 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
410 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
414 * Huffman code decoding is performed using a multi-level table lookup.
415 * The fastest way to decode is to simply build a lookup table whose
416 * size is determined by the longest code. However, the time it takes
417 * to build this table can also be a factor if the data being decoded
418 * is not very long. The most common codes are necessarily the
419 * shortest codes, so those codes dominate the decoding time, and hence
420 * the speed. The idea is you can have a shorter table that decodes the
421 * shorter, more probable codes, and then point to subsidiary tables for
422 * the longer codes. The time it costs to decode the longer codes is
423 * then traded against the time it takes to make longer tables.
425 * This results of this trade are in the variables lbits and dbits
426 * below. lbits is the number of bits the first level table for literal/
427 * length codes can decode in one step, and dbits is the same thing for
428 * the distance codes. Subsequent tables are also less than or equal to
429 * those sizes. These values may be adjusted either when all of the
430 * codes are shorter than that, in which case the longest code length in
431 * bits is used, or when the shortest code is *longer* than the requested
432 * table size, in which case the length of the shortest code in bits is
435 * There are two different values for the two tables, since they code a
436 * different number of possibilities each. The literal/length table
437 * codes 286 possible values, or in a flat code, a little over eight
438 * bits. The distance table codes 30 possible values, or a little less
439 * than five bits, flat. The optimum values for speed end up being
440 * about one bit more than those, so lbits is 8+1 and dbits is 5+1.
441 * The optimum values may differ though from machine to machine, and
442 * possibly even between compilers. Your mileage may vary.
445 static const int lbits
= 9; /* bits in base literal/length lookup table */
446 static const int dbits
= 6; /* bits in base distance lookup table */
448 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
449 #define BMAX 16 /* maximum bit length of any code (16 for explode) */
450 #define N_MAX 288 /* maximum number of codes in any set */
453 * Free the malloc'ed tables built by huft_build(), which makes a linked
454 * list of the tables it made, with the links in a dummy first entry of
458 static int huft_free(
459 struct InflateState
*is
, /* Inflate state */
460 struct huft
*t
/* table to free */
465 /* Go through linked list, freeing from the malloced (t[-1]) address. */
467 while (p
!= (struct huft
*)NULL
)
470 (*is
->free_ptr
)((char*)p
);
477 * Given a list of code lengths and a maximum table size, make a set of
478 * tables to decode that set of codes. Return zero on success, one if
479 * the given code set is incomplete (the tables are still built in this
480 * case), two if the input is invalid (all zero length codes or an
481 * oversubscribed set of lengths), and three if not enough memory.
482 * The code with value 256 is special, and the tables are constructed
483 * so that no bits beyond that code are fetched when that code is
487 static int huft_build(
488 struct InflateState
*is
, /* Inflate state */
489 unsigned *b
, /* code lengths in bits (all assumed <= BMAX) */
490 unsigned n
, /* number of codes (assumed <= N_MAX) */
491 unsigned s
, /* number of simple-valued codes (0..s-1) */
492 const ush
*d
, /* list of base values for non-simple codes */
493 const ush
*e
, /* list of extra bits for non-simple codes */
494 struct huft
**t
, /* result: starting table */
495 int *m
/* maximum lookup bits, returns actual */
498 unsigned a
; /* counter for codes of length k */
499 unsigned c
[BMAX
+1]; /* bit length count table */
500 unsigned el
; /* length of EOB code (value 256) */
501 unsigned f
; /* i repeats in table every f entries */
502 int g
; /* maximum code length */
503 int h
; /* table level */
504 unsigned i
; /* counter, current code */
505 unsigned j
; /* counter */
506 int k
; /* number of bits in current code */
507 int lx
[BMAX
+1]; /* memory for l[-1..BMAX-1] */
508 int *l
= lx
+1; /* stack of bits per table */
509 unsigned *p
; /* pointer into c[], b[], or v[] */
510 struct huft
*q
; /* points to current table */
511 struct huft r
; /* table entry for structure assignment */
512 struct huft
*u
[BMAX
]; /* table stack */
513 unsigned v
[N_MAX
]; /* values in order of bit length */
514 int w
; /* bits before this table == (l * h) */
515 unsigned x
[BMAX
+1]; /* bit offsets, then code stack */
516 unsigned *xp
; /* pointer into x */
517 int y
; /* number of dummy codes added */
518 unsigned z
; /* number of entries in current table */
520 /* clear the bit length count table */
521 for (i
=0; i
<(BMAX
+1); i
++)
526 /* Generate counts for each bit length */
527 el
= n
> 256 ? b
[256] : BMAX
; /* set length of EOB code, if any */
530 c
[*p
]++; p
++; /* assume all entries <= BMAX */
532 if (c
[0] == n
) /* null input--all zero length codes */
534 *t
= (struct huft
*)NULL
;
539 /* Find minimum and maximum length, bound *m by those */
540 for (j
= 1; j
<= BMAX
; j
++)
543 k
= j
; /* minimum code length */
544 if ((unsigned)*m
< j
)
546 for (i
= BMAX
; i
; i
--)
549 g
= i
; /* maximum code length */
550 if ((unsigned)*m
> i
)
553 /* Adjust last length count to fill out codes, if needed */
554 for (y
= 1 << j
; j
< i
; j
++, y
<<= 1)
556 return 2; /* bad input: more codes than bits */
561 /* Generate starting offsets into the value table for each length */
563 p
= c
+ 1; xp
= x
+ 2;
564 while (--i
) { /* note that i == g from above */
568 /* Make a table of values in order of bit lengths */
575 /* Generate the Huffman codes and for each, make the table entries */
576 x
[0] = i
= 0; /* first Huffman code is zero */
577 p
= v
; /* grab values in bit order */
578 h
= -1; /* no tables yet--level -1 */
579 w
= l
[-1] = 0; /* no bits decoded yet */
580 u
[0] = (struct huft
*)NULL
; /* just to keep compilers happy */
581 q
= (struct huft
*)NULL
; /* ditto */
584 /* go through the bit lengths (k already is bits in shortest code) */
590 /* here i is the Huffman code of length k bits for value *p */
591 /* make tables up to required level */
594 w
+= l
[h
++]; /* add bits already decoded */
596 /* compute minimum size table less than or equal to *m bits */
597 z
= (z
= g
- w
) > (unsigned)*m
? *m
: z
; /* upper limit */
598 if ((f
= 1 << (j
= k
- w
)) > a
+ 1) /* try a k-w bit table */
599 { /* too few codes for k-w bit table */
600 f
-= a
+ 1; /* deduct codes from patterns left */
602 while (++j
< z
) /* try smaller tables up to z bits */
604 if ((f
<<= 1) <= *++xp
)
605 break; /* enough codes to use up j bits */
606 f
-= *xp
; /* else deduct codes from patterns */
609 if ((unsigned)w
+ j
> el
&& (unsigned)w
< el
)
610 j
= el
- w
; /* make EOB code end at table */
611 z
= 1 << j
; /* table entries for j-bit table */
612 l
[h
] = j
; /* set table size in stack */
614 /* allocate and link in new table */
615 if ((q
= (struct huft
*)
616 ((*is
->malloc_ptr
)((z
+ 1)*sizeof(struct huft
)))) ==
621 return 3; /* not enough memory */
623 *t
= q
+ 1; /* link to list for huft_free() */
624 *(t
= &(q
->v
.t
)) = (struct huft
*)NULL
;
625 u
[h
] = ++q
; /* table starts after link */
627 /* connect to last table, if there is one */
630 x
[h
] = i
; /* save pattern for backing up */
631 r
.b
= (uch
)l
[h
-1]; /* bits to dump before this table */
632 r
.e
= (uch
)(16 + j
); /* bits in this table */
633 r
.v
.t
= q
; /* pointer to this table */
634 j
= (i
& ((1 << w
) - 1)) >> (w
- l
[h
-1]);
635 u
[h
-1][j
] = r
; /* connect to last table */
639 /* set up table entry in r */
642 r
.e
= 99; /* out of values--invalid code */
645 r
.e
= (uch
)(*p
< 256 ? 16 : 15); /* 256 is end-of-block code */
646 r
.v
.n
= (ush
) *p
++; /* simple code is just the value */
650 r
.e
= (uch
)e
[*p
- s
]; /* non-simple--look up in lists */
654 /* fill code-like entries with r */
656 for (j
= i
>> w
; j
< z
; j
+= f
)
659 /* backwards increment the k-bit code i */
660 for (j
= 1 << (k
- 1); i
& j
; j
>>= 1)
664 /* backup over finished tables */
665 while ((i
& ((1 << w
) - 1)) != x
[h
])
666 w
-= l
[--h
]; /* don't need to update q */
670 /* return actual size of base table */
673 /* Return true (1) if we were given an incomplete table */
674 return y
!= 0 && g
!= 1;
678 * inflate (decompress) the codes in a stored (uncompressed) block.
679 * Return an error code or zero if it all goes ok.
682 static int inflate_stored(
683 struct InflateState
*is
/* Inflate state */
686 ulg b
; /* bit buffer */
687 unsigned k
; /* number of bits in bit buffer */
688 unsigned w
; /* current window position */
690 /* make local copies of state */
691 b
= is
->bb
; /* initialize bit buffer */
692 k
= is
->bk
; /* initialize bit count */
693 w
= is
->wp
; /* initialize window position */
696 * Note that this code knows that NEEDBITS jumps to cleanup
699 while (is
->storelength
> 0) /* do until end of block */
702 is
->window
[w
++] = (uch
) b
;
704 FLUSHWINDOW(w
, FALSE
);
710 /* restore the state from the locals */
711 is
->bb
= b
; /* restore bit buffer */
712 is
->bk
= k
; /* restore bit count */
713 is
->wp
= w
; /* restore window pointer */
715 if (is
->storelength
> 0)
721 static int inflate_codes(
722 struct InflateState
*is
, /* Inflate state */
723 struct huft
*tl
, /* literal/length decoder table */
724 struct huft
*td
, /* distance decoder table */
725 int bl
, /* number of bits decoded by tl[] */
726 int bd
/* number of bits decoded by td[] */
729 unsigned e
; /* table entry flag/number of extra bits */
730 unsigned n
, d
; /* length and index for copy */
731 unsigned w
; /* current window position */
732 struct huft
*t
; /* pointer to table entry */
733 unsigned ml
, md
; /* masks for bl and bd bits */
734 ulg b
; /* bit buffer */
735 unsigned k
; /* number of bits in bit buffer */
737 /* make local copies of state */
738 b
= is
->bb
; /* initialize bit buffer */
739 k
= is
->bk
; /* initialize bit count */
740 w
= is
->wp
; /* initialize window position */
742 /* inflate the coded data */
743 ml
= mask_bits
[bl
]; /* precompute masks for speed */
745 for (;;) /* do until end of block */
749 NEEDBITS((unsigned)bl
)
750 if ((e
= (t
= tl
+ ((unsigned)b
& ml
))->e
) > 16)
757 } while ((e
= (t
= t
->v
.t
+ ((unsigned)b
& mask_bits
[e
]))->e
) > 16);
760 if (e
== 16) /* it's a literal */
762 is
->window
[w
++] = (uch
)t
->v
.n
;
763 FLUSHWINDOW(w
, FALSE
);
765 else if (e
== 15) /* it's an EOB */
769 else /* it's a length */
771 /* get length of block to copy */
773 n
= t
->v
.n
+ ((unsigned)b
& mask_bits
[e
]);
776 /* decode distance of block to copy */
777 NEEDBITS((unsigned)bd
)
778 if ((e
= (t
= td
+ ((unsigned)b
& md
))->e
) > 16)
785 } while ((e
= (t
= t
->v
.t
+ ((unsigned)b
& mask_bits
[e
]))->e
) > 16);
788 d
= w
- t
->v
.n
- ((unsigned)b
& mask_bits
[e
]);
793 n
-= (e
= ((e
= WINDOWSIZE
- ((d
&= WINDOWMASK
) > w
? d
: w
)) > n
)
797 if (w
- d
>= e
) /* (this test assumes unsigned comparison) */
799 memcpy(is
->window
+ w
, is
->window
+ d
, e
);
803 else /* do it slow to avoid memcpy() overlap */
806 is
->window
[w
++] = is
->window
[d
++];
808 FLUSHWINDOW(w
, FALSE
);
813 is
->wp
= w
; /* restore window pointer */
818 /* restore the state from the locals */
819 is
->bb
= b
; /* restore bit buffer */
820 is
->bk
= k
; /* restore bit count */
821 is
->wp
= w
; /* restore window pointer */
828 * "decompress" an inflated type 0 (stored) block.
831 static int inflate_stored_setup(
832 struct InflateState
*is
/* Inflate state */
835 unsigned n
; /* number of bytes in block */
836 ulg b
; /* bit buffer */
837 unsigned k
; /* number of bits in bit buffer */
839 /* make local copies of state */
840 b
= is
->bb
; /* initialize bit buffer */
841 k
= is
->bk
; /* initialize bit count */
845 /* go to byte boundary */
849 /* get the length and its complement */
851 n
= ((unsigned)b
& 0xffff);
854 if (n
!= (unsigned)((~b
) & 0xffff))
855 return 1; /* error in compressed data */
862 /* Save store state for this block */
865 /* restore the state from the locals */
866 is
->bb
= b
; /* restore bit buffer */
867 is
->bk
= k
; /* restore bit count */
873 * decompress an inflated type 1 (fixed Huffman codes) block. We should
874 * either replace this with a custom decoder, or at least precompute the
878 static int inflate_fixed_setup(
879 struct InflateState
*is
/* Inflate state */
882 int i
; /* temporary variable */
883 struct huft
*tl
; /* literal/length code table */
884 struct huft
*td
; /* distance code table */
885 int bl
; /* lookup bits for tl */
886 int bd
; /* lookup bits for td */
887 unsigned l
[288]; /* length list for huft_build */
889 /* set up literal table */
890 for (i
= 0; i
< 144; i
++)
896 for (; i
< 288; i
++) /* make a complete, but wrong code set */
899 if ((i
= huft_build(is
, l
, 288, 257, cplens
, cplext
, &tl
, &bl
)) != 0)
902 /* set up distance table */
903 for (i
= 0; i
< 30; i
++) /* make an incomplete code set */
906 if ((i
= huft_build(is
, l
, 30, 0, cpdist
, cpdext
, &td
, &bd
)) > 1)
912 /* Save inflate state for this block */
922 * decompress an inflated type 2 (dynamic Huffman codes) block.
925 #define PKZIP_BUG_WORKAROUND
927 static int inflate_dynamic_setup(
928 struct InflateState
*is
/* Inflate state */
931 int i
; /* temporary variables */
933 unsigned l
; /* last length */
934 unsigned m
; /* mask for bit lengths table */
935 unsigned n
; /* number of lengths to get */
936 struct huft
*tl
; /* literal/length code table */
937 struct huft
*td
; /* distance code table */
938 int bl
; /* lookup bits for tl */
939 int bd
; /* lookup bits for td */
940 unsigned nb
; /* number of bit length codes */
941 unsigned nl
; /* number of literal/length codes */
942 unsigned nd
; /* number of distance codes */
943 #ifdef PKZIP_BUG_WORKAROUND
944 unsigned ll
[288+32]; /* literal/length and distance code lengths */
946 unsigned ll
[286+30]; /* literal/length and distance code lengths */
948 ulg b
; /* bit buffer */
949 unsigned k
; /* number of bits in bit buffer */
951 /* make local copies of state */
952 b
= is
->bb
; /* initialize bit buffer */
953 k
= is
->bk
; /* initialize bit count */
955 /* initialize tl for cleanup */
960 /* read in table lengths */
962 nl
= 257 + ((unsigned)b
& 0x1f); /* number of literal/length codes */
965 nd
= 1 + ((unsigned)b
& 0x1f); /* number of distance codes */
968 nb
= 4 + ((unsigned)b
& 0xf); /* number of bit length codes */
970 #ifdef PKZIP_BUG_WORKAROUND
971 if (nl
> 288 || nd
> 32)
973 if (nl
> 286 || nd
> 30)
975 return 1; /* bad lengths */
977 /* read in bit-length-code lengths */
978 for (j
= 0; j
< 19; j
++) ll
[j
] = 0;
979 for (j
= 0; j
< nb
; j
++)
982 ll
[border
[j
]] = (unsigned)b
& 7;
986 /* build decoding table for trees--single level, 7 bit lookup */
988 if ((i
= huft_build(is
, ll
, 19, 19, NULL
, NULL
, &tl
, &bl
)) != 0)
992 return i
; /* incomplete code set */
995 /* read in literal and distance code lengths */
999 while ((unsigned)i
< n
)
1001 NEEDBITS((unsigned)bl
)
1002 j
= (td
= tl
+ ((unsigned)b
& m
))->b
;
1005 if (j
< 16) /* length of code in bits (0..15) */
1006 ll
[i
++] = l
= j
; /* save last length in l */
1007 else if (j
== 16) /* repeat last length 3 to 6 times */
1010 j
= 3 + ((unsigned)b
& 3);
1012 if ((unsigned)i
+ j
> n
)
1017 else if (j
== 17) /* 3 to 10 zero length codes */
1020 j
= 3 + ((unsigned)b
& 7);
1022 if ((unsigned)i
+ j
> n
)
1028 else /* j == 18: 11 to 138 zero length codes */
1031 j
= 11 + ((unsigned)b
& 0x7f);
1033 if ((unsigned)i
+ j
> n
)
1041 /* free decoding table for trees */
1045 if (tl
) huft_free(is
, tl
);
1049 /* restore the state from the locals */
1050 is
->bb
= b
; /* restore bit buffer */
1051 is
->bk
= k
; /* restore bit count */
1053 /* build the decoding tables for literal/length and distance codes */
1055 if ((i
= huft_build(is
, ll
, nl
, 257, cplens
, cplext
, &tl
, &bl
)) != 0)
1058 /* incomplete literal tree */
1061 return i
; /* incomplete code set */
1064 if ((i
= huft_build(is
, ll
+ nl
, nd
, 0, cpdist
, cpdext
, &td
, &bd
)) != 0)
1067 /* incomplete distance tree */
1068 #ifdef PKZIP_BUG_WORKAROUND
1074 return i
; /* incomplete code set */
1078 /* Save inflate state for this block */
1087 /* Routine to initialize inflate decompression */
1088 void *InflateInitialize( /* returns InflateState */
1089 void *AppState
, /* for passing to putbuffer */
1090 int (*putbuffer_ptr
)( /* returns 0 on success */
1091 void *AppState
, /* opaque ptr from Initialize */
1092 unsigned char *buffer
, /* buffer to put */
1093 long length
/* length of buffer */
1095 void *(*malloc_ptr
)(long length
), /* utility routine */
1096 void (*free_ptr
)(void *buffer
) /* utility routine */
1099 struct InflateState
*is
;
1101 /* Do some argument checking */
1102 if ((!putbuffer_ptr
) || (!malloc_ptr
) || (!free_ptr
)) return NULL
;
1104 /* Allocate the InflateState memory area */
1105 is
= (struct InflateState
*) (*malloc_ptr
)(sizeof(struct InflateState
));
1106 if (!is
) return NULL
;
1108 /* Set up the initial values of the inflate state */
1109 is
->runtimetypeid1
= INFLATESTATETYPE
;
1110 is
->errorencountered
= FALSE
;
1121 is
->lastblock
= FALSE
;
1123 is
->AppState
= AppState
;
1125 is
->putbuffer_ptr
= putbuffer_ptr
;
1126 is
->malloc_ptr
= malloc_ptr
;
1127 is
->free_ptr
= free_ptr
;
1129 is
->runtimetypeid2
= INFLATESTATETYPE
;
1131 /* Return this state info to the caller */
1135 /* Call-in routine to put a buffer into inflate decompression */
1136 int InflatePutBuffer( /* returns 0 on success */
1137 void *InflateState
, /* opaque ptr from Initialize */
1138 unsigned char *buffer
, /* buffer to put */
1139 long length
/* length of buffer */
1142 struct InflateState
*is
;
1146 /* Get (and check) the InflateState structure */
1147 is
= (struct InflateState
*) InflateState
;
1148 if (!is
|| (is
->runtimetypeid1
!= INFLATESTATETYPE
)
1149 || (is
->runtimetypeid2
!= INFLATESTATETYPE
)) return TRUE
;
1150 if (is
->errorencountered
) return TRUE
;
1157 if ((is
->state
== -1) && (is
->lastblock
)) break;
1159 /* Save the beginning state */
1160 beginstate
= is
->state
;
1162 /* Push as much as possible into input buffer */
1163 size
= BUFFERSIZE
- is
->bs
;
1164 if (size
> length
) size
= (int) length
;
1165 i
= is
->bp
+ is
->bs
;
1169 is
->buffer
[i
++ & BUFFERMASK
] = *buffer
;
1175 /* Process some more data */
1176 if (is
->state
== -1)
1178 int e
; /* last block flag */
1179 unsigned t
; /* block type */
1181 ulg b
; /* bit buffer */
1182 unsigned k
; /* number of bits in bit buffer */
1184 /* make local copies of state */
1185 b
= is
->bb
; /* initialize bit buffer */
1186 k
= is
->bk
; /* initialize bit count */
1190 /* read in last block bit */
1195 /* read in block type */
1197 t
= (unsigned)b
& 3;
1213 /* restore the state from the locals */
1214 is
->bb
= b
; /* restore bit buffer */
1215 is
->bk
= k
; /* restore bit count */
1217 else if (is
->state
== 0)
1221 ret
= inflate_stored_setup(is
);
1226 if (ret
== 0) is
->state
+= 10;
1228 else if (is
->state
== 1)
1232 ret
= inflate_fixed_setup(is
);
1237 if (ret
== 0) is
->state
+= 10;
1239 else if (is
->state
== 2)
1243 ret
= inflate_dynamic_setup(is
);
1248 if (ret
== 0) is
->state
+= 10;
1250 else if (is
->state
== 10)
1254 ret
= inflate_stored(is
);
1264 else if ((is
->state
== 11) ||
1269 ret
= inflate_codes(is
, is
->tl
, is
->td
, is
->bl
, is
->bd
);
1276 /* free the decoding tables */
1277 huft_free(is
, is
->tl
);
1278 huft_free(is
, is
->td
);
1287 while (length
|| (is
->state
!= beginstate
));
1289 FLUSHWINDOW(is
->wp
, TRUE
);
1291 return is
->errorencountered
;
1294 /* Routine to terminate inflate decompression */
1295 int InflateTerminate( /* returns 0 on success */
1296 void *InflateState
/* opaque ptr from Initialize */
1300 void (*free_ptr
)(void *buffer
);
1302 struct InflateState
*is
;
1304 /* Get (and check) the InflateState structure */
1305 is
= (struct InflateState
*) InflateState
;
1306 if (!is
|| (is
->runtimetypeid1
!= INFLATESTATETYPE
)
1307 || (is
->runtimetypeid2
!= INFLATESTATETYPE
)) return TRUE
;
1309 /* save the error return */
1310 err
= is
->errorencountered
|| (is
->bs
> 0)
1311 || (is
->state
!= -1)
1312 || (!is
->lastblock
);
1314 /* save the address of the free routine */
1315 free_ptr
= is
->free_ptr
;
1317 /* Deallocate everything */