home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / UNZP50P1.ZIP / inflate.c < prev    next >
C/C++ Source or Header  |  1993-01-23  |  33KB  |  968 lines

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