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