busybox/archival/libarchive/decompress_gunzip.c
<<
>>
Prefs
   1/* vi: set sw=4 ts=4: */
   2/*
   3 * gunzip implementation for busybox
   4 *
   5 * Based on GNU gzip v1.2.4 Copyright (C) 1992-1993 Jean-loup Gailly.
   6 *
   7 * Originally adjusted for busybox by Sven Rudolph <sr1@inf.tu-dresden.de>
   8 * based on gzip sources
   9 *
  10 * Adjusted further by Erik Andersen <andersen@codepoet.org> to support
  11 * files as well as stdin/stdout, and to generally behave itself wrt
  12 * command line handling.
  13 *
  14 * General cleanup to better adhere to the style guide and make use of standard
  15 * busybox functions by Glenn McGrath
  16 *
  17 * read_gz interface + associated hacking by Laurence Anderson
  18 *
  19 * Fixed huft_build() so decoding end-of-block code does not grab more bits
  20 * than necessary (this is required by unzip applet), added inflate_cleanup()
  21 * to free leaked bytebuffer memory (used in unzip.c), and some minor style
  22 * guide cleanups by Ed Clark
  23 *
  24 * gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
  25 * Copyright (C) 1992-1993 Jean-loup Gailly
  26 * The unzip code was written and put in the public domain by Mark Adler.
  27 * Portions of the lzw code are derived from the public domain 'compress'
  28 * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
  29 * Ken Turkowski, Dave Mack and Peter Jannesen.
  30 *
  31 * See the file algorithm.doc for the compression algorithms and file formats.
  32 *
  33 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  34 */
  35#include "libbb.h"
  36#include "bb_archive.h"
  37
  38typedef struct huft_t {
  39        unsigned char e;        /* number of extra bits or operation */
  40        unsigned char b;        /* number of bits in this code or subcode */
  41        union {
  42                unsigned short n;       /* literal, length base, or distance base */
  43                struct huft_t *t;       /* pointer to next level of table */
  44        } v;
  45} huft_t;
  46
  47enum {
  48        /* gunzip_window size--must be a power of two, and
  49         * at least 32K for zip's deflate method */
  50        GUNZIP_WSIZE = 0x8000,
  51        /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
  52        BMAX = 16,      /* maximum bit length of any code (16 for explode) */
  53        N_MAX = 288,    /* maximum number of codes in any set */
  54};
  55
  56
  57/* This is somewhat complex-looking arrangement, but it allows
  58 * to place decompressor state either in bss or in
  59 * malloc'ed space simply by changing #defines below.
  60 * Sizes on i386:
  61 * text    data     bss     dec     hex
  62 * 5256       0     108    5364    14f4 - bss
  63 * 4915       0       0    4915    1333 - malloc
  64 */
  65#define STATE_IN_BSS 0
  66#define STATE_IN_MALLOC 1
  67
  68
  69typedef struct state_t {
  70        off_t gunzip_bytes_out; /* number of output bytes */
  71        uint32_t gunzip_crc;
  72
  73        int gunzip_src_fd;
  74        unsigned gunzip_outbuf_count; /* bytes in output buffer */
  75
  76        unsigned char *gunzip_window;
  77
  78        uint32_t *gunzip_crc_table;
  79
  80        /* bitbuffer */
  81        unsigned gunzip_bb; /* bit buffer */
  82        unsigned char gunzip_bk; /* bits in bit buffer */
  83
  84        /* input (compressed) data */
  85        unsigned char *bytebuffer;      /* buffer itself */
  86        off_t to_read;                  /* compressed bytes to read (unzip only, -1 for gunzip) */
  87//      unsigned bytebuffer_max;        /* buffer size */
  88        unsigned bytebuffer_offset;     /* buffer position */
  89        unsigned bytebuffer_size;       /* how much data is there (size <= max) */
  90
  91        /* private data of inflate_codes() */
  92        unsigned inflate_codes_ml; /* masks for bl and bd bits */
  93        unsigned inflate_codes_md; /* masks for bl and bd bits */
  94        unsigned inflate_codes_bb; /* bit buffer */
  95        unsigned inflate_codes_k; /* number of bits in bit buffer */
  96        unsigned inflate_codes_w; /* current gunzip_window position */
  97        huft_t *inflate_codes_tl;
  98        huft_t *inflate_codes_td;
  99        unsigned inflate_codes_bl;
 100        unsigned inflate_codes_bd;
 101        unsigned inflate_codes_nn; /* length and index for copy */
 102        unsigned inflate_codes_dd;
 103
 104        smallint resume_copy;
 105
 106        /* private data of inflate_get_next_window() */
 107        smallint method; /* method == -1 for stored, -2 for codes */
 108        smallint need_another_block;
 109        smallint end_reached;
 110
 111        /* private data of inflate_stored() */
 112        unsigned inflate_stored_n;
 113        unsigned inflate_stored_b;
 114        unsigned inflate_stored_k;
 115        unsigned inflate_stored_w;
 116
 117        const char *error_msg;
 118        jmp_buf error_jmp;
 119} state_t;
 120#define gunzip_bytes_out    (S()gunzip_bytes_out   )
 121#define gunzip_crc          (S()gunzip_crc         )
 122#define gunzip_src_fd       (S()gunzip_src_fd      )
 123#define gunzip_outbuf_count (S()gunzip_outbuf_count)
 124#define gunzip_window       (S()gunzip_window      )
 125#define gunzip_crc_table    (S()gunzip_crc_table   )
 126#define gunzip_bb           (S()gunzip_bb          )
 127#define gunzip_bk           (S()gunzip_bk          )
 128#define to_read             (S()to_read            )
 129// #define bytebuffer_max   (S()bytebuffer_max     )
 130// Both gunzip and unzip can use constant buffer size now (16k):
 131#define bytebuffer_max      0x4000
 132#define bytebuffer          (S()bytebuffer         )
 133#define bytebuffer_offset   (S()bytebuffer_offset  )
 134#define bytebuffer_size     (S()bytebuffer_size    )
 135#define inflate_codes_ml    (S()inflate_codes_ml   )
 136#define inflate_codes_md    (S()inflate_codes_md   )
 137#define inflate_codes_bb    (S()inflate_codes_bb   )
 138#define inflate_codes_k     (S()inflate_codes_k    )
 139#define inflate_codes_w     (S()inflate_codes_w    )
 140#define inflate_codes_tl    (S()inflate_codes_tl   )
 141#define inflate_codes_td    (S()inflate_codes_td   )
 142#define inflate_codes_bl    (S()inflate_codes_bl   )
 143#define inflate_codes_bd    (S()inflate_codes_bd   )
 144#define inflate_codes_nn    (S()inflate_codes_nn   )
 145#define inflate_codes_dd    (S()inflate_codes_dd   )
 146#define resume_copy         (S()resume_copy        )
 147#define method              (S()method             )
 148#define need_another_block  (S()need_another_block )
 149#define end_reached         (S()end_reached        )
 150#define inflate_stored_n    (S()inflate_stored_n   )
 151#define inflate_stored_b    (S()inflate_stored_b   )
 152#define inflate_stored_k    (S()inflate_stored_k   )
 153#define inflate_stored_w    (S()inflate_stored_w   )
 154#define error_msg           (S()error_msg          )
 155#define error_jmp           (S()error_jmp          )
 156
 157/* This is a generic part */
 158#if STATE_IN_BSS /* Use global data segment */
 159#define DECLARE_STATE /*nothing*/
 160#define ALLOC_STATE /*nothing*/
 161#define DEALLOC_STATE ((void)0)
 162#define S() state.
 163#define PASS_STATE /*nothing*/
 164#define PASS_STATE_ONLY /*nothing*/
 165#define STATE_PARAM /*nothing*/
 166#define STATE_PARAM_ONLY void
 167static state_t state;
 168#endif
 169
 170#if STATE_IN_MALLOC /* Use malloc space */
 171#define DECLARE_STATE state_t *state
 172#define ALLOC_STATE (state = xzalloc(sizeof(*state)))
 173#define DEALLOC_STATE free(state)
 174#define S() state->
 175#define PASS_STATE state,
 176#define PASS_STATE_ONLY state
 177#define STATE_PARAM state_t *state,
 178#define STATE_PARAM_ONLY state_t *state
 179#endif
 180
 181
 182static const uint16_t mask_bits[] ALIGN2 = {
 183        0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
 184        0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
 185};
 186
 187/* Copy lengths for literal codes 257..285 */
 188static const uint16_t cplens[] ALIGN2 = {
 189        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
 190        67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
 191};
 192
 193/* note: see note #13 above about the 258 in this list. */
 194/* Extra bits for literal codes 257..285 */
 195static const uint8_t cplext[] ALIGN1 = {
 196        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5,
 197        5, 5, 5, 0, 99, 99
 198}; /* 99 == invalid */
 199
 200/* Copy offsets for distance codes 0..29 */
 201static const uint16_t cpdist[] ALIGN2 = {
 202        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
 203        769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577
 204};
 205
 206/* Extra bits for distance codes */
 207static const uint8_t cpdext[] ALIGN1 = {
 208        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10,
 209        11, 11, 12, 12, 13, 13
 210};
 211
 212/* Tables for deflate from PKZIP's appnote.txt. */
 213/* Order of the bit length code lengths */
 214static const uint8_t border[] ALIGN1 = {
 215        16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
 216};
 217
 218
 219/*
 220 * Free the malloc'ed tables built by huft_build(), which makes a linked
 221 * list of the tables it made, with the links in a dummy first entry of
 222 * each table.
 223 * t: table to free
 224 */
 225static void huft_free(huft_t *p)
 226{
 227        huft_t *q;
 228
 229        /* Go through linked list, freeing from the malloced (t[-1]) address. */
 230        while (p) {
 231                q = (--p)->v.t;
 232                free(p);
 233                p = q;
 234        }
 235}
 236
 237static void huft_free_all(STATE_PARAM_ONLY)
 238{
 239        huft_free(inflate_codes_tl);
 240        huft_free(inflate_codes_td);
 241        inflate_codes_tl = NULL;
 242        inflate_codes_td = NULL;
 243}
 244
 245static void abort_unzip(STATE_PARAM_ONLY) NORETURN;
 246static void abort_unzip(STATE_PARAM_ONLY)
 247{
 248        huft_free_all(PASS_STATE_ONLY);
 249        longjmp(error_jmp, 1);
 250}
 251
 252static unsigned fill_bitbuffer(STATE_PARAM unsigned bitbuffer, unsigned *current, const unsigned required)
 253{
 254        while (*current < required) {
 255                if (bytebuffer_offset >= bytebuffer_size) {
 256                        unsigned sz = bytebuffer_max - 4;
 257                        if (to_read >= 0 && to_read < sz) /* unzip only */
 258                                sz = to_read;
 259                        /* Leave the first 4 bytes empty so we can always unwind the bitbuffer
 260                         * to the front of the bytebuffer */
 261                        bytebuffer_size = safe_read(gunzip_src_fd, &bytebuffer[4], sz);
 262                        if ((int)bytebuffer_size < 1) {
 263                                error_msg = "unexpected end of file";
 264                                abort_unzip(PASS_STATE_ONLY);
 265                        }
 266                        if (to_read >= 0) /* unzip only */
 267                                to_read -= bytebuffer_size;
 268                        bytebuffer_size += 4;
 269                        bytebuffer_offset = 4;
 270                }
 271                bitbuffer |= ((unsigned) bytebuffer[bytebuffer_offset]) << *current;
 272                bytebuffer_offset++;
 273                *current += 8;
 274        }
 275        return bitbuffer;
 276}
 277
 278
 279/* Given a list of code lengths and a maximum table size, make a set of
 280 * tables to decode that set of codes.  Return zero on success, one if
 281 * the given code set is incomplete (the tables are still built in this
 282 * case), two if the input is invalid (an oversubscribed set of lengths)
 283 * - in this case stores NULL in *t.
 284 *
 285 * b:   code lengths in bits (all assumed <= BMAX)
 286 * n:   number of codes (assumed <= N_MAX)
 287 * s:   number of simple-valued codes (0..s-1)
 288 * d:   list of base values for non-simple codes
 289 * e:   list of extra bits for non-simple codes
 290 * t:   result: starting table
 291 * m:   maximum lookup bits, returns actual
 292 */
 293static int huft_build(const unsigned *b, const unsigned n,
 294                        const unsigned s, const unsigned short *d,
 295                        const unsigned char *e, huft_t **t, unsigned *m)
 296{
 297        unsigned a;             /* counter for codes of length k */
 298        unsigned c[BMAX + 1];   /* bit length count table */
 299        unsigned eob_len;       /* length of end-of-block code (value 256) */
 300        unsigned f;             /* i repeats in table every f entries */
 301        int g;                  /* maximum code length */
 302        int htl;                /* table level */
 303        unsigned i;             /* counter, current code */
 304        unsigned j;             /* counter */
 305        int k;                  /* number of bits in current code */
 306        const unsigned *p;      /* pointer into c[], b[], or v[] */
 307        huft_t *q;              /* points to current table */
 308        huft_t r;               /* table entry for structure assignment */
 309        huft_t *u[BMAX];        /* table stack */
 310        unsigned v[N_MAX + 1];  /* values in order of bit length. last v[] is never used */
 311        int ws[BMAX + 1];       /* bits decoded stack */
 312        int w;                  /* bits decoded */
 313        unsigned x[BMAX + 1];   /* bit offsets, then code stack */
 314        unsigned *xp;           /* pointer into x */
 315        int y;                  /* number of dummy codes added */
 316        unsigned z;             /* number of entries in current table */
 317
 318        /* Length of EOB code, if any */
 319        eob_len = n > 256 ? b[256] : BMAX;
 320
 321        *t = NULL;
 322
 323        /* Generate counts for each bit length */
 324        memset(c, 0, sizeof(c));
 325        p = b;
 326        i = n;
 327        do {
 328                c[*p]++; /* assume all entries <= BMAX */
 329                p++;     /* can't combine with above line (Solaris bug) */
 330        } while (--i);
 331        if (c[0] == n) {  /* null input - all zero length codes */
 332                q = xzalloc(3 * sizeof(*q));
 333                //q[0].v.t = NULL;
 334                q[1].e = 99;    /* invalid code marker */
 335                q[1].b = 1;
 336                q[2].e = 99;    /* invalid code marker */
 337                q[2].b = 1;
 338                *t = q + 1;
 339                *m = 1;
 340                return 0;
 341        }
 342
 343        /* Find minimum and maximum length, bound *m by those */
 344        for (j = 1; (j <= BMAX) && (c[j] == 0); j++)
 345                continue;
 346        k = j; /* minimum code length */
 347        for (i = BMAX; (c[i] == 0) && i; i--)
 348                continue;
 349        g = i; /* maximum code length */
 350        *m = (*m < j) ? j : ((*m > i) ? i : *m);
 351
 352        /* Adjust last length count to fill out codes, if needed */
 353        for (y = 1 << j; j < i; j++, y <<= 1) {
 354                y -= c[j];
 355                if (y < 0)
 356                        return 2; /* bad input: more codes than bits */
 357        }
 358        y -= c[i];
 359        if (y < 0)
 360                return 2;
 361        c[i] += y;
 362
 363        /* Generate starting offsets into the value table for each length */
 364        x[1] = j = 0;
 365        p = c + 1;
 366        xp = x + 2;
 367        while (--i) { /* note that i == g from above */
 368                j += *p++;
 369                *xp++ = j;
 370        }
 371
 372        /* Make a table of values in order of bit lengths.
 373         * To detect bad input, unused v[i]'s are set to invalid value UINT_MAX.
 374         * In particular, last v[i] is never filled and must not be accessed.
 375         */
 376        memset(v, 0xff, sizeof(v));
 377        p = b;
 378        i = 0;
 379        do {
 380                j = *p++;
 381                if (j != 0) {
 382                        v[x[j]++] = i;
 383                }
 384        } while (++i < n);
 385
 386        /* Generate the Huffman codes and for each, make the table entries */
 387        x[0] = i = 0;   /* first Huffman code is zero */
 388        p = v;          /* grab values in bit order */
 389        htl = -1;       /* no tables yet--level -1 */
 390        w = ws[0] = 0;  /* bits decoded */
 391        u[0] = NULL;    /* just to keep compilers happy */
 392        q = NULL;       /* ditto */
 393        z = 0;          /* ditto */
 394
 395        /* go through the bit lengths (k already is bits in shortest code) */
 396        for (; k <= g; k++) {
 397                a = c[k];
 398                while (a--) {
 399                        /* here i is the Huffman code of length k bits for value *p */
 400                        /* make tables up to required level */
 401                        while (k > ws[htl + 1]) {
 402                                w = ws[++htl];
 403
 404                                /* compute minimum size table less than or equal to *m bits */
 405                                z = g - w;
 406                                z = z > *m ? *m : z; /* upper limit on table size */
 407                                j = k - w;
 408                                f = 1 << j;
 409                                if (f > a + 1) { /* try a k-w bit table */
 410                                        /* too few codes for k-w bit table */
 411                                        f -= a + 1; /* deduct codes from patterns left */
 412                                        xp = c + k;
 413                                        while (++j < z) { /* try smaller tables up to z bits */
 414                                                f <<= 1;
 415                                                if (f <= *++xp) {
 416                                                        break; /* enough codes to use up j bits */
 417                                                }
 418                                                f -= *xp; /* else deduct codes from patterns */
 419                                        }
 420                                }
 421                                j = (w + j > eob_len && w < eob_len) ? eob_len - w : j; /* make EOB code end at table */
 422                                z = 1 << j;     /* table entries for j-bit table */
 423                                ws[htl+1] = w + j;      /* set bits decoded in stack */
 424
 425                                /* allocate and link in new table */
 426                                q = xzalloc((z + 1) * sizeof(huft_t));
 427                                *t = q + 1;     /* link to list for huft_free() */
 428                                t = &(q->v.t);
 429                                u[htl] = ++q;   /* table starts after link */
 430
 431                                /* connect to last table, if there is one */
 432                                if (htl) {
 433                                        x[htl] = i; /* save pattern for backing up */
 434                                        r.b = (unsigned char) (w - ws[htl - 1]); /* bits to dump before this table */
 435                                        r.e = (unsigned char) (16 + j); /* bits in this table */
 436                                        r.v.t = q; /* pointer to this table */
 437                                        j = (i & ((1 << w) - 1)) >> ws[htl - 1];
 438                                        u[htl - 1][j] = r; /* connect to last table */
 439                                }
 440                        }
 441
 442                        /* set up table entry in r */
 443                        r.b = (unsigned char) (k - w);
 444                        if (/*p >= v + n || -- redundant, caught by the second check: */
 445                            *p == UINT_MAX /* do we access uninited v[i]? (see memset(v))*/
 446                        ) {
 447                                r.e = 99; /* out of values--invalid code */
 448                        } else if (*p < s) {
 449                                r.e = (unsigned char) (*p < 256 ? 16 : 15);     /* 256 is EOB code */
 450                                r.v.n = (unsigned short) (*p++); /* simple code is just the value */
 451                        } else {
 452                                r.e = (unsigned char) e[*p - s]; /* non-simple--look up in lists */
 453                                r.v.n = d[*p++ - s];
 454                        }
 455
 456                        /* fill code-like entries with r */
 457                        f = 1 << (k - w);
 458                        for (j = i >> w; j < z; j += f) {
 459                                q[j] = r;
 460                        }
 461
 462                        /* backwards increment the k-bit code i */
 463                        for (j = 1 << (k - 1); i & j; j >>= 1) {
 464                                i ^= j;
 465                        }
 466                        i ^= j;
 467
 468                        /* backup over finished tables */
 469                        while ((i & ((1 << w) - 1)) != x[htl]) {
 470                                w = ws[--htl];
 471                        }
 472                }
 473        }
 474
 475        /* return actual size of base table */
 476        *m = ws[1];
 477
 478        /* Return 1 if we were given an incomplete table */
 479        return y != 0 && g != 1;
 480}
 481
 482
 483/*
 484 * inflate (decompress) the codes in a deflated (compressed) block.
 485 * Return an error code or zero if it all goes ok.
 486 *
 487 * tl, td: literal/length and distance decoder tables
 488 * bl, bd: number of bits decoded by tl[] and td[]
 489 */
 490/* called once from inflate_block */
 491
 492/* map formerly local static variables to globals */
 493#define ml inflate_codes_ml
 494#define md inflate_codes_md
 495#define bb inflate_codes_bb
 496#define k  inflate_codes_k
 497#define w  inflate_codes_w
 498#define tl inflate_codes_tl
 499#define td inflate_codes_td
 500#define bl inflate_codes_bl
 501#define bd inflate_codes_bd
 502#define nn inflate_codes_nn
 503#define dd inflate_codes_dd
 504static void inflate_codes_setup(STATE_PARAM unsigned my_bl, unsigned my_bd)
 505{
 506        bl = my_bl;
 507        bd = my_bd;
 508        /* make local copies of globals */
 509        bb = gunzip_bb;                 /* initialize bit buffer */
 510        k = gunzip_bk;
 511        w = gunzip_outbuf_count;        /* initialize gunzip_window position */
 512        /* inflate the coded data */
 513        ml = mask_bits[bl];             /* precompute masks for speed */
 514        md = mask_bits[bd];
 515}
 516/* called once from inflate_get_next_window */
 517static NOINLINE int inflate_codes(STATE_PARAM_ONLY)
 518{
 519        unsigned e;     /* table entry flag/number of extra bits */
 520        huft_t *t;      /* pointer to table entry */
 521
 522        if (resume_copy)
 523                goto do_copy;
 524
 525        while (1) {                     /* do until end of block */
 526                bb = fill_bitbuffer(PASS_STATE bb, &k, bl);
 527                t = tl + ((unsigned) bb & ml);
 528                e = t->e;
 529                if (e > 16)
 530                        do {
 531                                if (e == 99) {
 532                                        abort_unzip(PASS_STATE_ONLY);
 533                                }
 534                                bb >>= t->b;
 535                                k -= t->b;
 536                                e -= 16;
 537                                bb = fill_bitbuffer(PASS_STATE bb, &k, e);
 538                                t = t->v.t + ((unsigned) bb & mask_bits[e]);
 539                                e = t->e;
 540                        } while (e > 16);
 541                bb >>= t->b;
 542                k -= t->b;
 543                if (e == 16) {  /* then it's a literal */
 544                        gunzip_window[w++] = (unsigned char) t->v.n;
 545                        if (w == GUNZIP_WSIZE) {
 546                                gunzip_outbuf_count = w;
 547                                //flush_gunzip_window();
 548                                w = 0;
 549                                return 1; // We have a block to read
 550                        }
 551                } else {                /* it's an EOB or a length */
 552                        /* exit if end of block */
 553                        if (e == 15) {
 554                                break;
 555                        }
 556
 557                        /* get length of block to copy */
 558                        bb = fill_bitbuffer(PASS_STATE bb, &k, e);
 559                        nn = t->v.n + ((unsigned) bb & mask_bits[e]);
 560                        bb >>= e;
 561                        k -= e;
 562
 563                        /* decode distance of block to copy */
 564                        bb = fill_bitbuffer(PASS_STATE bb, &k, bd);
 565                        t = td + ((unsigned) bb & md);
 566                        e = t->e;
 567                        if (e > 16)
 568                                do {
 569                                        if (e == 99) {
 570                                                abort_unzip(PASS_STATE_ONLY);
 571                                        }
 572                                        bb >>= t->b;
 573                                        k -= t->b;
 574                                        e -= 16;
 575                                        bb = fill_bitbuffer(PASS_STATE bb, &k, e);
 576                                        t = t->v.t + ((unsigned) bb & mask_bits[e]);
 577                                        e = t->e;
 578                                } while (e > 16);
 579                        bb >>= t->b;
 580                        k -= t->b;
 581                        bb = fill_bitbuffer(PASS_STATE bb, &k, e);
 582                        dd = w - t->v.n - ((unsigned) bb & mask_bits[e]);
 583                        bb >>= e;
 584                        k -= e;
 585
 586                        /* do the copy */
 587 do_copy:
 588                        do {
 589                                /* Was: nn -= (e = (e = GUNZIP_WSIZE - ((dd &= GUNZIP_WSIZE - 1) > w ? dd : w)) > nn ? nn : e); */
 590                                /* Who wrote THAT?? rewritten as: */
 591                                unsigned delta;
 592
 593                                dd &= GUNZIP_WSIZE - 1;
 594                                e = GUNZIP_WSIZE - (dd > w ? dd : w);
 595                                delta = w > dd ? w - dd : dd - w;
 596                                if (e > nn) e = nn;
 597                                nn -= e;
 598
 599                                /* copy to new buffer to prevent possible overwrite */
 600                                if (delta >= e) {
 601                                        memcpy(gunzip_window + w, gunzip_window + dd, e);
 602                                        w += e;
 603                                        dd += e;
 604                                } else {
 605                                        /* do it slow to avoid memcpy() overlap */
 606                                        /* !NOMEMCPY */
 607                                        do {
 608                                                gunzip_window[w++] = gunzip_window[dd++];
 609                                        } while (--e);
 610                                }
 611                                if (w == GUNZIP_WSIZE) {
 612                                        gunzip_outbuf_count = w;
 613                                        resume_copy = (nn != 0);
 614                                        //flush_gunzip_window();
 615                                        w = 0;
 616                                        return 1;
 617                                }
 618                        } while (nn);
 619                        resume_copy = 0;
 620                }
 621        }
 622
 623        /* restore the globals from the locals */
 624        gunzip_outbuf_count = w;        /* restore global gunzip_window pointer */
 625        gunzip_bb = bb;                 /* restore global bit buffer */
 626        gunzip_bk = k;
 627
 628        /* normally just after call to inflate_codes, but save code by putting it here */
 629        /* free the decoding tables (tl and td), return */
 630        huft_free_all(PASS_STATE_ONLY);
 631
 632        /* done */
 633        return 0;
 634}
 635#undef ml
 636#undef md
 637#undef bb
 638#undef k
 639#undef w
 640#undef tl
 641#undef td
 642#undef bl
 643#undef bd
 644#undef nn
 645#undef dd
 646
 647
 648/* called once from inflate_block */
 649static void inflate_stored_setup(STATE_PARAM int my_n, int my_b, int my_k)
 650{
 651        inflate_stored_n = my_n;
 652        inflate_stored_b = my_b;
 653        inflate_stored_k = my_k;
 654        /* initialize gunzip_window position */
 655        inflate_stored_w = gunzip_outbuf_count;
 656}
 657/* called once from inflate_get_next_window */
 658static int inflate_stored(STATE_PARAM_ONLY)
 659{
 660        /* read and output the compressed data */
 661        while (inflate_stored_n--) {
 662                inflate_stored_b = fill_bitbuffer(PASS_STATE inflate_stored_b, &inflate_stored_k, 8);
 663                gunzip_window[inflate_stored_w++] = (unsigned char) inflate_stored_b;
 664                if (inflate_stored_w == GUNZIP_WSIZE) {
 665                        gunzip_outbuf_count = inflate_stored_w;
 666                        //flush_gunzip_window();
 667                        inflate_stored_w = 0;
 668                        inflate_stored_b >>= 8;
 669                        inflate_stored_k -= 8;
 670                        return 1; /* We have a block */
 671                }
 672                inflate_stored_b >>= 8;
 673                inflate_stored_k -= 8;
 674        }
 675
 676        /* restore the globals from the locals */
 677        gunzip_outbuf_count = inflate_stored_w;         /* restore global gunzip_window pointer */
 678        gunzip_bb = inflate_stored_b;   /* restore global bit buffer */
 679        gunzip_bk = inflate_stored_k;
 680        return 0; /* Finished */
 681}
 682
 683
 684/*
 685 * decompress an inflated block
 686 * e: last block flag
 687 *
 688 * GLOBAL VARIABLES: bb, kk,
 689 */
 690/* Return values: -1 = inflate_stored, -2 = inflate_codes */
 691/* One callsite in inflate_get_next_window */
 692static int inflate_block(STATE_PARAM smallint *e)
 693{
 694        unsigned ll[286 + 30];  /* literal/length and distance code lengths */
 695        unsigned t;     /* block type */
 696        unsigned b;     /* bit buffer */
 697        unsigned k;     /* number of bits in bit buffer */
 698
 699        /* make local bit buffer */
 700
 701        b = gunzip_bb;
 702        k = gunzip_bk;
 703
 704        /* read in last block bit */
 705        b = fill_bitbuffer(PASS_STATE b, &k, 1);
 706        *e = b & 1;
 707        b >>= 1;
 708        k -= 1;
 709
 710        /* read in block type */
 711        b = fill_bitbuffer(PASS_STATE b, &k, 2);
 712        t = (unsigned) b & 3;
 713        b >>= 2;
 714        k -= 2;
 715
 716        /* restore the global bit buffer */
 717        gunzip_bb = b;
 718        gunzip_bk = k;
 719
 720        /* Do we see block type 1 often? Yes!
 721         * TODO: fix performance problem (see below) */
 722        //bb_error_msg("blktype %d", t);
 723
 724        /* inflate that block type */
 725        switch (t) {
 726        case 0: /* Inflate stored */
 727        {
 728                unsigned n;     /* number of bytes in block */
 729                unsigned b_stored;      /* bit buffer */
 730                unsigned k_stored;      /* number of bits in bit buffer */
 731
 732                /* make local copies of globals */
 733                b_stored = gunzip_bb;   /* initialize bit buffer */
 734                k_stored = gunzip_bk;
 735
 736                /* go to byte boundary */
 737                n = k_stored & 7;
 738                b_stored >>= n;
 739                k_stored -= n;
 740
 741                /* get the length and its complement */
 742                b_stored = fill_bitbuffer(PASS_STATE b_stored, &k_stored, 16);
 743                n = ((unsigned) b_stored & 0xffff);
 744                b_stored >>= 16;
 745                k_stored -= 16;
 746
 747                b_stored = fill_bitbuffer(PASS_STATE b_stored, &k_stored, 16);
 748                if (n != (unsigned) ((~b_stored) & 0xffff)) {
 749                        abort_unzip(PASS_STATE_ONLY);   /* error in compressed data */
 750                }
 751                b_stored >>= 16;
 752                k_stored -= 16;
 753
 754                inflate_stored_setup(PASS_STATE n, b_stored, k_stored);
 755
 756                return -1;
 757        }
 758        case 1:
 759        /* Inflate fixed
 760         * decompress an inflated type 1 (fixed Huffman codes) block. We should
 761         * either replace this with a custom decoder, or at least precompute the
 762         * Huffman tables. TODO */
 763        {
 764                int i;                  /* temporary variable */
 765                unsigned bl;            /* lookup bits for tl */
 766                unsigned bd;            /* lookup bits for td */
 767                /* gcc 4.2.1 is too dumb to reuse stackspace. Moved up... */
 768                //unsigned ll[288];     /* length list for huft_build */
 769
 770                /* set up literal table */
 771                for (i = 0; i < 144; i++)
 772                        ll[i] = 8;
 773                for (; i < 256; i++)
 774                        ll[i] = 9;
 775                for (; i < 280; i++)
 776                        ll[i] = 7;
 777                for (; i < 288; i++) /* make a complete, but wrong code set */
 778                        ll[i] = 8;
 779                bl = 7;
 780                huft_build(ll, 288, 257, cplens, cplext, &inflate_codes_tl, &bl);
 781                /* huft_build() never return nonzero - we use known data */
 782
 783                /* set up distance table */
 784                for (i = 0; i < 30; i++) /* make an incomplete code set */
 785                        ll[i] = 5;
 786                bd = 5;
 787                huft_build(ll, 30, 0, cpdist, cpdext, &inflate_codes_td, &bd);
 788
 789                /* set up data for inflate_codes() */
 790                inflate_codes_setup(PASS_STATE bl, bd);
 791
 792                /* huft_free code moved into inflate_codes */
 793
 794                return -2;
 795        }
 796        case 2: /* Inflate dynamic */
 797        {
 798                enum { dbits = 6 };     /* bits in base distance lookup table */
 799                enum { lbits = 9 };     /* bits in base literal/length lookup table */
 800
 801                huft_t *td;             /* distance code table */
 802                unsigned i;             /* temporary variables */
 803                unsigned j;
 804                unsigned l;             /* last length */
 805                unsigned m;             /* mask for bit lengths table */
 806                unsigned n;             /* number of lengths to get */
 807                unsigned bl;            /* lookup bits for tl */
 808                unsigned bd;            /* lookup bits for td */
 809                unsigned nb;            /* number of bit length codes */
 810                unsigned nl;            /* number of literal/length codes */
 811                unsigned nd;            /* number of distance codes */
 812
 813                //unsigned ll[286 + 30];/* literal/length and distance code lengths */
 814                unsigned b_dynamic;     /* bit buffer */
 815                unsigned k_dynamic;     /* number of bits in bit buffer */
 816
 817                /* make local bit buffer */
 818                b_dynamic = gunzip_bb;
 819                k_dynamic = gunzip_bk;
 820
 821                /* read in table lengths */
 822                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 5);
 823                nl = 257 + ((unsigned) b_dynamic & 0x1f);       /* number of literal/length codes */
 824
 825                b_dynamic >>= 5;
 826                k_dynamic -= 5;
 827                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 5);
 828                nd = 1 + ((unsigned) b_dynamic & 0x1f); /* number of distance codes */
 829
 830                b_dynamic >>= 5;
 831                k_dynamic -= 5;
 832                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 4);
 833                nb = 4 + ((unsigned) b_dynamic & 0xf);  /* number of bit length codes */
 834
 835                b_dynamic >>= 4;
 836                k_dynamic -= 4;
 837                if (nl > 286 || nd > 30) {
 838                        abort_unzip(PASS_STATE_ONLY);   /* bad lengths */
 839                }
 840
 841                /* read in bit-length-code lengths */
 842                for (j = 0; j < nb; j++) {
 843                        b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 3);
 844                        ll[border[j]] = (unsigned) b_dynamic & 7;
 845                        b_dynamic >>= 3;
 846                        k_dynamic -= 3;
 847                }
 848                for (; j < 19; j++)
 849                        ll[border[j]] = 0;
 850
 851                /* build decoding table for trees - single level, 7 bit lookup */
 852                bl = 7;
 853                i = huft_build(ll, 19, 19, NULL, NULL, &inflate_codes_tl, &bl);
 854                if (i != 0) {
 855                        abort_unzip(PASS_STATE_ONLY); //return i;       /* incomplete code set */
 856                }
 857
 858                /* read in literal and distance code lengths */
 859                n = nl + nd;
 860                m = mask_bits[bl];
 861                i = l = 0;
 862                while ((unsigned) i < n) {
 863                        b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, (unsigned)bl);
 864                        td = inflate_codes_tl + ((unsigned) b_dynamic & m);
 865                        j = td->b;
 866                        b_dynamic >>= j;
 867                        k_dynamic -= j;
 868                        j = td->v.n;
 869                        if (j < 16) {   /* length of code in bits (0..15) */
 870                                ll[i++] = l = j;        /* save last length in l */
 871                        } else if (j == 16) {   /* repeat last length 3 to 6 times */
 872                                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 2);
 873                                j = 3 + ((unsigned) b_dynamic & 3);
 874                                b_dynamic >>= 2;
 875                                k_dynamic -= 2;
 876                                if ((unsigned) i + j > n) {
 877                                        abort_unzip(PASS_STATE_ONLY); //return 1;
 878                                }
 879                                while (j--) {
 880                                        ll[i++] = l;
 881                                }
 882                        } else if (j == 17) {   /* 3 to 10 zero length codes */
 883                                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 3);
 884                                j = 3 + ((unsigned) b_dynamic & 7);
 885                                b_dynamic >>= 3;
 886                                k_dynamic -= 3;
 887                                if ((unsigned) i + j > n) {
 888                                        abort_unzip(PASS_STATE_ONLY); //return 1;
 889                                }
 890                                while (j--) {
 891                                        ll[i++] = 0;
 892                                }
 893                                l = 0;
 894                        } else {        /* j == 18: 11 to 138 zero length codes */
 895                                b_dynamic = fill_bitbuffer(PASS_STATE b_dynamic, &k_dynamic, 7);
 896                                j = 11 + ((unsigned) b_dynamic & 0x7f);
 897                                b_dynamic >>= 7;
 898                                k_dynamic -= 7;
 899                                if ((unsigned) i + j > n) {
 900                                        abort_unzip(PASS_STATE_ONLY); //return 1;
 901                                }
 902                                while (j--) {
 903                                        ll[i++] = 0;
 904                                }
 905                                l = 0;
 906                        }
 907                }
 908
 909                /* free decoding table for trees */
 910                huft_free(inflate_codes_tl);
 911
 912                /* restore the global bit buffer */
 913                gunzip_bb = b_dynamic;
 914                gunzip_bk = k_dynamic;
 915
 916                /* build the decoding tables for literal/length and distance codes */
 917                bl = lbits;
 918
 919                i = huft_build(ll, nl, 257, cplens, cplext, &inflate_codes_tl, &bl);
 920                if (i != 0) {
 921                        abort_unzip(PASS_STATE_ONLY);
 922                }
 923                bd = dbits;
 924                i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &inflate_codes_td, &bd);
 925                if (i != 0) {
 926                        abort_unzip(PASS_STATE_ONLY);
 927                }
 928
 929                /* set up data for inflate_codes() */
 930                inflate_codes_setup(PASS_STATE bl, bd);
 931
 932                /* huft_free code moved into inflate_codes */
 933
 934                return -2;
 935        }
 936        default:
 937                abort_unzip(PASS_STATE_ONLY);
 938        }
 939}
 940
 941/* Two callsites, both in inflate_get_next_window */
 942static void calculate_gunzip_crc(STATE_PARAM_ONLY)
 943{
 944        gunzip_crc = crc32_block_endian0(gunzip_crc, gunzip_window, gunzip_outbuf_count, gunzip_crc_table);
 945        gunzip_bytes_out += gunzip_outbuf_count;
 946}
 947
 948/* One callsite in inflate_unzip_internal */
 949static int inflate_get_next_window(STATE_PARAM_ONLY)
 950{
 951        gunzip_outbuf_count = 0;
 952
 953        while (1) {
 954                int ret;
 955
 956                if (need_another_block) {
 957                        if (end_reached) {
 958                                calculate_gunzip_crc(PASS_STATE_ONLY);
 959                                end_reached = 0;
 960                                /* NB: need_another_block is still set */
 961                                return 0; /* Last block */
 962                        }
 963                        method = inflate_block(PASS_STATE &end_reached);
 964                        need_another_block = 0;
 965                }
 966
 967                switch (method) {
 968                case -1:
 969                        ret = inflate_stored(PASS_STATE_ONLY);
 970                        break;
 971                case -2:
 972                        ret = inflate_codes(PASS_STATE_ONLY);
 973                        break;
 974                default: /* cannot happen */
 975                        abort_unzip(PASS_STATE_ONLY);
 976                }
 977
 978                if (ret == 1) {
 979                        calculate_gunzip_crc(PASS_STATE_ONLY);
 980                        return 1; /* more data left */
 981                }
 982                need_another_block = 1; /* end of that block */
 983        }
 984        /* Doesnt get here */
 985}
 986
 987
 988/* Called from unpack_gz_stream() and inflate_unzip() */
 989static IF_DESKTOP(long long) int
 990inflate_unzip_internal(STATE_PARAM transformer_state_t *xstate)
 991{
 992        IF_DESKTOP(long long) int n = 0;
 993        ssize_t nwrote;
 994
 995        /* Allocate all global buffers (for DYN_ALLOC option) */
 996        gunzip_window = xmalloc(GUNZIP_WSIZE);
 997        gunzip_outbuf_count = 0;
 998        gunzip_bytes_out = 0;
 999        gunzip_src_fd = xstate->src_fd;
1000
1001        /* (re) initialize state */
1002        method = -1;
1003        need_another_block = 1;
1004        resume_copy = 0;
1005        gunzip_bk = 0;
1006        gunzip_bb = 0;
1007
1008        /* Create the crc table */
1009        gunzip_crc_table = crc32_new_table_le();
1010        gunzip_crc = ~0;
1011
1012        error_msg = "corrupted data";
1013        if (setjmp(error_jmp)) {
1014                /* Error from deep inside zip machinery */
1015                bb_error_msg(error_msg);
1016                n = -1;
1017                goto ret;
1018        }
1019
1020        while (1) {
1021                int r = inflate_get_next_window(PASS_STATE_ONLY);
1022                nwrote = transformer_write(xstate, gunzip_window, gunzip_outbuf_count);
1023                if (nwrote == (ssize_t)-1) {
1024                        n = -1;
1025                        goto ret;
1026                }
1027                IF_DESKTOP(n += nwrote;)
1028                if (r == 0) break;
1029        }
1030
1031        /* Store unused bytes in a global buffer so calling applets can access it */
1032        if (gunzip_bk >= 8) {
1033                /* Undo too much lookahead. The next read will be byte aligned
1034                 * so we can discard unused bits in the last meaningful byte. */
1035                bytebuffer_offset--;
1036                bytebuffer[bytebuffer_offset] = gunzip_bb & 0xff;
1037                gunzip_bb >>= 8;
1038                gunzip_bk -= 8;
1039        }
1040 ret:
1041        /* Cleanup */
1042        free(gunzip_window);
1043        free(gunzip_crc_table);
1044        return n;
1045}
1046
1047
1048/* External entry points */
1049
1050/* For unzip */
1051
1052IF_DESKTOP(long long) int FAST_FUNC
1053inflate_unzip(transformer_state_t *xstate)
1054{
1055        IF_DESKTOP(long long) int n;
1056        DECLARE_STATE;
1057
1058        ALLOC_STATE;
1059
1060        to_read = xstate->bytes_in;
1061//      bytebuffer_max = 0x8000;
1062        bytebuffer_offset = 4;
1063        bytebuffer = xmalloc(bytebuffer_max);
1064        n = inflate_unzip_internal(PASS_STATE xstate);
1065        free(bytebuffer);
1066
1067        xstate->crc32 = gunzip_crc;
1068        xstate->bytes_out = gunzip_bytes_out;
1069        DEALLOC_STATE;
1070        return n;
1071}
1072
1073
1074/* For gunzip */
1075
1076/* helpers first */
1077
1078/* Top up the input buffer with at least n bytes. */
1079static int top_up(STATE_PARAM unsigned n)
1080{
1081        int count = bytebuffer_size - bytebuffer_offset;
1082
1083        if (count < (int)n) {
1084                memmove(bytebuffer, &bytebuffer[bytebuffer_offset], count);
1085                bytebuffer_offset = 0;
1086                bytebuffer_size = full_read(gunzip_src_fd, &bytebuffer[count], bytebuffer_max - count);
1087                if ((int)bytebuffer_size < 0) {
1088                        bb_error_msg(bb_msg_read_error);
1089                        return 0;
1090                }
1091                bytebuffer_size += count;
1092                if (bytebuffer_size < n)
1093                        return 0;
1094        }
1095        return 1;
1096}
1097
1098static uint16_t buffer_read_le_u16(STATE_PARAM_ONLY)
1099{
1100        uint16_t res;
1101#if BB_LITTLE_ENDIAN
1102        move_from_unaligned16(res, &bytebuffer[bytebuffer_offset]);
1103#else
1104        res = bytebuffer[bytebuffer_offset];
1105        res |= bytebuffer[bytebuffer_offset + 1] << 8;
1106#endif
1107        bytebuffer_offset += 2;
1108        return res;
1109}
1110
1111static uint32_t buffer_read_le_u32(STATE_PARAM_ONLY)
1112{
1113        uint32_t res;
1114#if BB_LITTLE_ENDIAN
1115        move_from_unaligned32(res, &bytebuffer[bytebuffer_offset]);
1116#else
1117        res = bytebuffer[bytebuffer_offset];
1118        res |= bytebuffer[bytebuffer_offset + 1] << 8;
1119        res |= bytebuffer[bytebuffer_offset + 2] << 16;
1120        res |= bytebuffer[bytebuffer_offset + 3] << 24;
1121#endif
1122        bytebuffer_offset += 4;
1123        return res;
1124}
1125
1126static int check_header_gzip(STATE_PARAM transformer_state_t *xstate)
1127{
1128        union {
1129                unsigned char raw[8];
1130                struct {
1131                        uint8_t gz_method;
1132                        uint8_t flags;
1133                        uint32_t mtime;
1134                        uint8_t xtra_flags_UNUSED;
1135                        uint8_t os_flags_UNUSED;
1136                } PACKED formatted;
1137        } header;
1138
1139        BUILD_BUG_ON(sizeof(header) != 8);
1140
1141        /*
1142         * Rewind bytebuffer. We use the beginning because the header has 8
1143         * bytes, leaving enough for unwinding afterwards.
1144         */
1145        bytebuffer_size -= bytebuffer_offset;
1146        memmove(bytebuffer, &bytebuffer[bytebuffer_offset], bytebuffer_size);
1147        bytebuffer_offset = 0;
1148
1149        if (!top_up(PASS_STATE 8))
1150                return 0;
1151        memcpy(header.raw, &bytebuffer[bytebuffer_offset], 8);
1152        bytebuffer_offset += 8;
1153
1154        /* Check the compression method */
1155        if (header.formatted.gz_method != 8) {
1156                return 0;
1157        }
1158
1159        if (header.formatted.flags & 0x04) {
1160                /* bit 2 set: extra field present */
1161                unsigned extra_short;
1162
1163                if (!top_up(PASS_STATE 2))
1164                        return 0;
1165                extra_short = buffer_read_le_u16(PASS_STATE_ONLY);
1166                if (!top_up(PASS_STATE extra_short))
1167                        return 0;
1168                /* Ignore extra field */
1169                bytebuffer_offset += extra_short;
1170        }
1171
1172        /* Discard original name and file comment if any */
1173        /* bit 3 set: original file name present */
1174        /* bit 4 set: file comment present */
1175        if (header.formatted.flags & 0x18) {
1176                while (1) {
1177                        do {
1178                                if (!top_up(PASS_STATE 1))
1179                                        return 0;
1180                        } while (bytebuffer[bytebuffer_offset++] != 0);
1181                        if ((header.formatted.flags & 0x18) != 0x18)
1182                                break;
1183                        header.formatted.flags &= ~0x18;
1184                }
1185        }
1186
1187        xstate->mtime = SWAP_LE32(header.formatted.mtime);
1188
1189        /* Read the header checksum */
1190        if (header.formatted.flags & 0x02) {
1191                if (!top_up(PASS_STATE 2))
1192                        return 0;
1193                bytebuffer_offset += 2;
1194        }
1195        return 1;
1196}
1197
1198IF_DESKTOP(long long) int FAST_FUNC
1199unpack_gz_stream(transformer_state_t *xstate)
1200{
1201        uint32_t v32;
1202        IF_DESKTOP(long long) int total, n;
1203        DECLARE_STATE;
1204
1205#if !ENABLE_FEATURE_SEAMLESS_Z
1206        if (check_signature16(xstate, GZIP_MAGIC))
1207                return -1;
1208#else
1209        if (!xstate->signature_skipped) {
1210                uint16_t magic2;
1211
1212                if (full_read(xstate->src_fd, &magic2, 2) != 2) {
1213 bad_magic:
1214                        bb_error_msg("invalid magic");
1215                        return -1;
1216                }
1217                if (magic2 == COMPRESS_MAGIC) {
1218                        xstate->signature_skipped = 2;
1219                        return unpack_Z_stream(xstate);
1220                }
1221                if (magic2 != GZIP_MAGIC)
1222                        goto bad_magic;
1223        }
1224#endif
1225
1226        total = 0;
1227
1228        ALLOC_STATE;
1229        to_read = -1;
1230//      bytebuffer_max = 0x8000;
1231        bytebuffer = xmalloc(bytebuffer_max);
1232        gunzip_src_fd = xstate->src_fd;
1233
1234 again:
1235        if (!check_header_gzip(PASS_STATE xstate)) {
1236                bb_error_msg("corrupted data");
1237                total = -1;
1238                goto ret;
1239        }
1240
1241        n = inflate_unzip_internal(PASS_STATE xstate);
1242        if (n < 0) {
1243                total = -1;
1244                goto ret;
1245        }
1246        total += n;
1247
1248        if (!top_up(PASS_STATE 8)) {
1249                bb_error_msg("corrupted data");
1250                total = -1;
1251                goto ret;
1252        }
1253
1254        /* Validate decompression - crc */
1255        v32 = buffer_read_le_u32(PASS_STATE_ONLY);
1256        if ((~gunzip_crc) != v32) {
1257                bb_error_msg("crc error");
1258                total = -1;
1259                goto ret;
1260        }
1261
1262        /* Validate decompression - size */
1263        v32 = buffer_read_le_u32(PASS_STATE_ONLY);
1264        if ((uint32_t)gunzip_bytes_out != v32) {
1265                bb_error_msg("incorrect length");
1266                total = -1;
1267        }
1268
1269        if (!top_up(PASS_STATE 2))
1270                goto ret; /* EOF */
1271
1272        if (bytebuffer[bytebuffer_offset] == 0x1f
1273         && bytebuffer[bytebuffer_offset + 1] == 0x8b
1274        ) {
1275                bytebuffer_offset += 2;
1276                goto again;
1277        }
1278        /* GNU gzip says: */
1279        /*bb_error_msg("decompression OK, trailing garbage ignored");*/
1280
1281 ret:
1282        free(bytebuffer);
1283        DEALLOC_STATE;
1284        return total;
1285}
1286