Bump to version 1.22.1
[platform/upstream/busybox.git] / archival / gzip.c
index 76ee1cf..1e779c9 100644 (file)
@@ -13,9 +13,8 @@
  * files as well as stdin/stdout, and to generally behave itself wrt
  * command line handling.
  *
- * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
+ * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  */
-
 /* big objects in bss:
  * 00000020 b bl_count
  * 00000074 b base_length
@@ -31,7 +30,6 @@
  * 00000480 b static_ltree
  * 000008f4 b dyn_ltree
  */
-
 /* TODO: full support for -v for DESKTOP
  * "/usr/bin/gzip -v a bogus aa" should say:
 a:       85.1% -- replaced with a.gz
@@ -39,7 +37,52 @@ gzip: bogus: No such file or directory
 aa:      85.1% -- replaced with aa.gz
 */
 
-#include "busybox.h"
+//config:config GZIP
+//config:      bool "gzip"
+//config:      default y
+//config:      help
+//config:        gzip is used to compress files.
+//config:        It's probably the most widely used UNIX compression program.
+//config:
+//config:config FEATURE_GZIP_LONG_OPTIONS
+//config:      bool "Enable long options"
+//config:      default y
+//config:      depends on GZIP && LONG_OPTS
+//config:      help
+//config:        Enable use of long options, increases size by about 106 Bytes
+//config:
+//config:config GZIP_FAST
+//config:      int "Trade memory for gzip speed (0:small,slow - 2:fast,big)"
+//config:      default 0
+//config:      range 0 2
+//config:      depends on GZIP
+//config:      help
+//config:        Enable big memory options for gzip.
+//config:        0: small buffers, small hash-tables
+//config:        1: larger buffers, larger hash-tables
+//config:        2: larger buffers, largest hash-tables
+//config:        Larger models may give slightly better compression
+
+//applet:IF_GZIP(APPLET(gzip, BB_DIR_BIN, BB_SUID_DROP))
+//kbuild:lib-$(CONFIG_GZIP) += gzip.o
+
+//usage:#define gzip_trivial_usage
+//usage:       "[-cfd] [FILE]..."
+//usage:#define gzip_full_usage "\n\n"
+//usage:       "Compress FILEs (or stdin)\n"
+//usage:     "\n       -d      Decompress"
+//usage:     "\n       -c      Write to stdout"
+//usage:     "\n       -f      Force"
+//usage:
+//usage:#define gzip_example_usage
+//usage:       "$ ls -la /tmp/busybox*\n"
+//usage:       "-rw-rw-r--    1 andersen andersen  1761280 Apr 14 17:47 /tmp/busybox.tar\n"
+//usage:       "$ gzip /tmp/busybox.tar\n"
+//usage:       "$ ls -la /tmp/busybox*\n"
+//usage:       "-rw-rw-r--    1 andersen andersen   554058 Apr 14 17:49 /tmp/busybox.tar.gz\n"
+
+#include "libbb.h"
+#include "bb_archive.h"
 
 
 /* ===========================================================================
@@ -47,12 +90,12 @@ aa:      85.1% -- replaced with aa.gz
 //#define DEBUG 1
 /* Diagnostic functions */
 #ifdef DEBUG
-#  define Assert(cond,msg) {if(!(cond)) bb_error_msg(msg);}
+#  define Assert(cond,msg) { if (!(cond)) bb_error_msg(msg); }
 #  define Trace(x) fprintf x
-#  define Tracev(x) {if (verbose) fprintf x ;}
-#  define Tracevv(x) {if (verbose > 1) fprintf x ;}
-#  define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
-#  define Tracecv(c,x) {if (verbose > 1 && (c)) fprintf x ;}
+#  define Tracev(x) {if (verbose) fprintf x}
+#  define Tracevv(x) {if (verbose > 1) fprintf x}
+#  define Tracec(c,x) {if (verbose && (c)) fprintf x}
+#  define Tracecv(c,x) {if (verbose > 1 && (c)) fprintf x}
 #else
 #  define Assert(cond,msg)
 #  define Trace(x)
@@ -65,15 +108,17 @@ aa:      85.1% -- replaced with aa.gz
 
 /* ===========================================================================
  */
-#define SMALL_MEM
-
-//// /* Compression methods (see algorithm.doc) */
-//// /* Only STORED and DEFLATED are supported by this BusyBox module */
-//// #define STORED      0
-//// /* methods 4 to 7 reserved */
-//// #define DEFLATED    8
+#if   CONFIG_GZIP_FAST == 0
+# define SMALL_MEM
+#elif CONFIG_GZIP_FAST == 1
+# define MEDIUM_MEM
+#elif CONFIG_GZIP_FAST == 2
+# define BIG_MEM
+#else
+# error "Invalid CONFIG_GZIP_FAST value"
+#endif
 
-#ifndef        INBUFSIZ
+#ifndef INBUFSIZ
 #  ifdef SMALL_MEM
 #    define INBUFSIZ  0x2000   /* input buffer size */
 #  else
@@ -81,7 +126,7 @@ aa:      85.1% -- replaced with aa.gz
 #  endif
 #endif
 
-#ifndef        OUTBUFSIZ
+#ifndef OUTBUFSIZ
 #  ifdef SMALL_MEM
 #    define OUTBUFSIZ   8192   /* output buffer size */
 #  else
@@ -241,7 +286,7 @@ enum {
 };
 
 
-struct global1 {
+struct globals {
 
        lng block_start;
 
@@ -272,7 +317,7 @@ struct global1 {
 #define DECLARE(type, array, size) \
        type * array
 #define ALLOC(type, array, size) \
-       array = xzalloc((size_t)(((size)+1L)/2) * 2*sizeof(type));
+       array = xzalloc((size_t)(((size)+1L)/2) * 2*sizeof(type))
 #define FREE(array) \
        do { free(array); array = NULL; } while (0)
 
@@ -307,25 +352,19 @@ struct global1 {
        /* DECLARE(Pos, head, 1<<HASH_BITS); */
 #define head (G1.prev + WSIZE) /* hash head (see deflate.c) */
 
-
 /* number of input bytes */
        ulg isize;              /* only 32 bits stored in .gz file */
 
-////   int method = DEFLATED;  /* compression method */
-//##   int exit_code;          /* program exit code */
+/* bbox always use stdin/stdout */
+#define ifd STDIN_FILENO       /* input file descriptor */
+#define ofd STDOUT_FILENO      /* output file descriptor */
 
-/* original time stamp (modification time) */
-       ulg time_stamp;         /* only 32 bits stored in .gz file */
-
-//TODO: get rid of this
-       int ifd;                        /* input file descriptor */
-       int ofd;                        /* output file descriptor */
 #ifdef DEBUG
        unsigned insize;        /* valid bytes in l_buf */
 #endif
        unsigned outcnt;        /* bytes in output buffer */
 
-       smallint eofile;                /* flag set at end of input file */
+       smallint eofile;        /* flag set at end of input file */
 
 /* ===========================================================================
  * Local data used by the "bit string" routines.
@@ -351,12 +390,11 @@ struct global1 {
        ulg bits_sent;                  /* bit length of the compressed data */
 #endif
 
-       uint32_t *crc_32_tab;
+       /*uint32_t *crc_32_tab;*/
        uint32_t crc;   /* shift register contents */
 };
 
-extern struct global1 *global_ptr;
-#define G1 (*(global_ptr - 1))
+#define G1 (*(ptr_to_globals - 1))
 
 
 /* ===========================================================================
@@ -368,7 +406,7 @@ static void flush_outbuf(void)
        if (G1.outcnt == 0)
                return;
 
-       xwrite(G1.ofd, (char *) G1.outbuf, G1.outcnt);
+       xwrite(ofd, (char *) G1.outbuf, G1.outcnt);
        G1.outcnt = 0;
 }
 
@@ -401,32 +439,13 @@ static void put_32bit(ulg n)
 }
 
 /* ===========================================================================
- * Clear input and output buffers
- */
-static void clear_bufs(void)
-{
-       G1.outcnt = 0;
-#ifdef DEBUG
-       G1.insize = 0;
-#endif
-       G1.isize = 0;
-}
-
-
-/* ===========================================================================
  * Run a set of bytes through the crc shift register.  If s is a NULL
  * pointer, then initialize the crc shift register contents instead.
  * Return the current crc in either case.
  */
-static uint32_t updcrc(uch * s, unsigned n)
+static void updcrc(uch * s, unsigned n)
 {
-       uint32_t c = G1.crc;
-       while (n) {
-               c = G1.crc_32_tab[(uch)(c ^ *s++)] ^ (c >> 8);
-               n--;
-       }
-       G1.crc = c;
-       return c;
+       G1.crc = crc32_block_endian0(G1.crc, s, n, global_crc32_table /*G1.crc_32_tab*/);
 }
 
 
@@ -441,7 +460,7 @@ static unsigned file_read(void *buf, unsigned size)
 
        Assert(G1.insize == 0, "l_buf not empty");
 
-       len = safe_read(G1.ifd, buf, size);
+       len = safe_read(ifd, buf, size);
        if (len == (unsigned)(-1) || len == 0)
                return len;
 
@@ -645,10 +664,12 @@ static int longest_match(IPos cur_match)
                /* Skip to next match if the match length cannot increase
                 * or if the match length is less than 2:
                 */
-               if (match[best_len] != scan_end ||
-                       match[best_len - 1] != scan_end1 ||
-                       *match != *scan || *++match != scan[1])
+               if (match[best_len] != scan_end
+                || match[best_len - 1] != scan_end1
+                || *match != *scan || *++match != scan[1]
+               ) {
                        continue;
+               }
 
                /* The check at best_len-1 can be removed because it will be made
                 * again later. (This heuristic is not always a win.)
@@ -699,7 +720,7 @@ static void check_match(IPos start, IPos match, int length)
        if (verbose > 1) {
                bb_error_msg("\\[%d,%d]", start - match, length);
                do {
-                       putc(G1.window[start++], stderr);
+                       bb_putchar_stderr(G1.window[start++]);
                } while (--length != 0);
        }
 }
@@ -743,10 +764,10 @@ static void check_match(IPos start, IPos match, int length)
  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
  *
  *  INTERFACE
- *      void ct_init() //// ush *attr, int *methodp)
- *          Allocate the match buffer, initialize the various tables and save
+ *      void ct_init()
+ *          Allocate the match buffer, initialize the various tables [and save
  *          the location of the internal file attribute (ascii/binary) and
- *          method (DEFLATE/STORE)
+ *          method (DEFLATE/STORE) -- deleted in bbox]
  *
  *      void ct_tally(int dist, int lc);
  *          Save the match info and tally the frequency counts.
@@ -781,26 +802,24 @@ static void check_match(IPos start, IPos match, int length)
 #define BL_CODES  19
 /* number of codes used to transfer the bit lengths */
 
-typedef uch extra_bits_t;
-
 /* extra bits for each length code */
-static const extra_bits_t extra_lbits[LENGTH_CODES]= {
+static const uint8_t extra_lbits[LENGTH_CODES] ALIGN1 = {
        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, 5, 5, 5, 0
 };
 
 /* extra bits for each distance code */
-static const extra_bits_t extra_dbits[D_CODES] = {
+static const uint8_t extra_dbits[D_CODES] ALIGN1 = {
        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,
        10, 10, 11, 11, 12, 12, 13, 13
 };
 
 /* extra bits for each bit length code */
-static const extra_bits_t extra_blbits[BL_CODES] = {
+static const uint8_t extra_blbits[BL_CODES] ALIGN1 = {
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 };
 
 /* number of codes at each bit length for an optimal tree */
-static const uch bl_order[BL_CODES] = {
+static const uint8_t bl_order[BL_CODES] ALIGN1 = {
        16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
 
 #define STORED_BLOCK 0
@@ -874,14 +893,14 @@ typedef struct ct_data {
 typedef struct tree_desc {
        ct_data *dyn_tree;      /* the dynamic tree */
        ct_data *static_tree;   /* corresponding static tree or NULL */
-       const extra_bits_t *extra_bits; /* extra bits for each code or NULL */
+       const uint8_t *extra_bits;      /* extra bits for each code or NULL */
        int extra_base;         /* base index for extra_bits */
        int elems;                      /* max number of elements in the tree */
        int max_length;         /* max bit length for the codes */
        int max_code;           /* largest code with non zero frequency */
 } tree_desc;
 
-struct global2 {
+struct globals2 {
 
        ush heap[HEAP_SIZE];     /* heap used to build the Huffman trees */
        int heap_len;            /* number of elements in the heap */
@@ -966,13 +985,9 @@ struct global2 {
        ulg static_len;          /* bit length of current block with static trees */
 
        ulg compressed_len;      /* total bit length of compressed file */
-
-////   ush *file_type;          /* pointer to UNKNOWN, BINARY or ASCII */
-////   int *file_method;        /* pointer to DEFLATE or STORE */
-
 };
 
-#define G2ptr ((struct global2*)(global_ptr))
+#define G2ptr ((struct globals2*)(ptr_to_globals))
 #define G2 (*G2ptr)
 
 
@@ -993,7 +1008,7 @@ static void compress_block(ct_data * ltree, ct_data * dtree);
 #else
 #  define SEND_CODE(c, tree) \
 { \
-       if (verbose > 1) bb_error_msg("\ncd %3d ",(c)); \
+       if (verbose > 1) bb_error_msg("\ncd %3d ", (c)); \
        send_bits(tree[c].Code, tree[c].Len); \
 }
 #endif
@@ -1081,7 +1096,7 @@ static void pqdownheap(ct_data * tree, int k)
 static void gen_bitlen(tree_desc * desc)
 {
        ct_data *tree = desc->dyn_tree;
-       const extra_bits_t *extra = desc->extra_bits;
+       const uint8_t *extra = desc->extra_bits;
        int base = desc->extra_base;
        int max_code = desc->max_code;
        int max_length = desc->max_length;
@@ -1191,7 +1206,7 @@ static void gen_codes(ct_data * tree, int max_code)
         * must be all ones.
         */
        Assert(code + G2.bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
-                  "inconsistent bit counts");
+                       "inconsistent bit counts");
        Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
 
        for (n = 0; n <= max_code; n++) {
@@ -1204,7 +1219,7 @@ static void gen_codes(ct_data * tree, int max_code)
 
                Tracec(tree != G2.static_ltree,
                           (stderr, "\nn %3d %c l %2d c %4x (%x) ", n,
-                               (isgraph(n) ? n : ' '), len, tree[n].Code,
+                               (n > ' ' ? n : ' '), len, tree[n].Code,
                                next_code[len] - 1));
        }
 }
@@ -1495,31 +1510,6 @@ static void send_all_trees(int lcodes, int dcodes, int blcodes)
 }
 
 
-/////* ===========================================================================
-//// * Set the file type to ASCII or BINARY, using a crude approximation:
-//// * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
-//// * IN assertion: the fields freq of dyn_ltree are set and the total of all
-//// * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
-//// */
-////static void set_file_type(void)
-////{
-////   int n = 0;
-////   unsigned ascii_freq = 0;
-////   unsigned bin_freq = 0;
-////
-////   while (n < 7)
-////           bin_freq += G2.dyn_ltree[n++].Freq;
-////   while (n < 128)
-////           ascii_freq += G2.dyn_ltree[n++].Freq;
-////   while (n < LITERALS)
-////           bin_freq += G2.dyn_ltree[n++].Freq;
-////   *G2.file_type = (bin_freq > (ascii_freq >> 2)) ? BINARY : ASCII;
-////   if (*G2.file_type == BINARY && translate_eol) {
-////           bb_error_msg("-l used on binary file");
-////   }
-////}
-
-
 /* ===========================================================================
  * Save the match info and tally the frequency counts. Return true if
  * the current block must be flushed.
@@ -1564,9 +1554,9 @@ static int ct_tally(int dist, int lc)
                }
                out_length >>= 3;
                Trace((stderr,
-                          "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
-                          G2.last_lit, G2.last_dist, in_length, out_length,
-                          100L - out_length * 100L / in_length));
+                               "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
+                               G2.last_lit, G2.last_dist, in_length, out_length,
+                               100L - out_length * 100L / in_length));
                if (G2.last_dist < G2.last_lit / 2 && out_length < in_length / 2)
                        return 1;
        }
@@ -1597,7 +1587,7 @@ static void compress_block(ct_data * ltree, ct_data * dtree)
                lc = G1.l_buf[lx++];
                if ((flag & 1) == 0) {
                        SEND_CODE(lc, ltree);   /* send a literal byte */
-                       Tracecv(isgraph(lc), (stderr, " '%c' ", lc));
+                       Tracecv(lc > ' ', (stderr, " '%c' ", lc));
                } else {
                        /* Here, lc is the match length - MIN_MATCH */
                        code = G2.length_code[lc];
@@ -1638,10 +1628,6 @@ static ulg flush_block(char *buf, ulg stored_len, int eof)
 
        G2.flag_buf[G2.last_flags] = G2.flags;   /* Save the flags for the last 8 items */
 
-////   /* Check if the file is ascii or binary */
-////   if (*G2.file_type == (ush) UNKNOWN)
-////           set_file_type();
-
        /* Construct the literal and distance trees */
        build_tree(&G2.l_desc);
        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", G2.opt_len, G2.static_len));
@@ -1662,9 +1648,9 @@ static ulg flush_block(char *buf, ulg stored_len, int eof)
        static_lenb = (G2.static_len + 3 + 7) >> 3;
 
        Trace((stderr,
-                  "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
-                  opt_lenb, G2.opt_len, static_lenb, G2.static_len, stored_len,
-                  G2.last_lit, G2.last_dist));
+                       "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
+                       opt_lenb, G2.opt_len, static_lenb, G2.static_len, stored_len,
+                       G2.last_lit, G2.last_dist));
 
        if (static_lenb <= opt_lenb)
                opt_lenb = static_lenb;
@@ -1680,7 +1666,6 @@ static ulg flush_block(char *buf, ulg stored_len, int eof)
 
                copy_block(buf, (unsigned) stored_len, 0);      /* without header */
                G2.compressed_len = stored_len << 3;
-////           *file_method = STORED;
 
        } else if (stored_len + 4 <= opt_lenb && buf != NULL) {
                /* 4: two words for the lengths */
@@ -1703,7 +1688,7 @@ static ulg flush_block(char *buf, ulg stored_len, int eof)
        } else {
                send_bits((DYN_TREES << 1) + eof, 3);
                send_all_trees(G2.l_desc.max_code + 1, G2.d_desc.max_code + 1,
-                                          max_blindex + 1);
+                                       max_blindex + 1);
                compress_block((ct_data *) G2.dyn_ltree, (ct_data *) G2.dyn_dtree);
                G2.compressed_len += 3 + G2.opt_len;
        }
@@ -1723,7 +1708,7 @@ static ulg flush_block(char *buf, ulg stored_len, int eof)
 
 /* ===========================================================================
  * Update a hash value with the given input byte
- * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
+ * IN  assertion: all calls to UPDATE_HASH are made with consecutive
  *    input characters, so that a running hash key can be computed from the
  *    previous key instead of complete recalculation each time.
  */
@@ -1754,7 +1739,7 @@ static ulg flush_block(char *buf, ulg stored_len, int eof)
 /* Insert string s in the dictionary and set match_head to the previous head
  * of the hash chain (the most recent string with same hash key). Return
  * the previous length of the hash chain.
- * IN  assertion: all calls to to INSERT_STRING are made with consecutive
+ * IN  assertion: all calls to INSERT_STRING are made with consecutive
  *    input characters and the first MIN_MATCH bytes of s are valid
  *    (except for the last MIN_MATCH-1 bytes of the input file). */
 #define INSERT_STRING(s, match_head) \
@@ -1931,15 +1916,13 @@ static void lm_init(ush * flagsp)
  * (DEFLATE/STORE).
  * One callsite in zip()
  */
-static void ct_init(void) ////ush * attr, int *methodp)
+static void ct_init(void)
 {
        int n;                          /* iterates over tree elements */
        int length;                     /* length value */
        int code;                       /* code value */
        int dist;                       /* distance index */
 
-////   file_type = attr;
-////   file_method = methodp;
        G2.compressed_len = 0L;
 
 #ifdef NOT_NEEDED
@@ -2022,42 +2005,26 @@ static void ct_init(void) ////ush * attr, int *methodp)
 /* ===========================================================================
  * Deflate in to out.
  * IN assertions: the input and output buffers are cleared.
- *   The variables time_stamp and save_orig_name are initialized.
  */
 
-/* put_header_byte is used for the compressed output
- * - for the initial 4 bytes that can't overflow the buffer. */
-#define put_header_byte(c) G1.outbuf[G1.outcnt++] = (c)
-
-static void zip(int in, int out)
+static void zip(ulg time_stamp)
 {
-////   uch my_flags = 0;       /* general purpose bit flags */
-////   ush attr = 0;           /* ascii/binary flag */
        ush deflate_flags = 0;  /* pkzip -es, -en or -ex equivalent */
-////   int method = DEFLATED;  /* compression method */
 
-       G1.ifd = in;
-       G1.ofd = out;
        G1.outcnt = 0;
 
        /* Write the header to the gzip file. See algorithm.doc for the format */
-
-       //put_header_byte(0x1f); /* magic header for gzip files, 1F 8B */
-       //put_header_byte(0x8b);
-       //////put_header_byte(DEFLATED); /* compression method */
-       //put_header_byte(8); /* compression method */
-       //put_header_byte(0); /* general flags */
        /* magic header for gzip files: 1F 8B */
-       /* compression method: 8 */
+       /* compression method: 8 (DEFLATED) */
        /* general flags: 0 */
        put_32bit(0x00088b1f);
-       put_32bit(G1.time_stamp);
+       put_32bit(time_stamp);
 
        /* Write deflated file to zip file */
        G1.crc = ~0;
 
        bi_init();
-       ct_init(); //// &attr, &method);
+       ct_init();
        lm_init(&deflate_flags);
 
        put_8bit(deflate_flags);        /* extra flags */
@@ -2074,81 +2041,34 @@ static void zip(int in, int out)
 
 
 /* ======================================================================== */
-static void abort_gzip(int ATTRIBUTE_UNUSED ignored)
+static
+IF_DESKTOP(long long) int FAST_FUNC pack_gzip(transformer_aux_data_t *aux UNUSED_PARAM)
 {
-       exit(1);
-}
-
-int gzip_main(int argc, char **argv);
-int gzip_main(int argc, char **argv)
-{
-       enum {
-               OPT_tostdout = 0x1,
-               OPT_force = 0x2,
-       };
-
-       unsigned opt;
-       int inFileNum;
-       int outFileNum;
-       int i;
-       struct stat statBuf;
+       struct stat s;
 
-       opt = getopt32(argc, argv, "cf123456789qv" USE_GUNZIP("d"));
-       //if (opt & 0x1) // -c
-       //if (opt & 0x2) // -f
-       /* Ignore 1-9 (compression level) options */
-       //if (opt & 0x4) // -1
-       //if (opt & 0x8) // -2
-       //if (opt & 0x10) // -3
-       //if (opt & 0x20) // -4
-       //if (opt & 0x40) // -5
-       //if (opt & 0x80) // -6
-       //if (opt & 0x100) // -7
-       //if (opt & 0x200) // -8
-       //if (opt & 0x400) // -9
-       //if (opt & 0x800) // -q
-       //if (opt & 0x1000) // -v
-#if ENABLE_GUNZIP /* gunzip_main may not be visible... */
-       if (opt & 0x2000) { // -d
-               /* FIXME: getopt32 should not depend on optind */
-               optind = 1;
-               return gunzip_main(argc, argv);
-       }
-#endif
-
-       /* Comment?? */
-       if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
-               signal(SIGINT, abort_gzip);
-       }
-#ifdef SIGTERM
-       if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
-               signal(SIGTERM, abort_gzip);
-       }
-#endif
-#ifdef SIGHUP
-       if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
-               signal(SIGHUP, abort_gzip);
-       }
+       /* Clear input and output buffers */
+       G1.outcnt = 0;
+#ifdef DEBUG
+       G1.insize = 0;
 #endif
+       G1.isize = 0;
 
-       global_ptr = xzalloc(sizeof(struct global1) + sizeof(struct global2));
-       global_ptr++;
-       G2.l_desc.dyn_tree    = G2.dyn_ltree;
-       G2.l_desc.static_tree = G2.static_ltree;
-       G2.l_desc.extra_bits  = extra_lbits;
-       G2.l_desc.extra_base  = LITERALS + 1;
-       G2.l_desc.elems       = L_CODES;
-       G2.l_desc.max_length  = MAX_BITS;
-       //G2.l_desc.max_code    = 0;
-
-       G2.d_desc.dyn_tree    = G2.dyn_dtree;
-       G2.d_desc.static_tree = G2.static_dtree;
-       G2.d_desc.extra_bits  = extra_dbits;
-       //G2.d_desc.extra_base  = 0;
-       G2.d_desc.elems       = D_CODES;
-       G2.d_desc.max_length  = MAX_BITS;
-       //G2.d_desc.max_code    = 0;
-
+       /* Reinit G2.xxx */
+       memset(&G2, 0, sizeof(G2));
+       G2.l_desc.dyn_tree     = G2.dyn_ltree;
+       G2.l_desc.static_tree  = G2.static_ltree;
+       G2.l_desc.extra_bits   = extra_lbits;
+       G2.l_desc.extra_base   = LITERALS + 1;
+       G2.l_desc.elems        = L_CODES;
+       G2.l_desc.max_length   = MAX_BITS;
+       //G2.l_desc.max_code     = 0;
+       G2.d_desc.dyn_tree     = G2.dyn_dtree;
+       G2.d_desc.static_tree  = G2.static_dtree;
+       G2.d_desc.extra_bits   = extra_dbits;
+       //G2.d_desc.extra_base   = 0;
+       G2.d_desc.elems        = D_CODES;
+       G2.d_desc.max_length   = MAX_BITS;
+       //G2.d_desc.max_code     = 0;
        G2.bl_desc.dyn_tree    = G2.bl_tree;
        //G2.bl_desc.static_tree = NULL;
        G2.bl_desc.extra_bits  = extra_blbits,
@@ -2157,86 +2077,79 @@ int gzip_main(int argc, char **argv)
        G2.bl_desc.max_length  = MAX_BL_BITS;
        //G2.bl_desc.max_code    = 0;
 
-       /* Allocate all global buffers (for DYN_ALLOC option) */
-       ALLOC(uch, G1.l_buf, INBUFSIZ);
-       ALLOC(uch, G1.outbuf, OUTBUFSIZ);
-       ALLOC(ush, G1.d_buf, DIST_BUFSIZE);
-       ALLOC(uch, G1.window, 2L * WSIZE);
-       ALLOC(ush, G1.prev, 1L << BITS);
-
-       /* Initialise the CRC32 table */
-       G1.crc_32_tab = crc32_filltable(0);
-
-       clear_bufs();
-
-       if (optind == argc) {
-               G1.time_stamp = 0;
-               zip(STDIN_FILENO, STDOUT_FILENO);
-               return 0; //## G1.exit_code;
-       }
-
-       for (i = optind; i < argc; i++) {
-               char *path = NULL;
-
-               clear_bufs();
-               if (LONE_DASH(argv[i])) {
-                       G1.time_stamp = 0;
-                       inFileNum = STDIN_FILENO;
-                       outFileNum = STDOUT_FILENO;
-               } else {
-                       inFileNum = xopen(argv[i], O_RDONLY);
-                       if (fstat(inFileNum, &statBuf) < 0)
-                               bb_perror_msg_and_die("%s", argv[i]);
-                       G1.time_stamp = statBuf.st_ctime;
+       s.st_ctime = 0;
+       fstat(STDIN_FILENO, &s);
+       zip(s.st_ctime);
+       return 0;
+}
 
-                       if (!(opt & OPT_tostdout)) {
-                               path = xasprintf("%s.gz", argv[i]);
+#if ENABLE_FEATURE_GZIP_LONG_OPTIONS
+static const char gzip_longopts[] ALIGN1 =
+       "stdout\0"              No_argument       "c"
+       "to-stdout\0"           No_argument       "c"
+       "force\0"               No_argument       "f"
+       "verbose\0"             No_argument       "v"
+#if ENABLE_GUNZIP
+       "decompress\0"          No_argument       "d"
+       "uncompress\0"          No_argument       "d"
+       "test\0"                No_argument       "t"
+#endif
+       "quiet\0"               No_argument       "q"
+       "fast\0"                No_argument       "1"
+       "best\0"                No_argument       "9"
+       ;
+#endif
 
-                               /* Open output file */
-#if defined(__GLIBC__) && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 1 && defined(O_NOFOLLOW)
-                               outFileNum = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
+/*
+ * Linux kernel build uses gzip -d -n. We accept and ignore -n.
+ * Man page says:
+ * -n --no-name
+ * gzip: do not save the original file name and time stamp.
+ * (The original name is always saved if the name had to be truncated.)
+ * gunzip: do not restore the original file name/time even if present
+ * (remove only the gzip suffix from the compressed file name).
+ * This option is the default when decompressing.
+ * -N --name
+ * gzip: always save the original file name and time stamp (this is the default)
+ * gunzip: restore the original file name and time stamp if present.
+ */
+
+int gzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+#if ENABLE_GUNZIP
+int gzip_main(int argc, char **argv)
 #else
-                               outFileNum = open(path, O_RDWR | O_CREAT | O_EXCL);
+int gzip_main(int argc UNUSED_PARAM, char **argv)
 #endif
-                               if (outFileNum < 0) {
-                                       bb_perror_msg("%s", path);
-                                       free(path);
-                                       continue;
-                               }
-
-                               /* Set permissions on the file */
-                               fchmod(outFileNum, statBuf.st_mode);
-                       } else
-                               outFileNum = STDOUT_FILENO;
-               }
-
-               if (path == NULL && isatty(outFileNum) && !(opt & OPT_force)) {
-                       bb_error_msg("compressed data not written "
-                               "to a terminal. Use -f to force compression.");
-                       free(path);
-                       continue;
-               }
-
-               zip(inFileNum, outFileNum);
+{
+       unsigned opt;
 
-               if (path != NULL) {
-                       char *delFileName;
+#if ENABLE_FEATURE_GZIP_LONG_OPTIONS
+       applet_long_options = gzip_longopts;
+#endif
+       /* Must match bbunzip's constants OPT_STDOUT, OPT_FORCE! */
+       opt = getopt32(argv, "cfv" IF_GUNZIP("dt") "q123456789n");
+#if ENABLE_GUNZIP /* gunzip_main may not be visible... */
+       if (opt & 0x18) // -d and/or -t
+               return gunzip_main(argc, argv);
+#endif
+       option_mask32 &= 0x7; /* ignore -q, -0..9 */
+       //if (opt & 0x1) // -c
+       //if (opt & 0x2) // -f
+       //if (opt & 0x4) // -v
+       argv += optind;
 
-                       close(inFileNum);
-                       close(outFileNum);
+       SET_PTR_TO_GLOBALS((char *)xzalloc(sizeof(struct globals)+sizeof(struct globals2))
+                       + sizeof(struct globals));
 
-                       /* Delete the original file */
-                       // Pity we don't propagate zip failures to this place...
-                       //if (zip_is_ok)
-                               delFileName = argv[i];
-                       //else
-                       //      delFileName = path;
-                       if (unlink(delFileName) < 0)
-                               bb_perror_msg("%s", delFileName);
-               }
+       /* Allocate all global buffers (for DYN_ALLOC option) */
+       ALLOC(uch, G1.l_buf, INBUFSIZ);
+       ALLOC(uch, G1.outbuf, OUTBUFSIZ);
+       ALLOC(ush, G1.d_buf, DIST_BUFSIZE);
+       ALLOC(uch, G1.window, 2L * WSIZE);
+       ALLOC(ush, G1.prev, 1L << BITS);
 
-               free(path);
-       }
+       /* Initialize the CRC32 table */
+       global_crc32_table = crc32_filltable(NULL, 0);
 
-       return 0; //##G1.exit_code;
+       return bbunpack(argv, pack_gzip, append_ext, "gz");
 }