blob: a9d34aeb19ba9401d41a658c4bfecbf6d2ea06f8 [file] [log] [blame]
Erik Andersene49d5ec2000-02-08 19:58:47 +00001/* vi: set sw=4 ts=4: */
Erik Andersen61677fe2000-04-13 01:18:56 +00002/*
3 * Gzip implementation for busybox
Eric Andersencc8ed391999-10-05 16:24:54 +00004 *
Erik Andersen61677fe2000-04-13 01:18:56 +00005 * Based on GNU gzip Copyright (C) 1992-1993 Jean-loup Gailly.
6 *
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."
11 *
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.
15 *
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.
20 *
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.
25 *
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
29 *
Eric Andersencc8ed391999-10-05 16:24:54 +000030 */
Eric Andersencc8ed391999-10-05 16:24:54 +000031
Erik Andersen61677fe2000-04-13 01:18:56 +000032#include "internal.h"
33
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.*/
37#define SMALL_MEM
38#define DYN_ALLOC
39
Eric Andersencc8ed391999-10-05 16:24:54 +000040
Eric Andersenc296b541999-11-11 01:36:55 +000041static const char gzip_usage[] =
Erik Andersene49d5ec2000-02-08 19:58:47 +000042 "gzip [OPTION]... FILE\n\n"
43 "Compress FILE with maximum compression.\n"
Erik Andersen5e1189e2000-04-15 16:34:54 +000044 "When FILE is '-', reads standard input. Implies -c.\n\n"
Erik Andersene49d5ec2000-02-08 19:58:47 +000045
46 "Options:\n"
47 "\t-c\tWrite output to standard output instead of FILE.gz\n";
Eric Andersenc296b541999-11-11 01:36:55 +000048
Eric Andersencc8ed391999-10-05 16:24:54 +000049
Eric Andersencc8ed391999-10-05 16:24:54 +000050/* I don't like nested includes, but the string and io functions are used
51 * too often
52 */
53#include <stdio.h>
Erik Andersen61677fe2000-04-13 01:18:56 +000054#include <string.h>
55#define memzero(s, n) memset ((void *)(s), 0, (n))
Eric Andersencc8ed391999-10-05 16:24:54 +000056
57#ifndef RETSIGTYPE
58# define RETSIGTYPE void
59#endif
60
61#define local static
62
Erik Andersene49d5ec2000-02-08 19:58:47 +000063typedef unsigned char uch;
Eric Andersencc8ed391999-10-05 16:24:54 +000064typedef unsigned short ush;
Erik Andersene49d5ec2000-02-08 19:58:47 +000065typedef unsigned long ulg;
Eric Andersencc8ed391999-10-05 16:24:54 +000066
67/* Return codes from gzip */
68#define OK 0
69#define ERROR 1
70#define WARNING 2
71
72/* Compression methods (see algorithm.doc) */
73#define STORED 0
74#define COMPRESSED 1
75#define PACKED 2
76#define LZHED 3
77/* methods 4 to 7 reserved */
78#define DEFLATED 8
79#define MAX_METHODS 9
Erik Andersene49d5ec2000-02-08 19:58:47 +000080extern int method; /* compression method */
Eric Andersencc8ed391999-10-05 16:24:54 +000081
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.
91 */
92
93#ifndef INBUFSIZ
94# ifdef SMALL_MEM
Erik Andersene49d5ec2000-02-08 19:58:47 +000095# define INBUFSIZ 0x2000 /* input buffer size */
Eric Andersencc8ed391999-10-05 16:24:54 +000096# else
Erik Andersene49d5ec2000-02-08 19:58:47 +000097# define INBUFSIZ 0x8000 /* input buffer size */
Eric Andersencc8ed391999-10-05 16:24:54 +000098# endif
99#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000100#define INBUF_EXTRA 64 /* required by unlzw() */
Eric Andersencc8ed391999-10-05 16:24:54 +0000101
102#ifndef OUTBUFSIZ
103# ifdef SMALL_MEM
Erik Andersene49d5ec2000-02-08 19:58:47 +0000104# define OUTBUFSIZ 8192 /* output buffer size */
Eric Andersencc8ed391999-10-05 16:24:54 +0000105# else
Erik Andersene49d5ec2000-02-08 19:58:47 +0000106# define OUTBUFSIZ 16384 /* output buffer size */
Eric Andersencc8ed391999-10-05 16:24:54 +0000107# endif
108#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000109#define OUTBUF_EXTRA 2048 /* required by unlzw() */
Eric Andersencc8ed391999-10-05 16:24:54 +0000110
111#ifndef DIST_BUFSIZE
112# ifdef SMALL_MEM
Erik Andersene49d5ec2000-02-08 19:58:47 +0000113# define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
Eric Andersencc8ed391999-10-05 16:24:54 +0000114# else
Erik Andersene49d5ec2000-02-08 19:58:47 +0000115# define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
Eric Andersencc8ed391999-10-05 16:24:54 +0000116# endif
117#endif
118
119#ifdef DYN_ALLOC
Erik Andersen61677fe2000-04-13 01:18:56 +0000120# define EXTERN(type, array) extern type * array
121# define DECLARE(type, array, size) type * array
Eric Andersencc8ed391999-10-05 16:24:54 +0000122# define ALLOC(type, array, size) { \
Erik Andersen61677fe2000-04-13 01:18:56 +0000123 array = (type*)calloc((size_t)(((size)+1L)/2), 2*sizeof(type)); \
Erik Andersen9ffdaa62000-02-11 21:55:04 +0000124 if (array == NULL) errorMsg("insufficient memory"); \
Eric Andersencc8ed391999-10-05 16:24:54 +0000125 }
Erik Andersen61677fe2000-04-13 01:18:56 +0000126# define FREE(array) {if (array != NULL) free(array), array=NULL;}
Eric Andersencc8ed391999-10-05 16:24:54 +0000127#else
128# define EXTERN(type, array) extern type array[]
129# define DECLARE(type, array, size) type array[size]
130# define ALLOC(type, array, size)
131# define FREE(array)
132#endif
133
Erik Andersene49d5ec2000-02-08 19:58:47 +0000134EXTERN(uch, inbuf); /* input buffer */
135EXTERN(uch, outbuf); /* output buffer */
136EXTERN(ush, d_buf); /* buffer for distances, see trees.c */
137EXTERN(uch, window); /* Sliding window and suffix table (unlzw) */
Eric Andersencc8ed391999-10-05 16:24:54 +0000138#define tab_suffix window
139#ifndef MAXSEG_64K
Erik Andersene49d5ec2000-02-08 19:58:47 +0000140# define tab_prefix prev /* hash link (see deflate.c) */
141# define head (prev+WSIZE) /* hash head (see deflate.c) */
142EXTERN(ush, tab_prefix); /* prefix code (see unlzw.c) */
Eric Andersencc8ed391999-10-05 16:24:54 +0000143#else
144# define tab_prefix0 prev
145# define head tab_prefix1
Erik Andersene49d5ec2000-02-08 19:58:47 +0000146EXTERN(ush, tab_prefix0); /* prefix for even codes */
147EXTERN(ush, tab_prefix1); /* prefix for odd codes */
Eric Andersencc8ed391999-10-05 16:24:54 +0000148#endif
149
Erik Andersene49d5ec2000-02-08 19:58:47 +0000150extern unsigned insize; /* valid bytes in inbuf */
151extern unsigned inptr; /* index of next byte to be processed in inbuf */
152extern unsigned outcnt; /* bytes in output buffer */
Eric Andersencc8ed391999-10-05 16:24:54 +0000153
Erik Andersene49d5ec2000-02-08 19:58:47 +0000154extern long bytes_in; /* number of input bytes */
155extern long bytes_out; /* number of output bytes */
156extern long header_bytes; /* number of bytes in gzip header */
Eric Andersencc8ed391999-10-05 16:24:54 +0000157
158#define isize bytes_in
159/* for compatibility with old zip sources (to be cleaned) */
160
Erik Andersene49d5ec2000-02-08 19:58:47 +0000161extern int ifd; /* input file descriptor */
162extern int ofd; /* output file descriptor */
163extern char ifname[]; /* input file name or "stdin" */
164extern char ofname[]; /* output file name or "stdout" */
165extern char *progname; /* program name */
Eric Andersencc8ed391999-10-05 16:24:54 +0000166
Erik Andersene49d5ec2000-02-08 19:58:47 +0000167extern long time_stamp; /* original time stamp (modification time) */
168extern long ifile_size; /* input file size, -1 for devices (debug only) */
Eric Andersencc8ed391999-10-05 16:24:54 +0000169
Erik Andersene49d5ec2000-02-08 19:58:47 +0000170typedef int file_t; /* Do not use stdio */
171
172#define NO_FILE (-1) /* in memory compression */
Eric Andersencc8ed391999-10-05 16:24:54 +0000173
174
Erik Andersene49d5ec2000-02-08 19:58:47 +0000175#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 */
Eric Andersencc8ed391999-10-05 16:24:54 +0000180
181/* gzip flag byte */
Erik Andersene49d5ec2000-02-08 19:58:47 +0000182#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 */
Eric Andersencc8ed391999-10-05 16:24:54 +0000189
190/* internal file attribute */
191#define UNKNOWN 0xffff
192#define BINARY 0
193#define ASCII 1
194
195#ifndef WSIZE
Erik Andersene49d5ec2000-02-08 19:58:47 +0000196# define WSIZE 0x8000 /* window size--must be a power of two, and */
197#endif /* at least 32K for zip's deflate method */
Eric Andersencc8ed391999-10-05 16:24:54 +0000198
199#define MIN_MATCH 3
200#define MAX_MATCH 258
201/* The minimum and maximum match lengths */
202
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.
206 */
207
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.
211 */
212
Erik Andersene49d5ec2000-02-08 19:58:47 +0000213extern int decrypt; /* flag to turn on decryption */
214extern int exit_code; /* program exit code */
215extern int verbose; /* be verbose (-v) */
216extern int quiet; /* be quiet (-q) */
217extern int test; /* check .z file integrity */
218extern int save_orig_name; /* set if original name must be saved */
Eric Andersencc8ed391999-10-05 16:24:54 +0000219
220#define get_byte() (inptr < insize ? inbuf[inptr++] : fill_inbuf(0))
221#define try_byte() (inptr < insize ? inbuf[inptr++] : fill_inbuf(1))
222
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).
227 */
228#define put_byte(c) {outbuf[outcnt++]=(uch)(c); if (outcnt==OUTBUFSIZ)\
229 flush_outbuf();}
230#define put_ubyte(c) {window[outcnt++]=(uch)(c); if (outcnt==WSIZE)\
231 flush_window();}
232
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); \
238 } else { \
239 put_byte((uch)((w) & 0xff)); \
240 put_byte((uch)((ush)(w) >> 8)); \
241 } \
242}
243
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); \
248}
249
Erik Andersene49d5ec2000-02-08 19:58:47 +0000250#define seekable() 0 /* force sequential output */
251#define translate_eol 0 /* no option -a yet */
Eric Andersencc8ed391999-10-05 16:24:54 +0000252
Erik Andersene49d5ec2000-02-08 19:58:47 +0000253#define tolow(c) (isupper(c) ? (c)-'A'+'a' : (c)) /* force to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000254
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))
258
259/* Diagnostic functions */
260#ifdef DEBUG
Erik Andersen9ffdaa62000-02-11 21:55:04 +0000261# define Assert(cond,msg) {if(!(cond)) errorMsg(msg);}
Eric Andersencc8ed391999-10-05 16:24:54 +0000262# 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 ;}
267#else
268# define Assert(cond,msg)
269# define Trace(x)
270# define Tracev(x)
271# define Tracevv(x)
272# define Tracec(c,x)
273# define Tracecv(c,x)
274#endif
275
276#define WARN(msg) {if (!quiet) fprintf msg ; \
277 if (exit_code == OK) exit_code = WARNING;}
278
Erik Andersen3fe39dc2000-01-25 18:13:53 +0000279#define do_exit(c) exit(c)
280
Eric Andersencc8ed391999-10-05 16:24:54 +0000281
282 /* in zip.c: */
Erik Andersen61677fe2000-04-13 01:18:56 +0000283extern int zip (int in, int out);
284extern int file_read (char *buf, unsigned size);
Eric Andersencc8ed391999-10-05 16:24:54 +0000285
286 /* in unzip.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000287extern int unzip (int in, int out);
288extern int check_zipfile (int in);
Eric Andersencc8ed391999-10-05 16:24:54 +0000289
290 /* in unpack.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000291extern int unpack (int in, int out);
Eric Andersencc8ed391999-10-05 16:24:54 +0000292
293 /* in unlzh.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000294extern int unlzh (int in, int out);
Eric Andersencc8ed391999-10-05 16:24:54 +0000295
296 /* in gzip.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000297RETSIGTYPE abort_gzip (void);
Eric Andersencc8ed391999-10-05 16:24:54 +0000298
Erik Andersene49d5ec2000-02-08 19:58:47 +0000299 /* in deflate.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000300void lm_init (ush * flags);
301ulg deflate (void);
Eric Andersencc8ed391999-10-05 16:24:54 +0000302
Erik Andersene49d5ec2000-02-08 19:58:47 +0000303 /* in trees.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000304void ct_init (ush * attr, int *method);
305int ct_tally (int dist, int lc);
306ulg flush_block (char *buf, ulg stored_len, int eof);
Eric Andersencc8ed391999-10-05 16:24:54 +0000307
Erik Andersene49d5ec2000-02-08 19:58:47 +0000308 /* in bits.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000309void bi_init (file_t zipfile);
310void send_bits (int value, int length);
311unsigned bi_reverse (unsigned value, int length);
312void bi_windup (void);
313void copy_block (char *buf, unsigned len, int header);
314extern int (*read_buf) (char *buf, unsigned size);
Eric Andersencc8ed391999-10-05 16:24:54 +0000315
316 /* in util.c: */
Erik Andersen61677fe2000-04-13 01:18:56 +0000317extern int copy (int in, int out);
318extern ulg updcrc (uch * s, unsigned n);
319extern void clear_bufs (void);
320extern int fill_inbuf (int eof_ok);
321extern void flush_outbuf (void);
322extern void flush_window (void);
323extern void write_buf (int fd, void * buf, unsigned cnt);
324extern char *strlwr (char *s);
325extern char *add_envopt (int *argcp, char ***argvp, char *env);
326extern void read_error (void);
327extern void write_error (void);
328extern void display_ratio (long num, long den, FILE * file);
Eric Andersencc8ed391999-10-05 16:24:54 +0000329
330 /* in inflate.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000331extern int inflate (void);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000332
Eric Andersencc8ed391999-10-05 16:24:54 +0000333/* 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.
337 */
338
339#if !defined(OF) && defined(lint)
340# include "gzip.h"
341#endif
342
343#ifndef BITS
344# define BITS 16
345#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000346#define INIT_BITS 9 /* Initial number of bits per code */
Eric Andersencc8ed391999-10-05 16:24:54 +0000347
Erik Andersene49d5ec2000-02-08 19:58:47 +0000348#define BIT_MASK 0x1f /* Mask for 'number of compression bits' */
Eric Andersencc8ed391999-10-05 16:24:54 +0000349/* 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".
356 */
357
358#define BLOCK_MODE 0x80
359/* Block compression: if table is full and compression rate is dropping,
360 * clear the dictionary.
361 */
362
Erik Andersene49d5ec2000-02-08 19:58:47 +0000363#define LZW_RESERVED 0x60 /* reserved bits */
Eric Andersencc8ed391999-10-05 16:24:54 +0000364
Erik Andersene49d5ec2000-02-08 19:58:47 +0000365#define CLEAR 256 /* flush the dictionary */
366#define FIRST (CLEAR+1) /* first free entry */
Eric Andersencc8ed391999-10-05 16:24:54 +0000367
Erik Andersene49d5ec2000-02-08 19:58:47 +0000368extern int maxbits; /* max bits per code for LZW */
369extern int block_mode; /* block compress mode -C compatible with 2.0 */
Eric Andersencc8ed391999-10-05 16:24:54 +0000370
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.
375 */
376
377#define VERSION "1.2.4"
378#define PATCHLEVEL 0
379#define REVDATE "18 Aug 93"
380
381/* This version does not support compression into old compress format: */
382#ifdef LZW
383# undef LZW
384#endif
385
Eric Andersencc8ed391999-10-05 16:24:54 +0000386/* 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.
390 */
391
392/* The target dependent definitions should be defined here only.
393 * The target dependent functions should be defined in tailor.c.
394 */
395
Eric Andersencc8ed391999-10-05 16:24:54 +0000396
397#if defined(__MSDOS__) && !defined(MSDOS)
398# define MSDOS
399#endif
400
401#if defined(__OS2__) && !defined(OS2)
402# define OS2
403#endif
404
Erik Andersene49d5ec2000-02-08 19:58:47 +0000405#if defined(OS2) && defined(MSDOS) /* MS C under OS/2 */
Eric Andersencc8ed391999-10-05 16:24:54 +0000406# undef MSDOS
407#endif
408
409#ifdef MSDOS
410# ifdef __GNUC__
Erik Andersene49d5ec2000-02-08 19:58:47 +0000411 /* DJGPP version 1.09+ on MS-DOS.
412 * The DJGPP 1.09 stat() function must be upgraded before gzip will
413 * fully work.
414 * No need for DIRENT, since <unistd.h> defines POSIX_SOURCE which
415 * implies DIRENT.
416 */
Eric Andersencc8ed391999-10-05 16:24:54 +0000417# define near
418# else
419# define MAXSEG_64K
420# ifdef __TURBOC__
421# define NO_OFF_T
422# ifdef __BORLANDC__
423# define DIRENT
424# else
425# define NO_UTIME
426# endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000427# else /* MSC */
Eric Andersencc8ed391999-10-05 16:24:54 +0000428# define HAVE_SYS_UTIME_H
429# define NO_UTIME_H
430# endif
431# endif
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"
438# define NO_CHOWN
439# define PROTO
440# define STDC_HEADERS
441# define NO_SIZE_CHECK
Erik Andersene49d5ec2000-02-08 19:58:47 +0000442# define casemap(c) tolow(c) /* Force file names to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000443# include <io.h>
444# define OS_CODE 0x00
445# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
446# if !defined(NO_ASM) && !defined(ASMV)
447# define ASMV
448# endif
449#else
450# define near
451#endif
452
453#ifdef OS2
454# define PATH_SEP2 '\\'
455# define PATH_SEP3 ':'
456# define MAX_PATH_LEN 260
457# ifdef OS2FAT
458# define NO_MULTIPLE_DOTS
459# define MAX_EXT_CHARS 3
460# define Z_SUFFIX "z"
461# define casemap(c) tolow(c)
462# endif
463# define NO_CHOWN
464# define PROTO
465# define STDC_HEADERS
466# include <io.h>
467# define OS_CODE 0x06
468# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
469# ifdef _MSC_VER
470# define HAVE_SYS_UTIME_H
471# define NO_UTIME_H
472# define MAXSEG_64K
473# undef near
474# define near _near
475# endif
476# ifdef __EMX__
477# define HAVE_SYS_UTIME_H
478# define NO_UTIME_H
479# define DIRENT
480# define EXPAND(argc,argv) \
481 {_response(&argc, &argv); _wildcard(&argc, &argv);}
482# endif
483# ifdef __BORLANDC__
484# define DIRENT
485# endif
486# ifdef __ZTC__
487# define NO_DIR
488# define NO_UTIME_H
489# include <dos.h>
490# define EXPAND(argc,argv) \
491 {response_expand(&argc, &argv);}
492# endif
493#endif
494
Erik Andersene49d5ec2000-02-08 19:58:47 +0000495#ifdef WIN32 /* Windows NT */
Eric Andersencc8ed391999-10-05 16:24:54 +0000496# define HAVE_SYS_UTIME_H
497# define NO_UTIME_H
498# define PATH_SEP2 '\\'
499# define PATH_SEP3 ':'
500# define MAX_PATH_LEN 260
501# define NO_CHOWN
502# define PROTO
503# define STDC_HEADERS
504# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
505# include <io.h>
506# include <malloc.h>
507# ifdef NTFAT
508# define NO_MULTIPLE_DOTS
509# define MAX_EXT_CHARS 3
510# define Z_SUFFIX "z"
Erik Andersene49d5ec2000-02-08 19:58:47 +0000511# define casemap(c) tolow(c) /* Force file names to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000512# endif
513# define OS_CODE 0x0b
514#endif
515
516#ifdef MSDOS
517# ifdef __TURBOC__
518# include <alloc.h>
519# define DYN_ALLOC
Erik Andersene49d5ec2000-02-08 19:58:47 +0000520 /* Turbo C 2.0 does not accept static allocations of large arrays */
521void *fcalloc(unsigned items, unsigned size);
522void fcfree(void *ptr);
523# else /* MSC */
Eric Andersencc8ed391999-10-05 16:24:54 +0000524# include <malloc.h>
525# define fcalloc(nitems,itemsize) halloc((long)(nitems),(itemsize))
526# define fcfree(ptr) hfree(ptr)
527# endif
528#else
529# ifdef MAXSEG_64K
530# define fcalloc(items,size) calloc((items),(size))
531# else
532# define fcalloc(items,size) malloc((size_t)(items)*(size_t)(size))
533# endif
534# define fcfree(ptr) free(ptr)
535#endif
536
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"
543# define RECORD_IO 1
544# define casemap(c) tolow(c)
545# define OS_CODE 0x02
546# define OPTIONS_VAR "GZIP_OPT"
547# define STDC_HEADERS
548# define NO_UTIME
549# define EXPAND(argc,argv) vms_expand_args(&argc,&argv);
550# include <file.h>
551# define unlink delete
552# ifdef VAXC
553# define NO_FCNTL_H
554# include <unixio.h>
555# endif
556#endif
557
558#ifdef AMIGA
559# define PATH_SEP2 ':'
560# define STDC_HEADERS
561# define OS_CODE 0x01
562# define ASMV
563# ifdef __GNUC__
564# define DIRENT
565# define HAVE_UNISTD_H
Erik Andersene49d5ec2000-02-08 19:58:47 +0000566# else /* SASC */
Eric Andersencc8ed391999-10-05 16:24:54 +0000567# define NO_STDIN_FSTAT
568# define SYSDIR
569# define NO_SYMLINK
570# define NO_CHOWN
571# define NO_FCNTL_H
Erik Andersene49d5ec2000-02-08 19:58:47 +0000572# include <fcntl.h> /* for read() and write() */
Eric Andersencc8ed391999-10-05 16:24:54 +0000573# define direct dirent
Erik Andersene49d5ec2000-02-08 19:58:47 +0000574extern void _expand_args(int *argc, char ***argv);
575
Eric Andersencc8ed391999-10-05 16:24:54 +0000576# define EXPAND(argc,argv) _expand_args(&argc,&argv);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000577# undef O_BINARY /* disable useless --ascii option */
Eric Andersencc8ed391999-10-05 16:24:54 +0000578# endif
579#endif
580
581#if defined(ATARI) || defined(atarist)
582# ifndef STDC_HEADERS
583# define STDC_HEADERS
584# define HAVE_UNISTD_H
585# define DIRENT
586# endif
587# define ASMV
588# define OS_CODE 0x05
589# ifdef TOSFS
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"
596# define NO_CHOWN
Erik Andersene49d5ec2000-02-08 19:58:47 +0000597# define casemap(c) tolow(c) /* Force file names to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000598# define NO_SYMLINK
599# endif
600#endif
601
602#ifdef MACOS
603# define PATH_SEP ':'
604# define DYN_ALLOC
605# define PROTO
606# define NO_STDIN_FSTAT
607# define NO_CHOWN
608# define NO_UTIME
609# define chmod(file, mode) (0)
610# define OPEN(name, flags, mode) open(name, flags)
611# define OS_CODE 0x07
612# ifdef MPW
613# define isatty(fd) ((fd) <= 2)
614# endif
615#endif
616
Erik Andersene49d5ec2000-02-08 19:58:47 +0000617#ifdef __50SERIES /* Prime/PRIMOS */
Eric Andersencc8ed391999-10-05 16:24:54 +0000618# define PATH_SEP '>'
619# define STDC_HEADERS
620# define NO_MEMORY_H
621# define NO_UTIME_H
622# define NO_UTIME
Erik Andersene49d5ec2000-02-08 19:58:47 +0000623# define NO_CHOWN
624# define NO_STDIN_FSTAT
625# define NO_SIZE_CHECK
Eric Andersencc8ed391999-10-05 16:24:54 +0000626# define NO_SYMLINK
627# define RECORD_IO 1
Erik Andersene49d5ec2000-02-08 19:58:47 +0000628# define casemap(c) tolow(c) /* Force file names to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000629# define put_char(c) put_byte((c) & 0x7F)
630# define get_char(c) ascii2pascii(get_byte())
Erik Andersene49d5ec2000-02-08 19:58:47 +0000631# define OS_CODE 0x0F /* temporary, subject to change */
Eric Andersencc8ed391999-10-05 16:24:54 +0000632# ifdef SIGTERM
Erik Andersene49d5ec2000-02-08 19:58:47 +0000633# undef SIGTERM /* We don't want a signal handler for SIGTERM */
Eric Andersencc8ed391999-10-05 16:24:54 +0000634# endif
635#endif
636
Erik Andersene49d5ec2000-02-08 19:58:47 +0000637#if defined(pyr) && !defined(NOMEMCPY) /* Pyramid */
638# define NOMEMCPY /* problem with overlapping copies */
Eric Andersencc8ed391999-10-05 16:24:54 +0000639#endif
640
641#ifdef TOPS20
642# define OS_CODE 0x0a
643#endif
644
645#ifndef unix
Erik Andersene49d5ec2000-02-08 19:58:47 +0000646# define NO_ST_INO /* don't rely on inode numbers */
Eric Andersencc8ed391999-10-05 16:24:54 +0000647#endif
648
649
650 /* Common defaults */
651
652#ifndef OS_CODE
Erik Andersene49d5ec2000-02-08 19:58:47 +0000653# define OS_CODE 0x03 /* assume Unix */
Eric Andersencc8ed391999-10-05 16:24:54 +0000654#endif
655
656#ifndef PATH_SEP
657# define PATH_SEP '/'
658#endif
659
660#ifndef casemap
661# define casemap(c) (c)
662#endif
663
664#ifndef OPTIONS_VAR
665# define OPTIONS_VAR "GZIP"
666#endif
667
668#ifndef Z_SUFFIX
669# define Z_SUFFIX ".gz"
670#endif
671
672#ifdef MAX_EXT_CHARS
673# define MAX_SUFFIX MAX_EXT_CHARS
674#else
675# define MAX_SUFFIX 30
676#endif
677
678#ifndef MAKE_LEGAL_NAME
679# ifdef NO_MULTIPLE_DOTS
680# define MAKE_LEGAL_NAME(name) make_simple_name(name)
681# else
682# define MAKE_LEGAL_NAME(name)
683# endif
684#endif
685
686#ifndef MIN_PART
687# define MIN_PART 3
688 /* keep at least MIN_PART chars between dots in a file name. */
689#endif
690
691#ifndef EXPAND
692# define EXPAND(argc,argv)
693#endif
694
695#ifndef RECORD_IO
696# define RECORD_IO 0
697#endif
698
699#ifndef SET_BINARY_MODE
700# define SET_BINARY_MODE(fd)
701#endif
702
703#ifndef OPEN
704# define OPEN(name, flags, mode) open(name, flags, mode)
705#endif
706
707#ifndef get_char
708# define get_char() get_byte()
709#endif
710
711#ifndef put_char
712# define put_char(c) put_byte(c)
713#endif
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.
718 */
719
720
721/*
722 * PURPOSE
723 *
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.)
726 *
727 * DISCUSSION
728 *
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.
732 *
733 * The first bit of each byte is the low-order bit.
734 *
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().
739 *
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
743 * machines.
744 *
745 * INTERFACE
746 *
747 * void bi_init (FILE *zipfile)
748 * Initialize the bit string routines.
749 *
750 * void send_bits (int value, int length)
751 * Write out a bit string, taking the source bits right to
752 * left.
753 *
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.
757 *
758 * void bi_windup (void)
759 * Write out any remaining bits in an incomplete byte.
760 *
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.
764 *
765 */
766
767#ifdef DEBUG
768# include <stdio.h>
769#endif
770
Eric Andersencc8ed391999-10-05 16:24:54 +0000771/* ===========================================================================
772 * Local data used by the "bit string" routines.
773 */
774
Erik Andersene49d5ec2000-02-08 19:58:47 +0000775local file_t zfile; /* output gzip file */
Eric Andersencc8ed391999-10-05 16:24:54 +0000776
777local unsigned short bi_buf;
Erik Andersene49d5ec2000-02-08 19:58:47 +0000778
Eric Andersencc8ed391999-10-05 16:24:54 +0000779/* Output buffer. bits are inserted starting at the bottom (least significant
780 * bits).
781 */
782
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.)
786 */
787
788local int bi_valid;
Erik Andersene49d5ec2000-02-08 19:58:47 +0000789
Eric Andersencc8ed391999-10-05 16:24:54 +0000790/* Number of valid bits in bi_buf. All bits above the last valid bit
791 * are always zero.
792 */
793
Erik Andersen61677fe2000-04-13 01:18:56 +0000794int (*read_buf) (char *buf, unsigned size);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000795
Eric Andersencc8ed391999-10-05 16:24:54 +0000796/* Current input function. Set to mem_read for in-memory compression */
797
798#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000799ulg bits_sent; /* bit length of the compressed data */
Eric Andersencc8ed391999-10-05 16:24:54 +0000800#endif
801
802/* ===========================================================================
803 * Initialize the bit string routines.
804 */
Erik Andersene49d5ec2000-02-08 19:58:47 +0000805void bi_init(zipfile)
806file_t zipfile; /* output zip file, NO_FILE for in-memory compression */
Eric Andersencc8ed391999-10-05 16:24:54 +0000807{
Erik Andersene49d5ec2000-02-08 19:58:47 +0000808 zfile = zipfile;
809 bi_buf = 0;
810 bi_valid = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +0000811#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000812 bits_sent = 0L;
Eric Andersencc8ed391999-10-05 16:24:54 +0000813#endif
814
Erik Andersene49d5ec2000-02-08 19:58:47 +0000815 /* Set the defaults for file compression. They are set by memcompress
816 * for in-memory compression.
817 */
818 if (zfile != NO_FILE) {
819 read_buf = file_read;
820 }
Eric Andersencc8ed391999-10-05 16:24:54 +0000821}
822
823/* ===========================================================================
824 * Send a value on a given number of bits.
825 * IN assertion: length <= 16 and value fits in length bits.
826 */
827void send_bits(value, length)
Erik Andersene49d5ec2000-02-08 19:58:47 +0000828int value; /* value to send */
829int length; /* number of bits */
Eric Andersencc8ed391999-10-05 16:24:54 +0000830{
831#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000832 Tracev((stderr, " l %2d v %4x ", length, value));
833 Assert(length > 0 && length <= 15, "invalid length");
834 bits_sent += (ulg) length;
Eric Andersencc8ed391999-10-05 16:24:54 +0000835#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000836 /* 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.
839 */
840 if (bi_valid > (int) Buf_size - length) {
841 bi_buf |= (value << bi_valid);
842 put_short(bi_buf);
843 bi_buf = (ush) value >> (Buf_size - bi_valid);
844 bi_valid += length - Buf_size;
845 } else {
846 bi_buf |= value << bi_valid;
847 bi_valid += length;
848 }
Eric Andersencc8ed391999-10-05 16:24:54 +0000849}
850
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
855 */
856unsigned bi_reverse(code, len)
Erik Andersene49d5ec2000-02-08 19:58:47 +0000857unsigned code; /* the value to invert */
858int len; /* its bit length */
Eric Andersencc8ed391999-10-05 16:24:54 +0000859{
Erik Andersene49d5ec2000-02-08 19:58:47 +0000860 register unsigned res = 0;
861
862 do {
863 res |= code & 1;
864 code >>= 1, res <<= 1;
865 } while (--len > 0);
866 return res >> 1;
Eric Andersencc8ed391999-10-05 16:24:54 +0000867}
868
869/* ===========================================================================
870 * Write out any remaining bits in an incomplete byte.
871 */
872void bi_windup()
873{
Erik Andersene49d5ec2000-02-08 19:58:47 +0000874 if (bi_valid > 8) {
875 put_short(bi_buf);
876 } else if (bi_valid > 0) {
877 put_byte(bi_buf);
878 }
879 bi_buf = 0;
880 bi_valid = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +0000881#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000882 bits_sent = (bits_sent + 7) & ~7;
Eric Andersencc8ed391999-10-05 16:24:54 +0000883#endif
884}
885
886/* ===========================================================================
887 * Copy a stored block to the zip file, storing first the length and its
888 * one's complement if requested.
889 */
890void copy_block(buf, len, header)
Erik Andersene49d5ec2000-02-08 19:58:47 +0000891char *buf; /* the input data */
892unsigned len; /* its length */
893int header; /* true if block header must be written */
Eric Andersencc8ed391999-10-05 16:24:54 +0000894{
Erik Andersene49d5ec2000-02-08 19:58:47 +0000895 bi_windup(); /* align on byte boundary */
Eric Andersencc8ed391999-10-05 16:24:54 +0000896
Erik Andersene49d5ec2000-02-08 19:58:47 +0000897 if (header) {
898 put_short((ush) len);
899 put_short((ush) ~ len);
Eric Andersencc8ed391999-10-05 16:24:54 +0000900#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000901 bits_sent += 2 * 16;
Eric Andersencc8ed391999-10-05 16:24:54 +0000902#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000903 }
Eric Andersencc8ed391999-10-05 16:24:54 +0000904#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000905 bits_sent += (ulg) len << 3;
Eric Andersencc8ed391999-10-05 16:24:54 +0000906#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000907 while (len--) {
Eric Andersencc8ed391999-10-05 16:24:54 +0000908#ifdef CRYPT
Erik Andersene49d5ec2000-02-08 19:58:47 +0000909 int t;
910
911 if (key)
912 zencode(*buf, t);
Eric Andersencc8ed391999-10-05 16:24:54 +0000913#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000914 put_byte(*buf++);
915 }
Eric Andersencc8ed391999-10-05 16:24:54 +0000916}
Erik Andersene49d5ec2000-02-08 19:58:47 +0000917
Eric Andersencc8ed391999-10-05 16:24:54 +0000918/* 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.
922 */
923
924/*
925 * PURPOSE
926 *
927 * Identify new text as repetitions of old text within a fixed-
928 * length sliding window trailing behind the new text.
929 *
930 * DISCUSSION
931 *
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).
935 *
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.
953 *
954 * ACKNOWLEDGEMENTS
955 *
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.
959 *
960 * REFERENCES
961 *
962 * APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
963 *
964 * A description of the Rabin and Karp algorithm is given in the book
965 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
966 *
967 * Fiala,E.R., and Greene,D.H.
968 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
969 *
970 * INTERFACE
971 *
972 * void lm_init (int pack_level, ush *flags)
973 * Initialize the "longest match" routines for a new file
974 *
975 * ulg deflate (void)
976 * Processes a new input file and return its compressed length. Sets
977 * the compressed length, crc, deflate flags and internal file
978 * attributes.
979 */
980
981#include <stdio.h>
982
Eric Andersencc8ed391999-10-05 16:24:54 +0000983/* ===========================================================================
984 * Configuration parameters
985 */
986
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.
993 */
994
995#ifdef SMALL_MEM
Erik Andersene49d5ec2000-02-08 19:58:47 +0000996# define HASH_BITS 13 /* Number of bits used to hash strings */
Eric Andersencc8ed391999-10-05 16:24:54 +0000997#endif
998#ifdef MEDIUM_MEM
999# define HASH_BITS 14
1000#endif
1001#ifndef HASH_BITS
1002# define HASH_BITS 15
1003 /* For portability to 16 bit machines, do not use values above 15. */
1004#endif
1005
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:
1008 */
1009#if (WSIZE<<1) > (1<<BITS)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001010error:cannot overlay window with tab_suffix and prev with tab_prefix0
Eric Andersencc8ed391999-10-05 16:24:54 +00001011#endif
1012#if HASH_BITS > BITS-1
Erik Andersene49d5ec2000-02-08 19:58:47 +00001013error:cannot overlay head with tab_prefix1
Eric Andersencc8ed391999-10-05 16:24:54 +00001014#endif
Eric Andersencc8ed391999-10-05 16:24:54 +00001015#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 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001019#define NIL 0
1020/* Tail of hash chains */
Eric Andersencc8ed391999-10-05 16:24:54 +00001021#define FAST 4
1022#define SLOW 2
1023/* speed options for the general purpose bit flag */
Eric Andersencc8ed391999-10-05 16:24:54 +00001024#ifndef TOO_FAR
1025# define TOO_FAR 4096
1026#endif
1027/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
Eric Andersencc8ed391999-10-05 16:24:54 +00001028/* ===========================================================================
1029 * Local data used by the "longest match" routines.
1030 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001031typedef ush Pos;
1032typedef unsigned IPos;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001033
Eric Andersencc8ed391999-10-05 16:24:54 +00001034/* 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.
1036 */
1037
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).
1047 */
1048
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.
1053 */
1054
1055/* DECLARE(Pos, head, 1<<HASH_BITS); */
1056/* Heads of the hash chains or NIL. */
1057
Erik Andersene49d5ec2000-02-08 19:58:47 +00001058ulg window_size = (ulg) 2 * WSIZE;
1059
Eric Andersencc8ed391999-10-05 16:24:54 +00001060/* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
1061 * input file length plus MIN_LOOKAHEAD.
1062 */
1063
1064long block_start;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001065
Eric Andersencc8ed391999-10-05 16:24:54 +00001066/* window position at the beginning of the current output block. Gets
1067 * negative when the window is moved backwards.
1068 */
1069
Erik Andersene49d5ec2000-02-08 19:58:47 +00001070local unsigned ins_h; /* hash index of string to be inserted */
Eric Andersencc8ed391999-10-05 16:24:54 +00001071
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
1077 */
1078
1079unsigned int near prev_length;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001080
Eric Andersencc8ed391999-10-05 16:24:54 +00001081/* Length of the best match at previous step. Matches not greater than this
1082 * are discarded. This is used in the lazy match evaluation.
1083 */
1084
Erik Andersene49d5ec2000-02-08 19:58:47 +00001085unsigned near strstart; /* start of string to insert */
1086unsigned near match_start; /* start of matching string */
1087local int eofile; /* flag set at end of input file */
1088local unsigned lookahead; /* number of valid bytes ahead in window */
Eric Andersencc8ed391999-10-05 16:24:54 +00001089
1090unsigned near max_chain_length;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001091
Eric Andersencc8ed391999-10-05 16:24:54 +00001092/* To speed up deflation, hash chains are never searched beyond this length.
1093 * A higher limit improves compression ratio but degrades the speed.
1094 */
1095
1096local unsigned int max_lazy_match;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001097
Eric Andersencc8ed391999-10-05 16:24:54 +00001098/* 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
1100 * levels >= 4.
1101 */
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.
1106 */
1107
1108unsigned near good_match;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001109
Eric Andersencc8ed391999-10-05 16:24:54 +00001110/* Use a faster search when the previous match is longer than this */
1111
1112
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.
1117 */
1118
1119typedef struct config {
Erik Andersene49d5ec2000-02-08 19:58:47 +00001120 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 */
1123 ush max_chain;
Eric Andersencc8ed391999-10-05 16:24:54 +00001124} config;
1125
1126#ifdef FULL_SEARCH
1127# define nice_match MAX_MATCH
1128#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001129int near nice_match; /* Stop searching when current match exceeds this */
Eric Andersencc8ed391999-10-05 16:24:54 +00001130#endif
1131
Erik Andersene49d5ec2000-02-08 19:58:47 +00001132local config configuration_table =
1133 /* 9 */ { 32, 258, 258, 4096 };
1134 /* maximum compression */
Eric Andersencc8ed391999-10-05 16:24:54 +00001135
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
1138 * meaning.
1139 */
1140
1141#define EQUAL 0
1142/* result of memcmp for equal strings */
1143
1144/* ===========================================================================
1145 * Prototypes for local functions.
1146 */
Erik Andersen61677fe2000-04-13 01:18:56 +00001147local void fill_window (void);
Eric Andersencc8ed391999-10-05 16:24:54 +00001148
Erik Andersen61677fe2000-04-13 01:18:56 +00001149int longest_match (IPos cur_match);
Erik Andersene49d5ec2000-02-08 19:58:47 +00001150
Eric Andersencc8ed391999-10-05 16:24:54 +00001151#ifdef ASMV
Erik Andersen61677fe2000-04-13 01:18:56 +00001152void match_init (void); /* asm code initialization */
Eric Andersencc8ed391999-10-05 16:24:54 +00001153#endif
1154
1155#ifdef DEBUG
Erik Andersen61677fe2000-04-13 01:18:56 +00001156local void check_match (IPos start, IPos match, int length);
Eric Andersencc8ed391999-10-05 16:24:54 +00001157#endif
1158
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.
1164 */
1165#define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
1166
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).
1174 */
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], \
1178 head[ins_h] = (s))
1179
1180/* ===========================================================================
1181 * Initialize the "longest match" routines for a new file
1182 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00001183void lm_init(flags)
1184ush *flags; /* general purpose bit flag */
Eric Andersencc8ed391999-10-05 16:24:54 +00001185{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001186 register unsigned j;
Eric Andersencc8ed391999-10-05 16:24:54 +00001187
Erik Andersene49d5ec2000-02-08 19:58:47 +00001188 /* Initialize the hash table. */
Eric Andersencc8ed391999-10-05 16:24:54 +00001189#if defined(MAXSEG_64K) && HASH_BITS == 15
Erik Andersene49d5ec2000-02-08 19:58:47 +00001190 for (j = 0; j < HASH_SIZE; j++)
1191 head[j] = NIL;
Eric Andersencc8ed391999-10-05 16:24:54 +00001192#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001193 memzero((char *) head, HASH_SIZE * sizeof(*head));
Eric Andersencc8ed391999-10-05 16:24:54 +00001194#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001195 /* prev will be initialized on the fly */
Eric Andersencc8ed391999-10-05 16:24:54 +00001196
Erik Andersene49d5ec2000-02-08 19:58:47 +00001197 /* Set the default configuration parameters:
1198 */
1199 max_lazy_match = configuration_table.max_lazy;
1200 good_match = configuration_table.good_length;
Eric Andersencc8ed391999-10-05 16:24:54 +00001201#ifndef FULL_SEARCH
Erik Andersene49d5ec2000-02-08 19:58:47 +00001202 nice_match = configuration_table.nice_length;
Eric Andersencc8ed391999-10-05 16:24:54 +00001203#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001204 max_chain_length = configuration_table.max_chain;
1205 *flags |= SLOW;
1206 /* ??? reduce max_chain_length for binary files */
Eric Andersencc8ed391999-10-05 16:24:54 +00001207
Erik Andersene49d5ec2000-02-08 19:58:47 +00001208 strstart = 0;
1209 block_start = 0L;
Eric Andersencc8ed391999-10-05 16:24:54 +00001210#ifdef ASMV
Erik Andersene49d5ec2000-02-08 19:58:47 +00001211 match_init(); /* initialize the asm code */
Eric Andersencc8ed391999-10-05 16:24:54 +00001212#endif
1213
Erik Andersene49d5ec2000-02-08 19:58:47 +00001214 lookahead = read_buf((char *) window,
1215 sizeof(int) <= 2 ? (unsigned) WSIZE : 2 * WSIZE);
Eric Andersencc8ed391999-10-05 16:24:54 +00001216
Erik Andersene49d5ec2000-02-08 19:58:47 +00001217 if (lookahead == 0 || lookahead == (unsigned) EOF) {
1218 eofile = 1, lookahead = 0;
1219 return;
1220 }
1221 eofile = 0;
1222 /* Make sure that we always have enough lookahead. This is important
1223 * if input comes from a device such as a tty.
1224 */
1225 while (lookahead < MIN_LOOKAHEAD && !eofile)
1226 fill_window();
Eric Andersencc8ed391999-10-05 16:24:54 +00001227
Erik Andersene49d5ec2000-02-08 19:58:47 +00001228 ins_h = 0;
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.
1233 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001234}
1235
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
1240 * garbage.
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
1243 */
1244#ifndef ASMV
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
1247 * if desired.
1248 */
1249int longest_match(cur_match)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001250IPos cur_match; /* current match */
Eric Andersencc8ed391999-10-05 16:24:54 +00001251{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001252 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 */
1257 IPos limit =
1258
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.
1262 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001263
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.
1266 */
1267#if HASH_BITS < 8 || MAX_MATCH != 258
Erik Andersene49d5ec2000-02-08 19:58:47 +00001268 error:Code too clever
Eric Andersencc8ed391999-10-05 16:24:54 +00001269#endif
Eric Andersencc8ed391999-10-05 16:24:54 +00001270#ifdef UNALIGNED_OK
Erik Andersene49d5ec2000-02-08 19:58:47 +00001271 /* Compare two bytes at a time. Note: this is not always beneficial.
1272 * Try with and without -DUNALIGNED_OK to check.
1273 */
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);
Eric Andersencc8ed391999-10-05 16:24:54 +00001277#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001278 register uch *strend = window + strstart + MAX_MATCH;
1279 register uch scan_end1 = scan[best_len - 1];
1280 register uch scan_end = scan[best_len];
Eric Andersencc8ed391999-10-05 16:24:54 +00001281#endif
1282
Erik Andersene49d5ec2000-02-08 19:58:47 +00001283 /* Do not waste too much time if we already have a good match: */
1284 if (prev_length >= good_match) {
1285 chain_length >>= 2;
1286 }
1287 Assert(strstart <= window_size - MIN_LOOKAHEAD,
1288 "insufficient lookahead");
Eric Andersencc8ed391999-10-05 16:24:54 +00001289
Erik Andersene49d5ec2000-02-08 19:58:47 +00001290 do {
1291 Assert(cur_match < strstart, "no future");
1292 match = window + cur_match;
Eric Andersencc8ed391999-10-05 16:24:54 +00001293
Erik Andersene49d5ec2000-02-08 19:58:47 +00001294 /* Skip to next match if the match length cannot increase
1295 * or if the match length is less than 2:
1296 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001297#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001298 /* This code assumes sizeof(unsigned short) == 2. Do not use
1299 * UNALIGNED_OK if your compiler uses a different size.
1300 */
1301 if (*(ush *) (match + best_len - 1) != scan_end ||
1302 *(ush *) match != scan_start)
1303 continue;
Eric Andersencc8ed391999-10-05 16:24:54 +00001304
Erik Andersene49d5ec2000-02-08 19:58:47 +00001305 /* 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.
1313 */
1314 scan++, match++;
1315 do {
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) &&
1320 scan < strend);
1321 /* The funny "do {}" generates better code on most compilers */
Eric Andersencc8ed391999-10-05 16:24:54 +00001322
Erik Andersene49d5ec2000-02-08 19:58:47 +00001323 /* Here, scan <= window+strstart+257 */
1324 Assert(scan <= window + (unsigned) (window_size - 1), "wild scan");
1325 if (*scan == *match)
1326 scan++;
Eric Andersencc8ed391999-10-05 16:24:54 +00001327
Erik Andersene49d5ec2000-02-08 19:58:47 +00001328 len = (MAX_MATCH - 1) - (int) (strend - scan);
1329 scan = strend - (MAX_MATCH - 1);
Eric Andersencc8ed391999-10-05 16:24:54 +00001330
Erik Andersene49d5ec2000-02-08 19:58:47 +00001331#else /* UNALIGNED_OK */
Eric Andersencc8ed391999-10-05 16:24:54 +00001332
Erik Andersene49d5ec2000-02-08 19:58:47 +00001333 if (match[best_len] != scan_end ||
1334 match[best_len - 1] != scan_end1 ||
1335 *match != *scan || *++match != scan[1])
1336 continue;
Eric Andersencc8ed391999-10-05 16:24:54 +00001337
Erik Andersene49d5ec2000-02-08 19:58:47 +00001338 /* 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.
1343 */
1344 scan += 2, match++;
Eric Andersencc8ed391999-10-05 16:24:54 +00001345
Erik Andersene49d5ec2000-02-08 19:58:47 +00001346 /* We check for insufficient lookahead only every 8th comparison;
1347 * the 256th check will be made at strstart+258.
1348 */
1349 do {
1350 } while (*++scan == *++match && *++scan == *++match &&
1351 *++scan == *++match && *++scan == *++match &&
1352 *++scan == *++match && *++scan == *++match &&
1353 *++scan == *++match && *++scan == *++match &&
1354 scan < strend);
Eric Andersencc8ed391999-10-05 16:24:54 +00001355
Erik Andersene49d5ec2000-02-08 19:58:47 +00001356 len = MAX_MATCH - (int) (strend - scan);
1357 scan = strend - MAX_MATCH;
Eric Andersencc8ed391999-10-05 16:24:54 +00001358
Erik Andersene49d5ec2000-02-08 19:58:47 +00001359#endif /* UNALIGNED_OK */
Eric Andersencc8ed391999-10-05 16:24:54 +00001360
Erik Andersene49d5ec2000-02-08 19:58:47 +00001361 if (len > best_len) {
1362 match_start = cur_match;
1363 best_len = len;
1364 if (len >= nice_match)
1365 break;
Eric Andersencc8ed391999-10-05 16:24:54 +00001366#ifdef UNALIGNED_OK
Erik Andersene49d5ec2000-02-08 19:58:47 +00001367 scan_end = *(ush *) (scan + best_len - 1);
Eric Andersencc8ed391999-10-05 16:24:54 +00001368#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001369 scan_end1 = scan[best_len - 1];
1370 scan_end = scan[best_len];
Eric Andersencc8ed391999-10-05 16:24:54 +00001371#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001372 }
1373 } while ((cur_match = prev[cur_match & WMASK]) > limit
1374 && --chain_length != 0);
Eric Andersencc8ed391999-10-05 16:24:54 +00001375
Erik Andersene49d5ec2000-02-08 19:58:47 +00001376 return best_len;
Eric Andersencc8ed391999-10-05 16:24:54 +00001377}
Erik Andersene49d5ec2000-02-08 19:58:47 +00001378#endif /* ASMV */
Eric Andersencc8ed391999-10-05 16:24:54 +00001379
1380#ifdef DEBUG
1381/* ===========================================================================
1382 * Check that the match at match_start is indeed a match.
1383 */
1384local void check_match(start, match, length)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001385IPos start, match;
1386int length;
Eric Andersencc8ed391999-10-05 16:24:54 +00001387{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001388 /* check that the match is indeed a match */
1389 if (memcmp((char *) window + match,
1390 (char *) window + start, length) != EQUAL) {
1391 fprintf(stderr,
1392 " start %d, match %d, length %d\n", start, match, length);
Erik Andersen9ffdaa62000-02-11 21:55:04 +00001393 errorMsg("invalid match");
Erik Andersene49d5ec2000-02-08 19:58:47 +00001394 }
1395 if (verbose > 1) {
1396 fprintf(stderr, "\\[%d,%d]", start - match, length);
1397 do {
1398 putc(window[start++], stderr);
1399 } while (--length != 0);
1400 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001401}
1402#else
1403# define check_match(start, match, length)
1404#endif
1405
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).
1413 */
1414local void fill_window()
1415{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001416 register unsigned n, m;
1417 unsigned more =
Eric Andersencc8ed391999-10-05 16:24:54 +00001418
Erik Andersene49d5ec2000-02-08 19:58:47 +00001419 (unsigned) (window_size - (ulg) lookahead - (ulg) strstart);
1420 /* Amount of free space at the end of the window. */
Eric Andersencc8ed391999-10-05 16:24:54 +00001421
Erik Andersene49d5ec2000-02-08 19:58:47 +00001422 /* 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.
1424 */
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)
1428 */
1429 more--;
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.
1433 */
1434 Assert(window_size == (ulg) 2 * WSIZE, "no sliding with BIG_MEM");
Eric Andersencc8ed391999-10-05 16:24:54 +00001435
Erik Andersene49d5ec2000-02-08 19:58:47 +00001436 memcpy((char *) window, (char *) window + WSIZE, (unsigned) WSIZE);
1437 match_start -= WSIZE;
1438 strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
Eric Andersencc8ed391999-10-05 16:24:54 +00001439
Erik Andersene49d5ec2000-02-08 19:58:47 +00001440 block_start -= (long) WSIZE;
1441
1442 for (n = 0; n < HASH_SIZE; n++) {
1443 m = head[n];
1444 head[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
1445 }
1446 for (n = 0; n < WSIZE; n++) {
1447 m = prev[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.
1451 */
1452 }
1453 more += WSIZE;
1454 }
1455 /* At this point, more >= 2 */
1456 if (!eofile) {
1457 n = read_buf((char *) window + strstart + lookahead, more);
1458 if (n == 0 || n == (unsigned) EOF) {
1459 eofile = 1;
1460 } else {
1461 lookahead += n;
1462 }
1463 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001464}
1465
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.
1469 */
1470#define FLUSH_BLOCK(eof) \
1471 flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
1472 (char*)NULL, (long)strstart - block_start, (eof))
1473
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.
1478 */
1479ulg deflate()
1480{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001481 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 */
1486
Eric Andersencc8ed391999-10-05 16:24:54 +00001487#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +00001488 extern long isize; /* byte length of input file, for debug only */
Eric Andersencc8ed391999-10-05 16:24:54 +00001489#endif
1490
Erik Andersene49d5ec2000-02-08 19:58:47 +00001491 /* 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:
1495 */
1496 INSERT_STRING(strstart, hash_head);
Eric Andersencc8ed391999-10-05 16:24:54 +00001497
Erik Andersene49d5ec2000-02-08 19:58:47 +00001498 /* Find the longest match, discarding those <= prev_length.
1499 */
1500 prev_length = match_length, prev_match = match_start;
1501 match_length = MIN_MATCH - 1;
Eric Andersencc8ed391999-10-05 16:24:54 +00001502
Erik Andersene49d5ec2000-02-08 19:58:47 +00001503 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).
1508 */
1509 match_length = longest_match(hash_head);
1510 /* longest_match() sets match_start */
1511 if (match_length > lookahead)
1512 match_length = lookahead;
Eric Andersencc8ed391999-10-05 16:24:54 +00001513
Erik Andersene49d5ec2000-02-08 19:58:47 +00001514 /* 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.
1519 */
1520 match_length--;
1521 }
1522 }
1523 /* If there was a match at the previous step and the current
1524 * match is not better, output the previous match:
1525 */
1526 if (prev_length >= MIN_MATCH && match_length <= prev_length) {
Eric Andersencc8ed391999-10-05 16:24:54 +00001527
Erik Andersene49d5ec2000-02-08 19:58:47 +00001528 check_match(strstart - 1, prev_match, prev_length);
Eric Andersencc8ed391999-10-05 16:24:54 +00001529
Erik Andersene49d5ec2000-02-08 19:58:47 +00001530 flush =
1531 ct_tally(strstart - 1 - prev_match,
1532 prev_length - MIN_MATCH);
Eric Andersencc8ed391999-10-05 16:24:54 +00001533
Erik Andersene49d5ec2000-02-08 19:58:47 +00001534 /* Insert in hash table all strings up to the end of the match.
1535 * strstart-1 and strstart are already inserted.
1536 */
1537 lookahead -= prev_length - 1;
1538 prev_length -= 2;
1539 do {
1540 strstart++;
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.
1546 */
1547 } while (--prev_length != 0);
1548 match_available = 0;
1549 match_length = MIN_MATCH - 1;
1550 strstart++;
1551 if (flush)
1552 FLUSH_BLOCK(0), block_start = strstart;
Eric Andersencc8ed391999-10-05 16:24:54 +00001553
Erik Andersene49d5ec2000-02-08 19:58:47 +00001554 } 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.
1558 */
1559 Tracevv((stderr, "%c", window[strstart - 1]));
1560 if (ct_tally(0, window[strstart - 1])) {
1561 FLUSH_BLOCK(0), block_start = strstart;
1562 }
1563 strstart++;
1564 lookahead--;
1565 } else {
1566 /* There is no previous match to compare with, wait for
1567 * the next step to decide.
1568 */
1569 match_available = 1;
1570 strstart++;
1571 lookahead--;
1572 }
1573 Assert(strstart <= isize && lookahead <= isize, "a bit too far");
Eric Andersencc8ed391999-10-05 16:24:54 +00001574
Erik Andersene49d5ec2000-02-08 19:58:47 +00001575 /* 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.
1579 */
1580 while (lookahead < MIN_LOOKAHEAD && !eofile)
1581 fill_window();
1582 }
1583 if (match_available)
1584 ct_tally(0, window[strstart - 1]);
Eric Andersencc8ed391999-10-05 16:24:54 +00001585
Erik Andersene49d5ec2000-02-08 19:58:47 +00001586 return FLUSH_BLOCK(1); /* eof */
Eric Andersencc8ed391999-10-05 16:24:54 +00001587}
Erik Andersene49d5ec2000-02-08 19:58:47 +00001588
Eric Andersencc8ed391999-10-05 16:24:54 +00001589/* 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.
1595 *
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.
1598 */
1599
1600/* Compress files with zip algorithm and 'compress' interface.
1601 * See usage() and help() functions below for all options.
1602 * Outputs:
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.
1608 *
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.
1614 *
1615 * For the meaning of all compilation flags, see comments in Makefile.in.
1616 */
1617
Eric Andersencc8ed391999-10-05 16:24:54 +00001618#include <ctype.h>
1619#include <sys/types.h>
1620#include <signal.h>
1621#include <sys/stat.h>
1622#include <errno.h>
1623
1624 /* configuration */
1625
1626#ifdef NO_TIME_H
1627# include <sys/time.h>
1628#else
1629# include <time.h>
1630#endif
1631
1632#ifndef NO_FCNTL_H
1633# include <fcntl.h>
1634#endif
1635
1636#ifdef HAVE_UNISTD_H
1637# include <unistd.h>
1638#endif
1639
1640#if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
1641# include <stdlib.h>
1642#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001643extern int errno;
Eric Andersencc8ed391999-10-05 16:24:54 +00001644#endif
1645
1646#if defined(DIRENT)
1647# include <dirent.h>
Erik Andersene49d5ec2000-02-08 19:58:47 +00001648typedef struct dirent dir_type;
1649
Eric Andersencc8ed391999-10-05 16:24:54 +00001650# define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
1651# define DIR_OPT "DIRENT"
1652#else
1653# define NLENGTH(dirent) ((dirent)->d_namlen)
1654# ifdef SYSDIR
1655# include <sys/dir.h>
Erik Andersene49d5ec2000-02-08 19:58:47 +00001656typedef struct direct dir_type;
1657
Eric Andersencc8ed391999-10-05 16:24:54 +00001658# define DIR_OPT "SYSDIR"
1659# else
1660# ifdef SYSNDIR
1661# include <sys/ndir.h>
Erik Andersene49d5ec2000-02-08 19:58:47 +00001662typedef struct direct dir_type;
1663
Eric Andersencc8ed391999-10-05 16:24:54 +00001664# define DIR_OPT "SYSNDIR"
1665# else
1666# ifdef NDIR
1667# include <ndir.h>
Erik Andersene49d5ec2000-02-08 19:58:47 +00001668typedef struct direct dir_type;
1669
Eric Andersencc8ed391999-10-05 16:24:54 +00001670# define DIR_OPT "NDIR"
1671# else
1672# define NO_DIR
1673# define DIR_OPT "NO_DIR"
1674# endif
1675# endif
1676# endif
1677#endif
1678
1679#ifndef NO_UTIME
1680# ifndef NO_UTIME_H
1681# include <utime.h>
1682# define TIME_OPT "UTIME"
1683# else
1684# ifdef HAVE_SYS_UTIME_H
1685# include <sys/utime.h>
1686# define TIME_OPT "SYS_UTIME"
1687# else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001688struct utimbuf {
1689 time_t actime;
1690 time_t modtime;
1691};
1692
Eric Andersencc8ed391999-10-05 16:24:54 +00001693# define TIME_OPT ""
1694# endif
1695# endif
1696#else
1697# define TIME_OPT "NO_UTIME"
1698#endif
1699
1700#if !defined(S_ISDIR) && defined(S_IFDIR)
1701# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1702#endif
1703#if !defined(S_ISREG) && defined(S_IFREG)
1704# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1705#endif
1706
Erik Andersen61677fe2000-04-13 01:18:56 +00001707typedef RETSIGTYPE(*sig_type) (int);
Eric Andersencc8ed391999-10-05 16:24:54 +00001708
1709#ifndef O_BINARY
Erik Andersene49d5ec2000-02-08 19:58:47 +00001710# define O_BINARY 0 /* creation mode for open() */
Eric Andersencc8ed391999-10-05 16:24:54 +00001711#endif
1712
1713#ifndef O_CREAT
1714 /* Pure BSD system? */
1715# include <sys/file.h>
1716# ifndef O_CREAT
1717# define O_CREAT FCREAT
1718# endif
1719# ifndef O_EXCL
1720# define O_EXCL FEXCL
1721# endif
1722#endif
1723
1724#ifndef S_IRUSR
1725# define S_IRUSR 0400
1726#endif
1727#ifndef S_IWUSR
1728# define S_IWUSR 0200
1729#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001730#define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */
Eric Andersencc8ed391999-10-05 16:24:54 +00001731
1732#ifndef MAX_PATH_LEN
Erik Andersene49d5ec2000-02-08 19:58:47 +00001733# define MAX_PATH_LEN 1024 /* max pathname length */
Eric Andersencc8ed391999-10-05 16:24:54 +00001734#endif
1735
1736#ifndef SEEK_END
1737# define SEEK_END 2
1738#endif
1739
1740#ifdef NO_OFF_T
Erik Andersene49d5ec2000-02-08 19:58:47 +00001741typedef long off_t;
Erik Andersen61677fe2000-04-13 01:18:56 +00001742off_t lseek (int fd, off_t offset, int whence);
Eric Andersencc8ed391999-10-05 16:24:54 +00001743#endif
1744
1745/* Separator for file name parts (see shorten_name()) */
1746#ifdef NO_MULTIPLE_DOTS
1747# define PART_SEP "-"
1748#else
1749# define PART_SEP "."
1750#endif
1751
1752 /* global buffers */
1753
Erik Andersene49d5ec2000-02-08 19:58:47 +00001754DECLARE(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
1755DECLARE(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
1756DECLARE(ush, d_buf, DIST_BUFSIZE);
1757DECLARE(uch, window, 2L * WSIZE);
Eric Andersencc8ed391999-10-05 16:24:54 +00001758#ifndef MAXSEG_64K
Erik Andersene49d5ec2000-02-08 19:58:47 +00001759DECLARE(ush, tab_prefix, 1L << BITS);
Eric Andersencc8ed391999-10-05 16:24:54 +00001760#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001761DECLARE(ush, tab_prefix0, 1L << (BITS - 1));
1762DECLARE(ush, tab_prefix1, 1L << (BITS - 1));
Eric Andersencc8ed391999-10-05 16:24:54 +00001763#endif
1764
1765 /* local variables */
1766
Erik Andersene49d5ec2000-02-08 19:58:47 +00001767int ascii = 0; /* convert end-of-lines to local OS conventions */
1768int decompress = 0; /* decompress (-d) */
1769int no_name = -1; /* don't save or restore the original file name */
1770int no_time = -1; /* don't save or restore the original file time */
1771int foreground; /* set if program run in foreground */
1772char *progname; /* program name */
1773static int method = DEFLATED; /* compression method */
1774static int exit_code = OK; /* program exit code */
1775int save_orig_name; /* set if original name must be saved */
1776int last_member; /* set for .zip and .Z files */
1777int part_nb; /* number of parts in .gz file */
1778long time_stamp; /* original time stamp (modification time) */
1779long ifile_size; /* input file size, -1 for devices (debug only) */
1780char *env; /* contents of GZIP env variable */
1781char **args = NULL; /* argv pointer if GZIP env variable defined */
1782char z_suffix[MAX_SUFFIX + 1]; /* default suffix (can be set with --suffix) */
1783int z_len; /* strlen(z_suffix) */
Eric Andersencc8ed391999-10-05 16:24:54 +00001784
Erik Andersene49d5ec2000-02-08 19:58:47 +00001785long bytes_in; /* number of input bytes */
1786long bytes_out; /* number of output bytes */
1787char ifname[MAX_PATH_LEN]; /* input file name */
1788char ofname[MAX_PATH_LEN]; /* output file name */
1789int remove_ofname = 0; /* remove output file on error */
1790struct stat istat; /* status for input file */
1791int ifd; /* input file descriptor */
1792int ofd; /* output file descriptor */
1793unsigned insize; /* valid bytes in inbuf */
1794unsigned inptr; /* index of next byte to be processed in inbuf */
1795unsigned outcnt; /* bytes in output buffer */
Eric Andersencc8ed391999-10-05 16:24:54 +00001796
1797/* local functions */
1798
Eric Andersencc8ed391999-10-05 16:24:54 +00001799#define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
1800
1801/* ======================================================================== */
1802// int main (argc, argv)
1803// int argc;
1804// char **argv;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001805int gzip_main(int argc, char **argv)
Eric Andersencc8ed391999-10-05 16:24:54 +00001806{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001807 int result;
1808 int inFileNum;
1809 int outFileNum;
1810 struct stat statBuf;
1811 char *delFileName;
1812 int tostdout = 0;
1813 int fromstdin = 0;
Eric Andersen96bcfd31999-11-12 01:30:18 +00001814
Erik Andersene49d5ec2000-02-08 19:58:47 +00001815 if (argc == 1)
Eric Andersenc296b541999-11-11 01:36:55 +00001816 usage(gzip_usage);
Eric Andersenc296b541999-11-11 01:36:55 +00001817
Erik Andersene49d5ec2000-02-08 19:58:47 +00001818 /* Parse any options */
1819 while (--argc > 0 && **(++argv) == '-') {
1820 if (*((*argv) + 1) == '\0') {
1821 fromstdin = 1;
1822 tostdout = 1;
1823 }
1824 while (*(++(*argv))) {
1825 switch (**argv) {
1826 case 'c':
1827 tostdout = 1;
1828 break;
1829 default:
1830 usage(gzip_usage);
1831 }
1832 }
1833 }
1834
1835 foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
1836 if (foreground) {
1837 (void) signal(SIGINT, (sig_type) abort_gzip);
1838 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001839#ifdef SIGTERM
Erik Andersene49d5ec2000-02-08 19:58:47 +00001840 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
1841 (void) signal(SIGTERM, (sig_type) abort_gzip);
1842 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001843#endif
1844#ifdef SIGHUP
Erik Andersene49d5ec2000-02-08 19:58:47 +00001845 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
1846 (void) signal(SIGHUP, (sig_type) abort_gzip);
1847 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001848#endif
1849
Erik Andersene49d5ec2000-02-08 19:58:47 +00001850 strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix) - 1);
1851 z_len = strlen(z_suffix);
Eric Andersencc8ed391999-10-05 16:24:54 +00001852
Erik Andersene49d5ec2000-02-08 19:58:47 +00001853 /* 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);
Eric Andersencc8ed391999-10-05 16:24:54 +00001858#ifndef MAXSEG_64K
Erik Andersene49d5ec2000-02-08 19:58:47 +00001859 ALLOC(ush, tab_prefix, 1L << BITS);
Eric Andersencc8ed391999-10-05 16:24:54 +00001860#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001861 ALLOC(ush, tab_prefix0, 1L << (BITS - 1));
1862 ALLOC(ush, tab_prefix1, 1L << (BITS - 1));
Eric Andersencc8ed391999-10-05 16:24:54 +00001863#endif
1864
Erik Andersene49d5ec2000-02-08 19:58:47 +00001865 if (fromstdin == 1) {
1866 strcpy(ofname, "stdin");
Eric Andersen96bcfd31999-11-12 01:30:18 +00001867
Erik Andersene49d5ec2000-02-08 19:58:47 +00001868 inFileNum = fileno(stdin);
1869 time_stamp = 0; /* time unknown by default */
1870 ifile_size = -1L; /* convention for unknown size */
1871 } else {
1872 /* Open up the input file */
1873 if (*argv == '\0')
1874 usage(gzip_usage);
1875 strncpy(ifname, *argv, MAX_PATH_LEN);
Eric Andersen96bcfd31999-11-12 01:30:18 +00001876
Erik Andersene49d5ec2000-02-08 19:58:47 +00001877 /* Open input fille */
1878 inFileNum = open(ifname, O_RDONLY);
1879 if (inFileNum < 0) {
1880 perror(ifname);
1881 do_exit(WARNING);
1882 }
1883 /* Get the time stamp on the input file. */
1884 result = stat(ifname, &statBuf);
1885 if (result < 0) {
1886 perror(ifname);
1887 do_exit(WARNING);
1888 }
1889 time_stamp = statBuf.st_ctime;
1890 ifile_size = statBuf.st_size;
Eric Andersen96bcfd31999-11-12 01:30:18 +00001891 }
Eric Andersen96bcfd31999-11-12 01:30:18 +00001892
1893
Erik Andersene49d5ec2000-02-08 19:58:47 +00001894 if (tostdout == 1) {
1895 /* And get to work */
1896 strcpy(ofname, "stdout");
1897 outFileNum = fileno(stdout);
1898 SET_BINARY_MODE(fileno(stdout));
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001899
Erik Andersene49d5ec2000-02-08 19:58:47 +00001900 clear_bufs(); /* clear input and output buffers */
1901 part_nb = 0;
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001902
Erik Andersene49d5ec2000-02-08 19:58:47 +00001903 /* Actually do the compression/decompression. */
1904 zip(inFileNum, outFileNum);
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001905
Erik Andersene49d5ec2000-02-08 19:58:47 +00001906 } else {
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001907
Erik Andersene49d5ec2000-02-08 19:58:47 +00001908 /* And get to work */
1909 strncpy(ofname, ifname, MAX_PATH_LEN - 4);
1910 strcat(ofname, ".gz");
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001911
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001912
Erik Andersene49d5ec2000-02-08 19:58:47 +00001913 /* Open output fille */
Erik Andersen4d1d0111999-12-17 18:44:15 +00001914#if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001915 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
Erik Andersen4d1d0111999-12-17 18:44:15 +00001916#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001917 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL);
Erik Andersen4d1d0111999-12-17 18:44:15 +00001918#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001919 if (outFileNum < 0) {
1920 perror(ofname);
1921 do_exit(WARNING);
1922 }
1923 SET_BINARY_MODE(outFileNum);
1924 /* Set permissions on the file */
1925 fchmod(outFileNum, statBuf.st_mode);
1926
1927 clear_bufs(); /* clear input and output buffers */
1928 part_nb = 0;
1929
1930 /* Actually do the compression/decompression. */
1931 result = zip(inFileNum, outFileNum);
1932 close(outFileNum);
1933 close(inFileNum);
1934 /* Delete the original file */
1935 if (result == OK)
1936 delFileName = ifname;
1937 else
1938 delFileName = ofname;
1939
1940 if (unlink(delFileName) < 0) {
1941 perror(delFileName);
1942 exit(FALSE);
1943 }
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001944 }
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001945
Erik Andersene49d5ec2000-02-08 19:58:47 +00001946 do_exit(exit_code);
Eric Andersencc8ed391999-10-05 16:24:54 +00001947}
1948
Eric Andersencc8ed391999-10-05 16:24:54 +00001949/* 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.
1953 */
1954
1955/*
1956 * PURPOSE
1957 *
1958 * Encode various sets of source values using variable-length
1959 * binary code trees.
1960 *
1961 * DISCUSSION
1962 *
1963 * The PKZIP "deflation" process uses several Huffman trees. The more
1964 * common source values are represented by shorter bit sequences.
1965 *
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.
1972 *
1973 * REFERENCES
1974 *
1975 * Lynch, Thomas J.
1976 * Data Compression: Techniques and Applications, pp. 53-55.
1977 * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
1978 *
1979 * Storer, James A.
1980 * Data Compression: Methods and Theory, pp. 49-50.
1981 * Computer Science Press, 1988. ISBN 0-7167-8156-5.
1982 *
1983 * Sedgewick, R.
1984 * Algorithms, p290.
1985 * Addison-Wesley, 1983. ISBN 0-201-06672-6.
1986 *
1987 * INTERFACE
1988 *
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)
1993 *
1994 * void ct_tally (int dist, int lc);
1995 * Save the match info and tally the frequency counts.
1996 *
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.
2001 *
2002 */
2003
2004#include <ctype.h>
2005
Eric Andersencc8ed391999-10-05 16:24:54 +00002006/* ===========================================================================
2007 * Constants
2008 */
2009
2010#define MAX_BITS 15
2011/* All codes must not exceed MAX_BITS bits */
2012
2013#define MAX_BL_BITS 7
2014/* Bit length codes must not exceed MAX_BL_BITS bits */
2015
2016#define LENGTH_CODES 29
2017/* number of length codes, not counting the special END_BLOCK code */
2018
2019#define LITERALS 256
2020/* number of literal bytes 0..255 */
2021
2022#define END_BLOCK 256
2023/* end of block literal code */
2024
2025#define L_CODES (LITERALS+1+LENGTH_CODES)
2026/* number of Literal or Length codes, including the END_BLOCK code */
2027
2028#define D_CODES 30
2029/* number of distance codes */
2030
2031#define BL_CODES 19
2032/* number of codes used to transfer the bit lengths */
2033
2034
Erik Andersene49d5ec2000-02-08 19:58:47 +00002035local 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 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002038
Erik Andersene49d5ec2000-02-08 19:58:47 +00002039local 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 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002042
Erik Andersene49d5ec2000-02-08 19:58:47 +00002043local 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 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002045
2046#define STORED_BLOCK 0
2047#define STATIC_TREES 1
2048#define DYN_TREES 2
2049/* The three kinds of block type */
2050
2051#ifndef LIT_BUFSIZE
2052# ifdef SMALL_MEM
2053# define LIT_BUFSIZE 0x2000
2054# else
2055# ifdef MEDIUM_MEM
2056# define LIT_BUFSIZE 0x4000
2057# else
2058# define LIT_BUFSIZE 0x8000
2059# endif
2060# endif
2061#endif
2062#ifndef DIST_BUFSIZE
2063# define DIST_BUFSIZE LIT_BUFSIZE
2064#endif
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
2079 * more frequently.
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.
2084 */
2085#if LIT_BUFSIZE > INBUFSIZ
Erik Andersene49d5ec2000-02-08 19:58:47 +00002086error cannot overlay l_buf and inbuf
Eric Andersencc8ed391999-10-05 16:24:54 +00002087#endif
Eric Andersencc8ed391999-10-05 16:24:54 +00002088#define REP_3_6 16
2089/* repeat previous bit length 3-6 times (2 bits of repeat count) */
Eric Andersencc8ed391999-10-05 16:24:54 +00002090#define REPZ_3_10 17
2091/* repeat a zero length 3-10 times (3 bits of repeat count) */
Eric Andersencc8ed391999-10-05 16:24:54 +00002092#define REPZ_11_138 18
Erik Andersene49d5ec2000-02-08 19:58:47 +00002093/* repeat a zero length 11-138 times (7 bits of repeat count) *//* ===========================================================================
Eric Andersencc8ed391999-10-05 16:24:54 +00002094 * Local data
Erik Andersene49d5ec2000-02-08 19:58:47 +00002095 *//* Data structure describing a single value and its code string. */ typedef struct ct_data {
2096 union {
2097 ush freq; /* frequency count */
2098 ush code; /* bit string */
2099 } fc;
2100 union {
2101 ush dad; /* father node in Huffman tree */
2102 ush len; /* length of bit string */
2103 } dl;
Eric Andersencc8ed391999-10-05 16:24:54 +00002104} ct_data;
2105
2106#define Freq fc.freq
2107#define Code fc.code
2108#define Dad dl.dad
2109#define Len dl.len
2110
2111#define HEAP_SIZE (2*L_CODES+1)
2112/* maximum heap size */
2113
Erik Andersene49d5ec2000-02-08 19:58:47 +00002114local ct_data near dyn_ltree[HEAP_SIZE]; /* literal and length tree */
2115local ct_data near dyn_dtree[2 * D_CODES + 1]; /* distance tree */
Eric Andersencc8ed391999-10-05 16:24:54 +00002116
Erik Andersene49d5ec2000-02-08 19:58:47 +00002117local ct_data near static_ltree[L_CODES + 2];
2118
Eric Andersencc8ed391999-10-05 16:24:54 +00002119/* 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
2122 * below).
2123 */
2124
2125local ct_data near static_dtree[D_CODES];
Erik Andersene49d5ec2000-02-08 19:58:47 +00002126
Eric Andersencc8ed391999-10-05 16:24:54 +00002127/* The static distance tree. (Actually a trivial tree since all codes use
2128 * 5 bits.)
2129 */
2130
Erik Andersene49d5ec2000-02-08 19:58:47 +00002131local ct_data near bl_tree[2 * BL_CODES + 1];
2132
Eric Andersencc8ed391999-10-05 16:24:54 +00002133/* Huffman tree for the bit lengths */
2134
2135typedef struct tree_desc {
Erik Andersene49d5ec2000-02-08 19:58:47 +00002136 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 */
Eric Andersencc8ed391999-10-05 16:24:54 +00002143} tree_desc;
2144
2145local tree_desc near l_desc =
Erik Andersene49d5ec2000-02-08 19:58:47 +00002146 { dyn_ltree, static_ltree, extra_lbits, LITERALS + 1, L_CODES,
2147 MAX_BITS, 0 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002148
2149local tree_desc near d_desc =
Erik Andersene49d5ec2000-02-08 19:58:47 +00002150 { dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002151
2152local tree_desc near bl_desc =
Erik Andersene49d5ec2000-02-08 19:58:47 +00002153 { bl_tree, (ct_data near *) 0, extra_blbits, 0, BL_CODES, MAX_BL_BITS,
2154 0 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002155
2156
Erik Andersene49d5ec2000-02-08 19:58:47 +00002157local ush near bl_count[MAX_BITS + 1];
2158
Eric Andersencc8ed391999-10-05 16:24:54 +00002159/* number of codes at each bit length for an optimal tree */
2160
2161local uch near bl_order[BL_CODES]
Erik Andersene49d5ec2000-02-08 19:58:47 +00002162= { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
2163
Eric Andersencc8ed391999-10-05 16:24:54 +00002164/* 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.
2166 */
2167
Erik Andersene49d5ec2000-02-08 19:58:47 +00002168local int near heap[2 * L_CODES + 1]; /* heap used to build the Huffman trees */
2169local int heap_len; /* number of elements in the heap */
2170local int heap_max; /* element of largest frequency */
2171
Eric Andersencc8ed391999-10-05 16:24:54 +00002172/* 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.
2174 */
2175
Erik Andersene49d5ec2000-02-08 19:58:47 +00002176local uch near depth[2 * L_CODES + 1];
2177
Eric Andersencc8ed391999-10-05 16:24:54 +00002178/* Depth of each subtree used as tie breaker for trees of equal frequency */
2179
Erik Andersene49d5ec2000-02-08 19:58:47 +00002180local uch length_code[MAX_MATCH - MIN_MATCH + 1];
2181
Eric Andersencc8ed391999-10-05 16:24:54 +00002182/* length code for each normalized match length (0 == MIN_MATCH) */
2183
2184local uch dist_code[512];
Erik Andersene49d5ec2000-02-08 19:58:47 +00002185
Eric Andersencc8ed391999-10-05 16:24:54 +00002186/* 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.
2189 */
2190
2191local int near base_length[LENGTH_CODES];
Erik Andersene49d5ec2000-02-08 19:58:47 +00002192
Eric Andersencc8ed391999-10-05 16:24:54 +00002193/* First normalized length for each code (0 = MIN_MATCH) */
2194
2195local int near base_dist[D_CODES];
Erik Andersene49d5ec2000-02-08 19:58:47 +00002196
Eric Andersencc8ed391999-10-05 16:24:54 +00002197/* First normalized distance for each code (0 = distance of 1) */
2198
2199#define l_buf inbuf
2200/* DECLARE(uch, l_buf, LIT_BUFSIZE); buffer for literals or lengths */
2201
2202/* DECLARE(ush, d_buf, DIST_BUFSIZE); buffer for distances */
2203
Erik Andersene49d5ec2000-02-08 19:58:47 +00002204local uch near flag_buf[(LIT_BUFSIZE / 8)];
2205
Eric Andersencc8ed391999-10-05 16:24:54 +00002206/* flag_buf is a bit array distinguishing literals from lengths in
2207 * l_buf, thus indicating the presence or absence of a distance.
2208 */
2209
Erik Andersene49d5ec2000-02-08 19:58:47 +00002210local unsigned last_lit; /* running index in l_buf */
2211local unsigned last_dist; /* running index in d_buf */
2212local unsigned last_flags; /* running index in flag_buf */
2213local uch flags; /* current flags not yet saved in flag_buf */
2214local uch flag_bit; /* current bit used in flags */
2215
Eric Andersencc8ed391999-10-05 16:24:54 +00002216/* 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.
2219 */
2220
Erik Andersene49d5ec2000-02-08 19:58:47 +00002221local ulg opt_len; /* bit length of current block with optimal trees */
2222local ulg static_len; /* bit length of current block with static trees */
Eric Andersencc8ed391999-10-05 16:24:54 +00002223
Erik Andersene49d5ec2000-02-08 19:58:47 +00002224local ulg compressed_len; /* total bit length of compressed file */
Eric Andersencc8ed391999-10-05 16:24:54 +00002225
Erik Andersene49d5ec2000-02-08 19:58:47 +00002226local ulg input_len; /* total byte length of input file */
2227
Eric Andersencc8ed391999-10-05 16:24:54 +00002228/* input_len is for debugging only since we can get it by other means. */
2229
Erik Andersene49d5ec2000-02-08 19:58:47 +00002230ush *file_type; /* pointer to UNKNOWN, BINARY or ASCII */
2231int *file_method; /* pointer to DEFLATE or STORE */
Eric Andersencc8ed391999-10-05 16:24:54 +00002232
2233#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +00002234extern ulg bits_sent; /* bit length of the compressed data */
2235extern long isize; /* byte length of input file */
Eric Andersencc8ed391999-10-05 16:24:54 +00002236#endif
2237
Erik Andersene49d5ec2000-02-08 19:58:47 +00002238extern long block_start; /* window offset of current block */
2239extern unsigned near strstart; /* window offset of current string */
Eric Andersencc8ed391999-10-05 16:24:54 +00002240
2241/* ===========================================================================
2242 * Local (static) routines in this file.
2243 */
2244
Erik Andersen61677fe2000-04-13 01:18:56 +00002245local void init_block (void);
2246local void pqdownheap (ct_data near * tree, int k);
2247local void gen_bitlen (tree_desc near * desc);
2248local void gen_codes (ct_data near * tree, int max_code);
2249local void build_tree (tree_desc near * desc);
2250local void scan_tree (ct_data near * tree, int max_code);
2251local void send_tree (ct_data near * tree, int max_code);
2252local int build_bl_tree (void);
2253local void send_all_trees (int lcodes, int dcodes, int blcodes);
2254local void compress_block (ct_data near * ltree, ct_data near * dtree);
2255local void set_file_type (void);
Eric Andersencc8ed391999-10-05 16:24:54 +00002256
2257
2258#ifndef DEBUG
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 */
2261
Erik Andersene49d5ec2000-02-08 19:58:47 +00002262#else /* DEBUG */
Eric Andersencc8ed391999-10-05 16:24:54 +00002263# define send_code(c, tree) \
2264 { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \
2265 send_bits(tree[c].Code, tree[c].Len); }
2266#endif
2267
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
2272 * used.
2273 */
2274
2275#define MAX(a,b) (a >= b ? a : b)
2276/* the arguments must not have side effects */
2277
2278/* ===========================================================================
2279 * Allocate the match buffer, initialize the various tables and save the
2280 * location of the internal file attribute (ascii/binary) and method
2281 * (DEFLATE/STORE).
2282 */
2283void ct_init(attr, methodp)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002284ush *attr; /* pointer to internal file attribute */
2285int *methodp; /* pointer to compression method */
Eric Andersencc8ed391999-10-05 16:24:54 +00002286{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002287 int n; /* iterates over tree elements */
2288 int bits; /* bit counter */
2289 int length; /* length value */
2290 int code; /* code value */
2291 int dist; /* distance index */
Eric Andersencc8ed391999-10-05 16:24:54 +00002292
Erik Andersene49d5ec2000-02-08 19:58:47 +00002293 file_type = attr;
2294 file_method = methodp;
2295 compressed_len = input_len = 0L;
Eric Andersencc8ed391999-10-05 16:24:54 +00002296
Erik Andersene49d5ec2000-02-08 19:58:47 +00002297 if (static_dtree[0].Len != 0)
2298 return; /* ct_init already called */
Eric Andersencc8ed391999-10-05 16:24:54 +00002299
Erik Andersene49d5ec2000-02-08 19:58:47 +00002300 /* Initialize the mapping length (0..255) -> length code (0..28) */
2301 length = 0;
2302 for (code = 0; code < LENGTH_CODES - 1; code++) {
2303 base_length[code] = length;
2304 for (n = 0; n < (1 << extra_lbits[code]); n++) {
2305 length_code[length++] = (uch) code;
2306 }
2307 }
2308 Assert(length == 256, "ct_init: length != 256");
2309 /* Note that the length 255 (match length 258) can be represented
2310 * in two different ways: code 284 + 5 bits or code 285, so we
2311 * overwrite length_code[255] to use the best encoding:
2312 */
2313 length_code[length - 1] = (uch) code;
Eric Andersencc8ed391999-10-05 16:24:54 +00002314
Erik Andersene49d5ec2000-02-08 19:58:47 +00002315 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
2316 dist = 0;
2317 for (code = 0; code < 16; code++) {
2318 base_dist[code] = dist;
2319 for (n = 0; n < (1 << extra_dbits[code]); n++) {
2320 dist_code[dist++] = (uch) code;
2321 }
2322 }
2323 Assert(dist == 256, "ct_init: dist != 256");
2324 dist >>= 7; /* from now on, all distances are divided by 128 */
2325 for (; code < D_CODES; code++) {
2326 base_dist[code] = dist << 7;
2327 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
2328 dist_code[256 + dist++] = (uch) code;
2329 }
2330 }
2331 Assert(dist == 256, "ct_init: 256+dist != 512");
Eric Andersencc8ed391999-10-05 16:24:54 +00002332
Erik Andersene49d5ec2000-02-08 19:58:47 +00002333 /* Construct the codes of the static literal tree */
2334 for (bits = 0; bits <= MAX_BITS; bits++)
2335 bl_count[bits] = 0;
2336 n = 0;
2337 while (n <= 143)
2338 static_ltree[n++].Len = 8, bl_count[8]++;
2339 while (n <= 255)
2340 static_ltree[n++].Len = 9, bl_count[9]++;
2341 while (n <= 279)
2342 static_ltree[n++].Len = 7, bl_count[7]++;
2343 while (n <= 287)
2344 static_ltree[n++].Len = 8, bl_count[8]++;
2345 /* Codes 286 and 287 do not exist, but we must include them in the
2346 * tree construction to get a canonical Huffman tree (longest code
2347 * all ones)
2348 */
2349 gen_codes((ct_data near *) static_ltree, L_CODES + 1);
Eric Andersencc8ed391999-10-05 16:24:54 +00002350
Erik Andersene49d5ec2000-02-08 19:58:47 +00002351 /* The static distance tree is trivial: */
2352 for (n = 0; n < D_CODES; n++) {
2353 static_dtree[n].Len = 5;
2354 static_dtree[n].Code = bi_reverse(n, 5);
2355 }
2356
2357 /* Initialize the first block of the first file: */
2358 init_block();
Eric Andersencc8ed391999-10-05 16:24:54 +00002359}
2360
2361/* ===========================================================================
2362 * Initialize a new block.
2363 */
2364local void init_block()
2365{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002366 int n; /* iterates over tree elements */
Eric Andersencc8ed391999-10-05 16:24:54 +00002367
Erik Andersene49d5ec2000-02-08 19:58:47 +00002368 /* Initialize the trees. */
2369 for (n = 0; n < L_CODES; n++)
2370 dyn_ltree[n].Freq = 0;
2371 for (n = 0; n < D_CODES; n++)
2372 dyn_dtree[n].Freq = 0;
2373 for (n = 0; n < BL_CODES; n++)
2374 bl_tree[n].Freq = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00002375
Erik Andersene49d5ec2000-02-08 19:58:47 +00002376 dyn_ltree[END_BLOCK].Freq = 1;
2377 opt_len = static_len = 0L;
2378 last_lit = last_dist = last_flags = 0;
2379 flags = 0;
2380 flag_bit = 1;
Eric Andersencc8ed391999-10-05 16:24:54 +00002381}
2382
2383#define SMALLEST 1
2384/* Index within the heap array of least frequent node in the Huffman tree */
2385
2386
2387/* ===========================================================================
2388 * Remove the smallest element from the heap and recreate the heap with
2389 * one less element. Updates heap and heap_len.
2390 */
2391#define pqremove(tree, top) \
2392{\
2393 top = heap[SMALLEST]; \
2394 heap[SMALLEST] = heap[heap_len--]; \
2395 pqdownheap(tree, SMALLEST); \
2396}
2397
2398/* ===========================================================================
2399 * Compares to subtrees, using the tree depth as tie breaker when
2400 * the subtrees have equal frequency. This minimizes the worst case length.
2401 */
2402#define smaller(tree, n, m) \
2403 (tree[n].Freq < tree[m].Freq || \
2404 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
2405
2406/* ===========================================================================
2407 * Restore the heap property by moving down the tree starting at node k,
2408 * exchanging a node with the smallest of its two sons if necessary, stopping
2409 * when the heap property is re-established (each father smaller than its
2410 * two sons).
2411 */
2412local void pqdownheap(tree, k)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002413ct_data near *tree; /* the tree to restore */
2414int k; /* node to move down */
Eric Andersencc8ed391999-10-05 16:24:54 +00002415{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002416 int v = heap[k];
2417 int j = k << 1; /* left son of k */
Eric Andersencc8ed391999-10-05 16:24:54 +00002418
Erik Andersene49d5ec2000-02-08 19:58:47 +00002419 while (j <= heap_len) {
2420 /* Set j to the smallest of the two sons: */
2421 if (j < heap_len && smaller(tree, heap[j + 1], heap[j]))
2422 j++;
Eric Andersencc8ed391999-10-05 16:24:54 +00002423
Erik Andersene49d5ec2000-02-08 19:58:47 +00002424 /* Exit if v is smaller than both sons */
2425 if (smaller(tree, v, heap[j]))
2426 break;
Eric Andersencc8ed391999-10-05 16:24:54 +00002427
Erik Andersene49d5ec2000-02-08 19:58:47 +00002428 /* Exchange v with the smallest son */
2429 heap[k] = heap[j];
2430 k = j;
2431
2432 /* And continue down the tree, setting j to the left son of k */
2433 j <<= 1;
2434 }
2435 heap[k] = v;
Eric Andersencc8ed391999-10-05 16:24:54 +00002436}
2437
2438/* ===========================================================================
2439 * Compute the optimal bit lengths for a tree and update the total bit length
2440 * for the current block.
2441 * IN assertion: the fields freq and dad are set, heap[heap_max] and
2442 * above are the tree nodes sorted by increasing frequency.
2443 * OUT assertions: the field len is set to the optimal bit length, the
2444 * array bl_count contains the frequencies for each bit length.
2445 * The length opt_len is updated; static_len is also updated if stree is
2446 * not null.
2447 */
2448local void gen_bitlen(desc)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002449tree_desc near *desc; /* the tree descriptor */
Eric Andersencc8ed391999-10-05 16:24:54 +00002450{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002451 ct_data near *tree = desc->dyn_tree;
2452 int near *extra = desc->extra_bits;
2453 int base = desc->extra_base;
2454 int max_code = desc->max_code;
2455 int max_length = desc->max_length;
2456 ct_data near *stree = desc->static_tree;
2457 int h; /* heap index */
2458 int n, m; /* iterate over the tree elements */
2459 int bits; /* bit length */
2460 int xbits; /* extra bits */
2461 ush f; /* frequency */
2462 int overflow = 0; /* number of elements with bit length too large */
Eric Andersencc8ed391999-10-05 16:24:54 +00002463
Erik Andersene49d5ec2000-02-08 19:58:47 +00002464 for (bits = 0; bits <= MAX_BITS; bits++)
2465 bl_count[bits] = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00002466
Erik Andersene49d5ec2000-02-08 19:58:47 +00002467 /* In a first pass, compute the optimal bit lengths (which may
2468 * overflow in the case of the bit length tree).
2469 */
2470 tree[heap[heap_max]].Len = 0; /* root of the heap */
Eric Andersencc8ed391999-10-05 16:24:54 +00002471
Erik Andersene49d5ec2000-02-08 19:58:47 +00002472 for (h = heap_max + 1; h < HEAP_SIZE; h++) {
2473 n = heap[h];
2474 bits = tree[tree[n].Dad].Len + 1;
2475 if (bits > max_length)
2476 bits = max_length, overflow++;
2477 tree[n].Len = (ush) bits;
2478 /* We overwrite tree[n].Dad which is no longer needed */
Eric Andersencc8ed391999-10-05 16:24:54 +00002479
Erik Andersene49d5ec2000-02-08 19:58:47 +00002480 if (n > max_code)
2481 continue; /* not a leaf node */
Eric Andersencc8ed391999-10-05 16:24:54 +00002482
Erik Andersene49d5ec2000-02-08 19:58:47 +00002483 bl_count[bits]++;
2484 xbits = 0;
2485 if (n >= base)
2486 xbits = extra[n - base];
2487 f = tree[n].Freq;
2488 opt_len += (ulg) f *(bits + xbits);
Eric Andersencc8ed391999-10-05 16:24:54 +00002489
Erik Andersene49d5ec2000-02-08 19:58:47 +00002490 if (stree)
2491 static_len += (ulg) f *(stree[n].Len + xbits);
2492 }
2493 if (overflow == 0)
2494 return;
Eric Andersencc8ed391999-10-05 16:24:54 +00002495
Erik Andersene49d5ec2000-02-08 19:58:47 +00002496 Trace((stderr, "\nbit length overflow\n"));
2497 /* This happens for example on obj2 and pic of the Calgary corpus */
Eric Andersencc8ed391999-10-05 16:24:54 +00002498
Erik Andersene49d5ec2000-02-08 19:58:47 +00002499 /* Find the first bit length which could increase: */
2500 do {
2501 bits = max_length - 1;
2502 while (bl_count[bits] == 0)
2503 bits--;
2504 bl_count[bits]--; /* move one leaf down the tree */
2505 bl_count[bits + 1] += 2; /* move one overflow item as its brother */
2506 bl_count[max_length]--;
2507 /* The brother of the overflow item also moves one step up,
2508 * but this does not affect bl_count[max_length]
2509 */
2510 overflow -= 2;
2511 } while (overflow > 0);
2512
2513 /* Now recompute all bit lengths, scanning in increasing frequency.
2514 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
2515 * lengths instead of fixing only the wrong ones. This idea is taken
2516 * from 'ar' written by Haruhiko Okumura.)
2517 */
2518 for (bits = max_length; bits != 0; bits--) {
2519 n = bl_count[bits];
2520 while (n != 0) {
2521 m = heap[--h];
2522 if (m > max_code)
2523 continue;
2524 if (tree[m].Len != (unsigned) bits) {
2525 Trace(
2526 (stderr, "code %d bits %d->%d\n", m, tree[m].Len,
2527 bits));
2528 opt_len +=
2529 ((long) bits -
2530 (long) tree[m].Len) * (long) tree[m].Freq;
2531 tree[m].Len = (ush) bits;
2532 }
2533 n--;
2534 }
2535 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002536}
2537
2538/* ===========================================================================
2539 * Generate the codes for a given tree and bit counts (which need not be
2540 * optimal).
2541 * IN assertion: the array bl_count contains the bit length statistics for
2542 * the given tree and the field len is set for all tree elements.
2543 * OUT assertion: the field code is set for all tree elements of non
2544 * zero code length.
2545 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00002546local void gen_codes(tree, max_code)
2547ct_data near *tree; /* the tree to decorate */
2548int max_code; /* largest code with non zero frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002549{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002550 ush next_code[MAX_BITS + 1]; /* next code value for each bit length */
2551 ush code = 0; /* running code value */
2552 int bits; /* bit index */
2553 int n; /* code index */
Eric Andersencc8ed391999-10-05 16:24:54 +00002554
Erik Andersene49d5ec2000-02-08 19:58:47 +00002555 /* The distribution counts are first used to generate the code values
2556 * without bit reversal.
2557 */
2558 for (bits = 1; bits <= MAX_BITS; bits++) {
2559 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
2560 }
2561 /* Check that the bit counts in bl_count are consistent. The last code
2562 * must be all ones.
2563 */
2564 Assert(code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
2565 "inconsistent bit counts");
2566 Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
Eric Andersencc8ed391999-10-05 16:24:54 +00002567
Erik Andersene49d5ec2000-02-08 19:58:47 +00002568 for (n = 0; n <= max_code; n++) {
2569 int len = tree[n].Len;
Eric Andersencc8ed391999-10-05 16:24:54 +00002570
Erik Andersene49d5ec2000-02-08 19:58:47 +00002571 if (len == 0)
2572 continue;
2573 /* Now reverse the bits */
2574 tree[n].Code = bi_reverse(next_code[len]++, len);
2575
2576 Tracec(tree != static_ltree,
2577 (stderr, "\nn %3d %c l %2d c %4x (%x) ", n,
2578 (isgraph(n) ? n : ' '), len, tree[n].Code,
2579 next_code[len] - 1));
2580 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002581}
2582
2583/* ===========================================================================
2584 * Construct one Huffman tree and assigns the code bit strings and lengths.
2585 * Update the total bit length for the current block.
2586 * IN assertion: the field freq is set for all tree elements.
2587 * OUT assertions: the fields len and code are set to the optimal bit length
2588 * and corresponding code. The length opt_len is updated; static_len is
2589 * also updated if stree is not null. The field max_code is set.
2590 */
2591local void build_tree(desc)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002592tree_desc near *desc; /* the tree descriptor */
Eric Andersencc8ed391999-10-05 16:24:54 +00002593{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002594 ct_data near *tree = desc->dyn_tree;
2595 ct_data near *stree = desc->static_tree;
2596 int elems = desc->elems;
2597 int n, m; /* iterate over heap elements */
2598 int max_code = -1; /* largest code with non zero frequency */
2599 int node = elems; /* next internal node of the tree */
Eric Andersencc8ed391999-10-05 16:24:54 +00002600
Erik Andersene49d5ec2000-02-08 19:58:47 +00002601 /* Construct the initial heap, with least frequent element in
2602 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
2603 * heap[0] is not used.
2604 */
2605 heap_len = 0, heap_max = HEAP_SIZE;
Eric Andersencc8ed391999-10-05 16:24:54 +00002606
Erik Andersene49d5ec2000-02-08 19:58:47 +00002607 for (n = 0; n < elems; n++) {
2608 if (tree[n].Freq != 0) {
2609 heap[++heap_len] = max_code = n;
2610 depth[n] = 0;
2611 } else {
2612 tree[n].Len = 0;
2613 }
2614 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002615
Erik Andersene49d5ec2000-02-08 19:58:47 +00002616 /* The pkzip format requires that at least one distance code exists,
2617 * and that at least one bit should be sent even if there is only one
2618 * possible code. So to avoid special checks later on we force at least
2619 * two codes of non zero frequency.
2620 */
2621 while (heap_len < 2) {
2622 int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
Eric Andersencc8ed391999-10-05 16:24:54 +00002623
Erik Andersene49d5ec2000-02-08 19:58:47 +00002624 tree[new].Freq = 1;
2625 depth[new] = 0;
2626 opt_len--;
2627 if (stree)
2628 static_len -= stree[new].Len;
2629 /* new is 0 or 1 so it does not have extra bits */
2630 }
2631 desc->max_code = max_code;
Eric Andersencc8ed391999-10-05 16:24:54 +00002632
Erik Andersene49d5ec2000-02-08 19:58:47 +00002633 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
2634 * establish sub-heaps of increasing lengths:
2635 */
2636 for (n = heap_len / 2; n >= 1; n--)
2637 pqdownheap(tree, n);
Eric Andersencc8ed391999-10-05 16:24:54 +00002638
Erik Andersene49d5ec2000-02-08 19:58:47 +00002639 /* Construct the Huffman tree by repeatedly combining the least two
2640 * frequent nodes.
2641 */
2642 do {
2643 pqremove(tree, n); /* n = node of least frequency */
2644 m = heap[SMALLEST]; /* m = node of next least frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002645
Erik Andersene49d5ec2000-02-08 19:58:47 +00002646 heap[--heap_max] = n; /* keep the nodes sorted by frequency */
2647 heap[--heap_max] = m;
2648
2649 /* Create a new node father of n and m */
2650 tree[node].Freq = tree[n].Freq + tree[m].Freq;
2651 depth[node] = (uch) (MAX(depth[n], depth[m]) + 1);
2652 tree[n].Dad = tree[m].Dad = (ush) node;
Eric Andersencc8ed391999-10-05 16:24:54 +00002653#ifdef DUMP_BL_TREE
Erik Andersene49d5ec2000-02-08 19:58:47 +00002654 if (tree == bl_tree) {
2655 fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)",
2656 node, tree[node].Freq, n, tree[n].Freq, m,
2657 tree[m].Freq);
2658 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002659#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00002660 /* and insert the new node in the heap */
2661 heap[SMALLEST] = node++;
2662 pqdownheap(tree, SMALLEST);
Eric Andersencc8ed391999-10-05 16:24:54 +00002663
Erik Andersene49d5ec2000-02-08 19:58:47 +00002664 } while (heap_len >= 2);
Eric Andersencc8ed391999-10-05 16:24:54 +00002665
Erik Andersene49d5ec2000-02-08 19:58:47 +00002666 heap[--heap_max] = heap[SMALLEST];
Eric Andersencc8ed391999-10-05 16:24:54 +00002667
Erik Andersene49d5ec2000-02-08 19:58:47 +00002668 /* At this point, the fields freq and dad are set. We can now
2669 * generate the bit lengths.
2670 */
2671 gen_bitlen((tree_desc near *) desc);
Eric Andersencc8ed391999-10-05 16:24:54 +00002672
Erik Andersene49d5ec2000-02-08 19:58:47 +00002673 /* The field len is now set, we can generate the bit codes */
2674 gen_codes((ct_data near *) tree, max_code);
Eric Andersencc8ed391999-10-05 16:24:54 +00002675}
2676
2677/* ===========================================================================
2678 * Scan a literal or distance tree to determine the frequencies of the codes
2679 * in the bit length tree. Updates opt_len to take into account the repeat
2680 * counts. (The contribution of the bit length codes will be added later
2681 * during the construction of bl_tree.)
2682 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00002683local void scan_tree(tree, max_code)
2684ct_data near *tree; /* the tree to be scanned */
2685int max_code; /* and its largest code of non zero frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002686{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002687 int n; /* iterates over all tree elements */
2688 int prevlen = -1; /* last emitted length */
2689 int curlen; /* length of current code */
2690 int nextlen = tree[0].Len; /* length of next code */
2691 int count = 0; /* repeat count of the current code */
2692 int max_count = 7; /* max repeat count */
2693 int min_count = 4; /* min repeat count */
Eric Andersencc8ed391999-10-05 16:24:54 +00002694
Erik Andersene49d5ec2000-02-08 19:58:47 +00002695 if (nextlen == 0)
2696 max_count = 138, min_count = 3;
2697 tree[max_code + 1].Len = (ush) 0xffff; /* guard */
Eric Andersencc8ed391999-10-05 16:24:54 +00002698
Erik Andersene49d5ec2000-02-08 19:58:47 +00002699 for (n = 0; n <= max_code; n++) {
2700 curlen = nextlen;
2701 nextlen = tree[n + 1].Len;
2702 if (++count < max_count && curlen == nextlen) {
2703 continue;
2704 } else if (count < min_count) {
2705 bl_tree[curlen].Freq += count;
2706 } else if (curlen != 0) {
2707 if (curlen != prevlen)
2708 bl_tree[curlen].Freq++;
2709 bl_tree[REP_3_6].Freq++;
2710 } else if (count <= 10) {
2711 bl_tree[REPZ_3_10].Freq++;
2712 } else {
2713 bl_tree[REPZ_11_138].Freq++;
2714 }
2715 count = 0;
2716 prevlen = curlen;
2717 if (nextlen == 0) {
2718 max_count = 138, min_count = 3;
2719 } else if (curlen == nextlen) {
2720 max_count = 6, min_count = 3;
2721 } else {
2722 max_count = 7, min_count = 4;
2723 }
2724 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002725}
2726
2727/* ===========================================================================
2728 * Send a literal or distance tree in compressed form, using the codes in
2729 * bl_tree.
2730 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00002731local void send_tree(tree, max_code)
2732ct_data near *tree; /* the tree to be scanned */
2733int max_code; /* and its largest code of non zero frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002734{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002735 int n; /* iterates over all tree elements */
2736 int prevlen = -1; /* last emitted length */
2737 int curlen; /* length of current code */
2738 int nextlen = tree[0].Len; /* length of next code */
2739 int count = 0; /* repeat count of the current code */
2740 int max_count = 7; /* max repeat count */
2741 int min_count = 4; /* min repeat count */
Eric Andersencc8ed391999-10-05 16:24:54 +00002742
Erik Andersene49d5ec2000-02-08 19:58:47 +00002743/* tree[max_code+1].Len = -1; *//* guard already set */
2744 if (nextlen == 0)
2745 max_count = 138, min_count = 3;
Eric Andersencc8ed391999-10-05 16:24:54 +00002746
Erik Andersene49d5ec2000-02-08 19:58:47 +00002747 for (n = 0; n <= max_code; n++) {
2748 curlen = nextlen;
2749 nextlen = tree[n + 1].Len;
2750 if (++count < max_count && curlen == nextlen) {
2751 continue;
2752 } else if (count < min_count) {
2753 do {
2754 send_code(curlen, bl_tree);
2755 } while (--count != 0);
Eric Andersencc8ed391999-10-05 16:24:54 +00002756
Erik Andersene49d5ec2000-02-08 19:58:47 +00002757 } else if (curlen != 0) {
2758 if (curlen != prevlen) {
2759 send_code(curlen, bl_tree);
2760 count--;
2761 }
2762 Assert(count >= 3 && count <= 6, " 3_6?");
2763 send_code(REP_3_6, bl_tree);
2764 send_bits(count - 3, 2);
Eric Andersencc8ed391999-10-05 16:24:54 +00002765
Erik Andersene49d5ec2000-02-08 19:58:47 +00002766 } else if (count <= 10) {
2767 send_code(REPZ_3_10, bl_tree);
2768 send_bits(count - 3, 3);
Eric Andersencc8ed391999-10-05 16:24:54 +00002769
Erik Andersene49d5ec2000-02-08 19:58:47 +00002770 } else {
2771 send_code(REPZ_11_138, bl_tree);
2772 send_bits(count - 11, 7);
2773 }
2774 count = 0;
2775 prevlen = curlen;
2776 if (nextlen == 0) {
2777 max_count = 138, min_count = 3;
2778 } else if (curlen == nextlen) {
2779 max_count = 6, min_count = 3;
2780 } else {
2781 max_count = 7, min_count = 4;
2782 }
2783 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002784}
2785
2786/* ===========================================================================
2787 * Construct the Huffman tree for the bit lengths and return the index in
2788 * bl_order of the last bit length code to send.
2789 */
2790local int build_bl_tree()
2791{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002792 int max_blindex; /* index of last bit length code of non zero freq */
Eric Andersencc8ed391999-10-05 16:24:54 +00002793
Erik Andersene49d5ec2000-02-08 19:58:47 +00002794 /* Determine the bit length frequencies for literal and distance trees */
2795 scan_tree((ct_data near *) dyn_ltree, l_desc.max_code);
2796 scan_tree((ct_data near *) dyn_dtree, d_desc.max_code);
Eric Andersencc8ed391999-10-05 16:24:54 +00002797
Erik Andersene49d5ec2000-02-08 19:58:47 +00002798 /* Build the bit length tree: */
2799 build_tree((tree_desc near *) (&bl_desc));
2800 /* opt_len now includes the length of the tree representations, except
2801 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
2802 */
Eric Andersencc8ed391999-10-05 16:24:54 +00002803
Erik Andersene49d5ec2000-02-08 19:58:47 +00002804 /* Determine the number of bit length codes to send. The pkzip format
2805 * requires that at least 4 bit length codes be sent. (appnote.txt says
2806 * 3 but the actual value used is 4.)
2807 */
2808 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
2809 if (bl_tree[bl_order[max_blindex]].Len != 0)
2810 break;
2811 }
2812 /* Update opt_len to include the bit length tree and counts */
2813 opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
2814 Tracev(
2815 (stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len,
2816 static_len));
Eric Andersencc8ed391999-10-05 16:24:54 +00002817
Erik Andersene49d5ec2000-02-08 19:58:47 +00002818 return max_blindex;
Eric Andersencc8ed391999-10-05 16:24:54 +00002819}
2820
2821/* ===========================================================================
2822 * Send the header for a block using dynamic Huffman trees: the counts, the
2823 * lengths of the bit length codes, the literal tree and the distance tree.
2824 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
2825 */
2826local void send_all_trees(lcodes, dcodes, blcodes)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002827int lcodes, dcodes, blcodes; /* number of codes for each tree */
Eric Andersencc8ed391999-10-05 16:24:54 +00002828{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002829 int rank; /* index in bl_order */
Eric Andersencc8ed391999-10-05 16:24:54 +00002830
Erik Andersene49d5ec2000-02-08 19:58:47 +00002831 Assert(lcodes >= 257 && dcodes >= 1
2832 && blcodes >= 4, "not enough codes");
2833 Assert(lcodes <= L_CODES && dcodes <= D_CODES
2834 && blcodes <= BL_CODES, "too many codes");
2835 Tracev((stderr, "\nbl counts: "));
2836 send_bits(lcodes - 257, 5); /* not +255 as stated in appnote.txt */
2837 send_bits(dcodes - 1, 5);
2838 send_bits(blcodes - 4, 4); /* not -3 as stated in appnote.txt */
2839 for (rank = 0; rank < blcodes; rank++) {
2840 Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
2841 send_bits(bl_tree[bl_order[rank]].Len, 3);
2842 }
2843 Tracev((stderr, "\nbl tree: sent %ld", bits_sent));
Eric Andersencc8ed391999-10-05 16:24:54 +00002844
Erik Andersene49d5ec2000-02-08 19:58:47 +00002845 send_tree((ct_data near *) dyn_ltree, lcodes - 1); /* send the literal tree */
2846 Tracev((stderr, "\nlit tree: sent %ld", bits_sent));
Eric Andersencc8ed391999-10-05 16:24:54 +00002847
Erik Andersene49d5ec2000-02-08 19:58:47 +00002848 send_tree((ct_data near *) dyn_dtree, dcodes - 1); /* send the distance tree */
2849 Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
Eric Andersencc8ed391999-10-05 16:24:54 +00002850}
2851
2852/* ===========================================================================
2853 * Determine the best encoding for the current block: dynamic trees, static
2854 * trees or store, and output the encoded block to the zip file. This function
2855 * returns the total compressed length for the file so far.
2856 */
2857ulg flush_block(buf, stored_len, eof)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002858char *buf; /* input block, or NULL if too old */
2859ulg stored_len; /* length of input block */
2860int eof; /* true if this is the last block for a file */
Eric Andersencc8ed391999-10-05 16:24:54 +00002861{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002862 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
2863 int max_blindex; /* index of last bit length code of non zero freq */
Eric Andersencc8ed391999-10-05 16:24:54 +00002864
Erik Andersene49d5ec2000-02-08 19:58:47 +00002865 flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
Eric Andersencc8ed391999-10-05 16:24:54 +00002866
Erik Andersene49d5ec2000-02-08 19:58:47 +00002867 /* Check if the file is ascii or binary */
2868 if (*file_type == (ush) UNKNOWN)
2869 set_file_type();
Eric Andersencc8ed391999-10-05 16:24:54 +00002870
Erik Andersene49d5ec2000-02-08 19:58:47 +00002871 /* Construct the literal and distance trees */
2872 build_tree((tree_desc near *) (&l_desc));
2873 Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
Eric Andersencc8ed391999-10-05 16:24:54 +00002874
Erik Andersene49d5ec2000-02-08 19:58:47 +00002875 build_tree((tree_desc near *) (&d_desc));
2876 Tracev(
2877 (stderr, "\ndist data: dyn %ld, stat %ld", opt_len,
2878 static_len));
2879 /* At this point, opt_len and static_len are the total bit lengths of
2880 * the compressed block data, excluding the tree representations.
2881 */
Eric Andersencc8ed391999-10-05 16:24:54 +00002882
Erik Andersene49d5ec2000-02-08 19:58:47 +00002883 /* Build the bit length tree for the above two trees, and get the index
2884 * in bl_order of the last bit length code to send.
2885 */
2886 max_blindex = build_bl_tree();
Eric Andersencc8ed391999-10-05 16:24:54 +00002887
Erik Andersene49d5ec2000-02-08 19:58:47 +00002888 /* Determine the best encoding. Compute first the block length in bytes */
2889 opt_lenb = (opt_len + 3 + 7) >> 3;
2890 static_lenb = (static_len + 3 + 7) >> 3;
2891 input_len += stored_len; /* for debugging only */
Eric Andersencc8ed391999-10-05 16:24:54 +00002892
Erik Andersene49d5ec2000-02-08 19:58:47 +00002893 Trace(
2894 (stderr,
2895 "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
2896 opt_lenb, opt_len, static_lenb, static_len, stored_len,
2897 last_lit, last_dist));
Eric Andersencc8ed391999-10-05 16:24:54 +00002898
Erik Andersene49d5ec2000-02-08 19:58:47 +00002899 if (static_lenb <= opt_lenb)
2900 opt_lenb = static_lenb;
Eric Andersencc8ed391999-10-05 16:24:54 +00002901
Erik Andersene49d5ec2000-02-08 19:58:47 +00002902 /* If compression failed and this is the first and last block,
2903 * and if the zip file can be seeked (to rewrite the local header),
2904 * the whole file is transformed into a stored file:
2905 */
Eric Andersencc8ed391999-10-05 16:24:54 +00002906#ifdef FORCE_METHOD
2907#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00002908 if (stored_len <= opt_lenb && eof && compressed_len == 0L
2909 && seekable()) {
Eric Andersencc8ed391999-10-05 16:24:54 +00002910#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00002911 /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
2912 if (buf == (char *) 0)
Erik Andersen9ffdaa62000-02-11 21:55:04 +00002913 errorMsg("block vanished");
Eric Andersencc8ed391999-10-05 16:24:54 +00002914
Erik Andersene49d5ec2000-02-08 19:58:47 +00002915 copy_block(buf, (unsigned) stored_len, 0); /* without header */
2916 compressed_len = stored_len << 3;
2917 *file_method = STORED;
Eric Andersencc8ed391999-10-05 16:24:54 +00002918
2919#ifdef FORCE_METHOD
2920#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00002921 } else if (stored_len + 4 <= opt_lenb && buf != (char *) 0) {
2922 /* 4: two words for the lengths */
Eric Andersencc8ed391999-10-05 16:24:54 +00002923#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00002924 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
2925 * Otherwise we can't have processed more than WSIZE input bytes since
2926 * the last block flush, because compression would have been
2927 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
2928 * transform a block into a stored block.
2929 */
2930 send_bits((STORED_BLOCK << 1) + eof, 3); /* send block type */
2931 compressed_len = (compressed_len + 3 + 7) & ~7L;
2932 compressed_len += (stored_len + 4) << 3;
Eric Andersencc8ed391999-10-05 16:24:54 +00002933
Erik Andersene49d5ec2000-02-08 19:58:47 +00002934 copy_block(buf, (unsigned) stored_len, 1); /* with header */
Eric Andersencc8ed391999-10-05 16:24:54 +00002935
2936#ifdef FORCE_METHOD
2937#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00002938 } else if (static_lenb == opt_lenb) {
Eric Andersencc8ed391999-10-05 16:24:54 +00002939#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00002940 send_bits((STATIC_TREES << 1) + eof, 3);
2941 compress_block((ct_data near *) static_ltree,
2942 (ct_data near *) static_dtree);
2943 compressed_len += 3 + static_len;
2944 } else {
2945 send_bits((DYN_TREES << 1) + eof, 3);
2946 send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1,
2947 max_blindex + 1);
2948 compress_block((ct_data near *) dyn_ltree,
2949 (ct_data near *) dyn_dtree);
2950 compressed_len += 3 + opt_len;
2951 }
2952 Assert(compressed_len == bits_sent, "bad compressed size");
2953 init_block();
Eric Andersencc8ed391999-10-05 16:24:54 +00002954
Erik Andersene49d5ec2000-02-08 19:58:47 +00002955 if (eof) {
2956 Assert(input_len == isize, "bad input size");
2957 bi_windup();
2958 compressed_len += 7; /* align on byte boundary */
2959 }
2960 Tracev((stderr, "\ncomprlen %lu(%lu) ", compressed_len >> 3,
2961 compressed_len - 7 * eof));
Eric Andersencc8ed391999-10-05 16:24:54 +00002962
Erik Andersene49d5ec2000-02-08 19:58:47 +00002963 return compressed_len >> 3;
Eric Andersencc8ed391999-10-05 16:24:54 +00002964}
2965
2966/* ===========================================================================
2967 * Save the match info and tally the frequency counts. Return true if
2968 * the current block must be flushed.
2969 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00002970int ct_tally(dist, lc)
2971int dist; /* distance of matched string */
2972int lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
Eric Andersencc8ed391999-10-05 16:24:54 +00002973{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002974 l_buf[last_lit++] = (uch) lc;
2975 if (dist == 0) {
2976 /* lc is the unmatched char */
2977 dyn_ltree[lc].Freq++;
2978 } else {
2979 /* Here, lc is the match length - MIN_MATCH */
2980 dist--; /* dist = match distance - 1 */
2981 Assert((ush) dist < (ush) MAX_DIST &&
2982 (ush) lc <= (ush) (MAX_MATCH - MIN_MATCH) &&
2983 (ush) d_code(dist) < (ush) D_CODES, "ct_tally: bad match");
Eric Andersencc8ed391999-10-05 16:24:54 +00002984
Erik Andersene49d5ec2000-02-08 19:58:47 +00002985 dyn_ltree[length_code[lc] + LITERALS + 1].Freq++;
2986 dyn_dtree[d_code(dist)].Freq++;
Eric Andersencc8ed391999-10-05 16:24:54 +00002987
Erik Andersene49d5ec2000-02-08 19:58:47 +00002988 d_buf[last_dist++] = (ush) dist;
2989 flags |= flag_bit;
2990 }
2991 flag_bit <<= 1;
Eric Andersencc8ed391999-10-05 16:24:54 +00002992
Erik Andersene49d5ec2000-02-08 19:58:47 +00002993 /* Output the flags if they fill a byte: */
2994 if ((last_lit & 7) == 0) {
2995 flag_buf[last_flags++] = flags;
2996 flags = 0, flag_bit = 1;
2997 }
2998 /* Try to guess if it is profitable to stop the current block here */
2999 if ((last_lit & 0xfff) == 0) {
3000 /* Compute an upper bound for the compressed length */
3001 ulg out_length = (ulg) last_lit * 8L;
3002 ulg in_length = (ulg) strstart - block_start;
3003 int dcode;
3004
3005 for (dcode = 0; dcode < D_CODES; dcode++) {
3006 out_length +=
3007 (ulg) dyn_dtree[dcode].Freq * (5L + extra_dbits[dcode]);
3008 }
3009 out_length >>= 3;
3010 Trace(
3011 (stderr,
3012 "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
3013 last_lit, last_dist, in_length, out_length,
3014 100L - out_length * 100L / in_length));
3015 if (last_dist < last_lit / 2 && out_length < in_length / 2)
3016 return 1;
3017 }
3018 return (last_lit == LIT_BUFSIZE - 1 || last_dist == DIST_BUFSIZE);
3019 /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
3020 * on 16 bit machines and because stored blocks are restricted to
3021 * 64K-1 bytes.
3022 */
Eric Andersencc8ed391999-10-05 16:24:54 +00003023}
3024
3025/* ===========================================================================
3026 * Send the block data compressed using the given Huffman trees
3027 */
3028local void compress_block(ltree, dtree)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003029ct_data near *ltree; /* literal tree */
3030ct_data near *dtree; /* distance tree */
Eric Andersencc8ed391999-10-05 16:24:54 +00003031{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003032 unsigned dist; /* distance of matched string */
3033 int lc; /* match length or unmatched char (if dist == 0) */
3034 unsigned lx = 0; /* running index in l_buf */
3035 unsigned dx = 0; /* running index in d_buf */
3036 unsigned fx = 0; /* running index in flag_buf */
3037 uch flag = 0; /* current flags */
3038 unsigned code; /* the code to send */
3039 int extra; /* number of extra bits to send */
Eric Andersencc8ed391999-10-05 16:24:54 +00003040
Erik Andersene49d5ec2000-02-08 19:58:47 +00003041 if (last_lit != 0)
3042 do {
3043 if ((lx & 7) == 0)
3044 flag = flag_buf[fx++];
3045 lc = l_buf[lx++];
3046 if ((flag & 1) == 0) {
3047 send_code(lc, ltree); /* send a literal byte */
3048 Tracecv(isgraph(lc), (stderr, " '%c' ", lc));
3049 } else {
3050 /* Here, lc is the match length - MIN_MATCH */
3051 code = length_code[lc];
3052 send_code(code + LITERALS + 1, ltree); /* send the length code */
3053 extra = extra_lbits[code];
3054 if (extra != 0) {
3055 lc -= base_length[code];
3056 send_bits(lc, extra); /* send the extra length bits */
3057 }
3058 dist = d_buf[dx++];
3059 /* Here, dist is the match distance - 1 */
3060 code = d_code(dist);
3061 Assert(code < D_CODES, "bad d_code");
Eric Andersencc8ed391999-10-05 16:24:54 +00003062
Erik Andersene49d5ec2000-02-08 19:58:47 +00003063 send_code(code, dtree); /* send the distance code */
3064 extra = extra_dbits[code];
3065 if (extra != 0) {
3066 dist -= base_dist[code];
3067 send_bits(dist, extra); /* send the extra distance bits */
3068 }
3069 } /* literal or match pair ? */
3070 flag >>= 1;
3071 } while (lx < last_lit);
Eric Andersencc8ed391999-10-05 16:24:54 +00003072
Erik Andersene49d5ec2000-02-08 19:58:47 +00003073 send_code(END_BLOCK, ltree);
Eric Andersencc8ed391999-10-05 16:24:54 +00003074}
3075
3076/* ===========================================================================
3077 * Set the file type to ASCII or BINARY, using a crude approximation:
3078 * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
3079 * IN assertion: the fields freq of dyn_ltree are set and the total of all
3080 * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
3081 */
3082local void set_file_type()
3083{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003084 int n = 0;
3085 unsigned ascii_freq = 0;
3086 unsigned bin_freq = 0;
3087
3088 while (n < 7)
3089 bin_freq += dyn_ltree[n++].Freq;
3090 while (n < 128)
3091 ascii_freq += dyn_ltree[n++].Freq;
3092 while (n < LITERALS)
3093 bin_freq += dyn_ltree[n++].Freq;
3094 *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
3095 if (*file_type == BINARY && translate_eol) {
Erik Andersen825aead2000-04-07 06:00:07 +00003096 errorMsg("-l used on binary file");
Erik Andersene49d5ec2000-02-08 19:58:47 +00003097 }
Eric Andersencc8ed391999-10-05 16:24:54 +00003098}
Erik Andersene49d5ec2000-02-08 19:58:47 +00003099
Eric Andersencc8ed391999-10-05 16:24:54 +00003100/* util.c -- utility functions for gzip support
3101 * Copyright (C) 1992-1993 Jean-loup Gailly
3102 * This is free software; you can redistribute it and/or modify it under the
3103 * terms of the GNU General Public License, see the file COPYING.
3104 */
3105
Eric Andersencc8ed391999-10-05 16:24:54 +00003106#include <ctype.h>
3107#include <errno.h>
3108#include <sys/types.h>
3109
3110#ifdef HAVE_UNISTD_H
3111# include <unistd.h>
3112#endif
3113#ifndef NO_FCNTL_H
3114# include <fcntl.h>
3115#endif
3116
3117#if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
3118# include <stdlib.h>
3119#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00003120extern int errno;
Eric Andersencc8ed391999-10-05 16:24:54 +00003121#endif
3122
Eric Andersencc8ed391999-10-05 16:24:54 +00003123/* ===========================================================================
3124 * Copy input to output unchanged: zcat == cat with --force.
3125 * IN assertion: insize bytes have already been read in inbuf.
3126 */
3127int copy(in, out)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003128int in, out; /* input and output file descriptors */
Eric Andersencc8ed391999-10-05 16:24:54 +00003129{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003130 errno = 0;
3131 while (insize != 0 && (int) insize != EOF) {
3132 write_buf(out, (char *) inbuf, insize);
3133 bytes_out += insize;
3134 insize = read(in, (char *) inbuf, INBUFSIZ);
3135 }
3136 if ((int) insize == EOF && errno != 0) {
3137 read_error();
3138 }
3139 bytes_in = bytes_out;
3140 return OK;
Eric Andersencc8ed391999-10-05 16:24:54 +00003141}
3142
3143/* ========================================================================
3144 * Put string s in lower case, return s.
3145 */
3146char *strlwr(s)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003147char *s;
Eric Andersencc8ed391999-10-05 16:24:54 +00003148{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003149 char *t;
3150
3151 for (t = s; *t; t++)
3152 *t = tolow(*t);
3153 return s;
Eric Andersencc8ed391999-10-05 16:24:54 +00003154}
3155
3156#if defined(NO_STRING_H) && !defined(STDC_HEADERS)
3157
3158/* Provide missing strspn and strcspn functions. */
3159
Erik Andersen61677fe2000-04-13 01:18:56 +00003160int strspn (const char *s, const char *accept);
3161int strcspn (const char *s, const char *reject);
Eric Andersencc8ed391999-10-05 16:24:54 +00003162
3163/* ========================================================================
3164 * Return the length of the maximum initial segment
3165 * of s which contains only characters in accept.
3166 */
3167int strspn(s, accept)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003168const char *s;
3169const char *accept;
Eric Andersencc8ed391999-10-05 16:24:54 +00003170{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003171 register const char *p;
3172 register const char *a;
3173 register int count = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00003174
Erik Andersene49d5ec2000-02-08 19:58:47 +00003175 for (p = s; *p != '\0'; ++p) {
3176 for (a = accept; *a != '\0'; ++a) {
3177 if (*p == *a)
3178 break;
3179 }
3180 if (*a == '\0')
3181 return count;
3182 ++count;
Eric Andersencc8ed391999-10-05 16:24:54 +00003183 }
Erik Andersene49d5ec2000-02-08 19:58:47 +00003184 return count;
Eric Andersencc8ed391999-10-05 16:24:54 +00003185}
3186
3187/* ========================================================================
3188 * Return the length of the maximum inital segment of s
3189 * which contains no characters from reject.
3190 */
3191int strcspn(s, reject)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003192const char *s;
3193const char *reject;
Eric Andersencc8ed391999-10-05 16:24:54 +00003194{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003195 register int count = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00003196
Erik Andersene49d5ec2000-02-08 19:58:47 +00003197 while (*s != '\0') {
3198 if (strchr(reject, *s++) != NULL)
3199 return count;
3200 ++count;
3201 }
3202 return count;
Eric Andersencc8ed391999-10-05 16:24:54 +00003203}
3204
Erik Andersene49d5ec2000-02-08 19:58:47 +00003205#endif /* NO_STRING_H */
Eric Andersencc8ed391999-10-05 16:24:54 +00003206
3207/* ========================================================================
3208 * Add an environment variable (if any) before argv, and update argc.
3209 * Return the expanded environment variable to be freed later, or NULL
3210 * if no options were added to argv.
3211 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00003212#define SEPARATOR " \t" /* separators in env variable */
Eric Andersencc8ed391999-10-05 16:24:54 +00003213
3214char *add_envopt(argcp, argvp, env)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003215int *argcp; /* pointer to argc */
3216char ***argvp; /* pointer to argv */
3217char *env; /* name of environment variable */
Eric Andersencc8ed391999-10-05 16:24:54 +00003218{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003219 char *p; /* running pointer through env variable */
3220 char **oargv; /* runs through old argv array */
3221 char **nargv; /* runs through new argv array */
3222 int oargc = *argcp; /* old argc */
3223 int nargc = 0; /* number of arguments in env variable */
Eric Andersencc8ed391999-10-05 16:24:54 +00003224
Erik Andersene49d5ec2000-02-08 19:58:47 +00003225 env = (char *) getenv(env);
3226 if (env == NULL)
3227 return NULL;
Eric Andersencc8ed391999-10-05 16:24:54 +00003228
Erik Andersene49d5ec2000-02-08 19:58:47 +00003229 p = (char *) xmalloc(strlen(env) + 1);
3230 env = strcpy(p, env); /* keep env variable intact */
Eric Andersencc8ed391999-10-05 16:24:54 +00003231
Erik Andersene49d5ec2000-02-08 19:58:47 +00003232 for (p = env; *p; nargc++) { /* move through env */
3233 p += strspn(p, SEPARATOR); /* skip leading separators */
3234 if (*p == '\0')
3235 break;
Eric Andersencc8ed391999-10-05 16:24:54 +00003236
Erik Andersene49d5ec2000-02-08 19:58:47 +00003237 p += strcspn(p, SEPARATOR); /* find end of word */
3238 if (*p)
3239 *p++ = '\0'; /* mark it */
3240 }
3241 if (nargc == 0) {
3242 free(env);
3243 return NULL;
3244 }
3245 *argcp += nargc;
3246 /* Allocate the new argv array, with an extra element just in case
3247 * the original arg list did not end with a NULL.
3248 */
3249 nargv = (char **) calloc(*argcp + 1, sizeof(char *));
Eric Andersencc8ed391999-10-05 16:24:54 +00003250
Erik Andersene49d5ec2000-02-08 19:58:47 +00003251 if (nargv == NULL)
Erik Andersen9ffdaa62000-02-11 21:55:04 +00003252 errorMsg("out of memory");
Erik Andersene49d5ec2000-02-08 19:58:47 +00003253 oargv = *argvp;
3254 *argvp = nargv;
Eric Andersencc8ed391999-10-05 16:24:54 +00003255
Erik Andersene49d5ec2000-02-08 19:58:47 +00003256 /* Copy the program name first */
3257 if (oargc-- < 0)
Erik Andersen9ffdaa62000-02-11 21:55:04 +00003258 errorMsg("argc<=0");
Erik Andersene49d5ec2000-02-08 19:58:47 +00003259 *(nargv++) = *(oargv++);
Eric Andersencc8ed391999-10-05 16:24:54 +00003260
Erik Andersene49d5ec2000-02-08 19:58:47 +00003261 /* Then copy the environment args */
3262 for (p = env; nargc > 0; nargc--) {
3263 p += strspn(p, SEPARATOR); /* skip separators */
3264 *(nargv++) = p; /* store start */
3265 while (*p++); /* skip over word */
3266 }
3267
3268 /* Finally copy the old args and add a NULL (usual convention) */
3269 while (oargc--)
3270 *(nargv++) = *(oargv++);
3271 *nargv = NULL;
3272 return env;
Eric Andersencc8ed391999-10-05 16:24:54 +00003273}
Erik Andersene49d5ec2000-02-08 19:58:47 +00003274
Eric Andersencc8ed391999-10-05 16:24:54 +00003275/* ========================================================================
3276 * Display compression ratio on the given stream on 6 characters.
3277 */
3278void display_ratio(num, den, file)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003279long num;
3280long den;
3281FILE *file;
Eric Andersencc8ed391999-10-05 16:24:54 +00003282{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003283 long ratio; /* 1000 times the compression ratio */
Eric Andersencc8ed391999-10-05 16:24:54 +00003284
Erik Andersene49d5ec2000-02-08 19:58:47 +00003285 if (den == 0) {
3286 ratio = 0; /* no compression */
3287 } else if (den < 2147483L) { /* (2**31 -1)/1000 */
3288 ratio = 1000L * num / den;
3289 } else {
3290 ratio = num / (den / 1000L);
3291 }
3292 if (ratio < 0) {
3293 putc('-', file);
3294 ratio = -ratio;
3295 } else {
3296 putc(' ', file);
3297 }
3298 fprintf(file, "%2ld.%1ld%%", ratio / 10L, ratio % 10L);
Eric Andersencc8ed391999-10-05 16:24:54 +00003299}
3300
3301
3302/* zip.c -- compress files to the gzip or pkzip format
3303 * Copyright (C) 1992-1993 Jean-loup Gailly
3304 * This is free software; you can redistribute it and/or modify it under the
3305 * terms of the GNU General Public License, see the file COPYING.
3306 */
3307
Eric Andersencc8ed391999-10-05 16:24:54 +00003308#include <ctype.h>
3309#include <sys/types.h>
3310
3311#ifdef HAVE_UNISTD_H
3312# include <unistd.h>
3313#endif
3314#ifndef NO_FCNTL_H
3315# include <fcntl.h>
3316#endif
3317
Erik Andersene49d5ec2000-02-08 19:58:47 +00003318local ulg crc; /* crc on uncompressed file data */
3319long header_bytes; /* number of bytes in gzip header */
Eric Andersencc8ed391999-10-05 16:24:54 +00003320
3321/* ===========================================================================
3322 * Deflate in to out.
3323 * IN assertions: the input and output buffers are cleared.
3324 * The variables time_stamp and save_orig_name are initialized.
3325 */
3326int zip(in, out)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003327int in, out; /* input and output file descriptors */
Eric Andersencc8ed391999-10-05 16:24:54 +00003328{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003329 uch flags = 0; /* general purpose bit flags */
3330 ush attr = 0; /* ascii/binary flag */
3331 ush deflate_flags = 0; /* pkzip -es, -en or -ex equivalent */
Eric Andersencc8ed391999-10-05 16:24:54 +00003332
Erik Andersene49d5ec2000-02-08 19:58:47 +00003333 ifd = in;
3334 ofd = out;
3335 outcnt = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00003336
Erik Andersene49d5ec2000-02-08 19:58:47 +00003337 /* Write the header to the gzip file. See algorithm.doc for the format */
Eric Andersencc8ed391999-10-05 16:24:54 +00003338
Eric Andersen96bcfd31999-11-12 01:30:18 +00003339
Erik Andersene49d5ec2000-02-08 19:58:47 +00003340 method = DEFLATED;
3341 put_byte(GZIP_MAGIC[0]); /* magic header */
3342 put_byte(GZIP_MAGIC[1]);
3343 put_byte(DEFLATED); /* compression method */
Eric Andersencc8ed391999-10-05 16:24:54 +00003344
Erik Andersene49d5ec2000-02-08 19:58:47 +00003345 put_byte(flags); /* general flags */
3346 put_long(time_stamp);
Eric Andersencc8ed391999-10-05 16:24:54 +00003347
Erik Andersene49d5ec2000-02-08 19:58:47 +00003348 /* Write deflated file to zip file */
3349 crc = updcrc(0, 0);
Eric Andersencc8ed391999-10-05 16:24:54 +00003350
Erik Andersene49d5ec2000-02-08 19:58:47 +00003351 bi_init(out);
3352 ct_init(&attr, &method);
3353 lm_init(&deflate_flags);
Eric Andersencc8ed391999-10-05 16:24:54 +00003354
Erik Andersene49d5ec2000-02-08 19:58:47 +00003355 put_byte((uch) deflate_flags); /* extra flags */
3356 put_byte(OS_CODE); /* OS identifier */
Eric Andersencc8ed391999-10-05 16:24:54 +00003357
Erik Andersene49d5ec2000-02-08 19:58:47 +00003358 header_bytes = (long) outcnt;
Eric Andersencc8ed391999-10-05 16:24:54 +00003359
Erik Andersene49d5ec2000-02-08 19:58:47 +00003360 (void) deflate();
Eric Andersencc8ed391999-10-05 16:24:54 +00003361
Erik Andersene49d5ec2000-02-08 19:58:47 +00003362 /* Write the crc and uncompressed size */
3363 put_long(crc);
3364 put_long(isize);
3365 header_bytes += 2 * sizeof(long);
Eric Andersencc8ed391999-10-05 16:24:54 +00003366
Erik Andersene49d5ec2000-02-08 19:58:47 +00003367 flush_outbuf();
3368 return OK;
Eric Andersencc8ed391999-10-05 16:24:54 +00003369}
3370
3371
3372/* ===========================================================================
3373 * Read a new buffer from the current input file, perform end-of-line
3374 * translation, and update the crc and input file size.
3375 * IN assertion: size >= 2 (for end-of-line translation)
3376 */
3377int file_read(buf, size)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003378char *buf;
3379unsigned size;
Eric Andersencc8ed391999-10-05 16:24:54 +00003380{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003381 unsigned len;
Eric Andersencc8ed391999-10-05 16:24:54 +00003382
Erik Andersene49d5ec2000-02-08 19:58:47 +00003383 Assert(insize == 0, "inbuf not empty");
Eric Andersencc8ed391999-10-05 16:24:54 +00003384
Erik Andersene49d5ec2000-02-08 19:58:47 +00003385 len = read(ifd, buf, size);
3386 if (len == (unsigned) (-1) || len == 0)
3387 return (int) len;
Eric Andersencc8ed391999-10-05 16:24:54 +00003388
Erik Andersene49d5ec2000-02-08 19:58:47 +00003389 crc = updcrc((uch *) buf, len);
3390 isize += (ulg) len;
3391 return (int) len;
Eric Andersencc8ed391999-10-05 16:24:54 +00003392}