2008-11-01 Robert Millan <rmh@aybabtu.com>
[grub2/phcoder.git] / io / gzio.c
blob0fada6cc5e2b5b7f3e0833b67b683902d03293a7
1 /* gzio.c - decompression support for gzip */
2 /*
3 * GRUB -- GRand Unified Bootloader
4 * Copyright (C) 1999,2005,2006,2007 Free Software Foundation, Inc.
6 * GRUB is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * GRUB is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
21 * Most of this file was originally the source file "inflate.c", written
22 * by Mark Adler. It has been very heavily modified. In particular, the
23 * original would run through the whole file at once, and this version can
24 * be stopped and restarted on any boundary during the decompression process.
26 * The license and header comments that file are included here.
29 /* inflate.c -- Not copyrighted 1992 by Mark Adler
30 version c10p1, 10 January 1993 */
32 /* You can do whatever you like with this source file, though I would
33 prefer that if you modify it and redistribute it that you include
34 comments to that effect with your name and the date. Thank you.
37 #include <grub/err.h>
38 #include <grub/types.h>
39 #include <grub/mm.h>
40 #include <grub/misc.h>
41 #include <grub/fs.h>
42 #include <grub/file.h>
43 #include <grub/gzio.h>
46 * Window Size
48 * This must be a power of two, and at least 32K for zip's deflate method
51 #define WSIZE 0x8000
54 #define INBUFSIZ 0x2000
56 /* The state stored in filesystem-specific data. */
57 struct grub_gzio
59 /* The underlying file object. */
60 grub_file_t file;
61 /* The offset at which the data starts in the underlying file. */
62 grub_off_t data_offset;
63 /* The type of current block. */
64 int block_type;
65 /* The length of current block. */
66 int block_len;
67 /* The flag of the last block. */
68 int last_block;
69 /* The flag of codes. */
70 int code_state;
71 /* The length of a copy. */
72 unsigned inflate_n;
73 /* The index of a copy. */
74 unsigned inflate_d;
75 /* The input buffer. */
76 grub_uint8_t inbuf[INBUFSIZ];
77 int inbuf_d;
78 /* The bit buffer. */
79 unsigned long bb;
80 /* The bits in the bit buffer. */
81 unsigned bk;
82 /* The sliding window in uncompressed data. */
83 grub_uint8_t slide[WSIZE];
84 /* Current position in the slide. */
85 unsigned wp;
86 /* The literal/length code table. */
87 struct huft *tl;
88 /* The distance code table. */
89 struct huft *td;
90 /* The lookup bits for the literal/length code table. */
91 int bl;
92 /* The lookup bits for the distance code table. */
93 int bd;
94 /* The original offset value. */
95 grub_off_t saved_offset;
97 typedef struct grub_gzio *grub_gzio_t;
99 /* Declare the filesystem structure for grub_gzio_open. */
100 static struct grub_fs grub_gzio_fs;
102 /* Function prototypes */
103 static void initialize_tables (grub_file_t file);
105 /* Eat variable-length header fields. */
106 static int
107 eat_field (grub_file_t file, int len)
109 char ch = 1;
110 int not_retval = 1;
114 if (len >= 0)
116 if (! (len--))
117 break;
119 else
121 if (! ch)
122 break;
125 while ((not_retval = grub_file_read (file, &ch, 1)) == 1);
127 return ! not_retval;
131 /* Little-Endian defines for the 2-byte magic numbers for gzip files. */
132 #define GZIP_MAGIC grub_le_to_cpu16 (0x8B1F)
133 #define OLD_GZIP_MAGIC grub_le_to_cpu16 (0x9E1F)
135 /* Compression methods (see algorithm.doc) */
136 #define STORED 0
137 #define COMPRESSED 1
138 #define PACKED 2
139 #define LZHED 3
140 /* methods 4 to 7 reserved */
141 #define DEFLATED 8
142 #define MAX_METHODS 9
144 /* gzip flag byte */
145 #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
146 #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
147 #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
148 #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
149 #define COMMENT 0x10 /* bit 4 set: file comment present */
150 #define ENCRYPTED 0x20 /* bit 5 set: file is encrypted */
151 #define RESERVED 0xC0 /* bit 6,7: reserved */
153 #define UNSUPPORTED_FLAGS (CONTINUATION | ENCRYPTED | RESERVED)
155 /* inflate block codes */
156 #define INFLATE_STORED 0
157 #define INFLATE_FIXED 1
158 #define INFLATE_DYNAMIC 2
160 typedef unsigned char uch;
161 typedef unsigned short ush;
162 typedef unsigned long ulg;
164 static int
165 test_header (grub_file_t file)
167 unsigned char buf[10] __attribute__ ((aligned));
168 grub_gzio_t gzio = file->data;
170 if (grub_file_tell (gzio->file) != 0)
171 grub_file_seek (gzio->file, 0);
174 * This checks if the file is gzipped. If a problem occurs here
175 * (other than a real error with the disk) then we don't think it
176 * is a compressed file, and simply mark it as such.
178 if (grub_file_read (gzio->file, (char *) buf, 10) != 10
179 || ((*((grub_uint16_t *) buf) != GZIP_MAGIC)
180 && (*((grub_uint16_t *) buf) != OLD_GZIP_MAGIC)))
182 grub_error (GRUB_ERR_BAD_FILE_TYPE, "no gzip magic found");
183 return 0;
187 * This does consistency checking on the header data. If a
188 * problem occurs from here on, then we have corrupt or otherwise
189 * bad data, and the error should be reported to the user.
191 if (buf[2] != DEFLATED
192 || (buf[3] & UNSUPPORTED_FLAGS)
193 || ((buf[3] & EXTRA_FIELD)
194 && (grub_file_read (gzio->file, (char *) buf, 2) != 2
195 || eat_field (gzio->file,
196 grub_le_to_cpu16 (*((grub_uint16_t *) buf)))))
197 || ((buf[3] & ORIG_NAME) && eat_field (gzio->file, -1))
198 || ((buf[3] & COMMENT) && eat_field (gzio->file, -1)))
200 grub_error (GRUB_ERR_BAD_GZIP_DATA, "unsupported gzip format");
201 return 0;
204 gzio->data_offset = grub_file_tell (gzio->file);
206 grub_file_seek (gzio->file, grub_file_size (gzio->file) - 8);
208 if (grub_file_read (gzio->file, (char *) buf, 8) != 8)
210 grub_error (GRUB_ERR_BAD_FILE_TYPE, "unsupported gzip format");
211 return 0;
214 /* FIXME: this does not handle files whose original size is over 4GB.
215 But how can we know the real original size? */
216 file->size = grub_le_to_cpu32 (*((grub_uint32_t *) (buf + 4)));
218 initialize_tables (file);
220 return 1;
224 /* Huffman code lookup table entry--this entry is four bytes for machines
225 that have 16-bit pointers (e.g. PC's in the small or medium model).
226 Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16
227 means that v is a literal, 16 < e < 32 means that v is a pointer to
228 the next table, which codes e - 16 bits, and lastly e == 99 indicates
229 an unused code. If a code with e == 99 is looked up, this implies an
230 error in the data. */
231 struct huft
233 uch e; /* number of extra bits or operation */
234 uch b; /* number of bits in this code or subcode */
235 union
237 ush n; /* literal, length base, or distance base */
238 struct huft *t; /* pointer to next level of table */
244 /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
245 stream to find repeated byte strings. This is implemented here as a
246 circular buffer. The index is updated simply by incrementing and then
247 and'ing with 0x7fff (32K-1). */
248 /* It is left to other modules to supply the 32K area. It is assumed
249 to be usable as if it were declared "uch slide[32768];" or as just
250 "uch *slide;" and then malloc'ed in the latter case. The definition
251 must be in unzip.h, included above. */
254 /* Tables for deflate from PKZIP's appnote.txt. */
255 static unsigned bitorder[] =
256 { /* Order of the bit length code lengths */
257 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
258 static ush cplens[] =
259 { /* Copy lengths for literal codes 257..285 */
260 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
261 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
262 /* note: see note #13 above about the 258 in this list. */
263 static ush cplext[] =
264 { /* Extra bits for literal codes 257..285 */
265 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
266 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
267 static ush cpdist[] =
268 { /* Copy offsets for distance codes 0..29 */
269 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
270 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
271 8193, 12289, 16385, 24577};
272 static ush cpdext[] =
273 { /* Extra bits for distance codes */
274 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
275 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
276 12, 12, 13, 13};
280 Huffman code decoding is performed using a multi-level table lookup.
281 The fastest way to decode is to simply build a lookup table whose
282 size is determined by the longest code. However, the time it takes
283 to build this table can also be a factor if the data being decoded
284 is not very long. The most common codes are necessarily the
285 shortest codes, so those codes dominate the decoding time, and hence
286 the speed. The idea is you can have a shorter table that decodes the
287 shorter, more probable codes, and then point to subsidiary tables for
288 the longer codes. The time it costs to decode the longer codes is
289 then traded against the time it takes to make longer tables.
291 This results of this trade are in the variables lbits and dbits
292 below. lbits is the number of bits the first level table for literal/
293 length codes can decode in one step, and dbits is the same thing for
294 the distance codes. Subsequent tables are also less than or equal to
295 those sizes. These values may be adjusted either when all of the
296 codes are shorter than that, in which case the longest code length in
297 bits is used, or when the shortest code is *longer* than the requested
298 table size, in which case the length of the shortest code in bits is
299 used.
301 There are two different values for the two tables, since they code a
302 different number of possibilities each. The literal/length table
303 codes 286 possible values, or in a flat code, a little over eight
304 bits. The distance table codes 30 possible values, or a little less
305 than five bits, flat. The optimum values for speed end up being
306 about one bit more than those, so lbits is 8+1 and dbits is 5+1.
307 The optimum values may differ though from machine to machine, and
308 possibly even between compilers. Your mileage may vary.
312 static int lbits = 9; /* bits in base literal/length lookup table */
313 static int dbits = 6; /* bits in base distance lookup table */
316 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
317 #define BMAX 16 /* maximum bit length of any code (16 for explode) */
318 #define N_MAX 288 /* maximum number of codes in any set */
321 /* Macros for inflate() bit peeking and grabbing.
322 The usage is:
324 NEEDBITS(j)
325 x = b & mask_bits[j];
326 DUMPBITS(j)
328 where NEEDBITS makes sure that b has at least j bits in it, and
329 DUMPBITS removes the bits from b. The macros use the variable k
330 for the number of bits in b. Normally, b and k are register
331 variables for speed, and are initialized at the beginning of a
332 routine that uses these macros from a global bit buffer and count.
334 If we assume that EOB will be the longest code, then we will never
335 ask for bits with NEEDBITS that are beyond the end of the stream.
336 So, NEEDBITS should not read any more bytes than are needed to
337 meet the request. Then no bytes need to be "returned" to the buffer
338 at the end of the last block.
340 However, this assumption is not true for fixed blocks--the EOB code
341 is 7 bits, but the other literal/length codes can be 8 or 9 bits.
342 (The EOB code is shorter than other codes because fixed blocks are
343 generally short. So, while a block always has an EOB, many other
344 literal/length codes have a significantly lower probability of
345 showing up at all.) However, by making the first table have a
346 lookup of seven bits, the EOB code will be found in that first
347 lookup, and so will not require that too many bits be pulled from
348 the stream.
351 static ush mask_bits[] =
353 0x0000,
354 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
355 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
358 #define NEEDBITS(n) do {while(k<(n)){b|=((ulg)get_byte(file))<<k;k+=8;}} while (0)
359 #define DUMPBITS(n) do {b>>=(n);k-=(n);} while (0)
361 static int
362 get_byte (grub_file_t file)
364 grub_gzio_t gzio = file->data;
366 if (grub_file_tell (gzio->file) == (grub_off_t) gzio->data_offset
367 || gzio->inbuf_d == INBUFSIZ)
369 gzio->inbuf_d = 0;
370 grub_file_read (gzio->file, (char *) gzio->inbuf, INBUFSIZ);
373 return gzio->inbuf[gzio->inbuf_d++];
376 /* more function prototypes */
377 static int huft_build (unsigned *, unsigned, unsigned, ush *, ush *,
378 struct huft **, int *);
379 static int huft_free (struct huft *);
380 static int inflate_codes_in_window (grub_file_t);
383 /* Given a list of code lengths and a maximum table size, make a set of
384 tables to decode that set of codes. Return zero on success, one if
385 the given code set is incomplete (the tables are still built in this
386 case), two if the input is invalid (all zero length codes or an
387 oversubscribed set of lengths), and three if not enough memory. */
389 static int
390 huft_build (unsigned *b, /* code lengths in bits (all assumed <= BMAX) */
391 unsigned n, /* number of codes (assumed <= N_MAX) */
392 unsigned s, /* number of simple-valued codes (0..s-1) */
393 ush * d, /* list of base values for non-simple codes */
394 ush * e, /* list of extra bits for non-simple codes */
395 struct huft **t, /* result: starting table */
396 int *m) /* maximum lookup bits, returns actual */
398 unsigned a; /* counter for codes of length k */
399 unsigned c[BMAX + 1]; /* bit length count table */
400 unsigned f; /* i repeats in table every f entries */
401 int g; /* maximum code length */
402 int h; /* table level */
403 register unsigned i; /* counter, current code */
404 register unsigned j; /* counter */
405 register int k; /* number of bits in current code */
406 int l; /* bits per table (returned in m) */
407 register unsigned *p; /* pointer into c[], b[], or v[] */
408 register struct huft *q; /* points to current table */
409 struct huft r; /* table entry for structure assignment */
410 struct huft *u[BMAX]; /* table stack */
411 unsigned v[N_MAX]; /* values in order of bit length */
412 register int w; /* bits before this table == (l * h) */
413 unsigned x[BMAX + 1]; /* bit offsets, then code stack */
414 unsigned *xp; /* pointer into x */
415 int y; /* number of dummy codes added */
416 unsigned z; /* number of entries in current table */
418 /* Generate counts for each bit length */
419 grub_memset ((char *) c, 0, sizeof (c));
420 p = b;
421 i = n;
424 c[*p]++; /* assume all entries <= BMAX */
425 p++; /* Can't combine with above line (Solaris bug) */
427 while (--i);
428 if (c[0] == n) /* null input--all zero length codes */
430 *t = (struct huft *) NULL;
431 *m = 0;
432 return 0;
435 /* Find minimum and maximum length, bound *m by those */
436 l = *m;
437 for (j = 1; j <= BMAX; j++)
438 if (c[j])
439 break;
440 k = j; /* minimum code length */
441 if ((unsigned) l < j)
442 l = j;
443 for (i = BMAX; i; i--)
444 if (c[i])
445 break;
446 g = i; /* maximum code length */
447 if ((unsigned) l > i)
448 l = i;
449 *m = l;
451 /* Adjust last length count to fill out codes, if needed */
452 for (y = 1 << j; j < i; j++, y <<= 1)
453 if ((y -= c[j]) < 0)
454 return 2; /* bad input: more codes than bits */
455 if ((y -= c[i]) < 0)
456 return 2;
457 c[i] += y;
459 /* Generate starting offsets into the value table for each length */
460 x[1] = j = 0;
461 p = c + 1;
462 xp = x + 2;
463 while (--i)
464 { /* note that i == g from above */
465 *xp++ = (j += *p++);
468 /* Make a table of values in order of bit lengths */
469 p = b;
470 i = 0;
473 if ((j = *p++) != 0)
474 v[x[j]++] = i;
476 while (++i < n);
478 /* Generate the Huffman codes and for each, make the table entries */
479 x[0] = i = 0; /* first Huffman code is zero */
480 p = v; /* grab values in bit order */
481 h = -1; /* no tables yet--level -1 */
482 w = -l; /* bits decoded == (l * h) */
483 u[0] = (struct huft *) NULL; /* just to keep compilers happy */
484 q = (struct huft *) NULL; /* ditto */
485 z = 0; /* ditto */
487 /* go through the bit lengths (k already is bits in shortest code) */
488 for (; k <= g; k++)
490 a = c[k];
491 while (a--)
493 /* here i is the Huffman code of length k bits for value *p */
494 /* make tables up to required level */
495 while (k > w + l)
497 h++;
498 w += l; /* previous table always l bits */
500 /* compute minimum size table less than or equal to l bits */
501 z = (z = (unsigned) (g - w)) > (unsigned) l ? (unsigned) l : z; /* upper limit on table size */
502 if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
503 { /* too few codes for k-w bit table */
504 f -= a + 1; /* deduct codes from patterns left */
505 xp = c + k;
506 while (++j < z) /* try smaller tables up to z bits */
508 if ((f <<= 1) <= *++xp)
509 break; /* enough codes to use up j bits */
510 f -= *xp; /* else deduct codes from patterns */
513 z = 1 << j; /* table entries for j-bit table */
515 /* allocate and link in new table */
516 q = (struct huft *) grub_malloc ((z + 1) * sizeof (struct huft));
517 if (! q)
519 if (h)
520 huft_free (u[0]);
521 return 3;
524 *t = q + 1; /* link to list for huft_free() */
525 *(t = &(q->v.t)) = (struct huft *) NULL;
526 u[h] = ++q; /* table starts after link */
528 /* connect to last table, if there is one */
529 if (h)
531 x[h] = i; /* save pattern for backing up */
532 r.b = (uch) l; /* bits to dump before this table */
533 r.e = (uch) (16 + j); /* bits in this table */
534 r.v.t = q; /* pointer to this table */
535 j = i >> (w - l); /* (get around Turbo C bug) */
536 u[h - 1][j] = r; /* connect to last table */
540 /* set up table entry in r */
541 r.b = (uch) (k - w);
542 if (p >= v + n)
543 r.e = 99; /* out of values--invalid code */
544 else if (*p < s)
546 r.e = (uch) (*p < 256 ? 16 : 15); /* 256 is end-of-block code */
547 r.v.n = (ush) (*p); /* simple code is just the value */
548 p++; /* one compiler does not like *p++ */
550 else
552 r.e = (uch) e[*p - s]; /* non-simple--look up in lists */
553 r.v.n = d[*p++ - s];
556 /* fill code-like entries with r */
557 f = 1 << (k - w);
558 for (j = i >> w; j < z; j += f)
559 q[j] = r;
561 /* backwards increment the k-bit code i */
562 for (j = 1 << (k - 1); i & j; j >>= 1)
563 i ^= j;
564 i ^= j;
566 /* backup over finished tables */
567 while ((i & ((1 << w) - 1)) != x[h])
569 h--; /* don't need to update q */
570 w -= l;
575 /* Return true (1) if we were given an incomplete table */
576 return y != 0 && g != 1;
580 /* Free the malloc'ed tables built by huft_build(), which makes a linked
581 list of the tables it made, with the links in a dummy first entry of
582 each table. */
583 static int
584 huft_free (struct huft *t)
586 register struct huft *p, *q;
589 /* Go through linked list, freeing from the malloced (t[-1]) address. */
590 p = t;
591 while (p != (struct huft *) NULL)
593 q = (--p)->v.t;
594 grub_free ((char *) p);
595 p = q;
597 return 0;
602 * inflate (decompress) the codes in a deflated (compressed) block.
603 * Return an error code or zero if it all goes ok.
606 static int
607 inflate_codes_in_window (grub_file_t file)
609 register unsigned e; /* table entry flag/number of extra bits */
610 unsigned n, d; /* length and index for copy */
611 unsigned w; /* current window position */
612 struct huft *t; /* pointer to table entry */
613 unsigned ml, md; /* masks for bl and bd bits */
614 register ulg b; /* bit buffer */
615 register unsigned k; /* number of bits in bit buffer */
616 grub_gzio_t gzio = file->data;
618 /* make local copies of globals */
619 d = gzio->inflate_d;
620 n = gzio->inflate_n;
621 b = gzio->bb; /* initialize bit buffer */
622 k = gzio->bk;
623 w = gzio->wp; /* initialize window position */
625 /* inflate the coded data */
626 ml = mask_bits[gzio->bl]; /* precompute masks for speed */
627 md = mask_bits[gzio->bd];
628 for (;;) /* do until end of block */
630 if (! gzio->code_state)
632 NEEDBITS ((unsigned) gzio->bl);
633 if ((e = (t = gzio->tl + ((unsigned) b & ml))->e) > 16)
636 if (e == 99)
638 grub_error (GRUB_ERR_BAD_GZIP_DATA,
639 "an unused code found");
640 return 1;
642 DUMPBITS (t->b);
643 e -= 16;
644 NEEDBITS (e);
646 while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e) > 16);
647 DUMPBITS (t->b);
649 if (e == 16) /* then it's a literal */
651 gzio->slide[w++] = (uch) t->v.n;
652 if (w == WSIZE)
653 break;
655 else
656 /* it's an EOB or a length */
658 /* exit if end of block */
659 if (e == 15)
661 gzio->block_len = 0;
662 break;
665 /* get length of block to copy */
666 NEEDBITS (e);
667 n = t->v.n + ((unsigned) b & mask_bits[e]);
668 DUMPBITS (e);
670 /* decode distance of block to copy */
671 NEEDBITS ((unsigned) gzio->bd);
672 if ((e = (t = gzio->td + ((unsigned) b & md))->e) > 16)
675 if (e == 99)
677 grub_error (GRUB_ERR_BAD_GZIP_DATA,
678 "an unused code found");
679 return 1;
681 DUMPBITS (t->b);
682 e -= 16;
683 NEEDBITS (e);
685 while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e)
686 > 16);
687 DUMPBITS (t->b);
688 NEEDBITS (e);
689 d = w - t->v.n - ((unsigned) b & mask_bits[e]);
690 DUMPBITS (e);
691 gzio->code_state++;
695 if (gzio->code_state)
697 /* do the copy */
700 n -= (e = (e = WSIZE - ((d &= WSIZE - 1) > w ? d : w)) > n ? n
701 : e);
703 if (w - d >= e)
705 grub_memmove (gzio->slide + w, gzio->slide + d, e);
706 w += e;
707 d += e;
709 else
710 /* purposefully use the overlap for extra copies here!! */
712 while (e--)
713 gzio->slide[w++] = gzio->slide[d++];
716 if (w == WSIZE)
717 break;
719 while (n);
721 if (! n)
722 gzio->code_state--;
724 /* did we break from the loop too soon? */
725 if (w == WSIZE)
726 break;
730 /* restore the globals from the locals */
731 gzio->inflate_d = d;
732 gzio->inflate_n = n;
733 gzio->wp = w; /* restore global window pointer */
734 gzio->bb = b; /* restore global bit buffer */
735 gzio->bk = k;
737 return ! gzio->block_len;
741 /* get header for an inflated type 0 (stored) block. */
743 static void
744 init_stored_block (grub_file_t file)
746 register ulg b; /* bit buffer */
747 register unsigned k; /* number of bits in bit buffer */
748 grub_gzio_t gzio = file->data;
750 /* make local copies of globals */
751 b = gzio->bb; /* initialize bit buffer */
752 k = gzio->bk;
754 /* go to byte boundary */
755 DUMPBITS (k & 7);
757 /* get the length and its complement */
758 NEEDBITS (16);
759 gzio->block_len = ((unsigned) b & 0xffff);
760 DUMPBITS (16);
761 NEEDBITS (16);
762 if (gzio->block_len != (int) ((~b) & 0xffff))
763 grub_error (GRUB_ERR_BAD_GZIP_DATA,
764 "the length of a stored block does not match");
765 DUMPBITS (16);
767 /* restore global variables */
768 gzio->bb = b;
769 gzio->bk = k;
773 /* get header for an inflated type 1 (fixed Huffman codes) block. We should
774 either replace this with a custom decoder, or at least precompute the
775 Huffman tables. */
777 static void
778 init_fixed_block (grub_file_t file)
780 int i; /* temporary variable */
781 unsigned l[288]; /* length list for huft_build */
782 grub_gzio_t gzio = file->data;
784 /* set up literal table */
785 for (i = 0; i < 144; i++)
786 l[i] = 8;
787 for (; i < 256; i++)
788 l[i] = 9;
789 for (; i < 280; i++)
790 l[i] = 7;
791 for (; i < 288; i++) /* make a complete, but wrong code set */
792 l[i] = 8;
793 gzio->bl = 7;
794 if (huft_build (l, 288, 257, cplens, cplext, &gzio->tl, &gzio->bl) != 0)
796 if (grub_errno == GRUB_ERR_NONE)
797 grub_error (GRUB_ERR_BAD_GZIP_DATA,
798 "failed in building a Huffman code table");
799 return;
802 /* set up distance table */
803 for (i = 0; i < 30; i++) /* make an incomplete code set */
804 l[i] = 5;
805 gzio->bd = 5;
806 if (huft_build (l, 30, 0, cpdist, cpdext, &gzio->td, &gzio->bd) > 1)
808 if (grub_errno == GRUB_ERR_NONE)
809 grub_error (GRUB_ERR_BAD_GZIP_DATA,
810 "failed in building a Huffman code table");
811 huft_free (gzio->tl);
812 gzio->tl = 0;
813 return;
816 /* indicate we're now working on a block */
817 gzio->code_state = 0;
818 gzio->block_len++;
822 /* get header for an inflated type 2 (dynamic Huffman codes) block. */
824 static void
825 init_dynamic_block (grub_file_t file)
827 int i; /* temporary variables */
828 unsigned j;
829 unsigned l; /* last length */
830 unsigned m; /* mask for bit lengths table */
831 unsigned n; /* number of lengths to get */
832 unsigned nb; /* number of bit length codes */
833 unsigned nl; /* number of literal/length codes */
834 unsigned nd; /* number of distance codes */
835 unsigned ll[286 + 30]; /* literal/length and distance code lengths */
836 register ulg b; /* bit buffer */
837 register unsigned k; /* number of bits in bit buffer */
838 grub_gzio_t gzio = file->data;
840 /* make local bit buffer */
841 b = gzio->bb;
842 k = gzio->bk;
844 /* read in table lengths */
845 NEEDBITS (5);
846 nl = 257 + ((unsigned) b & 0x1f); /* number of literal/length codes */
847 DUMPBITS (5);
848 NEEDBITS (5);
849 nd = 1 + ((unsigned) b & 0x1f); /* number of distance codes */
850 DUMPBITS (5);
851 NEEDBITS (4);
852 nb = 4 + ((unsigned) b & 0xf); /* number of bit length codes */
853 DUMPBITS (4);
854 if (nl > 286 || nd > 30)
856 grub_error (GRUB_ERR_BAD_GZIP_DATA, "too much data");
857 return;
860 /* read in bit-length-code lengths */
861 for (j = 0; j < nb; j++)
863 NEEDBITS (3);
864 ll[bitorder[j]] = (unsigned) b & 7;
865 DUMPBITS (3);
867 for (; j < 19; j++)
868 ll[bitorder[j]] = 0;
870 /* build decoding table for trees--single level, 7 bit lookup */
871 gzio->bl = 7;
872 if (huft_build (ll, 19, 19, NULL, NULL, &gzio->tl, &gzio->bl) != 0)
874 grub_error (GRUB_ERR_BAD_GZIP_DATA,
875 "failed in building a Huffman code table");
876 return;
879 /* read in literal and distance code lengths */
880 n = nl + nd;
881 m = mask_bits[gzio->bl];
882 i = l = 0;
883 while ((unsigned) i < n)
885 NEEDBITS ((unsigned) gzio->bl);
886 j = (gzio->td = gzio->tl + ((unsigned) b & m))->b;
887 DUMPBITS (j);
888 j = gzio->td->v.n;
889 if (j < 16) /* length of code in bits (0..15) */
890 ll[i++] = l = j; /* save last length in l */
891 else if (j == 16) /* repeat last length 3 to 6 times */
893 NEEDBITS (2);
894 j = 3 + ((unsigned) b & 3);
895 DUMPBITS (2);
896 if ((unsigned) i + j > n)
898 grub_error (GRUB_ERR_BAD_GZIP_DATA, "too many codes found");
899 return;
901 while (j--)
902 ll[i++] = l;
904 else if (j == 17) /* 3 to 10 zero length codes */
906 NEEDBITS (3);
907 j = 3 + ((unsigned) b & 7);
908 DUMPBITS (3);
909 if ((unsigned) i + j > n)
911 grub_error (GRUB_ERR_BAD_GZIP_DATA, "too many codes found");
912 return;
914 while (j--)
915 ll[i++] = 0;
916 l = 0;
918 else
919 /* j == 18: 11 to 138 zero length codes */
921 NEEDBITS (7);
922 j = 11 + ((unsigned) b & 0x7f);
923 DUMPBITS (7);
924 if ((unsigned) i + j > n)
926 grub_error (GRUB_ERR_BAD_GZIP_DATA, "too many codes found");
927 return;
929 while (j--)
930 ll[i++] = 0;
931 l = 0;
935 /* free decoding table for trees */
936 huft_free (gzio->tl);
937 gzio->td = 0;
938 gzio->tl = 0;
940 /* restore the global bit buffer */
941 gzio->bb = b;
942 gzio->bk = k;
944 /* build the decoding tables for literal/length and distance codes */
945 gzio->bl = lbits;
946 if (huft_build (ll, nl, 257, cplens, cplext, &gzio->tl, &gzio->bl) != 0)
948 grub_error (GRUB_ERR_BAD_GZIP_DATA,
949 "failed in building a Huffman code table");
950 return;
952 gzio->bd = dbits;
953 if (huft_build (ll + nl, nd, 0, cpdist, cpdext, &gzio->td, &gzio->bd) != 0)
955 huft_free (gzio->tl);
956 gzio->tl = 0;
957 grub_error (GRUB_ERR_BAD_GZIP_DATA,
958 "failed in building a Huffman code table");
959 return;
962 /* indicate we're now working on a block */
963 gzio->code_state = 0;
964 gzio->block_len++;
968 static void
969 get_new_block (grub_file_t file)
971 register ulg b; /* bit buffer */
972 register unsigned k; /* number of bits in bit buffer */
973 grub_gzio_t gzio = file->data;
975 /* make local bit buffer */
976 b = gzio->bb;
977 k = gzio->bk;
979 /* read in last block bit */
980 NEEDBITS (1);
981 gzio->last_block = (int) b & 1;
982 DUMPBITS (1);
984 /* read in block type */
985 NEEDBITS (2);
986 gzio->block_type = (unsigned) b & 3;
987 DUMPBITS (2);
989 /* restore the global bit buffer */
990 gzio->bb = b;
991 gzio->bk = k;
993 switch (gzio->block_type)
995 case INFLATE_STORED:
996 init_stored_block (file);
997 break;
998 case INFLATE_FIXED:
999 init_fixed_block (file);
1000 break;
1001 case INFLATE_DYNAMIC:
1002 init_dynamic_block (file);
1003 break;
1004 default:
1005 break;
1010 static void
1011 inflate_window (grub_file_t file)
1013 grub_gzio_t gzio = file->data;
1015 /* initialize window */
1016 gzio->wp = 0;
1019 * Main decompression loop.
1022 while (gzio->wp < WSIZE && grub_errno == GRUB_ERR_NONE)
1024 if (! gzio->block_len)
1026 if (gzio->last_block)
1027 break;
1029 get_new_block (file);
1032 if (gzio->block_type > INFLATE_DYNAMIC)
1033 grub_error (GRUB_ERR_BAD_GZIP_DATA,
1034 "unknown block type %d", gzio->block_type);
1036 if (grub_errno != GRUB_ERR_NONE)
1037 return;
1040 * Expand stored block here.
1042 if (gzio->block_type == INFLATE_STORED)
1044 int w = gzio->wp;
1047 * This is basically a glorified pass-through
1050 while (gzio->block_len && w < WSIZE && grub_errno == GRUB_ERR_NONE)
1052 gzio->slide[w++] = get_byte (file);
1053 gzio->block_len--;
1056 gzio->wp = w;
1058 continue;
1062 * Expand other kind of block.
1065 if (inflate_codes_in_window (file))
1067 huft_free (gzio->tl);
1068 huft_free (gzio->td);
1069 gzio->tl = 0;
1070 gzio->td = 0;
1074 gzio->saved_offset += WSIZE;
1076 /* XXX do CRC calculation here! */
1080 static void
1081 initialize_tables (grub_file_t file)
1083 grub_gzio_t gzio = file->data;
1085 gzio->saved_offset = 0;
1086 grub_file_seek (gzio->file, gzio->data_offset);
1088 /* Initialize the bit buffer. */
1089 gzio->bk = 0;
1090 gzio->bb = 0;
1092 /* Reset partial decompression code. */
1093 gzio->last_block = 0;
1094 gzio->block_len = 0;
1096 /* Reset memory allocation stuff. */
1097 huft_free (gzio->tl);
1098 huft_free (gzio->td);
1102 /* Open a new decompressing object on the top of IO. If TRANSPARENT is true,
1103 even if IO does not contain data compressed by gzip, return a valid file
1104 object. Note that this function won't close IO, even if an error occurs. */
1105 grub_file_t
1106 grub_gzio_open (grub_file_t io, int transparent)
1108 grub_file_t file;
1109 grub_gzio_t gzio = 0;
1111 file = (grub_file_t) grub_malloc (sizeof (*file));
1112 if (! file)
1113 return 0;
1115 gzio = grub_malloc (sizeof (*gzio));
1116 if (! gzio)
1118 grub_free (file);
1119 return 0;
1122 grub_memset (gzio, 0, sizeof (*gzio));
1123 gzio->file = io;
1125 file->device = io->device;
1126 file->offset = 0;
1127 file->data = gzio;
1128 file->read_hook = 0;
1129 file->fs = &grub_gzio_fs;
1131 if (! test_header (file))
1133 grub_free (gzio);
1134 grub_free (file);
1135 grub_file_seek (io, 0);
1137 if (grub_errno == GRUB_ERR_BAD_FILE_TYPE && transparent)
1139 grub_errno = GRUB_ERR_NONE;
1140 return io;
1142 else
1143 return 0;
1146 return file;
1149 /* This is similar to grub_gzio_open, but takes a file name as an argument. */
1150 grub_file_t
1151 grub_gzfile_open (const char *name, int transparent)
1153 grub_file_t io, file;
1155 io = grub_file_open (name);
1156 if (! io)
1157 return 0;
1159 file = grub_gzio_open (io, transparent);
1160 if (! file)
1162 grub_file_close (io);
1163 return 0;
1166 return file;
1169 static grub_ssize_t
1170 grub_gzio_read (grub_file_t file, char *buf, grub_size_t len)
1172 grub_ssize_t ret = 0;
1173 grub_gzio_t gzio = file->data;
1174 grub_off_t offset;
1176 /* Do we reset decompression to the beginning of the file? */
1177 if (gzio->saved_offset > file->offset + WSIZE)
1178 initialize_tables (file);
1181 * This loop operates upon uncompressed data only. The only
1182 * special thing it does is to make sure the decompression
1183 * window is within the range of data it needs.
1186 offset = file->offset;
1188 while (len > 0 && grub_errno == GRUB_ERR_NONE)
1190 register grub_size_t size;
1191 register char *srcaddr;
1193 while (offset >= gzio->saved_offset)
1194 inflate_window (file);
1196 srcaddr = (char *) ((offset & (WSIZE - 1)) + gzio->slide);
1197 size = gzio->saved_offset - offset;
1198 if (size > len)
1199 size = len;
1201 grub_memmove (buf, srcaddr, size);
1203 buf += size;
1204 len -= size;
1205 ret += size;
1206 offset += size;
1209 if (grub_errno != GRUB_ERR_NONE)
1210 ret = -1;
1212 return ret;
1215 /* Release everything, including the underlying file object. */
1216 static grub_err_t
1217 grub_gzio_close (grub_file_t file)
1219 grub_gzio_t gzio = file->data;
1221 grub_file_close (gzio->file);
1222 huft_free (gzio->tl);
1223 huft_free (gzio->td);
1224 grub_free (gzio);
1226 /* No need to close the same device twice. */
1227 file->device = 0;
1229 return grub_errno;
1234 static struct grub_fs grub_gzio_fs =
1236 .name = "gzio",
1237 .dir = 0,
1238 .open = 0,
1239 .read = grub_gzio_read,
1240 .close = grub_gzio_close,
1241 .label = 0,
1242 .next = 0