home *** CD-ROM | disk | FTP | other *** search
/ Nebula 1995 August / NEBULA.mdf / Apps / DevTools / SmartPackage / Sources / funzip / inflate.c < prev    next >
Encoding:
Text File  |  1994-04-12  |  33.8 KB  |  1,002 lines

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