inflate.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. #define DEBG(x)
  2. #define DEBG1(x)
  3. /* inflate.c -- Not copyrighted 1992 by Mark Adler
  4. version c10p1, 10 January 1993 */
  5. /*
  6. * Adapted for booting Linux by Hannu Savolainen 1993
  7. * based on gzip-1.0.3
  8. *
  9. * Nicolas Pitre <nico@cam.org>, 1999/04/14 :
  10. * Little mods for all variable to reside either into rodata or bss segments
  11. * by marking constant variables with 'const' and initializing all the others
  12. * at run-time only. This allows for the kernel uncompressor to run
  13. * directly from Flash or ROM memory on embedded systems.
  14. */
  15. /*
  16. Inflate deflated (PKZIP's method 8 compressed) data. The compression
  17. method searches for as much of the current string of bytes (up to a
  18. length of 258) in the previous 32 K bytes. If it doesn't find any
  19. matches (of at least length 3), it codes the next byte. Otherwise, it
  20. codes the length of the matched string and its distance backwards from
  21. the current position. There is a single Huffman code that codes both
  22. single bytes (called "literals") and match lengths. A second Huffman
  23. code codes the distance information, which follows a length code. Each
  24. length or distance code actually represents a base value and a number
  25. of "extra" (sometimes zero) bits to get to add to the base value. At
  26. the end of each deflated block is a special end-of-block (EOB) literal/
  27. length code. The decoding process is basically: get a literal/length
  28. code; if EOB then done; if a literal, emit the decoded byte; if a
  29. length then get the distance and emit the referred-to bytes from the
  30. sliding window of previously emitted data.
  31. There are (currently) three kinds of inflate blocks: stored, fixed, and
  32. dynamic. The compressor deals with some chunk of data at a time, and
  33. decides which method to use on a chunk-by-chunk basis. A chunk might
  34. typically be 32 K or 64 K. If the chunk is incompressible, then the
  35. "stored" method is used. In this case, the bytes are simply stored as
  36. is, eight bits per byte, with none of the above coding. The bytes are
  37. preceded by a count, since there is no longer an EOB code.
  38. If the data is compressible, then either the fixed or dynamic methods
  39. are used. In the dynamic method, the compressed data is preceded by
  40. an encoding of the literal/length and distance Huffman codes that are
  41. to be used to decode this block. The representation is itself Huffman
  42. coded, and so is preceded by a description of that code. These code
  43. descriptions take up a little space, and so for small blocks, there is
  44. a predefined set of codes, called the fixed codes. The fixed method is
  45. used if the block codes up smaller that way (usually for quite small
  46. chunks), otherwise the dynamic method is used. In the latter case, the
  47. codes are customized to the probabilities in the current block, and so
  48. can code it much better than the pre-determined fixed codes.
  49. The Huffman codes themselves are decoded using a multi-level table
  50. lookup, in order to maximize the speed of decoding plus the speed of
  51. building the decoding tables. See the comments below that precede the
  52. lbits and dbits tuning parameters.
  53. */
  54. /*
  55. Notes beyond the 1.93a appnote.txt:
  56. 1. Distance pointers never point before the beginning of the output
  57. stream.
  58. 2. Distance pointers can point back across blocks, up to 32k away.
  59. 3. There is an implied maximum of 7 bits for the bit length table and
  60. 15 bits for the actual data.
  61. 4. If only one code exists, then it is encoded using one bit. (Zero
  62. would be more efficient, but perhaps a little confusing.) If two
  63. codes exist, they are coded using one bit each (0 and 1).
  64. 5. There is no way of sending zero distance codes--a dummy must be
  65. sent if there are none. (History: a pre 2.0 version of PKZIP would
  66. store blocks with no distance codes, but this was discovered to be
  67. too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
  68. zero distance codes, which is sent as one code of zero bits in
  69. length.
  70. 6. There are up to 286 literal/length codes. Code 256 represents the
  71. end-of-block. Note however that the static length tree defines
  72. 288 codes just to fill out the Huffman codes. Codes 286 and 287
  73. cannot be used though, since there is no length base or extra bits
  74. defined for them. Similarly, there are up to 30 distance codes.
  75. However, static trees define 32 codes (all 5 bits) to fill out the
  76. Huffman codes, but the last two had better not show up in the data.
  77. 7. Unzip can check dynamic Huffman blocks for complete code sets.
  78. The exception is that a single code would not be complete (see #4).
  79. 8. The five bits following the block type is really the number of
  80. literal codes sent minus 257.
  81. 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
  82. (1+6+6). Therefore, to output three times the length, you output
  83. three codes (1+1+1), whereas to output four times the same length,
  84. you only need two codes (1+3). Hmm.
  85. 10. In the tree reconstruction algorithm, Code = Code + Increment
  86. only if BitLength(i) is not zero. (Pretty obvious.)
  87. 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
  88. 12. Note: length code 284 can represent 227-258, but length code 285
  89. really is 258. The last length deserves its own, short code
  90. since it gets used a lot in very redundant files. The length
  91. 258 is special since 258 - 3 (the min match length) is 255.
  92. 13. The literal/length and distance code bit lengths are read as a
  93. single stream of lengths. It is possible (and advantageous) for
  94. a repeat code (16, 17, or 18) to go across the boundary between
  95. the two sets of lengths.
  96. */
  97. #include <linux/compiler.h>
  98. #ifdef RCSID
  99. static char rcsid[] = "#Id: inflate.c,v 0.14 1993/06/10 13:27:04 jloup Exp #";
  100. #endif
  101. #ifndef STATIC
  102. #if defined(STDC_HEADERS) || defined(HAVE_STDLIB_H)
  103. # include <sys/types.h>
  104. # include <stdlib.h>
  105. #endif
  106. #include "gzip.h"
  107. #define STATIC
  108. #endif /* !STATIC */
  109. #ifndef INIT
  110. #define INIT
  111. #endif
  112. #define slide window
  113. /* Huffman code lookup table entry--this entry is four bytes for machines
  114. that have 16-bit pointers (e.g. PC's in the small or medium model).
  115. Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16
  116. means that v is a literal, 16 < e < 32 means that v is a pointer to
  117. the next table, which codes e - 16 bits, and lastly e == 99 indicates
  118. an unused code. If a code with e == 99 is looked up, this implies an
  119. error in the data. */
  120. struct huft {
  121. uch e; /* number of extra bits or operation */
  122. uch b; /* number of bits in this code or subcode */
  123. union {
  124. ush n; /* literal, length base, or distance base */
  125. struct huft *t; /* pointer to next level of table */
  126. } v;
  127. };
  128. /* Function prototypes */
  129. STATIC int INIT huft_build OF((unsigned *, unsigned, unsigned,
  130. const ush *, const ush *, struct huft **, int *));
  131. STATIC int INIT huft_free OF((struct huft *));
  132. STATIC int INIT inflate_codes OF((struct huft *, struct huft *, int, int));
  133. STATIC int INIT inflate_stored OF((void));
  134. STATIC int INIT inflate_fixed OF((void));
  135. STATIC int INIT inflate_dynamic OF((void));
  136. STATIC int INIT inflate_block OF((int *));
  137. STATIC int INIT inflate OF((void));
  138. /* The inflate algorithm uses a sliding 32 K byte window on the uncompressed
  139. stream to find repeated byte strings. This is implemented here as a
  140. circular buffer. The index is updated simply by incrementing and then
  141. ANDing with 0x7fff (32K-1). */
  142. /* It is left to other modules to supply the 32 K area. It is assumed
  143. to be usable as if it were declared "uch slide[32768];" or as just
  144. "uch *slide;" and then malloc'ed in the latter case. The definition
  145. must be in unzip.h, included above. */
  146. /* unsigned wp; current position in slide */
  147. #define wp outcnt
  148. #define flush_output(w) (wp=(w),flush_window())
  149. /* Tables for deflate from PKZIP's appnote.txt. */
  150. static const unsigned border[] = { /* Order of the bit length code lengths */
  151. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  152. static const ush cplens[] = { /* Copy lengths for literal codes 257..285 */
  153. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  154. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  155. /* note: see note #13 above about the 258 in this list. */
  156. static const ush cplext[] = { /* Extra bits for literal codes 257..285 */
  157. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  158. 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
  159. static const ush cpdist[] = { /* Copy offsets for distance codes 0..29 */
  160. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  161. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  162. 8193, 12289, 16385, 24577};
  163. static const ush cpdext[] = { /* Extra bits for distance codes */
  164. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  165. 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  166. 12, 12, 13, 13};
  167. /* Macros for inflate() bit peeking and grabbing.
  168. The usage is:
  169. NEEDBITS(j)
  170. x = b & mask_bits[j];
  171. DUMPBITS(j)
  172. where NEEDBITS makes sure that b has at least j bits in it, and
  173. DUMPBITS removes the bits from b. The macros use the variable k
  174. for the number of bits in b. Normally, b and k are register
  175. variables for speed, and are initialized at the beginning of a
  176. routine that uses these macros from a global bit buffer and count.
  177. If we assume that EOB will be the longest code, then we will never
  178. ask for bits with NEEDBITS that are beyond the end of the stream.
  179. So, NEEDBITS should not read any more bytes than are needed to
  180. meet the request. Then no bytes need to be "returned" to the buffer
  181. at the end of the last block.
  182. However, this assumption is not true for fixed blocks--the EOB code
  183. is 7 bits, but the other literal/length codes can be 8 or 9 bits.
  184. (The EOB code is shorter than other codes because fixed blocks are
  185. generally short. So, while a block always has an EOB, many other
  186. literal/length codes have a significantly lower probability of
  187. showing up at all.) However, by making the first table have a
  188. lookup of seven bits, the EOB code will be found in that first
  189. lookup, and so will not require that too many bits be pulled from
  190. the stream.
  191. */
  192. STATIC ulg bb; /* bit buffer */
  193. STATIC unsigned bk; /* bits in bit buffer */
  194. STATIC const ush mask_bits[] = {
  195. 0x0000,
  196. 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
  197. 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
  198. };
  199. #define NEXTBYTE() ({ int v = get_byte(); if (v < 0) goto underrun; (uch)v; })
  200. #define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE())<<k;k+=8;}}
  201. #define DUMPBITS(n) {b>>=(n);k-=(n);}
  202. /*
  203. Huffman code decoding is performed using a multi-level table lookup.
  204. The fastest way to decode is to simply build a lookup table whose
  205. size is determined by the longest code. However, the time it takes
  206. to build this table can also be a factor if the data being decoded
  207. is not very long. The most common codes are necessarily the
  208. shortest codes, so those codes dominate the decoding time, and hence
  209. the speed. The idea is you can have a shorter table that decodes the
  210. shorter, more probable codes, and then point to subsidiary tables for
  211. the longer codes. The time it costs to decode the longer codes is
  212. then traded against the time it takes to make longer tables.
  213. This results of this trade are in the variables lbits and dbits
  214. below. lbits is the number of bits the first level table for literal/
  215. length codes can decode in one step, and dbits is the same thing for
  216. the distance codes. Subsequent tables are also less than or equal to
  217. those sizes. These values may be adjusted either when all of the
  218. codes are shorter than that, in which case the longest code length in
  219. bits is used, or when the shortest code is *longer* than the requested
  220. table size, in which case the length of the shortest code in bits is
  221. used.
  222. There are two different values for the two tables, since they code a
  223. different number of possibilities each. The literal/length table
  224. codes 286 possible values, or in a flat code, a little over eight
  225. bits. The distance table codes 30 possible values, or a little less
  226. than five bits, flat. The optimum values for speed end up being
  227. about one bit more than those, so lbits is 8+1 and dbits is 5+1.
  228. The optimum values may differ though from machine to machine, and
  229. possibly even between compilers. Your mileage may vary.
  230. */
  231. STATIC const int lbits = 9; /* bits in base literal/length lookup table */
  232. STATIC const int dbits = 6; /* bits in base distance lookup table */
  233. /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
  234. #define BMAX 16 /* maximum bit length of any code (16 for explode) */
  235. #define N_MAX 288 /* maximum number of codes in any set */
  236. STATIC unsigned hufts; /* track memory usage */
  237. STATIC int INIT huft_build(
  238. unsigned *b, /* code lengths in bits (all assumed <= BMAX) */
  239. unsigned n, /* number of codes (assumed <= N_MAX) */
  240. unsigned s, /* number of simple-valued codes (0..s-1) */
  241. const ush *d, /* list of base values for non-simple codes */
  242. const ush *e, /* list of extra bits for non-simple codes */
  243. struct huft **t, /* result: starting table */
  244. int *m /* maximum lookup bits, returns actual */
  245. )
  246. /* Given a list of code lengths and a maximum table size, make a set of
  247. tables to decode that set of codes. Return zero on success, one if
  248. the given code set is incomplete (the tables are still built in this
  249. case), two if the input is invalid (all zero length codes or an
  250. oversubscribed set of lengths), and three if not enough memory. */
  251. {
  252. unsigned a; /* counter for codes of length k */
  253. unsigned c[BMAX+1]; /* bit length count table */
  254. unsigned f; /* i repeats in table every f entries */
  255. int g; /* maximum code length */
  256. int h; /* table level */
  257. register unsigned i; /* counter, current code */
  258. register unsigned j; /* counter */
  259. register int k; /* number of bits in current code */
  260. int l; /* bits per table (returned in m) */
  261. register unsigned *p; /* pointer into c[], b[], or v[] */
  262. register struct huft *q; /* points to current table */
  263. struct huft r; /* table entry for structure assignment */
  264. struct huft *u[BMAX]; /* table stack */
  265. unsigned v[N_MAX]; /* values in order of bit length */
  266. register int w; /* bits before this table == (l * h) */
  267. unsigned x[BMAX+1]; /* bit offsets, then code stack */
  268. unsigned *xp; /* pointer into x */
  269. int y; /* number of dummy codes added */
  270. unsigned z; /* number of entries in current table */
  271. DEBG("huft1 ");
  272. /* Generate counts for each bit length */
  273. memzero(c, sizeof(c));
  274. p = b; i = n;
  275. do {
  276. Tracecv(*p, (stderr, (n-i >= ' ' && n-i <= '~' ? "%c %d\n" : "0x%x %d\n"),
  277. n-i, *p));
  278. c[*p]++; /* assume all entries <= BMAX */
  279. p++; /* Can't combine with above line (Solaris bug) */
  280. } while (--i);
  281. if (c[0] == n) /* null input--all zero length codes */
  282. {
  283. *t = (struct huft *)NULL;
  284. *m = 0;
  285. return 2;
  286. }
  287. DEBG("huft2 ");
  288. /* Find minimum and maximum length, bound *m by those */
  289. l = *m;
  290. for (j = 1; j <= BMAX; j++)
  291. if (c[j])
  292. break;
  293. k = j; /* minimum code length */
  294. if ((unsigned)l < j)
  295. l = j;
  296. for (i = BMAX; i; i--)
  297. if (c[i])
  298. break;
  299. g = i; /* maximum code length */
  300. if ((unsigned)l > i)
  301. l = i;
  302. *m = l;
  303. DEBG("huft3 ");
  304. /* Adjust last length count to fill out codes, if needed */
  305. for (y = 1 << j; j < i; j++, y <<= 1)
  306. if ((y -= c[j]) < 0)
  307. return 2; /* bad input: more codes than bits */
  308. if ((y -= c[i]) < 0)
  309. return 2;
  310. c[i] += y;
  311. DEBG("huft4 ");
  312. /* Generate starting offsets into the value table for each length */
  313. x[1] = j = 0;
  314. p = c + 1; xp = x + 2;
  315. while (--i) { /* note that i == g from above */
  316. *xp++ = (j += *p++);
  317. }
  318. DEBG("huft5 ");
  319. /* Make a table of values in order of bit lengths */
  320. p = b; i = 0;
  321. do {
  322. if ((j = *p++) != 0)
  323. v[x[j]++] = i;
  324. } while (++i < n);
  325. n = x[g]; /* set n to length of v */
  326. DEBG("h6 ");
  327. /* Generate the Huffman codes and for each, make the table entries */
  328. x[0] = i = 0; /* first Huffman code is zero */
  329. p = v; /* grab values in bit order */
  330. h = -1; /* no tables yet--level -1 */
  331. w = -l; /* bits decoded == (l * h) */
  332. u[0] = (struct huft *)NULL; /* just to keep compilers happy */
  333. q = (struct huft *)NULL; /* ditto */
  334. z = 0; /* ditto */
  335. DEBG("h6a ");
  336. /* go through the bit lengths (k already is bits in shortest code) */
  337. for (; k <= g; k++)
  338. {
  339. DEBG("h6b ");
  340. a = c[k];
  341. while (a--)
  342. {
  343. DEBG("h6b1 ");
  344. /* here i is the Huffman code of length k bits for value *p */
  345. /* make tables up to required level */
  346. while (k > w + l)
  347. {
  348. DEBG1("1 ");
  349. h++;
  350. w += l; /* previous table always l bits */
  351. /* compute minimum size table less than or equal to l bits */
  352. z = (z = g - w) > (unsigned)l ? l : z; /* upper limit on table size */
  353. if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
  354. { /* too few codes for k-w bit table */
  355. DEBG1("2 ");
  356. f -= a + 1; /* deduct codes from patterns left */
  357. xp = c + k;
  358. if (j < z)
  359. while (++j < z) /* try smaller tables up to z bits */
  360. {
  361. if ((f <<= 1) <= *++xp)
  362. break; /* enough codes to use up j bits */
  363. f -= *xp; /* else deduct codes from patterns */
  364. }
  365. }
  366. DEBG1("3 ");
  367. z = 1 << j; /* table entries for j-bit table */
  368. /* allocate and link in new table */
  369. if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) ==
  370. (struct huft *)NULL)
  371. {
  372. if (h)
  373. huft_free(u[0]);
  374. return 3; /* not enough memory */
  375. }
  376. DEBG1("4 ");
  377. hufts += z + 1; /* track memory usage */
  378. *t = q + 1; /* link to list for huft_free() */
  379. *(t = &(q->v.t)) = (struct huft *)NULL;
  380. u[h] = ++q; /* table starts after link */
  381. DEBG1("5 ");
  382. /* connect to last table, if there is one */
  383. if (h)
  384. {
  385. x[h] = i; /* save pattern for backing up */
  386. r.b = (uch)l; /* bits to dump before this table */
  387. r.e = (uch)(16 + j); /* bits in this table */
  388. r.v.t = q; /* pointer to this table */
  389. j = i >> (w - l); /* (get around Turbo C bug) */
  390. u[h-1][j] = r; /* connect to last table */
  391. }
  392. DEBG1("6 ");
  393. }
  394. DEBG("h6c ");
  395. /* set up table entry in r */
  396. r.b = (uch)(k - w);
  397. if (p >= v + n)
  398. r.e = 99; /* out of values--invalid code */
  399. else if (*p < s)
  400. {
  401. r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */
  402. r.v.n = (ush)(*p); /* simple code is just the value */
  403. p++; /* one compiler does not like *p++ */
  404. }
  405. else
  406. {
  407. r.e = (uch)e[*p - s]; /* non-simple--look up in lists */
  408. r.v.n = d[*p++ - s];
  409. }
  410. DEBG("h6d ");
  411. /* fill code-like entries with r */
  412. f = 1 << (k - w);
  413. for (j = i >> w; j < z; j += f)
  414. q[j] = r;
  415. /* backwards increment the k-bit code i */
  416. for (j = 1 << (k - 1); i & j; j >>= 1)
  417. i ^= j;
  418. i ^= j;
  419. /* backup over finished tables */
  420. while ((i & ((1 << w) - 1)) != x[h])
  421. {
  422. h--; /* don't need to update q */
  423. w -= l;
  424. }
  425. DEBG("h6e ");
  426. }
  427. DEBG("h6f ");
  428. }
  429. DEBG("huft7 ");
  430. /* Return true (1) if we were given an incomplete table */
  431. return y != 0 && g != 1;
  432. }
  433. STATIC int INIT huft_free(
  434. struct huft *t /* table to free */
  435. )
  436. /* Free the malloc'ed tables built by huft_build(), which makes a linked
  437. list of the tables it made, with the links in a dummy first entry of
  438. each table. */
  439. {
  440. register struct huft *p, *q;
  441. /* Go through linked list, freeing from the malloced (t[-1]) address. */
  442. p = t;
  443. while (p != (struct huft *)NULL)
  444. {
  445. q = (--p)->v.t;
  446. free((char*)p);
  447. p = q;
  448. }
  449. return 0;
  450. }
  451. STATIC int INIT inflate_codes(
  452. struct huft *tl, /* literal/length decoder tables */
  453. struct huft *td, /* distance decoder tables */
  454. int bl, /* number of bits decoded by tl[] */
  455. int bd /* number of bits decoded by td[] */
  456. )
  457. /* inflate (decompress) the codes in a deflated (compressed) block.
  458. Return an error code or zero if it all goes ok. */
  459. {
  460. register unsigned e; /* table entry flag/number of extra bits */
  461. unsigned n, d; /* length and index for copy */
  462. unsigned w; /* current window position */
  463. struct huft *t; /* pointer to table entry */
  464. unsigned ml, md; /* masks for bl and bd bits */
  465. register ulg b; /* bit buffer */
  466. register unsigned k; /* number of bits in bit buffer */
  467. /* make local copies of globals */
  468. b = bb; /* initialize bit buffer */
  469. k = bk;
  470. w = wp; /* initialize window position */
  471. /* inflate the coded data */
  472. ml = mask_bits[bl]; /* precompute masks for speed */
  473. md = mask_bits[bd];
  474. for (;;) /* do until end of block */
  475. {
  476. NEEDBITS((unsigned)bl)
  477. if ((e = (t = tl + ((unsigned)b & ml))->e) > 16)
  478. do {
  479. if (e == 99)
  480. return 1;
  481. DUMPBITS(t->b)
  482. e -= 16;
  483. NEEDBITS(e)
  484. } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16);
  485. DUMPBITS(t->b)
  486. if (e == 16) /* then it's a literal */
  487. {
  488. slide[w++] = (uch)t->v.n;
  489. Tracevv((stderr, "%c", slide[w-1]));
  490. if (w == WSIZE)
  491. {
  492. flush_output(w);
  493. w = 0;
  494. }
  495. }
  496. else /* it's an EOB or a length */
  497. {
  498. /* exit if end of block */
  499. if (e == 15)
  500. break;
  501. /* get length of block to copy */
  502. NEEDBITS(e)
  503. n = t->v.n + ((unsigned)b & mask_bits[e]);
  504. DUMPBITS(e);
  505. /* decode distance of block to copy */
  506. NEEDBITS((unsigned)bd)
  507. if ((e = (t = td + ((unsigned)b & md))->e) > 16)
  508. do {
  509. if (e == 99)
  510. return 1;
  511. DUMPBITS(t->b)
  512. e -= 16;
  513. NEEDBITS(e)
  514. } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16);
  515. DUMPBITS(t->b)
  516. NEEDBITS(e)
  517. d = w - t->v.n - ((unsigned)b & mask_bits[e]);
  518. DUMPBITS(e)
  519. Tracevv((stderr,"\\[%d,%d]", w-d, n));
  520. /* do the copy */
  521. do {
  522. n -= (e = (e = WSIZE - ((d &= WSIZE-1) > w ? d : w)) > n ? n : e);
  523. #if !defined(NOMEMCPY) && !defined(DEBUG)
  524. if (w - d >= e) /* (this test assumes unsigned comparison) */
  525. {
  526. memcpy(slide + w, slide + d, e);
  527. w += e;
  528. d += e;
  529. }
  530. else /* do it slow to avoid memcpy() overlap */
  531. #endif /* !NOMEMCPY */
  532. do {
  533. slide[w++] = slide[d++];
  534. Tracevv((stderr, "%c", slide[w-1]));
  535. } while (--e);
  536. if (w == WSIZE)
  537. {
  538. flush_output(w);
  539. w = 0;
  540. }
  541. } while (n);
  542. }
  543. }
  544. /* restore the globals from the locals */
  545. wp = w; /* restore global window pointer */
  546. bb = b; /* restore global bit buffer */
  547. bk = k;
  548. /* done */
  549. return 0;
  550. underrun:
  551. return 4; /* Input underrun */
  552. }
  553. STATIC int INIT inflate_stored(void)
  554. /* "decompress" an inflated type 0 (stored) block. */
  555. {
  556. unsigned n; /* number of bytes in block */
  557. unsigned w; /* current window position */
  558. register ulg b; /* bit buffer */
  559. register unsigned k; /* number of bits in bit buffer */
  560. DEBG("<stor");
  561. /* make local copies of globals */
  562. b = bb; /* initialize bit buffer */
  563. k = bk;
  564. w = wp; /* initialize window position */
  565. /* go to byte boundary */
  566. n = k & 7;
  567. DUMPBITS(n);
  568. /* get the length and its complement */
  569. NEEDBITS(16)
  570. n = ((unsigned)b & 0xffff);
  571. DUMPBITS(16)
  572. NEEDBITS(16)
  573. if (n != (unsigned)((~b) & 0xffff))
  574. return 1; /* error in compressed data */
  575. DUMPBITS(16)
  576. /* read and output the compressed data */
  577. while (n--)
  578. {
  579. NEEDBITS(8)
  580. slide[w++] = (uch)b;
  581. if (w == WSIZE)
  582. {
  583. flush_output(w);
  584. w = 0;
  585. }
  586. DUMPBITS(8)
  587. }
  588. /* restore the globals from the locals */
  589. wp = w; /* restore global window pointer */
  590. bb = b; /* restore global bit buffer */
  591. bk = k;
  592. DEBG(">");
  593. return 0;
  594. underrun:
  595. return 4; /* Input underrun */
  596. }
  597. /*
  598. * We use `noinline' here to prevent gcc-3.5 from using too much stack space
  599. */
  600. STATIC int noinline INIT inflate_fixed(void)
  601. /* decompress an inflated type 1 (fixed Huffman codes) block. We should
  602. either replace this with a custom decoder, or at least precompute the
  603. Huffman tables. */
  604. {
  605. int i; /* temporary variable */
  606. struct huft *tl; /* literal/length code table */
  607. struct huft *td; /* distance code table */
  608. int bl; /* lookup bits for tl */
  609. int bd; /* lookup bits for td */
  610. unsigned l[288]; /* length list for huft_build */
  611. DEBG("<fix");
  612. /* set up literal table */
  613. for (i = 0; i < 144; i++)
  614. l[i] = 8;
  615. for (; i < 256; i++)
  616. l[i] = 9;
  617. for (; i < 280; i++)
  618. l[i] = 7;
  619. for (; i < 288; i++) /* make a complete, but wrong code set */
  620. l[i] = 8;
  621. bl = 7;
  622. if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0)
  623. return i;
  624. /* set up distance table */
  625. for (i = 0; i < 30; i++) /* make an incomplete code set */
  626. l[i] = 5;
  627. bd = 5;
  628. if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1)
  629. {
  630. huft_free(tl);
  631. DEBG(">");
  632. return i;
  633. }
  634. /* decompress until an end-of-block code */
  635. if (inflate_codes(tl, td, bl, bd))
  636. return 1;
  637. /* free the decoding tables, return */
  638. huft_free(tl);
  639. huft_free(td);
  640. return 0;
  641. }
  642. /*
  643. * We use `noinline' here to prevent gcc-3.5 from using too much stack space
  644. */
  645. STATIC int noinline INIT inflate_dynamic(void)
  646. /* decompress an inflated type 2 (dynamic Huffman codes) block. */
  647. {
  648. int i; /* temporary variables */
  649. unsigned j;
  650. unsigned l; /* last length */
  651. unsigned m; /* mask for bit lengths table */
  652. unsigned n; /* number of lengths to get */
  653. struct huft *tl; /* literal/length code table */
  654. struct huft *td; /* distance code table */
  655. int bl; /* lookup bits for tl */
  656. int bd; /* lookup bits for td */
  657. unsigned nb; /* number of bit length codes */
  658. unsigned nl; /* number of literal/length codes */
  659. unsigned nd; /* number of distance codes */
  660. #ifdef PKZIP_BUG_WORKAROUND
  661. unsigned ll[288+32]; /* literal/length and distance code lengths */
  662. #else
  663. unsigned ll[286+30]; /* literal/length and distance code lengths */
  664. #endif
  665. register ulg b; /* bit buffer */
  666. register unsigned k; /* number of bits in bit buffer */
  667. DEBG("<dyn");
  668. /* make local bit buffer */
  669. b = bb;
  670. k = bk;
  671. /* read in table lengths */
  672. NEEDBITS(5)
  673. nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */
  674. DUMPBITS(5)
  675. NEEDBITS(5)
  676. nd = 1 + ((unsigned)b & 0x1f); /* number of distance codes */
  677. DUMPBITS(5)
  678. NEEDBITS(4)
  679. nb = 4 + ((unsigned)b & 0xf); /* number of bit length codes */
  680. DUMPBITS(4)
  681. #ifdef PKZIP_BUG_WORKAROUND
  682. if (nl > 288 || nd > 32)
  683. #else
  684. if (nl > 286 || nd > 30)
  685. #endif
  686. return 1; /* bad lengths */
  687. DEBG("dyn1 ");
  688. /* read in bit-length-code lengths */
  689. for (j = 0; j < nb; j++)
  690. {
  691. NEEDBITS(3)
  692. ll[border[j]] = (unsigned)b & 7;
  693. DUMPBITS(3)
  694. }
  695. for (; j < 19; j++)
  696. ll[border[j]] = 0;
  697. DEBG("dyn2 ");
  698. /* build decoding table for trees--single level, 7 bit lookup */
  699. bl = 7;
  700. if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0)
  701. {
  702. if (i == 1)
  703. huft_free(tl);
  704. return i; /* incomplete code set */
  705. }
  706. DEBG("dyn3 ");
  707. /* read in literal and distance code lengths */
  708. n = nl + nd;
  709. m = mask_bits[bl];
  710. i = l = 0;
  711. while ((unsigned)i < n)
  712. {
  713. NEEDBITS((unsigned)bl)
  714. j = (td = tl + ((unsigned)b & m))->b;
  715. DUMPBITS(j)
  716. j = td->v.n;
  717. if (j < 16) /* length of code in bits (0..15) */
  718. ll[i++] = l = j; /* save last length in l */
  719. else if (j == 16) /* repeat last length 3 to 6 times */
  720. {
  721. NEEDBITS(2)
  722. j = 3 + ((unsigned)b & 3);
  723. DUMPBITS(2)
  724. if ((unsigned)i + j > n)
  725. return 1;
  726. while (j--)
  727. ll[i++] = l;
  728. }
  729. else if (j == 17) /* 3 to 10 zero length codes */
  730. {
  731. NEEDBITS(3)
  732. j = 3 + ((unsigned)b & 7);
  733. DUMPBITS(3)
  734. if ((unsigned)i + j > n)
  735. return 1;
  736. while (j--)
  737. ll[i++] = 0;
  738. l = 0;
  739. }
  740. else /* j == 18: 11 to 138 zero length codes */
  741. {
  742. NEEDBITS(7)
  743. j = 11 + ((unsigned)b & 0x7f);
  744. DUMPBITS(7)
  745. if ((unsigned)i + j > n)
  746. return 1;
  747. while (j--)
  748. ll[i++] = 0;
  749. l = 0;
  750. }
  751. }
  752. DEBG("dyn4 ");
  753. /* free decoding table for trees */
  754. huft_free(tl);
  755. DEBG("dyn5 ");
  756. /* restore the global bit buffer */
  757. bb = b;
  758. bk = k;
  759. DEBG("dyn5a ");
  760. /* build the decoding tables for literal/length and distance codes */
  761. bl = lbits;
  762. if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0)
  763. {
  764. DEBG("dyn5b ");
  765. if (i == 1) {
  766. error("incomplete literal tree");
  767. huft_free(tl);
  768. }
  769. return i; /* incomplete code set */
  770. }
  771. DEBG("dyn5c ");
  772. bd = dbits;
  773. if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0)
  774. {
  775. DEBG("dyn5d ");
  776. if (i == 1) {
  777. error("incomplete distance tree");
  778. #ifdef PKZIP_BUG_WORKAROUND
  779. i = 0;
  780. }
  781. #else
  782. huft_free(td);
  783. }
  784. huft_free(tl);
  785. return i; /* incomplete code set */
  786. #endif
  787. }
  788. DEBG("dyn6 ");
  789. /* decompress until an end-of-block code */
  790. if (inflate_codes(tl, td, bl, bd))
  791. return 1;
  792. DEBG("dyn7 ");
  793. /* free the decoding tables, return */
  794. huft_free(tl);
  795. huft_free(td);
  796. DEBG(">");
  797. return 0;
  798. underrun:
  799. return 4; /* Input underrun */
  800. }
  801. STATIC int INIT inflate_block(
  802. int *e /* last block flag */
  803. )
  804. /* decompress an inflated block */
  805. {
  806. unsigned t; /* block type */
  807. register ulg b; /* bit buffer */
  808. register unsigned k; /* number of bits in bit buffer */
  809. DEBG("<blk");
  810. /* make local bit buffer */
  811. b = bb;
  812. k = bk;
  813. /* read in last block bit */
  814. NEEDBITS(1)
  815. *e = (int)b & 1;
  816. DUMPBITS(1)
  817. /* read in block type */
  818. NEEDBITS(2)
  819. t = (unsigned)b & 3;
  820. DUMPBITS(2)
  821. /* restore the global bit buffer */
  822. bb = b;
  823. bk = k;
  824. /* inflate that block type */
  825. if (t == 2)
  826. return inflate_dynamic();
  827. if (t == 0)
  828. return inflate_stored();
  829. if (t == 1)
  830. return inflate_fixed();
  831. DEBG(">");
  832. /* bad block type */
  833. return 2;
  834. underrun:
  835. return 4; /* Input underrun */
  836. }
  837. STATIC int INIT inflate(void)
  838. /* decompress an inflated entry */
  839. {
  840. int e; /* last block flag */
  841. int r; /* result code */
  842. unsigned h; /* maximum struct huft's malloc'ed */
  843. void *ptr;
  844. /* initialize window, bit buffer */
  845. wp = 0;
  846. bk = 0;
  847. bb = 0;
  848. /* decompress until the last block */
  849. h = 0;
  850. do {
  851. hufts = 0;
  852. gzip_mark(&ptr);
  853. if ((r = inflate_block(&e)) != 0) {
  854. gzip_release(&ptr);
  855. return r;
  856. }
  857. gzip_release(&ptr);
  858. if (hufts > h)
  859. h = hufts;
  860. } while (!e);
  861. /* Undo too much lookahead. The next read will be byte aligned so we
  862. * can discard unused bits in the last meaningful byte.
  863. */
  864. while (bk >= 8) {
  865. bk -= 8;
  866. inptr--;
  867. }
  868. /* flush out slide */
  869. flush_output(wp);
  870. /* return success */
  871. #ifdef DEBUG
  872. fprintf(stderr, "<%u> ", h);
  873. #endif /* DEBUG */
  874. return 0;
  875. }
  876. /**********************************************************************
  877. *
  878. * The following are support routines for inflate.c
  879. *
  880. **********************************************************************/
  881. static ulg crc_32_tab[256];
  882. static ulg crc; /* initialized in makecrc() so it'll reside in bss */
  883. #define CRC_VALUE (crc ^ 0xffffffffUL)
  884. /*
  885. * Code to compute the CRC-32 table. Borrowed from
  886. * gzip-1.0.3/makecrc.c.
  887. */
  888. static void INIT
  889. makecrc(void)
  890. {
  891. /* Not copyrighted 1990 Mark Adler */
  892. unsigned long c; /* crc shift register */
  893. unsigned long e; /* polynomial exclusive-or pattern */
  894. int i; /* counter for all possible eight bit values */
  895. int k; /* byte being shifted into crc apparatus */
  896. /* terms of polynomial defining this crc (except x^32): */
  897. static const int p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  898. /* Make exclusive-or pattern from polynomial */
  899. e = 0;
  900. for (i = 0; i < sizeof(p)/sizeof(int); i++)
  901. e |= 1L << (31 - p[i]);
  902. crc_32_tab[0] = 0;
  903. for (i = 1; i < 256; i++)
  904. {
  905. c = 0;
  906. for (k = i | 256; k != 1; k >>= 1)
  907. {
  908. c = c & 1 ? (c >> 1) ^ e : c >> 1;
  909. if (k & 1)
  910. c ^= e;
  911. }
  912. crc_32_tab[i] = c;
  913. }
  914. /* this is initialized here so this code could reside in ROM */
  915. crc = (ulg)0xffffffffUL; /* shift register contents */
  916. }
  917. /* gzip flag byte */
  918. #define ASCII_FLAG 0x01 /* bit 0 set: file probably ASCII text */
  919. #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
  920. #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
  921. #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
  922. #define COMMENT 0x10 /* bit 4 set: file comment present */
  923. #define ENCRYPTED 0x20 /* bit 5 set: file is encrypted */
  924. #define RESERVED 0xC0 /* bit 6,7: reserved */
  925. /*
  926. * Do the uncompression!
  927. */
  928. static int INIT gunzip(void)
  929. {
  930. uch flags;
  931. unsigned char magic[2]; /* magic header */
  932. char method;
  933. ulg orig_crc = 0; /* original crc */
  934. ulg orig_len = 0; /* original uncompressed length */
  935. int res;
  936. magic[0] = NEXTBYTE();
  937. magic[1] = NEXTBYTE();
  938. method = NEXTBYTE();
  939. if (magic[0] != 037 ||
  940. ((magic[1] != 0213) && (magic[1] != 0236))) {
  941. error("bad gzip magic numbers");
  942. return -1;
  943. }
  944. /* We only support method #8, DEFLATED */
  945. if (method != 8) {
  946. error("internal error, invalid method");
  947. return -1;
  948. }
  949. flags = (uch)get_byte();
  950. if ((flags & ENCRYPTED) != 0) {
  951. error("Input is encrypted");
  952. return -1;
  953. }
  954. if ((flags & CONTINUATION) != 0) {
  955. error("Multi part input");
  956. return -1;
  957. }
  958. if ((flags & RESERVED) != 0) {
  959. error("Input has invalid flags");
  960. return -1;
  961. }
  962. NEXTBYTE(); /* Get timestamp */
  963. NEXTBYTE();
  964. NEXTBYTE();
  965. NEXTBYTE();
  966. (void)NEXTBYTE(); /* Ignore extra flags for the moment */
  967. (void)NEXTBYTE(); /* Ignore OS type for the moment */
  968. if ((flags & EXTRA_FIELD) != 0) {
  969. unsigned len = (unsigned)NEXTBYTE();
  970. len |= ((unsigned)NEXTBYTE())<<8;
  971. while (len--) (void)NEXTBYTE();
  972. }
  973. /* Get original file name if it was truncated */
  974. if ((flags & ORIG_NAME) != 0) {
  975. /* Discard the old name */
  976. while (NEXTBYTE() != 0) /* null */ ;
  977. }
  978. /* Discard file comment if any */
  979. if ((flags & COMMENT) != 0) {
  980. while (NEXTBYTE() != 0) /* null */ ;
  981. }
  982. /* Decompress */
  983. if ((res = inflate())) {
  984. switch (res) {
  985. case 0:
  986. break;
  987. case 1:
  988. error("invalid compressed format (err=1)");
  989. break;
  990. case 2:
  991. error("invalid compressed format (err=2)");
  992. break;
  993. case 3:
  994. error("out of memory");
  995. break;
  996. case 4:
  997. error("out of input data");
  998. break;
  999. default:
  1000. error("invalid compressed format (other)");
  1001. }
  1002. return -1;
  1003. }
  1004. /* Get the crc and original length */
  1005. /* crc32 (see algorithm.doc)
  1006. * uncompressed input size modulo 2^32
  1007. */
  1008. orig_crc = (ulg) NEXTBYTE();
  1009. orig_crc |= (ulg) NEXTBYTE() << 8;
  1010. orig_crc |= (ulg) NEXTBYTE() << 16;
  1011. orig_crc |= (ulg) NEXTBYTE() << 24;
  1012. orig_len = (ulg) NEXTBYTE();
  1013. orig_len |= (ulg) NEXTBYTE() << 8;
  1014. orig_len |= (ulg) NEXTBYTE() << 16;
  1015. orig_len |= (ulg) NEXTBYTE() << 24;
  1016. /* Validate decompression */
  1017. if (orig_crc != CRC_VALUE) {
  1018. error("crc error");
  1019. return -1;
  1020. }
  1021. if (orig_len != bytes_out) {
  1022. error("length error");
  1023. return -1;
  1024. }
  1025. return 0;
  1026. underrun: /* NEXTBYTE() goto's here if needed */
  1027. error("out of input data");
  1028. return -1;
  1029. }