1 /* vi: set sw=4 ts=4: */
3 * Gzip implementation for busybox
5 * Based on GNU gzip Copyright (C) 1992-1993 Jean-loup Gailly.
7 * Originally adjusted for busybox by Charles P. Wright <cpw@unix.asb.com>
8 * "this is a stripped down version of gzip I put into busybox, it does
9 * only standard in to standard out with -9 compression. It also requires
10 * the zcat module for some important functions."
12 * Adjusted further by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
13 * to support files as well as stdin/stdout, and to generally behave itself wrt
14 * command line handling.
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 /* These defines are very important for BusyBox. Without these,
35 * huge chunks of ram are pre-allocated making the BusyBox bss
36 * size Freaking Huge(tm), which is a bad thing.*/
41 static const char gzip_usage[] =
42 "gzip [OPTION]... FILE\n\n"
43 "Compress FILE with maximum compression.\n"
44 "When FILE is '-', reads standard input. Implies -c.\n\n"
47 "\t-c\tWrite output to standard output instead of FILE.gz\n";
50 /* I don't like nested includes, but the string and io functions are used
55 #define memzero(s, n) memset ((void *)(s), 0, (n))
58 # define RETSIGTYPE void
63 typedef unsigned char uch;
64 typedef unsigned short ush;
65 typedef unsigned long ulg;
67 /* Return codes from gzip */
72 /* Compression methods (see algorithm.doc) */
77 /* methods 4 to 7 reserved */
80 extern int method; /* compression method */
82 /* To save memory for 16 bit systems, some arrays are overlaid between
83 * the various modules:
84 * deflate: prev+head window d_buf l_buf outbuf
85 * unlzw: tab_prefix tab_suffix stack inbuf outbuf
86 * inflate: window inbuf
87 * unpack: window inbuf prefix_len
88 * unlzh: left+right window c_table inbuf c_len
89 * For compression, input is done in window[]. For decompression, output
90 * is done in window except for unlzw.
95 # define INBUFSIZ 0x2000 /* input buffer size */
97 # define INBUFSIZ 0x8000 /* input buffer size */
100 #define INBUF_EXTRA 64 /* required by unlzw() */
104 # define OUTBUFSIZ 8192 /* output buffer size */
106 # define OUTBUFSIZ 16384 /* output buffer size */
109 #define OUTBUF_EXTRA 2048 /* required by unlzw() */
113 # define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
115 # define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
120 # define EXTERN(type, array) extern type * array
121 # define DECLARE(type, array, size) type * array
122 # define ALLOC(type, array, size) { \
123 array = (type*)calloc((size_t)(((size)+1L)/2), 2*sizeof(type)); \
124 if (array == NULL) errorMsg("insufficient memory"); \
126 # define FREE(array) {if (array != NULL) free(array), array=NULL;}
128 # define EXTERN(type, array) extern type array[]
129 # define DECLARE(type, array, size) type array[size]
130 # define ALLOC(type, array, size)
134 EXTERN(uch, inbuf); /* input buffer */
135 EXTERN(uch, outbuf); /* output buffer */
136 EXTERN(ush, d_buf); /* buffer for distances, see trees.c */
137 EXTERN(uch, window); /* Sliding window and suffix table (unlzw) */
138 #define tab_suffix window
140 # define tab_prefix prev /* hash link (see deflate.c) */
141 # define head (prev+WSIZE) /* hash head (see deflate.c) */
142 EXTERN(ush, tab_prefix); /* prefix code (see unlzw.c) */
144 # define tab_prefix0 prev
145 # define head tab_prefix1
146 EXTERN(ush, tab_prefix0); /* prefix for even codes */
147 EXTERN(ush, tab_prefix1); /* prefix for odd codes */
150 extern unsigned insize; /* valid bytes in inbuf */
151 extern unsigned inptr; /* index of next byte to be processed in inbuf */
152 extern unsigned outcnt; /* bytes in output buffer */
154 extern long bytes_in; /* number of input bytes */
155 extern long bytes_out; /* number of output bytes */
156 extern long header_bytes; /* number of bytes in gzip header */
158 #define isize bytes_in
159 /* for compatibility with old zip sources (to be cleaned) */
161 extern int ifd; /* input file descriptor */
162 extern int ofd; /* output file descriptor */
163 extern char ifname[]; /* input file name or "stdin" */
164 extern char ofname[]; /* output file name or "stdout" */
165 extern char *progname; /* program name */
167 extern long time_stamp; /* original time stamp (modification time) */
168 extern long ifile_size; /* input file size, -1 for devices (debug only) */
170 typedef int file_t; /* Do not use stdio */
172 #define NO_FILE (-1) /* in memory compression */
175 #define PACK_MAGIC "\037\036" /* Magic header for packed files */
176 #define GZIP_MAGIC "\037\213" /* Magic header for gzip files, 1F 8B */
177 #define OLD_GZIP_MAGIC "\037\236" /* Magic header for gzip 0.5 = freeze 1.x */
178 #define LZH_MAGIC "\037\240" /* Magic header for SCO LZH Compress files */
179 #define PKZIP_MAGIC "\120\113\003\004" /* Magic header for pkzip files */
182 #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
183 #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
184 #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
185 #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
186 #define COMMENT 0x10 /* bit 4 set: file comment present */
187 #define ENCRYPTED 0x20 /* bit 5 set: file is encrypted */
188 #define RESERVED 0xC0 /* bit 6,7: reserved */
190 /* internal file attribute */
191 #define UNKNOWN 0xffff
196 # define WSIZE 0x8000 /* window size--must be a power of two, and */
197 #endif /* at least 32K for zip's deflate method */
200 #define MAX_MATCH 258
201 /* The minimum and maximum match lengths */
203 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
204 /* Minimum amount of lookahead, except at the end of the input file.
205 * See deflate.c for comments about the MIN_MATCH+1.
208 #define MAX_DIST (WSIZE-MIN_LOOKAHEAD)
209 /* In order to simplify the code, particularly on 16 bit machines, match
210 * distances are limited to MAX_DIST instead of WSIZE.
213 extern int decrypt; /* flag to turn on decryption */
214 extern int exit_code; /* program exit code */
215 extern int verbose; /* be verbose (-v) */
216 extern int quiet; /* be quiet (-q) */
217 extern int test; /* check .z file integrity */
218 extern int save_orig_name; /* set if original name must be saved */
220 #define get_byte() (inptr < insize ? inbuf[inptr++] : fill_inbuf(0))
221 #define try_byte() (inptr < insize ? inbuf[inptr++] : fill_inbuf(1))
223 /* put_byte is used for the compressed output, put_ubyte for the
224 * uncompressed output. However unlzw() uses window for its
225 * suffix table instead of its output buffer, so it does not use put_ubyte
226 * (to be cleaned up).
228 #define put_byte(c) {outbuf[outcnt++]=(uch)(c); if (outcnt==OUTBUFSIZ)\
230 #define put_ubyte(c) {window[outcnt++]=(uch)(c); if (outcnt==WSIZE)\
233 /* Output a 16 bit value, lsb first */
234 #define put_short(w) \
235 { if (outcnt < OUTBUFSIZ-2) { \
236 outbuf[outcnt++] = (uch) ((w) & 0xff); \
237 outbuf[outcnt++] = (uch) ((ush)(w) >> 8); \
239 put_byte((uch)((w) & 0xff)); \
240 put_byte((uch)((ush)(w) >> 8)); \
244 /* Output a 32 bit value to the bit stream, lsb first */
245 #define put_long(n) { \
246 put_short((n) & 0xffff); \
247 put_short(((ulg)(n)) >> 16); \
250 #define seekable() 0 /* force sequential output */
251 #define translate_eol 0 /* no option -a yet */
253 #define tolow(c) (isupper(c) ? (c)-'A'+'a' : (c)) /* force to lower case */
255 /* Macros for getting two-byte and four-byte header values */
256 #define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
257 #define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
259 /* Diagnostic functions */
261 # define Assert(cond,msg) {if(!(cond)) errorMsg(msg);}
262 # define Trace(x) fprintf x
263 # define Tracev(x) {if (verbose) fprintf x ;}
264 # define Tracevv(x) {if (verbose>1) fprintf x ;}
265 # define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
266 # define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
268 # define Assert(cond,msg)
273 # define Tracecv(c,x)
276 #define WARN(msg) {if (!quiet) fprintf msg ; \
277 if (exit_code == OK) exit_code = WARNING;}
279 #define do_exit(c) exit(c)
283 extern int zip (int in, int out);
284 extern int file_read (char *buf, unsigned size);
287 extern int unzip (int in, int out);
288 extern int check_zipfile (int in);
291 extern int unpack (int in, int out);
294 extern int unlzh (int in, int out);
297 RETSIGTYPE abort_gzip (void);
300 void lm_init (ush * flags);
304 void ct_init (ush * attr, int *method);
305 int ct_tally (int dist, int lc);
306 ulg flush_block (char *buf, ulg stored_len, int eof);
309 void bi_init (file_t zipfile);
310 void send_bits (int value, int length);
311 unsigned bi_reverse (unsigned value, int length);
312 void bi_windup (void);
313 void copy_block (char *buf, unsigned len, int header);
314 extern int (*read_buf) (char *buf, unsigned size);
317 extern int copy (int in, int out);
318 extern ulg updcrc (uch * s, unsigned n);
319 extern void clear_bufs (void);
320 extern int fill_inbuf (int eof_ok);
321 extern void flush_outbuf (void);
322 extern void flush_window (void);
323 extern void write_buf (int fd, void * buf, unsigned cnt);
324 extern char *strlwr (char *s);
325 extern char *add_envopt (int *argcp, char ***argvp, char *env);
326 extern void read_error (void);
327 extern void write_error (void);
328 extern void display_ratio (long num, long den, FILE * file);
331 extern int inflate (void);
333 /* lzw.h -- define the lzw functions.
334 * Copyright (C) 1992-1993 Jean-loup Gailly.
335 * This is free software; you can redistribute it and/or modify it under the
336 * terms of the GNU General Public License, see the file COPYING.
339 #if !defined(OF) && defined(lint)
346 #define INIT_BITS 9 /* Initial number of bits per code */
348 #define BIT_MASK 0x1f /* Mask for 'number of compression bits' */
349 /* Mask 0x20 is reserved to mean a fourth header byte, and 0x40 is free.
350 * It's a pity that old uncompress does not check bit 0x20. That makes
351 * extension of the format actually undesirable because old compress
352 * would just crash on the new format instead of giving a meaningful
353 * error message. It does check the number of bits, but it's more
354 * helpful to say "unsupported format, get a new version" than
355 * "can only handle 16 bits".
358 #define BLOCK_MODE 0x80
359 /* Block compression: if table is full and compression rate is dropping,
360 * clear the dictionary.
363 #define LZW_RESERVED 0x60 /* reserved bits */
365 #define CLEAR 256 /* flush the dictionary */
366 #define FIRST (CLEAR+1) /* first free entry */
368 extern int maxbits; /* max bits per code for LZW */
369 extern int block_mode; /* block compress mode -C compatible with 2.0 */
371 /* revision.h -- define the version number
372 * Copyright (C) 1992-1993 Jean-loup Gailly.
373 * This is free software; you can redistribute it and/or modify it under the
374 * terms of the GNU General Public License, see the file COPYING.
377 #define VERSION "1.2.4"
379 #define REVDATE "18 Aug 93"
381 /* This version does not support compression into old compress format: */
386 /* tailor.h -- target dependent definitions
387 * Copyright (C) 1992-1993 Jean-loup Gailly.
388 * This is free software; you can redistribute it and/or modify it under the
389 * terms of the GNU General Public License, see the file COPYING.
392 /* The target dependent definitions should be defined here only.
393 * The target dependent functions should be defined in tailor.c.
397 #if defined(__MSDOS__) && !defined(MSDOS)
401 #if defined(__OS2__) && !defined(OS2)
405 #if defined(OS2) && defined(MSDOS) /* MS C under OS/2 */
411 /* DJGPP version 1.09+ on MS-DOS.
412 * The DJGPP 1.09 stat() function must be upgraded before gzip will
414 * No need for DIRENT, since <unistd.h> defines POSIX_SOURCE which
428 # define HAVE_SYS_UTIME_H
432 # define PATH_SEP2 '\\'
433 # define PATH_SEP3 ':'
434 # define MAX_PATH_LEN 128
435 # define NO_MULTIPLE_DOTS
436 # define MAX_EXT_CHARS 3
437 # define Z_SUFFIX "z"
440 # define STDC_HEADERS
441 # define NO_SIZE_CHECK
442 # define casemap(c) tolow(c) /* Force file names to lower case */
444 # define OS_CODE 0x00
445 # define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
446 # if !defined(NO_ASM) && !defined(ASMV)
454 # define PATH_SEP2 '\\'
455 # define PATH_SEP3 ':'
456 # define MAX_PATH_LEN 260
458 # define NO_MULTIPLE_DOTS
459 # define MAX_EXT_CHARS 3
460 # define Z_SUFFIX "z"
461 # define casemap(c) tolow(c)
465 # define STDC_HEADERS
467 # define OS_CODE 0x06
468 # define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
470 # define HAVE_SYS_UTIME_H
477 # define HAVE_SYS_UTIME_H
480 # define EXPAND(argc,argv) \
481 {_response(&argc, &argv); _wildcard(&argc, &argv);}
490 # define EXPAND(argc,argv) \
491 {response_expand(&argc, &argv);}
495 #ifdef WIN32 /* Windows NT */
496 # define HAVE_SYS_UTIME_H
498 # define PATH_SEP2 '\\'
499 # define PATH_SEP3 ':'
500 # define MAX_PATH_LEN 260
503 # define STDC_HEADERS
504 # define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
508 # define NO_MULTIPLE_DOTS
509 # define MAX_EXT_CHARS 3
510 # define Z_SUFFIX "z"
511 # define casemap(c) tolow(c) /* Force file names to lower case */
513 # define OS_CODE 0x0b
520 /* Turbo C 2.0 does not accept static allocations of large arrays */
521 void *fcalloc(unsigned items, unsigned size);
522 void fcfree(void *ptr);
525 # define fcalloc(nitems,itemsize) halloc((long)(nitems),(itemsize))
526 # define fcfree(ptr) hfree(ptr)
530 # define fcalloc(items,size) calloc((items),(size))
532 # define fcalloc(items,size) malloc((size_t)(items)*(size_t)(size))
534 # define fcfree(ptr) free(ptr)
537 #if defined(VAXC) || defined(VMS)
538 # define PATH_SEP ']'
539 # define PATH_SEP2 ':'
540 # define SUFFIX_SEP ';'
541 # define NO_MULTIPLE_DOTS
542 # define Z_SUFFIX "-gz"
544 # define casemap(c) tolow(c)
545 # define OS_CODE 0x02
546 # define OPTIONS_VAR "GZIP_OPT"
547 # define STDC_HEADERS
549 # define EXPAND(argc,argv) vms_expand_args(&argc,&argv);
551 # define unlink delete
559 # define PATH_SEP2 ':'
560 # define STDC_HEADERS
561 # define OS_CODE 0x01
565 # define HAVE_UNISTD_H
567 # define NO_STDIN_FSTAT
572 # include <fcntl.h> /* for read() and write() */
573 # define direct dirent
574 extern void _expand_args(int *argc, char ***argv);
576 # define EXPAND(argc,argv) _expand_args(&argc,&argv);
577 # undef O_BINARY /* disable useless --ascii option */
581 #if defined(ATARI) || defined(atarist)
582 # ifndef STDC_HEADERS
583 # define STDC_HEADERS
584 # define HAVE_UNISTD_H
588 # define OS_CODE 0x05
590 # define PATH_SEP2 '\\'
591 # define PATH_SEP3 ':'
592 # define MAX_PATH_LEN 128
593 # define NO_MULTIPLE_DOTS
594 # define MAX_EXT_CHARS 3
595 # define Z_SUFFIX "z"
597 # define casemap(c) tolow(c) /* Force file names to lower case */
603 # define PATH_SEP ':'
606 # define NO_STDIN_FSTAT
609 # define chmod(file, mode) (0)
610 # define OPEN(name, flags, mode) open(name, flags)
611 # define OS_CODE 0x07
613 # define isatty(fd) ((fd) <= 2)
617 #ifdef __50SERIES /* Prime/PRIMOS */
618 # define PATH_SEP '>'
619 # define STDC_HEADERS
624 # define NO_STDIN_FSTAT
625 # define NO_SIZE_CHECK
628 # define casemap(c) tolow(c) /* Force file names to lower case */
629 # define put_char(c) put_byte((c) & 0x7F)
630 # define get_char(c) ascii2pascii(get_byte())
631 # define OS_CODE 0x0F /* temporary, subject to change */
633 # undef SIGTERM /* We don't want a signal handler for SIGTERM */
637 #if defined(pyr) && !defined(NOMEMCPY) /* Pyramid */
638 # define NOMEMCPY /* problem with overlapping copies */
642 # define OS_CODE 0x0a
646 # define NO_ST_INO /* don't rely on inode numbers */
650 /* Common defaults */
653 # define OS_CODE 0x03 /* assume Unix */
657 # define PATH_SEP '/'
661 # define casemap(c) (c)
665 # define OPTIONS_VAR "GZIP"
669 # define Z_SUFFIX ".gz"
673 # define MAX_SUFFIX MAX_EXT_CHARS
675 # define MAX_SUFFIX 30
678 #ifndef MAKE_LEGAL_NAME
679 # ifdef NO_MULTIPLE_DOTS
680 # define MAKE_LEGAL_NAME(name) make_simple_name(name)
682 # define MAKE_LEGAL_NAME(name)
688 /* keep at least MIN_PART chars between dots in a file name. */
692 # define EXPAND(argc,argv)
699 #ifndef SET_BINARY_MODE
700 # define SET_BINARY_MODE(fd)
704 # define OPEN(name, flags, mode) open(name, flags, mode)
708 # define get_char() get_byte()
712 # define put_char(c) put_byte(c)
714 /* bits.c -- output variable-length bit strings
715 * Copyright (C) 1992-1993 Jean-loup Gailly
716 * This is free software; you can redistribute it and/or modify it under the
717 * terms of the GNU General Public License, see the file COPYING.
724 * Output variable-length bit strings. Compression can be done
725 * to a file or to memory. (The latter is not supported in this version.)
729 * The PKZIP "deflate" file format interprets compressed file data
730 * as a sequence of bits. Multi-bit strings in the file may cross
731 * byte boundaries without restriction.
733 * The first bit of each byte is the low-order bit.
735 * The routines in this file allow a variable-length bit value to
736 * be output right-to-left (useful for literal values). For
737 * left-to-right output (useful for code strings from the tree routines),
738 * the bits must have been reversed first with bi_reverse().
740 * For in-memory compression, the compressed bit stream goes directly
741 * into the requested output buffer. The input data is read in blocks
742 * by the mem_read() function. The buffer is limited to 64K on 16 bit
747 * void bi_init (FILE *zipfile)
748 * Initialize the bit string routines.
750 * void send_bits (int value, int length)
751 * Write out a bit string, taking the source bits right to
754 * int bi_reverse (int value, int length)
755 * Reverse the bits of a bit string, taking the source bits left to
756 * right and emitting them right to left.
758 * void bi_windup (void)
759 * Write out any remaining bits in an incomplete byte.
761 * void copy_block(char *buf, unsigned len, int header)
762 * Copy a stored block to the zip file, storing first the length and
763 * its one's complement if requested.
771 /* ===========================================================================
772 * Local data used by the "bit string" routines.
775 local file_t zfile; /* output gzip file */
777 local unsigned short bi_buf;
779 /* Output buffer. bits are inserted starting at the bottom (least significant
783 #define Buf_size (8 * 2*sizeof(char))
784 /* Number of bits used within bi_buf. (bi_buf might be implemented on
785 * more than 16 bits on some systems.)
790 /* Number of valid bits in bi_buf. All bits above the last valid bit
794 int (*read_buf) (char *buf, unsigned size);
796 /* Current input function. Set to mem_read for in-memory compression */
799 ulg bits_sent; /* bit length of the compressed data */
802 /* ===========================================================================
803 * Initialize the bit string routines.
805 void bi_init(zipfile)
806 file_t zipfile; /* output zip file, NO_FILE for in-memory compression */
815 /* Set the defaults for file compression. They are set by memcompress
816 * for in-memory compression.
818 if (zfile != NO_FILE) {
819 read_buf = file_read;
823 /* ===========================================================================
824 * Send a value on a given number of bits.
825 * IN assertion: length <= 16 and value fits in length bits.
827 void send_bits(value, length)
828 int value; /* value to send */
829 int length; /* number of bits */
832 Tracev((stderr, " l %2d v %4x ", length, value));
833 Assert(length > 0 && length <= 15, "invalid length");
834 bits_sent += (ulg) length;
836 /* If not enough room in bi_buf, use (valid) bits from bi_buf and
837 * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
838 * unused bits in value.
840 if (bi_valid > (int) Buf_size - length) {
841 bi_buf |= (value << bi_valid);
843 bi_buf = (ush) value >> (Buf_size - bi_valid);
844 bi_valid += length - Buf_size;
846 bi_buf |= value << bi_valid;
851 /* ===========================================================================
852 * Reverse the first len bits of a code, using straightforward code (a faster
853 * method would use a table)
854 * IN assertion: 1 <= len <= 15
856 unsigned bi_reverse(code, len)
857 unsigned code; /* the value to invert */
858 int len; /* its bit length */
860 register unsigned res = 0;
864 code >>= 1, res <<= 1;
869 /* ===========================================================================
870 * Write out any remaining bits in an incomplete byte.
876 } else if (bi_valid > 0) {
882 bits_sent = (bits_sent + 7) & ~7;
886 /* ===========================================================================
887 * Copy a stored block to the zip file, storing first the length and its
888 * one's complement if requested.
890 void copy_block(buf, len, header)
891 char *buf; /* the input data */
892 unsigned len; /* its length */
893 int header; /* true if block header must be written */
895 bi_windup(); /* align on byte boundary */
898 put_short((ush) len);
899 put_short((ush) ~ len);
905 bits_sent += (ulg) len << 3;
918 /* deflate.c -- compress data using the deflation algorithm
919 * Copyright (C) 1992-1993 Jean-loup Gailly
920 * This is free software; you can redistribute it and/or modify it under the
921 * terms of the GNU General Public License, see the file COPYING.
927 * Identify new text as repetitions of old text within a fixed-
928 * length sliding window trailing behind the new text.
932 * The "deflation" process depends on being able to identify portions
933 * of the input text which are identical to earlier input (within a
934 * sliding window trailing behind the input currently being processed).
936 * The most straightforward technique turns out to be the fastest for
937 * most input files: try all possible matches and select the longest.
938 * The key feature of this algorithm is that insertions into the string
939 * dictionary are very simple and thus fast, and deletions are avoided
940 * completely. Insertions are performed at each input character, whereas
941 * string matches are performed only when the previous match ends. So it
942 * is preferable to spend more time in matches to allow very fast string
943 * insertions and avoid deletions. The matching algorithm for small
944 * strings is inspired from that of Rabin & Karp. A brute force approach
945 * is used to find longer strings when a small match has been found.
946 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
947 * (by Leonid Broukhis).
948 * A previous version of this file used a more sophisticated algorithm
949 * (by Fiala and Greene) which is guaranteed to run in linear amortized
950 * time, but has a larger average cost, uses more memory and is patented.
951 * However the F&G algorithm may be faster for some highly redundant
952 * files if the parameter max_chain_length (described below) is too large.
956 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
957 * I found it in 'freeze' written by Leonid Broukhis.
958 * Thanks to many info-zippers for bug reports and testing.
962 * APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
964 * A description of the Rabin and Karp algorithm is given in the book
965 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
967 * Fiala,E.R., and Greene,D.H.
968 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
972 * void lm_init (int pack_level, ush *flags)
973 * Initialize the "longest match" routines for a new file
976 * Processes a new input file and return its compressed length. Sets
977 * the compressed length, crc, deflate flags and internal file
983 /* ===========================================================================
984 * Configuration parameters
987 /* Compile with MEDIUM_MEM to reduce the memory requirements or
988 * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
989 * entire input file can be held in memory (not possible on 16 bit systems).
990 * Warning: defining these symbols affects HASH_BITS (see below) and thus
991 * affects the compression ratio. The compressed output
992 * is still correct, and might even be smaller in some cases.
996 # define HASH_BITS 13 /* Number of bits used to hash strings */
999 # define HASH_BITS 14
1002 # define HASH_BITS 15
1003 /* For portability to 16 bit machines, do not use values above 15. */
1006 /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
1007 * window with tab_suffix. Check that we can do this:
1009 #if (WSIZE<<1) > (1<<BITS)
1010 error:cannot overlay window with tab_suffix and prev with tab_prefix0
1012 #if HASH_BITS > BITS-1
1013 error:cannot overlay head with tab_prefix1
1015 #define HASH_SIZE (unsigned)(1<<HASH_BITS)
1016 #define HASH_MASK (HASH_SIZE-1)
1017 #define WMASK (WSIZE-1)
1018 /* HASH_SIZE and WSIZE must be powers of two */
1020 /* Tail of hash chains */
1023 /* speed options for the general purpose bit flag */
1025 # define TOO_FAR 4096
1027 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
1028 /* ===========================================================================
1029 * Local data used by the "longest match" routines.
1032 typedef unsigned IPos;
1034 /* A Pos is an index in the character window. We use short instead of int to
1035 * save space in the various tables. IPos is used only for parameter passing.
1038 /* DECLARE(uch, window, 2L*WSIZE); */
1039 /* Sliding window. Input bytes are read into the second half of the window,
1040 * and move to the first half later to keep a dictionary of at least WSIZE
1041 * bytes. With this organization, matches are limited to a distance of
1042 * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
1043 * performed with a length multiple of the block size. Also, it limits
1044 * the window size to 64K, which is quite useful on MSDOS.
1045 * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
1046 * be less efficient).
1049 /* DECLARE(Pos, prev, WSIZE); */
1050 /* Link to older string with same hash index. To limit the size of this
1051 * array to 64K, this link is maintained only for the last 32K strings.
1052 * An index in this array is thus a window index modulo 32K.
1055 /* DECLARE(Pos, head, 1<<HASH_BITS); */
1056 /* Heads of the hash chains or NIL. */
1058 ulg window_size = (ulg) 2 * WSIZE;
1060 /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
1061 * input file length plus MIN_LOOKAHEAD.
1066 /* window position at the beginning of the current output block. Gets
1067 * negative when the window is moved backwards.
1070 local unsigned ins_h; /* hash index of string to be inserted */
1072 #define H_SHIFT ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
1073 /* Number of bits by which ins_h and del_h must be shifted at each
1074 * input step. It must be such that after MIN_MATCH steps, the oldest
1075 * byte no longer takes part in the hash key, that is:
1076 * H_SHIFT * MIN_MATCH >= HASH_BITS
1079 unsigned int near prev_length;
1081 /* Length of the best match at previous step. Matches not greater than this
1082 * are discarded. This is used in the lazy match evaluation.
1085 unsigned near strstart; /* start of string to insert */
1086 unsigned near match_start; /* start of matching string */
1087 local int eofile; /* flag set at end of input file */
1088 local unsigned lookahead; /* number of valid bytes ahead in window */
1090 unsigned near max_chain_length;
1092 /* To speed up deflation, hash chains are never searched beyond this length.
1093 * A higher limit improves compression ratio but degrades the speed.
1096 local unsigned int max_lazy_match;
1098 /* Attempt to find a better match only when the current match is strictly
1099 * smaller than this value. This mechanism is used only for compression
1102 #define max_insert_length max_lazy_match
1103 /* Insert new strings in the hash table only if the match length
1104 * is not greater than this length. This saves time but degrades compression.
1105 * max_insert_length is used only for compression levels <= 3.
1108 unsigned near good_match;
1110 /* Use a faster search when the previous match is longer than this */
1113 /* Values for max_lazy_match, good_match and max_chain_length, depending on
1114 * the desired pack level (0..9). The values given below have been tuned to
1115 * exclude worst case performance for pathological files. Better values may be
1116 * found for specific files.
1119 typedef struct config {
1120 ush good_length; /* reduce lazy search above this match length */
1121 ush max_lazy; /* do not perform lazy search above this match length */
1122 ush nice_length; /* quit search above this match length */
1127 # define nice_match MAX_MATCH
1129 int near nice_match; /* Stop searching when current match exceeds this */
1132 local config configuration_table =
1133 /* 9 */ { 32, 258, 258, 4096 };
1134 /* maximum compression */
1136 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
1137 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
1142 /* result of memcmp for equal strings */
1144 /* ===========================================================================
1145 * Prototypes for local functions.
1147 local void fill_window (void);
1149 int longest_match (IPos cur_match);
1152 void match_init (void); /* asm code initialization */
1156 local void check_match (IPos start, IPos match, int length);
1159 /* ===========================================================================
1160 * Update a hash value with the given input byte
1161 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
1162 * input characters, so that a running hash key can be computed from the
1163 * previous key instead of complete recalculation each time.
1165 #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
1167 /* ===========================================================================
1168 * Insert string s in the dictionary and set match_head to the previous head
1169 * of the hash chain (the most recent string with same hash key). Return
1170 * the previous length of the hash chain.
1171 * IN assertion: all calls to to INSERT_STRING are made with consecutive
1172 * input characters and the first MIN_MATCH bytes of s are valid
1173 * (except for the last MIN_MATCH-1 bytes of the input file).
1175 #define INSERT_STRING(s, match_head) \
1176 (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
1177 prev[(s) & WMASK] = match_head = head[ins_h], \
1180 /* ===========================================================================
1181 * Initialize the "longest match" routines for a new file
1184 ush *flags; /* general purpose bit flag */
1186 register unsigned j;
1188 /* Initialize the hash table. */
1189 #if defined(MAXSEG_64K) && HASH_BITS == 15
1190 for (j = 0; j < HASH_SIZE; j++)
1193 memzero((char *) head, HASH_SIZE * sizeof(*head));
1195 /* prev will be initialized on the fly */
1197 /* Set the default configuration parameters:
1199 max_lazy_match = configuration_table.max_lazy;
1200 good_match = configuration_table.good_length;
1202 nice_match = configuration_table.nice_length;
1204 max_chain_length = configuration_table.max_chain;
1206 /* ??? reduce max_chain_length for binary files */
1211 match_init(); /* initialize the asm code */
1214 lookahead = read_buf((char *) window,
1215 sizeof(int) <= 2 ? (unsigned) WSIZE : 2 * WSIZE);
1217 if (lookahead == 0 || lookahead == (unsigned) EOF) {
1218 eofile = 1, lookahead = 0;
1222 /* Make sure that we always have enough lookahead. This is important
1223 * if input comes from a device such as a tty.
1225 while (lookahead < MIN_LOOKAHEAD && !eofile)
1229 for (j = 0; j < MIN_MATCH - 1; j++)
1230 UPDATE_HASH(ins_h, window[j]);
1231 /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
1232 * not important since only literal bytes will be emitted.
1236 /* ===========================================================================
1237 * Set match_start to the longest match starting at the given string and
1238 * return its length. Matches shorter or equal to prev_length are discarded,
1239 * in which case the result is equal to prev_length and match_start is
1241 * IN assertions: cur_match is the head of the hash chain for the current
1242 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1245 /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
1246 * match.s. The code is functionally equivalent, so you can use the C version
1249 int longest_match(cur_match)
1250 IPos cur_match; /* current match */
1252 unsigned chain_length = max_chain_length; /* max hash chain length */
1253 register uch *scan = window + strstart; /* current string */
1254 register uch *match; /* matched string */
1255 register int len; /* length of current match */
1256 int best_len = prev_length; /* best match length so far */
1259 strstart > (IPos) MAX_DIST ? strstart - (IPos) MAX_DIST : NIL;
1260 /* Stop when cur_match becomes <= limit. To simplify the code,
1261 * we prevent matches with the string of window index 0.
1264 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1265 * It is easy to get rid of this optimization if necessary.
1267 #if HASH_BITS < 8 || MAX_MATCH != 258
1268 error:Code too clever
1271 /* Compare two bytes at a time. Note: this is not always beneficial.
1272 * Try with and without -DUNALIGNED_OK to check.
1274 register uch *strend = window + strstart + MAX_MATCH - 1;
1275 register ush scan_start = *(ush *) scan;
1276 register ush scan_end = *(ush *) (scan + best_len - 1);
1278 register uch *strend = window + strstart + MAX_MATCH;
1279 register uch scan_end1 = scan[best_len - 1];
1280 register uch scan_end = scan[best_len];
1283 /* Do not waste too much time if we already have a good match: */
1284 if (prev_length >= good_match) {
1287 Assert(strstart <= window_size - MIN_LOOKAHEAD,
1288 "insufficient lookahead");
1291 Assert(cur_match < strstart, "no future");
1292 match = window + cur_match;
1294 /* Skip to next match if the match length cannot increase
1295 * or if the match length is less than 2:
1297 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1298 /* This code assumes sizeof(unsigned short) == 2. Do not use
1299 * UNALIGNED_OK if your compiler uses a different size.
1301 if (*(ush *) (match + best_len - 1) != scan_end ||
1302 *(ush *) match != scan_start)
1305 /* It is not necessary to compare scan[2] and match[2] since they are
1306 * always equal when the other bytes match, given that the hash keys
1307 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1308 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1309 * lookahead only every 4th comparison; the 128th check will be made
1310 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1311 * necessary to put more guard bytes at the end of the window, or
1312 * to check more often for insufficient lookahead.
1316 } while (*(ush *) (scan += 2) == *(ush *) (match += 2) &&
1317 *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1318 *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1319 *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1321 /* The funny "do {}" generates better code on most compilers */
1323 /* Here, scan <= window+strstart+257 */
1324 Assert(scan <= window + (unsigned) (window_size - 1), "wild scan");
1325 if (*scan == *match)
1328 len = (MAX_MATCH - 1) - (int) (strend - scan);
1329 scan = strend - (MAX_MATCH - 1);
1331 #else /* UNALIGNED_OK */
1333 if (match[best_len] != scan_end ||
1334 match[best_len - 1] != scan_end1 ||
1335 *match != *scan || *++match != scan[1])
1338 /* The check at best_len-1 can be removed because it will be made
1339 * again later. (This heuristic is not always a win.)
1340 * It is not necessary to compare scan[2] and match[2] since they
1341 * are always equal when the other bytes match, given that
1342 * the hash keys are equal and that HASH_BITS >= 8.
1346 /* We check for insufficient lookahead only every 8th comparison;
1347 * the 256th check will be made at strstart+258.
1350 } while (*++scan == *++match && *++scan == *++match &&
1351 *++scan == *++match && *++scan == *++match &&
1352 *++scan == *++match && *++scan == *++match &&
1353 *++scan == *++match && *++scan == *++match &&
1356 len = MAX_MATCH - (int) (strend - scan);
1357 scan = strend - MAX_MATCH;
1359 #endif /* UNALIGNED_OK */
1361 if (len > best_len) {
1362 match_start = cur_match;
1364 if (len >= nice_match)
1367 scan_end = *(ush *) (scan + best_len - 1);
1369 scan_end1 = scan[best_len - 1];
1370 scan_end = scan[best_len];
1373 } while ((cur_match = prev[cur_match & WMASK]) > limit
1374 && --chain_length != 0);
1381 /* ===========================================================================
1382 * Check that the match at match_start is indeed a match.
1384 local void check_match(start, match, length)
1388 /* check that the match is indeed a match */
1389 if (memcmp((char *) window + match,
1390 (char *) window + start, length) != EQUAL) {
1392 " start %d, match %d, length %d\n", start, match, length);
1393 errorMsg("invalid match");
1396 fprintf(stderr, "\\[%d,%d]", start - match, length);
1398 putc(window[start++], stderr);
1399 } while (--length != 0);
1403 # define check_match(start, match, length)
1406 /* ===========================================================================
1407 * Fill the window when the lookahead becomes insufficient.
1408 * Updates strstart and lookahead, and sets eofile if end of input file.
1409 * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
1410 * OUT assertions: at least one byte has been read, or eofile is set;
1411 * file reads are performed for at least two bytes (required for the
1412 * translate_eol option).
1414 local void fill_window()
1416 register unsigned n, m;
1419 (unsigned) (window_size - (ulg) lookahead - (ulg) strstart);
1420 /* Amount of free space at the end of the window. */
1422 /* If the window is almost full and there is insufficient lookahead,
1423 * move the upper half to the lower one to make room in the upper half.
1425 if (more == (unsigned) EOF) {
1426 /* Very unlikely, but possible on 16 bit machine if strstart == 0
1427 * and lookahead == 1 (input done one byte at time)
1430 } else if (strstart >= WSIZE + MAX_DIST) {
1431 /* By the IN assertion, the window is not empty so we can't confuse
1432 * more == 0 with more == 64K on a 16 bit machine.
1434 Assert(window_size == (ulg) 2 * WSIZE, "no sliding with BIG_MEM");
1436 memcpy((char *) window, (char *) window + WSIZE, (unsigned) WSIZE);
1437 match_start -= WSIZE;
1438 strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
1440 block_start -= (long) WSIZE;
1442 for (n = 0; n < HASH_SIZE; n++) {
1444 head[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
1446 for (n = 0; n < WSIZE; n++) {
1448 prev[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
1449 /* If n is not on any hash chain, prev[n] is garbage but
1450 * its value will never be used.
1455 /* At this point, more >= 2 */
1457 n = read_buf((char *) window + strstart + lookahead, more);
1458 if (n == 0 || n == (unsigned) EOF) {
1466 /* ===========================================================================
1467 * Flush the current block, with given end-of-file flag.
1468 * IN assertion: strstart is set to the end of the current match.
1470 #define FLUSH_BLOCK(eof) \
1471 flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
1472 (char*)NULL, (long)strstart - block_start, (eof))
1474 /* ===========================================================================
1475 * Same as above, but achieves better compression. We use a lazy
1476 * evaluation for matches: a match is finally adopted only if there is
1477 * no better match at the next window position.
1481 IPos hash_head; /* head of hash chain */
1482 IPos prev_match; /* previous match */
1483 int flush; /* set if current block must be flushed */
1484 int match_available = 0; /* set if previous match exists */
1485 register unsigned match_length = MIN_MATCH - 1; /* length of best match */
1488 extern long isize; /* byte length of input file, for debug only */
1491 /* Process the input block. */
1492 while (lookahead != 0) {
1493 /* Insert the string window[strstart .. strstart+2] in the
1494 * dictionary, and set hash_head to the head of the hash chain:
1496 INSERT_STRING(strstart, hash_head);
1498 /* Find the longest match, discarding those <= prev_length.
1500 prev_length = match_length, prev_match = match_start;
1501 match_length = MIN_MATCH - 1;
1503 if (hash_head != NIL && prev_length < max_lazy_match &&
1504 strstart - hash_head <= MAX_DIST) {
1505 /* To simplify the code, we prevent matches with the string
1506 * of window index 0 (in particular we have to avoid a match
1507 * of the string with itself at the start of the input file).
1509 match_length = longest_match(hash_head);
1510 /* longest_match() sets match_start */
1511 if (match_length > lookahead)
1512 match_length = lookahead;
1514 /* Ignore a length 3 match if it is too distant: */
1515 if (match_length == MIN_MATCH
1516 && strstart - match_start > TOO_FAR) {
1517 /* If prev_match is also MIN_MATCH, match_start is garbage
1518 * but we will ignore the current match anyway.
1523 /* If there was a match at the previous step and the current
1524 * match is not better, output the previous match:
1526 if (prev_length >= MIN_MATCH && match_length <= prev_length) {
1528 check_match(strstart - 1, prev_match, prev_length);
1531 ct_tally(strstart - 1 - prev_match,
1532 prev_length - MIN_MATCH);
1534 /* Insert in hash table all strings up to the end of the match.
1535 * strstart-1 and strstart are already inserted.
1537 lookahead -= prev_length - 1;
1541 INSERT_STRING(strstart, hash_head);
1542 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1543 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
1544 * these bytes are garbage, but it does not matter since the
1545 * next lookahead bytes will always be emitted as literals.
1547 } while (--prev_length != 0);
1548 match_available = 0;
1549 match_length = MIN_MATCH - 1;
1552 FLUSH_BLOCK(0), block_start = strstart;
1554 } else if (match_available) {
1555 /* If there was no match at the previous position, output a
1556 * single literal. If there was a match but the current match
1557 * is longer, truncate the previous match to a single literal.
1559 Tracevv((stderr, "%c", window[strstart - 1]));
1560 if (ct_tally(0, window[strstart - 1])) {
1561 FLUSH_BLOCK(0), block_start = strstart;
1566 /* There is no previous match to compare with, wait for
1567 * the next step to decide.
1569 match_available = 1;
1573 Assert(strstart <= isize && lookahead <= isize, "a bit too far");
1575 /* Make sure that we always have enough lookahead, except
1576 * at the end of the input file. We need MAX_MATCH bytes
1577 * for the next match, plus MIN_MATCH bytes to insert the
1578 * string following the next match.
1580 while (lookahead < MIN_LOOKAHEAD && !eofile)
1583 if (match_available)
1584 ct_tally(0, window[strstart - 1]);
1586 return FLUSH_BLOCK(1); /* eof */
1589 /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
1590 * Copyright (C) 1992-1993 Jean-loup Gailly
1591 * The unzip code was written and put in the public domain by Mark Adler.
1592 * Portions of the lzw code are derived from the public domain 'compress'
1593 * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
1594 * Ken Turkowski, Dave Mack and Peter Jannesen.
1596 * See the license_msg below and the file COPYING for the software license.
1597 * See the file algorithm.doc for the compression algorithms and file formats.
1600 /* Compress files with zip algorithm and 'compress' interface.
1601 * See usage() and help() functions below for all options.
1603 * file.gz: compressed file with same mode, owner, and utimes
1604 * or stdout with -c option or if stdin used as input.
1605 * If the output file name had to be truncated, the original name is kept
1606 * in the compressed file.
1607 * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
1609 * Using gz on MSDOS would create too many file name conflicts. For
1610 * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for
1611 * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz.
1612 * I also considered 12345678.txt -> 12345txt.gz but this truncates the name
1613 * too heavily. There is no ideal solution given the MSDOS 8+3 limitation.
1615 * For the meaning of all compilation flags, see comments in Makefile.in.
1619 #include <sys/types.h>
1621 #include <sys/stat.h>
1627 # include <sys/time.h>
1636 #ifdef HAVE_UNISTD_H
1637 # include <unistd.h>
1640 #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
1641 # include <stdlib.h>
1647 # include <dirent.h>
1648 typedef struct dirent dir_type;
1650 # define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
1651 # define DIR_OPT "DIRENT"
1653 # define NLENGTH(dirent) ((dirent)->d_namlen)
1655 # include <sys/dir.h>
1656 typedef struct direct dir_type;
1658 # define DIR_OPT "SYSDIR"
1661 # include <sys/ndir.h>
1662 typedef struct direct dir_type;
1664 # define DIR_OPT "SYSNDIR"
1668 typedef struct direct dir_type;
1670 # define DIR_OPT "NDIR"
1673 # define DIR_OPT "NO_DIR"
1682 # define TIME_OPT "UTIME"
1684 # ifdef HAVE_SYS_UTIME_H
1685 # include <sys/utime.h>
1686 # define TIME_OPT "SYS_UTIME"
1693 # define TIME_OPT ""
1697 # define TIME_OPT "NO_UTIME"
1700 #if !defined(S_ISDIR) && defined(S_IFDIR)
1701 # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1703 #if !defined(S_ISREG) && defined(S_IFREG)
1704 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1707 typedef RETSIGTYPE(*sig_type) (int);
1710 # define O_BINARY 0 /* creation mode for open() */
1714 /* Pure BSD system? */
1715 # include <sys/file.h>
1717 # define O_CREAT FCREAT
1720 # define O_EXCL FEXCL
1725 # define S_IRUSR 0400
1728 # define S_IWUSR 0200
1730 #define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */
1732 #ifndef MAX_PATH_LEN
1733 # define MAX_PATH_LEN 1024 /* max pathname length */
1742 off_t lseek (int fd, off_t offset, int whence);
1745 /* Separator for file name parts (see shorten_name()) */
1746 #ifdef NO_MULTIPLE_DOTS
1747 # define PART_SEP "-"
1749 # define PART_SEP "."
1752 /* global buffers */
1754 DECLARE(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
1755 DECLARE(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
1756 DECLARE(ush, d_buf, DIST_BUFSIZE);
1757 DECLARE(uch, window, 2L * WSIZE);
1759 DECLARE(ush, tab_prefix, 1L << BITS);
1761 DECLARE(ush, tab_prefix0, 1L << (BITS - 1));
1762 DECLARE(ush, tab_prefix1, 1L << (BITS - 1));
1765 /* local variables */
1767 int ascii = 0; /* convert end-of-lines to local OS conventions */
1768 int decompress = 0; /* decompress (-d) */
1769 int no_name = -1; /* don't save or restore the original file name */
1770 int no_time = -1; /* don't save or restore the original file time */
1771 int foreground; /* set if program run in foreground */
1772 char *progname; /* program name */
1773 static int method = DEFLATED; /* compression method */
1774 static int exit_code = OK; /* program exit code */
1775 int save_orig_name; /* set if original name must be saved */
1776 int last_member; /* set for .zip and .Z files */
1777 int part_nb; /* number of parts in .gz file */
1778 long time_stamp; /* original time stamp (modification time) */
1779 long ifile_size; /* input file size, -1 for devices (debug only) */
1780 char *env; /* contents of GZIP env variable */
1781 char **args = NULL; /* argv pointer if GZIP env variable defined */
1782 char z_suffix[MAX_SUFFIX + 1]; /* default suffix (can be set with --suffix) */
1783 int z_len; /* strlen(z_suffix) */
1785 long bytes_in; /* number of input bytes */
1786 long bytes_out; /* number of output bytes */
1787 char ifname[MAX_PATH_LEN]; /* input file name */
1788 char ofname[MAX_PATH_LEN]; /* output file name */
1789 int remove_ofname = 0; /* remove output file on error */
1790 struct stat istat; /* status for input file */
1791 int ifd; /* input file descriptor */
1792 int ofd; /* output file descriptor */
1793 unsigned insize; /* valid bytes in inbuf */
1794 unsigned inptr; /* index of next byte to be processed in inbuf */
1795 unsigned outcnt; /* bytes in output buffer */
1797 /* local functions */
1799 #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
1801 /* ======================================================================== */
1802 // int main (argc, argv)
1805 int gzip_main(int argc, char **argv)
1810 struct stat statBuf;
1818 /* Parse any options */
1819 while (--argc > 0 && **(++argv) == '-') {
1820 if (*((*argv) + 1) == '\0') {
1824 while (*(++(*argv))) {
1835 foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
1837 (void) signal(SIGINT, (sig_type) abort_gzip);
1840 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
1841 (void) signal(SIGTERM, (sig_type) abort_gzip);
1845 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
1846 (void) signal(SIGHUP, (sig_type) abort_gzip);
1850 strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix) - 1);
1851 z_len = strlen(z_suffix);
1853 /* Allocate all global buffers (for DYN_ALLOC option) */
1854 ALLOC(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
1855 ALLOC(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
1856 ALLOC(ush, d_buf, DIST_BUFSIZE);
1857 ALLOC(uch, window, 2L * WSIZE);
1859 ALLOC(ush, tab_prefix, 1L << BITS);
1861 ALLOC(ush, tab_prefix0, 1L << (BITS - 1));
1862 ALLOC(ush, tab_prefix1, 1L << (BITS - 1));
1865 if (fromstdin == 1) {
1866 strcpy(ofname, "stdin");
1868 inFileNum = fileno(stdin);
1869 time_stamp = 0; /* time unknown by default */
1870 ifile_size = -1L; /* convention for unknown size */
1872 /* Open up the input file */
1875 strncpy(ifname, *argv, MAX_PATH_LEN);
1877 /* Open input fille */
1878 inFileNum = open(ifname, O_RDONLY);
1879 if (inFileNum < 0) {
1883 /* Get the time stamp on the input file. */
1884 result = stat(ifname, &statBuf);
1889 time_stamp = statBuf.st_ctime;
1890 ifile_size = statBuf.st_size;
1894 if (tostdout == 1) {
1895 /* And get to work */
1896 strcpy(ofname, "stdout");
1897 outFileNum = fileno(stdout);
1898 SET_BINARY_MODE(fileno(stdout));
1900 clear_bufs(); /* clear input and output buffers */
1903 /* Actually do the compression/decompression. */
1904 zip(inFileNum, outFileNum);
1908 /* And get to work */
1909 strncpy(ofname, ifname, MAX_PATH_LEN - 4);
1910 strcat(ofname, ".gz");
1913 /* Open output fille */
1914 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
1915 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
1917 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL);
1919 if (outFileNum < 0) {
1923 SET_BINARY_MODE(outFileNum);
1924 /* Set permissions on the file */
1925 fchmod(outFileNum, statBuf.st_mode);
1927 clear_bufs(); /* clear input and output buffers */
1930 /* Actually do the compression/decompression. */
1931 result = zip(inFileNum, outFileNum);
1934 /* Delete the original file */
1936 delFileName = ifname;
1938 delFileName = ofname;
1940 if (unlink(delFileName) < 0) {
1941 perror(delFileName);
1949 /* trees.c -- output deflated data using Huffman coding
1950 * Copyright (C) 1992-1993 Jean-loup Gailly
1951 * This is free software; you can redistribute it and/or modify it under the
1952 * terms of the GNU General Public License, see the file COPYING.
1958 * Encode various sets of source values using variable-length
1959 * binary code trees.
1963 * The PKZIP "deflation" process uses several Huffman trees. The more
1964 * common source values are represented by shorter bit sequences.
1966 * Each code tree is stored in the ZIP file in a compressed form
1967 * which is itself a Huffman encoding of the lengths of
1968 * all the code strings (in ascending order by source values).
1969 * The actual code strings are reconstructed from the lengths in
1970 * the UNZIP process, as described in the "application note"
1971 * (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
1976 * Data Compression: Techniques and Applications, pp. 53-55.
1977 * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
1980 * Data Compression: Methods and Theory, pp. 49-50.
1981 * Computer Science Press, 1988. ISBN 0-7167-8156-5.
1985 * Addison-Wesley, 1983. ISBN 0-201-06672-6.
1989 * void ct_init (ush *attr, int *methodp)
1990 * Allocate the match buffer, initialize the various tables and save
1991 * the location of the internal file attribute (ascii/binary) and
1992 * method (DEFLATE/STORE)
1994 * void ct_tally (int dist, int lc);
1995 * Save the match info and tally the frequency counts.
1997 * long flush_block (char *buf, ulg stored_len, int eof)
1998 * Determine the best encoding for the current block: dynamic trees,
1999 * static trees or store, and output the encoded block to the zip
2000 * file. Returns the total compressed length for the file so far.
2006 /* ===========================================================================
2011 /* All codes must not exceed MAX_BITS bits */
2013 #define MAX_BL_BITS 7
2014 /* Bit length codes must not exceed MAX_BL_BITS bits */
2016 #define LENGTH_CODES 29
2017 /* number of length codes, not counting the special END_BLOCK code */
2019 #define LITERALS 256
2020 /* number of literal bytes 0..255 */
2022 #define END_BLOCK 256
2023 /* end of block literal code */
2025 #define L_CODES (LITERALS+1+LENGTH_CODES)
2026 /* number of Literal or Length codes, including the END_BLOCK code */
2029 /* number of distance codes */
2032 /* number of codes used to transfer the bit lengths */
2035 local int near extra_lbits[LENGTH_CODES] /* extra bits for each length code */
2036 = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
2037 4, 4, 5, 5, 5, 5, 0 };
2039 local int near extra_dbits[D_CODES] /* extra bits for each distance code */
2040 = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,
2041 10, 10, 11, 11, 12, 12, 13, 13 };
2043 local int near extra_blbits[BL_CODES] /* extra bits for each bit length code */
2044 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 };
2046 #define STORED_BLOCK 0
2047 #define STATIC_TREES 1
2049 /* The three kinds of block type */
2053 # define LIT_BUFSIZE 0x2000
2056 # define LIT_BUFSIZE 0x4000
2058 # define LIT_BUFSIZE 0x8000
2062 #ifndef DIST_BUFSIZE
2063 # define DIST_BUFSIZE LIT_BUFSIZE
2065 /* Sizes of match buffers for literals/lengths and distances. There are
2066 * 4 reasons for limiting LIT_BUFSIZE to 64K:
2067 * - frequencies can be kept in 16 bit counters
2068 * - if compression is not successful for the first block, all input data is
2069 * still in the window so we can still emit a stored block even when input
2070 * comes from standard input. (This can also be done for all blocks if
2071 * LIT_BUFSIZE is not greater than 32K.)
2072 * - if compression is not successful for a file smaller than 64K, we can
2073 * even emit a stored file instead of a stored block (saving 5 bytes).
2074 * - creating new Huffman trees less frequently may not provide fast
2075 * adaptation to changes in the input data statistics. (Take for
2076 * example a binary file with poorly compressible code followed by
2077 * a highly compressible string table.) Smaller buffer sizes give
2078 * fast adaptation but have of course the overhead of transmitting trees
2080 * - I can't count above 4
2081 * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
2082 * memory at the expense of compression). Some optimizations would be possible
2083 * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
2085 #if LIT_BUFSIZE > INBUFSIZ
2086 error cannot overlay l_buf and inbuf
2089 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
2090 #define REPZ_3_10 17
2091 /* repeat a zero length 3-10 times (3 bits of repeat count) */
2092 #define REPZ_11_138 18
2093 /* repeat a zero length 11-138 times (7 bits of repeat count) *//* ===========================================================================
2095 *//* Data structure describing a single value and its code string. */ typedef struct ct_data {
2097 ush freq; /* frequency count */
2098 ush code; /* bit string */
2101 ush dad; /* father node in Huffman tree */
2102 ush len; /* length of bit string */
2106 #define Freq fc.freq
2107 #define Code fc.code
2111 #define HEAP_SIZE (2*L_CODES+1)
2112 /* maximum heap size */
2114 local ct_data near dyn_ltree[HEAP_SIZE]; /* literal and length tree */
2115 local ct_data near dyn_dtree[2 * D_CODES + 1]; /* distance tree */
2117 local ct_data near static_ltree[L_CODES + 2];
2119 /* The static literal tree. Since the bit lengths are imposed, there is no
2120 * need for the L_CODES extra codes used during heap construction. However
2121 * The codes 286 and 287 are needed to build a canonical tree (see ct_init
2125 local ct_data near static_dtree[D_CODES];
2127 /* The static distance tree. (Actually a trivial tree since all codes use
2131 local ct_data near bl_tree[2 * BL_CODES + 1];
2133 /* Huffman tree for the bit lengths */
2135 typedef struct tree_desc {
2136 ct_data near *dyn_tree; /* the dynamic tree */
2137 ct_data near *static_tree; /* corresponding static tree or NULL */
2138 int near *extra_bits; /* extra bits for each code or NULL */
2139 int extra_base; /* base index for extra_bits */
2140 int elems; /* max number of elements in the tree */
2141 int max_length; /* max bit length for the codes */
2142 int max_code; /* largest code with non zero frequency */
2145 local tree_desc near l_desc =
2146 { dyn_ltree, static_ltree, extra_lbits, LITERALS + 1, L_CODES,
2149 local tree_desc near d_desc =
2150 { dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0 };
2152 local tree_desc near bl_desc =
2153 { bl_tree, (ct_data near *) 0, extra_blbits, 0, BL_CODES, MAX_BL_BITS,
2157 local ush near bl_count[MAX_BITS + 1];
2159 /* number of codes at each bit length for an optimal tree */
2161 local uch near bl_order[BL_CODES]
2162 = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
2164 /* The lengths of the bit length codes are sent in order of decreasing
2165 * probability, to avoid transmitting the lengths for unused bit length codes.
2168 local int near heap[2 * L_CODES + 1]; /* heap used to build the Huffman trees */
2169 local int heap_len; /* number of elements in the heap */
2170 local int heap_max; /* element of largest frequency */
2172 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
2173 * The same heap array is used to build all trees.
2176 local uch near depth[2 * L_CODES + 1];
2178 /* Depth of each subtree used as tie breaker for trees of equal frequency */
2180 local uch length_code[MAX_MATCH - MIN_MATCH + 1];
2182 /* length code for each normalized match length (0 == MIN_MATCH) */
2184 local uch dist_code[512];
2186 /* distance codes. The first 256 values correspond to the distances
2187 * 3 .. 258, the last 256 values correspond to the top 8 bits of
2188 * the 15 bit distances.
2191 local int near base_length[LENGTH_CODES];
2193 /* First normalized length for each code (0 = MIN_MATCH) */
2195 local int near base_dist[D_CODES];
2197 /* First normalized distance for each code (0 = distance of 1) */
2200 /* DECLARE(uch, l_buf, LIT_BUFSIZE); buffer for literals or lengths */
2202 /* DECLARE(ush, d_buf, DIST_BUFSIZE); buffer for distances */
2204 local uch near flag_buf[(LIT_BUFSIZE / 8)];
2206 /* flag_buf is a bit array distinguishing literals from lengths in
2207 * l_buf, thus indicating the presence or absence of a distance.
2210 local unsigned last_lit; /* running index in l_buf */
2211 local unsigned last_dist; /* running index in d_buf */
2212 local unsigned last_flags; /* running index in flag_buf */
2213 local uch flags; /* current flags not yet saved in flag_buf */
2214 local uch flag_bit; /* current bit used in flags */
2216 /* bits are filled in flags starting at bit 0 (least significant).
2217 * Note: these flags are overkill in the current code since we don't
2218 * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
2221 local ulg opt_len; /* bit length of current block with optimal trees */
2222 local ulg static_len; /* bit length of current block with static trees */
2224 local ulg compressed_len; /* total bit length of compressed file */
2226 local ulg input_len; /* total byte length of input file */
2228 /* input_len is for debugging only since we can get it by other means. */
2230 ush *file_type; /* pointer to UNKNOWN, BINARY or ASCII */
2231 int *file_method; /* pointer to DEFLATE or STORE */
2234 extern ulg bits_sent; /* bit length of the compressed data */
2235 extern long isize; /* byte length of input file */
2238 extern long block_start; /* window offset of current block */
2239 extern unsigned near strstart; /* window offset of current string */
2241 /* ===========================================================================
2242 * Local (static) routines in this file.
2245 local void init_block (void);
2246 local void pqdownheap (ct_data near * tree, int k);
2247 local void gen_bitlen (tree_desc near * desc);
2248 local void gen_codes (ct_data near * tree, int max_code);
2249 local void build_tree (tree_desc near * desc);
2250 local void scan_tree (ct_data near * tree, int max_code);
2251 local void send_tree (ct_data near * tree, int max_code);
2252 local int build_bl_tree (void);
2253 local void send_all_trees (int lcodes, int dcodes, int blcodes);
2254 local void compress_block (ct_data near * ltree, ct_data near * dtree);
2255 local void set_file_type (void);
2259 # define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
2260 /* Send a code of the given tree. c and tree must not have side effects */
2263 # define send_code(c, tree) \
2264 { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \
2265 send_bits(tree[c].Code, tree[c].Len); }
2268 #define d_code(dist) \
2269 ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
2270 /* Mapping from a distance to a distance code. dist is the distance - 1 and
2271 * must not have side effects. dist_code[256] and dist_code[257] are never
2275 /* the arguments must not have side effects */
2277 /* ===========================================================================
2278 * Allocate the match buffer, initialize the various tables and save the
2279 * location of the internal file attribute (ascii/binary) and method
2282 void ct_init(attr, methodp)
2283 ush *attr; /* pointer to internal file attribute */
2284 int *methodp; /* pointer to compression method */
2286 int n; /* iterates over tree elements */
2287 int bits; /* bit counter */
2288 int length; /* length value */
2289 int code; /* code value */
2290 int dist; /* distance index */
2293 file_method = methodp;
2294 compressed_len = input_len = 0L;
2296 if (static_dtree[0].Len != 0)
2297 return; /* ct_init already called */
2299 /* Initialize the mapping length (0..255) -> length code (0..28) */
2301 for (code = 0; code < LENGTH_CODES - 1; code++) {
2302 base_length[code] = length;
2303 for (n = 0; n < (1 << extra_lbits[code]); n++) {
2304 length_code[length++] = (uch) code;
2307 Assert(length == 256, "ct_init: length != 256");
2308 /* Note that the length 255 (match length 258) can be represented
2309 * in two different ways: code 284 + 5 bits or code 285, so we
2310 * overwrite length_code[255] to use the best encoding:
2312 length_code[length - 1] = (uch) code;
2314 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
2316 for (code = 0; code < 16; code++) {
2317 base_dist[code] = dist;
2318 for (n = 0; n < (1 << extra_dbits[code]); n++) {
2319 dist_code[dist++] = (uch) code;
2322 Assert(dist == 256, "ct_init: dist != 256");
2323 dist >>= 7; /* from now on, all distances are divided by 128 */
2324 for (; code < D_CODES; code++) {
2325 base_dist[code] = dist << 7;
2326 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
2327 dist_code[256 + dist++] = (uch) code;
2330 Assert(dist == 256, "ct_init: 256+dist != 512");
2332 /* Construct the codes of the static literal tree */
2333 for (bits = 0; bits <= MAX_BITS; bits++)
2337 static_ltree[n++].Len = 8, bl_count[8]++;
2339 static_ltree[n++].Len = 9, bl_count[9]++;
2341 static_ltree[n++].Len = 7, bl_count[7]++;
2343 static_ltree[n++].Len = 8, bl_count[8]++;
2344 /* Codes 286 and 287 do not exist, but we must include them in the
2345 * tree construction to get a canonical Huffman tree (longest code
2348 gen_codes((ct_data near *) static_ltree, L_CODES + 1);
2350 /* The static distance tree is trivial: */
2351 for (n = 0; n < D_CODES; n++) {
2352 static_dtree[n].Len = 5;
2353 static_dtree[n].Code = bi_reverse(n, 5);
2356 /* Initialize the first block of the first file: */
2360 /* ===========================================================================
2361 * Initialize a new block.
2363 local void init_block()
2365 int n; /* iterates over tree elements */
2367 /* Initialize the trees. */
2368 for (n = 0; n < L_CODES; n++)
2369 dyn_ltree[n].Freq = 0;
2370 for (n = 0; n < D_CODES; n++)
2371 dyn_dtree[n].Freq = 0;
2372 for (n = 0; n < BL_CODES; n++)
2373 bl_tree[n].Freq = 0;
2375 dyn_ltree[END_BLOCK].Freq = 1;
2376 opt_len = static_len = 0L;
2377 last_lit = last_dist = last_flags = 0;
2383 /* Index within the heap array of least frequent node in the Huffman tree */
2386 /* ===========================================================================
2387 * Remove the smallest element from the heap and recreate the heap with
2388 * one less element. Updates heap and heap_len.
2390 #define pqremove(tree, top) \
2392 top = heap[SMALLEST]; \
2393 heap[SMALLEST] = heap[heap_len--]; \
2394 pqdownheap(tree, SMALLEST); \
2397 /* ===========================================================================
2398 * Compares to subtrees, using the tree depth as tie breaker when
2399 * the subtrees have equal frequency. This minimizes the worst case length.
2401 #define smaller(tree, n, m) \
2402 (tree[n].Freq < tree[m].Freq || \
2403 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
2405 /* ===========================================================================
2406 * Restore the heap property by moving down the tree starting at node k,
2407 * exchanging a node with the smallest of its two sons if necessary, stopping
2408 * when the heap property is re-established (each father smaller than its
2411 local void pqdownheap(tree, k)
2412 ct_data near *tree; /* the tree to restore */
2413 int k; /* node to move down */
2416 int j = k << 1; /* left son of k */
2418 while (j <= heap_len) {
2419 /* Set j to the smallest of the two sons: */
2420 if (j < heap_len && smaller(tree, heap[j + 1], heap[j]))
2423 /* Exit if v is smaller than both sons */
2424 if (smaller(tree, v, heap[j]))
2427 /* Exchange v with the smallest son */
2431 /* And continue down the tree, setting j to the left son of k */
2437 /* ===========================================================================
2438 * Compute the optimal bit lengths for a tree and update the total bit length
2439 * for the current block.
2440 * IN assertion: the fields freq and dad are set, heap[heap_max] and
2441 * above are the tree nodes sorted by increasing frequency.
2442 * OUT assertions: the field len is set to the optimal bit length, the
2443 * array bl_count contains the frequencies for each bit length.
2444 * The length opt_len is updated; static_len is also updated if stree is
2447 local void gen_bitlen(desc)
2448 tree_desc near *desc; /* the tree descriptor */
2450 ct_data near *tree = desc->dyn_tree;
2451 int near *extra = desc->extra_bits;
2452 int base = desc->extra_base;
2453 int max_code = desc->max_code;
2454 int max_length = desc->max_length;
2455 ct_data near *stree = desc->static_tree;
2456 int h; /* heap index */
2457 int n, m; /* iterate over the tree elements */
2458 int bits; /* bit length */
2459 int xbits; /* extra bits */
2460 ush f; /* frequency */
2461 int overflow = 0; /* number of elements with bit length too large */
2463 for (bits = 0; bits <= MAX_BITS; bits++)
2466 /* In a first pass, compute the optimal bit lengths (which may
2467 * overflow in the case of the bit length tree).
2469 tree[heap[heap_max]].Len = 0; /* root of the heap */
2471 for (h = heap_max + 1; h < HEAP_SIZE; h++) {
2473 bits = tree[tree[n].Dad].Len + 1;
2474 if (bits > max_length)
2475 bits = max_length, overflow++;
2476 tree[n].Len = (ush) bits;
2477 /* We overwrite tree[n].Dad which is no longer needed */
2480 continue; /* not a leaf node */
2485 xbits = extra[n - base];
2487 opt_len += (ulg) f *(bits + xbits);
2490 static_len += (ulg) f *(stree[n].Len + xbits);
2495 Trace((stderr, "\nbit length overflow\n"));
2496 /* This happens for example on obj2 and pic of the Calgary corpus */
2498 /* Find the first bit length which could increase: */
2500 bits = max_length - 1;
2501 while (bl_count[bits] == 0)
2503 bl_count[bits]--; /* move one leaf down the tree */
2504 bl_count[bits + 1] += 2; /* move one overflow item as its brother */
2505 bl_count[max_length]--;
2506 /* The brother of the overflow item also moves one step up,
2507 * but this does not affect bl_count[max_length]
2510 } while (overflow > 0);
2512 /* Now recompute all bit lengths, scanning in increasing frequency.
2513 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
2514 * lengths instead of fixing only the wrong ones. This idea is taken
2515 * from 'ar' written by Haruhiko Okumura.)
2517 for (bits = max_length; bits != 0; bits--) {
2523 if (tree[m].Len != (unsigned) bits) {
2525 (stderr, "code %d bits %d->%d\n", m, tree[m].Len,
2529 (long) tree[m].Len) * (long) tree[m].Freq;
2530 tree[m].Len = (ush) bits;
2537 /* ===========================================================================
2538 * Generate the codes for a given tree and bit counts (which need not be
2540 * IN assertion: the array bl_count contains the bit length statistics for
2541 * the given tree and the field len is set for all tree elements.
2542 * OUT assertion: the field code is set for all tree elements of non
2545 local void gen_codes(tree, max_code)
2546 ct_data near *tree; /* the tree to decorate */
2547 int max_code; /* largest code with non zero frequency */
2549 ush next_code[MAX_BITS + 1]; /* next code value for each bit length */
2550 ush code = 0; /* running code value */
2551 int bits; /* bit index */
2552 int n; /* code index */
2554 /* The distribution counts are first used to generate the code values
2555 * without bit reversal.
2557 for (bits = 1; bits <= MAX_BITS; bits++) {
2558 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
2560 /* Check that the bit counts in bl_count are consistent. The last code
2563 Assert(code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
2564 "inconsistent bit counts");
2565 Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
2567 for (n = 0; n <= max_code; n++) {
2568 int len = tree[n].Len;
2572 /* Now reverse the bits */
2573 tree[n].Code = bi_reverse(next_code[len]++, len);
2575 Tracec(tree != static_ltree,
2576 (stderr, "\nn %3d %c l %2d c %4x (%x) ", n,
2577 (isgraph(n) ? n : ' '), len, tree[n].Code,
2578 next_code[len] - 1));
2582 /* ===========================================================================
2583 * Construct one Huffman tree and assigns the code bit strings and lengths.
2584 * Update the total bit length for the current block.
2585 * IN assertion: the field freq is set for all tree elements.
2586 * OUT assertions: the fields len and code are set to the optimal bit length
2587 * and corresponding code. The length opt_len is updated; static_len is
2588 * also updated if stree is not null. The field max_code is set.
2590 local void build_tree(desc)
2591 tree_desc near *desc; /* the tree descriptor */
2593 ct_data near *tree = desc->dyn_tree;
2594 ct_data near *stree = desc->static_tree;
2595 int elems = desc->elems;
2596 int n, m; /* iterate over heap elements */
2597 int max_code = -1; /* largest code with non zero frequency */
2598 int node = elems; /* next internal node of the tree */
2600 /* Construct the initial heap, with least frequent element in
2601 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
2602 * heap[0] is not used.
2604 heap_len = 0, heap_max = HEAP_SIZE;
2606 for (n = 0; n < elems; n++) {
2607 if (tree[n].Freq != 0) {
2608 heap[++heap_len] = max_code = n;
2615 /* The pkzip format requires that at least one distance code exists,
2616 * and that at least one bit should be sent even if there is only one
2617 * possible code. So to avoid special checks later on we force at least
2618 * two codes of non zero frequency.
2620 while (heap_len < 2) {
2621 int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
2627 static_len -= stree[new].Len;
2628 /* new is 0 or 1 so it does not have extra bits */
2630 desc->max_code = max_code;
2632 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
2633 * establish sub-heaps of increasing lengths:
2635 for (n = heap_len / 2; n >= 1; n--)
2636 pqdownheap(tree, n);
2638 /* Construct the Huffman tree by repeatedly combining the least two
2642 pqremove(tree, n); /* n = node of least frequency */
2643 m = heap[SMALLEST]; /* m = node of next least frequency */
2645 heap[--heap_max] = n; /* keep the nodes sorted by frequency */
2646 heap[--heap_max] = m;
2648 /* Create a new node father of n and m */
2649 tree[node].Freq = tree[n].Freq + tree[m].Freq;
2650 depth[node] = (uch) (MAX(depth[n], depth[m]) + 1);
2651 tree[n].Dad = tree[m].Dad = (ush) node;
2653 if (tree == bl_tree) {
2654 fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)",
2655 node, tree[node].Freq, n, tree[n].Freq, m,
2659 /* and insert the new node in the heap */
2660 heap[SMALLEST] = node++;
2661 pqdownheap(tree, SMALLEST);
2663 } while (heap_len >= 2);
2665 heap[--heap_max] = heap[SMALLEST];
2667 /* At this point, the fields freq and dad are set. We can now
2668 * generate the bit lengths.
2670 gen_bitlen((tree_desc near *) desc);
2672 /* The field len is now set, we can generate the bit codes */
2673 gen_codes((ct_data near *) tree, max_code);
2676 /* ===========================================================================
2677 * Scan a literal or distance tree to determine the frequencies of the codes
2678 * in the bit length tree. Updates opt_len to take into account the repeat
2679 * counts. (The contribution of the bit length codes will be added later
2680 * during the construction of bl_tree.)
2682 local void scan_tree(tree, max_code)
2683 ct_data near *tree; /* the tree to be scanned */
2684 int max_code; /* and its largest code of non zero frequency */
2686 int n; /* iterates over all tree elements */
2687 int prevlen = -1; /* last emitted length */
2688 int curlen; /* length of current code */
2689 int nextlen = tree[0].Len; /* length of next code */
2690 int count = 0; /* repeat count of the current code */
2691 int max_count = 7; /* max repeat count */
2692 int min_count = 4; /* min repeat count */
2695 max_count = 138, min_count = 3;
2696 tree[max_code + 1].Len = (ush) 0xffff; /* guard */
2698 for (n = 0; n <= max_code; n++) {
2700 nextlen = tree[n + 1].Len;
2701 if (++count < max_count && curlen == nextlen) {
2703 } else if (count < min_count) {
2704 bl_tree[curlen].Freq += count;
2705 } else if (curlen != 0) {
2706 if (curlen != prevlen)
2707 bl_tree[curlen].Freq++;
2708 bl_tree[REP_3_6].Freq++;
2709 } else if (count <= 10) {
2710 bl_tree[REPZ_3_10].Freq++;
2712 bl_tree[REPZ_11_138].Freq++;
2717 max_count = 138, min_count = 3;
2718 } else if (curlen == nextlen) {
2719 max_count = 6, min_count = 3;
2721 max_count = 7, min_count = 4;
2726 /* ===========================================================================
2727 * Send a literal or distance tree in compressed form, using the codes in
2730 local void send_tree(tree, max_code)
2731 ct_data near *tree; /* the tree to be scanned */
2732 int max_code; /* and its largest code of non zero frequency */
2734 int n; /* iterates over all tree elements */
2735 int prevlen = -1; /* last emitted length */
2736 int curlen; /* length of current code */
2737 int nextlen = tree[0].Len; /* length of next code */
2738 int count = 0; /* repeat count of the current code */
2739 int max_count = 7; /* max repeat count */
2740 int min_count = 4; /* min repeat count */
2742 /* tree[max_code+1].Len = -1; *//* guard already set */
2744 max_count = 138, min_count = 3;
2746 for (n = 0; n <= max_code; n++) {
2748 nextlen = tree[n + 1].Len;
2749 if (++count < max_count && curlen == nextlen) {
2751 } else if (count < min_count) {
2753 send_code(curlen, bl_tree);
2754 } while (--count != 0);
2756 } else if (curlen != 0) {
2757 if (curlen != prevlen) {
2758 send_code(curlen, bl_tree);
2761 Assert(count >= 3 && count <= 6, " 3_6?");
2762 send_code(REP_3_6, bl_tree);
2763 send_bits(count - 3, 2);
2765 } else if (count <= 10) {
2766 send_code(REPZ_3_10, bl_tree);
2767 send_bits(count - 3, 3);
2770 send_code(REPZ_11_138, bl_tree);
2771 send_bits(count - 11, 7);
2776 max_count = 138, min_count = 3;
2777 } else if (curlen == nextlen) {
2778 max_count = 6, min_count = 3;
2780 max_count = 7, min_count = 4;
2785 /* ===========================================================================
2786 * Construct the Huffman tree for the bit lengths and return the index in
2787 * bl_order of the last bit length code to send.
2789 local int build_bl_tree()
2791 int max_blindex; /* index of last bit length code of non zero freq */
2793 /* Determine the bit length frequencies for literal and distance trees */
2794 scan_tree((ct_data near *) dyn_ltree, l_desc.max_code);
2795 scan_tree((ct_data near *) dyn_dtree, d_desc.max_code);
2797 /* Build the bit length tree: */
2798 build_tree((tree_desc near *) (&bl_desc));
2799 /* opt_len now includes the length of the tree representations, except
2800 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
2803 /* Determine the number of bit length codes to send. The pkzip format
2804 * requires that at least 4 bit length codes be sent. (appnote.txt says
2805 * 3 but the actual value used is 4.)
2807 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
2808 if (bl_tree[bl_order[max_blindex]].Len != 0)
2811 /* Update opt_len to include the bit length tree and counts */
2812 opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
2814 (stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len,
2820 /* ===========================================================================
2821 * Send the header for a block using dynamic Huffman trees: the counts, the
2822 * lengths of the bit length codes, the literal tree and the distance tree.
2823 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
2825 local void send_all_trees(lcodes, dcodes, blcodes)
2826 int lcodes, dcodes, blcodes; /* number of codes for each tree */
2828 int rank; /* index in bl_order */
2830 Assert(lcodes >= 257 && dcodes >= 1
2831 && blcodes >= 4, "not enough codes");
2832 Assert(lcodes <= L_CODES && dcodes <= D_CODES
2833 && blcodes <= BL_CODES, "too many codes");
2834 Tracev((stderr, "\nbl counts: "));
2835 send_bits(lcodes - 257, 5); /* not +255 as stated in appnote.txt */
2836 send_bits(dcodes - 1, 5);
2837 send_bits(blcodes - 4, 4); /* not -3 as stated in appnote.txt */
2838 for (rank = 0; rank < blcodes; rank++) {
2839 Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
2840 send_bits(bl_tree[bl_order[rank]].Len, 3);
2842 Tracev((stderr, "\nbl tree: sent %ld", bits_sent));
2844 send_tree((ct_data near *) dyn_ltree, lcodes - 1); /* send the literal tree */
2845 Tracev((stderr, "\nlit tree: sent %ld", bits_sent));
2847 send_tree((ct_data near *) dyn_dtree, dcodes - 1); /* send the distance tree */
2848 Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
2851 /* ===========================================================================
2852 * Determine the best encoding for the current block: dynamic trees, static
2853 * trees or store, and output the encoded block to the zip file. This function
2854 * returns the total compressed length for the file so far.
2856 ulg flush_block(buf, stored_len, eof)
2857 char *buf; /* input block, or NULL if too old */
2858 ulg stored_len; /* length of input block */
2859 int eof; /* true if this is the last block for a file */
2861 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
2862 int max_blindex; /* index of last bit length code of non zero freq */
2864 flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
2866 /* Check if the file is ascii or binary */
2867 if (*file_type == (ush) UNKNOWN)
2870 /* Construct the literal and distance trees */
2871 build_tree((tree_desc near *) (&l_desc));
2872 Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
2874 build_tree((tree_desc near *) (&d_desc));
2876 (stderr, "\ndist data: dyn %ld, stat %ld", opt_len,
2878 /* At this point, opt_len and static_len are the total bit lengths of
2879 * the compressed block data, excluding the tree representations.
2882 /* Build the bit length tree for the above two trees, and get the index
2883 * in bl_order of the last bit length code to send.
2885 max_blindex = build_bl_tree();
2887 /* Determine the best encoding. Compute first the block length in bytes */
2888 opt_lenb = (opt_len + 3 + 7) >> 3;
2889 static_lenb = (static_len + 3 + 7) >> 3;
2890 input_len += stored_len; /* for debugging only */
2894 "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
2895 opt_lenb, opt_len, static_lenb, static_len, stored_len,
2896 last_lit, last_dist));
2898 if (static_lenb <= opt_lenb)
2899 opt_lenb = static_lenb;
2901 /* If compression failed and this is the first and last block,
2902 * and if the zip file can be seeked (to rewrite the local header),
2903 * the whole file is transformed into a stored file:
2907 if (stored_len <= opt_lenb && eof && compressed_len == 0L
2910 /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
2911 if (buf == (char *) 0)
2912 errorMsg("block vanished");
2914 copy_block(buf, (unsigned) stored_len, 0); /* without header */
2915 compressed_len = stored_len << 3;
2916 *file_method = STORED;
2920 } else if (stored_len + 4 <= opt_lenb && buf != (char *) 0) {
2921 /* 4: two words for the lengths */
2923 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
2924 * Otherwise we can't have processed more than WSIZE input bytes since
2925 * the last block flush, because compression would have been
2926 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
2927 * transform a block into a stored block.
2929 send_bits((STORED_BLOCK << 1) + eof, 3); /* send block type */
2930 compressed_len = (compressed_len + 3 + 7) & ~7L;
2931 compressed_len += (stored_len + 4) << 3;
2933 copy_block(buf, (unsigned) stored_len, 1); /* with header */
2937 } else if (static_lenb == opt_lenb) {
2939 send_bits((STATIC_TREES << 1) + eof, 3);
2940 compress_block((ct_data near *) static_ltree,
2941 (ct_data near *) static_dtree);
2942 compressed_len += 3 + static_len;
2944 send_bits((DYN_TREES << 1) + eof, 3);
2945 send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1,
2947 compress_block((ct_data near *) dyn_ltree,
2948 (ct_data near *) dyn_dtree);
2949 compressed_len += 3 + opt_len;
2951 Assert(compressed_len == bits_sent, "bad compressed size");
2955 Assert(input_len == isize, "bad input size");
2957 compressed_len += 7; /* align on byte boundary */
2959 Tracev((stderr, "\ncomprlen %lu(%lu) ", compressed_len >> 3,
2960 compressed_len - 7 * eof));
2962 return compressed_len >> 3;
2965 /* ===========================================================================
2966 * Save the match info and tally the frequency counts. Return true if
2967 * the current block must be flushed.
2969 int ct_tally(dist, lc)
2970 int dist; /* distance of matched string */
2971 int lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
2973 l_buf[last_lit++] = (uch) lc;
2975 /* lc is the unmatched char */
2976 dyn_ltree[lc].Freq++;
2978 /* Here, lc is the match length - MIN_MATCH */
2979 dist--; /* dist = match distance - 1 */
2980 Assert((ush) dist < (ush) MAX_DIST &&
2981 (ush) lc <= (ush) (MAX_MATCH - MIN_MATCH) &&
2982 (ush) d_code(dist) < (ush) D_CODES, "ct_tally: bad match");
2984 dyn_ltree[length_code[lc] + LITERALS + 1].Freq++;
2985 dyn_dtree[d_code(dist)].Freq++;
2987 d_buf[last_dist++] = (ush) dist;
2992 /* Output the flags if they fill a byte: */
2993 if ((last_lit & 7) == 0) {
2994 flag_buf[last_flags++] = flags;
2995 flags = 0, flag_bit = 1;
2997 /* Try to guess if it is profitable to stop the current block here */
2998 if ((last_lit & 0xfff) == 0) {
2999 /* Compute an upper bound for the compressed length */
3000 ulg out_length = (ulg) last_lit * 8L;
3001 ulg in_length = (ulg) strstart - block_start;
3004 for (dcode = 0; dcode < D_CODES; dcode++) {
3006 (ulg) dyn_dtree[dcode].Freq * (5L + extra_dbits[dcode]);
3011 "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
3012 last_lit, last_dist, in_length, out_length,
3013 100L - out_length * 100L / in_length));
3014 if (last_dist < last_lit / 2 && out_length < in_length / 2)
3017 return (last_lit == LIT_BUFSIZE - 1 || last_dist == DIST_BUFSIZE);
3018 /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
3019 * on 16 bit machines and because stored blocks are restricted to
3024 /* ===========================================================================
3025 * Send the block data compressed using the given Huffman trees
3027 local void compress_block(ltree, dtree)
3028 ct_data near *ltree; /* literal tree */
3029 ct_data near *dtree; /* distance tree */
3031 unsigned dist; /* distance of matched string */
3032 int lc; /* match length or unmatched char (if dist == 0) */
3033 unsigned lx = 0; /* running index in l_buf */
3034 unsigned dx = 0; /* running index in d_buf */
3035 unsigned fx = 0; /* running index in flag_buf */
3036 uch flag = 0; /* current flags */
3037 unsigned code; /* the code to send */
3038 int extra; /* number of extra bits to send */
3043 flag = flag_buf[fx++];
3045 if ((flag & 1) == 0) {
3046 send_code(lc, ltree); /* send a literal byte */
3047 Tracecv(isgraph(lc), (stderr, " '%c' ", lc));
3049 /* Here, lc is the match length - MIN_MATCH */
3050 code = length_code[lc];
3051 send_code(code + LITERALS + 1, ltree); /* send the length code */
3052 extra = extra_lbits[code];
3054 lc -= base_length[code];
3055 send_bits(lc, extra); /* send the extra length bits */
3058 /* Here, dist is the match distance - 1 */
3059 code = d_code(dist);
3060 Assert(code < D_CODES, "bad d_code");
3062 send_code(code, dtree); /* send the distance code */
3063 extra = extra_dbits[code];
3065 dist -= base_dist[code];
3066 send_bits(dist, extra); /* send the extra distance bits */
3068 } /* literal or match pair ? */
3070 } while (lx < last_lit);
3072 send_code(END_BLOCK, ltree);
3075 /* ===========================================================================
3076 * Set the file type to ASCII or BINARY, using a crude approximation:
3077 * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
3078 * IN assertion: the fields freq of dyn_ltree are set and the total of all
3079 * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
3081 local void set_file_type()
3084 unsigned ascii_freq = 0;
3085 unsigned bin_freq = 0;
3088 bin_freq += dyn_ltree[n++].Freq;
3090 ascii_freq += dyn_ltree[n++].Freq;
3091 while (n < LITERALS)
3092 bin_freq += dyn_ltree[n++].Freq;
3093 *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
3094 if (*file_type == BINARY && translate_eol) {
3095 errorMsg("-l used on binary file");
3099 /* util.c -- utility functions for gzip support
3100 * Copyright (C) 1992-1993 Jean-loup Gailly
3101 * This is free software; you can redistribute it and/or modify it under the
3102 * terms of the GNU General Public License, see the file COPYING.
3107 #include <sys/types.h>
3109 #ifdef HAVE_UNISTD_H
3110 # include <unistd.h>
3116 #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
3117 # include <stdlib.h>
3122 /* ===========================================================================
3123 * Copy input to output unchanged: zcat == cat with --force.
3124 * IN assertion: insize bytes have already been read in inbuf.
3127 int in, out; /* input and output file descriptors */
3130 while (insize != 0 && (int) insize != EOF) {
3131 write_buf(out, (char *) inbuf, insize);
3132 bytes_out += insize;
3133 insize = read(in, (char *) inbuf, INBUFSIZ);
3135 if ((int) insize == EOF && errno != 0) {
3138 bytes_in = bytes_out;
3142 /* ========================================================================
3143 * Put string s in lower case, return s.
3150 for (t = s; *t; t++)
3155 #if defined(NO_STRING_H) && !defined(STDC_HEADERS)
3157 /* Provide missing strspn and strcspn functions. */
3159 int strspn (const char *s, const char *accept);
3160 int strcspn (const char *s, const char *reject);
3162 /* ========================================================================
3163 * Return the length of the maximum initial segment
3164 * of s which contains only characters in accept.
3166 int strspn(s, accept)
3170 register const char *p;
3171 register const char *a;
3172 register int count = 0;
3174 for (p = s; *p != '\0'; ++p) {
3175 for (a = accept; *a != '\0'; ++a) {
3186 /* ========================================================================
3187 * Return the length of the maximum inital segment of s
3188 * which contains no characters from reject.
3190 int strcspn(s, reject)
3194 register int count = 0;
3196 while (*s != '\0') {
3197 if (strchr(reject, *s++) != NULL)
3204 #endif /* NO_STRING_H */
3206 /* ========================================================================
3207 * Add an environment variable (if any) before argv, and update argc.
3208 * Return the expanded environment variable to be freed later, or NULL
3209 * if no options were added to argv.
3211 #define SEPARATOR " \t" /* separators in env variable */
3213 char *add_envopt(argcp, argvp, env)
3214 int *argcp; /* pointer to argc */
3215 char ***argvp; /* pointer to argv */
3216 char *env; /* name of environment variable */
3218 char *p; /* running pointer through env variable */
3219 char **oargv; /* runs through old argv array */
3220 char **nargv; /* runs through new argv array */
3221 int oargc = *argcp; /* old argc */
3222 int nargc = 0; /* number of arguments in env variable */
3224 env = (char *) getenv(env);
3228 p = (char *) xmalloc(strlen(env) + 1);
3229 env = strcpy(p, env); /* keep env variable intact */
3231 for (p = env; *p; nargc++) { /* move through env */
3232 p += strspn(p, SEPARATOR); /* skip leading separators */
3236 p += strcspn(p, SEPARATOR); /* find end of word */
3238 *p++ = '\0'; /* mark it */
3245 /* Allocate the new argv array, with an extra element just in case
3246 * the original arg list did not end with a NULL.
3248 nargv = (char **) calloc(*argcp + 1, sizeof(char *));
3251 errorMsg("out of memory");
3255 /* Copy the program name first */
3257 errorMsg("argc<=0");
3258 *(nargv++) = *(oargv++);
3260 /* Then copy the environment args */
3261 for (p = env; nargc > 0; nargc--) {
3262 p += strspn(p, SEPARATOR); /* skip separators */
3263 *(nargv++) = p; /* store start */
3264 while (*p++); /* skip over word */
3267 /* Finally copy the old args and add a NULL (usual convention) */
3269 *(nargv++) = *(oargv++);
3274 /* ========================================================================
3275 * Display compression ratio on the given stream on 6 characters.
3277 void display_ratio(num, den, file)
3282 long ratio; /* 1000 times the compression ratio */
3285 ratio = 0; /* no compression */
3286 } else if (den < 2147483L) { /* (2**31 -1)/1000 */
3287 ratio = 1000L * num / den;
3289 ratio = num / (den / 1000L);
3297 fprintf(file, "%2ld.%1ld%%", ratio / 10L, ratio % 10L);
3301 /* zip.c -- compress files to the gzip or pkzip format
3302 * Copyright (C) 1992-1993 Jean-loup Gailly
3303 * This is free software; you can redistribute it and/or modify it under the
3304 * terms of the GNU General Public License, see the file COPYING.
3308 #include <sys/types.h>
3310 #ifdef HAVE_UNISTD_H
3311 # include <unistd.h>
3317 local ulg crc; /* crc on uncompressed file data */
3318 long header_bytes; /* number of bytes in gzip header */
3320 /* ===========================================================================
3321 * Deflate in to out.
3322 * IN assertions: the input and output buffers are cleared.
3323 * The variables time_stamp and save_orig_name are initialized.
3326 int in, out; /* input and output file descriptors */
3328 uch flags = 0; /* general purpose bit flags */
3329 ush attr = 0; /* ascii/binary flag */
3330 ush deflate_flags = 0; /* pkzip -es, -en or -ex equivalent */
3336 /* Write the header to the gzip file. See algorithm.doc for the format */
3340 put_byte(GZIP_MAGIC[0]); /* magic header */
3341 put_byte(GZIP_MAGIC[1]);
3342 put_byte(DEFLATED); /* compression method */
3344 put_byte(flags); /* general flags */
3345 put_long(time_stamp);
3347 /* Write deflated file to zip file */
3351 ct_init(&attr, &method);
3352 lm_init(&deflate_flags);
3354 put_byte((uch) deflate_flags); /* extra flags */
3355 put_byte(OS_CODE); /* OS identifier */
3357 header_bytes = (long) outcnt;
3361 /* Write the crc and uncompressed size */
3364 header_bytes += 2 * sizeof(long);
3371 /* ===========================================================================
3372 * Read a new buffer from the current input file, perform end-of-line
3373 * translation, and update the crc and input file size.
3374 * IN assertion: size >= 2 (for end-of-line translation)
3376 int file_read(buf, size)
3382 Assert(insize == 0, "inbuf not empty");
3384 len = read(ifd, buf, size);
3385 if (len == (unsigned) (-1) || len == 0)
3388 crc = updcrc((uch *) buf, len);