Home | History | Annotate | Line # | Download | only in zlib
      1 /*	$NetBSD: inflate.c,v 1.8 2024/09/22 19:12:27 christos Exp $	*/
      2 
      3 /* inflate.c -- zlib decompression
      4  * Copyright (C) 1995-2022 Mark Adler
      5  * For conditions of distribution and use, see copyright notice in zlib.h
      6  */
      7 
      8 /*
      9  * Change history:
     10  *
     11  * 1.2.beta0    24 Nov 2002
     12  * - First version -- complete rewrite of inflate to simplify code, avoid
     13  *   creation of window when not needed, minimize use of window when it is
     14  *   needed, make inffast.c even faster, implement gzip decoding, and to
     15  *   improve code readability and style over the previous zlib inflate code
     16  *
     17  * 1.2.beta1    25 Nov 2002
     18  * - Use pointers for available input and output checking in inffast.c
     19  * - Remove input and output counters in inffast.c
     20  * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
     21  * - Remove unnecessary second byte pull from length extra in inffast.c
     22  * - Unroll direct copy to three copies per loop in inffast.c
     23  *
     24  * 1.2.beta2    4 Dec 2002
     25  * - Change external routine names to reduce potential conflicts
     26  * - Correct filename to inffixed.h for fixed tables in inflate.c
     27  * - Make hbuf[] unsigned char to match parameter type in inflate.c
     28  * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
     29  *   to avoid negation problem on Alphas (64 bit) in inflate.c
     30  *
     31  * 1.2.beta3    22 Dec 2002
     32  * - Add comments on state->bits assertion in inffast.c
     33  * - Add comments on op field in inftrees.h
     34  * - Fix bug in reuse of allocated window after inflateReset()
     35  * - Remove bit fields--back to byte structure for speed
     36  * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
     37  * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
     38  * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
     39  * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
     40  * - Use local copies of stream next and avail values, as well as local bit
     41  *   buffer and bit count in inflate()--for speed when inflate_fast() not used
     42  *
     43  * 1.2.beta4    1 Jan 2003
     44  * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
     45  * - Move a comment on output buffer sizes from inffast.c to inflate.c
     46  * - Add comments in inffast.c to introduce the inflate_fast() routine
     47  * - Rearrange window copies in inflate_fast() for speed and simplification
     48  * - Unroll last copy for window match in inflate_fast()
     49  * - Use local copies of window variables in inflate_fast() for speed
     50  * - Pull out common wnext == 0 case for speed in inflate_fast()
     51  * - Make op and len in inflate_fast() unsigned for consistency
     52  * - Add FAR to lcode and dcode declarations in inflate_fast()
     53  * - Simplified bad distance check in inflate_fast()
     54  * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
     55  *   source file infback.c to provide a call-back interface to inflate for
     56  *   programs like gzip and unzip -- uses window as output buffer to avoid
     57  *   window copying
     58  *
     59  * 1.2.beta5    1 Jan 2003
     60  * - Improved inflateBack() interface to allow the caller to provide initial
     61  *   input in strm.
     62  * - Fixed stored blocks bug in inflateBack()
     63  *
     64  * 1.2.beta6    4 Jan 2003
     65  * - Added comments in inffast.c on effectiveness of POSTINC
     66  * - Typecasting all around to reduce compiler warnings
     67  * - Changed loops from while (1) or do {} while (1) to for (;;), again to
     68  *   make compilers happy
     69  * - Changed type of window in inflateBackInit() to unsigned char *
     70  *
     71  * 1.2.beta7    27 Jan 2003
     72  * - Changed many types to unsigned or unsigned short to avoid warnings
     73  * - Added inflateCopy() function
     74  *
     75  * 1.2.0        9 Mar 2003
     76  * - Changed inflateBack() interface to provide separate opaque descriptors
     77  *   for the in() and out() functions
     78  * - Changed inflateBack() argument and in_func typedef to swap the length
     79  *   and buffer address return values for the input function
     80  * - Check next_in and next_out for Z_NULL on entry to inflate()
     81  *
     82  * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
     83  */
     84 
     85 #include "zutil.h"
     86 #include "inftrees.h"
     87 #include "inflate.h"
     88 #include "inffast.h"
     89 
     90 #ifdef MAKEFIXED
     91 #  ifndef BUILDFIXED
     92 #    define BUILDFIXED
     93 #  endif
     94 #endif
     95 
     96 local int inflateStateCheck(z_streamp strm) {
     97     struct inflate_state FAR *state;
     98     if (strm == Z_NULL ||
     99         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
    100         return 1;
    101     state = (struct inflate_state FAR *)strm->state;
    102     if (state == Z_NULL || state->strm != strm ||
    103         state->mode < HEAD || state->mode > SYNC)
    104         return 1;
    105     return 0;
    106 }
    107 
    108 int ZEXPORT inflateResetKeep(z_streamp strm) {
    109     struct inflate_state FAR *state;
    110 
    111     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
    112     state = (struct inflate_state FAR *)strm->state;
    113     strm->total_in = strm->total_out = state->total = 0;
    114     strm->msg = Z_NULL;
    115     if (state->wrap)        /* to support ill-conceived Java test suite */
    116         strm->adler = state->wrap & 1;
    117     state->mode = HEAD;
    118     state->last = 0;
    119     state->havedict = 0;
    120     state->flags = -1;
    121     state->dmax = 32768U;
    122     state->head = Z_NULL;
    123     state->hold = 0;
    124     state->bits = 0;
    125     state->lencode = state->distcode = state->next = state->codes;
    126     state->sane = 1;
    127     state->back = -1;
    128     Tracev((stderr, "inflate: reset\n"));
    129     return Z_OK;
    130 }
    131 
    132 int ZEXPORT inflateReset(z_streamp strm) {
    133     struct inflate_state FAR *state;
    134 
    135     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
    136     state = (struct inflate_state FAR *)strm->state;
    137     state->wsize = 0;
    138     state->whave = 0;
    139     state->wnext = 0;
    140     return inflateResetKeep(strm);
    141 }
    142 
    143 int ZEXPORT inflateReset2(z_streamp strm, int windowBits) {
    144     int wrap;
    145     struct inflate_state FAR *state;
    146 
    147     /* get the state */
    148     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
    149     state = (struct inflate_state FAR *)strm->state;
    150 
    151     /* extract wrap request from windowBits parameter */
    152     if (windowBits < 0) {
    153         if (windowBits < -15)
    154             return Z_STREAM_ERROR;
    155         wrap = 0;
    156         windowBits = -windowBits;
    157     }
    158     else {
    159         wrap = (windowBits >> 4) + 5;
    160 #ifdef GUNZIP
    161         if (windowBits < 48)
    162             windowBits &= 15;
    163 #endif
    164     }
    165 
    166     /* set number of window bits, free window if different */
    167     if (windowBits && (windowBits < 8 || windowBits > 15))
    168         return Z_STREAM_ERROR;
    169     if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
    170         ZFREE(strm, state->window);
    171         state->window = Z_NULL;
    172     }
    173 
    174     /* update state and reset the rest of it */
    175     state->wrap = wrap;
    176     state->wbits = (unsigned)windowBits;
    177     return inflateReset(strm);
    178 }
    179 
    180 int ZEXPORT inflateInit2_(z_streamp strm, int windowBits,
    181                           const char *version, int stream_size) {
    182     int ret;
    183     struct inflate_state FAR *state;
    184 
    185     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
    186         stream_size != (int)(sizeof(z_stream)))
    187         return Z_VERSION_ERROR;
    188     if (strm == Z_NULL) return Z_STREAM_ERROR;
    189     strm->msg = Z_NULL;                 /* in case we return an error */
    190     if (strm->zalloc == (alloc_func)0) {
    191 #ifdef Z_SOLO
    192         return Z_STREAM_ERROR;
    193 #else
    194         strm->zalloc = zcalloc;
    195         strm->opaque = (voidpf)0;
    196 #endif
    197     }
    198     if (strm->zfree == (free_func)0)
    199 #ifdef Z_SOLO
    200         return Z_STREAM_ERROR;
    201 #else
    202         strm->zfree = zcfree;
    203 #endif
    204     state = (struct inflate_state FAR *)
    205             ZALLOC(strm, 1, sizeof(struct inflate_state));
    206     if (state == Z_NULL) return Z_MEM_ERROR;
    207     Tracev((stderr, "inflate: allocated\n"));
    208     strm->state = (struct internal_state FAR *)state;
    209     state->strm = strm;
    210     state->window = Z_NULL;
    211     state->mode = HEAD;     /* to pass state test in inflateReset2() */
    212     ret = inflateReset2(strm, windowBits);
    213     if (ret != Z_OK) {
    214         ZFREE(strm, state);
    215         strm->state = Z_NULL;
    216     }
    217     return ret;
    218 }
    219 
    220 int ZEXPORT inflateInit_(z_streamp strm, const char *version,
    221                          int stream_size) {
    222     return inflateInit2_(strm, DEF_WBITS, version, stream_size);
    223 }
    224 
    225 int ZEXPORT inflatePrime(z_streamp strm, int bits, int value) {
    226     struct inflate_state FAR *state;
    227 
    228     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
    229     if (bits == 0)
    230         return Z_OK;
    231     state = (struct inflate_state FAR *)strm->state;
    232     if (bits < 0) {
    233         state->hold = 0;
    234         state->bits = 0;
    235         return Z_OK;
    236     }
    237     if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;
    238     value &= (1L << bits) - 1;
    239     state->hold += (unsigned)value << state->bits;
    240     state->bits += (uInt)bits;
    241     return Z_OK;
    242 }
    243 
    244 /*
    245    Return state with length and distance decoding tables and index sizes set to
    246    fixed code decoding.  Normally this returns fixed tables from inffixed.h.
    247    If BUILDFIXED is defined, then instead this routine builds the tables the
    248    first time it's called, and returns those tables the first time and
    249    thereafter.  This reduces the size of the code by about 2K bytes, in
    250    exchange for a little execution time.  However, BUILDFIXED should not be
    251    used for threaded applications, since the rewriting of the tables and virgin
    252    may not be thread-safe.
    253  */
    254 local void fixedtables(struct inflate_state FAR *state) {
    255 #ifdef BUILDFIXED
    256     static int virgin = 1;
    257     static code *lenfix, *distfix;
    258     static code fixed[544];
    259 
    260     /* build fixed huffman tables if first call (may not be thread safe) */
    261     if (virgin) {
    262         unsigned sym, bits;
    263         static code *next;
    264 
    265         /* literal/length table */
    266         sym = 0;
    267         while (sym < 144) state->lens[sym++] = 8;
    268         while (sym < 256) state->lens[sym++] = 9;
    269         while (sym < 280) state->lens[sym++] = 7;
    270         while (sym < 288) state->lens[sym++] = 8;
    271         next = fixed;
    272         lenfix = next;
    273         bits = 9;
    274         inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
    275 
    276         /* distance table */
    277         sym = 0;
    278         while (sym < 32) state->lens[sym++] = 5;
    279         distfix = next;
    280         bits = 5;
    281         inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
    282 
    283         /* do this just once */
    284         virgin = 0;
    285     }
    286 #else /* !BUILDFIXED */
    287 #   include "inffixed.h"
    288 #endif /* BUILDFIXED */
    289     state->lencode = lenfix;
    290     state->lenbits = 9;
    291     state->distcode = distfix;
    292     state->distbits = 5;
    293 }
    294 
    295 #ifdef MAKEFIXED
    296 #include <stdio.h>
    297 
    298 /*
    299    Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
    300    defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
    301    those tables to stdout, which would be piped to inffixed.h.  A small program
    302    can simply call makefixed to do this:
    303 
    304     void makefixed(void);
    305 
    306     int main(void)
    307     {
    308         makefixed();
    309         return 0;
    310     }
    311 
    312    Then that can be linked with zlib built with MAKEFIXED defined and run:
    313 
    314     a.out > inffixed.h
    315  */
    316 void makefixed(void)
    317 {
    318     unsigned low, size;
    319     struct inflate_state state;
    320 
    321     fixedtables(&state);
    322     puts("    /* inffixed.h -- table for decoding fixed codes");
    323     puts("     * Generated automatically by makefixed().");
    324     puts("     */");
    325     puts("");
    326     puts("    /* WARNING: this file should *not* be used by applications.");
    327     puts("       It is part of the implementation of this library and is");
    328     puts("       subject to change. Applications should only use zlib.h.");
    329     puts("     */");
    330     puts("");
    331     size = 1U << 9;
    332     printf("    static const code lenfix[%u] = {", size);
    333     low = 0;
    334     for (;;) {
    335         if ((low % 7) == 0) printf("\n        ");
    336         printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
    337                state.lencode[low].bits, state.lencode[low].val);
    338         if (++low == size) break;
    339         putchar(',');
    340     }
    341     puts("\n    };");
    342     size = 1U << 5;
    343     printf("\n    static const code distfix[%u] = {", size);
    344     low = 0;
    345     for (;;) {
    346         if ((low % 6) == 0) printf("\n        ");
    347         printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
    348                state.distcode[low].val);
    349         if (++low == size) break;
    350         putchar(',');
    351     }
    352     puts("\n    };");
    353 }
    354 #endif /* MAKEFIXED */
    355 
    356 /*
    357    Update the window with the last wsize (normally 32K) bytes written before
    358    returning.  If window does not exist yet, create it.  This is only called
    359    when a window is already in use, or when output has been written during this
    360    inflate call, but the end of the deflate stream has not been reached yet.
    361    It is also called to create a window for dictionary data when a dictionary
    362    is loaded.
    363 
    364    Providing output buffers larger than 32K to inflate() should provide a speed
    365    advantage, since only the last 32K of output is copied to the sliding window
    366    upon return from inflate(), and since all distances after the first 32K of
    367    output will fall in the output data, making match copies simpler and faster.
    368    The advantage may be dependent on the size of the processor's data caches.
    369  */
    370 local int updatewindow(z_streamp strm, const Bytef *end, unsigned copy) {
    371     struct inflate_state FAR *state;
    372     unsigned dist;
    373 
    374     state = (struct inflate_state FAR *)strm->state;
    375 
    376     /* if it hasn't been done already, allocate space for the window */
    377     if (state->window == Z_NULL) {
    378         state->window = (unsigned char FAR *)
    379                         ZALLOC(strm, 1U << state->wbits,
    380                                sizeof(unsigned char));
    381         if (state->window == Z_NULL) return 1;
    382     }
    383 
    384     /* if window not in use yet, initialize */
    385     if (state->wsize == 0) {
    386         state->wsize = 1U << state->wbits;
    387         state->wnext = 0;
    388         state->whave = 0;
    389     }
    390 
    391     /* copy state->wsize or less output bytes into the circular window */
    392     if (copy >= state->wsize) {
    393         zmemcpy(state->window, end - state->wsize, state->wsize);
    394         state->wnext = 0;
    395         state->whave = state->wsize;
    396     }
    397     else {
    398         dist = state->wsize - state->wnext;
    399         if (dist > copy) dist = copy;
    400         zmemcpy(state->window + state->wnext, end - copy, dist);
    401         copy -= dist;
    402         if (copy) {
    403             zmemcpy(state->window, end - copy, copy);
    404             state->wnext = copy;
    405             state->whave = state->wsize;
    406         }
    407         else {
    408             state->wnext += dist;
    409             if (state->wnext == state->wsize) state->wnext = 0;
    410             if (state->whave < state->wsize) state->whave += dist;
    411         }
    412     }
    413     return 0;
    414 }
    415 
    416 /* Macros for inflate(): */
    417 
    418 /* check function to use adler32() for zlib or crc32() for gzip */
    419 #ifdef GUNZIP
    420 #  define UPDATE_CHECK(check, buf, len) \
    421     (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
    422 #else
    423 #  define UPDATE_CHECK(check, buf, len) adler32(check, buf, len)
    424 #endif
    425 
    426 /* check macros for header crc */
    427 #ifdef GUNZIP
    428 #  define CRC2(check, word) \
    429     do { \
    430         hbuf[0] = (unsigned char)(word); \
    431         hbuf[1] = (unsigned char)((word) >> 8); \
    432         check = crc32(check, hbuf, 2); \
    433     } while (0)
    434 
    435 #  define CRC4(check, word) \
    436     do { \
    437         hbuf[0] = (unsigned char)(word); \
    438         hbuf[1] = (unsigned char)((word) >> 8); \
    439         hbuf[2] = (unsigned char)((word) >> 16); \
    440         hbuf[3] = (unsigned char)((word) >> 24); \
    441         check = crc32(check, hbuf, 4); \
    442     } while (0)
    443 #endif
    444 
    445 /* Load registers with state in inflate() for speed */
    446 #define LOAD() \
    447     do { \
    448         put = strm->next_out; \
    449         left = strm->avail_out; \
    450         next = strm->next_in; \
    451         have = strm->avail_in; \
    452         hold = state->hold; \
    453         bits = state->bits; \
    454     } while (0)
    455 
    456 /* Restore state from registers in inflate() */
    457 #define RESTORE() \
    458     do { \
    459         strm->next_out = put; \
    460         strm->avail_out = left; \
    461         strm->next_in = next; \
    462         strm->avail_in = have; \
    463         state->hold = hold; \
    464         state->bits = bits; \
    465     } while (0)
    466 
    467 /* Clear the input bit accumulator */
    468 #define INITBITS() \
    469     do { \
    470         hold = 0; \
    471         bits = 0; \
    472     } while (0)
    473 
    474 /* Get a byte of input into the bit accumulator, or return from inflate()
    475    if there is no input available. */
    476 #define PULLBYTE() \
    477     do { \
    478         if (have == 0) goto inf_leave; \
    479         have--; \
    480         hold += (unsigned long)(*next++) << bits; \
    481         bits += 8; \
    482     } while (0)
    483 
    484 /* Assure that there are at least n bits in the bit accumulator.  If there is
    485    not enough available input to do that, then return from inflate(). */
    486 #define NEEDBITS(n) \
    487     do { \
    488         while (bits < (unsigned)(n)) \
    489             PULLBYTE(); \
    490     } while (0)
    491 
    492 /* Return the low n bits of the bit accumulator (n < 16) */
    493 #define BITS(n) \
    494     ((unsigned)hold & ((1U << (n)) - 1))
    495 
    496 /* Remove n bits from the bit accumulator */
    497 #define DROPBITS(n) \
    498     do { \
    499         hold >>= (n); \
    500         bits -= (unsigned)(n); \
    501     } while (0)
    502 
    503 /* Remove zero to seven bits as needed to go to a byte boundary */
    504 #define BYTEBITS() \
    505     do { \
    506         hold >>= bits & 7; \
    507         bits -= bits & 7; \
    508     } while (0)
    509 
    510 /*
    511    inflate() uses a state machine to process as much input data and generate as
    512    much output data as possible before returning.  The state machine is
    513    structured roughly as follows:
    514 
    515     for (;;) switch (state) {
    516     ...
    517     case STATEn:
    518         if (not enough input data or output space to make progress)
    519             return;
    520         ... make progress ...
    521         state = STATEm;
    522         break;
    523     ...
    524     }
    525 
    526    so when inflate() is called again, the same case is attempted again, and
    527    if the appropriate resources are provided, the machine proceeds to the
    528    next state.  The NEEDBITS() macro is usually the way the state evaluates
    529    whether it can proceed or should return.  NEEDBITS() does the return if
    530    the requested bits are not available.  The typical use of the BITS macros
    531    is:
    532 
    533         NEEDBITS(n);
    534         ... do something with BITS(n) ...
    535         DROPBITS(n);
    536 
    537    where NEEDBITS(n) either returns from inflate() if there isn't enough
    538    input left to load n bits into the accumulator, or it continues.  BITS(n)
    539    gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
    540    the low n bits off the accumulator.  INITBITS() clears the accumulator
    541    and sets the number of available bits to zero.  BYTEBITS() discards just
    542    enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
    543    and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
    544 
    545    NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
    546    if there is no input available.  The decoding of variable length codes uses
    547    PULLBYTE() directly in order to pull just enough bytes to decode the next
    548    code, and no more.
    549 
    550    Some states loop until they get enough input, making sure that enough
    551    state information is maintained to continue the loop where it left off
    552    if NEEDBITS() returns in the loop.  For example, want, need, and keep
    553    would all have to actually be part of the saved state in case NEEDBITS()
    554    returns:
    555 
    556     case STATEw:
    557         while (want < need) {
    558             NEEDBITS(n);
    559             keep[want++] = BITS(n);
    560             DROPBITS(n);
    561         }
    562         state = STATEx;
    563     case STATEx:
    564 
    565    As shown above, if the next state is also the next case, then the break
    566    is omitted.
    567 
    568    A state may also return if there is not enough output space available to
    569    complete that state.  Those states are copying stored data, writing a
    570    literal byte, and copying a matching string.
    571 
    572    When returning, a "goto inf_leave" is used to update the total counters,
    573    update the check value, and determine whether any progress has been made
    574    during that inflate() call in order to return the proper return code.
    575    Progress is defined as a change in either strm->avail_in or strm->avail_out.
    576    When there is a window, goto inf_leave will update the window with the last
    577    output written.  If a goto inf_leave occurs in the middle of decompression
    578    and there is no window currently, goto inf_leave will create one and copy
    579    output to the window for the next call of inflate().
    580 
    581    In this implementation, the flush parameter of inflate() only affects the
    582    return code (per zlib.h).  inflate() always writes as much as possible to
    583    strm->next_out, given the space available and the provided input--the effect
    584    documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
    585    the allocation of and copying into a sliding window until necessary, which
    586    provides the effect documented in zlib.h for Z_FINISH when the entire input
    587    stream available.  So the only thing the flush parameter actually does is:
    588    when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
    589    will return Z_BUF_ERROR if it has not reached the end of the stream.
    590  */
    591 
    592 int ZEXPORT inflate(z_streamp strm, int flush) {
    593     struct inflate_state FAR *state;
    594     z_const unsigned char FAR *next;    /* next input */
    595     unsigned char FAR *put;     /* next output */
    596     unsigned have, left;        /* available input and output */
    597     unsigned long hold;         /* bit buffer */
    598     unsigned bits;              /* bits in bit buffer */
    599     unsigned in, out;           /* save starting available input and output */
    600     unsigned copy;              /* number of stored or match bytes to copy */
    601     unsigned char FAR *from;    /* where to copy match bytes from */
    602     code here;                  /* current decoding table entry */
    603     code last;                  /* parent table entry */
    604     unsigned len;               /* length to copy for repeats, bits to drop */
    605     int ret;                    /* return code */
    606 #ifdef GUNZIP
    607     unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
    608 #endif
    609     static const unsigned short order[19] = /* permutation of code lengths */
    610         {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
    611 
    612 #if defined(__NetBSD__) && defined(_STANDALONE)
    613     /* Some kernels are loaded at address 0x0 so strm->next_out could be NULL */
    614     if (inflateStateCheck(strm) ||
    615         (strm->next_in == Z_NULL && strm->avail_in != 0))
    616         return Z_STREAM_ERROR;
    617 #else
    618     if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||
    619         (strm->next_in == Z_NULL && strm->avail_in != 0))
    620         return Z_STREAM_ERROR;
    621 #endif
    622 
    623     state = (struct inflate_state FAR *)strm->state;
    624     if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
    625     LOAD();
    626     in = have;
    627     out = left;
    628     ret = Z_OK;
    629     for (;;)
    630         switch (state->mode) {
    631         case HEAD:
    632             if (state->wrap == 0) {
    633                 state->mode = TYPEDO;
    634                 break;
    635             }
    636             NEEDBITS(16);
    637 #ifdef GUNZIP
    638             if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
    639                 if (state->wbits == 0)
    640                     state->wbits = 15;
    641                 state->check = crc32(0L, Z_NULL, 0);
    642                 CRC2(state->check, hold);
    643                 INITBITS();
    644                 state->mode = FLAGS;
    645                 break;
    646             }
    647             if (state->head != Z_NULL)
    648                 state->head->done = -1;
    649             if (!(state->wrap & 1) ||   /* check if zlib header allowed */
    650 #else
    651             if (
    652 #endif
    653                 ((BITS(8) << 8) + (hold >> 8)) % 31) {
    654                 strm->msg = __UNCONST("incorrect header check");
    655                 state->mode = BAD;
    656                 break;
    657             }
    658             if (BITS(4) != Z_DEFLATED) {
    659                 strm->msg = __UNCONST("unknown compression method");
    660                 state->mode = BAD;
    661                 break;
    662             }
    663             DROPBITS(4);
    664             len = BITS(4) + 8;
    665             if (state->wbits == 0)
    666                 state->wbits = len;
    667             if (len > 15 || len > state->wbits) {
    668                 strm->msg = __UNCONST("invalid window size");
    669                 state->mode = BAD;
    670                 break;
    671             }
    672             state->dmax = 1U << len;
    673             state->flags = 0;               /* indicate zlib header */
    674             Tracev((stderr, "inflate:   zlib header ok\n"));
    675             strm->adler = state->check = adler32(0L, Z_NULL, 0);
    676             state->mode = hold & 0x200 ? DICTID : TYPE;
    677             INITBITS();
    678             break;
    679 #ifdef GUNZIP
    680         case FLAGS:
    681             NEEDBITS(16);
    682             state->flags = (int)(hold);
    683             if ((state->flags & 0xff) != Z_DEFLATED) {
    684                 strm->msg = __UNCONST("unknown compression method");
    685                 state->mode = BAD;
    686                 break;
    687             }
    688             if (state->flags & 0xe000) {
    689                 strm->msg = __UNCONST("unknown header flags set");
    690                 state->mode = BAD;
    691                 break;
    692             }
    693             if (state->head != Z_NULL)
    694                 state->head->text = (int)((hold >> 8) & 1);
    695             if ((state->flags & 0x0200) && (state->wrap & 4))
    696                 CRC2(state->check, hold);
    697             INITBITS();
    698             state->mode = TIME;
    699                 /* fallthrough */
    700         case TIME:
    701             NEEDBITS(32);
    702             if (state->head != Z_NULL)
    703                 state->head->time = hold;
    704             if ((state->flags & 0x0200) && (state->wrap & 4))
    705                 CRC4(state->check, hold);
    706             INITBITS();
    707             state->mode = OS;
    708                 /* fallthrough */
    709         case OS:
    710             NEEDBITS(16);
    711             if (state->head != Z_NULL) {
    712                 state->head->xflags = (int)(hold & 0xff);
    713                 state->head->os = (int)(hold >> 8);
    714             }
    715             if ((state->flags & 0x0200) && (state->wrap & 4))
    716                 CRC2(state->check, hold);
    717             INITBITS();
    718             state->mode = EXLEN;
    719                 /* fallthrough */
    720         case EXLEN:
    721             if (state->flags & 0x0400) {
    722                 NEEDBITS(16);
    723                 state->length = (unsigned)(hold);
    724                 if (state->head != Z_NULL)
    725                     state->head->extra_len = (unsigned)hold;
    726                 if ((state->flags & 0x0200) && (state->wrap & 4))
    727                     CRC2(state->check, hold);
    728                 INITBITS();
    729             }
    730             else if (state->head != Z_NULL)
    731                 state->head->extra = Z_NULL;
    732             state->mode = EXTRA;
    733                 /* fallthrough */
    734         case EXTRA:
    735             if (state->flags & 0x0400) {
    736                 copy = state->length;
    737                 if (copy > have) copy = have;
    738                 if (copy) {
    739                     if (state->head != Z_NULL &&
    740                         state->head->extra != Z_NULL &&
    741                         (len = state->head->extra_len - state->length) <
    742                             state->head->extra_max) {
    743                         zmemcpy(state->head->extra + len, next,
    744                                 len + copy > state->head->extra_max ?
    745                                 state->head->extra_max - len : copy);
    746                     }
    747                     if ((state->flags & 0x0200) && (state->wrap & 4))
    748                         state->check = crc32(state->check, next, copy);
    749                     have -= copy;
    750                     next += copy;
    751                     state->length -= copy;
    752                 }
    753                 if (state->length) goto inf_leave;
    754             }
    755             state->length = 0;
    756             state->mode = NAME;
    757                 /* fallthrough */
    758         case NAME:
    759             if (state->flags & 0x0800) {
    760                 if (have == 0) goto inf_leave;
    761                 copy = 0;
    762                 do {
    763                     len = (unsigned)(next[copy++]);
    764                     if (state->head != Z_NULL &&
    765                             state->head->name != Z_NULL &&
    766                             state->length < state->head->name_max)
    767                         state->head->name[state->length++] = (Bytef)len;
    768                 } while (len && copy < have);
    769                 if ((state->flags & 0x0200) && (state->wrap & 4))
    770                     state->check = crc32(state->check, next, copy);
    771                 have -= copy;
    772                 next += copy;
    773                 if (len) goto inf_leave;
    774             }
    775             else if (state->head != Z_NULL)
    776                 state->head->name = Z_NULL;
    777             state->length = 0;
    778             state->mode = COMMENT;
    779                 /* fallthrough */
    780         case COMMENT:
    781             if (state->flags & 0x1000) {
    782                 if (have == 0) goto inf_leave;
    783                 copy = 0;
    784                 do {
    785                     len = (unsigned)(next[copy++]);
    786                     if (state->head != Z_NULL &&
    787                             state->head->comment != Z_NULL &&
    788                             state->length < state->head->comm_max)
    789                         state->head->comment[state->length++] = (Bytef)len;
    790                 } while (len && copy < have);
    791                 if ((state->flags & 0x0200) && (state->wrap & 4))
    792                     state->check = crc32(state->check, next, copy);
    793                 have -= copy;
    794                 next += copy;
    795                 if (len) goto inf_leave;
    796             }
    797             else if (state->head != Z_NULL)
    798                 state->head->comment = Z_NULL;
    799             state->mode = HCRC;
    800                 /* fallthrough */
    801         case HCRC:
    802             if (state->flags & 0x0200) {
    803                 NEEDBITS(16);
    804                 if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
    805                     strm->msg = __UNCONST("header crc mismatch");
    806                     state->mode = BAD;
    807                     break;
    808                 }
    809                 INITBITS();
    810             }
    811             if (state->head != Z_NULL) {
    812                 state->head->hcrc = (int)((state->flags >> 9) & 1);
    813                 state->head->done = 1;
    814             }
    815             strm->adler = state->check = crc32(0L, Z_NULL, 0);
    816             state->mode = TYPE;
    817             break;
    818 #endif
    819         case DICTID:
    820             NEEDBITS(32);
    821             strm->adler = state->check = ZSWAP32(hold);
    822             INITBITS();
    823             state->mode = DICT;
    824                 /* fallthrough */
    825         case DICT:
    826             if (state->havedict == 0) {
    827                 RESTORE();
    828                 return Z_NEED_DICT;
    829             }
    830             strm->adler = state->check = adler32(0L, Z_NULL, 0);
    831             state->mode = TYPE;
    832                 /* fallthrough */
    833         case TYPE:
    834             if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
    835                 /* fallthrough */
    836         case TYPEDO:
    837             if (state->last) {
    838                 BYTEBITS();
    839                 state->mode = CHECK;
    840                 break;
    841             }
    842             NEEDBITS(3);
    843             state->last = BITS(1);
    844             DROPBITS(1);
    845             switch (BITS(2)) {
    846             case 0:                             /* stored block */
    847                 Tracev((stderr, "inflate:     stored block%s\n",
    848                         state->last ? " (last)" : ""));
    849                 state->mode = STORED;
    850                 break;
    851             case 1:                             /* fixed block */
    852                 fixedtables(state);
    853                 Tracev((stderr, "inflate:     fixed codes block%s\n",
    854                         state->last ? " (last)" : ""));
    855                 state->mode = LEN_;             /* decode codes */
    856                 if (flush == Z_TREES) {
    857                     DROPBITS(2);
    858                     goto inf_leave;
    859                 }
    860                 break;
    861             case 2:                             /* dynamic block */
    862                 Tracev((stderr, "inflate:     dynamic codes block%s\n",
    863                         state->last ? " (last)" : ""));
    864                 state->mode = TABLE;
    865                 break;
    866             case 3:
    867                 strm->msg = __UNCONST("invalid block type");
    868                 state->mode = BAD;
    869             }
    870             DROPBITS(2);
    871             break;
    872         case STORED:
    873             BYTEBITS();                         /* go to byte boundary */
    874             NEEDBITS(32);
    875             if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
    876                 strm->msg = __UNCONST("invalid stored block lengths");
    877                 state->mode = BAD;
    878                 break;
    879             }
    880             state->length = (unsigned)hold & 0xffff;
    881             Tracev((stderr, "inflate:       stored length %u\n",
    882                     state->length));
    883             INITBITS();
    884             state->mode = COPY_;
    885             if (flush == Z_TREES) goto inf_leave;
    886                 /* fallthrough */
    887         case COPY_:
    888             state->mode = COPY;
    889                 /* fallthrough */
    890         case COPY:
    891             copy = state->length;
    892             if (copy) {
    893                 if (copy > have) copy = have;
    894                 if (copy > left) copy = left;
    895                 if (copy == 0) goto inf_leave;
    896                 zmemcpy(put, next, copy);
    897                 have -= copy;
    898                 next += copy;
    899                 left -= copy;
    900                 put += copy;
    901                 state->length -= copy;
    902                 break;
    903             }
    904             Tracev((stderr, "inflate:       stored end\n"));
    905             state->mode = TYPE;
    906             break;
    907         case TABLE:
    908             NEEDBITS(14);
    909             state->nlen = BITS(5) + 257;
    910             DROPBITS(5);
    911             state->ndist = BITS(5) + 1;
    912             DROPBITS(5);
    913             state->ncode = BITS(4) + 4;
    914             DROPBITS(4);
    915 #ifndef PKZIP_BUG_WORKAROUND
    916             if (state->nlen > 286 || state->ndist > 30) {
    917                 strm->msg = __UNCONST("too many length or distance symbols");
    918                 state->mode = BAD;
    919                 break;
    920             }
    921 #endif
    922             Tracev((stderr, "inflate:       table sizes ok\n"));
    923             state->have = 0;
    924             state->mode = LENLENS;
    925                 /* fallthrough */
    926         case LENLENS:
    927             while (state->have < state->ncode) {
    928                 NEEDBITS(3);
    929                 state->lens[order[state->have++]] = (unsigned short)BITS(3);
    930                 DROPBITS(3);
    931             }
    932             while (state->have < 19)
    933                 state->lens[order[state->have++]] = 0;
    934             state->next = state->codes;
    935             state->lencode = (const code FAR *)(state->next);
    936             state->lenbits = 7;
    937             ret = inflate_table(CODES, state->lens, 19, &(state->next),
    938                                 &(state->lenbits), state->work);
    939             if (ret) {
    940                 strm->msg = __UNCONST("invalid code lengths set");
    941                 state->mode = BAD;
    942                 break;
    943             }
    944             Tracev((stderr, "inflate:       code lengths ok\n"));
    945             state->have = 0;
    946             state->mode = CODELENS;
    947                 /* fallthrough */
    948         case CODELENS:
    949             while (state->have < state->nlen + state->ndist) {
    950                 for (;;) {
    951                     here = state->lencode[BITS(state->lenbits)];
    952                     if ((unsigned)(here.bits) <= bits) break;
    953                     PULLBYTE();
    954                 }
    955                 if (here.val < 16) {
    956                     DROPBITS(here.bits);
    957                     state->lens[state->have++] = here.val;
    958                 }
    959                 else {
    960                     if (here.val == 16) {
    961                         NEEDBITS(here.bits + 2);
    962                         DROPBITS(here.bits);
    963                         if (state->have == 0) {
    964                             strm->msg = __UNCONST("invalid bit length repeat");
    965                             state->mode = BAD;
    966                             break;
    967                         }
    968                         len = state->lens[state->have - 1];
    969                         copy = 3 + BITS(2);
    970                         DROPBITS(2);
    971                     }
    972                     else if (here.val == 17) {
    973                         NEEDBITS(here.bits + 3);
    974                         DROPBITS(here.bits);
    975                         len = 0;
    976                         copy = 3 + BITS(3);
    977                         DROPBITS(3);
    978                     }
    979                     else {
    980                         NEEDBITS(here.bits + 7);
    981                         DROPBITS(here.bits);
    982                         len = 0;
    983                         copy = 11 + BITS(7);
    984                         DROPBITS(7);
    985                     }
    986                     if (state->have + copy > state->nlen + state->ndist) {
    987                         strm->msg = __UNCONST("invalid bit length repeat");
    988                         state->mode = BAD;
    989                         break;
    990                     }
    991                     while (copy--)
    992                         state->lens[state->have++] = (unsigned short)len;
    993                 }
    994             }
    995 
    996             /* handle error breaks in while */
    997             if (state->mode == BAD) break;
    998 
    999             /* check for end-of-block code (better have one) */
   1000             if (state->lens[256] == 0) {
   1001                 strm->msg = __UNCONST("invalid code -- missing end-of-block");
   1002                 state->mode = BAD;
   1003                 break;
   1004             }
   1005 
   1006             /* build code tables -- note: do not change the lenbits or distbits
   1007                values here (9 and 6) without reading the comments in inftrees.h
   1008                concerning the ENOUGH constants, which depend on those values */
   1009             state->next = state->codes;
   1010             state->lencode = (const code FAR *)(state->next);
   1011             state->lenbits = 9;
   1012             ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
   1013                                 &(state->lenbits), state->work);
   1014             if (ret) {
   1015                 strm->msg = __UNCONST("invalid literal/lengths set");
   1016                 state->mode = BAD;
   1017                 break;
   1018             }
   1019             state->distcode = (const code FAR *)(state->next);
   1020             state->distbits = 6;
   1021             ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
   1022                             &(state->next), &(state->distbits), state->work);
   1023             if (ret) {
   1024                 strm->msg = __UNCONST("invalid distances set");
   1025                 state->mode = BAD;
   1026                 break;
   1027             }
   1028             Tracev((stderr, "inflate:       codes ok\n"));
   1029             state->mode = LEN_;
   1030             if (flush == Z_TREES) goto inf_leave;
   1031                 /* fallthrough */
   1032         case LEN_:
   1033             state->mode = LEN;
   1034                 /* fallthrough */
   1035         case LEN:
   1036             if (have >= 6 && left >= 258) {
   1037                 RESTORE();
   1038                 inflate_fast(strm, out);
   1039                 LOAD();
   1040                 if (state->mode == TYPE)
   1041                     state->back = -1;
   1042                 break;
   1043             }
   1044             state->back = 0;
   1045             for (;;) {
   1046                 here = state->lencode[BITS(state->lenbits)];
   1047                 if ((unsigned)(here.bits) <= bits) break;
   1048                 PULLBYTE();
   1049             }
   1050             if (here.op && (here.op & 0xf0) == 0) {
   1051                 last = here;
   1052                 for (;;) {
   1053                     here = state->lencode[last.val +
   1054                             (BITS(last.bits + last.op) >> last.bits)];
   1055                     if ((unsigned)(last.bits + here.bits) <= bits) break;
   1056                     PULLBYTE();
   1057                 }
   1058                 DROPBITS(last.bits);
   1059                 state->back += last.bits;
   1060             }
   1061             DROPBITS(here.bits);
   1062             state->back += here.bits;
   1063             state->length = (unsigned)here.val;
   1064             if ((int)(here.op) == 0) {
   1065                 Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
   1066                         "inflate:         literal '%c'\n" :
   1067                         "inflate:         literal 0x%02x\n", here.val));
   1068                 state->mode = LIT;
   1069                 break;
   1070             }
   1071             if (here.op & 32) {
   1072                 Tracevv((stderr, "inflate:         end of block\n"));
   1073                 state->back = -1;
   1074                 state->mode = TYPE;
   1075                 break;
   1076             }
   1077             if (here.op & 64) {
   1078                 strm->msg = __UNCONST("invalid literal/length code");
   1079                 state->mode = BAD;
   1080                 break;
   1081             }
   1082             state->extra = (unsigned)(here.op) & 15;
   1083             state->mode = LENEXT;
   1084                 /* fallthrough */
   1085         case LENEXT:
   1086             if (state->extra) {
   1087                 NEEDBITS(state->extra);
   1088                 state->length += BITS(state->extra);
   1089                 DROPBITS(state->extra);
   1090                 state->back += state->extra;
   1091             }
   1092             Tracevv((stderr, "inflate:         length %u\n", state->length));
   1093             state->was = state->length;
   1094             state->mode = DIST;
   1095                 /* fallthrough */
   1096         case DIST:
   1097             for (;;) {
   1098                 here = state->distcode[BITS(state->distbits)];
   1099                 if ((unsigned)(here.bits) <= bits) break;
   1100                 PULLBYTE();
   1101             }
   1102             if ((here.op & 0xf0) == 0) {
   1103                 last = here;
   1104                 for (;;) {
   1105                     here = state->distcode[last.val +
   1106                             (BITS(last.bits + last.op) >> last.bits)];
   1107                     if ((unsigned)(last.bits + here.bits) <= bits) break;
   1108                     PULLBYTE();
   1109                 }
   1110                 DROPBITS(last.bits);
   1111                 state->back += last.bits;
   1112             }
   1113             DROPBITS(here.bits);
   1114             state->back += here.bits;
   1115             if (here.op & 64) {
   1116                 strm->msg = __UNCONST("invalid distance code");
   1117                 state->mode = BAD;
   1118                 break;
   1119             }
   1120             state->offset = (unsigned)here.val;
   1121             state->extra = (unsigned)(here.op) & 15;
   1122             state->mode = DISTEXT;
   1123                 /* fallthrough */
   1124         case DISTEXT:
   1125             if (state->extra) {
   1126                 NEEDBITS(state->extra);
   1127                 state->offset += BITS(state->extra);
   1128                 DROPBITS(state->extra);
   1129                 state->back += state->extra;
   1130             }
   1131 #ifdef INFLATE_STRICT
   1132             if (state->offset > state->dmax) {
   1133                 strm->msg = __UNCONST("invalid distance too far back");
   1134                 state->mode = BAD;
   1135                 break;
   1136             }
   1137 #endif
   1138             Tracevv((stderr, "inflate:         distance %u\n", state->offset));
   1139             state->mode = MATCH;
   1140                 /* fallthrough */
   1141         case MATCH:
   1142             if (left == 0) goto inf_leave;
   1143             copy = out - left;
   1144             if (state->offset > copy) {         /* copy from window */
   1145                 copy = state->offset - copy;
   1146                 if (copy > state->whave) {
   1147                     if (state->sane) {
   1148                         strm->msg = __UNCONST("invalid distance too far back");
   1149                         state->mode = BAD;
   1150                         break;
   1151                     }
   1152 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
   1153                     Trace((stderr, "inflate.c too far\n"));
   1154                     copy -= state->whave;
   1155                     if (copy > state->length) copy = state->length;
   1156                     if (copy > left) copy = left;
   1157                     left -= copy;
   1158                     state->length -= copy;
   1159                     do {
   1160                         *put++ = 0;
   1161                     } while (--copy);
   1162                     if (state->length == 0) state->mode = LEN;
   1163                     break;
   1164 #endif
   1165                 }
   1166                 if (copy > state->wnext) {
   1167                     copy -= state->wnext;
   1168                     from = state->window + (state->wsize - copy);
   1169                 }
   1170                 else
   1171                     from = state->window + (state->wnext - copy);
   1172                 if (copy > state->length) copy = state->length;
   1173             }
   1174             else {                              /* copy from output */
   1175                 from = put - state->offset;
   1176                 copy = state->length;
   1177             }
   1178             if (copy > left) copy = left;
   1179             left -= copy;
   1180             state->length -= copy;
   1181             do {
   1182                 *put++ = *from++;
   1183             } while (--copy);
   1184             if (state->length == 0) state->mode = LEN;
   1185             break;
   1186         case LIT:
   1187             if (left == 0) goto inf_leave;
   1188             *put++ = (unsigned char)(state->length);
   1189             left--;
   1190             state->mode = LEN;
   1191             break;
   1192         case CHECK:
   1193             if (state->wrap) {
   1194                 NEEDBITS(32);
   1195                 out -= left;
   1196                 strm->total_out += out;
   1197                 state->total += out;
   1198                 if ((state->wrap & 4) && out)
   1199                     strm->adler = state->check =
   1200                         UPDATE_CHECK(state->check, put - out, out);
   1201                 out = left;
   1202                 if ((state->wrap & 4) && (
   1203 #ifdef GUNZIP
   1204                      state->flags ? hold :
   1205 #endif
   1206                      ZSWAP32(hold)) != state->check) {
   1207                     strm->msg = __UNCONST("incorrect data check");
   1208                     state->mode = BAD;
   1209                     break;
   1210                 }
   1211                 INITBITS();
   1212                 Tracev((stderr, "inflate:   check matches trailer\n"));
   1213             }
   1214 #ifdef GUNZIP
   1215             state->mode = LENGTH;
   1216                 /* fallthrough */
   1217         case LENGTH:
   1218             if (state->wrap && state->flags) {
   1219                 NEEDBITS(32);
   1220                 if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {
   1221                     strm->msg = __UNCONST("incorrect length check");
   1222                     state->mode = BAD;
   1223                     break;
   1224                 }
   1225                 INITBITS();
   1226                 Tracev((stderr, "inflate:   length matches trailer\n"));
   1227             }
   1228 #endif
   1229             state->mode = DONE;
   1230                 /* fallthrough */
   1231         case DONE:
   1232             ret = Z_STREAM_END;
   1233             goto inf_leave;
   1234         case BAD:
   1235             ret = Z_DATA_ERROR;
   1236             goto inf_leave;
   1237         case MEM:
   1238             return Z_MEM_ERROR;
   1239         case SYNC:
   1240                 /* fallthrough */
   1241         default:
   1242             return Z_STREAM_ERROR;
   1243         }
   1244 
   1245     /*
   1246        Return from inflate(), updating the total counts and the check value.
   1247        If there was no progress during the inflate() call, return a buffer
   1248        error.  Call updatewindow() to create and/or update the window state.
   1249        Note: a memory error from inflate() is non-recoverable.
   1250      */
   1251   inf_leave:
   1252     RESTORE();
   1253     if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
   1254             (state->mode < CHECK || flush != Z_FINISH)))
   1255         if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
   1256             state->mode = MEM;
   1257             return Z_MEM_ERROR;
   1258         }
   1259     in -= strm->avail_in;
   1260     out -= strm->avail_out;
   1261     strm->total_in += in;
   1262     strm->total_out += out;
   1263     state->total += out;
   1264     if ((state->wrap & 4) && out)
   1265         strm->adler = state->check =
   1266             UPDATE_CHECK(state->check, strm->next_out - out, out);
   1267     strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
   1268                       (state->mode == TYPE ? 128 : 0) +
   1269                       (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
   1270     if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
   1271         ret = Z_BUF_ERROR;
   1272     return ret;
   1273 }
   1274 
   1275 int ZEXPORT inflateEnd(z_streamp strm) {
   1276     struct inflate_state FAR *state;
   1277     if (inflateStateCheck(strm))
   1278         return Z_STREAM_ERROR;
   1279     state = (struct inflate_state FAR *)strm->state;
   1280     if (state->window != Z_NULL) ZFREE(strm, state->window);
   1281     ZFREE(strm, strm->state);
   1282     strm->state = Z_NULL;
   1283     Tracev((stderr, "inflate: end\n"));
   1284     return Z_OK;
   1285 }
   1286 
   1287 int ZEXPORT inflateGetDictionary(z_streamp strm, Bytef *dictionary,
   1288                                  uInt *dictLength) {
   1289     struct inflate_state FAR *state;
   1290 
   1291     /* check state */
   1292     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
   1293     state = (struct inflate_state FAR *)strm->state;
   1294 
   1295     /* copy dictionary */
   1296     if (state->whave && dictionary != Z_NULL) {
   1297         zmemcpy(dictionary, state->window + state->wnext,
   1298                 state->whave - state->wnext);
   1299         zmemcpy(dictionary + state->whave - state->wnext,
   1300                 state->window, state->wnext);
   1301     }
   1302     if (dictLength != Z_NULL)
   1303         *dictLength = state->whave;
   1304     return Z_OK;
   1305 }
   1306 
   1307 int ZEXPORT inflateSetDictionary(z_streamp strm, const Bytef *dictionary,
   1308                                  uInt dictLength) {
   1309     struct inflate_state FAR *state;
   1310     unsigned long dictid;
   1311     int ret;
   1312 
   1313     /* check state */
   1314     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
   1315     state = (struct inflate_state FAR *)strm->state;
   1316     if (state->wrap != 0 && state->mode != DICT)
   1317         return Z_STREAM_ERROR;
   1318 
   1319     /* check for correct dictionary identifier */
   1320     if (state->mode == DICT) {
   1321         dictid = adler32(0L, Z_NULL, 0);
   1322         dictid = adler32(dictid, dictionary, dictLength);
   1323         if (dictid != state->check)
   1324             return Z_DATA_ERROR;
   1325     }
   1326 
   1327     /* copy dictionary to window using updatewindow(), which will amend the
   1328        existing dictionary if appropriate */
   1329     ret = updatewindow(strm, dictionary + dictLength, dictLength);
   1330     if (ret) {
   1331         state->mode = MEM;
   1332         return Z_MEM_ERROR;
   1333     }
   1334     state->havedict = 1;
   1335     Tracev((stderr, "inflate:   dictionary set\n"));
   1336     return Z_OK;
   1337 }
   1338 
   1339 int ZEXPORT inflateGetHeader(z_streamp strm, gz_headerp head) {
   1340     struct inflate_state FAR *state;
   1341 
   1342     /* check state */
   1343     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
   1344     state = (struct inflate_state FAR *)strm->state;
   1345     if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
   1346 
   1347     /* save header structure */
   1348     state->head = head;
   1349     head->done = 0;
   1350     return Z_OK;
   1351 }
   1352 
   1353 /*
   1354    Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
   1355    or when out of input.  When called, *have is the number of pattern bytes
   1356    found in order so far, in 0..3.  On return *have is updated to the new
   1357    state.  If on return *have equals four, then the pattern was found and the
   1358    return value is how many bytes were read including the last byte of the
   1359    pattern.  If *have is less than four, then the pattern has not been found
   1360    yet and the return value is len.  In the latter case, syncsearch() can be
   1361    called again with more data and the *have state.  *have is initialized to
   1362    zero for the first call.
   1363  */
   1364 local unsigned syncsearch(unsigned FAR *have, const unsigned char FAR *buf,
   1365                           unsigned len) {
   1366     unsigned got;
   1367     unsigned next;
   1368 
   1369     got = *have;
   1370     next = 0;
   1371     while (next < len && got < 4) {
   1372         if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
   1373             got++;
   1374         else if (buf[next])
   1375             got = 0;
   1376         else
   1377             got = 4 - got;
   1378         next++;
   1379     }
   1380     *have = got;
   1381     return next;
   1382 }
   1383 
   1384 int ZEXPORT inflateSync(z_streamp strm) {
   1385     unsigned len;               /* number of bytes to look at or looked at */
   1386     int flags;                  /* temporary to save header status */
   1387     unsigned long in, out;      /* temporary to save total_in and total_out */
   1388     unsigned char buf[4];       /* to restore bit buffer to byte string */
   1389     struct inflate_state FAR *state;
   1390 
   1391     /* check parameters */
   1392     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
   1393     state = (struct inflate_state FAR *)strm->state;
   1394     if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
   1395 
   1396     /* if first time, start search in bit buffer */
   1397     if (state->mode != SYNC) {
   1398         state->mode = SYNC;
   1399         state->hold >>= state->bits & 7;
   1400         state->bits -= state->bits & 7;
   1401         len = 0;
   1402         while (state->bits >= 8) {
   1403             buf[len++] = (unsigned char)(state->hold);
   1404             state->hold >>= 8;
   1405             state->bits -= 8;
   1406         }
   1407         state->have = 0;
   1408         syncsearch(&(state->have), buf, len);
   1409     }
   1410 
   1411     /* search available input */
   1412     len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
   1413     strm->avail_in -= len;
   1414     strm->next_in += len;
   1415     strm->total_in += len;
   1416 
   1417     /* return no joy or set up to restart inflate() on a new block */
   1418     if (state->have != 4) return Z_DATA_ERROR;
   1419     if (state->flags == -1)
   1420         state->wrap = 0;    /* if no header yet, treat as raw */
   1421     else
   1422         state->wrap &= ~4;  /* no point in computing a check value now */
   1423     flags = state->flags;
   1424     in = strm->total_in;  out = strm->total_out;
   1425     inflateReset(strm);
   1426     strm->total_in = in;  strm->total_out = out;
   1427     state->flags = flags;
   1428     state->mode = TYPE;
   1429     return Z_OK;
   1430 }
   1431 
   1432 /*
   1433    Returns true if inflate is currently at the end of a block generated by
   1434    Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
   1435    implementation to provide an additional safety check. PPP uses
   1436    Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
   1437    block. When decompressing, PPP checks that at the end of input packet,
   1438    inflate is waiting for these length bytes.
   1439  */
   1440 int ZEXPORT inflateSyncPoint(z_streamp strm) {
   1441     struct inflate_state FAR *state;
   1442 
   1443     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
   1444     state = (struct inflate_state FAR *)strm->state;
   1445     return state->mode == STORED && state->bits == 0;
   1446 }
   1447 
   1448 int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) {
   1449     struct inflate_state FAR *state;
   1450     struct inflate_state FAR *copy;
   1451     unsigned char FAR *window;
   1452     unsigned wsize;
   1453 
   1454     /* check input */
   1455     if (inflateStateCheck(source) || dest == Z_NULL)
   1456         return Z_STREAM_ERROR;
   1457     state = (struct inflate_state FAR *)source->state;
   1458 
   1459     /* allocate space */
   1460     copy = (struct inflate_state FAR *)
   1461            ZALLOC(source, 1, sizeof(struct inflate_state));
   1462     if (copy == Z_NULL) return Z_MEM_ERROR;
   1463     window = Z_NULL;
   1464     if (state->window != Z_NULL) {
   1465         window = (unsigned char FAR *)
   1466                  ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
   1467         if (window == Z_NULL) {
   1468             ZFREE(source, copy);
   1469             return Z_MEM_ERROR;
   1470         }
   1471     }
   1472 
   1473     /* copy state */
   1474     zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
   1475     zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
   1476     copy->strm = dest;
   1477     if (state->lencode >= state->codes &&
   1478         state->lencode <= state->codes + ENOUGH - 1) {
   1479         copy->lencode = copy->codes + (state->lencode - state->codes);
   1480         copy->distcode = copy->codes + (state->distcode - state->codes);
   1481     }
   1482     copy->next = copy->codes + (state->next - state->codes);
   1483     if (window != Z_NULL) {
   1484         wsize = 1U << state->wbits;
   1485         zmemcpy(window, state->window, wsize);
   1486     }
   1487     copy->window = window;
   1488     dest->state = (struct internal_state FAR *)copy;
   1489     return Z_OK;
   1490 }
   1491 
   1492 int ZEXPORT inflateUndermine(z_streamp strm, int subvert) {
   1493     struct inflate_state FAR *state;
   1494 
   1495     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
   1496     state = (struct inflate_state FAR *)strm->state;
   1497 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
   1498     state->sane = !subvert;
   1499     return Z_OK;
   1500 #else
   1501     (void)subvert;
   1502     state->sane = 1;
   1503     return Z_DATA_ERROR;
   1504 #endif
   1505 }
   1506 
   1507 int ZEXPORT inflateValidate(z_streamp strm, int check) {
   1508     struct inflate_state FAR *state;
   1509 
   1510     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
   1511     state = (struct inflate_state FAR *)strm->state;
   1512     if (check && state->wrap)
   1513         state->wrap |= 4;
   1514     else
   1515         state->wrap &= ~4;
   1516     return Z_OK;
   1517 }
   1518 
   1519 long ZEXPORT inflateMark(z_streamp strm) {
   1520     struct inflate_state FAR *state;
   1521 
   1522     if (inflateStateCheck(strm))
   1523         return -(1L << 16);
   1524     state = (struct inflate_state FAR *)strm->state;
   1525     return (long)(((unsigned long)((long)state->back)) << 16) +
   1526         (state->mode == COPY ? state->length :
   1527             (state->mode == MATCH ? state->was - state->length : 0));
   1528 }
   1529 
   1530 unsigned long ZEXPORT inflateCodesUsed(z_streamp strm) {
   1531     struct inflate_state FAR *state;
   1532     if (inflateStateCheck(strm)) return (unsigned long)-1;
   1533     state = (struct inflate_state FAR *)strm->state;
   1534     return (unsigned long)(state->next - state->codes);
   1535 }
   1536