]> code.delx.au - refind/blob - filesystems/gzio.c
Added primitive cache to most drivers to improve performance,
[refind] / filesystems / gzio.c
1 /*
2 * this file take from grub 2.0
3 * for btrfs UEFI driver
4 */
5
6 /* gzio.c - decompression support for gzip */
7 /*
8 * GRUB -- GRand Unified Bootloader
9 * Copyright (C) 1999,2005,2006,2007,2009 Free Software Foundation, Inc.
10 *
11 * GRUB is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * GRUB is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 /*
26 * Most of this file was originally the source file "inflate.c", written
27 * by Mark Adler. It has been very heavily modified. In particular, the
28 * original would run through the whole file at once, and this version can
29 * be stopped and restarted on any boundary during the decompression process.
30 *
31 * The license and header comments that file are included here.
32 */
33
34 /* inflate.c -- Not copyrighted 1992 by Mark Adler
35 version c10p1, 10 January 1993 */
36
37 /* You can do whatever you like with this source file, though I would
38 prefer that if you modify it and redistribute it that you include
39 comments to that effect with your name and the date. Thank you.
40 */
41
42 #if 0
43 #include <grub/err.h>
44 #include <grub/types.h>
45 #include <grub/mm.h>
46 #include <grub/misc.h>
47 #include <grub/fs.h>
48 #include <grub/file.h>
49 #include <grub/dl.h>
50 #include <grub/deflate.h>
51 #include <grub/i18n.h>
52
53 GRUB_MOD_LICENSE ("GPLv3+");
54 #endif
55
56 /*
57 * Window Size
58 *
59 * This must be a power of two, and at least 32K for zip's deflate method
60 */
61
62 #define WSIZE 0x8000
63
64
65 #define INBUFSIZ 0x2000
66
67 /* The state stored in filesystem-specific data. */
68 struct grub_gzio
69 {
70 int err;
71 /* If input is in memory following fields are used instead of file. */
72 int mem_input_size, mem_input_off;
73 uint8_t *mem_input;
74 /* The offset at which the data starts in the underlying file. */
75 int data_offset;
76 /* The type of current block. */
77 int block_type;
78 /* The length of current block. */
79 int block_len;
80 /* The flag of the last block. */
81 int last_block;
82 /* The flag of codes. */
83 int code_state;
84 /* The length of a copy. */
85 unsigned inflate_n;
86 /* The index of a copy. */
87 unsigned inflate_d;
88 /* The input buffer. */
89 uint8_t inbuf[INBUFSIZ];
90 int inbuf_d;
91 /* The bit buffer. */
92 unsigned long bb;
93 /* The bits in the bit buffer. */
94 unsigned bk;
95 /* The sliding window in uncompressed data. */
96 uint8_t slide[WSIZE];
97 /* Current position in the slide. */
98 unsigned wp;
99 /* The literal/length code table. */
100 struct huft *tl;
101 /* The distance code table. */
102 struct huft *td;
103 /* The lookup bits for the literal/length code table. */
104 int bl;
105 /* The lookup bits for the distance code table. */
106 int bd;
107 /* The original offset value. */
108 int saved_offset;
109 };
110 typedef struct grub_gzio *grub_gzio_t;
111
112 /* Function prototypes */
113 static void initialize_tables (grub_gzio_t);
114
115 /* Little-Endian defines for the 2-byte magic numbers for gzip files. */
116 #define GZIP_MAGIC grub_le_to_cpu16 (0x8B1F)
117 #define OLD_GZIP_MAGIC grub_le_to_cpu16 (0x9E1F)
118
119 /* Compression methods (see algorithm.doc) */
120 #define STORED 0
121 #define COMPRESSED 1
122 //#define PACKED 2
123 #define LZHED 3
124 /* methods 4 to 7 reserved */
125 #define DEFLATED 8
126 #define MAX_METHODS 9
127
128 /* gzip flag byte */
129 #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
130 #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
131 #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
132 #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
133 #define COMMENT 0x10 /* bit 4 set: file comment present */
134 #define ENCRYPTED 0x20 /* bit 5 set: file is encrypted */
135 #define RESERVED 0xC0 /* bit 6,7: reserved */
136
137 #define UNSUPPORTED_FLAGS (CONTINUATION | ENCRYPTED | RESERVED)
138
139 /* inflate block codes */
140 #define INFLATE_STORED 0
141 #define INFLATE_FIXED 1
142 #define INFLATE_DYNAMIC 2
143
144 typedef unsigned char uch;
145 typedef unsigned short ush;
146 typedef unsigned long ulg;
147
148 /* Huffman code lookup table entry--this entry is four bytes for machines
149 that have 16-bit pointers (e.g. PC's in the small or medium model).
150 Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16
151 means that v is a literal, 16 < e < 32 means that v is a pointer to
152 the next table, which codes e - 16 bits, and lastly e == 99 indicates
153 an unused code. If a code with e == 99 is looked up, this implies an
154 error in the data. */
155 struct huft
156 {
157 uch e; /* number of extra bits or operation */
158 uch b; /* number of bits in this code or subcode */
159 union
160 {
161 ush n; /* literal, length base, or distance base */
162 struct huft *t; /* pointer to next level of table */
163 }
164 v;
165 };
166
167
168 /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
169 stream to find repeated byte strings. This is implemented here as a
170 circular buffer. The index is updated simply by incrementing and then
171 and'ing with 0x7fff (32K-1). */
172 /* It is left to other modules to supply the 32K area. It is assumed
173 to be usable as if it were declared "uch slide[32768];" or as just
174 "uch *slide;" and then malloc'ed in the latter case. The definition
175 must be in unzip.h, included above. */
176
177
178 /* Tables for deflate from PKZIP's appnote.txt. */
179 static unsigned bitorder[] =
180 { /* Order of the bit length code lengths */
181 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
182 static ush cplens[] =
183 { /* Copy lengths for literal codes 257..285 */
184 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
185 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
186 /* note: see note #13 above about the 258 in this list. */
187 static ush cplext[] =
188 { /* Extra bits for literal codes 257..285 */
189 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
190 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
191 static ush cpdist[] =
192 { /* Copy offsets for distance codes 0..29 */
193 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
194 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
195 8193, 12289, 16385, 24577};
196 static ush cpdext[] =
197 { /* Extra bits for distance codes */
198 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
199 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
200 12, 12, 13, 13};
201
202
203 /*
204 Huffman code decoding is performed using a multi-level table lookup.
205 The fastest way to decode is to simply build a lookup table whose
206 size is determined by the longest code. However, the time it takes
207 to build this table can also be a factor if the data being decoded
208 is not very long. The most common codes are necessarily the
209 shortest codes, so those codes dominate the decoding time, and hence
210 the speed. The idea is you can have a shorter table that decodes the
211 shorter, more probable codes, and then point to subsidiary tables for
212 the longer codes. The time it costs to decode the longer codes is
213 then traded against the time it takes to make longer tables.
214
215 This results of this trade are in the variables lbits and dbits
216 below. lbits is the number of bits the first level table for literal/
217 length codes can decode in one step, and dbits is the same thing for
218 the distance codes. Subsequent tables are also less than or equal to
219 those sizes. These values may be adjusted either when all of the
220 codes are shorter than that, in which case the longest code length in
221 bits is used, or when the shortest code is *longer* than the requested
222 table size, in which case the length of the shortest code in bits is
223 used.
224
225 There are two different values for the two tables, since they code a
226 different number of possibilities each. The literal/length table
227 codes 286 possible values, or in a flat code, a little over eight
228 bits. The distance table codes 30 possible values, or a little less
229 than five bits, flat. The optimum values for speed end up being
230 about one bit more than those, so lbits is 8+1 and dbits is 5+1.
231 The optimum values may differ though from machine to machine, and
232 possibly even between compilers. Your mileage may vary.
233 */
234
235
236 static int lbits = 9; /* bits in base literal/length lookup table */
237 static int dbits = 6; /* bits in base distance lookup table */
238
239
240 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
241 #define BMAX 16 /* maximum bit length of any code (16 for explode) */
242 #define N_MAX 288 /* maximum number of codes in any set */
243
244
245 /* Macros for inflate() bit peeking and grabbing.
246 The usage is:
247
248 NEEDBITS(j)
249 x = b & mask_bits[j];
250 DUMPBITS(j)
251
252 where NEEDBITS makes sure that b has at least j bits in it, and
253 DUMPBITS removes the bits from b. The macros use the variable k
254 for the number of bits in b. Normally, b and k are register
255 variables for speed, and are initialized at the beginning of a
256 routine that uses these macros from a global bit buffer and count.
257
258 If we assume that EOB will be the longest code, then we will never
259 ask for bits with NEEDBITS that are beyond the end of the stream.
260 So, NEEDBITS should not read any more bytes than are needed to
261 meet the request. Then no bytes need to be "returned" to the buffer
262 at the end of the last block.
263
264 However, this assumption is not true for fixed blocks--the EOB code
265 is 7 bits, but the other literal/length codes can be 8 or 9 bits.
266 (The EOB code is shorter than other codes because fixed blocks are
267 generally short. So, while a block always has an EOB, many other
268 literal/length codes have a significantly lower probability of
269 showing up at all.) However, by making the first table have a
270 lookup of seven bits, the EOB code will be found in that first
271 lookup, and so will not require that too many bits be pulled from
272 the stream.
273 */
274
275 static ush mask_bits[] =
276 {
277 0x0000,
278 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
279 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
280 };
281
282 #pragma GCC diagnostic ignored "-Wunsafe-loop-optimizations"
283
284 #define NEEDBITS(n) do {while(k<(n)){b|=((ulg)get_byte(gzio))<<k;k+=8;}} while (0)
285 #define DUMPBITS(n) do {b>>=(n);k-=(n);} while (0)
286
287 static int
288 get_byte (grub_gzio_t gzio)
289 {
290 if (gzio->mem_input_off < gzio->mem_input_size)
291 return gzio->mem_input[gzio->mem_input_off++];
292 return 0;
293 }
294
295 static void
296 gzio_seek (grub_gzio_t gzio, grub_off_t off)
297 {
298 if (off > gzio->mem_input_size)
299 gzio->err = -1;
300 else
301 gzio->mem_input_off = off;
302 }
303
304 /* more function prototypes */
305 static int huft_build (unsigned *, unsigned, unsigned, ush *, ush *,
306 struct huft **, int *);
307 static int huft_free (struct huft *);
308 static int inflate_codes_in_window (grub_gzio_t);
309
310
311 /* Given a list of code lengths and a maximum table size, make a set of
312 tables to decode that set of codes. Return zero on success, one if
313 the given code set is incomplete (the tables are still built in this
314 case), two if the input is invalid (all zero length codes or an
315 oversubscribed set of lengths), and three if not enough memory. */
316
317 static int
318 huft_build (unsigned *b, /* code lengths in bits (all assumed <= BMAX) */
319 unsigned n, /* number of codes (assumed <= N_MAX) */
320 unsigned s, /* number of simple-valued codes (0..s-1) */
321 ush * d, /* list of base values for non-simple codes */
322 ush * e, /* list of extra bits for non-simple codes */
323 struct huft **t, /* result: starting table */
324 int *m) /* maximum lookup bits, returns actual */
325 {
326 unsigned a; /* counter for codes of length k */
327 unsigned c[BMAX + 1]; /* bit length count table */
328 unsigned f; /* i repeats in table every f entries */
329 int g; /* maximum code length */
330 int h; /* table level */
331 register unsigned i; /* counter, current code */
332 register unsigned j; /* counter */
333 register int k; /* number of bits in current code */
334 int l; /* bits per table (returned in m) */
335 register unsigned *p; /* pointer into c[], b[], or v[] */
336 register struct huft *q; /* points to current table */
337 struct huft r; /* table entry for structure assignment */
338 struct huft *u[BMAX]; /* table stack */
339 unsigned v[N_MAX]; /* values in order of bit length */
340 register int w; /* bits before this table == (l * h) */
341 unsigned x[BMAX + 1]; /* bit offsets, then code stack */
342 unsigned *xp; /* pointer into x */
343 int y; /* number of dummy codes added */
344 unsigned z; /* number of entries in current table */
345
346 /* Generate counts for each bit length */
347 fsw_memzero ((char *) c, sizeof (c));
348 p = b;
349 i = n;
350 do
351 {
352 c[*p]++; /* assume all entries <= BMAX */
353 p++; /* Can't combine with above line (Solaris bug) */
354 }
355 while (--i);
356 if (c[0] == n) /* null input--all zero length codes */
357 {
358 *t = (struct huft *) NULL;
359 *m = 0;
360 return 0;
361 }
362
363 /* Find minimum and maximum length, bound *m by those */
364 l = *m;
365 for (j = 1; j <= BMAX; j++)
366 if (c[j])
367 break;
368 k = j; /* minimum code length */
369 if ((unsigned) l < j)
370 l = j;
371 for (i = BMAX; i; i--)
372 if (c[i])
373 break;
374 g = i; /* maximum code length */
375 if ((unsigned) l > i)
376 l = i;
377 *m = l;
378
379 /* Adjust last length count to fill out codes, if needed */
380 for (y = 1 << j; j < i; j++, y <<= 1)
381 if ((y -= c[j]) < 0)
382 return 2; /* bad input: more codes than bits */
383 if ((y -= c[i]) < 0)
384 return 2;
385 c[i] += y;
386
387 /* Generate starting offsets into the value table for each length */
388 x[1] = j = 0;
389 p = c + 1;
390 xp = x + 2;
391 while (--i)
392 { /* note that i == g from above */
393 *xp++ = (j += *p++);
394 }
395
396 /* Make a table of values in order of bit lengths */
397 p = b;
398 i = 0;
399 do
400 {
401 if ((j = *p++) != 0)
402 v[x[j]++] = i;
403 }
404 while (++i < n);
405
406 /* Generate the Huffman codes and for each, make the table entries */
407 x[0] = i = 0; /* first Huffman code is zero */
408 p = v; /* grab values in bit order */
409 h = -1; /* no tables yet--level -1 */
410 w = -l; /* bits decoded == (l * h) */
411 u[0] = (struct huft *) NULL; /* just to keep compilers happy */
412 q = (struct huft *) NULL; /* ditto */
413 z = 0; /* ditto */
414
415 /* go through the bit lengths (k already is bits in shortest code) */
416 for (; k <= g; k++)
417 {
418 a = c[k];
419 while (a--)
420 {
421 /* here i is the Huffman code of length k bits for value *p */
422 /* make tables up to required level */
423 while (k > w + l)
424 {
425 h++;
426 w += l; /* previous table always l bits */
427
428 /* compute minimum size table less than or equal to l bits */
429 z = (z = (unsigned) (g - w)) > (unsigned) l ? (unsigned) l : z; /* upper limit on table size */
430 if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
431 { /* too few codes for k-w bit table */
432 f -= a + 1; /* deduct codes from patterns left */
433 xp = c + k;
434 while (++j < z) /* try smaller tables up to z bits */
435 {
436 if ((f <<= 1) <= *++xp)
437 break; /* enough codes to use up j bits */
438 f -= *xp; /* else deduct codes from patterns */
439 }
440 }
441 z = 1 << j; /* table entries for j-bit table */
442
443 /* allocate and link in new table */
444 q = (struct huft *) AllocatePool ((z + 1) * sizeof (struct huft));
445 if (! q)
446 {
447 if (h)
448 huft_free (u[0]);
449 return 3;
450 }
451
452 *t = q + 1; /* link to list for huft_free() */
453 *(t = &(q->v.t)) = (struct huft *) NULL;
454 u[h] = ++q; /* table starts after link */
455
456 /* connect to last table, if there is one */
457 if (h)
458 {
459 x[h] = i; /* save pattern for backing up */
460 r.b = (uch) l; /* bits to dump before this table */
461 r.e = (uch) (16 + j); /* bits in this table */
462 r.v.t = q; /* pointer to this table */
463 j = i >> (w - l); /* (get around Turbo C bug) */
464 u[h - 1][j] = r; /* connect to last table */
465 }
466 }
467
468 /* set up table entry in r */
469 r.b = (uch) (k - w);
470 if (p >= v + n)
471 r.e = 99; /* out of values--invalid code */
472 else if (*p < s)
473 {
474 r.e = (uch) (*p < 256 ? 16 : 15); /* 256 is end-of-block code */
475 r.v.n = (ush) (*p); /* simple code is just the value */
476 p++; /* one compiler does not like *p++ */
477 }
478 else
479 {
480 r.e = (uch) e[*p - s]; /* non-simple--look up in lists */
481 r.v.n = d[*p++ - s];
482 }
483
484 /* fill code-like entries with r */
485 f = 1 << (k - w);
486 for (j = i >> w; j < z; j += f)
487 q[j] = r;
488
489 /* backwards increment the k-bit code i */
490 for (j = 1 << (k - 1); i & j; j >>= 1)
491 i ^= j;
492 i ^= j;
493
494 /* backup over finished tables */
495 while ((i & ((1 << w) - 1)) != x[h])
496 {
497 h--; /* don't need to update q */
498 w -= l;
499 }
500 }
501 }
502
503 /* Return true (1) if we were given an incomplete table */
504 return y != 0 && g != 1;
505 }
506
507
508 /* Free the malloc'ed tables built by huft_build(), which makes a linked
509 list of the tables it made, with the links in a dummy first entry of
510 each table. */
511 static int
512 huft_free (struct huft *t)
513 {
514 register struct huft *p, *q;
515
516
517 /* Go through linked list, freeing from the malloced (t[-1]) address. */
518 p = t;
519 while (p != (struct huft *) NULL)
520 {
521 q = (--p)->v.t;
522 FreePool ((char *) p);
523 p = q;
524 }
525 return 0;
526 }
527
528
529 /*
530 * inflate (decompress) the codes in a deflated (compressed) block.
531 * Return an error code or zero if it all goes ok.
532 */
533
534 static int
535 inflate_codes_in_window (grub_gzio_t gzio)
536 {
537 register unsigned e; /* table entry flag/number of extra bits */
538 unsigned n, d; /* length and index for copy */
539 unsigned w; /* current window position */
540 struct huft *t; /* pointer to table entry */
541 unsigned ml, md; /* masks for bl and bd bits */
542 register ulg b; /* bit buffer */
543 register unsigned k; /* number of bits in bit buffer */
544
545 /* make local copies of globals */
546 d = gzio->inflate_d;
547 n = gzio->inflate_n;
548 b = gzio->bb; /* initialize bit buffer */
549 k = gzio->bk;
550 w = gzio->wp; /* initialize window position */
551
552 /* inflate the coded data */
553 ml = mask_bits[gzio->bl]; /* precompute masks for speed */
554 md = mask_bits[gzio->bd];
555 for (;;) /* do until end of block */
556 {
557 if (! gzio->code_state)
558 {
559 NEEDBITS ((unsigned) gzio->bl);
560 if ((e = (t = gzio->tl + ((unsigned) b & ml))->e) > 16)
561 do
562 {
563 if (e == 99)
564 {
565 gzio->err = -1;
566 return 1;
567 }
568 DUMPBITS (t->b);
569 e -= 16;
570 NEEDBITS (e);
571 }
572 while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e) > 16);
573 DUMPBITS (t->b);
574
575 if (e == 16) /* then it's a literal */
576 {
577 gzio->slide[w++] = (uch) t->v.n;
578 if (w == WSIZE)
579 break;
580 }
581 else
582 /* it's an EOB or a length */
583 {
584 /* exit if end of block */
585 if (e == 15)
586 {
587 gzio->block_len = 0;
588 break;
589 }
590
591 /* get length of block to copy */
592 NEEDBITS (e);
593 n = t->v.n + ((unsigned) b & mask_bits[e]);
594 DUMPBITS (e);
595
596 /* decode distance of block to copy */
597 NEEDBITS ((unsigned) gzio->bd);
598 if ((e = (t = gzio->td + ((unsigned) b & md))->e) > 16)
599 do
600 {
601 if (e == 99)
602 {
603 gzio->err = -1;
604 return 1;
605 }
606 DUMPBITS (t->b);
607 e -= 16;
608 NEEDBITS (e);
609 }
610 while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e)
611 > 16);
612 DUMPBITS (t->b);
613 NEEDBITS (e);
614 d = w - t->v.n - ((unsigned) b & mask_bits[e]);
615 DUMPBITS (e);
616 gzio->code_state++;
617 }
618 }
619
620 if (gzio->code_state)
621 {
622 /* do the copy */
623 do
624 {
625 n -= (e = (e = WSIZE - ((d &= WSIZE - 1) > w ? d : w)) > n ? n
626 : e);
627
628 if (w - d >= e)
629 {
630 fsw_memcpy (gzio->slide + w, gzio->slide + d, e);
631 w += e;
632 d += e;
633 }
634 else
635 /* purposefully use the overlap for extra copies here!! */
636 {
637 while (e--)
638 gzio->slide[w++] = gzio->slide[d++];
639 }
640
641 if (w == WSIZE)
642 break;
643 }
644 while (n);
645
646 if (! n)
647 gzio->code_state--;
648
649 /* did we break from the loop too soon? */
650 if (w == WSIZE)
651 break;
652 }
653 }
654
655 /* restore the globals from the locals */
656 gzio->inflate_d = d;
657 gzio->inflate_n = n;
658 gzio->wp = w; /* restore global window pointer */
659 gzio->bb = b; /* restore global bit buffer */
660 gzio->bk = k;
661
662 return ! gzio->block_len;
663 }
664
665
666 /* get header for an inflated type 0 (stored) block. */
667
668 static void
669 init_stored_block (grub_gzio_t gzio)
670 {
671 register ulg b; /* bit buffer */
672 register unsigned k; /* number of bits in bit buffer */
673
674 /* make local copies of globals */
675 b = gzio->bb; /* initialize bit buffer */
676 k = gzio->bk;
677
678 /* go to byte boundary */
679 DUMPBITS (k & 7);
680
681 /* get the length and its complement */
682 NEEDBITS (16);
683 gzio->block_len = ((unsigned) b & 0xffff);
684 DUMPBITS (16);
685 NEEDBITS (16);
686 if (gzio->block_len != (int) ((~b) & 0xffff))
687 gzio->err = -1;
688 DUMPBITS (16);
689
690 /* restore global variables */
691 gzio->bb = b;
692 gzio->bk = k;
693 }
694
695
696 /* get header for an inflated type 1 (fixed Huffman codes) block. We should
697 either replace this with a custom decoder, or at least precompute the
698 Huffman tables. */
699
700 static void
701 init_fixed_block (grub_gzio_t gzio)
702 {
703 int i; /* temporary variable */
704 unsigned l[288]; /* length list for huft_build */
705
706 /* set up literal table */
707 for (i = 0; i < 144; i++)
708 l[i] = 8;
709 for (; i < 256; i++)
710 l[i] = 9;
711 for (; i < 280; i++)
712 l[i] = 7;
713 for (; i < 288; i++) /* make a complete, but wrong code set */
714 l[i] = 8;
715 gzio->bl = 7;
716 if (huft_build (l, 288, 257, cplens, cplext, &gzio->tl, &gzio->bl) != 0)
717 {
718 gzio->err = -1;
719 return;
720 }
721
722 /* set up distance table */
723 for (i = 0; i < 30; i++) /* make an incomplete code set */
724 l[i] = 5;
725 gzio->bd = 5;
726 if (huft_build (l, 30, 0, cpdist, cpdext, &gzio->td, &gzio->bd) > 1)
727 {
728 gzio->err = -1;
729 huft_free (gzio->tl);
730 gzio->tl = 0;
731 return;
732 }
733
734 /* indicate we're now working on a block */
735 gzio->code_state = 0;
736 gzio->block_len++;
737 }
738
739
740 /* get header for an inflated type 2 (dynamic Huffman codes) block. */
741
742 static void
743 init_dynamic_block (grub_gzio_t gzio)
744 {
745 int i; /* temporary variables */
746 unsigned j;
747 unsigned l; /* last length */
748 unsigned m; /* mask for bit lengths table */
749 unsigned n; /* number of lengths to get */
750 unsigned nb; /* number of bit length codes */
751 unsigned nl; /* number of literal/length codes */
752 unsigned nd; /* number of distance codes */
753 unsigned ll[286 + 30]; /* literal/length and distance code lengths */
754 register ulg b; /* bit buffer */
755 register unsigned k; /* number of bits in bit buffer */
756
757 /* make local bit buffer */
758 b = gzio->bb;
759 k = gzio->bk;
760
761 /* read in table lengths */
762 NEEDBITS (5);
763 nl = 257 + ((unsigned) b & 0x1f); /* number of literal/length codes */
764 DUMPBITS (5);
765 NEEDBITS (5);
766 nd = 1 + ((unsigned) b & 0x1f); /* number of distance codes */
767 DUMPBITS (5);
768 NEEDBITS (4);
769 nb = 4 + ((unsigned) b & 0xf); /* number of bit length codes */
770 DUMPBITS (4);
771 if (nl > 286 || nd > 30)
772 {
773 gzio->err = -1;
774 return;
775 }
776
777 /* read in bit-length-code lengths */
778 for (j = 0; j < nb; j++)
779 {
780 NEEDBITS (3);
781 ll[bitorder[j]] = (unsigned) b & 7;
782 DUMPBITS (3);
783 }
784 for (; j < 19; j++)
785 ll[bitorder[j]] = 0;
786
787 /* build decoding table for trees--single level, 7 bit lookup */
788 gzio->bl = 7;
789 if (huft_build (ll, 19, 19, NULL, NULL, &gzio->tl, &gzio->bl) != 0)
790 {
791 gzio->err = -1;
792 return;
793 }
794
795 /* read in literal and distance code lengths */
796 n = nl + nd;
797 m = mask_bits[gzio->bl];
798 i = l = 0;
799 while ((unsigned) i < n)
800 {
801 NEEDBITS ((unsigned) gzio->bl);
802 j = (gzio->td = gzio->tl + ((unsigned) b & m))->b;
803 DUMPBITS (j);
804 j = gzio->td->v.n;
805 if (j < 16) /* length of code in bits (0..15) */
806 ll[i++] = l = j; /* save last length in l */
807 else if (j == 16) /* repeat last length 3 to 6 times */
808 {
809 NEEDBITS (2);
810 j = 3 + ((unsigned) b & 3);
811 DUMPBITS (2);
812 if ((unsigned) i + j > n)
813 {
814 gzio->err = -1;
815 return;
816 }
817 while (j--)
818 ll[i++] = l;
819 }
820 else if (j == 17) /* 3 to 10 zero length codes */
821 {
822 NEEDBITS (3);
823 j = 3 + ((unsigned) b & 7);
824 DUMPBITS (3);
825 if ((unsigned) i + j > n)
826 {
827 gzio->err = -1;
828 return;
829 }
830 while (j--)
831 ll[i++] = 0;
832 l = 0;
833 }
834 else
835 /* j == 18: 11 to 138 zero length codes */
836 {
837 NEEDBITS (7);
838 j = 11 + ((unsigned) b & 0x7f);
839 DUMPBITS (7);
840 if ((unsigned) i + j > n)
841 {
842 gzio->err = -1;
843 return;
844 }
845 while (j--)
846 ll[i++] = 0;
847 l = 0;
848 }
849 }
850
851 /* free decoding table for trees */
852 huft_free (gzio->tl);
853 gzio->td = 0;
854 gzio->tl = 0;
855
856 /* restore the global bit buffer */
857 gzio->bb = b;
858 gzio->bk = k;
859
860 /* build the decoding tables for literal/length and distance codes */
861 gzio->bl = lbits;
862 if (huft_build (ll, nl, 257, cplens, cplext, &gzio->tl, &gzio->bl) != 0)
863 {
864 gzio->err = -1;
865 return;
866 }
867 gzio->bd = dbits;
868 if (huft_build (ll + nl, nd, 0, cpdist, cpdext, &gzio->td, &gzio->bd) != 0)
869 {
870 huft_free (gzio->tl);
871 gzio->tl = 0;
872 gzio->err = -1;
873 return;
874 }
875
876 /* indicate we're now working on a block */
877 gzio->code_state = 0;
878 gzio->block_len++;
879 }
880
881
882 static void
883 get_new_block (grub_gzio_t gzio)
884 {
885 register ulg b; /* bit buffer */
886 register unsigned k; /* number of bits in bit buffer */
887
888 /* make local bit buffer */
889 b = gzio->bb;
890 k = gzio->bk;
891
892 /* read in last block bit */
893 NEEDBITS (1);
894 gzio->last_block = (int) b & 1;
895 DUMPBITS (1);
896
897 /* read in block type */
898 NEEDBITS (2);
899 gzio->block_type = (unsigned) b & 3;
900 DUMPBITS (2);
901
902 /* restore the global bit buffer */
903 gzio->bb = b;
904 gzio->bk = k;
905
906 switch (gzio->block_type)
907 {
908 case INFLATE_STORED:
909 init_stored_block (gzio);
910 break;
911 case INFLATE_FIXED:
912 init_fixed_block (gzio);
913 break;
914 case INFLATE_DYNAMIC:
915 init_dynamic_block (gzio);
916 break;
917 default:
918 break;
919 }
920 }
921
922
923 static void
924 inflate_window (grub_gzio_t gzio)
925 {
926 /* initialize window */
927 gzio->wp = 0;
928
929 /*
930 * Main decompression loop.
931 */
932
933 while (gzio->wp < WSIZE && !gzio->err)
934 {
935 if (! gzio->block_len)
936 {
937 if (gzio->last_block)
938 break;
939
940 get_new_block (gzio);
941 }
942
943 if (gzio->block_type > INFLATE_DYNAMIC)
944 gzio->err = -1;
945
946 if (gzio->err)
947 return;
948
949 /*
950 * Expand stored block here.
951 */
952 if (gzio->block_type == INFLATE_STORED)
953 {
954 int w = gzio->wp;
955
956 /*
957 * This is basically a glorified pass-through
958 */
959
960 while (gzio->block_len && w < WSIZE && !gzio->err)
961 {
962 gzio->slide[w++] = get_byte (gzio);
963 gzio->block_len--;
964 }
965
966 gzio->wp = w;
967
968 continue;
969 }
970
971 /*
972 * Expand other kind of block.
973 */
974
975 if (inflate_codes_in_window (gzio))
976 {
977 huft_free (gzio->tl);
978 huft_free (gzio->td);
979 gzio->tl = 0;
980 gzio->td = 0;
981 }
982 }
983
984 gzio->saved_offset += WSIZE;
985
986 /* XXX do CRC calculation here! */
987 }
988
989
990 static void
991 initialize_tables (grub_gzio_t gzio)
992 {
993 gzio->saved_offset = 0;
994 gzio_seek (gzio, gzio->data_offset);
995
996 /* Initialize the bit buffer. */
997 gzio->bk = 0;
998 gzio->bb = 0;
999
1000 /* Reset partial decompression code. */
1001 gzio->last_block = 0;
1002 gzio->block_len = 0;
1003
1004 /* Reset memory allocation stuff. */
1005 huft_free (gzio->tl);
1006 huft_free (gzio->td);
1007 }
1008
1009
1010 static int
1011 test_zlib_header (grub_gzio_t gzio)
1012 {
1013 uint8_t cmf, flg;
1014
1015 cmf = get_byte (gzio);
1016 flg = get_byte (gzio);
1017
1018 /* Check that compression method is DEFLATE. */
1019 if ((cmf & 0xf) != DEFLATED)
1020 {
1021 return 0;
1022 }
1023
1024 if ((cmf * 256 + flg) % 31)
1025 {
1026 return 0;
1027 }
1028
1029 /* Dictionary isn't supported. */
1030 if (flg & 0x20)
1031 {
1032 return 0;
1033 }
1034
1035 gzio->data_offset = 2;
1036 initialize_tables (gzio);
1037
1038 return 1;
1039 }
1040
1041 static grub_ssize_t
1042 grub_gzio_read_real (grub_gzio_t gzio, grub_off_t offset,
1043 char *buf, grub_size_t len)
1044 {
1045 grub_ssize_t ret = 0;
1046
1047 /* Do we reset decompression to the beginning of the file? */
1048 if (gzio->saved_offset > offset + WSIZE)
1049 initialize_tables (gzio);
1050
1051 /*
1052 * This loop operates upon uncompressed data only. The only
1053 * special thing it does is to make sure the decompression
1054 * window is within the range of data it needs.
1055 */
1056
1057 while (len > 0 && !gzio->err)
1058 {
1059 register grub_size_t size;
1060 register char *srcaddr;
1061
1062 while (offset >= gzio->saved_offset)
1063 inflate_window (gzio);
1064
1065 srcaddr = (char *) ((offset & (WSIZE - 1)) + gzio->slide);
1066 size = gzio->saved_offset - offset;
1067 if (size > len)
1068 size = len;
1069
1070 fsw_memcpy (buf, srcaddr, size);
1071
1072 buf += size;
1073 len -= size;
1074 ret += size;
1075 offset += size;
1076 }
1077
1078 if (gzio->err)
1079 ret = -1;
1080
1081 return ret;
1082 }
1083
1084 grub_ssize_t
1085 grub_zlib_decompress (char *inbuf, grub_size_t insize, grub_off_t off,
1086 char *outbuf, grub_size_t outsize)
1087 {
1088 grub_gzio_t gzio = 0;
1089 grub_ssize_t ret;
1090
1091 gzio = AllocatePool (sizeof (*gzio));
1092 if (! gzio)
1093 return -1;
1094 fsw_memzero(gzio, sizeof(*gzio));
1095 gzio->mem_input = (uint8_t *) inbuf;
1096 gzio->mem_input_size = insize;
1097 gzio->mem_input_off = 0;
1098
1099 if (!test_zlib_header (gzio))
1100 {
1101 FreePool (gzio);
1102 return -1;
1103 }
1104
1105 ret = grub_gzio_read_real (gzio, off, outbuf, outsize);
1106 FreePool (gzio);
1107
1108 /* FIXME: Check Adler. */
1109 return ret;
1110 }
1111