inflate.c revision 92723
1/*
2 * Most parts of this file are not covered by:
3 * ----------------------------------------------------------------------------
4 * "THE BEER-WARE LICENSE" (Revision 42):
5 * <phk@login.dknet.dk> wrote this file.  As long as you retain this notice you
6 * can do whatever you want with this stuff. If we meet some day, and you think
7 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
8 * ----------------------------------------------------------------------------
9 *
10 * $FreeBSD: head/sys/kern/inflate.c 92723 2002-03-19 21:25:46Z alfred $
11 *
12 *
13 */
14
15#include <sys/param.h>
16#include <sys/inflate.h>
17#ifdef _KERNEL
18#include <sys/systm.h>
19#include <sys/kernel.h>
20#endif
21#include <sys/malloc.h>
22
23#ifdef _KERNEL
24static MALLOC_DEFINE(M_GZIP, "Gzip trees", "Gzip trees");
25#endif
26
27/* needed to make inflate() work */
28#define	uch u_char
29#define	ush u_short
30#define	ulg u_long
31
32/* Stuff to make inflate() work */
33#ifdef _KERNEL
34#define memzero(dest,len)      bzero(dest,len)
35#endif
36#define NOMEMCPY
37#ifdef _KERNEL
38#define FPRINTF printf
39#else
40extern void putstr (char *);
41#define FPRINTF putstr
42#endif
43
44#define FLUSH(x,y) {						\
45	int foo = (*x->gz_output)(x->gz_private,x->gz_slide,y);	\
46	if (foo) 						\
47		return foo;					\
48	}
49
50static const int qflag = 0;
51
52#ifndef _KERNEL /* want to use this file in kzip also */
53extern unsigned char *kzipmalloc (int);
54extern void kzipfree (void*);
55#define malloc(x, y, z) kzipmalloc((x))
56#define free(x, y) kzipfree((x))
57#endif
58
59/*
60 * This came from unzip-5.12.  I have changed it the flow to pass
61 * a structure pointer around, thus hopefully making it re-entrant.
62 * Poul-Henning
63 */
64
65/* inflate.c -- put in the public domain by Mark Adler
66   version c14o, 23 August 1994 */
67
68/* You can do whatever you like with this source file, though I would
69   prefer that if you modify it and redistribute it that you include
70   comments to that effect with your name and the date.  Thank you.
71
72   History:
73   vers    date          who           what
74   ----  ---------  --------------  ------------------------------------
75    a    ~~ Feb 92  M. Adler        used full (large, one-step) lookup table
76    b1   21 Mar 92  M. Adler        first version with partial lookup tables
77    b2   21 Mar 92  M. Adler        fixed bug in fixed-code blocks
78    b3   22 Mar 92  M. Adler        sped up match copies, cleaned up some
79    b4   25 Mar 92  M. Adler        added prototypes; removed window[] (now
80                                    is the responsibility of unzip.h--also
81                                    changed name to slide[]), so needs diffs
82                                    for unzip.c and unzip.h (this allows
83                                    compiling in the small model on MSDOS);
84                                    fixed cast of q in huft_build();
85    b5   26 Mar 92  M. Adler        got rid of unintended macro recursion.
86    b6   27 Mar 92  M. Adler        got rid of nextbyte() routine.  fixed
87                                    bug in inflate_fixed().
88    c1   30 Mar 92  M. Adler        removed lbits, dbits environment variables.
89                                    changed BMAX to 16 for explode.  Removed
90                                    OUTB usage, and replaced it with flush()--
91                                    this was a 20% speed improvement!  Added
92                                    an explode.c (to replace unimplod.c) that
93                                    uses the huft routines here.  Removed
94                                    register union.
95    c2    4 Apr 92  M. Adler        fixed bug for file sizes a multiple of 32k.
96    c3   10 Apr 92  M. Adler        reduced memory of code tables made by
97                                    huft_build significantly (factor of two to
98                                    three).
99    c4   15 Apr 92  M. Adler        added NOMEMCPY do kill use of memcpy().
100                                    worked around a Turbo C optimization bug.
101    c5   21 Apr 92  M. Adler        added the GZ_WSIZE #define to allow reducing
102                                    the 32K window size for specialized
103                                    applications.
104    c6   31 May 92  M. Adler        added some typecasts to eliminate warnings
105    c7   27 Jun 92  G. Roelofs      added some more typecasts (444:  MSC bug).
106    c8    5 Oct 92  J-l. Gailly     added ifdef'd code to deal with PKZIP bug.
107    c9    9 Oct 92  M. Adler        removed a memory error message (~line 416).
108    c10  17 Oct 92  G. Roelofs      changed ULONG/UWORD/byte to ulg/ush/uch,
109                                    removed old inflate, renamed inflate_entry
110                                    to inflate, added Mark's fix to a comment.
111   c10.5 14 Dec 92  M. Adler        fix up error messages for incomplete trees.
112    c11   2 Jan 93  M. Adler        fixed bug in detection of incomplete
113                                    tables, and removed assumption that EOB is
114                                    the longest code (bad assumption).
115    c12   3 Jan 93  M. Adler        make tables for fixed blocks only once.
116    c13   5 Jan 93  M. Adler        allow all zero length codes (pkzip 2.04c
117                                    outputs one zero length code for an empty
118                                    distance tree).
119    c14  12 Mar 93  M. Adler        made inflate.c standalone with the
120                                    introduction of inflate.h.
121   c14b  16 Jul 93  G. Roelofs      added (unsigned) typecast to w at 470.
122   c14c  19 Jul 93  J. Bush         changed v[N_MAX], l[288], ll[28x+3x] arrays
123                                    to static for Amiga.
124   c14d  13 Aug 93  J-l. Gailly     de-complicatified Mark's c[*p++]++ thing.
125   c14e   8 Oct 93  G. Roelofs      changed memset() to memzero().
126   c14f  22 Oct 93  G. Roelofs      renamed quietflg to qflag; made Trace()
127                                    conditional; added inflate_free().
128   c14g  28 Oct 93  G. Roelofs      changed l/(lx+1) macro to pointer (Cray bug)
129   c14h   7 Dec 93  C. Ghisler      huft_build() optimizations.
130   c14i   9 Jan 94  A. Verheijen    set fixed_t{d,l} to NULL after freeing;
131                    G. Roelofs      check NEXTBYTE macro for GZ_EOF.
132   c14j  23 Jan 94  G. Roelofs      removed Ghisler "optimizations"; ifdef'd
133                                    GZ_EOF check.
134   c14k  27 Feb 94  G. Roelofs      added some typecasts to avoid warnings.
135   c14l   9 Apr 94  G. Roelofs      fixed split comments on preprocessor lines
136                                    to avoid bug in Encore compiler.
137   c14m   7 Jul 94  P. Kienitz      modified to allow assembler version of
138                                    inflate_codes() (define ASM_INFLATECODES)
139   c14n  22 Jul 94  G. Roelofs      changed fprintf to FPRINTF for DLL versions
140   c14o  23 Aug 94  C. Spieler      added a newline to a debug statement;
141                    G. Roelofs      added another typecast to avoid MSC warning
142 */
143
144
145/*
146   Inflate deflated (PKZIP's method 8 compressed) data.  The compression
147   method searches for as much of the current string of bytes (up to a
148   length of 258) in the previous 32K bytes.  If it doesn't find any
149   matches (of at least length 3), it codes the next byte.  Otherwise, it
150   codes the length of the matched string and its distance backwards from
151   the current position.  There is a single Huffman code that codes both
152   single bytes (called "literals") and match lengths.  A second Huffman
153   code codes the distance information, which follows a length code.  Each
154   length or distance code actually represents a base value and a number
155   of "extra" (sometimes zero) bits to get to add to the base value.  At
156   the end of each deflated block is a special end-of-block (EOB) literal/
157   length code.  The decoding process is basically: get a literal/length
158   code; if EOB then done; if a literal, emit the decoded byte; if a
159   length then get the distance and emit the referred-to bytes from the
160   sliding window of previously emitted data.
161
162   There are (currently) three kinds of inflate blocks: stored, fixed, and
163   dynamic.  The compressor outputs a chunk of data at a time and decides
164   which method to use on a chunk-by-chunk basis.  A chunk might typically
165   be 32K to 64K, uncompressed.  If the chunk is uncompressible, then the
166   "stored" method is used.  In this case, the bytes are simply stored as
167   is, eight bits per byte, with none of the above coding.  The bytes are
168   preceded by a count, since there is no longer an EOB code.
169
170   If the data is compressible, then either the fixed or dynamic methods
171   are used.  In the dynamic method, the compressed data is preceded by
172   an encoding of the literal/length and distance Huffman codes that are
173   to be used to decode this block.  The representation is itself Huffman
174   coded, and so is preceded by a description of that code.  These code
175   descriptions take up a little space, and so for small blocks, there is
176   a predefined set of codes, called the fixed codes.  The fixed method is
177   used if the block ends up smaller that way (usually for quite small
178   chunks); otherwise the dynamic method is used.  In the latter case, the
179   codes are customized to the probabilities in the current block and so
180   can code it much better than the pre-determined fixed codes can.
181
182   The Huffman codes themselves are decoded using a mutli-level table
183   lookup, in order to maximize the speed of decoding plus the speed of
184   building the decoding tables.  See the comments below that precede the
185   lbits and dbits tuning parameters.
186 */
187
188
189/*
190   Notes beyond the 1.93a appnote.txt:
191
192   1. Distance pointers never point before the beginning of the output
193      stream.
194   2. Distance pointers can point back across blocks, up to 32k away.
195   3. There is an implied maximum of 7 bits for the bit length table and
196      15 bits for the actual data.
197   4. If only one code exists, then it is encoded using one bit.  (Zero
198      would be more efficient, but perhaps a little confusing.)  If two
199      codes exist, they are coded using one bit each (0 and 1).
200   5. There is no way of sending zero distance codes--a dummy must be
201      sent if there are none.  (History: a pre 2.0 version of PKZIP would
202      store blocks with no distance codes, but this was discovered to be
203      too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
204      zero distance codes, which is sent as one code of zero bits in
205      length.
206   6. There are up to 286 literal/length codes.  Code 256 represents the
207      end-of-block.  Note however that the static length tree defines
208      288 codes just to fill out the Huffman codes.  Codes 286 and 287
209      cannot be used though, since there is no length base or extra bits
210      defined for them.  Similarily, there are up to 30 distance codes.
211      However, static trees define 32 codes (all 5 bits) to fill out the
212      Huffman codes, but the last two had better not show up in the data.
213   7. Unzip can check dynamic Huffman blocks for complete code sets.
214      The exception is that a single code would not be complete (see #4).
215   8. The five bits following the block type is really the number of
216      literal codes sent minus 257.
217   9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
218      (1+6+6).  Therefore, to output three times the length, you output
219      three codes (1+1+1), whereas to output four times the same length,
220      you only need two codes (1+3).  Hmm.
221  10. In the tree reconstruction algorithm, Code = Code + Increment
222      only if BitLength(i) is not zero.  (Pretty obvious.)
223  11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
224  12. Note: length code 284 can represent 227-258, but length code 285
225      really is 258.  The last length deserves its own, short code
226      since it gets used a lot in very redundant files.  The length
227      258 is special since 258 - 3 (the min match length) is 255.
228  13. The literal/length and distance code bit lengths are read as a
229      single stream of lengths.  It is possible (and advantageous) for
230      a repeat code (16, 17, or 18) to go across the boundary between
231      the two sets of lengths.
232 */
233
234
235#define PKZIP_BUG_WORKAROUND	/* PKZIP 1.93a problem--live with it */
236
237/*
238    inflate.h must supply the uch slide[GZ_WSIZE] array and the NEXTBYTE,
239    FLUSH() and memzero macros.  If the window size is not 32K, it
240    should also define GZ_WSIZE.  If INFMOD is defined, it can include
241    compiled functions to support the NEXTBYTE and/or FLUSH() macros.
242    There are defaults for NEXTBYTE and FLUSH() below for use as
243    examples of what those functions need to do.  Normally, you would
244    also want FLUSH() to compute a crc on the data.  inflate.h also
245    needs to provide these typedefs:
246
247        typedef unsigned char uch;
248        typedef unsigned short ush;
249        typedef unsigned long ulg;
250
251    This module uses the external functions malloc() and free() (and
252    probably memset() or bzero() in the memzero() macro).  Their
253    prototypes are normally found in <string.h> and <stdlib.h>.
254 */
255#define INFMOD			/* tell inflate.h to include code to be
256				 * compiled */
257
258/* Huffman code lookup table entry--this entry is four bytes for machines
259   that have 16-bit pointers (e.g. PC's in the small or medium model).
260   Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
261   means that v is a literal, 16 < e < 32 means that v is a pointer to
262   the next table, which codes e - 16 bits, and lastly e == 99 indicates
263   an unused code.  If a code with e == 99 is looked up, this implies an
264   error in the data. */
265struct huft {
266	uch             e;	/* number of extra bits or operation */
267	uch             b;	/* number of bits in this code or subcode */
268	union {
269		ush             n;	/* literal, length base, or distance
270					 * base */
271		struct huft    *t;	/* pointer to next level of table */
272	}               v;
273};
274
275
276/* Function prototypes */
277static int huft_build(struct inflate *, unsigned *, unsigned, unsigned, const ush *, const ush *, struct huft **, int *);
278static int huft_free(struct inflate *, struct huft *);
279static int inflate_codes(struct inflate *, struct huft *, struct huft *, int, int);
280static int inflate_stored(struct inflate *);
281static int xinflate(struct inflate *);
282static int inflate_fixed(struct inflate *);
283static int inflate_dynamic(struct inflate *);
284static int inflate_block(struct inflate *, int *);
285
286/* The inflate algorithm uses a sliding 32K byte window on the uncompressed
287   stream to find repeated byte strings.  This is implemented here as a
288   circular buffer.  The index is updated simply by incrementing and then
289   and'ing with 0x7fff (32K-1). */
290/* It is left to other modules to supply the 32K area.  It is assumed
291   to be usable as if it were declared "uch slide[32768];" or as just
292   "uch *slide;" and then malloc'ed in the latter case.  The definition
293   must be in unzip.h, included above. */
294
295
296/* Tables for deflate from PKZIP's appnote.txt. */
297
298/* Order of the bit length code lengths */
299static const unsigned border[] = {
300	16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
301
302static const ush cplens[] = {	/* Copy lengths for literal codes 257..285 */
303	3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
304	35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
305 /* note: see note #13 above about the 258 in this list. */
306
307static const ush cplext[] = {	/* Extra bits for literal codes 257..285 */
308	0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
309	3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99};	/* 99==invalid */
310
311static const ush cpdist[] = {	/* Copy offsets for distance codes 0..29 */
312	1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
313	257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
314	8193, 12289, 16385, 24577};
315
316static const ush cpdext[] = {	/* Extra bits for distance codes */
317	0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
318	7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
319	12, 12, 13, 13};
320
321/* And'ing with mask[n] masks the lower n bits */
322static const ush mask[] = {
323	0x0000,
324	0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
325	0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
326};
327
328
329/* Macros for inflate() bit peeking and grabbing.
330   The usage is:
331
332        NEEDBITS(glbl,j)
333        x = b & mask[j];
334        DUMPBITS(j)
335
336   where NEEDBITS makes sure that b has at least j bits in it, and
337   DUMPBITS removes the bits from b.  The macros use the variable k
338   for the number of bits in b.  Normally, b and k are register
339   variables for speed, and are initialized at the begining of a
340   routine that uses these macros from a global bit buffer and count.
341
342   In order to not ask for more bits than there are in the compressed
343   stream, the Huffman tables are constructed to only ask for just
344   enough bits to make up the end-of-block code (value 256).  Then no
345   bytes need to be "returned" to the buffer at the end of the last
346   block.  See the huft_build() routine.
347 */
348
349/*
350 * The following 2 were global variables.
351 * They are now fields of the inflate structure.
352 */
353
354#define NEEDBITS(glbl,n) {						\
355		while(k<(n)) {						\
356			int c=(*glbl->gz_input)(glbl->gz_private);	\
357			if(c==GZ_EOF)					\
358				return 1; 				\
359			b|=((ulg)c)<<k;					\
360			k+=8;						\
361		}							\
362	}
363
364#define DUMPBITS(n) {b>>=(n);k-=(n);}
365
366/*
367   Huffman code decoding is performed using a multi-level table lookup.
368   The fastest way to decode is to simply build a lookup table whose
369   size is determined by the longest code.  However, the time it takes
370   to build this table can also be a factor if the data being decoded
371   is not very long.  The most common codes are necessarily the
372   shortest codes, so those codes dominate the decoding time, and hence
373   the speed.  The idea is you can have a shorter table that decodes the
374   shorter, more probable codes, and then point to subsidiary tables for
375   the longer codes.  The time it costs to decode the longer codes is
376   then traded against the time it takes to make longer tables.
377
378   This results of this trade are in the variables lbits and dbits
379   below.  lbits is the number of bits the first level table for literal/
380   length codes can decode in one step, and dbits is the same thing for
381   the distance codes.  Subsequent tables are also less than or equal to
382   those sizes.  These values may be adjusted either when all of the
383   codes are shorter than that, in which case the longest code length in
384   bits is used, or when the shortest code is *longer* than the requested
385   table size, in which case the length of the shortest code in bits is
386   used.
387
388   There are two different values for the two tables, since they code a
389   different number of possibilities each.  The literal/length table
390   codes 286 possible values, or in a flat code, a little over eight
391   bits.  The distance table codes 30 possible values, or a little less
392   than five bits, flat.  The optimum values for speed end up being
393   about one bit more than those, so lbits is 8+1 and dbits is 5+1.
394   The optimum values may differ though from machine to machine, and
395   possibly even between compilers.  Your mileage may vary.
396 */
397
398static const int lbits = 9;	/* bits in base literal/length lookup table */
399static const int dbits = 6;	/* bits in base distance lookup table */
400
401
402/* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
403#define BMAX 16			/* maximum bit length of any code (16 for
404				 * explode) */
405#define N_MAX 288		/* maximum number of codes in any set */
406
407/* Given a list of code lengths and a maximum table size, make a set of
408   tables to decode that set of codes.  Return zero on success, one if
409   the given code set is incomplete (the tables are still built in this
410   case), two if the input is invalid (all zero length codes or an
411   oversubscribed set of lengths), and three if not enough memory.
412   The code with value 256 is special, and the tables are constructed
413   so that no bits beyond that code are fetched when that code is
414   decoded. */
415static int
416huft_build(glbl, b, n, s, d, e, t, m)
417	struct inflate *glbl;
418	unsigned       *b;	/* code lengths in bits (all assumed <= BMAX) */
419	unsigned        n;	/* number of codes (assumed <= N_MAX) */
420	unsigned        s;	/* number of simple-valued codes (0..s-1) */
421	const ush      *d;	/* list of base values for non-simple codes */
422	const ush      *e;	/* list of extra bits for non-simple codes */
423	struct huft   **t;	/* result: starting table */
424	int            *m;	/* maximum lookup bits, returns actual */
425{
426	unsigned        a;	/* counter for codes of length k */
427	unsigned        c[BMAX + 1];	/* bit length count table */
428	unsigned        el;	/* length of EOB code (value 256) */
429	unsigned        f;	/* i repeats in table every f entries */
430	int             g;	/* maximum code length */
431	int             h;	/* table level */
432	register unsigned i;	/* counter, current code */
433	register unsigned j;	/* counter */
434	register int    k;	/* number of bits in current code */
435	int             lx[BMAX + 1];	/* memory for l[-1..BMAX-1] */
436	int            *l = lx + 1;	/* stack of bits per table */
437	register unsigned *p;	/* pointer into c[], b[], or v[] */
438	register struct huft *q;/* points to current table */
439	struct huft     r;	/* table entry for structure assignment */
440	struct huft    *u[BMAX];/* table stack */
441	unsigned        v[N_MAX];	/* values in order of bit length */
442	register int    w;	/* bits before this table == (l * h) */
443	unsigned        x[BMAX + 1];	/* bit offsets, then code stack */
444	unsigned       *xp;	/* pointer into x */
445	int             y;	/* number of dummy codes added */
446	unsigned        z;	/* number of entries in current table */
447
448	/* Generate counts for each bit length */
449	el = n > 256 ? b[256] : BMAX;	/* set length of EOB code, if any */
450#ifdef _KERNEL
451	memzero((char *) c, sizeof(c));
452#else
453	for (i = 0; i < BMAX+1; i++)
454		c [i] = 0;
455#endif
456	p = b;
457	i = n;
458	do {
459		c[*p]++;
460		p++;		/* assume all entries <= BMAX */
461	} while (--i);
462	if (c[0] == n) {	/* null input--all zero length codes */
463		*t = (struct huft *) NULL;
464		*m = 0;
465		return 0;
466	}
467	/* Find minimum and maximum length, bound *m by those */
468	for (j = 1; j <= BMAX; j++)
469		if (c[j])
470			break;
471	k = j;			/* minimum code length */
472	if ((unsigned) *m < j)
473		*m = j;
474	for (i = BMAX; i; i--)
475		if (c[i])
476			break;
477	g = i;			/* maximum code length */
478	if ((unsigned) *m > i)
479		*m = i;
480
481	/* Adjust last length count to fill out codes, if needed */
482	for (y = 1 << j; j < i; j++, y <<= 1)
483		if ((y -= c[j]) < 0)
484			return 2;	/* bad input: more codes than bits */
485	if ((y -= c[i]) < 0)
486		return 2;
487	c[i] += y;
488
489	/* Generate starting offsets into the value table for each length */
490	x[1] = j = 0;
491	p = c + 1;
492	xp = x + 2;
493	while (--i) {		/* note that i == g from above */
494		*xp++ = (j += *p++);
495	}
496
497	/* Make a table of values in order of bit lengths */
498	p = b;
499	i = 0;
500	do {
501		if ((j = *p++) != 0)
502			v[x[j]++] = i;
503	} while (++i < n);
504
505	/* Generate the Huffman codes and for each, make the table entries */
506	x[0] = i = 0;		/* first Huffman code is zero */
507	p = v;			/* grab values in bit order */
508	h = -1;			/* no tables yet--level -1 */
509	w = l[-1] = 0;		/* no bits decoded yet */
510	u[0] = (struct huft *) NULL;	/* just to keep compilers happy */
511	q = (struct huft *) NULL;	/* ditto */
512	z = 0;			/* ditto */
513
514	/* go through the bit lengths (k already is bits in shortest code) */
515	for (; k <= g; k++) {
516		a = c[k];
517		while (a--) {
518			/*
519			 * here i is the Huffman code of length k bits for
520			 * value *p
521			 */
522			/* make tables up to required level */
523			while (k > w + l[h]) {
524				w += l[h++];	/* add bits already decoded */
525
526				/*
527				 * compute minimum size table less than or
528				 * equal to *m bits
529				 */
530				z = (z = g - w) > (unsigned) *m ? *m : z;	/* upper limit */
531				if ((f = 1 << (j = k - w)) > a + 1) {	/* try a k-w bit table *//* t
532									 * oo few codes for k-w
533									 * bit table */
534					f -= a + 1;	/* deduct codes from
535							 * patterns left */
536					xp = c + k;
537					while (++j < z) {	/* try smaller tables up
538								 * to z bits */
539						if ((f <<= 1) <= *++xp)
540							break;	/* enough codes to use
541								 * up j bits */
542						f -= *xp;	/* else deduct codes
543								 * from patterns */
544					}
545				}
546				if ((unsigned) w + j > el && (unsigned) w < el)
547					j = el - w;	/* make EOB code end at
548							 * table */
549				z = 1 << j;	/* table entries for j-bit
550						 * table */
551				l[h] = j;	/* set table size in stack */
552
553				/* allocate and link in new table */
554				if ((q = (struct huft *) malloc((z + 1) * sizeof(struct huft), M_GZIP, M_WAITOK)) ==
555				    (struct huft *) NULL) {
556					if (h)
557						huft_free(glbl, u[0]);
558					return 3;	/* not enough memory */
559				}
560				glbl->gz_hufts += z + 1;	/* track memory usage */
561				*t = q + 1;	/* link to list for
562						 * huft_free() */
563				*(t = &(q->v.t)) = (struct huft *) NULL;
564				u[h] = ++q;	/* table starts after link */
565
566				/* connect to last table, if there is one */
567				if (h) {
568					x[h] = i;	/* save pattern for
569							 * backing up */
570					r.b = (uch) l[h - 1];	/* bits to dump before
571								 * this table */
572					r.e = (uch) (16 + j);	/* bits in this table */
573					r.v.t = q;	/* pointer to this table */
574					j = (i & ((1 << w) - 1)) >> (w - l[h - 1]);
575					u[h - 1][j] = r;	/* connect to last table */
576				}
577			}
578
579			/* set up table entry in r */
580			r.b = (uch) (k - w);
581			if (p >= v + n)
582				r.e = 99;	/* out of values--invalid
583						 * code */
584			else if (*p < s) {
585				r.e = (uch) (*p < 256 ? 16 : 15);	/* 256 is end-of-block
586									 * code */
587				r.v.n = *p++;	/* simple code is just the
588						 * value */
589			} else {
590				r.e = (uch) e[*p - s];	/* non-simple--look up
591							 * in lists */
592				r.v.n = d[*p++ - s];
593			}
594
595			/* fill code-like entries with r */
596			f = 1 << (k - w);
597			for (j = i >> w; j < z; j += f)
598				q[j] = r;
599
600			/* backwards increment the k-bit code i */
601			for (j = 1 << (k - 1); i & j; j >>= 1)
602				i ^= j;
603			i ^= j;
604
605			/* backup over finished tables */
606			while ((i & ((1 << w) - 1)) != x[h])
607				w -= l[--h];	/* don't need to update q */
608		}
609	}
610
611	/* return actual size of base table */
612	*m = l[0];
613
614	/* Return true (1) if we were given an incomplete table */
615	return y != 0 && g != 1;
616}
617
618static int
619huft_free(glbl, t)
620	struct inflate *glbl;
621	struct huft    *t;	/* table to free */
622/* Free the malloc'ed tables built by huft_build(), which makes a linked
623   list of the tables it made, with the links in a dummy first entry of
624   each table. */
625{
626	register struct huft *p, *q;
627
628	/* Go through linked list, freeing from the malloced (t[-1]) address. */
629	p = t;
630	while (p != (struct huft *) NULL) {
631		q = (--p)->v.t;
632		free(p, M_GZIP);
633		p = q;
634	}
635	return 0;
636}
637
638/* inflate (decompress) the codes in a deflated (compressed) block.
639   Return an error code or zero if it all goes ok. */
640static int
641inflate_codes(glbl, tl, td, bl, bd)
642	struct inflate *glbl;
643	struct huft    *tl, *td;/* literal/length and distance decoder tables */
644	int             bl, bd;	/* number of bits decoded by tl[] and td[] */
645{
646	register unsigned e;	/* table entry flag/number of extra bits */
647	unsigned        n, d;	/* length and index for copy */
648	unsigned        w;	/* current window position */
649	struct huft    *t;	/* pointer to table entry */
650	unsigned        ml, md;	/* masks for bl and bd bits */
651	register ulg    b;	/* bit buffer */
652	register unsigned k;	/* number of bits in bit buffer */
653
654	/* make local copies of globals */
655	b = glbl->gz_bb;			/* initialize bit buffer */
656	k = glbl->gz_bk;
657	w = glbl->gz_wp;	/* initialize window position */
658
659	/* inflate the coded data */
660	ml = mask[bl];		/* precompute masks for speed */
661	md = mask[bd];
662	while (1) {		/* do until end of block */
663		NEEDBITS(glbl, (unsigned) bl)
664			if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
665			do {
666				if (e == 99)
667					return 1;
668				DUMPBITS(t->b)
669					e -= 16;
670				NEEDBITS(glbl, e)
671			} while ((e = (t = t->v.t + ((unsigned) b & mask[e]))->e) > 16);
672		DUMPBITS(t->b)
673			if (e == 16) {	/* then it's a literal */
674			glbl->gz_slide[w++] = (uch) t->v.n;
675			if (w == GZ_WSIZE) {
676				FLUSH(glbl, w);
677				w = 0;
678			}
679		} else {	/* it's an EOB or a length */
680			/* exit if end of block */
681			if (e == 15)
682				break;
683
684			/* get length of block to copy */
685			NEEDBITS(glbl, e)
686				n = t->v.n + ((unsigned) b & mask[e]);
687			DUMPBITS(e);
688
689			/* decode distance of block to copy */
690			NEEDBITS(glbl, (unsigned) bd)
691				if ((e = (t = td + ((unsigned) b & md))->e) > 16)
692				do {
693					if (e == 99)
694						return 1;
695					DUMPBITS(t->b)
696						e -= 16;
697					NEEDBITS(glbl, e)
698				} while ((e = (t = t->v.t + ((unsigned) b & mask[e]))->e) > 16);
699			DUMPBITS(t->b)
700				NEEDBITS(glbl, e)
701				d = w - t->v.n - ((unsigned) b & mask[e]);
702			DUMPBITS(e)
703			/* do the copy */
704				do {
705				n -= (e = (e = GZ_WSIZE - ((d &= GZ_WSIZE - 1) > w ? d : w)) > n ? n : e);
706#ifndef NOMEMCPY
707				if (w - d >= e) {	/* (this test assumes
708							 * unsigned comparison) */
709					memcpy(glbl->gz_slide + w, glbl->gz_slide + d, e);
710					w += e;
711					d += e;
712				} else	/* do it slow to avoid memcpy()
713					 * overlap */
714#endif				/* !NOMEMCPY */
715					do {
716						glbl->gz_slide[w++] = glbl->gz_slide[d++];
717					} while (--e);
718				if (w == GZ_WSIZE) {
719					FLUSH(glbl, w);
720					w = 0;
721				}
722			} while (n);
723		}
724	}
725
726	/* restore the globals from the locals */
727	glbl->gz_wp = w;	/* restore global window pointer */
728	glbl->gz_bb = b;			/* restore global bit buffer */
729	glbl->gz_bk = k;
730
731	/* done */
732	return 0;
733}
734
735/* "decompress" an inflated type 0 (stored) block. */
736static int
737inflate_stored(glbl)
738	struct inflate *glbl;
739{
740	unsigned        n;	/* number of bytes in block */
741	unsigned        w;	/* current window position */
742	register ulg    b;	/* bit buffer */
743	register unsigned k;	/* number of bits in bit buffer */
744
745	/* make local copies of globals */
746	b = glbl->gz_bb;			/* initialize bit buffer */
747	k = glbl->gz_bk;
748	w = glbl->gz_wp;	/* initialize window position */
749
750	/* go to byte boundary */
751	n = k & 7;
752	DUMPBITS(n);
753
754	/* get the length and its complement */
755	NEEDBITS(glbl, 16)
756		n = ((unsigned) b & 0xffff);
757	DUMPBITS(16)
758		NEEDBITS(glbl, 16)
759		if (n != (unsigned) ((~b) & 0xffff))
760		return 1;	/* error in compressed data */
761	DUMPBITS(16)
762	/* read and output the compressed data */
763		while (n--) {
764		NEEDBITS(glbl, 8)
765			glbl->gz_slide[w++] = (uch) b;
766		if (w == GZ_WSIZE) {
767			FLUSH(glbl, w);
768			w = 0;
769		}
770		DUMPBITS(8)
771	}
772
773	/* restore the globals from the locals */
774	glbl->gz_wp = w;	/* restore global window pointer */
775	glbl->gz_bb = b;			/* restore global bit buffer */
776	glbl->gz_bk = k;
777	return 0;
778}
779
780/* decompress an inflated type 1 (fixed Huffman codes) block.  We should
781   either replace this with a custom decoder, or at least precompute the
782   Huffman tables. */
783static int
784inflate_fixed(glbl)
785	struct inflate *glbl;
786{
787	/* if first time, set up tables for fixed blocks */
788	if (glbl->gz_fixed_tl == (struct huft *) NULL) {
789		int             i;	/* temporary variable */
790		static unsigned l[288];	/* length list for huft_build */
791
792		/* literal table */
793		for (i = 0; i < 144; i++)
794			l[i] = 8;
795		for (; i < 256; i++)
796			l[i] = 9;
797		for (; i < 280; i++)
798			l[i] = 7;
799		for (; i < 288; i++)	/* make a complete, but wrong code
800					 * set */
801			l[i] = 8;
802		glbl->gz_fixed_bl = 7;
803		if ((i = huft_build(glbl, l, 288, 257, cplens, cplext,
804			    &glbl->gz_fixed_tl, &glbl->gz_fixed_bl)) != 0) {
805			glbl->gz_fixed_tl = (struct huft *) NULL;
806			return i;
807		}
808		/* distance table */
809		for (i = 0; i < 30; i++)	/* make an incomplete code
810						 * set */
811			l[i] = 5;
812		glbl->gz_fixed_bd = 5;
813		if ((i = huft_build(glbl, l, 30, 0, cpdist, cpdext,
814			     &glbl->gz_fixed_td, &glbl->gz_fixed_bd)) > 1) {
815			huft_free(glbl, glbl->gz_fixed_tl);
816			glbl->gz_fixed_tl = (struct huft *) NULL;
817			return i;
818		}
819	}
820	/* decompress until an end-of-block code */
821	return inflate_codes(glbl, glbl->gz_fixed_tl, glbl->gz_fixed_td, glbl->gz_fixed_bl, glbl->gz_fixed_bd) != 0;
822}
823
824/* decompress an inflated type 2 (dynamic Huffman codes) block. */
825static int
826inflate_dynamic(glbl)
827	struct inflate *glbl;
828{
829	int             i;	/* temporary variables */
830	unsigned        j;
831	unsigned        l;	/* last length */
832	unsigned        m;	/* mask for bit lengths table */
833	unsigned        n;	/* number of lengths to get */
834	struct huft    *tl;	/* literal/length code table */
835	struct huft    *td;	/* distance code table */
836	int             bl;	/* lookup bits for tl */
837	int             bd;	/* lookup bits for td */
838	unsigned        nb;	/* number of bit length codes */
839	unsigned        nl;	/* number of literal/length codes */
840	unsigned        nd;	/* number of distance codes */
841#ifdef PKZIP_BUG_WORKAROUND
842	unsigned        ll[288 + 32];	/* literal/length and distance code
843					 * lengths */
844#else
845	unsigned        ll[286 + 30];	/* literal/length and distance code
846					 * lengths */
847#endif
848	register ulg    b;	/* bit buffer */
849	register unsigned k;	/* number of bits in bit buffer */
850
851	/* make local bit buffer */
852	b = glbl->gz_bb;
853	k = glbl->gz_bk;
854
855	/* read in table lengths */
856	NEEDBITS(glbl, 5)
857		nl = 257 + ((unsigned) b & 0x1f);	/* number of
858							 * literal/length codes */
859	DUMPBITS(5)
860		NEEDBITS(glbl, 5)
861		nd = 1 + ((unsigned) b & 0x1f);	/* number of distance codes */
862	DUMPBITS(5)
863		NEEDBITS(glbl, 4)
864		nb = 4 + ((unsigned) b & 0xf);	/* number of bit length codes */
865	DUMPBITS(4)
866#ifdef PKZIP_BUG_WORKAROUND
867		if (nl > 288 || nd > 32)
868#else
869		if (nl > 286 || nd > 30)
870#endif
871		return 1;	/* bad lengths */
872	/* read in bit-length-code lengths */
873	for (j = 0; j < nb; j++) {
874		NEEDBITS(glbl, 3)
875			ll[border[j]] = (unsigned) b & 7;
876		DUMPBITS(3)
877	}
878	for (; j < 19; j++)
879		ll[border[j]] = 0;
880
881	/* build decoding table for trees--single level, 7 bit lookup */
882	bl = 7;
883	if ((i = huft_build(glbl, ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
884		if (i == 1)
885			huft_free(glbl, tl);
886		return i;	/* incomplete code set */
887	}
888	/* read in literal and distance code lengths */
889	n = nl + nd;
890	m = mask[bl];
891	i = l = 0;
892	while ((unsigned) i < n) {
893		NEEDBITS(glbl, (unsigned) bl)
894			j = (td = tl + ((unsigned) b & m))->b;
895		DUMPBITS(j)
896			j = td->v.n;
897		if (j < 16)	/* length of code in bits (0..15) */
898			ll[i++] = l = j;	/* save last length in l */
899		else if (j == 16) {	/* repeat last length 3 to 6 times */
900			NEEDBITS(glbl, 2)
901				j = 3 + ((unsigned) b & 3);
902			DUMPBITS(2)
903				if ((unsigned) i + j > n)
904				return 1;
905			while (j--)
906				ll[i++] = l;
907		} else if (j == 17) {	/* 3 to 10 zero length codes */
908			NEEDBITS(glbl, 3)
909				j = 3 + ((unsigned) b & 7);
910			DUMPBITS(3)
911				if ((unsigned) i + j > n)
912				return 1;
913			while (j--)
914				ll[i++] = 0;
915			l = 0;
916		} else {	/* j == 18: 11 to 138 zero length codes */
917			NEEDBITS(glbl, 7)
918				j = 11 + ((unsigned) b & 0x7f);
919			DUMPBITS(7)
920				if ((unsigned) i + j > n)
921				return 1;
922			while (j--)
923				ll[i++] = 0;
924			l = 0;
925		}
926	}
927
928	/* free decoding table for trees */
929	huft_free(glbl, tl);
930
931	/* restore the global bit buffer */
932	glbl->gz_bb = b;
933	glbl->gz_bk = k;
934
935	/* build the decoding tables for literal/length and distance codes */
936	bl = lbits;
937	i = huft_build(glbl, ll, nl, 257, cplens, cplext, &tl, &bl);
938	if (i != 0) {
939		if (i == 1 && !qflag) {
940			FPRINTF("(incomplete l-tree)  ");
941			huft_free(glbl, tl);
942		}
943		return i;	/* incomplete code set */
944	}
945	bd = dbits;
946	i = huft_build(glbl, ll + nl, nd, 0, cpdist, cpdext, &td, &bd);
947	if (i != 0) {
948		if (i == 1 && !qflag) {
949			FPRINTF("(incomplete d-tree)  ");
950#ifdef PKZIP_BUG_WORKAROUND
951			i = 0;
952		}
953#else
954			huft_free(glbl, td);
955		}
956		huft_free(glbl, tl);
957		return i;	/* incomplete code set */
958#endif
959	}
960	/* decompress until an end-of-block code */
961	if (inflate_codes(glbl, tl, td, bl, bd))
962		return 1;
963
964	/* free the decoding tables, return */
965	huft_free(glbl, tl);
966	huft_free(glbl, td);
967	return 0;
968}
969
970/* decompress an inflated block */
971static int
972inflate_block(glbl, e)
973	struct inflate *glbl;
974	int            *e;	/* last block flag */
975{
976	unsigned        t;	/* block type */
977	register ulg    b;	/* bit buffer */
978	register unsigned k;	/* number of bits in bit buffer */
979
980	/* make local bit buffer */
981	b = glbl->gz_bb;
982	k = glbl->gz_bk;
983
984	/* read in last block bit */
985	NEEDBITS(glbl, 1)
986		* e = (int) b & 1;
987	DUMPBITS(1)
988	/* read in block type */
989		NEEDBITS(glbl, 2)
990		t = (unsigned) b & 3;
991	DUMPBITS(2)
992	/* restore the global bit buffer */
993		glbl->gz_bb = b;
994	glbl->gz_bk = k;
995
996	/* inflate that block type */
997	if (t == 2)
998		return inflate_dynamic(glbl);
999	if (t == 0)
1000		return inflate_stored(glbl);
1001	if (t == 1)
1002		return inflate_fixed(glbl);
1003	/* bad block type */
1004	return 2;
1005}
1006
1007
1008
1009/* decompress an inflated entry */
1010static int
1011xinflate(glbl)
1012	struct inflate *glbl;
1013{
1014	int             e;	/* last block flag */
1015	int             r;	/* result code */
1016	unsigned        h;	/* maximum struct huft's malloc'ed */
1017
1018	glbl->gz_fixed_tl = (struct huft *) NULL;
1019
1020	/* initialize window, bit buffer */
1021	glbl->gz_wp = 0;
1022	glbl->gz_bk = 0;
1023	glbl->gz_bb = 0;
1024
1025	/* decompress until the last block */
1026	h = 0;
1027	do {
1028		glbl->gz_hufts = 0;
1029		if ((r = inflate_block(glbl, &e)) != 0)
1030			return r;
1031		if (glbl->gz_hufts > h)
1032			h = glbl->gz_hufts;
1033	} while (!e);
1034
1035	/* flush out slide */
1036	FLUSH(glbl, glbl->gz_wp);
1037
1038	/* return success */
1039	return 0;
1040}
1041
1042/* Nobody uses this - why not? */
1043int
1044inflate(glbl)
1045	struct inflate *glbl;
1046{
1047	int             i;
1048#ifdef _KERNEL
1049	u_char		*p = NULL;
1050
1051	if (!glbl->gz_slide)
1052		p = glbl->gz_slide = malloc(GZ_WSIZE, M_GZIP, M_WAITOK);
1053#endif
1054	if (!glbl->gz_slide)
1055#ifdef _KERNEL
1056		return(ENOMEM);
1057#else
1058		return 3; /* kzip expects 3 */
1059#endif
1060	i = xinflate(glbl);
1061
1062	if (glbl->gz_fixed_td != (struct huft *) NULL) {
1063		huft_free(glbl, glbl->gz_fixed_td);
1064		glbl->gz_fixed_td = (struct huft *) NULL;
1065	}
1066	if (glbl->gz_fixed_tl != (struct huft *) NULL) {
1067		huft_free(glbl, glbl->gz_fixed_tl);
1068		glbl->gz_fixed_tl = (struct huft *) NULL;
1069	}
1070#ifdef _KERNEL
1071	if (p == glbl->gz_slide) {
1072		free(glbl->gz_slide, M_GZIP);
1073		glbl->gz_slide = NULL;
1074	}
1075#endif
1076	return i;
1077}
1078/* ----------------------- END INFLATE.C */
1079