ZInflate.c

Go to the documentation of this file.
00001 /* @(#)root/zip:$Id: ZInflate.c 37986 2011-02-04 21:42:15Z pcanal $ */
00002 /* Author: */
00003 #include <stdio.h>
00004 #include <stdlib.h>
00005 #include <string.h>
00006 
00007 #ifdef WIN32
00008 #define __STDC__
00009 #endif
00010 #ifdef __MWERKS__
00011 #define __STDC__
00012 #endif
00013 
00014 #ifndef NULL
00015 #define NULL 0L
00016 #endif
00017 
00018 static const int qflag = 0;
00019 
00020 #include "zlib.h"
00021 
00022 /* inflate.c -- put in the public domain by Mark Adler
00023    version c14o, 23 August 1994 */
00024 
00025 
00026 /* You can do whatever you like with this source file, though I would
00027    prefer that if you modify it and redistribute it that you include
00028    comments to that effect with your name and the date.  Thank you.
00029 
00030    History:
00031    vers    date          who           what
00032    ----  ---------  --------------  ------------------------------------
00033     a    ~~ Feb 92  M. Adler        used full (large, one-step) lookup table
00034     b1   21 Mar 92  M. Adler        first version with partial lookup tables
00035     b2   21 Mar 92  M. Adler        fixed bug in fixed-code blocks
00036     b3   22 Mar 92  M. Adler        sped up match copies, cleaned up some
00037     b4   25 Mar 92  M. Adler        added prototypes; removed window[] (now
00038                                     is the responsibility of unzip.h--also
00039                                     changed name to slide[]), so needs diffs
00040                                     for unzip.c and unzip.h (this allows
00041                                     compiling in the small model on MSDOS);
00042                                     fixed cast of q in huft_build();
00043     b5   26 Mar 92  M. Adler        got rid of unintended macro recursion.
00044     b6   27 Mar 92  M. Adler        got rid of nextbyte() routine.  fixed
00045                                     bug in inflate_fixed().
00046     c1   30 Mar 92  M. Adler        removed lbits, dbits environment variables.
00047                                     changed BMAX to 16 for explode.  Removed
00048                                     OUTB usage, and replaced it with flush()--
00049                                     this was a 20% speed improvement!  Added
00050                                     an explode.c (to replace unimplod.c) that
00051                                     uses the huft routines here.  Removed
00052                                     register union.
00053     c2    4 Apr 92  M. Adler        fixed bug for file sizes a multiple of 32k.
00054     c3   10 Apr 92  M. Adler        reduced memory of code tables made by
00055                                     huft_build significantly (factor of two to
00056                                     three).
00057     c4   15 Apr 92  M. Adler        added NOMEMCPY do kill use of memcpy().
00058                                     worked around a Turbo C optimization bug.
00059     c5   21 Apr 92  M. Adler        added the WSIZE #define to allow reducing
00060                                     the 32K window size for specialized
00061                                     applications.
00062     c6   31 May 92  M. Adler        added some typecasts to eliminate warnings
00063     c7   27 Jun 92  G. Roelofs      added some more typecasts (444:  MSC bug).
00064     c8    5 Oct 92  J-l. Gailly     added ifdef'd code to deal with PKZIP bug.
00065     c9    9 Oct 92  M. Adler        removed a memory error message (~line 416).
00066     c10  17 Oct 92  G. Roelofs      changed ULONG/UWORD/byte to ulg/ush/uch,
00067                                     removed old inflate, renamed inflate_entry
00068                                     to inflate, added Mark's fix to a comment.
00069    c10.5 14 Dec 92  M. Adler        fix up error messages for incomplete trees.
00070     c11   2 Jan 93  M. Adler        fixed bug in detection of incomplete
00071                                     tables, and removed assumption that EOB is
00072                                     the longest code (bad assumption).
00073     c12   3 Jan 93  M. Adler        make tables for fixed blocks only once.
00074     c13   5 Jan 93  M. Adler        allow all zero length codes (pkzip 2.04c
00075                                     outputs one zero length code for an empty
00076                                     distance tree).
00077     c14  12 Mar 93  M. Adler        made inflate.c standalone with the
00078                                     introduction of inflate.h.
00079    c14b  16 Jul 93  G. Roelofs      added (unsigned) typecast to w at 470.
00080    c14c  19 Jul 93  J. Bush         changed v[N_MAX], l[288], ll[28x+3x] arrays
00081                                     to static for Amiga.
00082    c14d  13 Aug 93  J-l. Gailly     de-complicatified Mark's c[*p++]++ thing.
00083    c14e   8 Oct 93  G. Roelofs      changed memset() to memzero().
00084    c14f  22 Oct 93  G. Roelofs      renamed quietflg to qflag; made Trace()
00085                                     conditional; added inflate_free().
00086    c14g  28 Oct 93  G. Roelofs      changed l/(lx+1) macro to pointer (Cray bug)
00087    c14h   7 Dec 93  C. Ghisler      huft_build() optimizations.
00088    c14i   9 Jan 94  A. Verheijen    set fixed_t{d,l} to NULL after freeing;
00089                     G. Roelofs      check NEXTBYTE macro for EOF.
00090    c14j  23 Jan 94  G. Roelofs      removed Ghisler "optimizations"; ifdef'd
00091                                     EOF check.
00092    c14k  27 Feb 94  G. Roelofs      added some typecasts to avoid warnings.
00093    c14l   9 Apr 94  G. Roelofs      fixed split comments on preprocessor lines
00094                                     to avoid bug in Encore compiler.
00095    c14m   7 Jul 94  P. Kienitz      modified to allow assembler version of
00096                                     inflate_codes() (define ASM_INFLATECODES)
00097    c14n  22 Jul 94  G. Roelofs      changed fprintf to FPRINTF for DLL versions
00098    c14o  23 Aug 94  C. Spieler      added a newline to a debug statement;
00099                     G. Roelofs      added another typecast to avoid MSC warning
00100  */
00101 
00102 
00103 /*
00104    Inflate deflated (PKZIP's method 8 compressed) data.  The compression
00105    method searches for as much of the current string of bytes (up to a
00106    length of 258) in the previous 32K bytes.  If it doesn't find any
00107    matches (of at least length 3), it codes the next byte.  Otherwise, it
00108    codes the length of the matched string and its distance backwards from
00109    the current position.  There is a single Huffman code that codes both
00110    single bytes (called "literals") and match lengths.  A second Huffman
00111    code codes the distance information, which follows a length code.  Each
00112    length or distance code actually represents a base value and a number
00113    of "extra" (sometimes zero) bits to get to add to the base value.  At
00114    the end of each deflated block is a special end-of-block (EOB) literal/
00115    length code.  The decoding process is basically: get a literal/length
00116    code; if EOB then done; if a literal, emit the decoded byte; if a
00117    length then get the distance and emit the referred-to bytes from the
00118    sliding window of previously emitted data.
00119 
00120    There are (currently) three kinds of inflate blocks: stored, fixed, and
00121    dynamic.  The compressor outputs a chunk of data at a time and decides
00122    which method to use on a chunk-by-chunk basis.  A chunk might typically
00123    be 32K to 64K, uncompressed.  If the chunk is uncompressible, then the
00124    "stored" method is used.  In this case, the bytes are simply stored as
00125    is, eight bits per byte, with none of the above coding.  The bytes are
00126    preceded by a count, since there is no longer an EOB code.
00127 
00128    If the data is compressible, then either the fixed or dynamic methods
00129    are used.  In the dynamic method, the compressed data is preceded by
00130    an encoding of the literal/length and distance Huffman codes that are
00131    to be used to decode this block.  The representation is itself Huffman
00132    coded, and so is preceded by a description of that code.  These code
00133    descriptions take up a little space, and so for small blocks, there is
00134    a predefined set of codes, called the fixed codes.  The fixed method is
00135    used if the block ends up smaller that way (usually for quite small
00136    chunks); otherwise the dynamic method is used.  In the latter case, the
00137    codes are customized to the probabilities in the current block and so
00138    can code it much better than the pre-determined fixed codes can.
00139 
00140    The Huffman codes themselves are decoded using a mutli-level table
00141    lookup, in order to maximize the speed of decoding plus the speed of
00142    building the decoding tables.  See the comments below that precede the
00143    lbits and dbits tuning parameters.
00144  */
00145 
00146 
00147 /*
00148    Notes beyond the 1.93a appnote.txt:
00149 
00150    1. Distance pointers never point before the beginning of the output
00151       stream.
00152    2. Distance pointers can point back across blocks, up to 32k away.
00153    3. There is an implied maximum of 7 bits for the bit length table and
00154       15 bits for the actual data.
00155    4. If only one code exists, then it is encoded using one bit.  (Zero
00156       would be more efficient, but perhaps a little confusing.)  If two
00157       codes exist, they are coded using one bit each (0 and 1).
00158    5. There is no way of sending zero distance codes--a dummy must be
00159       sent if there are none.  (History: a pre 2.0 version of PKZIP would
00160       store blocks with no distance codes, but this was discovered to be
00161       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
00162       zero distance codes, which is sent as one code of zero bits in
00163       length.
00164    6. There are up to 286 literal/length codes.  Code 256 represents the
00165       end-of-block.  Note however that the static length tree defines
00166       288 codes just to fill out the Huffman codes.  Codes 286 and 287
00167       cannot be used though, since there is no length base or extra bits
00168       defined for them.  Similarily, there are up to 30 distance codes.
00169       However, static trees define 32 codes (all 5 bits) to fill out the
00170       Huffman codes, but the last two had better not show up in the data.
00171    7. Unzip can check dynamic Huffman blocks for complete code sets.
00172       The exception is that a single code would not be complete (see #4).
00173    8. The five bits following the block type is really the number of
00174       literal codes sent minus 257.
00175    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
00176       (1+6+6).  Therefore, to output three times the length, you output
00177       three codes (1+1+1), whereas to output four times the same length,
00178       you only need two codes (1+3).  Hmm.
00179   10. In the tree reconstruction algorithm, Code = Code + Increment
00180       only if BitLength(i) is not zero.  (Pretty obvious.)
00181   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
00182   12. Note: length code 284 can represent 227-258, but length code 285
00183       really is 258.  The last length deserves its own, short code
00184       since it gets used a lot in very redundant files.  The length
00185       258 is special since 258 - 3 (the min match length) is 255.
00186   13. The literal/length and distance code bit lengths are read as a
00187       single stream of lengths.  It is possible (and advantageous) for
00188       a repeat code (16, 17, or 18) to go across the boundary between
00189       the two sets of lengths.
00190  */
00191 
00192 
00193 #if 0
00194 #define PKZIP_BUG_WORKAROUND    /* PKZIP 1.93a problem--live with it */
00195 #endif
00196 
00197 /*
00198     inflate.h must supply the uch slide[WSIZE] array and the NEXTBYTE,
00199     FLUSH() and memzero macros.  If the window size is not 32K, it
00200     should also define WSIZE.  If INFMOD is defined, it can include
00201     compiled functions to support the NEXTBYTE and/or FLUSH() macros.
00202     There are defaults for NEXTBYTE and FLUSH() below for use as
00203     examples of what those functions need to do.  Normally, you would
00204     also want FLUSH() to compute a crc on the data.  inflate.h also
00205     needs to provide these typedefs:
00206 
00207         typedef unsigned char uch;
00208         typedef unsigned short ush;
00209         typedef unsigned long ulg;
00210 
00211     This module uses the external functions malloc() and free() (and
00212     probably memset() or bzero() in the memzero() macro).  Their
00213     prototypes are normally found in <string.h> and <stdlib.h>.
00214  */
00215 #define INFMOD          /* tell inflate.h to include code to be compiled */
00216 #if 0
00217 #include "Inflate.h"
00218 #endif
00219 
00220 typedef char              boolean;
00221 typedef unsigned char     uch;  /* code assumes unsigned bytes; these type-  */
00222 typedef unsigned short    ush;  /*  defs replace byte/UWORD/ULONG (which are */
00223 typedef unsigned long     ulg;  /*  predefined on some systems) & match zip  */
00224 
00225 #ifndef WSIZE           /* default is 32K */
00226 #  define WSIZE 0x8000  /* window size--must be a power of two, and at least */
00227 #endif                  /* 32K for zip's deflate method */
00228 
00229 #ifndef NEXTBYTE        /* default is to simply get a byte from stdin */
00230 #  define NEXTBYTE R__ReadByte()
00231 #endif
00232 
00233 #ifndef FPRINTF
00234 #  define FPRINTF fprintf
00235 #endif
00236 
00237 #ifndef FLUSH           /* default is to simply write the buffer to stdout */
00238 #  define FLUSH(n,obufptr,obufcnt,R__slide) R__WriteData(n,obufptr,obufcnt,R__slide)  /* return value not used */
00239 #endif
00240 /* Warning: the fwrite above might not work on 16-bit compilers, since
00241    0x8000 might be interpreted as -32,768 by the library function. */
00242 
00243 #ifndef Trace
00244 #  ifdef DEBUG
00245 #    define Trace(x) fprintf x
00246 #  else
00247 #    define Trace(x)
00248 #  endif
00249 #endif
00250 
00251 
00252 /* Huffman code lookup table entry--this entry is four bytes for machines
00253    that have 16-bit pointers (e.g. PC's in the small or medium model).
00254    Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
00255    means that v is a literal, 16 < e < 32 means that v is a pointer to
00256    the next table, which codes e - 16 bits, and lastly e == 99 indicates
00257    an unused code.  If a code with e == 99 is looked up, this implies an
00258    error in the data. */
00259 struct huft {
00260   uch e;                /* number of extra bits or operation */
00261   uch b;                /* number of bits in this code or subcode */
00262   union {
00263     ush n;              /* literal, length base, or distance base */
00264     struct huft *t;     /* pointer to next level of table */
00265   } v;
00266 };
00267 
00268 
00269 /* Function prototypes */
00270 #ifndef OF
00271 #  ifdef __STDC__
00272 #    define OF(a) a
00273 #  else /* !__STDC__ */
00274 #    define OF(a) ()
00275 #  endif /* ?__STDC__ */
00276 #endif
00277 int R__huft_build OF((unsigned *, unsigned, unsigned, const ush *, const ush *,
00278                    struct huft **, int *, unsigned*));
00279 int R__huft_free OF((struct huft *));
00280 int R__Inflate_codes OF((struct huft *, struct huft *, int, int, uch**, long*, uch**, long*, ulg*, unsigned*, uch* , unsigned*));
00281 int R__Inflate_stored OF((uch**, long*, uch**, long*, ulg*, unsigned*, uch* , unsigned*));
00282 int R__Inflate_fixed OF((uch**, long*, uch**, long*, ulg*, unsigned*, uch* , unsigned*, unsigned*));
00283 int R__Inflate_dynamic OF((uch**, long*, uch**, long*, ulg*, unsigned*, uch* , unsigned*, unsigned*));
00284 int R__Inflate_block OF((int *, uch**, long*, uch**, long*, ulg*, unsigned*, uch* , unsigned*, unsigned*));
00285 int R__Inflate OF((uch**, long*, uch**, long*));
00286 int R__Inflate_free OF((void));
00287 
00288 /* Tables for deflate from PKZIP's appnote.txt. */
00289 static const unsigned border[] = {    /* Order of the bit length code lengths */
00290         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
00291 static const ush cplens[] = {         /* Copy lengths for literal codes 257..285 */
00292         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
00293         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
00294         /* note: see note #13 above about the 258 in this list. */
00295 static const ush cplext[] = {         /* Extra bits for literal codes 257..285 */
00296         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
00297         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
00298 static const ush cpdist[] = {         /* Copy offsets for distance codes 0..29 */
00299         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
00300         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
00301         8193, 12289, 16385, 24577};
00302 static const ush cpdext[] = {         /* Extra bits for distance codes */
00303         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
00304         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
00305         12, 12, 13, 13};
00306 
00307 /* And'ing with mask[n] masks the lower n bits */
00308 static const ush mask[] = {
00309     0x0000,
00310     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
00311     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
00312 };
00313 
00314 
00315 /* Macros for inflate() bit peeking and grabbing.
00316    The usage is:
00317 
00318         NEEDBITS(j)
00319         x = b & mask[j];
00320         DUMPBITS(j)
00321 
00322    where NEEDBITS makes sure that b has at least j bits in it, and
00323    DUMPBITS removes the bits from b.  The macros use the variable k
00324    for the number of bits in b.  Normally, b and k are register
00325    variables for speed, and are initialized at the begining of a
00326    routine that uses these macros from a global bit buffer and count.
00327 
00328    In order to not ask for more bits than there are in the compressed
00329    stream, the Huffman tables are constructed to only ask for just
00330    enough bits to make up the end-of-block code (value 256).  Then no
00331    bytes need to be "returned" to the buffer at the end of the last
00332    block.  See the huft_build() routine.
00333  */
00334 
00335 #define CHECK_EOF
00336 
00337 #ifndef CHECK_EOF
00338 static int  R__ReadByte((uch  *, long*));
00339 #endif
00340 static void R__WriteData OF((int,uch**,long*,uch*));
00341 
00342 #ifndef CHECK_EOF
00343 #  define NEEDBITS(n,b,k,ibufptr,ibufcnt) {while((k)<(n)){(b)|=((ulg)NEXTBYTE)<<(k);(k)+=8;}}
00344 #else
00345 #  define NEEDBITS(n,b,k,ibufptr,ibufcnt) {while((k)<(n)){if((ibufcnt)-- <= 0)return 1;\
00346    (b)|=((ulg) *(ibufptr)++)<<(k);(k)+=8;}}
00347 #endif                      /* Piet Plomp:  change "return 1" to "break" */
00348 
00349 #define DUMPBITS(n,b,k) {(b)>>=(n);(k)-=(n);}
00350 
00351 
00352 /*
00353    Huffman code decoding is performed using a multi-level table lookup.
00354    The fastest way to decode is to simply build a lookup table whose
00355    size is determined by the longest code.  However, the time it takes
00356    to build this table can also be a factor if the data being decoded
00357    is not very long.  The most common codes are necessarily the
00358    shortest codes, so those codes dominate the decoding time, and hence
00359    the speed.  The idea is you can have a shorter table that decodes the
00360    shorter, more probable codes, and then point to subsidiary tables for
00361    the longer codes.  The time it costs to decode the longer codes is
00362    then traded against the time it takes to make longer tables.
00363 
00364    This results of this trade are in the variables lbits and dbits
00365    below.  lbits is the number of bits the first level table for literal/
00366    length codes can decode in one step, and dbits is the same thing for
00367    the distance codes.  Subsequent tables are also less than or equal to
00368    those sizes.  These values may be adjusted either when all of the
00369    codes are shorter than that, in which case the longest code length in
00370    bits is used, or when the shortest code is *longer* than the requested
00371    table size, in which case the length of the shortest code in bits is
00372    used.
00373 
00374    There are two different values for the two tables, since they code a
00375    different number of possibilities each.  The literal/length table
00376    codes 286 possible values, or in a flat code, a little over eight
00377    bits.  The distance table codes 30 possible values, or a little less
00378    than five bits, flat.  The optimum values for speed end up being
00379    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
00380    The optimum values may differ though from machine to machine, and
00381    possibly even between compilers.  Your mileage may vary.
00382  */
00383 
00384 
00385 static const int lbits = 9;    /* bits in base literal/length lookup table */
00386 static const int dbits = 6;    /* bits in base distance lookup table */
00387 
00388 
00389 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
00390 #define BMAX 16         /* maximum bit length of any code (16 for explode) */
00391 #define N_MAX 288       /* maximum number of codes in any set */
00392 
00393 
00394 int R__huft_build(unsigned *b, unsigned n, unsigned s, const ush *d, const ush *e, struct huft **t, int *m, unsigned* hufts)
00395 /* unsigned *b;             code lengths in bits (all assumed <= BMAX) */
00396 /* unsigned n;              number of codes (assumed <= N_MAX) */
00397 /* unsigned s;              number of simple-valued codes (0..s-1) */
00398 /* ush *d;                  list of base values for non-simple codes */
00399 /* ush *e;                  list of extra bits for non-simple codes */
00400 /* struct huft **t;         result: starting table */
00401 /* int *m;                  maximum lookup bits, returns actual */
00402 /* Given a list of code lengths and a maximum table size, make a set of
00403    tables to decode that set of codes.  Return zero on success, one if
00404    the given code set is incomplete (the tables are still built in this
00405    case), two if the input is invalid (all zero length codes or an
00406    oversubscribed set of lengths), and three if not enough memory.
00407    The code with value 256 is special, and the tables are constructed
00408    so that no bits beyond that code are fetched when that code is
00409    decoded. */
00410 {
00411   unsigned a;                   /* counter for codes of length k */
00412   unsigned c[BMAX+1];           /* bit length count table */
00413   unsigned el;                  /* length of EOB code (value 256) */
00414   unsigned f;                   /* i repeats in table every f entries */
00415   int g;                        /* maximum code length */
00416   int h;                        /* table level */
00417   register unsigned i;          /* counter, current code */
00418   register unsigned j;          /* counter */
00419   register int k;               /* number of bits in current code */
00420   int lx[BMAX+1];               /* memory for l[-1..BMAX-1] */
00421   int *l = lx+1;                /* stack of bits per table */
00422   register unsigned *p;         /* pointer into c[], b[], or v[] */
00423   register struct huft *q;      /* points to current table */
00424   struct huft r;                /* table entry for structure assignment */
00425   struct huft *u[BMAX];         /* table stack */
00426   /*static*/ unsigned v[N_MAX];     /* values in order of bit length */
00427   register int w;               /* bits before this table == (l * h) */
00428   unsigned x[BMAX+1];           /* bit offsets, then code stack */
00429   unsigned *xp;                 /* pointer into x */
00430   int y;                        /* number of dummy codes added */
00431   unsigned z;                   /* number of entries in current table */
00432 
00433 
00434   /* Generate counts for each bit length */
00435   el = n > 256 ? b[256] : BMAX; /* set length of EOB code, if any */
00436   memset((char *)c,0,sizeof(c));
00437   p = b;  i = n;
00438   do {
00439     c[*p]++; p++;               /* assume all entries <= BMAX */
00440   } while (--i);
00441   if (c[0] == n)                /* null input--all zero length codes */
00442   {
00443     *t = (struct huft *)NULL;
00444     *m = 0;
00445     return 0;
00446   }
00447 
00448 
00449   /* Find minimum and maximum length, bound *m by those */
00450   for (j = 1; j <= BMAX; j++)
00451     if (c[j])
00452       break;
00453   k = j;                        /* minimum code length */
00454   if ((unsigned)*m < j)
00455     *m = j;
00456   for (i = BMAX; i; i--)
00457     if (c[i])
00458       break;
00459   g = i;                        /* maximum code length */
00460   if ((unsigned)*m > i)
00461     *m = i;
00462 
00463 
00464   /* Adjust last length count to fill out codes, if needed */
00465   for (y = 1 << j; j < i; j++, y <<= 1)
00466     if ((y -= c[j]) < 0)
00467       return 2;                 /* bad input: more codes than bits */
00468   if ((y -= c[i]) < 0)
00469     return 2;
00470   c[i] += y;
00471 
00472 
00473   /* Generate starting offsets into the value table for each length */
00474   x[1] = j = 0;
00475   p = c + 1;  xp = x + 2;
00476   while (--i) {                 /* note that i == g from above */
00477     *xp++ = (j += *p++);
00478   }
00479 
00480 
00481   /* Make a table of values in order of bit lengths */
00482   p = b;  i = 0;
00483   do {
00484     if ((j = *p++) != 0)
00485       v[x[j]++] = i;
00486   } while (++i < n);
00487 
00488 
00489   /* Generate the Huffman codes and for each, make the table entries */
00490   x[0] = i = 0;                 /* first Huffman code is zero */
00491   p = v;                        /* grab values in bit order */
00492   h = -1;                       /* no tables yet--level -1 */
00493   w = l[-1] = 0;                /* no bits decoded yet */
00494   u[0] = (struct huft *)NULL;   /* just to keep compilers happy */
00495   q = (struct huft *)NULL;      /* ditto */
00496   z = 0;                        /* ditto */
00497 
00498   /* go through the bit lengths (k already is bits in shortest code) */
00499   for (; k <= g; k++)
00500   {
00501     a = c[k];
00502     while (a--)
00503     {
00504       /* here i is the Huffman code of length k bits for value *p */
00505       /* make tables up to required level */
00506       while (k > w + l[h])
00507       {
00508         w += l[h++];            /* add bits already decoded */
00509 
00510         /* compute minimum size table less than or equal to *m bits */
00511         z = (z = g - w) > (unsigned)*m ? (unsigned) *m : z;   /* upper limit */
00512         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
00513         {                       /* too few codes for k-w bit table */
00514           f -= a + 1;           /* deduct codes from patterns left */
00515           xp = c + k;
00516           while (++j < z)       /* try smaller tables up to z bits */
00517           {
00518             if ((f <<= 1) <= *++xp)
00519               break;            /* enough codes to use up j bits */
00520             f -= *xp;           /* else deduct codes from patterns */
00521           }
00522         }
00523         if ((unsigned)w + j > el && (unsigned)w < el)
00524           j = el - w;           /* make EOB code end at table */
00525         z = 1 << j;             /* table entries for j-bit table */
00526         l[h] = j;               /* set table size in stack */
00527 
00528         /* allocate and link in new table */
00529         if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) ==
00530             (struct huft *)NULL)
00531         {
00532           if (h)
00533             R__huft_free(u[0]);
00534           return 3;             /* not enough memory */
00535         }
00536         (*hufts) += z + 1;         /* track memory usage */
00537         *t = q + 1;             /* link to list for huft_free() */
00538         *(t = &(q->v.t)) = (struct huft *)NULL;
00539         u[h] = ++q;             /* table starts after link */
00540 
00541         /* connect to last table, if there is one */
00542         if (h)
00543         {
00544           x[h] = i;             /* save pattern for backing up */
00545           r.b = (uch)l[h-1];    /* bits to dump before this table */
00546           r.e = (uch)(16 + j);  /* bits in this table */
00547           r.v.t = q;            /* pointer to this table */
00548           j = (i & ((1 << w) - 1)) >> (w - l[h-1]);
00549           u[h-1][j] = r;        /* connect to last table */
00550         }
00551       }
00552 
00553       /* set up table entry in r */
00554       r.b = (uch)(k - w);
00555       if (p >= v + n)
00556         r.e = 99;               /* out of values--invalid code */
00557       else if (*p < s) {
00558         r.e = (uch)(*p < 256 ? 16 : 15);    /* 256 is end-of-block code */
00559         r.v.n = *p++;           /* simple code is just the value */
00560       } else if(e && d) {
00561         r.e = (uch)e[*p - s];   /* non-simple--look up in lists */
00562         r.v.n = d[*p++ - s];
00563       } else return 1;
00564 
00565       /* fill code-like entries with r */
00566       f = 1 << (k - w);
00567       for (j = i >> w; j < z; j += f)
00568         q[j] = r;
00569 
00570       /* backwards increment the k-bit code i */
00571       for (j = 1 << (k - 1); i & j; j >>= 1)
00572         i ^= j;
00573       i ^= j;
00574 
00575       /* backup over finished tables */
00576       while ((i & ((1 << w) - 1)) != x[h])
00577         w -= l[--h];            /* don't need to update q */
00578     }
00579   }
00580 
00581 
00582   /* return actual size of base table */
00583   *m = l[0];
00584 
00585 
00586   /* Return true (1) if we were given an incomplete table */
00587   return y != 0 && g != 1;
00588 }
00589 
00590 
00591 
00592 int R__huft_free(struct huft *t)
00593 /* struct huft *t;          table to free */
00594 /* Free the malloc'ed tables built by huft_build(), which makes a linked
00595    list of the tables it made, with the links in a dummy first entry of
00596    each table. */
00597 {
00598   register struct huft *p, *q;
00599 
00600 
00601   /* Go through linked list, freeing from the malloced (t[-1]) address. */
00602   p = t;
00603   while (p != (struct huft *)NULL)
00604   {
00605     q = (--p)->v.t;
00606     free(p);
00607     p = q;
00608   }
00609   return 0;
00610 }
00611 
00612 
00613 
00614 #ifdef ASM_INFLATECODES
00615 #  define R__Inflate_codes(tl,td,bl,bd)  R__Flate_codes(tl,td,bl,bd,(uch *)R__slide)
00616    int R__Flate_codes OF((struct huft *, struct huft *, int, int, uch *));
00617 
00618 #else
00619 
00620 int R__Inflate_codes(struct huft *tl, struct huft *td, int bl, int bd, uch** ibufptr, long*  ibufcnt, uch** obufptr, long*  obufcnt, ulg* bb, unsigned* bk, uch* R__slide, unsigned* wp)
00621 /* struct huft *tl, *td;    literal/length and distance decoder tables */
00622 /* int bl, bd;              number of bits decoded by tl[] and td[] */
00623 /* inflate (decompress) the codes in a deflated (compressed) block.
00624    Return an error code or zero if it all goes ok. */
00625 {
00626   register unsigned e;  /* table entry flag/number of extra bits */
00627   unsigned n, d;        /* length and index for copy */
00628   unsigned w;           /* current window position */
00629   struct huft *t;       /* pointer to table entry */
00630   unsigned ml, md;      /* masks for bl and bd bits */
00631   register ulg b;       /* bit buffer */
00632   register unsigned k;  /* number of bits in bit buffer */
00633 
00634 
00635   /* make local copies of globals */
00636   b = (*bb);                       /* initialize bit buffer */
00637   k = (*bk);
00638   w = (*wp);                       /* initialize window position */
00639 
00640 
00641   /* inflate the coded data */
00642   ml = mask[bl];           /* precompute masks for speed */
00643   md = mask[bd];
00644   while (1)                     /* do until end of block */
00645   {
00646     NEEDBITS((unsigned)bl,b,k,(*ibufptr),(*ibufcnt))
00647     if ((e = (t = tl + ((unsigned)b & ml))->e) > 16)
00648       do {
00649         if (e == 99)
00650           return 1;
00651         DUMPBITS(t->b,b,k)
00652         e -= 16;
00653         NEEDBITS(e,b,k,(*ibufptr),(*ibufcnt))
00654       } while ((e = (t = t->v.t + ((unsigned)b & mask[e]))->e) > 16);
00655     DUMPBITS(t->b,b,k)
00656     if (e == 16)                /* then it's a literal */
00657     {
00658       R__slide[w++] = (uch)t->v.n;
00659       if (w == WSIZE)
00660       {
00661         FLUSH(w,obufptr,obufcnt,R__slide);
00662         w = 0;
00663       }
00664     }
00665     else                        /* it's an EOB or a length */
00666     {
00667       /* exit if end of block */
00668       if (e == 15)
00669         break;
00670 
00671       /* get length of block to copy */
00672       NEEDBITS(e,b,k,(*ibufptr),(*ibufcnt))
00673       n = t->v.n + ((unsigned)b & mask[e]);
00674       DUMPBITS(e,b,k);
00675 
00676       /* decode distance of block to copy */
00677       NEEDBITS((unsigned)bd,b,k,(*ibufptr),(*ibufcnt))
00678       if ((e = (t = td + ((unsigned)b & md))->e) > 16)
00679         do {
00680           if (e == 99)
00681             return 1;
00682           DUMPBITS(t->b,b,k)
00683           e -= 16;
00684           NEEDBITS(e,b,k,(*ibufptr),(*ibufcnt))
00685         } while ((e = (t = t->v.t + ((unsigned)b & mask[e]))->e) > 16);
00686       DUMPBITS(t->b,b,k)
00687       NEEDBITS(e,b,k,(*ibufptr),(*ibufcnt))
00688       d = w - t->v.n - ((unsigned)b & mask[e]);
00689       DUMPBITS(e,b,k)
00690 
00691       /* do the copy */
00692       do {
00693         n -= (e = (e = WSIZE - ((d &= WSIZE-1) > w ? d : w)) > n ? n : e);
00694 #ifndef NOMEMCPY
00695         if (w - d >= e)         /* (this test assumes unsigned comparison) */
00696         {
00697           memcpy(R__slide + w, R__slide + d, e);
00698           w += e;
00699           d += e;
00700         }
00701         else                      /* do it slow to avoid memcpy() overlap */
00702 #endif /* !NOMEMCPY */
00703           do {
00704             R__slide[w++] = R__slide[d++];
00705           } while (--e);
00706         if (w == WSIZE)
00707         {
00708           FLUSH(w,obufptr,obufcnt,R__slide);
00709           w = 0;
00710         }
00711       } while (n);
00712     }
00713   }
00714 
00715 
00716   /* restore the globals from the locals */
00717   (*wp) = w;                       /* restore global window pointer */
00718   (*bb) = b;                       /* restore global bit buffer */
00719   (*bk) = k;
00720 
00721 
00722   /* done */
00723   return 0;
00724 }
00725 
00726 #endif /* ASM_INFLATECODES */
00727 
00728 
00729 
00730 int R__Inflate_stored(uch** ibufptr, long*  ibufcnt, uch** obufptr, long*  obufcnt, ulg* bb, unsigned* bk, uch* R__slide, unsigned* wp)
00731 /* "decompress" an inflated type 0 (stored) block. */
00732 {
00733   unsigned n;           /* number of bytes in block */
00734   unsigned w;           /* current window position */
00735   register ulg b;       /* bit buffer */
00736   register unsigned k;  /* number of bits in bit buffer */
00737 
00738 
00739   /* make local copies of globals */
00740   Trace((stderr, "\nstored block"));
00741   b = (*bb);                       /* initialize bit buffer */
00742   k = (*bk);
00743   w = (*wp);                       /* initialize window position */
00744 
00745 
00746   /* go to byte boundary */
00747   n = k & 7;
00748   DUMPBITS(n,b,k);
00749 
00750 
00751   /* get the length and its complement */
00752   NEEDBITS(16,b,k,(*ibufptr),(*ibufcnt))
00753   n = ((unsigned)b & 0xffff);
00754   DUMPBITS(16,b,k)
00755   NEEDBITS(16,b,k,(*ibufptr),(*ibufcnt))
00756   if (n != (unsigned)((~b) & 0xffff))
00757     return 1;                   /* error in compressed data */
00758   DUMPBITS(16,b,k)
00759 
00760 
00761   /* read and output the compressed data */
00762   while (n--)
00763   {
00764     NEEDBITS(8,b,k,(*ibufptr),(*ibufcnt))
00765     R__slide[w++] = (uch)b;
00766     if (w == WSIZE)
00767     {
00768       FLUSH(w,obufptr,obufcnt,R__slide);
00769       w = 0;
00770     }
00771     DUMPBITS(8,b,k)
00772   }
00773 
00774 
00775   /* restore the globals from the locals */
00776   (*wp) = w;                       /* restore global window pointer */
00777   (*bb) = b;                       /* restore global bit buffer */
00778   (*bk) = k;
00779   return 0;
00780 }
00781 
00782 
00783 /* Globals for literal tables (built once) */
00784 struct huft *R__fixed_tl = (struct huft *)NULL;
00785 struct huft *R__fixed_td;
00786 int R__fixed_bl, R__fixed_bd;
00787 
00788 int R__Inflate_fixed(uch** ibufptr, long*  ibufcnt, uch** obufptr, long*  obufcnt, ulg* bb, unsigned* bk, uch* R__slide, unsigned* wp, unsigned* hufts)
00789 /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
00790    either replace this with a custom decoder, or at least precompute the
00791    Huffman tables. */
00792 {
00793   /* if first time, set up tables for fixed blocks */
00794   Trace((stderr, "\nliteral block"));
00795   if (R__fixed_tl == (struct huft *)NULL)
00796   {
00797     int i;                /* temporary variable */
00798     /*static*/ unsigned l[288]; /* length list for huft_build */
00799 
00800     /* literal table */
00801     for (i = 0; i < 144; i++)
00802       l[i] = 8;
00803     for (; i < 256; i++)
00804       l[i] = 9;
00805     for (; i < 280; i++)
00806       l[i] = 7;
00807     for (; i < 288; i++)          /* make a complete, but wrong code set */
00808       l[i] = 8;
00809     R__fixed_bl = 7;
00810     if ((i = R__huft_build(l, 288, 257, cplens, cplext,
00811                         &R__fixed_tl, &R__fixed_bl, hufts)) != 0)
00812     {
00813       R__fixed_tl = (struct huft *)NULL;
00814       return i;
00815     }
00816 
00817     /* distance table */
00818     for (i = 0; i < 30; i++)      /* make an incomplete code set */
00819       l[i] = 5;
00820     R__fixed_bd = 5;
00821     if ((i = R__huft_build(l, 30, 0, cpdist, cpdext, &R__fixed_td, &R__fixed_bd, hufts)) > 1)
00822     {
00823       R__huft_free(R__fixed_tl);
00824       R__fixed_tl = (struct huft *)NULL;
00825       return i;
00826     }
00827   }
00828 
00829 
00830   /* decompress until an end-of-block code */
00831   return R__Inflate_codes(R__fixed_tl, R__fixed_td, R__fixed_bl, R__fixed_bd, ibufptr, ibufcnt, obufptr, obufcnt, bb, bk, R__slide, wp) != 0;
00832 }
00833 
00834 
00835 
00836 int R__Inflate_dynamic(uch** ibufptr, long*  ibufcnt, uch** obufptr, long*  obufcnt, ulg* bb, unsigned* bk, uch* R__slide, unsigned* wp, unsigned* hufts)
00837 /* decompress an inflated type 2 (dynamic Huffman codes) block. */
00838 {
00839   int i;                /* temporary variables */
00840   unsigned j;
00841   unsigned l;           /* last length */
00842   unsigned m;           /* mask for bit lengths table */
00843   unsigned n;           /* number of lengths to get */
00844   struct huft *tl;      /* literal/length code table */
00845   struct huft *td;      /* distance code table */
00846   int bl;               /* lookup bits for tl */
00847   int bd;               /* lookup bits for td */
00848   unsigned nb;          /* number of bit length codes */
00849   unsigned nl;          /* number of literal/length codes */
00850   unsigned nd;          /* number of distance codes */
00851 #ifdef PKZIP_BUG_WORKAROUND
00852   /*static*/ unsigned ll[288+32]; /* literal/length and distance code lengths */
00853 #else
00854   /*static*/ unsigned ll[286+30]; /* literal/length and distance code lengths */
00855 #endif
00856   register ulg b;       /* bit buffer */
00857   register unsigned k;  /* number of bits in bit buffer */
00858 
00859 
00860   /* make local bit buffer */
00861   Trace((stderr, "\ndynamic block"));
00862   b = (*bb);
00863   k = (*bk);
00864 
00865 
00866   /* read in table lengths */
00867   NEEDBITS(5,b,k,(*ibufptr),(*ibufcnt))
00868   nl = 257 + ((unsigned)b & 0x1f);      /* number of literal/length codes */
00869   DUMPBITS(5,b,k)
00870   NEEDBITS(5,b,k,(*ibufptr),(*ibufcnt))
00871   nd = 1 + ((unsigned)b & 0x1f);        /* number of distance codes */
00872   DUMPBITS(5,b,k)
00873   NEEDBITS(4,b,k,(*ibufptr),(*ibufcnt))
00874   nb = 4 + ((unsigned)b & 0xf);         /* number of bit length codes */
00875   DUMPBITS(4,b,k)
00876 #ifdef PKZIP_BUG_WORKAROUND
00877   if (nl > 288 || nd > 32)
00878 #else
00879   if (nl > 286 || nd > 30)
00880 #endif
00881     return 1;                   /* bad lengths */
00882 
00883 
00884   /* read in bit-length-code lengths */
00885   for (j = 0; j < nb; j++)
00886   {
00887     NEEDBITS(3,b,k,(*ibufptr),(*ibufcnt))
00888     ll[border[j]] = (unsigned)b & 7;
00889     DUMPBITS(3,b,k)
00890   }
00891   for (; j < 19; j++)
00892     ll[border[j]] = 0;
00893 
00894 
00895   /* build decoding table for trees--single level, 7 bit lookup */
00896   bl = 7;
00897   if ((i = R__huft_build(ll, 19, 19, NULL, NULL, &tl, &bl, hufts)) != 0)
00898   {
00899     if (i == 1)
00900       R__huft_free(tl);
00901     return i;                   /* incomplete code set */
00902   }
00903 
00904 
00905   /* read in literal and distance code lengths */
00906   n = nl + nd;
00907   m = mask[bl];
00908   i = l = 0;
00909   while ((unsigned)i < n)
00910   {
00911     NEEDBITS((unsigned)bl,b,k,(*ibufptr),(*ibufcnt))
00912     j = (td = tl + ((unsigned)b & m))->b;
00913     DUMPBITS(j,b,k)
00914     j = td->v.n;
00915     if (j < 16)                 /* length of code in bits (0..15) */
00916       ll[i++] = l = j;          /* save last length in l */
00917     else if (j == 16)           /* repeat last length 3 to 6 times */
00918     {
00919       NEEDBITS(2,b,k,(*ibufptr),(*ibufcnt))
00920       j = 3 + ((unsigned)b & 3);
00921       DUMPBITS(2,b,k)
00922       if ((unsigned)i + j > n)
00923         return 1;
00924       while (j--)
00925         ll[i++] = l;
00926     }
00927     else if (j == 17)           /* 3 to 10 zero length codes */
00928     {
00929       NEEDBITS(3,b,k,(*ibufptr),(*ibufcnt))
00930       j = 3 + ((unsigned)b & 7);
00931       DUMPBITS(3,b,k)
00932       if ((unsigned)i + j > n)
00933         return 1;
00934       while (j--)
00935         ll[i++] = 0;
00936       l = 0;
00937     }
00938     else                        /* j == 18: 11 to 138 zero length codes */
00939     {
00940       NEEDBITS(7,b,k,(*ibufptr),(*ibufcnt))
00941       j = 11 + ((unsigned)b & 0x7f);
00942       DUMPBITS(7,b,k)
00943       if ((unsigned)i + j > n)
00944         return 1;
00945       while (j--)
00946         ll[i++] = 0;
00947       l = 0;
00948     }
00949   }
00950 
00951 
00952   /* free decoding table for trees */
00953   R__huft_free(tl);
00954 
00955 
00956   /* restore the global bit buffer */
00957   (*bb) = b;
00958   (*bk) = k;
00959 
00960 
00961   /* build the decoding tables for literal/length and distance codes */
00962   bl = lbits;
00963   if ((i = R__huft_build(ll, nl, 257, cplens, cplext, &tl, &bl, hufts)) != 0)
00964   {
00965     if (i == 1 && !qflag) {
00966       FPRINTF(stderr, "(incomplete l-tree)  ");
00967       R__huft_free(tl);
00968     }
00969     return i;                   /* incomplete code set */
00970   }
00971   bd = dbits;
00972   if ((i = R__huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd, hufts)) != 0)
00973   {
00974     if (i == 1 && !qflag) {
00975       FPRINTF(stderr, "(incomplete d-tree)  ");
00976 #ifdef PKZIP_BUG_WORKAROUND
00977       i = 0;
00978     }
00979 #else
00980       R__huft_free(td);
00981     }
00982     R__huft_free(tl);
00983     return i;                   /* incomplete code set */
00984 #endif
00985   }
00986 
00987 
00988   /* decompress until an end-of-block code */
00989   if (R__Inflate_codes(tl, td, bl, bd, ibufptr, ibufcnt, obufptr, obufcnt, bb, bk, R__slide, wp))
00990     return 1;
00991 
00992 
00993   /* free the decoding tables, return */
00994   R__huft_free(tl);
00995   R__huft_free(td);
00996   return 0;
00997 }
00998 
00999 
01000 
01001 int R__Inflate_block(int *e, uch** ibufptr, long*  ibufcnt, uch** obufptr, long*  obufcnt, ulg* bb, unsigned* bk, uch* R__slide, unsigned* wp, unsigned* hufts)
01002 /* int *e;                  last block flag */
01003 /* decompress an inflated block */
01004 {
01005   unsigned t;           /* block type */
01006   register ulg b;       /* bit buffer */
01007   register unsigned k;  /* number of bits in bit buffer */
01008 
01009 
01010   /* make local bit buffer */
01011   b = (*bb);
01012   k = (*bk);
01013 
01014 
01015   /* read in last block bit */
01016   NEEDBITS(1,b,k,(*ibufptr),(*ibufcnt))
01017   *e = (int)b & 1;
01018   DUMPBITS(1,b,k)
01019 
01020 
01021   /* read in block type */
01022   NEEDBITS(2,b,k,(*ibufptr),(*ibufcnt))
01023   t = (unsigned)b & 3;
01024   DUMPBITS(2,b,k)
01025 
01026 
01027   /* restore the global bit buffer */
01028   (*bb) = b;
01029   (*bk) = k;
01030 
01031 
01032   /* inflate that block type */
01033   if (t == 2)
01034     return R__Inflate_dynamic(ibufptr,ibufcnt,obufptr,obufcnt,bb,bk,R__slide,wp,hufts);
01035   if (t == 0)
01036     return R__Inflate_stored(ibufptr,ibufcnt,obufptr,obufcnt,bb,bk,R__slide,wp);
01037   if (t == 1)
01038     return R__Inflate_fixed(ibufptr,ibufcnt,obufptr,obufcnt,bb,bk,R__slide,wp,hufts);
01039 
01040 
01041   /* bad block type */
01042   return 2;
01043 }
01044 
01045 int R__Inflate(uch** ibufptr, long*  ibufcnt, uch** obufptr, long*  obufcnt)
01046 /* decompress an inflated entry */
01047 {
01048   int e;                /* last block flag */
01049   int r;                /* result code */
01050   unsigned h;           /* maximum struct huft's malloc'ed */
01051 
01052 
01053   /* initialize window, bit buffer */
01054   unsigned bk = 0;      /* bits in bit buffer */
01055   ulg bb = 0;           /* bit buffer */
01056 
01057 /*The inflate algorithm uses a sliding 32K byte window on the uncompressed
01058   stream to find repeated byte strings.  This is implemented here as a
01059   circular buffer.  The index is updated simply by incrementing and then
01060   and'ing with 0x7fff (32K-1). */
01061 /*It is left to other modules to supply the 32K area.  It is assumed
01062   to be usable as if it were declared "uch slide[32768];" or as just
01063   "uch *slide;" and then malloc'ed in the latter case.  The definition
01064   must be in unzip.h, included above. */
01065   uch R__slide [32768];
01066   unsigned wp = 0;            /* current position in slide */
01067 
01068   /* decompress until the last block */
01069   h = 0;
01070   do {
01071     unsigned hufts = 0;            /* track memory usage */
01072     if ((r = R__Inflate_block(&e, ibufptr, ibufcnt, obufptr, obufcnt, &bb, &bk, R__slide, &wp, &hufts)) != 0)
01073       return r;
01074     if (hufts > h)
01075       h = hufts;
01076   } while (!e);
01077 
01078 
01079   /* flush out slide */
01080   FLUSH(wp,obufptr,obufcnt,R__slide);
01081 
01082 
01083   /* return success */
01084   Trace((stderr, "\n%u bytes in Huffman tables (%d/entry)\n",
01085          h * sizeof(struct huft), sizeof(struct huft)));
01086   return 0;
01087 }
01088 
01089 int R__Inflate_free()
01090 {
01091   if (R__fixed_tl != (struct huft *)NULL)
01092   {
01093     R__huft_free(R__fixed_td);
01094     R__huft_free(R__fixed_tl);
01095     R__fixed_td = R__fixed_tl = (struct huft *)NULL;
01096   }
01097   return 0;
01098 }
01099 
01100 /***********************************************************************
01101  *                                                                     *
01102  * Name: R__unzip                                    Date:    20.01.95 *
01103  * Author: E.Chernyaev (IHEP/Protvino)               Revised:          *
01104  *                                                                     *
01105  * Function: In memory ZIP decompression. Can be issued from FORTRAN.  *
01106  *           Written for DELPHI collaboration (CERN)                   *
01107  *                                                                     *
01108  * Input: scrsize - size of input buffer                               *
01109  *        src     - input buffer                                       *
01110  *        tgtsize - size of target buffer                              *
01111  *                                                                     *
01112  * Output: tgt - target buffer (decompressed)                          *
01113  *         irep - size of decompressed data                            *
01114  *                0 - if error                                         *
01115  *                                                                     *
01116  ***********************************************************************/
01117 #define HDRSIZE 9
01118 
01119 int R__unzip_header(int *srcsize, uch *src, int *tgtsize)
01120 { 
01121   // Reads header envelope, and determines target size.
01122   // Returns 0 in case of success.
01123 
01124   *srcsize = 0;
01125   *tgtsize = 0;
01126 
01127   /*   C H E C K   H E A D E R   */
01128 
01129   if ((src[0] != 'C' && src[0] != 'Z') ||
01130       (src[1] != 'S' && src[1] != 'L') ||
01131       src[2] != Z_DEFLATED) {
01132     fprintf(stderr,"R__unzip: error in header\n");
01133     return 1;
01134   }
01135 
01136   *srcsize = HDRSIZE + ((long)src[3] | ((long)src[4] << 8) | ((long)src[5] << 16));
01137   *tgtsize = (long)src[6] | ((long)src[7] << 8) | ((long)src[8] << 16);
01138 
01139   return 0;
01140 }
01141 
01142 void R__unzip(int *srcsize, uch *src, int *tgtsize, uch *tgt, int *irep)
01143 {
01144   long isize;
01145   uch  *ibufptr,*obufptr;
01146   long  ibufcnt, obufcnt;
01147 
01148   *irep = 0L;
01149 
01150   /*   C H E C K   H E A D E R   */
01151 
01152   if (*srcsize < HDRSIZE) {
01153     fprintf(stderr,"R__unzip: too small source\n");
01154     return;
01155   }
01156 
01157   if ((src[0] != 'C' && src[0] != 'Z') ||
01158       (src[1] != 'S' && src[1] != 'L') ||
01159       src[2] != Z_DEFLATED) {
01160     fprintf(stderr,"R__unzip: error in header\n");
01161     return;
01162   }
01163 
01164   ibufptr = src + HDRSIZE;
01165   ibufcnt = (long)src[3] | ((long)src[4] << 8) | ((long)src[5] << 16);
01166   isize   = (long)src[6] | ((long)src[7] << 8) | ((long)src[8] << 16);
01167   obufptr = tgt;
01168   obufcnt = *tgtsize;
01169 
01170   if (obufcnt < isize) {
01171     fprintf(stderr,"R__unzip: too small target\n");
01172     return;
01173   }
01174 
01175   if (ibufcnt + HDRSIZE != *srcsize) {
01176     fprintf(stderr,"R__unzip: discrepancy in source length\n");
01177     return;
01178   }
01179 
01180   /*   D E C O M P R E S S   D A T A  */
01181 
01182   /* New zlib format */
01183   if (src[0] == 'Z' && src[1] == 'L') {
01184     z_stream stream; /* decompression stream */
01185     int err = 0;
01186 
01187     stream.next_in   = (Bytef*)(&src[HDRSIZE]);
01188     stream.avail_in  = (uInt)(*srcsize);
01189     stream.next_out  = (Bytef*)tgt;
01190     stream.avail_out = (uInt)(*tgtsize);
01191     stream.zalloc    = (alloc_func)0;
01192     stream.zfree     = (free_func)0;
01193     stream.opaque    = (voidpf)0;
01194 
01195     err = inflateInit(&stream);
01196     if (err != Z_OK) {
01197       fprintf(stderr,"R__unzip: error %d in inflateInit (zlib)\n",err);
01198       return;
01199     }
01200 
01201     err = inflate(&stream, Z_FINISH);
01202     if (err != Z_STREAM_END) {
01203       inflateEnd(&stream);
01204       fprintf(stderr,"R__unzip: error %d in inflate (zlib)\n",err);
01205       return;
01206     }
01207 
01208     inflateEnd(&stream);
01209 
01210     *irep = stream.total_out;
01211     return;
01212   }
01213 
01214   /* Old zlib format */
01215   if (R__Inflate(&ibufptr, &ibufcnt, &obufptr, &obufcnt)) {
01216     fprintf(stderr,"R__unzip: error during decompression\n");
01217     return;
01218   }
01219 
01220   /* if (obufptr - tgt != isize) {
01221     There are some rare cases when a few more bytes are required */
01222   if (obufptr - tgt > *tgtsize) {
01223     fprintf(stderr,"R__unzip: discrepancy (%ld) with initial size: %ld, tgtsize=%d\n",
01224             (long)(obufptr - tgt),isize,*tgtsize);
01225     *irep = obufptr - tgt;
01226     return;
01227   }
01228 
01229   *irep = isize;
01230 }
01231 
01232 #ifndef CHECK_EOF
01233 static int R__ReadByte (uch** ibufptr, long*  ibufcnt)
01234 {
01235   int k;
01236   if((*ibufcnt)-- <= 0)
01237     k = -1;
01238   else
01239     k = *(*ibufptr)++;
01240   return k;
01241 }
01242 #endif
01243 
01244 static void R__WriteData(int n, uch** obufptr, long*  obufcnt, uch* R__slide)
01245 {
01246   if( (*obufcnt) >= n ) memcpy((*obufptr), R__slide, n);
01247   (*obufptr) += n;
01248   (*obufcnt) -= n;
01249 }
01250 

Generated on Tue Jul 5 14:12:07 2011 for ROOT_528-00b_version by  doxygen 1.5.1