/*1* inflate.c - inflate decompression routine2*3* Version 1.1.24*/56/*7* Copyright (C) 1995, Edward B. Hamrick8*9* Permission to use, copy, modify, and distribute this software and10* its documentation for any purpose and without fee is hereby granted,11* provided that the above copyright notice appear in all copies and12* that both that copyright notice and this permission notice appear in13* supporting documentation, and that the name of the copyright holders14* not be used in advertising or publicity pertaining to distribution of15* the software without specific, written prior permission. The copyright16* holders makes no representations about the suitability of this software17* for any purpose. It is provided "as is" without express or implied warranty.18*19* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS20* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,21* IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT22* OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF23* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER24* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE25* OF THIS SOFTWARE.26*/2728/*29* Changes from 1.1 to 1.1.2:30* Relicensed under the MIT license, with consent of the copyright holders.31* Claudio Matsuoka (Jan 11 2011)32*/3334/*35* inflate.c is based on the public-domain (non-copyrighted) version36* written by Mark Adler, version c14o, 23 August 1994. It has been37* modified to be reentrant, more portable, and to be data driven.38*/3940/*41* 1) All file i/o is done externally to these routines42* 2) Routines are symmetrical so inflate can feed into deflate43* 3) Routines can be easily integrated into wide range of applications44* 4) Routines are very portable, and use only ANSI C45* 5) No #defines in inflate.h to conflict with external #defines46* 6) No external routines need be called by these routines47* 7) Buffers are owned by the calling routine48* 8) No static non-constant variables are allowed49*/5051/*52* Note that for each call to InflatePutBuffer, there will be53* 0 or more calls to (*putbuffer_ptr). Before InflatePutBuffer54* returns, it will have output as much uncompressed data as55* is possible.56*/5758#ifdef MEMCPY59#include <mem.h>60#endif6162#include "inflate.h"6364/*65* Macros for constants66*/6768#ifndef NULL69#define NULL ((void *) 0)70#endif7172#ifndef TRUE73#define TRUE 174#endif7576#ifndef FALSE77#define FALSE 078#endif7980#ifndef WINDOWSIZE81#define WINDOWSIZE 0x800082#endif8384#ifndef WINDOWMASK85#define WINDOWMASK 0x7fff86#endif8788#ifndef BUFFERSIZE89#define BUFFERSIZE 0x400090#endif9192#ifndef BUFFERMASK93#define BUFFERMASK 0x3fff94#endif9596#ifndef INFLATESTATETYPE97#define INFLATESTATETYPE 0xabcdabcdL98#endif99100/*101* typedefs102*/103104typedef unsigned long ulg;105typedef unsigned short ush;106typedef unsigned char uch;107108/* Structure to hold state for inflating zip files */109struct InflateState {110111unsigned long runtimetypeid1; /* to detect run-time errors */112int errorencountered; /* error encountered flag */113114/* Decoding state */115int state; /* -1 -> need block type */116/* 0 -> need stored setup */117/* 1 -> need fixed setup */118/* 2 -> need dynamic setup */119/* 10 -> need stored data */120/* 11 -> need fixed data */121/* 12 -> need dynamic data */122123/* State for decoding fixed & dynamic data */124struct huft *tl; /* literal/length decoder tbl */125struct huft *td; /* distance decoder table */126int bl; /* bits decoded by tl */127int bd; /* bits decoded by td */128129/* State for decoding stored data */130unsigned int storelength;131132/* State to keep track that last block has been encountered */133int lastblock; /* current block is last */134135/* Input buffer state (circular) */136ulg bb; /* input buffer bits */137unsigned int bk; /* input buffer count of bits */138unsigned int bp; /* input buffer pointer */139unsigned int bs; /* input buffer size */140unsigned char buffer[BUFFERSIZE]; /* input buffer data */141142/* Storage for try/catch */143ulg catch_bb; /* bit buffer */144unsigned int catch_bk; /* bits in bit buffer */145unsigned int catch_bp; /* buffer pointer */146unsigned int catch_bs; /* buffer size */147148/* Output window state (circular) */149unsigned int wp; /* output window pointer */150unsigned int wf; /* output window flush-from */151unsigned char window[WINDOWSIZE]; /* output window data */152153/* Application state */154void *AppState; /* opaque ptr for callout */155156/* pointers to call-outs */157int (*putbuffer_ptr)( /* returns 0 on success */158void *AppState, /* opaque ptr from Initialize */159unsigned char *buffer, /* buffer to put */160long length /* length of buffer */161);162163void *(*malloc_ptr)(long length); /* utility routine */164165void (*free_ptr)(void *buffer); /* utility routine */166167unsigned long runtimetypeid2; /* to detect run-time errors */168};169170/*171* Error handling macro172*/173174#define ERROREXIT(is) {(is)->errorencountered = TRUE; return TRUE;}175176/*177* Macros for handling data in the input buffer178*179* Note that the NEEDBITS and DUMPBITS macros180* need to be bracketed by the TRY/CATCH macros181*182* The usage is:183*184* TRY185* {186* NEEDBITS(j)187* x = b & mask_bits[j];188* DUMPBITS(j)189* }190* CATCH_BEGIN191* cleanup code192* CATCH_END193*194* Note that there can only be one TRY/CATCH pair per routine195* because of the use of goto in the implementation of the macros.196*197* NEEDBITS makes sure that b has at least j bits in it, and198* DUMPBITS removes the bits from b. The macros use the variable k199* for the number of bits in b. Normally, b and k are register200* variables for speed, and are initialized at the beginning of a201* routine that uses these macros from a global bit buffer and count.202*203* In order to not ask for more bits than there are in the compressed204* stream, the Huffman tables are constructed to only ask for just205* enough bits to make up the end-of-block code (value 256). Then no206* bytes need to be "returned" to the buffer at the end of the last207* block. See the huft_build() routine.208*/209210#define TRY \211is->catch_bb = b; \212is->catch_bk = k; \213is->catch_bp = is->bp; \214is->catch_bs = is->bs;215216#define CATCH_BEGIN \217goto cleanup_done; \218cleanup: \219b = is->catch_bb; \220k = is->catch_bk; \221is->bb = b; \222is->bk = k; \223is->bp = is->catch_bp; \224is->bs = is->catch_bs;225226#define CATCH_END \227cleanup_done: ;228229#define NEEDBITS(n) \230{ \231while (k < (n)) \232{ \233if (is->bs <= 0) \234{ \235goto cleanup; \236} \237b |= ((ulg) (is->buffer[is->bp & BUFFERMASK])) << k; \238is->bs--; \239is->bp++; \240k += 8; \241} \242}243244#define DUMPBITS(n) \245{ \246b >>= (n); \247k -= (n); \248}249250/*251* Macro for flushing the output window to the putbuffer callout.252*253* Note that the window is always flushed when it fills to 32K,254* and before returning to the application.255*/256257#define FLUSHWINDOW(w, now) \258if ((now && (is->wp > is->wf)) || ((w) >= WINDOWSIZE)) \259{ \260is->wp = (w); \261if ((*(is->putbuffer_ptr)) \262(is->AppState, is->window+is->wf, is->wp-is->wf)) \263ERROREXIT(is); \264is->wp &= WINDOWMASK; \265is->wf = is->wp; \266(w) = is->wp; \267}268269/*270* Inflate deflated (PKZIP's method 8 compressed) data. The compression271* method searches for as much of the current string of bytes (up to a272* length of 258) in the previous 32K bytes. If it doesn't find any273* matches (of at least length 3), it codes the next byte. Otherwise, it274* codes the length of the matched string and its distance backwards from275* the current position. There is a single Huffman code that codes both276* single bytes (called "literals") and match lengths. A second Huffman277* code codes the distance information, which follows a length code. Each278* length or distance code actually represents a base value and a number279* of "extra" (sometimes zero) bits to get to add to the base value. At280* the end of each deflated block is a special end-of-block (EOB) literal/281* length code. The decoding process is basically: get a literal/length282* code; if EOB then done; if a literal, emit the decoded byte; if a283* length then get the distance and emit the referred-to bytes from the284* sliding window of previously emitted data.285*286* There are (currently) three kinds of inflate blocks: stored, fixed, and287* dynamic. The compressor outputs a chunk of data at a time and decides288* which method to use on a chunk-by-chunk basis. A chunk might typically289* be 32K to 64K, uncompressed. If the chunk is uncompressible, then the290* "stored" method is used. In this case, the bytes are simply stored as291* is, eight bits per byte, with none of the above coding. The bytes are292* preceded by a count, since there is no longer an EOB code.293*294* If the data is compressible, then either the fixed or dynamic methods295* are used. In the dynamic method, the compressed data is preceded by296* an encoding of the literal/length and distance Huffman codes that are297* to be used to decode this block. The representation is itself Huffman298* coded, and so is preceded by a description of that code. These code299* descriptions take up a little space, and so for small blocks, there is300* a predefined set of codes, called the fixed codes. The fixed method is301* used if the block ends up smaller that way (usually for quite small302* chunks); otherwise the dynamic method is used. In the latter case, the303* codes are customized to the probabilities in the current block and so304* can code it much better than the pre-determined fixed codes can.305*306* The Huffman codes themselves are decoded using a mutli-level table307* lookup, in order to maximize the speed of decoding plus the speed of308* building the decoding tables. See the comments below that precede the309* lbits and dbits tuning parameters.310*/311312/*313* Notes beyond the 1.93a appnote.txt:314*315* 1. Distance pointers never point before the beginning of the output316* stream.317* 2. Distance pointers can point back across blocks, up to 32k away.318* 3. There is an implied maximum of 7 bits for the bit length table and319* 15 bits for the actual data.320* 4. If only one code exists, then it is encoded using one bit. (Zero321* would be more efficient, but perhaps a little confusing.) If two322* codes exist, they are coded using one bit each (0 and 1).323* 5. There is no way of sending zero distance codes--a dummy must be324* sent if there are none. (History: a pre 2.0 version of PKZIP would325* store blocks with no distance codes, but this was discovered to be326* too harsh a criterion.) Valid only for 1.93a. 2.04c does allow327* zero distance codes, which is sent as one code of zero bits in328* length.329* 6. There are up to 286 literal/length codes. Code 256 represents the330* end-of-block. Note however that the static length tree defines331* 288 codes just to fill out the Huffman codes. Codes 286 and 287332* cannot be used though, since there is no length base or extra bits333* defined for them. Similarly, there are up to 30 distance codes.334* However, static trees define 32 codes (all 5 bits) to fill out the335* Huffman codes, but the last two had better not show up in the data.336* 7. Unzip can check dynamic Huffman blocks for complete code sets.337* The exception is that a single code would not be complete (see #4).338* 8. The five bits following the block type is really the number of339* literal codes sent minus 257.340* 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits341* (1+6+6). Therefore, to output three times the length, you output342* three codes (1+1+1), whereas to output four times the same length,343* you only need two codes (1+3). Hmm.344*10. In the tree reconstruction algorithm, Code = Code + Increment345* only if BitLength(i) is not zero. (Pretty obvious.)346*11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)347*12. Note: length code 284 can represent 227-258, but length code 285348* really is 258. The last length deserves its own, short code349* since it gets used a lot in very redundant files. The length350* 258 is special since 258 - 3 (the min match length) is 255.351*13. The literal/length and distance code bit lengths are read as a352* single stream of lengths. It is possible (and advantageous) for353* a repeat code (16, 17, or 18) to go across the boundary between354* the two sets of lengths.355*/356357/*358* Huffman code lookup table entry--this entry is four bytes for machines359* that have 16-bit pointers (e.g. PC's in the small or medium model).360* Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16361* means that v is a literal, 16 < e < 32 means that v is a pointer to362* the next table, which codes e - 16 bits, and lastly e == 99 indicates363* an unused code. If a code with e == 99 is looked up, this implies an364* error in the data.365*/366367struct huft {368uch e; /* number of extra bits or operation */369uch b; /* number of bits in this code or subcode */370union {371ush n; /* literal, length base, or distance base */372struct huft *t; /* pointer to next level of table */373} v;374};375376/*377* Tables for deflate from PKZIP's appnote.txt.378*/379380static const unsigned border[] = { /* Order of the bit length code lengths */38116, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};382383static const ush cplens[] = { /* Copy lengths for literal codes 257..285 */3843, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,38535, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};386/* note: see note #13 above about the 258 in this list. */387388static const ush cplext[] = { /* Extra bits for literal codes 257..285 */3890, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,3903, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */391392static const ush cpdist[] = { /* Copy offsets for distance codes 0..29 */3931, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,394257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,3958193, 12289, 16385, 24577};396397static const ush cpdext[] = { /* Extra bits for distance codes */3980, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,3997, 7, 8, 8, 9, 9, 10, 10, 11, 11,40012, 12, 13, 13};401402/*403* Constants for run-time computation of mask404*/405406static const ush mask_bits[] = {4070x0000,4080x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,4090x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff410};411412/*413* Huffman code decoding is performed using a multi-level table lookup.414* The fastest way to decode is to simply build a lookup table whose415* size is determined by the longest code. However, the time it takes416* to build this table can also be a factor if the data being decoded417* is not very long. The most common codes are necessarily the418* shortest codes, so those codes dominate the decoding time, and hence419* the speed. The idea is you can have a shorter table that decodes the420* shorter, more probable codes, and then point to subsidiary tables for421* the longer codes. The time it costs to decode the longer codes is422* then traded against the time it takes to make longer tables.423*424* This results of this trade are in the variables lbits and dbits425* below. lbits is the number of bits the first level table for literal/426* length codes can decode in one step, and dbits is the same thing for427* the distance codes. Subsequent tables are also less than or equal to428* those sizes. These values may be adjusted either when all of the429* codes are shorter than that, in which case the longest code length in430* bits is used, or when the shortest code is *longer* than the requested431* table size, in which case the length of the shortest code in bits is432* used.433*434* There are two different values for the two tables, since they code a435* different number of possibilities each. The literal/length table436* codes 286 possible values, or in a flat code, a little over eight437* bits. The distance table codes 30 possible values, or a little less438* than five bits, flat. The optimum values for speed end up being439* about one bit more than those, so lbits is 8+1 and dbits is 5+1.440* The optimum values may differ though from machine to machine, and441* possibly even between compilers. Your mileage may vary.442*/443444static const int lbits = 9; /* bits in base literal/length lookup table */445static const int dbits = 6; /* bits in base distance lookup table */446447/* If BMAX needs to be larger than 16, then h and x[] should be ulg. */448#define BMAX 16 /* maximum bit length of any code (16 for explode) */449#define N_MAX 288 /* maximum number of codes in any set */450451/*452* Free the malloc'ed tables built by huft_build(), which makes a linked453* list of the tables it made, with the links in a dummy first entry of454* each table.455*/456457static int huft_free(458struct InflateState *is, /* Inflate state */459struct huft *t /* table to free */460)461{462struct huft *p, *q;463464/* Go through linked list, freeing from the malloced (t[-1]) address. */465p = t;466while (p != (struct huft *)NULL)467{468q = (--p)->v.t;469(*is->free_ptr)((char*)p);470p = q;471}472return 0;473}474475/*476* Given a list of code lengths and a maximum table size, make a set of477* tables to decode that set of codes. Return zero on success, one if478* the given code set is incomplete (the tables are still built in this479* case), two if the input is invalid (all zero length codes or an480* oversubscribed set of lengths), and three if not enough memory.481* The code with value 256 is special, and the tables are constructed482* so that no bits beyond that code are fetched when that code is483* decoded.484*/485486static int huft_build(487struct InflateState *is, /* Inflate state */488unsigned *b, /* code lengths in bits (all assumed <= BMAX) */489unsigned n, /* number of codes (assumed <= N_MAX) */490unsigned s, /* number of simple-valued codes (0..s-1) */491const ush *d, /* list of base values for non-simple codes */492const ush *e, /* list of extra bits for non-simple codes */493struct huft **t, /* result: starting table */494int *m /* maximum lookup bits, returns actual */495)496{497unsigned a; /* counter for codes of length k */498unsigned c[BMAX+1]; /* bit length count table */499unsigned el; /* length of EOB code (value 256) */500unsigned f; /* i repeats in table every f entries */501int g; /* maximum code length */502int h; /* table level */503unsigned i; /* counter, current code */504unsigned j; /* counter */505int k; /* number of bits in current code */506int lx[BMAX+1]; /* memory for l[-1..BMAX-1] */507int *l = lx+1; /* stack of bits per table */508unsigned *p; /* pointer into c[], b[], or v[] */509struct huft *q; /* points to current table */510struct huft r; /* table entry for structure assignment */511struct huft *u[BMAX]; /* table stack */512unsigned v[N_MAX]; /* values in order of bit length */513int w; /* bits before this table == (l * h) */514unsigned x[BMAX+1]; /* bit offsets, then code stack */515unsigned *xp; /* pointer into x */516int y; /* number of dummy codes added */517unsigned z; /* number of entries in current table */518519/* clear the bit length count table */520for (i=0; i<(BMAX+1); i++)521{522c[i] = 0;523}524525/* Generate counts for each bit length */526el = n > 256 ? b[256] : BMAX; /* set length of EOB code, if any */527p = b; i = n;528do {529c[*p]++; p++; /* assume all entries <= BMAX */530} while (--i);531if (c[0] == n) /* null input--all zero length codes */532{533*t = (struct huft *)NULL;534*m = 0;535return 0;536}537538/* Find minimum and maximum length, bound *m by those */539for (j = 1; j <= BMAX; j++)540if (c[j])541break;542k = j; /* minimum code length */543if ((unsigned)*m < j)544*m = j;545for (i = BMAX; i; i--)546if (c[i])547break;548g = i; /* maximum code length */549if ((unsigned)*m > i)550*m = i;551552/* Adjust last length count to fill out codes, if needed */553for (y = 1 << j; j < i; j++, y <<= 1)554if ((y -= c[j]) < 0)555return 2; /* bad input: more codes than bits */556if ((y -= c[i]) < 0)557return 2;558c[i] += y;559560/* Generate starting offsets into the value table for each length */561x[1] = j = 0;562p = c + 1; xp = x + 2;563while (--i) { /* note that i == g from above */564*xp++ = (j += *p++);565}566567/* Make a table of values in order of bit lengths */568p = b; i = 0;569do {570if ((j = *p++) != 0)571v[x[j]++] = i;572} while (++i < n);573574/* Generate the Huffman codes and for each, make the table entries */575x[0] = i = 0; /* first Huffman code is zero */576p = v; /* grab values in bit order */577h = -1; /* no tables yet--level -1 */578w = l[-1] = 0; /* no bits decoded yet */579u[0] = (struct huft *)NULL; /* just to keep compilers happy */580q = (struct huft *)NULL; /* ditto */581z = 0; /* ditto */582583/* go through the bit lengths (k already is bits in shortest code) */584for (; k <= g; k++)585{586a = c[k];587while (a--)588{589/* here i is the Huffman code of length k bits for value *p */590/* make tables up to required level */591while (k > w + l[h])592{593w += l[h++]; /* add bits already decoded */594595/* compute minimum size table less than or equal to *m bits */596z = (z = g - w) > (unsigned)*m ? *m : z; /* upper limit */597if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */598{ /* too few codes for k-w bit table */599f -= a + 1; /* deduct codes from patterns left */600xp = c + k;601while (++j < z) /* try smaller tables up to z bits */602{603if ((f <<= 1) <= *++xp)604break; /* enough codes to use up j bits */605f -= *xp; /* else deduct codes from patterns */606}607}608if ((unsigned)w + j > el && (unsigned)w < el)609j = el - w; /* make EOB code end at table */610z = 1 << j; /* table entries for j-bit table */611l[h] = j; /* set table size in stack */612613/* allocate and link in new table */614if ((q = (struct huft *)615((*is->malloc_ptr)((z + 1)*sizeof(struct huft)))) ==616(struct huft *)NULL)617{618if (h)619huft_free(is, u[0]);620return 3; /* not enough memory */621}622*t = q + 1; /* link to list for huft_free() */623*(t = &(q->v.t)) = (struct huft *)NULL;624u[h] = ++q; /* table starts after link */625626/* connect to last table, if there is one */627if (h)628{629x[h] = i; /* save pattern for backing up */630r.b = (uch)l[h-1]; /* bits to dump before this table */631r.e = (uch)(16 + j); /* bits in this table */632r.v.t = q; /* pointer to this table */633j = (i & ((1 << w) - 1)) >> (w - l[h-1]);634u[h-1][j] = r; /* connect to last table */635}636}637638/* set up table entry in r */639r.b = (uch)(k - w);640if (p >= v + n)641r.e = 99; /* out of values--invalid code */642else if (*p < s)643{644r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */645r.v.n = (ush) *p++; /* simple code is just the value */646}647else648{649r.e = (uch)e[*p - s]; /* non-simple--look up in lists */650r.v.n = d[*p++ - s];651}652653/* fill code-like entries with r */654f = 1 << (k - w);655for (j = i >> w; j < z; j += f)656q[j] = r;657658/* backwards increment the k-bit code i */659for (j = 1 << (k - 1); i & j; j >>= 1)660i ^= j;661i ^= j;662663/* backup over finished tables */664while ((i & ((1 << w) - 1)) != x[h])665w -= l[--h]; /* don't need to update q */666}667}668669/* return actual size of base table */670*m = l[0];671672/* Return true (1) if we were given an incomplete table */673return y != 0 && g != 1;674}675676/*677* inflate (decompress) the codes in a stored (uncompressed) block.678* Return an error code or zero if it all goes ok.679*/680681static int inflate_stored(682struct InflateState *is /* Inflate state */683)684{685ulg b; /* bit buffer */686unsigned k; /* number of bits in bit buffer */687unsigned w; /* current window position */688689/* make local copies of state */690b = is->bb; /* initialize bit buffer */691k = is->bk; /* initialize bit count */692w = is->wp; /* initialize window position */693694/*695* Note that this code knows that NEEDBITS jumps to cleanup696*/697698while (is->storelength > 0) /* do until end of block */699{700NEEDBITS(8)701is->window[w++] = (uch) b;702DUMPBITS(8)703FLUSHWINDOW(w, FALSE);704is->storelength--;705}706707cleanup:708709/* restore the state from the locals */710is->bb = b; /* restore bit buffer */711is->bk = k; /* restore bit count */712is->wp = w; /* restore window pointer */713714if (is->storelength > 0)715return -1;716else717return 0;718}719720static int inflate_codes(721struct InflateState *is, /* Inflate state */722struct huft *tl, /* literal/length decoder table */723struct huft *td, /* distance decoder table */724int bl, /* number of bits decoded by tl[] */725int bd /* number of bits decoded by td[] */726)727{728unsigned e; /* table entry flag/number of extra bits */729unsigned n, d; /* length and index for copy */730unsigned w; /* current window position */731struct huft *t; /* pointer to table entry */732unsigned ml, md; /* masks for bl and bd bits */733ulg b; /* bit buffer */734unsigned k; /* number of bits in bit buffer */735736/* make local copies of state */737b = is->bb; /* initialize bit buffer */738k = is->bk; /* initialize bit count */739w = is->wp; /* initialize window position */740741/* inflate the coded data */742ml = mask_bits[bl]; /* precompute masks for speed */743md = mask_bits[bd];744for (;;) /* do until end of block */745{746TRY747{748NEEDBITS((unsigned)bl)749if ((e = (t = tl + ((unsigned)b & ml))->e) > 16)750do {751if (e == 99)752return 1;753DUMPBITS(t->b)754e -= 16;755NEEDBITS(e)756} while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16);757DUMPBITS(t->b)758759if (e == 16) /* it's a literal */760{761is->window[w++] = (uch)t->v.n;762FLUSHWINDOW(w, FALSE);763}764else if (e == 15) /* it's an EOB */765{766break;767}768else /* it's a length */769{770/* get length of block to copy */771NEEDBITS(e)772n = t->v.n + ((unsigned)b & mask_bits[e]);773DUMPBITS(e);774775/* decode distance of block to copy */776NEEDBITS((unsigned)bd)777if ((e = (t = td + ((unsigned)b & md))->e) > 16)778do {779if (e == 99)780return 1;781DUMPBITS(t->b)782e -= 16;783NEEDBITS(e)784} while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16);785DUMPBITS(t->b)786NEEDBITS(e)787d = w - t->v.n - ((unsigned)b & mask_bits[e]);788DUMPBITS(e)789790/* do the copy */791do {792n -= (e = ((e = WINDOWSIZE - ((d &= WINDOWMASK) > w ? d : w)) > n)793? n : e794);795#if defined(MEMCPY)796if (w - d >= e) /* (this test assumes unsigned comparison) */797{798memcpy(is->window + w, is->window + d, e);799w += e;800d += e;801}802else /* do it slow to avoid memcpy() overlap */803#endif /* MEMCPY */804do {805is->window[w++] = is->window[d++];806} while (--e);807FLUSHWINDOW(w, FALSE);808} while (n);809}810}811CATCH_BEGIN812is->wp = w; /* restore window pointer */813return -1;814CATCH_END815}816817/* restore the state from the locals */818is->bb = b; /* restore bit buffer */819is->bk = k; /* restore bit count */820is->wp = w; /* restore window pointer */821822/* done */823return 0;824}825826/*827* "decompress" an inflated type 0 (stored) block.828*/829830static int inflate_stored_setup(831struct InflateState *is /* Inflate state */832)833{834unsigned n; /* number of bytes in block */835ulg b; /* bit buffer */836unsigned k; /* number of bits in bit buffer */837838/* make local copies of state */839b = is->bb; /* initialize bit buffer */840k = is->bk; /* initialize bit count */841842TRY843{844/* go to byte boundary */845n = k & 7;846DUMPBITS(n);847848/* get the length and its complement */849NEEDBITS(16)850n = ((unsigned)b & 0xffff);851DUMPBITS(16)852NEEDBITS(16)853if (n != (unsigned)((~b) & 0xffff))854return 1; /* error in compressed data */855DUMPBITS(16)856}857CATCH_BEGIN858return -1;859CATCH_END860861/* Save store state for this block */862is->storelength = n;863864/* restore the state from the locals */865is->bb = b; /* restore bit buffer */866is->bk = k; /* restore bit count */867868return 0;869}870871/*872* decompress an inflated type 1 (fixed Huffman codes) block. We should873* either replace this with a custom decoder, or at least precompute the874* Huffman tables.875*/876877static int inflate_fixed_setup(878struct InflateState *is /* Inflate state */879)880{881int i; /* temporary variable */882struct huft *tl; /* literal/length code table */883struct huft *td; /* distance code table */884int bl; /* lookup bits for tl */885int bd; /* lookup bits for td */886unsigned l[288]; /* length list for huft_build */887888/* set up literal table */889for (i = 0; i < 144; i++)890l[i] = 8;891for (; i < 256; i++)892l[i] = 9;893for (; i < 280; i++)894l[i] = 7;895for (; i < 288; i++) /* make a complete, but wrong code set */896l[i] = 8;897bl = 7;898if ((i = huft_build(is, l, 288, 257, cplens, cplext, &tl, &bl)) != 0)899return i;900901/* set up distance table */902for (i = 0; i < 30; i++) /* make an incomplete code set */903l[i] = 5;904bd = 5;905if ((i = huft_build(is, l, 30, 0, cpdist, cpdext, &td, &bd)) > 1)906{907huft_free(is, tl);908return i;909}910911/* Save inflate state for this block */912is->tl = tl;913is->td = td;914is->bl = bl;915is->bd = bd;916917return 0;918}919920/*921* decompress an inflated type 2 (dynamic Huffman codes) block.922*/923924#define PKZIP_BUG_WORKAROUND925926static int inflate_dynamic_setup(927struct InflateState *is /* Inflate state */928)929{930int i; /* temporary variables */931unsigned j;932unsigned l; /* last length */933unsigned m; /* mask for bit lengths table */934unsigned n; /* number of lengths to get */935struct huft *tl; /* literal/length code table */936struct huft *td; /* distance code table */937int bl; /* lookup bits for tl */938int bd; /* lookup bits for td */939unsigned nb; /* number of bit length codes */940unsigned nl; /* number of literal/length codes */941unsigned nd; /* number of distance codes */942#ifdef PKZIP_BUG_WORKAROUND943unsigned ll[288+32]; /* literal/length and distance code lengths */944#else945unsigned ll[286+30]; /* literal/length and distance code lengths */946#endif947ulg b; /* bit buffer */948unsigned k; /* number of bits in bit buffer */949950/* make local copies of state */951b = is->bb; /* initialize bit buffer */952k = is->bk; /* initialize bit count */953954/* initialize tl for cleanup */955tl = NULL;956957TRY958{959/* read in table lengths */960NEEDBITS(5)961nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */962DUMPBITS(5)963NEEDBITS(5)964nd = 1 + ((unsigned)b & 0x1f); /* number of distance codes */965DUMPBITS(5)966NEEDBITS(4)967nb = 4 + ((unsigned)b & 0xf); /* number of bit length codes */968DUMPBITS(4)969#ifdef PKZIP_BUG_WORKAROUND970if (nl > 288 || nd > 32)971#else972if (nl > 286 || nd > 30)973#endif974return 1; /* bad lengths */975976/* read in bit-length-code lengths */977for (j = 0; j < 19; j++) ll[j] = 0;978for (j = 0; j < nb; j++)979{980NEEDBITS(3)981ll[border[j]] = (unsigned)b & 7;982DUMPBITS(3)983}984985/* build decoding table for trees--single level, 7 bit lookup */986bl = 7;987if ((i = huft_build(is, ll, 19, 19, NULL, NULL, &tl, &bl)) != 0)988{989if (i == 1)990huft_free(is, tl);991return i; /* incomplete code set */992}993994/* read in literal and distance code lengths */995n = nl + nd;996m = mask_bits[bl];997i = l = 0;998while ((unsigned)i < n)999{1000NEEDBITS((unsigned)bl)1001j = (td = tl + ((unsigned)b & m))->b;1002DUMPBITS(j)1003j = td->v.n;1004if (j < 16) /* length of code in bits (0..15) */1005ll[i++] = l = j; /* save last length in l */1006else if (j == 16) /* repeat last length 3 to 6 times */1007{1008NEEDBITS(2)1009j = 3 + ((unsigned)b & 3);1010DUMPBITS(2)1011if ((unsigned)i + j > n)1012return 1;1013while (j--)1014ll[i++] = l;1015}1016else if (j == 17) /* 3 to 10 zero length codes */1017{1018NEEDBITS(3)1019j = 3 + ((unsigned)b & 7);1020DUMPBITS(3)1021if ((unsigned)i + j > n)1022return 1;1023while (j--)1024ll[i++] = 0;1025l = 0;1026}1027else /* j == 18: 11 to 138 zero length codes */1028{1029NEEDBITS(7)1030j = 11 + ((unsigned)b & 0x7f);1031DUMPBITS(7)1032if ((unsigned)i + j > n)1033return 1;1034while (j--)1035ll[i++] = 0;1036l = 0;1037}1038}10391040/* free decoding table for trees */1041huft_free(is, tl);1042}1043CATCH_BEGIN1044if (tl) huft_free(is, tl);1045return -1;1046CATCH_END10471048/* restore the state from the locals */1049is->bb = b; /* restore bit buffer */1050is->bk = k; /* restore bit count */10511052/* build the decoding tables for literal/length and distance codes */1053bl = lbits;1054if ((i = huft_build(is, ll, nl, 257, cplens, cplext, &tl, &bl)) != 0)1055{1056if (i == 1) {1057/* incomplete literal tree */1058huft_free(is, tl);1059}1060return i; /* incomplete code set */1061}1062bd = dbits;1063if ((i = huft_build(is, ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0)1064{1065if (i == 1) {1066/* incomplete distance tree */1067#ifdef PKZIP_BUG_WORKAROUND1068}1069#else1070huft_free(is, td);1071}1072huft_free(is, tl);1073return i; /* incomplete code set */1074#endif1075}10761077/* Save inflate state for this block */1078is->tl = tl;1079is->td = td;1080is->bl = bl;1081is->bd = bd;10821083return 0;1084}10851086/* Routine to initialize inflate decompression */1087void *InflateInitialize( /* returns InflateState */1088void *AppState, /* for passing to putbuffer */1089int (*putbuffer_ptr)( /* returns 0 on success */1090void *AppState, /* opaque ptr from Initialize */1091unsigned char *buffer, /* buffer to put */1092long length /* length of buffer */1093),1094void *(*malloc_ptr)(long length), /* utility routine */1095void (*free_ptr)(void *buffer) /* utility routine */1096)1097{1098struct InflateState *is;10991100/* Do some argument checking */1101if ((!putbuffer_ptr) || (!malloc_ptr) || (!free_ptr)) return NULL;11021103/* Allocate the InflateState memory area */1104is = (struct InflateState *) (*malloc_ptr)(sizeof(struct InflateState));1105if (!is) return NULL;11061107/* Set up the initial values of the inflate state */1108is->runtimetypeid1 = INFLATESTATETYPE;1109is->errorencountered = FALSE;11101111is->bb = 0;1112is->bk = 0;1113is->bp = 0;1114is->bs = 0;11151116is->wp = 0;1117is->wf = 0;11181119is->state = -1;1120is->lastblock = FALSE;11211122is->AppState = AppState;11231124is->putbuffer_ptr = putbuffer_ptr;1125is->malloc_ptr = malloc_ptr;1126is->free_ptr = free_ptr;11271128is->runtimetypeid2 = INFLATESTATETYPE;11291130/* Return this state info to the caller */1131return is;1132}11331134/* Call-in routine to put a buffer into inflate decompression */1135int InflatePutBuffer( /* returns 0 on success */1136void *InflateState, /* opaque ptr from Initialize */1137unsigned char *buffer, /* buffer to put */1138long length /* length of buffer */1139)1140{1141struct InflateState *is;11421143int beginstate;11441145/* Get (and check) the InflateState structure */1146is = (struct InflateState *) InflateState;1147if (!is || (is->runtimetypeid1 != INFLATESTATETYPE)1148|| (is->runtimetypeid2 != INFLATESTATETYPE)) return TRUE;1149if (is->errorencountered) return TRUE;11501151do1152{1153int size, i;115411551156if ((is->state == -1) && (is->lastblock)) break;11571158/* Save the beginning state */1159beginstate = is->state;11601161/* Push as much as possible into input buffer */1162size = BUFFERSIZE - is->bs;1163if (size > length) size = (int) length;1164i = is->bp + is->bs;11651166while (size-- > 0)1167{1168is->buffer[i++ & BUFFERMASK] = *buffer;1169is->bs++;1170buffer++;1171length--;1172}11731174/* Process some more data */1175if (is->state == -1)1176{1177int e; /* last block flag */1178unsigned t; /* block type */11791180ulg b; /* bit buffer */1181unsigned k; /* number of bits in bit buffer */11821183/* make local copies of state */1184b = is->bb; /* initialize bit buffer */1185k = is->bk; /* initialize bit count */11861187TRY1188{1189/* read in last block bit */1190NEEDBITS(1)1191e = (int)b & 1;1192DUMPBITS(1)11931194/* read in block type */1195NEEDBITS(2)1196t = (unsigned)b & 3;1197DUMPBITS(2)11981199if (t <= 2)1200{1201is->state = t;1202is->lastblock = e;1203}1204else1205{1206ERROREXIT(is);1207}1208}1209CATCH_BEGIN1210CATCH_END12111212/* restore the state from the locals */1213is->bb = b; /* restore bit buffer */1214is->bk = k; /* restore bit count */1215}1216else if (is->state == 0)1217{1218int ret;12191220ret = inflate_stored_setup(is);12211222if (ret > 0)1223ERROREXIT(is);12241225if (ret == 0) is->state += 10;1226}1227else if (is->state == 1)1228{1229int ret;12301231ret = inflate_fixed_setup(is);12321233if (ret > 0)1234ERROREXIT(is);12351236if (ret == 0) is->state += 10;1237}1238else if (is->state == 2)1239{1240int ret;12411242ret = inflate_dynamic_setup(is);12431244if (ret > 0)1245ERROREXIT(is);12461247if (ret == 0) is->state += 10;1248}1249else if (is->state == 10)1250{1251int ret;12521253ret = inflate_stored(is);12541255if (ret > 0)1256ERROREXIT(is);12571258if (ret == 0)1259{1260is->state = -1;1261}1262}1263else if ((is->state == 11) ||1264(is->state == 12) )1265{1266int ret;12671268ret = inflate_codes(is, is->tl, is->td, is->bl, is->bd);12691270if (ret > 0)1271ERROREXIT(is);12721273if (ret == 0)1274{1275/* free the decoding tables */1276huft_free(is, is->tl);1277huft_free(is, is->td);1278is->state = -1;1279}1280}1281else1282{1283ERROREXIT(is);1284}1285}1286while (length || (is->state != beginstate));12871288FLUSHWINDOW(is->wp, TRUE);12891290return is->errorencountered;1291}12921293/* Routine to terminate inflate decompression */1294int InflateTerminate( /* returns 0 on success */1295void *InflateState /* opaque ptr from Initialize */1296)1297{1298int err;1299void (*free_ptr)(void *buffer);13001301struct InflateState *is;13021303/* Get (and check) the InflateState structure */1304is = (struct InflateState *) InflateState;1305if (!is || (is->runtimetypeid1 != INFLATESTATETYPE)1306|| (is->runtimetypeid2 != INFLATESTATETYPE)) return TRUE;13071308/* save the error return */1309err = is->errorencountered || (is->bs > 0)1310|| (is->state != -1)1311|| (!is->lastblock);13121313/* save the address of the free routine */1314free_ptr = is->free_ptr;13151316/* Deallocate everything */1317(*free_ptr)(is);13181319return err;1320}132113221323