1 /*-
2 * Most parts of this file are not covered by:
3 *
4 * SPDX-License-Identifier: Beerware
5 * ----------------------------------------------------------------------------
6 * "THE BEER-WARE LICENSE" (Revision 42):
7 * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you
8 * can do whatever you want with this stuff. If we meet some day, and you think
9 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
10 * ----------------------------------------------------------------------------
11 */
12
13 #include <sys/cdefs.h>
14 __FBSDID("$FreeBSD: releng/12.0/sys/kern/subr_inflate.c 336250 2018-07-13 17:41:28Z imp $");
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 printf
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 malloc(x, y, z) kzipmalloc((x))
57 #define free(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. Similarly, 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 beginning 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 * Arguments:
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 */
426 static int
427 huft_build(struct inflate *glbl, unsigned *b, unsigned n, unsigned s,
428 const ush *d, const ush *e, struct huft **t, int *m)
429 {
430 unsigned a; /* counter for codes of length k */
431 unsigned c[BMAX + 1]; /* bit length count table */
432 unsigned el; /* length of EOB code (value 256) */
433 unsigned f; /* i repeats in table every f entries */
434 int g; /* maximum code length */
435 int h; /* table level */
436 unsigned i; /* counter, current code */
437 unsigned j; /* counter */
438 int k; /* number of bits in current code */
439 int lx[BMAX + 1]; /* memory for l[-1..BMAX-1] */
440 int *l = lx + 1; /* stack of bits per table */
441 unsigned *p; /* pointer into c[], b[], or v[] */
442 struct huft *q; /* points to current table */
443 struct huft r; /* table entry for structure assignment */
444 struct huft *u[BMAX];/* table stack */
445 unsigned v[N_MAX]; /* values in order of bit length */
446 int w; /* bits before this table == (l * h) */
447 unsigned x[BMAX + 1]; /* bit offsets, then code stack */
448 unsigned *xp; /* pointer into x */
449 int y; /* number of dummy codes added */
450 unsigned z; /* number of entries in current table */
451
452 /* Generate counts for each bit length */
453 el = n > 256 ? b[256] : BMAX; /* set length of EOB code, if any */
454 #ifdef _KERNEL
455 memzero((char *) c, sizeof(c));
456 #else
457 for (i = 0; i < BMAX+1; i++)
458 c [i] = 0;
459 #endif
460 p = b;
461 i = n;
462 do {
463 c[*p]++;
464 p++; /* assume all entries <= BMAX */
465 } while (--i);
466 if (c[0] == n) { /* null input--all zero length codes */
467 *t = (struct huft *) NULL;
468 *m = 0;
469 return 0;
470 }
471 /* Find minimum and maximum length, bound *m by those */
472 for (j = 1; j <= BMAX; j++)
473 if (c[j])
474 break;
475 k = j; /* minimum code length */
476 if ((unsigned) *m < j)
477 *m = j;
478 for (i = BMAX; i; i--)
479 if (c[i])
480 break;
481 g = i; /* maximum code length */
482 if ((unsigned) *m > i)
483 *m = i;
484
485 /* Adjust last length count to fill out codes, if needed */
486 for (y = 1 << j; j < i; j++, y <<= 1)
487 if ((y -= c[j]) < 0)
488 return 2; /* bad input: more codes than bits */
489 if ((y -= c[i]) < 0)
490 return 2;
491 c[i] += y;
492
493 /* Generate starting offsets into the value table for each length */
494 x[1] = j = 0;
495 p = c + 1;
496 xp = x + 2;
497 while (--i) { /* note that i == g from above */
498 *xp++ = (j += *p++);
499 }
500
501 /* Make a table of values in order of bit lengths */
502 p = b;
503 i = 0;
504 do {
505 if ((j = *p++) != 0)
506 v[x[j]++] = i;
507 } while (++i < n);
508
509 /* Generate the Huffman codes and for each, make the table entries */
510 x[0] = i = 0; /* first Huffman code is zero */
511 p = v; /* grab values in bit order */
512 h = -1; /* no tables yet--level -1 */
513 w = l[-1] = 0; /* no bits decoded yet */
514 u[0] = (struct huft *) NULL; /* just to keep compilers happy */
515 q = (struct huft *) NULL; /* ditto */
516 z = 0; /* ditto */
517
518 /* go through the bit lengths (k already is bits in shortest code) */
519 for (; k <= g; k++) {
520 a = c[k];
521 while (a--) {
522 /*
523 * here i is the Huffman code of length k bits for
524 * value *p
525 */
526 /* make tables up to required level */
527 while (k > w + l[h]) {
528 w += l[h++]; /* add bits already decoded */
529
530 /*
531 * compute minimum size table less than or
532 * equal to *m bits
533 */
534 z = (z = g - w) > (unsigned) *m ? *m : z; /* upper limit */
535 if ((f = 1 << (j = k - w)) > a + 1) { /* try a k-w bit table *//* t
536 * oo few codes for k-w
537 * bit table */
538 f -= a + 1; /* deduct codes from
539 * patterns left */
540 xp = c + k;
541 while (++j < z) { /* try smaller tables up
542 * to z bits */
543 if ((f <<= 1) <= *++xp)
544 break; /* enough codes to use
545 * up j bits */
546 f -= *xp; /* else deduct codes
547 * from patterns */
548 }
549 }
550 if ((unsigned) w + j > el && (unsigned) w < el)
551 j = el - w; /* make EOB code end at
552 * table */
553 z = 1 << j; /* table entries for j-bit
554 * table */
555 l[h] = j; /* set table size in stack */
556
557 /* allocate and link in new table */
558 if ((q = (struct huft *) malloc((z + 1) * sizeof(struct huft), M_GZIP, M_WAITOK)) ==
559 (struct huft *) NULL) {
560 if (h)
561 huft_free(glbl, u[0]);
562 return 3; /* not enough memory */
563 }
564 glbl->gz_hufts += z + 1; /* track memory usage */
565 *t = q + 1; /* link to list for
566 * huft_free() */
567 *(t = &(q->v.t)) = (struct huft *) NULL;
568 u[h] = ++q; /* table starts after link */
569
570 /* connect to last table, if there is one */
571 if (h) {
572 x[h] = i; /* save pattern for
573 * backing up */
574 r.b = (uch) l[h - 1]; /* bits to dump before
575 * this table */
576 r.e = (uch) (16 + j); /* bits in this table */
577 r.v.t = q; /* pointer to this table */
578 j = (i & ((1 << w) - 1)) >> (w - l[h - 1]);
579 u[h - 1][j] = r; /* connect to last table */
580 }
581 }
582
583 /* set up table entry in r */
584 r.b = (uch) (k - w);
585 if (p >= v + n)
586 r.e = 99; /* out of values--invalid
587 * code */
588 else if (*p < s) {
589 r.e = (uch) (*p < 256 ? 16 : 15); /* 256 is end-of-block
590 * code */
591 r.v.n = *p++; /* simple code is just the
592 * value */
593 } else {
594 r.e = (uch) e[*p - s]; /* non-simple--look up
595 * in lists */
596 r.v.n = d[*p++ - s];
597 }
598
599 /* fill code-like entries with r */
600 f = 1 << (k - w);
601 for (j = i >> w; j < z; j += f)
602 q[j] = r;
603
604 /* backwards increment the k-bit code i */
605 for (j = 1 << (k - 1); i & j; j >>= 1)
606 i ^= j;
607 i ^= j;
608
609 /* backup over finished tables */
610 while ((i & ((1 << w) - 1)) != x[h])
611 w -= l[--h]; /* don't need to update q */
612 }
613 }
614
615 /* return actual size of base table */
616 *m = l[0];
617
618 /* Return true (1) if we were given an incomplete table */
619 return y != 0 && g != 1;
620 }
621
622 /*
623 * Arguments:
624 * t table to free
625 */
626 static int
627 huft_free(struct inflate *glbl, struct huft *t)
628 /* Free the malloc'ed tables built by huft_build(), which makes a linked
629 list of the tables it made, with the links in a dummy first entry of
630 each table. */
631 {
632 struct huft *p, *q;
633
634 /* Go through linked list, freeing from the malloced (t[-1]) address. */
635 p = t;
636 while (p != (struct huft *) NULL) {
637 q = (--p)->v.t;
638 free(p, M_GZIP);
639 p = q;
640 }
641 return 0;
642 }
643
644 /* inflate (decompress) the codes in a deflated (compressed) block.
645 Return an error code or zero if it all goes ok. */
646 /*
647 * Arguments:
648 * tl, td literal/length and distance decoder tables
649 * bl, bd number of bits decoded by tl[] and td[]
650 */
651 static int
652 inflate_codes(struct inflate *glbl, struct huft *tl, struct huft*td, int bl,
653 int bd)
654 {
655 unsigned e; /* table entry flag/number of extra bits */
656 unsigned n, d; /* length and index for copy */
657 unsigned w; /* current window position */
658 struct huft *t; /* pointer to table entry */
659 unsigned ml, md; /* masks for bl and bd bits */
660 ulg b; /* bit buffer */
661 unsigned k; /* number of bits in bit buffer */
662
663 /* make local copies of globals */
664 b = glbl->gz_bb; /* initialize bit buffer */
665 k = glbl->gz_bk;
666 w = glbl->gz_wp; /* initialize window position */
667
668 /* inflate the coded data */
669 ml = mask[bl]; /* precompute masks for speed */
670 md = mask[bd];
671 while (1) { /* do until end of block */
672 NEEDBITS(glbl, (unsigned) bl)
673 if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
674 do {
675 if (e == 99)
676 return 1;
677 DUMPBITS(t->b)
678 e -= 16;
679 NEEDBITS(glbl, e)
680 } while ((e = (t = t->v.t + ((unsigned) b & mask[e]))->e) > 16);
681 DUMPBITS(t->b)
682 if (e == 16) { /* then it's a literal */
683 glbl->gz_slide[w++] = (uch) t->v.n;
684 if (w == GZ_WSIZE) {
685 FLUSH(glbl, w);
686 w = 0;
687 }
688 } else { /* it's an EOB or a length */
689 /* exit if end of block */
690 if (e == 15)
691 break;
692
693 /* get length of block to copy */
694 NEEDBITS(glbl, e)
695 n = t->v.n + ((unsigned) b & mask[e]);
696 DUMPBITS(e);
697
698 /* decode distance of block to copy */
699 NEEDBITS(glbl, (unsigned) bd)
700 if ((e = (t = td + ((unsigned) b & md))->e) > 16)
701 do {
702 if (e == 99)
703 return 1;
704 DUMPBITS(t->b)
705 e -= 16;
706 NEEDBITS(glbl, e)
707 } while ((e = (t = t->v.t + ((unsigned) b & mask[e]))->e) > 16);
708 DUMPBITS(t->b)
709 NEEDBITS(glbl, e)
710 d = w - t->v.n - ((unsigned) b & mask[e]);
711 DUMPBITS(e)
712 /* do the copy */
713 do {
714 n -= (e = (e = GZ_WSIZE - ((d &= GZ_WSIZE - 1) > w ? d : w)) > n ? n : e);
715 #ifndef NOMEMCPY
716 if (w - d >= e) { /* (this test assumes
717 * unsigned comparison) */
718 memcpy(glbl->gz_slide + w, glbl->gz_slide + d, e);
719 w += e;
720 d += e;
721 } else /* do it slow to avoid memcpy()
722 * overlap */
723 #endif /* !NOMEMCPY */
724 do {
725 glbl->gz_slide[w++] = glbl->gz_slide[d++];
726 } while (--e);
727 if (w == GZ_WSIZE) {
728 FLUSH(glbl, w);
729 w = 0;
730 }
731 } while (n);
732 }
733 }
734
735 /* restore the globals from the locals */
736 glbl->gz_wp = w; /* restore global window pointer */
737 glbl->gz_bb = b; /* restore global bit buffer */
738 glbl->gz_bk = k;
739
740 /* done */
741 return 0;
742 }
743
744 /* "decompress" an inflated type 0 (stored) block. */
745 static int
746 inflate_stored(struct inflate *glbl)
747 {
748 unsigned n; /* number of bytes in block */
749 unsigned w; /* current window position */
750 ulg b; /* bit buffer */
751 unsigned k; /* number of bits in bit buffer */
752
753 /* make local copies of globals */
754 b = glbl->gz_bb; /* initialize bit buffer */
755 k = glbl->gz_bk;
756 w = glbl->gz_wp; /* initialize window position */
757
758 /* go to byte boundary */
759 n = k & 7;
760 DUMPBITS(n);
761
762 /* get the length and its complement */
763 NEEDBITS(glbl, 16)
764 n = ((unsigned) b & 0xffff);
765 DUMPBITS(16)
766 NEEDBITS(glbl, 16)
767 if (n != (unsigned) ((~b) & 0xffff))
768 return 1; /* error in compressed data */
769 DUMPBITS(16)
770 /* read and output the compressed data */
771 while (n--) {
772 NEEDBITS(glbl, 8)
773 glbl->gz_slide[w++] = (uch) b;
774 if (w == GZ_WSIZE) {
775 FLUSH(glbl, w);
776 w = 0;
777 }
778 DUMPBITS(8)
779 }
780
781 /* restore the globals from the locals */
782 glbl->gz_wp = w; /* restore global window pointer */
783 glbl->gz_bb = b; /* restore global bit buffer */
784 glbl->gz_bk = k;
785 return 0;
786 }
787
788 /* decompress an inflated type 1 (fixed Huffman codes) block. We should
789 either replace this with a custom decoder, or at least precompute the
790 Huffman tables. */
791 static int
792 inflate_fixed(struct inflate *glbl)
793 {
794 /* if first time, set up tables for fixed blocks */
795 if (glbl->gz_fixed_tl == (struct huft *) NULL) {
796 int i; /* temporary variable */
797 static unsigned l[288]; /* length list for huft_build */
798
799 /* literal table */
800 for (i = 0; i < 144; i++)
801 l[i] = 8;
802 for (; i < 256; i++)
803 l[i] = 9;
804 for (; i < 280; i++)
805 l[i] = 7;
806 for (; i < 288; i++) /* make a complete, but wrong code
807 * set */
808 l[i] = 8;
809 glbl->gz_fixed_bl = 7;
810 if ((i = huft_build(glbl, l, 288, 257, cplens, cplext,
811 &glbl->gz_fixed_tl, &glbl->gz_fixed_bl)) != 0) {
812 glbl->gz_fixed_tl = (struct huft *) NULL;
813 return i;
814 }
815 /* distance table */
816 for (i = 0; i < 30; i++) /* make an incomplete code
817 * set */
818 l[i] = 5;
819 glbl->gz_fixed_bd = 5;
820 if ((i = huft_build(glbl, l, 30, 0, cpdist, cpdext,
821 &glbl->gz_fixed_td, &glbl->gz_fixed_bd)) > 1) {
822 huft_free(glbl, glbl->gz_fixed_tl);
823 glbl->gz_fixed_tl = (struct huft *) NULL;
824 return i;
825 }
826 }
827 /* decompress until an end-of-block code */
828 return inflate_codes(glbl, glbl->gz_fixed_tl, glbl->gz_fixed_td, glbl->gz_fixed_bl, glbl->gz_fixed_bd) != 0;
829 }
830
831 /* decompress an inflated type 2 (dynamic Huffman codes) block. */
832 static int
833 inflate_dynamic(struct inflate *glbl)
834 {
835 int i; /* temporary variables */
836 unsigned j;
837 unsigned l; /* last length */
838 unsigned m; /* mask for bit lengths table */
839 unsigned n; /* number of lengths to get */
840 struct huft *tl; /* literal/length code table */
841 struct huft *td; /* distance code table */
842 int bl; /* lookup bits for tl */
843 int bd; /* lookup bits for td */
844 unsigned nb; /* number of bit length codes */
845 unsigned nl; /* number of literal/length codes */
846 unsigned nd; /* number of distance codes */
847 #ifdef PKZIP_BUG_WORKAROUND
848 unsigned ll[288 + 32]; /* literal/length and distance code
849 * lengths */
850 #else
851 unsigned ll[286 + 30]; /* literal/length and distance code
852 * lengths */
853 #endif
854 ulg b; /* bit buffer */
855 unsigned k; /* number of bits in bit buffer */
856
857 /* make local bit buffer */
858 b = glbl->gz_bb;
859 k = glbl->gz_bk;
860
861 /* read in table lengths */
862 NEEDBITS(glbl, 5)
863 nl = 257 + ((unsigned) b & 0x1f); /* number of
864 * literal/length codes */
865 DUMPBITS(5)
866 NEEDBITS(glbl, 5)
867 nd = 1 + ((unsigned) b & 0x1f); /* number of distance codes */
868 DUMPBITS(5)
869 NEEDBITS(glbl, 4)
870 nb = 4 + ((unsigned) b & 0xf); /* number of bit length codes */
871 DUMPBITS(4)
872 #ifdef PKZIP_BUG_WORKAROUND
873 if (nl > 288 || nd > 32)
874 #else
875 if (nl > 286 || nd > 30)
876 #endif
877 return 1; /* bad lengths */
878 /* read in bit-length-code lengths */
879 for (j = 0; j < nb; j++) {
880 NEEDBITS(glbl, 3)
881 ll[border[j]] = (unsigned) b & 7;
882 DUMPBITS(3)
883 }
884 for (; j < 19; j++)
885 ll[border[j]] = 0;
886
887 /* build decoding table for trees--single level, 7 bit lookup */
888 bl = 7;
889 if ((i = huft_build(glbl, ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
890 if (i == 1)
891 huft_free(glbl, tl);
892 return i; /* incomplete code set */
893 }
894 /* read in literal and distance code lengths */
895 n = nl + nd;
896 m = mask[bl];
897 i = l = 0;
898 while ((unsigned) i < n) {
899 NEEDBITS(glbl, (unsigned) bl)
900 j = (td = tl + ((unsigned) b & m))->b;
901 DUMPBITS(j)
902 j = td->v.n;
903 if (j < 16) /* length of code in bits (0..15) */
904 ll[i++] = l = j; /* save last length in l */
905 else if (j == 16) { /* repeat last length 3 to 6 times */
906 NEEDBITS(glbl, 2)
907 j = 3 + ((unsigned) b & 3);
908 DUMPBITS(2)
909 if ((unsigned) i + j > n)
910 return 1;
911 while (j--)
912 ll[i++] = l;
913 } else if (j == 17) { /* 3 to 10 zero length codes */
914 NEEDBITS(glbl, 3)
915 j = 3 + ((unsigned) b & 7);
916 DUMPBITS(3)
917 if ((unsigned) i + j > n)
918 return 1;
919 while (j--)
920 ll[i++] = 0;
921 l = 0;
922 } else { /* j == 18: 11 to 138 zero length codes */
923 NEEDBITS(glbl, 7)
924 j = 11 + ((unsigned) b & 0x7f);
925 DUMPBITS(7)
926 if ((unsigned) i + j > n)
927 return 1;
928 while (j--)
929 ll[i++] = 0;
930 l = 0;
931 }
932 }
933
934 /* free decoding table for trees */
935 huft_free(glbl, tl);
936
937 /* restore the global bit buffer */
938 glbl->gz_bb = b;
939 glbl->gz_bk = k;
940
941 /* build the decoding tables for literal/length and distance codes */
942 bl = lbits;
943 i = huft_build(glbl, ll, nl, 257, cplens, cplext, &tl, &bl);
944 if (i != 0) {
945 if (i == 1 && !qflag) {
946 FPRINTF("(incomplete l-tree) ");
947 huft_free(glbl, tl);
948 }
949 return i; /* incomplete code set */
950 }
951 bd = dbits;
952 i = huft_build(glbl, ll + nl, nd, 0, cpdist, cpdext, &td, &bd);
953 if (i != 0) {
954 if (i == 1 && !qflag) {
955 FPRINTF("(incomplete d-tree) ");
956 #ifdef PKZIP_BUG_WORKAROUND
957 i = 0;
958 }
959 #else
960 huft_free(glbl, td);
961 }
962 huft_free(glbl, tl);
963 return i; /* incomplete code set */
964 #endif
965 }
966 /* decompress until an end-of-block code */
967 if (inflate_codes(glbl, tl, td, bl, bd))
968 return 1;
969
970 /* free the decoding tables, return */
971 huft_free(glbl, tl);
972 huft_free(glbl, td);
973 return 0;
974 }
975
976 /* decompress an inflated block */
977 /*
978 * Arguments:
979 * e last block flag
980 */
981 static int
982 inflate_block(struct inflate *glbl, int *e)
983 {
984 unsigned t; /* block type */
985 ulg b; /* bit buffer */
986 unsigned k; /* number of bits in bit buffer */
987
988 /* make local bit buffer */
989 b = glbl->gz_bb;
990 k = glbl->gz_bk;
991
992 /* read in last block bit */
993 NEEDBITS(glbl, 1)
994 * e = (int) b & 1;
995 DUMPBITS(1)
996 /* read in block type */
997 NEEDBITS(glbl, 2)
998 t = (unsigned) b & 3;
999 DUMPBITS(2)
1000 /* restore the global bit buffer */
1001 glbl->gz_bb = b;
1002 glbl->gz_bk = k;
1003
1004 /* inflate that block type */
1005 if (t == 2)
1006 return inflate_dynamic(glbl);
1007 if (t == 0)
1008 return inflate_stored(glbl);
1009 if (t == 1)
1010 return inflate_fixed(glbl);
1011 /* bad block type */
1012 return 2;
1013 }
1014
1015
1016
1017 /* decompress an inflated entry */
1018 static int
1019 xinflate(struct inflate *glbl)
1020 {
1021 int e; /* last block flag */
1022 int r; /* result code */
1023 unsigned h; /* maximum struct huft's malloc'ed */
1024
1025 glbl->gz_fixed_tl = (struct huft *) NULL;
1026
1027 /* initialize window, bit buffer */
1028 glbl->gz_wp = 0;
1029 glbl->gz_bk = 0;
1030 glbl->gz_bb = 0;
1031
1032 /* decompress until the last block */
1033 h = 0;
1034 do {
1035 glbl->gz_hufts = 0;
1036 if ((r = inflate_block(glbl, &e)) != 0)
1037 return r;
1038 if (glbl->gz_hufts > h)
1039 h = glbl->gz_hufts;
1040 } while (!e);
1041
1042 /* flush out slide */
1043 FLUSH(glbl, glbl->gz_wp);
1044
1045 /* return success */
1046 return 0;
1047 }
1048
1049 /* Nobody uses this - why not? */
1050 int
1051 inflate(struct inflate *glbl)
1052 {
1053 int i;
1054 #ifdef _KERNEL
1055 u_char *p = NULL;
1056
1057 if (!glbl->gz_slide)
1058 p = glbl->gz_slide = malloc(GZ_WSIZE, M_GZIP, M_WAITOK);
1059 #endif
1060 if (!glbl->gz_slide)
1061 #ifdef _KERNEL
1062 return(ENOMEM);
1063 #else
1064 return 3; /* kzip expects 3 */
1065 #endif
1066 i = xinflate(glbl);
1067
1068 if (glbl->gz_fixed_td != (struct huft *) NULL) {
1069 huft_free(glbl, glbl->gz_fixed_td);
1070 glbl->gz_fixed_td = (struct huft *) NULL;
1071 }
1072 if (glbl->gz_fixed_tl != (struct huft *) NULL) {
1073 huft_free(glbl, glbl->gz_fixed_tl);
1074 glbl->gz_fixed_tl = (struct huft *) NULL;
1075 }
1076 #ifdef _KERNEL
1077 if (p == glbl->gz_slide) {
1078 free(glbl->gz_slide, M_GZIP);
1079 glbl->gz_slide = NULL;
1080 }
1081 #endif
1082 return i;
1083 }
1084 /* ----------------------- END INFLATE.C */
Cache object: cd2ec68f9c58d4e84cac227851203d27
|