home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / unzip531.zip / inflate.c < prev    next >
Text File  |  1997-04-20  |  45KB  |  1,293 lines

  1. /* inflate.c -- put in the public domain by Mark Adler
  2.    version c15c, 28 March 1997 */
  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 unimplod.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.    c10.5 14 Dec 92  M. Adler        fix up error messages for incomplete trees.
  49.     c11   2 Jan 93  M. Adler        fixed bug in detection of incomplete
  50.                                     tables, and removed assumption that EOB is
  51.                                     the longest code (bad assumption).
  52.     c12   3 Jan 93  M. Adler        make tables for fixed blocks only once.
  53.     c13   5 Jan 93  M. Adler        allow all zero length codes (pkzip 2.04c
  54.                                     outputs one zero length code for an empty
  55.                                     distance tree).
  56.     c14  12 Mar 93  M. Adler        made inflate.c standalone with the
  57.                                     introduction of inflate.h.
  58.    c14b  16 Jul 93  G. Roelofs      added (unsigned) typecast to w at 470.
  59.    c14c  19 Jul 93  J. Bush         changed v[N_MAX], l[288], ll[28x+3x] arrays
  60.                                     to static for Amiga.
  61.    c14d  13 Aug 93  J-l. Gailly     de-complicatified Mark's c[*p++]++ thing.
  62.    c14e   8 Oct 93  G. Roelofs      changed memset() to memzero().
  63.    c14f  22 Oct 93  G. Roelofs      renamed quietflg to qflag; made Trace()
  64.                                     conditional; added inflate_free().
  65.    c14g  28 Oct 93  G. Roelofs      changed l/(lx+1) macro to pointer (Cray bug)
  66.    c14h   7 Dec 93  C. Ghisler      huft_build() optimizations.
  67.    c14i   9 Jan 94  A. Verheijen    set fixed_t{d,l} to NULL after freeing;
  68.                     G. Roelofs      check NEXTBYTE macro for EOF.
  69.    c14j  23 Jan 94  G. Roelofs      removed Ghisler "optimizations"; ifdef'd
  70.                                     EOF check.
  71.    c14k  27 Feb 94  G. Roelofs      added some typecasts to avoid warnings.
  72.    c14l   9 Apr 94  G. Roelofs      fixed split comments on preprocessor lines
  73.                                     to avoid bug in Encore compiler.
  74.    c14m   7 Jul 94  P. Kienitz      modified to allow assembler version of
  75.                                     inflate_codes() (define ASM_INFLATECODES)
  76.    c14n  22 Jul 94  G. Roelofs      changed fprintf to macro for DLL versions
  77.    c14o  23 Aug 94  C. Spieler      added a newline to a debug statement;
  78.                     G. Roelofs      added another typecast to avoid MSC warning
  79.    c14p   4 Oct 94  G. Roelofs      added (voidp *) cast to free() argument
  80.    c14q  30 Oct 94  G. Roelofs      changed fprintf macro to MESSAGE()
  81.    c14r   1 Nov 94  G. Roelofs      fixed possible redefinition of CHECK_EOF
  82.    c14s   7 May 95  S. Maxwell      OS/2 DLL globals stuff incorporated;
  83.                     P. Kienitz      "fixed" ASM_INFLATECODES macro/prototype
  84.    c14t  18 Aug 95  G. Roelofs      added UZinflate() to use zlib functions;
  85.                                     changed voidp to zvoid; moved huft_build()
  86.                                     and huft_free() to end of file
  87.    c14u   1 Oct 95  G. Roelofs      moved G into definition of MESSAGE macro
  88.    c14v   8 Nov 95  P. Kienitz      changed ASM_INFLATECODES to use a regular
  89.                                     call with __G__ instead of a macro
  90.     c15   3 Aug 96  M. Adler        fixed bomb-bug on random input data (Adobe)
  91.    c15b  24 Aug 96  M. Adler        more fixes for random input data
  92.    c15c  28 Mar 97  G. Roelofs      changed USE_ZLIB fatal exit code from
  93.                                     PK_MEM2 to PK_MEM3
  94.     c16  20 Apr 97  J. Altman       added memzero(v[]) in huft_build()
  95.  */
  96.  
  97.  
  98. /*
  99.    Inflate deflated (PKZIP's method 8 compressed) data.  The compression
  100.    method searches for as much of the current string of bytes (up to a
  101.    length of 258) in the previous 32K bytes.  If it doesn't find any
  102.    matches (of at least length 3), it codes the next byte.  Otherwise, it
  103.    codes the length of the matched string and its distance backwards from
  104.    the current position.  There is a single Huffman code that codes both
  105.    single bytes (called "literals") and match lengths.  A second Huffman
  106.    code codes the distance information, which follows a length code.  Each
  107.    length or distance code actually represents a base value and a number
  108.    of "extra" (sometimes zero) bits to get to add to the base value.  At
  109.    the end of each deflated block is a special end-of-block (EOB) literal/
  110.    length code.  The decoding process is basically: get a literal/length
  111.    code; if EOB then done; if a literal, emit the decoded byte; if a
  112.    length then get the distance and emit the referred-to bytes from the
  113.    sliding window of previously emitted data.
  114.  
  115.    There are (currently) three kinds of inflate blocks: stored, fixed, and
  116.    dynamic.  The compressor outputs a chunk of data at a time and decides
  117.    which method to use on a chunk-by-chunk basis.  A chunk might typically
  118.    be 32K to 64K, uncompressed.  If the chunk is uncompressible, then the
  119.    "stored" method is used.  In this case, the bytes are simply stored as
  120.    is, eight bits per byte, with none of the above coding.  The bytes are
  121.    preceded by a count, since there is no longer an EOB code.
  122.  
  123.    If the data are compressible, then either the fixed or dynamic methods
  124.    are used.  In the dynamic method, the compressed data are preceded by
  125.    an encoding of the literal/length and distance Huffman codes that are
  126.    to be used to decode this block.  The representation is itself Huffman
  127.    coded, and so is preceded by a description of that code.  These code
  128.    descriptions take up a little space, and so for small blocks, there is
  129.    a predefined set of codes, called the fixed codes.  The fixed method is
  130.    used if the block ends up smaller that way (usually for quite small
  131.    chunks); otherwise the dynamic method is used.  In the latter case, the
  132.    codes are customized to the probabilities in the current block and so
  133.    can code it much better than the pre-determined fixed codes can.
  134.  
  135.    The Huffman codes themselves are decoded using a multi-level table
  136.    lookup, in order to maximize the speed of decoding plus the speed of
  137.    building the decoding tables.  See the comments below that precede the
  138.    lbits and dbits tuning parameters.
  139.  
  140.    GRR:  return values(?)
  141.            0  OK
  142.            1  incomplete table
  143.            2  bad input
  144.            3  not enough memory
  145.  */
  146.  
  147.  
  148. /*
  149.    Notes beyond the 1.93a appnote.txt:
  150.  
  151.    1. Distance pointers never point before the beginning of the output
  152.       stream.
  153.    2. Distance pointers can point back across blocks, up to 32k away.
  154.    3. There is an implied maximum of 7 bits for the bit length table and
  155.       15 bits for the actual data.
  156.    4. If only one code exists, then it is encoded using one bit.  (Zero
  157.       would be more efficient, but perhaps a little confusing.)  If two
  158.       codes exist, they are coded using one bit each (0 and 1).
  159.    5. There is no way of sending zero distance codes--a dummy must be
  160.       sent if there are none.  (History: a pre 2.0 version of PKZIP would
  161.       store blocks with no distance codes, but this was discovered to be
  162.       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
  163.       zero distance codes, which is sent as one code of zero bits in
  164.       length.
  165.    6. There are up to 286 literal/length codes.  Code 256 represents the
  166.       end-of-block.  Note however that the static length tree defines
  167.       288 codes just to fill out the Huffman codes.  Codes 286 and 287
  168.       cannot be used though, since there is no length base or extra bits
  169.       defined for them.  Similarily, there are up to 30 distance codes.
  170.       However, static trees define 32 codes (all 5 bits) to fill out the
  171.       Huffman codes, but the last two had better not show up in the data.
  172.    7. Unzip can check dynamic Huffman blocks for complete code sets.
  173.       The exception is that a single code would not be complete (see #4).
  174.    8. The five bits following the block type is really the number of
  175.       literal codes sent minus 257.
  176.    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
  177.       (1+6+6).  Therefore, to output three times the length, you output
  178.       three codes (1+1+1), whereas to output four times the same length,
  179.       you only need two codes (1+3).  Hmm.
  180.   10. In the tree reconstruction algorithm, Code = Code + Increment
  181.       only if BitLength(i) is not zero.  (Pretty obvious.)
  182.   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
  183.   12. Note: length code 284 can represent 227-258, but length code 285
  184.       really is 258.  The last length deserves its own, short code
  185.       since it gets used a lot in very redundant files.  The length
  186.       258 is special since 258 - 3 (the min match length) is 255.
  187.   13. The literal/length and distance code bit lengths are read as a
  188.       single stream of lengths.  It is possible (and advantageous) for
  189.       a repeat code (16, 17, or 18) to go across the boundary between
  190.       the two sets of lengths.
  191.  */
  192.  
  193.  
  194. #define PKZIP_BUG_WORKAROUND    /* PKZIP 1.93a problem--live with it */
  195.  
  196. /*
  197.     inflate.h must supply the uch slide[WSIZE] array, the zvoid typedef
  198.     (void if (void *) is accepted, else char) and the NEXTBYTE,
  199.     FLUSH() and memzero macros.  If the window size is not 32K, it
  200.     should also define WSIZE.  If INFMOD is defined, it can include
  201.     compiled functions to support the NEXTBYTE and/or FLUSH() macros.
  202.     There are defaults for NEXTBYTE and FLUSH() below for use as
  203.     examples of what those functions need to do.  Normally, you would
  204.     also want FLUSH() to compute a crc on the data.  inflate.h also
  205.     needs to provide these typedefs:
  206.  
  207.         typedef unsigned char uch;
  208.         typedef unsigned short ush;
  209.         typedef unsigned long ulg;
  210.  
  211.     This module uses the external functions malloc() and free() (and
  212.     probably memset() or bzero() in the memzero() macro).  Their
  213.     prototypes are normally found in <string.h> and <stdlib.h>.
  214.  */
  215.  
  216. /* #define DEBUG */
  217. #define INFMOD          /* tell inflate.h to include code to be compiled */
  218. #include "inflate.h"
  219.  
  220.  
  221. #ifndef WSIZE           /* default is 32K */
  222. #  define WSIZE 0x8000  /* window size--must be a power of two, and at least */
  223. #endif                  /* 32K for zip's deflate method */
  224.  
  225. #ifdef DLL
  226. #  define wsize G._wsize   /* wsize is a variable */
  227. #else
  228. #  define wsize WSIZE       /* wsize is a constant */
  229. #endif
  230.  
  231.  
  232. #ifndef NEXTBYTE        /* default is to simply get a byte from stdin */
  233. #  define NEXTBYTE getchar()
  234. #endif
  235.  
  236. #ifndef MESSAGE   /* only used twice, for fixed strings--NOT general-purpose */
  237. #  define MESSAGE(str,len,flag)  fprintf(stderr,(char *)(str))
  238. #endif
  239.  
  240. #ifndef FLUSH           /* default is to simply write the buffer to stdout */
  241. #  define FLUSH(n) fwrite(redirSlide, 1, n, stdout)  /* return value not used */
  242. #endif
  243. /* Warning: the fwrite above might not work on 16-bit compilers, since
  244.    0x8000 might be interpreted as -32,768 by the library function. */
  245.  
  246. #ifndef Trace
  247. #  ifdef DEBUG
  248. #    define Trace(x) fprintf x
  249. #  else
  250. #    define Trace(x)
  251. #  endif
  252. #endif
  253.  
  254.  
  255. /*---------------------------------------------------------------------------*/
  256. #ifdef USE_ZLIB
  257.  
  258. #include "zlib.h"
  259.  
  260.  
  261. /*
  262.    GRR:  return values for both original inflate() and UZinflate()
  263.            0  OK
  264.            1  incomplete table(?)
  265.            2  bad input
  266.            3  not enough memory
  267.  */
  268.  
  269. /**************************/
  270. /*  Function UZinflate()  */
  271. /**************************/
  272.  
  273. int UZinflate(__G)   /* decompress an inflated entry using the zlib routines */
  274.     __GDEF
  275. {
  276.     int i, windowBits, err=Z_OK;
  277.  
  278.  
  279. #ifdef DLL
  280.     if (G.redirect_data)
  281.         wsize = G.redirect_size, redirSlide = G.redirect_buffer;
  282.     else
  283.         wsize = WSIZE, redirSlide = slide;
  284. #endif
  285.     /* GRR:  "U" may not be compatible with K&R compilers */
  286.     if (wsize < 256U)   /* window sizes 2^8 .. 2^15 allowed currently */
  287.         return 2;
  288.  
  289.     /* windowBits = log2(wsize) */
  290.     for (i = wsize, windowBits = 0;  !(i & 1);  i >>= 1, ++windowBits);
  291.  
  292.     G.dstrm.next_out = redirSlide;
  293.     G.dstrm.avail_out = wsize;
  294.  
  295.     G.dstrm.next_in = G.inptr;
  296.     G.dstrm.avail_in = G.incnt;
  297.  
  298.     if (!G.inflInit) {
  299.         /* only need to test this stuff once */
  300.         if (zlib_version[0] != ZLIB_VERSION[0]) {
  301.             Info(slide, 0x21, ((char *)slide,
  302.               "error:  incompatible zlib version (expected %s, found %s)\n",
  303.               ZLIB_VERSION, zlib_version));
  304.             return 3;
  305.         } else if (strcmp(zlib_version, ZLIB_VERSION) != 0)
  306.             Info(slide, 0x21, ((char *)slide,
  307.               "warning:  different zlib version (expected %s, using %s)\n",
  308.               ZLIB_VERSION, zlib_version));
  309.  
  310.         G.dstrm.zalloc = (alloc_func)Z_NULL;
  311.         G.dstrm.zfree = (free_func)Z_NULL;
  312.  
  313.         Trace((stderr, "initializing inflate()\n"));
  314.         err = inflateInit2(&G.dstrm, -windowBits);
  315.  
  316.         if (err == Z_MEM_ERROR)
  317.             return 3;
  318.         else if (err != Z_OK)
  319.             Trace((stderr, "oops!  (inflateInit2() err = %d)\n", err));
  320.         G.inflInit = 1;
  321.     }
  322.  
  323. #ifdef FUNZIP
  324.     while (err != Z_STREAM_END) {
  325. #else /* !FUNZIP */
  326.     while (G.csize > 0) {
  327.         Trace((stderr, "first loop:  G.csize = %ld\n", G.csize));
  328. #endif /* ?FUNZIP */
  329.         while (G.dstrm.avail_out > 0) {
  330.             err = inflate(&G.dstrm, Z_PARTIAL_FLUSH);
  331.  
  332.             if (err == Z_DATA_ERROR)
  333.                 return 2;
  334.             else if (err == Z_MEM_ERROR)
  335.                 return 3;
  336.             else if (err != Z_OK && err != Z_STREAM_END)
  337.                 Trace((stderr, "oops!  (inflate(first loop) err = %d)\n", err));
  338.  
  339. #ifdef FUNZIP
  340.             if (err == Z_STREAM_END)    /* "END-of-entry-condition" ? */
  341. #else /* !FUNZIP */
  342.             if (G.csize <= 0L)          /* "END-of-entry-condition" ? */
  343. #endif /* ?FUNZIP */
  344.                 break;
  345.  
  346.             if (G.dstrm.avail_in <= 0) {
  347.                 if (fillinbuf(__G) == 0)
  348.                     return 2;  /* no "END-condition" yet, but no more data */
  349.  
  350.                 G.dstrm.next_in = G.inptr;
  351.                 G.dstrm.avail_in = G.incnt;
  352.             }
  353.             Trace((stderr, "     avail_in = %d\n", G.dstrm.avail_in));
  354.         }
  355.         FLUSH(wsize - G.dstrm.avail_out);   /* flush slide[] */
  356.         Trace((stderr, "inside loop:  flushing %ld bytes (ptr diff = %ld)\n",
  357.           (long)(wsize - G.dstrm.avail_out),
  358.           (long)(G.dstrm.next_out-(Bytef *)redirSlide)));
  359.         G.dstrm.next_out = redirSlide;
  360.         G.dstrm.avail_out = wsize;
  361.     }
  362.  
  363.     /* no more input, so loop until we have all output */
  364.     Trace((stderr, "beginning final loop:  err = %d\n", err));
  365.     while (err != Z_STREAM_END) {
  366.         err = inflate(&G.dstrm, Z_PARTIAL_FLUSH);
  367.         if (err == Z_DATA_ERROR)
  368.             return 2;
  369.         else if (err == Z_MEM_ERROR)
  370.             return 3;
  371.         else if (err == Z_BUF_ERROR) {              /* DEBUG */
  372.             Trace((stderr, "zlib inflate() did not detect stream end (%s, %s)\n"
  373.               , G.zipfn, G.filename));
  374.             break;
  375.         } else if (err != Z_OK && err != Z_STREAM_END) {
  376.             Trace((stderr, "oops!  (inflate(final loop) err = %d)\n", err));
  377.             DESTROYGLOBALS()
  378.             EXIT(PK_MEM3);
  379.         }
  380.         FLUSH(wsize - G.dstrm.avail_out);   /* final flush of slide[] */
  381.         Trace((stderr, "final loop:  flushing %ld bytes (ptr diff = %ld)\n",
  382.           (long)(wsize - G.dstrm.avail_out),
  383.           (long)(G.dstrm.next_out-(Bytef *)redirSlide)));
  384.         G.dstrm.next_out = redirSlide;
  385.         G.dstrm.avail_out = wsize;
  386.     }
  387.     Trace((stderr, "total in = %ld, total out = %ld\n", G.dstrm.total_in,
  388.       G.dstrm.total_out));
  389.  
  390.     G.inptr = G.dstrm.next_in;
  391.     G.incnt = (G.inbuf + INBUFSIZ) - G.inptr;  /* reset for other routines */
  392.  
  393.     err = inflateReset(&G.dstrm);
  394.     if (err != Z_OK)
  395.         Trace((stderr, "oops!  (inflateReset() err = %d)\n", err));
  396.  
  397.     return 0;
  398. }
  399.  
  400.  
  401. /*---------------------------------------------------------------------------*/
  402. #else /* !USE_ZLIB */
  403.  
  404.  
  405. /* Function prototypes */
  406. #ifndef OF
  407. #  ifdef __STDC__
  408. #    define OF(a) a
  409. #  else
  410. #    define OF(a) ()
  411. #  endif
  412. #endif /* !OF */
  413. int inflate_codes OF((__GPRO__ struct huft *tl, struct huft *td,
  414.                       int bl, int bd));
  415. static int inflate_stored OF((__GPRO));
  416. static int inflate_fixed OF((__GPRO));
  417. static int inflate_dynamic OF((__GPRO));
  418. static int inflate_block OF((__GPRO__ int *e));
  419.  
  420.  
  421. /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
  422.    stream to find repeated byte strings.  This is implemented here as a
  423.    circular buffer.  The index is updated simply by incrementing and then
  424.    and'ing with 0x7fff (32K-1). */
  425. /* It is left to other modules to supply the 32K area.  It is assumed
  426.    to be usable as if it were declared "uch slide[32768];" or as just
  427.    "uch *slide;" and then malloc'ed in the latter case.  The definition
  428.    must be in unzip.h, included above. */
  429.  
  430.  
  431. /* unsigned wp;  moved to globals.h */     /* current position in slide */
  432.  
  433.  
  434. /* Tables for deflate from PKZIP's appnote.txt. */
  435. static unsigned border[] = {    /* Order of the bit length code lengths */
  436.         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  437. static ush cplens[] = {         /* Copy lengths for literal codes 257..285 */
  438.         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  439.         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  440.         /* note: see note #13 above about the 258 in this list. */
  441. static ush cplext[] = {         /* Extra bits for literal codes 257..285 */
  442.         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  443.         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
  444. static ush cpdist[] = {         /* Copy offsets for distance codes 0..29 */
  445.         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  446.         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  447.         8193, 12289, 16385, 24577};
  448. static ush cpdext[] = {         /* Extra bits for distance codes */
  449.         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  450.         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  451.         12, 12, 13, 13};
  452.  
  453.  
  454. /* moved to consts.h (included in unzip.c), resp. funzip.c */
  455. #if 0
  456. /* And'ing with mask_bits[n] masks the lower n bits */
  457. ZCONST ush near mask_bits[] = {
  458.     0x0000,
  459.     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
  460.     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
  461. };
  462. #endif /* 0 */
  463.  
  464.  
  465. /* Macros for inflate() bit peeking and grabbing.
  466.    The usage is:
  467.  
  468.         NEEDBITS(j)
  469.         x = b & mask_bits[j];
  470.         DUMPBITS(j)
  471.  
  472.    where NEEDBITS makes sure that b has at least j bits in it, and
  473.    DUMPBITS removes the bits from b.  The macros use the variable k
  474.    for the number of bits in b.  Normally, b and k are register
  475.    variables for speed and are initialized at the begining of a
  476.    routine that uses these macros from a global bit buffer and count.
  477.  
  478.    In order to not ask for more bits than there are in the compressed
  479.    stream, the Huffman tables are constructed to only ask for just
  480.    enough bits to make up the end-of-block code (value 256).  Then no
  481.    bytes need to be "returned" to the buffer at the end of the last
  482.    block.  See the huft_build() routine.
  483.  */
  484.  
  485. /* These have been moved to globals.h */
  486. #if 0
  487. ulg bb;                         /* bit buffer */
  488. unsigned bk;                    /* bits in bit buffer */
  489. #endif
  490.  
  491. #ifndef CHECK_EOF
  492. #  define CHECK_EOF   /* default as of 5.13/5.2 */
  493. #endif
  494.  
  495. #ifndef CHECK_EOF
  496. #  define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE)<<k;k+=8;}}
  497. #else
  498. #  define NEEDBITS(n) {while(k<(n)){int c=NEXTBYTE;if(c==EOF)return 1;\
  499.     b|=((ulg)c)<<k;k+=8;}}
  500. #endif                      /* Piet Plomp:  change "return 1" to "break" */
  501.  
  502. #define DUMPBITS(n) {b>>=(n);k-=(n);}
  503.  
  504.  
  505. /*
  506.    Huffman code decoding is performed using a multi-level table lookup.
  507.    The fastest way to decode is to simply build a lookup table whose
  508.    size is determined by the longest code.  However, the time it takes
  509.    to build this table can also be a factor if the data being decoded
  510.    are not very long.  The most common codes are necessarily the
  511.    shortest codes, so those codes dominate the decoding time, and hence
  512.    the speed.  The idea is you can have a shorter table that decodes the
  513.    shorter, more probable codes, and then point to subsidiary tables for
  514.    the longer codes.  The time it costs to decode the longer codes is
  515.    then traded against the time it takes to make longer tables.
  516.  
  517.    This results of this trade are in the variables lbits and dbits
  518.    below.  lbits is the number of bits the first level table for literal/
  519.    length codes can decode in one step, and dbits is the same thing for
  520.    the distance codes.  Subsequent tables are also less than or equal to
  521.    those sizes.  These values may be adjusted either when all of the
  522.    codes are shorter than that, in which case the longest code length in
  523.    bits is used, or when the shortest code is *longer* than the requested
  524.    table size, in which case the length of the shortest code in bits is
  525.    used.
  526.  
  527.    There are two different values for the two tables, since they code a
  528.    different number of possibilities each.  The literal/length table
  529.    codes 286 possible values, or in a flat code, a little over eight
  530.    bits.  The distance table codes 30 possible values, or a little less
  531.    than five bits, flat.  The optimum values for speed end up being
  532.    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
  533.    The optimum values may differ though from machine to machine, and
  534.    possibly even between compilers.  Your mileage may vary.
  535.  */
  536.  
  537.  
  538. static int lbits = 9;           /* bits in base literal/length lookup table */
  539. static int dbits = 6;           /* bits in base distance lookup table */
  540.  
  541.  
  542. #ifndef ASM_INFLATECODES
  543.  
  544. int inflate_codes(__G__ tl, td, bl, bd)
  545.      __GDEF
  546. struct huft *tl, *td;   /* literal/length and distance decoder tables */
  547. int bl, bd;             /* number of bits decoded by tl[] and td[] */
  548. /* inflate (decompress) the codes in a deflated (compressed) block.
  549.    Return an error code or zero if it all goes ok. */
  550. {
  551.   register unsigned e;  /* table entry flag/number of extra bits */
  552.   unsigned n, d;        /* length and index for copy */
  553.   unsigned w;           /* current window position */
  554.   struct huft *t;       /* pointer to table entry */
  555.   unsigned ml, md;      /* masks for bl and bd bits */
  556.   register ulg b;       /* bit buffer */
  557.   register unsigned k;  /* number of bits in bit buffer */
  558.  
  559.  
  560.   /* make local copies of globals */
  561.   b = G.bb;                       /* initialize bit buffer */
  562.   k = G.bk;
  563.   w = G.wp;                       /* initialize window position */
  564.  
  565.  
  566.   /* inflate the coded data */
  567.   ml = mask_bits[bl];           /* precompute masks for speed */
  568.   md = mask_bits[bd];
  569.   while (1)                     /* do until end of block */
  570.   {
  571.     NEEDBITS((unsigned)bl)
  572.     if ((e = (t = tl + ((unsigned)b & ml))->e) > 16)
  573.       do {
  574.         if (e == 99)
  575.           return 1;
  576.         DUMPBITS(t->b)
  577.         e -= 16;
  578.         NEEDBITS(e)
  579.       } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16);
  580.     DUMPBITS(t->b)
  581.     if (e == 16)                /* then it's a literal */
  582.     {
  583.       redirSlide[w++] = (uch)t->v.n;
  584.       if (w == wsize)
  585.       {
  586.         FLUSH(w);
  587.         w = 0;
  588.       }
  589.     }
  590.     else                        /* it's an EOB or a length */
  591.     {
  592.       /* exit if end of block */
  593.       if (e == 15)
  594.         break;
  595.  
  596.       /* get length of block to copy */
  597.       NEEDBITS(e)
  598.       n = t->v.n + ((unsigned)b & mask_bits[e]);
  599.       DUMPBITS(e);
  600.  
  601.       /* decode distance of block to copy */
  602.       NEEDBITS((unsigned)bd)
  603.       if ((e = (t = td + ((unsigned)b & md))->e) > 16)
  604.         do {
  605.           if (e == 99)
  606.             return 1;
  607.           DUMPBITS(t->b)
  608.           e -= 16;
  609.           NEEDBITS(e)
  610.         } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16);
  611.       DUMPBITS(t->b)
  612.       NEEDBITS(e)
  613.       d = w - t->v.n - ((unsigned)b & mask_bits[e]);
  614.       DUMPBITS(e)
  615.  
  616.       /* do the copy */
  617.       do {
  618. #ifdef DLL
  619.         if (G.redirect_data)  /* &= w/ wsize unnecessary & wrong if redirect */
  620.           n -= (e = (e = wsize - (d > w ? d : w)) > n ? n : e);
  621.         else
  622. #endif
  623.           n -= (e = (e = wsize - ((d &= wsize-1) > w ? d : w)) > n ? n : e);
  624. #ifndef NOMEMCPY
  625.         if (w - d >= e)         /* (this test assumes unsigned comparison) */
  626.         {
  627.           memcpy(redirSlide + w, redirSlide + d, e);
  628.           w += e;
  629.           d += e;
  630.         }
  631.         else                    /* do it slowly to avoid memcpy() overlap */
  632. #endif /* !NOMEMCPY */
  633.           do {
  634.             redirSlide[w++] = redirSlide[d++];
  635.           } while (--e);
  636.         if (w == wsize)
  637.         {
  638.           FLUSH(w);
  639.           w = 0;
  640.         }
  641.       } while (n);
  642.     }
  643.   }
  644.  
  645.  
  646.   /* restore the globals from the locals */
  647.   G.wp = w;                       /* restore global window pointer */
  648.   G.bb = b;                       /* restore global bit buffer */
  649.   G.bk = k;
  650.  
  651.  
  652.   /* done */
  653.   return 0;
  654. }
  655.  
  656. #endif /* ASM_INFLATECODES */
  657.  
  658.  
  659.  
  660. static int inflate_stored(__G)
  661.      __GDEF
  662. /* "decompress" an inflated type 0 (stored) block. */
  663. {
  664.   unsigned n;           /* number of bytes in block */
  665.   unsigned w;           /* current window position */
  666.   register ulg b;       /* bit buffer */
  667.   register unsigned k;  /* number of bits in bit buffer */
  668.  
  669.  
  670.   /* make local copies of globals */
  671.   Trace((stderr, "\nstored block"));
  672.   b = G.bb;                       /* initialize bit buffer */
  673.   k = G.bk;
  674.   w = G.wp;                       /* initialize window position */
  675.  
  676.  
  677.   /* go to byte boundary */
  678.   n = k & 7;
  679.   DUMPBITS(n);
  680.  
  681.  
  682.   /* get the length and its complement */
  683.   NEEDBITS(16)
  684.   n = ((unsigned)b & 0xffff);
  685.   DUMPBITS(16)
  686.   NEEDBITS(16)
  687.   if (n != (unsigned)((~b) & 0xffff))
  688.     return 1;                   /* error in compressed data */
  689.   DUMPBITS(16)
  690.  
  691.  
  692.   /* read and output the compressed data */
  693.   while (n--)
  694.   {
  695.     NEEDBITS(8)
  696.     redirSlide[w++] = (uch)b;
  697.     if (w == wsize)
  698.     {
  699.       FLUSH(w);
  700.       w = 0;
  701.     }
  702.     DUMPBITS(8)
  703.   }
  704.  
  705.  
  706.   /* restore the globals from the locals */
  707.   G.wp = w;                       /* restore global window pointer */
  708.   G.bb = b;                       /* restore global bit buffer */
  709.   G.bk = k;
  710.   return 0;
  711. }
  712.  
  713.  
  714. /* Globals for literal tables (built once) */
  715. /* Moved to globals.h                      */
  716. #if 0
  717. struct huft *fixed_tl = (struct huft *)NULL;
  718. struct huft *fixed_td;
  719. int fixed_bl, fixed_bd;
  720. #endif
  721.  
  722. static int inflate_fixed(__G)
  723.      __GDEF
  724. /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
  725.    either replace this with a custom decoder, or at least precompute the
  726.    Huffman tables. */
  727. {
  728.   /* if first time, set up tables for fixed blocks */
  729.   Trace((stderr, "\nliteral block"));
  730.   if (G.fixed_tl == (struct huft *)NULL)
  731.   {
  732.     int i;                /* temporary variable */
  733.     unsigned l[288];      /* length list for huft_build */
  734.  
  735.     /* literal table */
  736.     for (i = 0; i < 144; i++)
  737.       l[i] = 8;
  738.     for (; i < 256; i++)
  739.       l[i] = 9;
  740.     for (; i < 280; i++)
  741.       l[i] = 7;
  742.     for (; i < 288; i++)          /* make a complete, but wrong code set */
  743.       l[i] = 8;
  744.     G.fixed_bl = 7;
  745.     if ((i = huft_build(__G__ l, 288, 257, cplens, cplext,
  746.                         &G.fixed_tl, &G.fixed_bl)) != 0)
  747.     {
  748.       G.fixed_tl = (struct huft *)NULL;
  749.       return i;
  750.     }
  751.  
  752.     /* distance table */
  753.     for (i = 0; i < 30; i++)      /* make an incomplete code set */
  754.       l[i] = 5;
  755.     G.fixed_bd = 5;
  756.     if ((i = huft_build(__G__ l, 30, 0, cpdist, cpdext,
  757.                         &G.fixed_td, &G.fixed_bd)) > 1)
  758.     {
  759.       huft_free(G.fixed_tl);
  760.       G.fixed_tl = (struct huft *)NULL;
  761.       return i;
  762.     }
  763.   }
  764.  
  765.   /* decompress until an end-of-block code */
  766.   return inflate_codes(__G__ G.fixed_tl, G.fixed_td,
  767.                              G.fixed_bl, G.fixed_bd) != 0;
  768. }
  769.  
  770.  
  771.  
  772. static int inflate_dynamic(__G)
  773.   __GDEF
  774. /* decompress an inflated type 2 (dynamic Huffman codes) block. */
  775. {
  776.   int i;                /* temporary variables */
  777.   unsigned j;
  778.   unsigned l;           /* last length */
  779.   unsigned m;           /* mask for bit lengths table */
  780.   unsigned n;           /* number of lengths to get */
  781.   struct huft *tl;      /* literal/length code table */
  782.   struct huft *td;      /* distance code table */
  783.   int bl;               /* lookup bits for tl */
  784.   int bd;               /* lookup bits for td */
  785.   unsigned nb;          /* number of bit length codes */
  786.   unsigned nl;          /* number of literal/length codes */
  787.   unsigned nd;          /* number of distance codes */
  788. #ifdef PKZIP_BUG_WORKAROUND
  789.   unsigned ll[288+32]; /* literal/length and distance code lengths */
  790. #else
  791.   unsigned ll[286+30]; /* literal/length and distance code lengths */
  792. #endif
  793.   register ulg b;       /* bit buffer */
  794.   register unsigned k;  /* number of bits in bit buffer */
  795.  
  796.  
  797.   /* make local bit buffer */
  798.   Trace((stderr, "\ndynamic block"));
  799.   b = G.bb;
  800.   k = G.bk;
  801.  
  802.  
  803.   /* read in table lengths */
  804.   NEEDBITS(5)
  805.   nl = 257 + ((unsigned)b & 0x1f);      /* number of literal/length codes */
  806.   DUMPBITS(5)
  807.   NEEDBITS(5)
  808.   nd = 1 + ((unsigned)b & 0x1f);        /* number of distance codes */
  809.   DUMPBITS(5)
  810.   NEEDBITS(4)
  811.   nb = 4 + ((unsigned)b & 0xf);         /* number of bit length codes */
  812.   DUMPBITS(4)
  813. #ifdef PKZIP_BUG_WORKAROUND
  814.   if (nl > 288 || nd > 32)
  815. #else
  816.   if (nl > 286 || nd > 30)
  817. #endif
  818.     return 1;                   /* bad lengths */
  819.  
  820.  
  821.   /* read in bit-length-code lengths */
  822.   for (j = 0; j < nb; j++)
  823.   {
  824.     NEEDBITS(3)
  825.     ll[border[j]] = (unsigned)b & 7;
  826.     DUMPBITS(3)
  827.   }
  828.   for (; j < 19; j++)
  829.     ll[border[j]] = 0;
  830.  
  831.  
  832.   /* build decoding table for trees--single level, 7 bit lookup */
  833.   bl = 7;
  834.   i = huft_build(__G__ ll, 19, 19, NULL, NULL, &tl, &bl);
  835.   if (bl == 0)                        /* no bit lengths */
  836.     i = 1;
  837.   if (i)
  838.   {
  839.     if (i == 1)
  840.       huft_free(tl);
  841.     return i;                   /* incomplete code set */
  842.   }
  843.  
  844.  
  845.   /* read in literal and distance code lengths */
  846.   n = nl + nd;
  847.   m = mask_bits[bl];
  848.   i = l = 0;
  849.   while ((unsigned)i < n)
  850.   {
  851.     NEEDBITS((unsigned)bl)
  852.     j = (td = tl + ((unsigned)b & m))->b;
  853.     DUMPBITS(j)
  854.     j = td->v.n;
  855.     if (j < 16)                 /* length of code in bits (0..15) */
  856.       ll[i++] = l = j;          /* save last length in l */
  857.     else if (j == 16)           /* repeat last length 3 to 6 times */
  858.     {
  859.       NEEDBITS(2)
  860.       j = 3 + ((unsigned)b & 3);
  861.       DUMPBITS(2)
  862.       if ((unsigned)i + j > n)
  863.         return 1;
  864.       while (j--)
  865.         ll[i++] = l;
  866.     }
  867.     else if (j == 17)           /* 3 to 10 zero length codes */
  868.     {
  869.       NEEDBITS(3)
  870.       j = 3 + ((unsigned)b & 7);
  871.       DUMPBITS(3)
  872.       if ((unsigned)i + j > n)
  873.         return 1;
  874.       while (j--)
  875.         ll[i++] = 0;
  876.       l = 0;
  877.     }
  878.     else                        /* j == 18: 11 to 138 zero length codes */
  879.     {
  880.       NEEDBITS(7)
  881.       j = 11 + ((unsigned)b & 0x7f);
  882.       DUMPBITS(7)
  883.       if ((unsigned)i + j > n)
  884.         return 1;
  885.       while (j--)
  886.         ll[i++] = 0;
  887.       l = 0;
  888.     }
  889.   }
  890.  
  891.  
  892.   /* free decoding table for trees */
  893.   huft_free(tl);
  894.  
  895.  
  896.   /* restore the global bit buffer */
  897.   G.bb = b;
  898.   G.bk = k;
  899.  
  900.  
  901.   /* build the decoding tables for literal/length and distance codes */
  902.   bl = lbits;
  903.   i = huft_build(__G__ ll, nl, 257, cplens, cplext, &tl, &bl);
  904.   if (bl == 0)                        /* no literals or lengths */
  905.     i = 1;
  906.   if (i)
  907.   {
  908.     if (i == 1) {
  909.       if (!G.qflag)
  910.         MESSAGE((uch *)"(incomplete l-tree)  ", 21L, 1);
  911.       huft_free(tl);
  912.     }
  913.     return i;                   /* incomplete code set */
  914.   }
  915.   bd = dbits;
  916.   i = huft_build(__G__ ll + nl, nd, 0, cpdist, cpdext, &td, &bd);
  917.   if (bd == 0 && nl > 257)    /* lengths but no distances */
  918.   {
  919.     if (!G.qflag)
  920.       MESSAGE((uch *)"(incomplete d-tree)  ", 21L, 1);
  921.     huft_free(tl);
  922.     return 1;
  923.   }
  924.   if (i == 1) {
  925. #ifdef PKZIP_BUG_WORKAROUND
  926.     i = 0;
  927. #else
  928.     if (!G.qflag)
  929.       MESSAGE((uch *)"(incomplete d-tree)  ", 21L, 1);
  930.     huft_free(td);
  931. #endif
  932.   }
  933.   if (i)
  934.   {
  935.     huft_free(tl);
  936.     return i;
  937.   }
  938.  
  939.  
  940.   /* decompress until an end-of-block code */
  941.   if (inflate_codes(__G__ tl, td, bl, bd))
  942.     return 1;
  943.  
  944.  
  945.   /* free the decoding tables, return */
  946.   huft_free(tl);
  947.   huft_free(td);
  948.   return 0;
  949. }
  950.  
  951.  
  952.  
  953. static int inflate_block(__G__ e)
  954.   __GDEF
  955.   int *e;               /* last block flag */
  956. /* decompress an inflated block */
  957. {
  958.   unsigned t;           /* block type */
  959.   register ulg b;       /* bit buffer */
  960.   register unsigned k;  /* number of bits in bit buffer */
  961.  
  962.  
  963.   /* make local bit buffer */
  964.   b = G.bb;
  965.   k = G.bk;
  966.  
  967.  
  968.   /* read in last block bit */
  969.   NEEDBITS(1)
  970.   *e = (int)b & 1;
  971.   DUMPBITS(1)
  972.  
  973.  
  974.   /* read in block type */
  975.   NEEDBITS(2)
  976.   t = (unsigned)b & 3;
  977.   DUMPBITS(2)
  978.  
  979.  
  980.   /* restore the global bit buffer */
  981.   G.bb = b;
  982.   G.bk = k;
  983.  
  984.  
  985.   /* inflate that block type */
  986.   if (t == 2)
  987.     return inflate_dynamic(__G);
  988.   if (t == 0)
  989.     return inflate_stored(__G);
  990.   if (t == 1)
  991.     return inflate_fixed(__G);
  992.  
  993.  
  994.   /* bad block type */
  995.   return 2;
  996. }
  997.  
  998.  
  999.  
  1000. int inflate(__G)
  1001.      __GDEF
  1002. /* decompress an inflated entry */
  1003. {
  1004.   int e;                /* last block flag */
  1005.   int r;                /* result code */
  1006.   unsigned h;           /* maximum struct huft's malloc'ed */
  1007.  
  1008. #ifdef DLL
  1009.   if (G.redirect_data)
  1010.     wsize = G.redirect_size, redirSlide = G.redirect_buffer;
  1011.   else
  1012.     wsize = WSIZE, redirSlide = slide;   /* how they're #defined if !DLL */
  1013. #endif
  1014.  
  1015.   /* initialize window, bit buffer */
  1016.   G.wp = 0;
  1017.   G.bk = 0;
  1018.   G.bb = 0;
  1019.  
  1020.  
  1021.   /* decompress until the last block */
  1022.   h = 0;
  1023.   do {
  1024.     G.hufts = 0;
  1025.     if ((r = inflate_block(__G__ &e)) != 0)
  1026.       return r;
  1027.     if (G.hufts > h)
  1028.       h = G.hufts;
  1029.   } while (!e);
  1030.  
  1031.  
  1032.   /* flush out redirSlide */
  1033.   FLUSH(G.wp);
  1034.  
  1035.  
  1036.   /* return success */
  1037.   Trace((stderr, "\n%u bytes in Huffman tables (%d/entry)\n",
  1038.          h * sizeof(struct huft), sizeof(struct huft)));
  1039.   return 0;
  1040. }
  1041.  
  1042.  
  1043.  
  1044. int inflate_free(__G)
  1045.      __GDEF
  1046. {
  1047.   if (G.fixed_tl != (struct huft *)NULL)
  1048.   {
  1049.     huft_free(G.fixed_td);
  1050.     huft_free(G.fixed_tl);
  1051.     G.fixed_td = G.fixed_tl = (struct huft *)NULL;
  1052.   }
  1053.   return 0;
  1054. }
  1055.  
  1056. #endif /* ?USE_ZLIB */
  1057.  
  1058.  
  1059. /*
  1060.  * GRR:  moved huft_build() and huft_free() down here; used by explode()
  1061.  *       and fUnZip regardless of whether USE_ZLIB defined or not
  1062.  */
  1063.  
  1064.  
  1065. /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
  1066. #define BMAX 16         /* maximum bit length of any code (16 for explode) */
  1067. #define N_MAX 288       /* maximum number of codes in any set */
  1068.  
  1069.  
  1070. int huft_build(__G__ b, n, s, d, e, t, m)
  1071.      __GDEF
  1072. unsigned *b;            /* code lengths in bits (all assumed <= BMAX) */
  1073. unsigned n;             /* number of codes (assumed <= N_MAX) */
  1074. unsigned s;             /* number of simple-valued codes (0..s-1) */
  1075. ush *d;                 /* list of base values for non-simple codes */
  1076. ush *e;                 /* list of extra bits for non-simple codes */
  1077. struct huft **t;        /* result: starting table */
  1078. int *m;                 /* maximum lookup bits, returns actual */
  1079. /* Given a list of code lengths and a maximum table size, make a set of
  1080.    tables to decode that set of codes.  Return zero on success, one if
  1081.    the given code set is incomplete (the tables are still built in this
  1082.    case), two if the input is invalid (all zero length codes or an
  1083.    oversubscribed set of lengths), and three if not enough memory.
  1084.    The code with value 256 is special, and the tables are constructed
  1085.    so that no bits beyond that code are fetched when that code is
  1086.    decoded. */
  1087. {
  1088.   unsigned a;                   /* counter for codes of length k */
  1089.   unsigned c[BMAX+1];           /* bit length count table */
  1090.   unsigned el;                  /* length of EOB code (value 256) */
  1091.   unsigned f;                   /* i repeats in table every f entries */
  1092.   int g;                        /* maximum code length */
  1093.   int h;                        /* table level */
  1094.   register unsigned i;          /* counter, current code */
  1095.   register unsigned j;          /* counter */
  1096.   register int k;               /* number of bits in current code */
  1097.   int lx[BMAX+1];               /* memory for l[-1..BMAX-1] */
  1098.   int *l = lx+1;                /* stack of bits per table */
  1099.   register unsigned *p;         /* pointer into c[], b[], or v[] */
  1100.   register struct huft *q;      /* points to current table */
  1101.   struct huft r;                /* table entry for structure assignment */
  1102.   struct huft *u[BMAX];         /* table stack */
  1103.   unsigned v[N_MAX];            /* values in order of bit length */
  1104.   register int w;               /* bits before this table == (l * h) */
  1105.   unsigned x[BMAX+1];           /* bit offsets, then code stack */
  1106.   unsigned *xp;                 /* pointer into x */
  1107.   int y;                        /* number of dummy codes added */
  1108.   unsigned z;                   /* number of entries in current table */
  1109.  
  1110.  
  1111.   /* Generate counts for each bit length */
  1112.   el = n > 256 ? b[256] : BMAX; /* set length of EOB code, if any */
  1113.   memzero((char *)c, sizeof(c));
  1114.   p = b;  i = n;
  1115.   do {
  1116.     c[*p]++; p++;               /* assume all entries <= BMAX */
  1117.   } while (--i);
  1118.   if (c[0] == n)                /* null input--all zero length codes */
  1119.   {
  1120.     *t = (struct huft *)NULL;
  1121.     *m = 0;
  1122.     return 0;
  1123.   }
  1124.  
  1125.  
  1126.   /* Find minimum and maximum length, bound *m by those */
  1127.   for (j = 1; j <= BMAX; j++)
  1128.     if (c[j])
  1129.       break;
  1130.   k = j;                        /* minimum code length */
  1131.   if ((unsigned)*m < j)
  1132.     *m = j;
  1133.   for (i = BMAX; i; i--)
  1134.     if (c[i])
  1135.       break;
  1136.   g = i;                        /* maximum code length */
  1137.   if ((unsigned)*m > i)
  1138.     *m = i;
  1139.  
  1140.  
  1141.   /* Adjust last length count to fill out codes, if needed */
  1142.   for (y = 1 << j; j < i; j++, y <<= 1)
  1143.     if ((y -= c[j]) < 0)
  1144.       return 2;                 /* bad input: more codes than bits */
  1145.   if ((y -= c[i]) < 0)
  1146.     return 2;
  1147.   c[i] += y;
  1148.  
  1149.  
  1150.   /* Generate starting offsets into the value table for each length */
  1151.   x[1] = j = 0;
  1152.   p = c + 1;  xp = x + 2;
  1153.   while (--i) {                 /* note that i == g from above */
  1154.     *xp++ = (j += *p++);
  1155.   }
  1156.  
  1157.  
  1158.   /* Make a table of values in order of bit lengths */
  1159.   memzero((char *)v, sizeof(v));
  1160.   p = b;  i = 0;
  1161.   do {
  1162.     if ((j = *p++) != 0)
  1163.       v[x[j]++] = i;
  1164.   } while (++i < n);
  1165.   n = x[g];                     /* set n to length of v */
  1166.  
  1167.  
  1168.   /* Generate the Huffman codes and for each, make the table entries */
  1169.   x[0] = i = 0;                 /* first Huffman code is zero */
  1170.   p = v;                        /* grab values in bit order */
  1171.   h = -1;                       /* no tables yet--level -1 */
  1172.   w = l[-1] = 0;                /* no bits decoded yet */
  1173.   u[0] = (struct huft *)NULL;   /* just to keep compilers happy */
  1174.   q = (struct huft *)NULL;      /* ditto */
  1175.   z = 0;                        /* ditto */
  1176.  
  1177.   /* go through the bit lengths (k already is bits in shortest code) */
  1178.   for (; k <= g; k++)
  1179.   {
  1180.     a = c[k];
  1181.     while (a--)
  1182.     {
  1183.       /* here i is the Huffman code of length k bits for value *p */
  1184.       /* make tables up to required level */
  1185.       while (k > w + l[h])
  1186.       {
  1187.         w += l[h++];            /* add bits already decoded */
  1188.  
  1189.         /* compute minimum size table less than or equal to *m bits */
  1190.         z = (z = g - w) > (unsigned)*m ? *m : z;        /* upper limit */
  1191.         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
  1192.         {                       /* too few codes for k-w bit table */
  1193.           f -= a + 1;           /* deduct codes from patterns left */
  1194.           xp = c + k;
  1195.           while (++j < z)       /* try smaller tables up to z bits */
  1196.           {
  1197.             if ((f <<= 1) <= *++xp)
  1198.               break;            /* enough codes to use up j bits */
  1199.             f -= *xp;           /* else deduct codes from patterns */
  1200.           }
  1201.         }
  1202.         if ((unsigned)w + j > el && (unsigned)w < el)
  1203.           j = el - w;           /* make EOB code end at table */
  1204.         z = 1 << j;             /* table entries for j-bit table */
  1205.         l[h] = j;               /* set table size in stack */
  1206.  
  1207.         /* allocate and link in new table */
  1208.         if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) ==
  1209.             (struct huft *)NULL)
  1210.         {
  1211.           if (h)
  1212.             huft_free(u[0]);
  1213.           return 3;             /* not enough memory */
  1214.         }
  1215.         G.hufts += z + 1;         /* track memory usage */
  1216.         *t = q + 1;             /* link to list for huft_free() */
  1217.         *(t = &(q->v.t)) = (struct huft *)NULL;
  1218.         u[h] = ++q;             /* table starts after link */
  1219.  
  1220.         /* connect to last table, if there is one */
  1221.         if (h)
  1222.         {
  1223.           x[h] = i;             /* save pattern for backing up */
  1224.           r.b = (uch)l[h-1];    /* bits to dump before this table */
  1225.           r.e = (uch)(16 + j);  /* bits in this table */
  1226.           r.v.t = q;            /* pointer to this table */
  1227.           j = (i & ((1 << w) - 1)) >> (w - l[h-1]);
  1228.           u[h-1][j] = r;        /* connect to last table */
  1229.         }
  1230.       }
  1231.  
  1232.       /* set up table entry in r */
  1233.       r.b = (uch)(k - w);
  1234.       if (p >= v + n)
  1235.         r.e = 99;               /* out of values--invalid code */
  1236.       else if (*p < s)
  1237.       {
  1238.         r.e = (uch)(*p < 256 ? 16 : 15);  /* 256 is end-of-block code */
  1239.         r.v.n = (ush)*p++;                /* simple code is just the value */
  1240.       }
  1241.       else
  1242.       {
  1243.         r.e = (uch)e[*p - s];   /* non-simple--look up in lists */
  1244.         r.v.n = d[*p++ - s];
  1245.       }
  1246.  
  1247.       /* fill code-like entries with r */
  1248.       f = 1 << (k - w);
  1249.       for (j = i >> w; j < z; j += f)
  1250.         q[j] = r;
  1251.  
  1252.       /* backwards increment the k-bit code i */
  1253.       for (j = 1 << (k - 1); i & j; j >>= 1)
  1254.         i ^= j;
  1255.       i ^= j;
  1256.  
  1257.       /* backup over finished tables */
  1258.       while ((i & ((1 << w) - 1)) != x[h])
  1259.         w -= l[--h];            /* don't need to update q */
  1260.     }
  1261.   }
  1262.  
  1263.  
  1264.   /* return actual size of base table */
  1265.   *m = l[0];
  1266.  
  1267.  
  1268.   /* Return true (1) if we were given an incomplete table */
  1269.   return y != 0 && g != 1;
  1270. }
  1271.  
  1272.  
  1273.  
  1274. int huft_free(t)
  1275. struct huft *t;         /* table to free */
  1276. /* Free the malloc'ed tables built by huft_build(), which makes a linked
  1277.    list of the tables it made, with the links in a dummy first entry of
  1278.    each table. */
  1279. {
  1280.   register struct huft *p, *q;
  1281.  
  1282.  
  1283.   /* Go through linked list, freeing from the malloced (t[-1]) address. */
  1284.   p = t;
  1285.   while (p != (struct huft *)NULL)
  1286.   {
  1287.     q = (--p)->v.t;
  1288.     free((zvoid *)p);
  1289.     p = q;
  1290.   }
  1291.   return 0;
  1292. }
  1293.