blob: 2a76046486bb83cbd83b75747bdb4ba9a065e9c4 [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/* These defines are very important for BusyBox. Without these,
33 * huge chunks of ram are pre-allocated making the BusyBox bss
34 * size Freaking Huge(tm), which is a bad thing.*/
35#define SMALL_MEM
36#define DYN_ALLOC
37
Eric Andersencc8ed391999-10-05 16:24:54 +000038/* I don't like nested includes, but the string and io functions are used
39 * too often
40 */
Eric Andersencbe31da2001-02-20 06:14:08 +000041#include <stdlib.h>
Eric Andersencc8ed391999-10-05 16:24:54 +000042#include <stdio.h>
Erik Andersen61677fe2000-04-13 01:18:56 +000043#include <string.h>
Eric Andersened3ef502001-01-27 08:24:39 +000044#include <unistd.h>
Glenn L McGrathf58efb52001-03-28 05:35:16 +000045#include <errno.h>
Eric Andersencbe31da2001-02-20 06:14:08 +000046#include "busybox.h"
47#define BB_DECLARE_EXTERN
48#define bb_need_memory_exhausted
49#include "messages.c"
50
Erik Andersen61677fe2000-04-13 01:18:56 +000051#define memzero(s, n) memset ((void *)(s), 0, (n))
Eric Andersencc8ed391999-10-05 16:24:54 +000052
53#ifndef RETSIGTYPE
54# define RETSIGTYPE void
55#endif
56
57#define local static
58
Erik Andersene49d5ec2000-02-08 19:58:47 +000059typedef unsigned char uch;
Eric Andersencc8ed391999-10-05 16:24:54 +000060typedef unsigned short ush;
Erik Andersene49d5ec2000-02-08 19:58:47 +000061typedef unsigned long ulg;
Eric Andersencc8ed391999-10-05 16:24:54 +000062
63/* Return codes from gzip */
64#define OK 0
65#define ERROR 1
66#define WARNING 2
67
68/* Compression methods (see algorithm.doc) */
69#define STORED 0
70#define COMPRESSED 1
71#define PACKED 2
72#define LZHED 3
73/* methods 4 to 7 reserved */
74#define DEFLATED 8
75#define MAX_METHODS 9
Glenn L McGrathf58efb52001-03-28 05:35:16 +000076static int method; /* compression method */
Eric Andersencc8ed391999-10-05 16:24:54 +000077
78/* To save memory for 16 bit systems, some arrays are overlaid between
79 * the various modules:
80 * deflate: prev+head window d_buf l_buf outbuf
81 * unlzw: tab_prefix tab_suffix stack inbuf outbuf
82 * inflate: window inbuf
83 * unpack: window inbuf prefix_len
84 * unlzh: left+right window c_table inbuf c_len
85 * For compression, input is done in window[]. For decompression, output
86 * is done in window except for unlzw.
87 */
88
89#ifndef INBUFSIZ
90# ifdef SMALL_MEM
Erik Andersene49d5ec2000-02-08 19:58:47 +000091# define INBUFSIZ 0x2000 /* input buffer size */
Eric Andersencc8ed391999-10-05 16:24:54 +000092# else
Erik Andersene49d5ec2000-02-08 19:58:47 +000093# define INBUFSIZ 0x8000 /* input buffer size */
Eric Andersencc8ed391999-10-05 16:24:54 +000094# endif
95#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +000096#define INBUF_EXTRA 64 /* required by unlzw() */
Eric Andersencc8ed391999-10-05 16:24:54 +000097
98#ifndef OUTBUFSIZ
99# ifdef SMALL_MEM
Erik Andersene49d5ec2000-02-08 19:58:47 +0000100# define OUTBUFSIZ 8192 /* output buffer size */
Eric Andersencc8ed391999-10-05 16:24:54 +0000101# else
Erik Andersene49d5ec2000-02-08 19:58:47 +0000102# define OUTBUFSIZ 16384 /* output buffer size */
Eric Andersencc8ed391999-10-05 16:24:54 +0000103# endif
104#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000105#define OUTBUF_EXTRA 2048 /* required by unlzw() */
Eric Andersencc8ed391999-10-05 16:24:54 +0000106
107#ifndef DIST_BUFSIZE
108# ifdef SMALL_MEM
Erik Andersene49d5ec2000-02-08 19:58:47 +0000109# define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
Eric Andersencc8ed391999-10-05 16:24:54 +0000110# else
Erik Andersene49d5ec2000-02-08 19:58:47 +0000111# define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
Eric Andersencc8ed391999-10-05 16:24:54 +0000112# endif
113#endif
114
115#ifdef DYN_ALLOC
Erik Andersen61677fe2000-04-13 01:18:56 +0000116# define EXTERN(type, array) extern type * array
117# define DECLARE(type, array, size) type * array
Eric Andersencc8ed391999-10-05 16:24:54 +0000118# define ALLOC(type, array, size) { \
Erik Andersen61677fe2000-04-13 01:18:56 +0000119 array = (type*)calloc((size_t)(((size)+1L)/2), 2*sizeof(type)); \
Mark Whitleyf57c9442000-12-07 19:56:48 +0000120 if (array == NULL) error_msg(memory_exhausted); \
Eric Andersencc8ed391999-10-05 16:24:54 +0000121 }
Erik Andersen61677fe2000-04-13 01:18:56 +0000122# define FREE(array) {if (array != NULL) free(array), array=NULL;}
Eric Andersencc8ed391999-10-05 16:24:54 +0000123#else
124# define EXTERN(type, array) extern type array[]
125# define DECLARE(type, array, size) type array[size]
126# define ALLOC(type, array, size)
127# define FREE(array)
128#endif
129
Erik Andersene49d5ec2000-02-08 19:58:47 +0000130EXTERN(uch, inbuf); /* input buffer */
131EXTERN(uch, outbuf); /* output buffer */
132EXTERN(ush, d_buf); /* buffer for distances, see trees.c */
133EXTERN(uch, window); /* Sliding window and suffix table (unlzw) */
Eric Andersencc8ed391999-10-05 16:24:54 +0000134#define tab_suffix window
135#ifndef MAXSEG_64K
Erik Andersene49d5ec2000-02-08 19:58:47 +0000136# define tab_prefix prev /* hash link (see deflate.c) */
137# define head (prev+WSIZE) /* hash head (see deflate.c) */
138EXTERN(ush, tab_prefix); /* prefix code (see unlzw.c) */
Eric Andersencc8ed391999-10-05 16:24:54 +0000139#else
140# define tab_prefix0 prev
141# define head tab_prefix1
Erik Andersene49d5ec2000-02-08 19:58:47 +0000142EXTERN(ush, tab_prefix0); /* prefix for even codes */
143EXTERN(ush, tab_prefix1); /* prefix for odd codes */
Eric Andersencc8ed391999-10-05 16:24:54 +0000144#endif
145
Erik Andersene49d5ec2000-02-08 19:58:47 +0000146extern unsigned insize; /* valid bytes in inbuf */
Glenn L McGrathf58efb52001-03-28 05:35:16 +0000147static unsigned inptr; /* index of next byte to be processed in inbuf */
Erik Andersene49d5ec2000-02-08 19:58:47 +0000148extern unsigned outcnt; /* bytes in output buffer */
Eric Andersencc8ed391999-10-05 16:24:54 +0000149
Erik Andersene49d5ec2000-02-08 19:58:47 +0000150extern long bytes_in; /* number of input bytes */
151extern long bytes_out; /* number of output bytes */
152extern long header_bytes; /* number of bytes in gzip header */
Eric Andersencc8ed391999-10-05 16:24:54 +0000153
154#define isize bytes_in
155/* for compatibility with old zip sources (to be cleaned) */
156
Erik Andersene49d5ec2000-02-08 19:58:47 +0000157extern int ifd; /* input file descriptor */
158extern int ofd; /* output file descriptor */
159extern char ifname[]; /* input file name or "stdin" */
160extern char ofname[]; /* output file name or "stdout" */
161extern char *progname; /* program name */
Eric Andersencc8ed391999-10-05 16:24:54 +0000162
Erik Andersene49d5ec2000-02-08 19:58:47 +0000163extern long time_stamp; /* original time stamp (modification time) */
164extern long ifile_size; /* input file size, -1 for devices (debug only) */
Eric Andersencc8ed391999-10-05 16:24:54 +0000165
Erik Andersene49d5ec2000-02-08 19:58:47 +0000166typedef int file_t; /* Do not use stdio */
167
168#define NO_FILE (-1) /* in memory compression */
Eric Andersencc8ed391999-10-05 16:24:54 +0000169
170
Erik Andersene49d5ec2000-02-08 19:58:47 +0000171#define PACK_MAGIC "\037\036" /* Magic header for packed files */
172#define GZIP_MAGIC "\037\213" /* Magic header for gzip files, 1F 8B */
173#define OLD_GZIP_MAGIC "\037\236" /* Magic header for gzip 0.5 = freeze 1.x */
174#define LZH_MAGIC "\037\240" /* Magic header for SCO LZH Compress files */
175#define PKZIP_MAGIC "\120\113\003\004" /* Magic header for pkzip files */
Eric Andersencc8ed391999-10-05 16:24:54 +0000176
177/* gzip flag byte */
Erik Andersene49d5ec2000-02-08 19:58:47 +0000178#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
179#define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
180#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
181#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
182#define COMMENT 0x10 /* bit 4 set: file comment present */
183#define ENCRYPTED 0x20 /* bit 5 set: file is encrypted */
184#define RESERVED 0xC0 /* bit 6,7: reserved */
Eric Andersencc8ed391999-10-05 16:24:54 +0000185
186/* internal file attribute */
187#define UNKNOWN 0xffff
188#define BINARY 0
189#define ASCII 1
190
191#ifndef WSIZE
Erik Andersene49d5ec2000-02-08 19:58:47 +0000192# define WSIZE 0x8000 /* window size--must be a power of two, and */
193#endif /* at least 32K for zip's deflate method */
Eric Andersencc8ed391999-10-05 16:24:54 +0000194
195#define MIN_MATCH 3
196#define MAX_MATCH 258
197/* The minimum and maximum match lengths */
198
199#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
200/* Minimum amount of lookahead, except at the end of the input file.
201 * See deflate.c for comments about the MIN_MATCH+1.
202 */
203
204#define MAX_DIST (WSIZE-MIN_LOOKAHEAD)
205/* In order to simplify the code, particularly on 16 bit machines, match
206 * distances are limited to MAX_DIST instead of WSIZE.
207 */
208
Erik Andersene49d5ec2000-02-08 19:58:47 +0000209extern int decrypt; /* flag to turn on decryption */
210extern int exit_code; /* program exit code */
211extern int verbose; /* be verbose (-v) */
212extern int quiet; /* be quiet (-q) */
213extern int test; /* check .z file integrity */
214extern int save_orig_name; /* set if original name must be saved */
Eric Andersencc8ed391999-10-05 16:24:54 +0000215
216#define get_byte() (inptr < insize ? inbuf[inptr++] : fill_inbuf(0))
217#define try_byte() (inptr < insize ? inbuf[inptr++] : fill_inbuf(1))
218
219/* put_byte is used for the compressed output, put_ubyte for the
220 * uncompressed output. However unlzw() uses window for its
221 * suffix table instead of its output buffer, so it does not use put_ubyte
222 * (to be cleaned up).
223 */
224#define put_byte(c) {outbuf[outcnt++]=(uch)(c); if (outcnt==OUTBUFSIZ)\
225 flush_outbuf();}
226#define put_ubyte(c) {window[outcnt++]=(uch)(c); if (outcnt==WSIZE)\
227 flush_window();}
228
229/* Output a 16 bit value, lsb first */
230#define put_short(w) \
231{ if (outcnt < OUTBUFSIZ-2) { \
232 outbuf[outcnt++] = (uch) ((w) & 0xff); \
233 outbuf[outcnt++] = (uch) ((ush)(w) >> 8); \
234 } else { \
235 put_byte((uch)((w) & 0xff)); \
236 put_byte((uch)((ush)(w) >> 8)); \
237 } \
238}
239
240/* Output a 32 bit value to the bit stream, lsb first */
241#define put_long(n) { \
242 put_short((n) & 0xffff); \
243 put_short(((ulg)(n)) >> 16); \
244}
245
Erik Andersene49d5ec2000-02-08 19:58:47 +0000246#define seekable() 0 /* force sequential output */
247#define translate_eol 0 /* no option -a yet */
Eric Andersencc8ed391999-10-05 16:24:54 +0000248
Erik Andersene49d5ec2000-02-08 19:58:47 +0000249#define tolow(c) (isupper(c) ? (c)-'A'+'a' : (c)) /* force to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000250
251/* Macros for getting two-byte and four-byte header values */
252#define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
253#define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
254
255/* Diagnostic functions */
256#ifdef DEBUG
Mark Whitleyf57c9442000-12-07 19:56:48 +0000257# define Assert(cond,msg) {if(!(cond)) error_msg(msg);}
Eric Andersencc8ed391999-10-05 16:24:54 +0000258# define Trace(x) fprintf x
259# define Tracev(x) {if (verbose) fprintf x ;}
260# define Tracevv(x) {if (verbose>1) fprintf x ;}
261# define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
262# define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
263#else
264# define Assert(cond,msg)
265# define Trace(x)
266# define Tracev(x)
267# define Tracevv(x)
268# define Tracec(c,x)
269# define Tracecv(c,x)
270#endif
271
272#define WARN(msg) {if (!quiet) fprintf msg ; \
273 if (exit_code == OK) exit_code = WARNING;}
274
Eric Andersencc8ed391999-10-05 16:24:54 +0000275
276 /* in zip.c: */
Erik Andersen61677fe2000-04-13 01:18:56 +0000277extern int zip (int in, int out);
278extern int file_read (char *buf, unsigned size);
Eric Andersencc8ed391999-10-05 16:24:54 +0000279
280 /* in unzip.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000281extern int unzip (int in, int out);
282extern int check_zipfile (int in);
Eric Andersencc8ed391999-10-05 16:24:54 +0000283
284 /* in unpack.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000285extern int unpack (int in, int out);
Eric Andersencc8ed391999-10-05 16:24:54 +0000286
287 /* in unlzh.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000288extern int unlzh (int in, int out);
Eric Andersencc8ed391999-10-05 16:24:54 +0000289
290 /* in gzip.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000291RETSIGTYPE abort_gzip (void);
Eric Andersencc8ed391999-10-05 16:24:54 +0000292
Erik Andersene49d5ec2000-02-08 19:58:47 +0000293 /* in deflate.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000294void lm_init (ush * flags);
295ulg deflate (void);
Eric Andersencc8ed391999-10-05 16:24:54 +0000296
Erik Andersene49d5ec2000-02-08 19:58:47 +0000297 /* in trees.c */
Eric Andersen851895a2001-03-21 21:52:25 +0000298void ct_init (ush * attr, int *methodp);
Erik Andersen61677fe2000-04-13 01:18:56 +0000299int ct_tally (int dist, int lc);
300ulg flush_block (char *buf, ulg stored_len, int eof);
Eric Andersencc8ed391999-10-05 16:24:54 +0000301
Erik Andersene49d5ec2000-02-08 19:58:47 +0000302 /* in bits.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000303void bi_init (file_t zipfile);
304void send_bits (int value, int length);
305unsigned bi_reverse (unsigned value, int length);
306void bi_windup (void);
307void copy_block (char *buf, unsigned len, int header);
308extern int (*read_buf) (char *buf, unsigned size);
Eric Andersencc8ed391999-10-05 16:24:54 +0000309
310 /* in util.c: */
Erik Andersen61677fe2000-04-13 01:18:56 +0000311extern int copy (int in, int out);
Glenn L McGrathf58efb52001-03-28 05:35:16 +0000312//extern ulg updcrc (uch * s, unsigned n);
313//extern void clear_bufs (void);
Erik Andersen61677fe2000-04-13 01:18:56 +0000314extern int fill_inbuf (int eof_ok);
315extern void flush_outbuf (void);
316extern void flush_window (void);
Glenn L McGrathf58efb52001-03-28 05:35:16 +0000317//extern void write_buf (int fd, void * buf, unsigned cnt);
Erik Andersen61677fe2000-04-13 01:18:56 +0000318extern char *strlwr (char *s);
319extern char *add_envopt (int *argcp, char ***argvp, char *env);
Glenn L McGrathf58efb52001-03-28 05:35:16 +0000320//extern void read_error_msg (void);
321//extern void write_error_msg (void);
Erik Andersen61677fe2000-04-13 01:18:56 +0000322extern void display_ratio (long num, long den, FILE * file);
Eric Andersencc8ed391999-10-05 16:24:54 +0000323
324 /* in inflate.c */
Erik Andersen61677fe2000-04-13 01:18:56 +0000325extern int inflate (void);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000326
Eric Andersencc8ed391999-10-05 16:24:54 +0000327/* lzw.h -- define the lzw functions.
328 * Copyright (C) 1992-1993 Jean-loup Gailly.
329 * This is free software; you can redistribute it and/or modify it under the
330 * terms of the GNU General Public License, see the file COPYING.
331 */
332
333#if !defined(OF) && defined(lint)
334# include "gzip.h"
335#endif
336
337#ifndef BITS
338# define BITS 16
339#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000340#define INIT_BITS 9 /* Initial number of bits per code */
Eric Andersencc8ed391999-10-05 16:24:54 +0000341
Erik Andersene49d5ec2000-02-08 19:58:47 +0000342#define BIT_MASK 0x1f /* Mask for 'number of compression bits' */
Eric Andersencc8ed391999-10-05 16:24:54 +0000343/* Mask 0x20 is reserved to mean a fourth header byte, and 0x40 is free.
344 * It's a pity that old uncompress does not check bit 0x20. That makes
345 * extension of the format actually undesirable because old compress
346 * would just crash on the new format instead of giving a meaningful
347 * error message. It does check the number of bits, but it's more
348 * helpful to say "unsupported format, get a new version" than
349 * "can only handle 16 bits".
350 */
351
352#define BLOCK_MODE 0x80
353/* Block compression: if table is full and compression rate is dropping,
354 * clear the dictionary.
355 */
356
Erik Andersene49d5ec2000-02-08 19:58:47 +0000357#define LZW_RESERVED 0x60 /* reserved bits */
Eric Andersencc8ed391999-10-05 16:24:54 +0000358
Erik Andersene49d5ec2000-02-08 19:58:47 +0000359#define CLEAR 256 /* flush the dictionary */
360#define FIRST (CLEAR+1) /* first free entry */
Eric Andersencc8ed391999-10-05 16:24:54 +0000361
Erik Andersene49d5ec2000-02-08 19:58:47 +0000362extern int maxbits; /* max bits per code for LZW */
363extern int block_mode; /* block compress mode -C compatible with 2.0 */
Eric Andersencc8ed391999-10-05 16:24:54 +0000364
365/* revision.h -- define the version number
366 * Copyright (C) 1992-1993 Jean-loup Gailly.
367 * This is free software; you can redistribute it and/or modify it under the
368 * terms of the GNU General Public License, see the file COPYING.
369 */
370
371#define VERSION "1.2.4"
372#define PATCHLEVEL 0
373#define REVDATE "18 Aug 93"
374
375/* This version does not support compression into old compress format: */
376#ifdef LZW
377# undef LZW
378#endif
379
Eric Andersencc8ed391999-10-05 16:24:54 +0000380/* tailor.h -- target dependent definitions
381 * Copyright (C) 1992-1993 Jean-loup Gailly.
382 * This is free software; you can redistribute it and/or modify it under the
383 * terms of the GNU General Public License, see the file COPYING.
384 */
385
386/* The target dependent definitions should be defined here only.
387 * The target dependent functions should be defined in tailor.c.
388 */
389
Eric Andersencc8ed391999-10-05 16:24:54 +0000390
391#if defined(__MSDOS__) && !defined(MSDOS)
392# define MSDOS
393#endif
394
395#if defined(__OS2__) && !defined(OS2)
396# define OS2
397#endif
398
Erik Andersene49d5ec2000-02-08 19:58:47 +0000399#if defined(OS2) && defined(MSDOS) /* MS C under OS/2 */
Eric Andersencc8ed391999-10-05 16:24:54 +0000400# undef MSDOS
401#endif
402
403#ifdef MSDOS
404# ifdef __GNUC__
Erik Andersene49d5ec2000-02-08 19:58:47 +0000405 /* DJGPP version 1.09+ on MS-DOS.
406 * The DJGPP 1.09 stat() function must be upgraded before gzip will
407 * fully work.
408 * No need for DIRENT, since <unistd.h> defines POSIX_SOURCE which
409 * implies DIRENT.
410 */
Eric Andersencc8ed391999-10-05 16:24:54 +0000411# define near
412# else
413# define MAXSEG_64K
414# ifdef __TURBOC__
415# define NO_OFF_T
416# ifdef __BORLANDC__
417# define DIRENT
418# else
419# define NO_UTIME
420# endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000421# else /* MSC */
Eric Andersencc8ed391999-10-05 16:24:54 +0000422# define HAVE_SYS_UTIME_H
423# define NO_UTIME_H
424# endif
425# endif
426# define PATH_SEP2 '\\'
427# define PATH_SEP3 ':'
428# define MAX_PATH_LEN 128
429# define NO_MULTIPLE_DOTS
430# define MAX_EXT_CHARS 3
431# define Z_SUFFIX "z"
432# define NO_CHOWN
433# define PROTO
434# define STDC_HEADERS
435# define NO_SIZE_CHECK
Erik Andersene49d5ec2000-02-08 19:58:47 +0000436# define casemap(c) tolow(c) /* Force file names to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000437# include <io.h>
438# define OS_CODE 0x00
439# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
440# if !defined(NO_ASM) && !defined(ASMV)
441# define ASMV
442# endif
443#else
444# define near
445#endif
446
447#ifdef OS2
448# define PATH_SEP2 '\\'
449# define PATH_SEP3 ':'
450# define MAX_PATH_LEN 260
451# ifdef OS2FAT
452# define NO_MULTIPLE_DOTS
453# define MAX_EXT_CHARS 3
454# define Z_SUFFIX "z"
455# define casemap(c) tolow(c)
456# endif
457# define NO_CHOWN
458# define PROTO
459# define STDC_HEADERS
460# include <io.h>
461# define OS_CODE 0x06
462# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
463# ifdef _MSC_VER
464# define HAVE_SYS_UTIME_H
465# define NO_UTIME_H
466# define MAXSEG_64K
467# undef near
468# define near _near
469# endif
470# ifdef __EMX__
471# define HAVE_SYS_UTIME_H
472# define NO_UTIME_H
473# define DIRENT
474# define EXPAND(argc,argv) \
475 {_response(&argc, &argv); _wildcard(&argc, &argv);}
476# endif
477# ifdef __BORLANDC__
478# define DIRENT
479# endif
480# ifdef __ZTC__
481# define NO_DIR
482# define NO_UTIME_H
483# include <dos.h>
484# define EXPAND(argc,argv) \
485 {response_expand(&argc, &argv);}
486# endif
487#endif
488
Erik Andersene49d5ec2000-02-08 19:58:47 +0000489#ifdef WIN32 /* Windows NT */
Eric Andersencc8ed391999-10-05 16:24:54 +0000490# define HAVE_SYS_UTIME_H
491# define NO_UTIME_H
492# define PATH_SEP2 '\\'
493# define PATH_SEP3 ':'
494# define MAX_PATH_LEN 260
495# define NO_CHOWN
496# define PROTO
497# define STDC_HEADERS
498# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
499# include <io.h>
500# include <malloc.h>
501# ifdef NTFAT
502# define NO_MULTIPLE_DOTS
503# define MAX_EXT_CHARS 3
504# define Z_SUFFIX "z"
Erik Andersene49d5ec2000-02-08 19:58:47 +0000505# define casemap(c) tolow(c) /* Force file names to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000506# endif
507# define OS_CODE 0x0b
508#endif
509
510#ifdef MSDOS
511# ifdef __TURBOC__
512# include <alloc.h>
513# define DYN_ALLOC
Erik Andersene49d5ec2000-02-08 19:58:47 +0000514 /* Turbo C 2.0 does not accept static allocations of large arrays */
515void *fcalloc(unsigned items, unsigned size);
516void fcfree(void *ptr);
517# else /* MSC */
Eric Andersencc8ed391999-10-05 16:24:54 +0000518# include <malloc.h>
519# define fcalloc(nitems,itemsize) halloc((long)(nitems),(itemsize))
520# define fcfree(ptr) hfree(ptr)
521# endif
522#else
523# ifdef MAXSEG_64K
524# define fcalloc(items,size) calloc((items),(size))
525# else
526# define fcalloc(items,size) malloc((size_t)(items)*(size_t)(size))
527# endif
528# define fcfree(ptr) free(ptr)
529#endif
530
531#if defined(VAXC) || defined(VMS)
532# define PATH_SEP ']'
533# define PATH_SEP2 ':'
534# define SUFFIX_SEP ';'
535# define NO_MULTIPLE_DOTS
536# define Z_SUFFIX "-gz"
537# define RECORD_IO 1
538# define casemap(c) tolow(c)
539# define OS_CODE 0x02
540# define OPTIONS_VAR "GZIP_OPT"
541# define STDC_HEADERS
542# define NO_UTIME
543# define EXPAND(argc,argv) vms_expand_args(&argc,&argv);
544# include <file.h>
545# define unlink delete
546# ifdef VAXC
547# define NO_FCNTL_H
548# include <unixio.h>
549# endif
550#endif
551
552#ifdef AMIGA
553# define PATH_SEP2 ':'
554# define STDC_HEADERS
555# define OS_CODE 0x01
556# define ASMV
557# ifdef __GNUC__
558# define DIRENT
559# define HAVE_UNISTD_H
Erik Andersene49d5ec2000-02-08 19:58:47 +0000560# else /* SASC */
Eric Andersencc8ed391999-10-05 16:24:54 +0000561# define NO_STDIN_FSTAT
562# define SYSDIR
563# define NO_SYMLINK
564# define NO_CHOWN
565# define NO_FCNTL_H
Erik Andersene49d5ec2000-02-08 19:58:47 +0000566# include <fcntl.h> /* for read() and write() */
Eric Andersencc8ed391999-10-05 16:24:54 +0000567# define direct dirent
Erik Andersene49d5ec2000-02-08 19:58:47 +0000568extern void _expand_args(int *argc, char ***argv);
569
Eric Andersencc8ed391999-10-05 16:24:54 +0000570# define EXPAND(argc,argv) _expand_args(&argc,&argv);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000571# undef O_BINARY /* disable useless --ascii option */
Eric Andersencc8ed391999-10-05 16:24:54 +0000572# endif
573#endif
574
575#if defined(ATARI) || defined(atarist)
576# ifndef STDC_HEADERS
577# define STDC_HEADERS
578# define HAVE_UNISTD_H
579# define DIRENT
580# endif
581# define ASMV
582# define OS_CODE 0x05
583# ifdef TOSFS
584# define PATH_SEP2 '\\'
585# define PATH_SEP3 ':'
586# define MAX_PATH_LEN 128
587# define NO_MULTIPLE_DOTS
588# define MAX_EXT_CHARS 3
589# define Z_SUFFIX "z"
590# define NO_CHOWN
Erik Andersene49d5ec2000-02-08 19:58:47 +0000591# define casemap(c) tolow(c) /* Force file names to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000592# define NO_SYMLINK
593# endif
594#endif
595
596#ifdef MACOS
597# define PATH_SEP ':'
598# define DYN_ALLOC
599# define PROTO
600# define NO_STDIN_FSTAT
601# define NO_CHOWN
602# define NO_UTIME
603# define chmod(file, mode) (0)
604# define OPEN(name, flags, mode) open(name, flags)
605# define OS_CODE 0x07
606# ifdef MPW
607# define isatty(fd) ((fd) <= 2)
608# endif
609#endif
610
Erik Andersene49d5ec2000-02-08 19:58:47 +0000611#ifdef __50SERIES /* Prime/PRIMOS */
Eric Andersencc8ed391999-10-05 16:24:54 +0000612# define PATH_SEP '>'
613# define STDC_HEADERS
614# define NO_MEMORY_H
615# define NO_UTIME_H
616# define NO_UTIME
Erik Andersene49d5ec2000-02-08 19:58:47 +0000617# define NO_CHOWN
618# define NO_STDIN_FSTAT
619# define NO_SIZE_CHECK
Eric Andersencc8ed391999-10-05 16:24:54 +0000620# define NO_SYMLINK
621# define RECORD_IO 1
Erik Andersene49d5ec2000-02-08 19:58:47 +0000622# define casemap(c) tolow(c) /* Force file names to lower case */
Eric Andersencc8ed391999-10-05 16:24:54 +0000623# define put_char(c) put_byte((c) & 0x7F)
624# define get_char(c) ascii2pascii(get_byte())
Erik Andersene49d5ec2000-02-08 19:58:47 +0000625# define OS_CODE 0x0F /* temporary, subject to change */
Eric Andersencc8ed391999-10-05 16:24:54 +0000626# ifdef SIGTERM
Erik Andersene49d5ec2000-02-08 19:58:47 +0000627# undef SIGTERM /* We don't want a signal handler for SIGTERM */
Eric Andersencc8ed391999-10-05 16:24:54 +0000628# endif
629#endif
630
Erik Andersene49d5ec2000-02-08 19:58:47 +0000631#if defined(pyr) && !defined(NOMEMCPY) /* Pyramid */
632# define NOMEMCPY /* problem with overlapping copies */
Eric Andersencc8ed391999-10-05 16:24:54 +0000633#endif
634
635#ifdef TOPS20
636# define OS_CODE 0x0a
637#endif
638
639#ifndef unix
Erik Andersene49d5ec2000-02-08 19:58:47 +0000640# define NO_ST_INO /* don't rely on inode numbers */
Eric Andersencc8ed391999-10-05 16:24:54 +0000641#endif
642
643
644 /* Common defaults */
645
646#ifndef OS_CODE
Erik Andersene49d5ec2000-02-08 19:58:47 +0000647# define OS_CODE 0x03 /* assume Unix */
Eric Andersencc8ed391999-10-05 16:24:54 +0000648#endif
649
650#ifndef PATH_SEP
651# define PATH_SEP '/'
652#endif
653
654#ifndef casemap
655# define casemap(c) (c)
656#endif
657
658#ifndef OPTIONS_VAR
659# define OPTIONS_VAR "GZIP"
660#endif
661
662#ifndef Z_SUFFIX
663# define Z_SUFFIX ".gz"
664#endif
665
666#ifdef MAX_EXT_CHARS
667# define MAX_SUFFIX MAX_EXT_CHARS
668#else
669# define MAX_SUFFIX 30
670#endif
671
672#ifndef MAKE_LEGAL_NAME
673# ifdef NO_MULTIPLE_DOTS
674# define MAKE_LEGAL_NAME(name) make_simple_name(name)
675# else
676# define MAKE_LEGAL_NAME(name)
677# endif
678#endif
679
680#ifndef MIN_PART
681# define MIN_PART 3
682 /* keep at least MIN_PART chars between dots in a file name. */
683#endif
684
685#ifndef EXPAND
686# define EXPAND(argc,argv)
687#endif
688
689#ifndef RECORD_IO
690# define RECORD_IO 0
691#endif
692
693#ifndef SET_BINARY_MODE
694# define SET_BINARY_MODE(fd)
695#endif
696
697#ifndef OPEN
698# define OPEN(name, flags, mode) open(name, flags, mode)
699#endif
700
701#ifndef get_char
702# define get_char() get_byte()
703#endif
704
705#ifndef put_char
706# define put_char(c) put_byte(c)
707#endif
Glenn L McGrathf58efb52001-03-28 05:35:16 +0000708
709int crc_table_empty = 1;
710
711/* ========================================================================
712 * Signal and error handler.
713 */
714void abort_gzip()
715{
716 exit(ERROR);
717}
718
719/* ===========================================================================
720 * Clear input and output buffers
721 */
722static void clear_bufs(void)
723{
724 outcnt = 0;
725 insize = inptr = 0;
726 bytes_in = bytes_out = 0L;
727}
728
729static void write_error_msg()
730{
731 fprintf(stderr, "\n");
732 perror("");
733 abort_gzip();
734}
735
736/* ===========================================================================
737 * Does the same as write(), but also handles partial pipe writes and checks
738 * for error return.
739 */
740static void write_buf(fd, buf, cnt)
741int fd;
742void * buf;
743unsigned cnt;
744{
745 unsigned n;
746
747 while ((n = write(fd, buf, cnt)) != cnt) {
748 if (n == (unsigned) (-1)) {
749 write_error_msg();
750 }
751 cnt -= n;
752 buf = (void *) ((char *) buf + n);
753 }
754}
755
756/* ========================================================================
757 * Error handlers.
758 */
759static void read_error_msg()
760{
761 fprintf(stderr, "\n");
762 if (errno != 0) {
763 perror("");
764 } else {
765 fprintf(stderr, "unexpected end of file\n");
766 }
767 abort_gzip();
768}
769
770/* ===========================================================================
771 * Run a set of bytes through the crc shift register. If s is a NULL
772 * pointer, then initialize the crc shift register contents instead.
773 * Return the current crc in either case.
774 */
775static ulg updcrc(s, n)
776uch *s; /* pointer to bytes to pump through */
777unsigned n; /* number of bytes in s[] */
778{
779 static ulg crc = (ulg) 0xffffffffL; /* shift register contents */
780 register ulg c; /* temporary variable */
781 static unsigned long crc_32_tab[256];
782 if (crc_table_empty) {
783 unsigned long csr; /* crc shift register */
784 unsigned long e; /* polynomial exclusive-or pattern */
785 int i; /* counter for all possible eight bit values */
786 int k; /* byte being shifted into crc apparatus */
787
788 /* terms of polynomial defining this crc (except x^32): */
789 static int p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
790
791 /* Make exclusive-or pattern from polynomial (0xedb88320) */
792 e = 0;
793 for (i = 0; i < sizeof(p)/sizeof(int); i++)
794 e |= 1L << (31 - p[i]);
795
796 /* Compute and print table of CRC's, five per line */
797 crc_32_tab[0] = 0x00000000L;
798 for (i = 1; i < 256; i++) {
799 csr = i;
800 /* The idea to initialize the register with the byte instead of
801 * zero was stolen from Haruhiko Okumura's ar002
802 */
803 for (k = 8; k; k--)
804 csr = csr & 1 ? (csr >> 1) ^ e : csr >> 1;
805 crc_32_tab[i]=csr;
806 }
807 }
808
809 if (s == NULL) {
810 c = 0xffffffffL;
811 } else {
812 c = crc;
813 if (n)
814 do {
815 c = crc_32_tab[((int) c ^ (*s++)) & 0xff] ^ (c >> 8);
816 } while (--n);
817 }
818 crc = c;
819 return c ^ 0xffffffffL; /* (instead of ~c for 64-bit machines) */
820}
821
Eric Andersencc8ed391999-10-05 16:24:54 +0000822/* bits.c -- output variable-length bit strings
823 * Copyright (C) 1992-1993 Jean-loup Gailly
824 * This is free software; you can redistribute it and/or modify it under the
825 * terms of the GNU General Public License, see the file COPYING.
826 */
827
828
829/*
830 * PURPOSE
831 *
832 * Output variable-length bit strings. Compression can be done
833 * to a file or to memory. (The latter is not supported in this version.)
834 *
835 * DISCUSSION
836 *
837 * The PKZIP "deflate" file format interprets compressed file data
838 * as a sequence of bits. Multi-bit strings in the file may cross
839 * byte boundaries without restriction.
840 *
841 * The first bit of each byte is the low-order bit.
842 *
843 * The routines in this file allow a variable-length bit value to
844 * be output right-to-left (useful for literal values). For
845 * left-to-right output (useful for code strings from the tree routines),
846 * the bits must have been reversed first with bi_reverse().
847 *
848 * For in-memory compression, the compressed bit stream goes directly
849 * into the requested output buffer. The input data is read in blocks
850 * by the mem_read() function. The buffer is limited to 64K on 16 bit
851 * machines.
852 *
853 * INTERFACE
854 *
855 * void bi_init (FILE *zipfile)
856 * Initialize the bit string routines.
857 *
858 * void send_bits (int value, int length)
859 * Write out a bit string, taking the source bits right to
860 * left.
861 *
862 * int bi_reverse (int value, int length)
863 * Reverse the bits of a bit string, taking the source bits left to
864 * right and emitting them right to left.
865 *
866 * void bi_windup (void)
867 * Write out any remaining bits in an incomplete byte.
868 *
869 * void copy_block(char *buf, unsigned len, int header)
870 * Copy a stored block to the zip file, storing first the length and
871 * its one's complement if requested.
872 *
873 */
874
875#ifdef DEBUG
876# include <stdio.h>
877#endif
878
Eric Andersencc8ed391999-10-05 16:24:54 +0000879/* ===========================================================================
880 * Local data used by the "bit string" routines.
881 */
882
Erik Andersene49d5ec2000-02-08 19:58:47 +0000883local file_t zfile; /* output gzip file */
Eric Andersencc8ed391999-10-05 16:24:54 +0000884
885local unsigned short bi_buf;
Erik Andersene49d5ec2000-02-08 19:58:47 +0000886
Eric Andersencc8ed391999-10-05 16:24:54 +0000887/* Output buffer. bits are inserted starting at the bottom (least significant
888 * bits).
889 */
890
891#define Buf_size (8 * 2*sizeof(char))
892/* Number of bits used within bi_buf. (bi_buf might be implemented on
893 * more than 16 bits on some systems.)
894 */
895
896local int bi_valid;
Erik Andersene49d5ec2000-02-08 19:58:47 +0000897
Eric Andersencc8ed391999-10-05 16:24:54 +0000898/* Number of valid bits in bi_buf. All bits above the last valid bit
899 * are always zero.
900 */
901
Erik Andersen61677fe2000-04-13 01:18:56 +0000902int (*read_buf) (char *buf, unsigned size);
Erik Andersene49d5ec2000-02-08 19:58:47 +0000903
Eric Andersencc8ed391999-10-05 16:24:54 +0000904/* Current input function. Set to mem_read for in-memory compression */
905
906#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000907ulg bits_sent; /* bit length of the compressed data */
Eric Andersencc8ed391999-10-05 16:24:54 +0000908#endif
909
910/* ===========================================================================
911 * Initialize the bit string routines.
912 */
Erik Andersene49d5ec2000-02-08 19:58:47 +0000913void bi_init(zipfile)
914file_t zipfile; /* output zip file, NO_FILE for in-memory compression */
Eric Andersencc8ed391999-10-05 16:24:54 +0000915{
Erik Andersene49d5ec2000-02-08 19:58:47 +0000916 zfile = zipfile;
917 bi_buf = 0;
918 bi_valid = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +0000919#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000920 bits_sent = 0L;
Eric Andersencc8ed391999-10-05 16:24:54 +0000921#endif
922
Erik Andersene49d5ec2000-02-08 19:58:47 +0000923 /* Set the defaults for file compression. They are set by memcompress
924 * for in-memory compression.
925 */
926 if (zfile != NO_FILE) {
927 read_buf = file_read;
928 }
Eric Andersencc8ed391999-10-05 16:24:54 +0000929}
930
931/* ===========================================================================
932 * Send a value on a given number of bits.
933 * IN assertion: length <= 16 and value fits in length bits.
934 */
935void send_bits(value, length)
Erik Andersene49d5ec2000-02-08 19:58:47 +0000936int value; /* value to send */
937int length; /* number of bits */
Eric Andersencc8ed391999-10-05 16:24:54 +0000938{
939#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000940 Tracev((stderr, " l %2d v %4x ", length, value));
941 Assert(length > 0 && length <= 15, "invalid length");
942 bits_sent += (ulg) length;
Eric Andersencc8ed391999-10-05 16:24:54 +0000943#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +0000944 /* If not enough room in bi_buf, use (valid) bits from bi_buf and
945 * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
946 * unused bits in value.
947 */
948 if (bi_valid > (int) Buf_size - length) {
949 bi_buf |= (value << bi_valid);
950 put_short(bi_buf);
951 bi_buf = (ush) value >> (Buf_size - bi_valid);
952 bi_valid += length - Buf_size;
953 } else {
954 bi_buf |= value << bi_valid;
955 bi_valid += length;
956 }
Eric Andersencc8ed391999-10-05 16:24:54 +0000957}
958
959/* ===========================================================================
960 * Reverse the first len bits of a code, using straightforward code (a faster
961 * method would use a table)
962 * IN assertion: 1 <= len <= 15
963 */
964unsigned bi_reverse(code, len)
Erik Andersene49d5ec2000-02-08 19:58:47 +0000965unsigned code; /* the value to invert */
966int len; /* its bit length */
Eric Andersencc8ed391999-10-05 16:24:54 +0000967{
Erik Andersene49d5ec2000-02-08 19:58:47 +0000968 register unsigned res = 0;
969
970 do {
971 res |= code & 1;
972 code >>= 1, res <<= 1;
973 } while (--len > 0);
974 return res >> 1;
Eric Andersencc8ed391999-10-05 16:24:54 +0000975}
976
977/* ===========================================================================
978 * Write out any remaining bits in an incomplete byte.
979 */
980void bi_windup()
981{
Erik Andersene49d5ec2000-02-08 19:58:47 +0000982 if (bi_valid > 8) {
983 put_short(bi_buf);
984 } else if (bi_valid > 0) {
985 put_byte(bi_buf);
986 }
987 bi_buf = 0;
988 bi_valid = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +0000989#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +0000990 bits_sent = (bits_sent + 7) & ~7;
Eric Andersencc8ed391999-10-05 16:24:54 +0000991#endif
992}
993
994/* ===========================================================================
995 * Copy a stored block to the zip file, storing first the length and its
996 * one's complement if requested.
997 */
998void copy_block(buf, len, header)
Erik Andersene49d5ec2000-02-08 19:58:47 +0000999char *buf; /* the input data */
1000unsigned len; /* its length */
1001int header; /* true if block header must be written */
Eric Andersencc8ed391999-10-05 16:24:54 +00001002{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001003 bi_windup(); /* align on byte boundary */
Eric Andersencc8ed391999-10-05 16:24:54 +00001004
Erik Andersene49d5ec2000-02-08 19:58:47 +00001005 if (header) {
1006 put_short((ush) len);
1007 put_short((ush) ~ len);
Eric Andersencc8ed391999-10-05 16:24:54 +00001008#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +00001009 bits_sent += 2 * 16;
Eric Andersencc8ed391999-10-05 16:24:54 +00001010#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001011 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001012#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +00001013 bits_sent += (ulg) len << 3;
Eric Andersencc8ed391999-10-05 16:24:54 +00001014#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001015 while (len--) {
Eric Andersencc8ed391999-10-05 16:24:54 +00001016#ifdef CRYPT
Erik Andersene49d5ec2000-02-08 19:58:47 +00001017 int t;
1018
1019 if (key)
1020 zencode(*buf, t);
Eric Andersencc8ed391999-10-05 16:24:54 +00001021#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001022 put_byte(*buf++);
1023 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001024}
Erik Andersene49d5ec2000-02-08 19:58:47 +00001025
Eric Andersencc8ed391999-10-05 16:24:54 +00001026/* deflate.c -- compress data using the deflation algorithm
1027 * Copyright (C) 1992-1993 Jean-loup Gailly
1028 * This is free software; you can redistribute it and/or modify it under the
1029 * terms of the GNU General Public License, see the file COPYING.
1030 */
1031
1032/*
1033 * PURPOSE
1034 *
1035 * Identify new text as repetitions of old text within a fixed-
1036 * length sliding window trailing behind the new text.
1037 *
1038 * DISCUSSION
1039 *
1040 * The "deflation" process depends on being able to identify portions
1041 * of the input text which are identical to earlier input (within a
1042 * sliding window trailing behind the input currently being processed).
1043 *
1044 * The most straightforward technique turns out to be the fastest for
1045 * most input files: try all possible matches and select the longest.
1046 * The key feature of this algorithm is that insertions into the string
1047 * dictionary are very simple and thus fast, and deletions are avoided
1048 * completely. Insertions are performed at each input character, whereas
1049 * string matches are performed only when the previous match ends. So it
1050 * is preferable to spend more time in matches to allow very fast string
1051 * insertions and avoid deletions. The matching algorithm for small
1052 * strings is inspired from that of Rabin & Karp. A brute force approach
1053 * is used to find longer strings when a small match has been found.
1054 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
1055 * (by Leonid Broukhis).
1056 * A previous version of this file used a more sophisticated algorithm
1057 * (by Fiala and Greene) which is guaranteed to run in linear amortized
1058 * time, but has a larger average cost, uses more memory and is patented.
1059 * However the F&G algorithm may be faster for some highly redundant
1060 * files if the parameter max_chain_length (described below) is too large.
1061 *
1062 * ACKNOWLEDGEMENTS
1063 *
1064 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
1065 * I found it in 'freeze' written by Leonid Broukhis.
1066 * Thanks to many info-zippers for bug reports and testing.
1067 *
1068 * REFERENCES
1069 *
1070 * APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
1071 *
1072 * A description of the Rabin and Karp algorithm is given in the book
1073 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
1074 *
1075 * Fiala,E.R., and Greene,D.H.
1076 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
1077 *
1078 * INTERFACE
1079 *
1080 * void lm_init (int pack_level, ush *flags)
1081 * Initialize the "longest match" routines for a new file
1082 *
1083 * ulg deflate (void)
1084 * Processes a new input file and return its compressed length. Sets
1085 * the compressed length, crc, deflate flags and internal file
1086 * attributes.
1087 */
1088
1089#include <stdio.h>
1090
Eric Andersencc8ed391999-10-05 16:24:54 +00001091/* ===========================================================================
1092 * Configuration parameters
1093 */
1094
1095/* Compile with MEDIUM_MEM to reduce the memory requirements or
1096 * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
1097 * entire input file can be held in memory (not possible on 16 bit systems).
1098 * Warning: defining these symbols affects HASH_BITS (see below) and thus
1099 * affects the compression ratio. The compressed output
1100 * is still correct, and might even be smaller in some cases.
1101 */
1102
1103#ifdef SMALL_MEM
Erik Andersene49d5ec2000-02-08 19:58:47 +00001104# define HASH_BITS 13 /* Number of bits used to hash strings */
Eric Andersencc8ed391999-10-05 16:24:54 +00001105#endif
1106#ifdef MEDIUM_MEM
1107# define HASH_BITS 14
1108#endif
1109#ifndef HASH_BITS
1110# define HASH_BITS 15
1111 /* For portability to 16 bit machines, do not use values above 15. */
1112#endif
1113
1114/* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
1115 * window with tab_suffix. Check that we can do this:
1116 */
1117#if (WSIZE<<1) > (1<<BITS)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001118error:cannot overlay window with tab_suffix and prev with tab_prefix0
Eric Andersencc8ed391999-10-05 16:24:54 +00001119#endif
1120#if HASH_BITS > BITS-1
Erik Andersene49d5ec2000-02-08 19:58:47 +00001121error:cannot overlay head with tab_prefix1
Eric Andersencc8ed391999-10-05 16:24:54 +00001122#endif
Eric Andersencc8ed391999-10-05 16:24:54 +00001123#define HASH_SIZE (unsigned)(1<<HASH_BITS)
1124#define HASH_MASK (HASH_SIZE-1)
1125#define WMASK (WSIZE-1)
1126/* HASH_SIZE and WSIZE must be powers of two */
Eric Andersencc8ed391999-10-05 16:24:54 +00001127#define NIL 0
1128/* Tail of hash chains */
Eric Andersencc8ed391999-10-05 16:24:54 +00001129#define FAST 4
1130#define SLOW 2
1131/* speed options for the general purpose bit flag */
Eric Andersencc8ed391999-10-05 16:24:54 +00001132#ifndef TOO_FAR
1133# define TOO_FAR 4096
1134#endif
1135/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
Eric Andersencc8ed391999-10-05 16:24:54 +00001136/* ===========================================================================
1137 * Local data used by the "longest match" routines.
1138 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001139typedef ush Pos;
1140typedef unsigned IPos;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001141
Eric Andersencc8ed391999-10-05 16:24:54 +00001142/* A Pos is an index in the character window. We use short instead of int to
1143 * save space in the various tables. IPos is used only for parameter passing.
1144 */
1145
1146/* DECLARE(uch, window, 2L*WSIZE); */
1147/* Sliding window. Input bytes are read into the second half of the window,
1148 * and move to the first half later to keep a dictionary of at least WSIZE
1149 * bytes. With this organization, matches are limited to a distance of
1150 * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
1151 * performed with a length multiple of the block size. Also, it limits
1152 * the window size to 64K, which is quite useful on MSDOS.
1153 * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
1154 * be less efficient).
1155 */
1156
1157/* DECLARE(Pos, prev, WSIZE); */
1158/* Link to older string with same hash index. To limit the size of this
1159 * array to 64K, this link is maintained only for the last 32K strings.
1160 * An index in this array is thus a window index modulo 32K.
1161 */
1162
1163/* DECLARE(Pos, head, 1<<HASH_BITS); */
1164/* Heads of the hash chains or NIL. */
1165
Erik Andersene49d5ec2000-02-08 19:58:47 +00001166ulg window_size = (ulg) 2 * WSIZE;
1167
Eric Andersencc8ed391999-10-05 16:24:54 +00001168/* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
1169 * input file length plus MIN_LOOKAHEAD.
1170 */
1171
1172long block_start;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001173
Eric Andersencc8ed391999-10-05 16:24:54 +00001174/* window position at the beginning of the current output block. Gets
1175 * negative when the window is moved backwards.
1176 */
1177
Erik Andersene49d5ec2000-02-08 19:58:47 +00001178local unsigned ins_h; /* hash index of string to be inserted */
Eric Andersencc8ed391999-10-05 16:24:54 +00001179
1180#define H_SHIFT ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
1181/* Number of bits by which ins_h and del_h must be shifted at each
1182 * input step. It must be such that after MIN_MATCH steps, the oldest
1183 * byte no longer takes part in the hash key, that is:
1184 * H_SHIFT * MIN_MATCH >= HASH_BITS
1185 */
1186
1187unsigned int near prev_length;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001188
Eric Andersencc8ed391999-10-05 16:24:54 +00001189/* Length of the best match at previous step. Matches not greater than this
1190 * are discarded. This is used in the lazy match evaluation.
1191 */
1192
Erik Andersene49d5ec2000-02-08 19:58:47 +00001193unsigned near strstart; /* start of string to insert */
1194unsigned near match_start; /* start of matching string */
1195local int eofile; /* flag set at end of input file */
1196local unsigned lookahead; /* number of valid bytes ahead in window */
Eric Andersencc8ed391999-10-05 16:24:54 +00001197
1198unsigned near max_chain_length;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001199
Eric Andersencc8ed391999-10-05 16:24:54 +00001200/* To speed up deflation, hash chains are never searched beyond this length.
1201 * A higher limit improves compression ratio but degrades the speed.
1202 */
1203
1204local unsigned int max_lazy_match;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001205
Eric Andersencc8ed391999-10-05 16:24:54 +00001206/* Attempt to find a better match only when the current match is strictly
1207 * smaller than this value. This mechanism is used only for compression
1208 * levels >= 4.
1209 */
1210#define max_insert_length max_lazy_match
1211/* Insert new strings in the hash table only if the match length
1212 * is not greater than this length. This saves time but degrades compression.
1213 * max_insert_length is used only for compression levels <= 3.
1214 */
1215
1216unsigned near good_match;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001217
Eric Andersencc8ed391999-10-05 16:24:54 +00001218/* Use a faster search when the previous match is longer than this */
1219
1220
1221/* Values for max_lazy_match, good_match and max_chain_length, depending on
1222 * the desired pack level (0..9). The values given below have been tuned to
1223 * exclude worst case performance for pathological files. Better values may be
1224 * found for specific files.
1225 */
1226
1227typedef struct config {
Erik Andersene49d5ec2000-02-08 19:58:47 +00001228 ush good_length; /* reduce lazy search above this match length */
1229 ush max_lazy; /* do not perform lazy search above this match length */
1230 ush nice_length; /* quit search above this match length */
1231 ush max_chain;
Eric Andersencc8ed391999-10-05 16:24:54 +00001232} config;
1233
1234#ifdef FULL_SEARCH
1235# define nice_match MAX_MATCH
1236#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001237int near nice_match; /* Stop searching when current match exceeds this */
Eric Andersencc8ed391999-10-05 16:24:54 +00001238#endif
1239
Erik Andersene49d5ec2000-02-08 19:58:47 +00001240local config configuration_table =
1241 /* 9 */ { 32, 258, 258, 4096 };
1242 /* maximum compression */
Eric Andersencc8ed391999-10-05 16:24:54 +00001243
1244/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
1245 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
1246 * meaning.
1247 */
1248
1249#define EQUAL 0
1250/* result of memcmp for equal strings */
1251
1252/* ===========================================================================
1253 * Prototypes for local functions.
1254 */
Erik Andersen61677fe2000-04-13 01:18:56 +00001255local void fill_window (void);
Eric Andersencc8ed391999-10-05 16:24:54 +00001256
Erik Andersen61677fe2000-04-13 01:18:56 +00001257int longest_match (IPos cur_match);
Erik Andersene49d5ec2000-02-08 19:58:47 +00001258
Eric Andersencc8ed391999-10-05 16:24:54 +00001259#ifdef ASMV
Erik Andersen61677fe2000-04-13 01:18:56 +00001260void match_init (void); /* asm code initialization */
Eric Andersencc8ed391999-10-05 16:24:54 +00001261#endif
1262
1263#ifdef DEBUG
Erik Andersen61677fe2000-04-13 01:18:56 +00001264local void check_match (IPos start, IPos match, int length);
Eric Andersencc8ed391999-10-05 16:24:54 +00001265#endif
1266
1267/* ===========================================================================
1268 * Update a hash value with the given input byte
1269 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
1270 * input characters, so that a running hash key can be computed from the
1271 * previous key instead of complete recalculation each time.
1272 */
1273#define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
1274
1275/* ===========================================================================
1276 * Insert string s in the dictionary and set match_head to the previous head
1277 * of the hash chain (the most recent string with same hash key). Return
1278 * the previous length of the hash chain.
1279 * IN assertion: all calls to to INSERT_STRING are made with consecutive
1280 * input characters and the first MIN_MATCH bytes of s are valid
1281 * (except for the last MIN_MATCH-1 bytes of the input file).
1282 */
1283#define INSERT_STRING(s, match_head) \
1284 (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
1285 prev[(s) & WMASK] = match_head = head[ins_h], \
1286 head[ins_h] = (s))
1287
1288/* ===========================================================================
1289 * Initialize the "longest match" routines for a new file
1290 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00001291void lm_init(flags)
1292ush *flags; /* general purpose bit flag */
Eric Andersencc8ed391999-10-05 16:24:54 +00001293{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001294 register unsigned j;
Eric Andersencc8ed391999-10-05 16:24:54 +00001295
Erik Andersene49d5ec2000-02-08 19:58:47 +00001296 /* Initialize the hash table. */
Eric Andersencc8ed391999-10-05 16:24:54 +00001297#if defined(MAXSEG_64K) && HASH_BITS == 15
Erik Andersene49d5ec2000-02-08 19:58:47 +00001298 for (j = 0; j < HASH_SIZE; j++)
1299 head[j] = NIL;
Eric Andersencc8ed391999-10-05 16:24:54 +00001300#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001301 memzero((char *) head, HASH_SIZE * sizeof(*head));
Eric Andersencc8ed391999-10-05 16:24:54 +00001302#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001303 /* prev will be initialized on the fly */
Eric Andersencc8ed391999-10-05 16:24:54 +00001304
Erik Andersene49d5ec2000-02-08 19:58:47 +00001305 /* Set the default configuration parameters:
1306 */
1307 max_lazy_match = configuration_table.max_lazy;
1308 good_match = configuration_table.good_length;
Eric Andersencc8ed391999-10-05 16:24:54 +00001309#ifndef FULL_SEARCH
Erik Andersene49d5ec2000-02-08 19:58:47 +00001310 nice_match = configuration_table.nice_length;
Eric Andersencc8ed391999-10-05 16:24:54 +00001311#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001312 max_chain_length = configuration_table.max_chain;
1313 *flags |= SLOW;
1314 /* ??? reduce max_chain_length for binary files */
Eric Andersencc8ed391999-10-05 16:24:54 +00001315
Erik Andersene49d5ec2000-02-08 19:58:47 +00001316 strstart = 0;
1317 block_start = 0L;
Eric Andersencc8ed391999-10-05 16:24:54 +00001318#ifdef ASMV
Erik Andersene49d5ec2000-02-08 19:58:47 +00001319 match_init(); /* initialize the asm code */
Eric Andersencc8ed391999-10-05 16:24:54 +00001320#endif
1321
Erik Andersene49d5ec2000-02-08 19:58:47 +00001322 lookahead = read_buf((char *) window,
1323 sizeof(int) <= 2 ? (unsigned) WSIZE : 2 * WSIZE);
Eric Andersencc8ed391999-10-05 16:24:54 +00001324
Erik Andersene49d5ec2000-02-08 19:58:47 +00001325 if (lookahead == 0 || lookahead == (unsigned) EOF) {
1326 eofile = 1, lookahead = 0;
1327 return;
1328 }
1329 eofile = 0;
1330 /* Make sure that we always have enough lookahead. This is important
1331 * if input comes from a device such as a tty.
1332 */
1333 while (lookahead < MIN_LOOKAHEAD && !eofile)
1334 fill_window();
Eric Andersencc8ed391999-10-05 16:24:54 +00001335
Erik Andersene49d5ec2000-02-08 19:58:47 +00001336 ins_h = 0;
1337 for (j = 0; j < MIN_MATCH - 1; j++)
1338 UPDATE_HASH(ins_h, window[j]);
1339 /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
1340 * not important since only literal bytes will be emitted.
1341 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001342}
1343
1344/* ===========================================================================
1345 * Set match_start to the longest match starting at the given string and
1346 * return its length. Matches shorter or equal to prev_length are discarded,
1347 * in which case the result is equal to prev_length and match_start is
1348 * garbage.
1349 * IN assertions: cur_match is the head of the hash chain for the current
1350 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1351 */
1352#ifndef ASMV
1353/* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
1354 * match.s. The code is functionally equivalent, so you can use the C version
1355 * if desired.
1356 */
1357int longest_match(cur_match)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001358IPos cur_match; /* current match */
Eric Andersencc8ed391999-10-05 16:24:54 +00001359{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001360 unsigned chain_length = max_chain_length; /* max hash chain length */
1361 register uch *scan = window + strstart; /* current string */
1362 register uch *match; /* matched string */
1363 register int len; /* length of current match */
1364 int best_len = prev_length; /* best match length so far */
1365 IPos limit =
1366
1367 strstart > (IPos) MAX_DIST ? strstart - (IPos) MAX_DIST : NIL;
1368 /* Stop when cur_match becomes <= limit. To simplify the code,
1369 * we prevent matches with the string of window index 0.
1370 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001371
1372/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1373 * It is easy to get rid of this optimization if necessary.
1374 */
1375#if HASH_BITS < 8 || MAX_MATCH != 258
Erik Andersene49d5ec2000-02-08 19:58:47 +00001376 error:Code too clever
Eric Andersencc8ed391999-10-05 16:24:54 +00001377#endif
Eric Andersencc8ed391999-10-05 16:24:54 +00001378#ifdef UNALIGNED_OK
Erik Andersene49d5ec2000-02-08 19:58:47 +00001379 /* Compare two bytes at a time. Note: this is not always beneficial.
1380 * Try with and without -DUNALIGNED_OK to check.
1381 */
1382 register uch *strend = window + strstart + MAX_MATCH - 1;
1383 register ush scan_start = *(ush *) scan;
1384 register ush scan_end = *(ush *) (scan + best_len - 1);
Eric Andersencc8ed391999-10-05 16:24:54 +00001385#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001386 register uch *strend = window + strstart + MAX_MATCH;
1387 register uch scan_end1 = scan[best_len - 1];
1388 register uch scan_end = scan[best_len];
Eric Andersencc8ed391999-10-05 16:24:54 +00001389#endif
1390
Erik Andersene49d5ec2000-02-08 19:58:47 +00001391 /* Do not waste too much time if we already have a good match: */
1392 if (prev_length >= good_match) {
1393 chain_length >>= 2;
1394 }
1395 Assert(strstart <= window_size - MIN_LOOKAHEAD,
1396 "insufficient lookahead");
Eric Andersencc8ed391999-10-05 16:24:54 +00001397
Erik Andersene49d5ec2000-02-08 19:58:47 +00001398 do {
1399 Assert(cur_match < strstart, "no future");
1400 match = window + cur_match;
Eric Andersencc8ed391999-10-05 16:24:54 +00001401
Erik Andersene49d5ec2000-02-08 19:58:47 +00001402 /* Skip to next match if the match length cannot increase
1403 * or if the match length is less than 2:
1404 */
Eric Andersencc8ed391999-10-05 16:24:54 +00001405#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001406 /* This code assumes sizeof(unsigned short) == 2. Do not use
1407 * UNALIGNED_OK if your compiler uses a different size.
1408 */
1409 if (*(ush *) (match + best_len - 1) != scan_end ||
1410 *(ush *) match != scan_start)
1411 continue;
Eric Andersencc8ed391999-10-05 16:24:54 +00001412
Erik Andersene49d5ec2000-02-08 19:58:47 +00001413 /* It is not necessary to compare scan[2] and match[2] since they are
1414 * always equal when the other bytes match, given that the hash keys
1415 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1416 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1417 * lookahead only every 4th comparison; the 128th check will be made
1418 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1419 * necessary to put more guard bytes at the end of the window, or
1420 * to check more often for insufficient lookahead.
1421 */
1422 scan++, match++;
1423 do {
1424 } while (*(ush *) (scan += 2) == *(ush *) (match += 2) &&
1425 *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1426 *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1427 *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1428 scan < strend);
1429 /* The funny "do {}" generates better code on most compilers */
Eric Andersencc8ed391999-10-05 16:24:54 +00001430
Erik Andersene49d5ec2000-02-08 19:58:47 +00001431 /* Here, scan <= window+strstart+257 */
1432 Assert(scan <= window + (unsigned) (window_size - 1), "wild scan");
1433 if (*scan == *match)
1434 scan++;
Eric Andersencc8ed391999-10-05 16:24:54 +00001435
Erik Andersene49d5ec2000-02-08 19:58:47 +00001436 len = (MAX_MATCH - 1) - (int) (strend - scan);
1437 scan = strend - (MAX_MATCH - 1);
Eric Andersencc8ed391999-10-05 16:24:54 +00001438
Erik Andersene49d5ec2000-02-08 19:58:47 +00001439#else /* UNALIGNED_OK */
Eric Andersencc8ed391999-10-05 16:24:54 +00001440
Erik Andersene49d5ec2000-02-08 19:58:47 +00001441 if (match[best_len] != scan_end ||
1442 match[best_len - 1] != scan_end1 ||
1443 *match != *scan || *++match != scan[1])
1444 continue;
Eric Andersencc8ed391999-10-05 16:24:54 +00001445
Erik Andersene49d5ec2000-02-08 19:58:47 +00001446 /* The check at best_len-1 can be removed because it will be made
1447 * again later. (This heuristic is not always a win.)
1448 * It is not necessary to compare scan[2] and match[2] since they
1449 * are always equal when the other bytes match, given that
1450 * the hash keys are equal and that HASH_BITS >= 8.
1451 */
1452 scan += 2, match++;
Eric Andersencc8ed391999-10-05 16:24:54 +00001453
Erik Andersene49d5ec2000-02-08 19:58:47 +00001454 /* We check for insufficient lookahead only every 8th comparison;
1455 * the 256th check will be made at strstart+258.
1456 */
1457 do {
1458 } while (*++scan == *++match && *++scan == *++match &&
1459 *++scan == *++match && *++scan == *++match &&
1460 *++scan == *++match && *++scan == *++match &&
1461 *++scan == *++match && *++scan == *++match &&
1462 scan < strend);
Eric Andersencc8ed391999-10-05 16:24:54 +00001463
Erik Andersene49d5ec2000-02-08 19:58:47 +00001464 len = MAX_MATCH - (int) (strend - scan);
1465 scan = strend - MAX_MATCH;
Eric Andersencc8ed391999-10-05 16:24:54 +00001466
Erik Andersene49d5ec2000-02-08 19:58:47 +00001467#endif /* UNALIGNED_OK */
Eric Andersencc8ed391999-10-05 16:24:54 +00001468
Erik Andersene49d5ec2000-02-08 19:58:47 +00001469 if (len > best_len) {
1470 match_start = cur_match;
1471 best_len = len;
1472 if (len >= nice_match)
1473 break;
Eric Andersencc8ed391999-10-05 16:24:54 +00001474#ifdef UNALIGNED_OK
Erik Andersene49d5ec2000-02-08 19:58:47 +00001475 scan_end = *(ush *) (scan + best_len - 1);
Eric Andersencc8ed391999-10-05 16:24:54 +00001476#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001477 scan_end1 = scan[best_len - 1];
1478 scan_end = scan[best_len];
Eric Andersencc8ed391999-10-05 16:24:54 +00001479#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001480 }
1481 } while ((cur_match = prev[cur_match & WMASK]) > limit
1482 && --chain_length != 0);
Eric Andersencc8ed391999-10-05 16:24:54 +00001483
Erik Andersene49d5ec2000-02-08 19:58:47 +00001484 return best_len;
Eric Andersencc8ed391999-10-05 16:24:54 +00001485}
Erik Andersene49d5ec2000-02-08 19:58:47 +00001486#endif /* ASMV */
Eric Andersencc8ed391999-10-05 16:24:54 +00001487
1488#ifdef DEBUG
1489/* ===========================================================================
1490 * Check that the match at match_start is indeed a match.
1491 */
1492local void check_match(start, match, length)
Erik Andersene49d5ec2000-02-08 19:58:47 +00001493IPos start, match;
1494int length;
Eric Andersencc8ed391999-10-05 16:24:54 +00001495{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001496 /* check that the match is indeed a match */
1497 if (memcmp((char *) window + match,
1498 (char *) window + start, length) != EQUAL) {
1499 fprintf(stderr,
1500 " start %d, match %d, length %d\n", start, match, length);
Matt Kraaidd19c692001-01-31 19:00:21 +00001501 error_msg("invalid match");
Erik Andersene49d5ec2000-02-08 19:58:47 +00001502 }
1503 if (verbose > 1) {
1504 fprintf(stderr, "\\[%d,%d]", start - match, length);
1505 do {
1506 putc(window[start++], stderr);
1507 } while (--length != 0);
1508 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001509}
1510#else
1511# define check_match(start, match, length)
1512#endif
1513
1514/* ===========================================================================
1515 * Fill the window when the lookahead becomes insufficient.
1516 * Updates strstart and lookahead, and sets eofile if end of input file.
1517 * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
1518 * OUT assertions: at least one byte has been read, or eofile is set;
1519 * file reads are performed for at least two bytes (required for the
1520 * translate_eol option).
1521 */
1522local void fill_window()
1523{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001524 register unsigned n, m;
1525 unsigned more =
Eric Andersencc8ed391999-10-05 16:24:54 +00001526
Erik Andersene49d5ec2000-02-08 19:58:47 +00001527 (unsigned) (window_size - (ulg) lookahead - (ulg) strstart);
1528 /* Amount of free space at the end of the window. */
Eric Andersencc8ed391999-10-05 16:24:54 +00001529
Erik Andersene49d5ec2000-02-08 19:58:47 +00001530 /* If the window is almost full and there is insufficient lookahead,
1531 * move the upper half to the lower one to make room in the upper half.
1532 */
1533 if (more == (unsigned) EOF) {
1534 /* Very unlikely, but possible on 16 bit machine if strstart == 0
1535 * and lookahead == 1 (input done one byte at time)
1536 */
1537 more--;
1538 } else if (strstart >= WSIZE + MAX_DIST) {
1539 /* By the IN assertion, the window is not empty so we can't confuse
1540 * more == 0 with more == 64K on a 16 bit machine.
1541 */
1542 Assert(window_size == (ulg) 2 * WSIZE, "no sliding with BIG_MEM");
Eric Andersencc8ed391999-10-05 16:24:54 +00001543
Erik Andersene49d5ec2000-02-08 19:58:47 +00001544 memcpy((char *) window, (char *) window + WSIZE, (unsigned) WSIZE);
1545 match_start -= WSIZE;
1546 strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
Eric Andersencc8ed391999-10-05 16:24:54 +00001547
Erik Andersene49d5ec2000-02-08 19:58:47 +00001548 block_start -= (long) WSIZE;
1549
1550 for (n = 0; n < HASH_SIZE; n++) {
1551 m = head[n];
1552 head[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
1553 }
1554 for (n = 0; n < WSIZE; n++) {
1555 m = prev[n];
1556 prev[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
1557 /* If n is not on any hash chain, prev[n] is garbage but
1558 * its value will never be used.
1559 */
1560 }
1561 more += WSIZE;
1562 }
1563 /* At this point, more >= 2 */
1564 if (!eofile) {
1565 n = read_buf((char *) window + strstart + lookahead, more);
1566 if (n == 0 || n == (unsigned) EOF) {
1567 eofile = 1;
1568 } else {
1569 lookahead += n;
1570 }
1571 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001572}
1573
1574/* ===========================================================================
1575 * Flush the current block, with given end-of-file flag.
1576 * IN assertion: strstart is set to the end of the current match.
1577 */
1578#define FLUSH_BLOCK(eof) \
1579 flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
1580 (char*)NULL, (long)strstart - block_start, (eof))
1581
1582/* ===========================================================================
1583 * Same as above, but achieves better compression. We use a lazy
1584 * evaluation for matches: a match is finally adopted only if there is
1585 * no better match at the next window position.
1586 */
1587ulg deflate()
1588{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001589 IPos hash_head; /* head of hash chain */
1590 IPos prev_match; /* previous match */
1591 int flush; /* set if current block must be flushed */
1592 int match_available = 0; /* set if previous match exists */
1593 register unsigned match_length = MIN_MATCH - 1; /* length of best match */
1594
Eric Andersencc8ed391999-10-05 16:24:54 +00001595#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +00001596 extern long isize; /* byte length of input file, for debug only */
Eric Andersencc8ed391999-10-05 16:24:54 +00001597#endif
1598
Erik Andersene49d5ec2000-02-08 19:58:47 +00001599 /* Process the input block. */
1600 while (lookahead != 0) {
1601 /* Insert the string window[strstart .. strstart+2] in the
1602 * dictionary, and set hash_head to the head of the hash chain:
1603 */
1604 INSERT_STRING(strstart, hash_head);
Eric Andersencc8ed391999-10-05 16:24:54 +00001605
Erik Andersene49d5ec2000-02-08 19:58:47 +00001606 /* Find the longest match, discarding those <= prev_length.
1607 */
1608 prev_length = match_length, prev_match = match_start;
1609 match_length = MIN_MATCH - 1;
Eric Andersencc8ed391999-10-05 16:24:54 +00001610
Erik Andersene49d5ec2000-02-08 19:58:47 +00001611 if (hash_head != NIL && prev_length < max_lazy_match &&
1612 strstart - hash_head <= MAX_DIST) {
1613 /* To simplify the code, we prevent matches with the string
1614 * of window index 0 (in particular we have to avoid a match
1615 * of the string with itself at the start of the input file).
1616 */
1617 match_length = longest_match(hash_head);
1618 /* longest_match() sets match_start */
1619 if (match_length > lookahead)
1620 match_length = lookahead;
Eric Andersencc8ed391999-10-05 16:24:54 +00001621
Erik Andersene49d5ec2000-02-08 19:58:47 +00001622 /* Ignore a length 3 match if it is too distant: */
1623 if (match_length == MIN_MATCH
1624 && strstart - match_start > TOO_FAR) {
1625 /* If prev_match is also MIN_MATCH, match_start is garbage
1626 * but we will ignore the current match anyway.
1627 */
1628 match_length--;
1629 }
1630 }
1631 /* If there was a match at the previous step and the current
1632 * match is not better, output the previous match:
1633 */
1634 if (prev_length >= MIN_MATCH && match_length <= prev_length) {
Eric Andersencc8ed391999-10-05 16:24:54 +00001635
Erik Andersene49d5ec2000-02-08 19:58:47 +00001636 check_match(strstart - 1, prev_match, prev_length);
Eric Andersencc8ed391999-10-05 16:24:54 +00001637
Erik Andersene49d5ec2000-02-08 19:58:47 +00001638 flush =
1639 ct_tally(strstart - 1 - prev_match,
1640 prev_length - MIN_MATCH);
Eric Andersencc8ed391999-10-05 16:24:54 +00001641
Erik Andersene49d5ec2000-02-08 19:58:47 +00001642 /* Insert in hash table all strings up to the end of the match.
1643 * strstart-1 and strstart are already inserted.
1644 */
1645 lookahead -= prev_length - 1;
1646 prev_length -= 2;
1647 do {
1648 strstart++;
1649 INSERT_STRING(strstart, hash_head);
1650 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1651 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
1652 * these bytes are garbage, but it does not matter since the
1653 * next lookahead bytes will always be emitted as literals.
1654 */
1655 } while (--prev_length != 0);
1656 match_available = 0;
1657 match_length = MIN_MATCH - 1;
1658 strstart++;
1659 if (flush)
1660 FLUSH_BLOCK(0), block_start = strstart;
Eric Andersencc8ed391999-10-05 16:24:54 +00001661
Erik Andersene49d5ec2000-02-08 19:58:47 +00001662 } else if (match_available) {
1663 /* If there was no match at the previous position, output a
1664 * single literal. If there was a match but the current match
1665 * is longer, truncate the previous match to a single literal.
1666 */
1667 Tracevv((stderr, "%c", window[strstart - 1]));
1668 if (ct_tally(0, window[strstart - 1])) {
1669 FLUSH_BLOCK(0), block_start = strstart;
1670 }
1671 strstart++;
1672 lookahead--;
1673 } else {
1674 /* There is no previous match to compare with, wait for
1675 * the next step to decide.
1676 */
1677 match_available = 1;
1678 strstart++;
1679 lookahead--;
1680 }
1681 Assert(strstart <= isize && lookahead <= isize, "a bit too far");
Eric Andersencc8ed391999-10-05 16:24:54 +00001682
Erik Andersene49d5ec2000-02-08 19:58:47 +00001683 /* Make sure that we always have enough lookahead, except
1684 * at the end of the input file. We need MAX_MATCH bytes
1685 * for the next match, plus MIN_MATCH bytes to insert the
1686 * string following the next match.
1687 */
1688 while (lookahead < MIN_LOOKAHEAD && !eofile)
1689 fill_window();
1690 }
1691 if (match_available)
1692 ct_tally(0, window[strstart - 1]);
Eric Andersencc8ed391999-10-05 16:24:54 +00001693
Erik Andersene49d5ec2000-02-08 19:58:47 +00001694 return FLUSH_BLOCK(1); /* eof */
Eric Andersencc8ed391999-10-05 16:24:54 +00001695}
Erik Andersene49d5ec2000-02-08 19:58:47 +00001696
Eric Andersencc8ed391999-10-05 16:24:54 +00001697/* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
1698 * Copyright (C) 1992-1993 Jean-loup Gailly
1699 * The unzip code was written and put in the public domain by Mark Adler.
1700 * Portions of the lzw code are derived from the public domain 'compress'
1701 * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
1702 * Ken Turkowski, Dave Mack and Peter Jannesen.
1703 *
1704 * See the license_msg below and the file COPYING for the software license.
1705 * See the file algorithm.doc for the compression algorithms and file formats.
1706 */
1707
1708/* Compress files with zip algorithm and 'compress' interface.
1709 * See usage() and help() functions below for all options.
1710 * Outputs:
1711 * file.gz: compressed file with same mode, owner, and utimes
1712 * or stdout with -c option or if stdin used as input.
1713 * If the output file name had to be truncated, the original name is kept
1714 * in the compressed file.
1715 * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
1716 *
1717 * Using gz on MSDOS would create too many file name conflicts. For
1718 * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for
1719 * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz.
1720 * I also considered 12345678.txt -> 12345txt.gz but this truncates the name
1721 * too heavily. There is no ideal solution given the MSDOS 8+3 limitation.
1722 *
1723 * For the meaning of all compilation flags, see comments in Makefile.in.
1724 */
1725
Eric Andersencc8ed391999-10-05 16:24:54 +00001726#include <ctype.h>
1727#include <sys/types.h>
1728#include <signal.h>
Eric Andersencc8ed391999-10-05 16:24:54 +00001729#include <errno.h>
1730
1731 /* configuration */
1732
1733#ifdef NO_TIME_H
1734# include <sys/time.h>
1735#else
1736# include <time.h>
1737#endif
1738
1739#ifndef NO_FCNTL_H
1740# include <fcntl.h>
1741#endif
1742
1743#ifdef HAVE_UNISTD_H
1744# include <unistd.h>
1745#endif
1746
Eric Andersencc8ed391999-10-05 16:24:54 +00001747#if defined(DIRENT)
1748# include <dirent.h>
Erik Andersene49d5ec2000-02-08 19:58:47 +00001749typedef struct dirent dir_type;
1750
Eric Andersencc8ed391999-10-05 16:24:54 +00001751# define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
1752# define DIR_OPT "DIRENT"
1753#else
1754# define NLENGTH(dirent) ((dirent)->d_namlen)
1755# ifdef SYSDIR
1756# include <sys/dir.h>
Erik Andersene49d5ec2000-02-08 19:58:47 +00001757typedef struct direct dir_type;
1758
Eric Andersencc8ed391999-10-05 16:24:54 +00001759# define DIR_OPT "SYSDIR"
1760# else
1761# ifdef SYSNDIR
1762# include <sys/ndir.h>
Erik Andersene49d5ec2000-02-08 19:58:47 +00001763typedef struct direct dir_type;
1764
Eric Andersencc8ed391999-10-05 16:24:54 +00001765# define DIR_OPT "SYSNDIR"
1766# else
1767# ifdef NDIR
1768# include <ndir.h>
Erik Andersene49d5ec2000-02-08 19:58:47 +00001769typedef struct direct dir_type;
1770
Eric Andersencc8ed391999-10-05 16:24:54 +00001771# define DIR_OPT "NDIR"
1772# else
1773# define NO_DIR
1774# define DIR_OPT "NO_DIR"
1775# endif
1776# endif
1777# endif
1778#endif
1779
1780#ifndef NO_UTIME
1781# ifndef NO_UTIME_H
1782# include <utime.h>
1783# define TIME_OPT "UTIME"
1784# else
1785# ifdef HAVE_SYS_UTIME_H
1786# include <sys/utime.h>
1787# define TIME_OPT "SYS_UTIME"
1788# else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001789struct utimbuf {
1790 time_t actime;
1791 time_t modtime;
1792};
1793
Eric Andersencc8ed391999-10-05 16:24:54 +00001794# define TIME_OPT ""
1795# endif
1796# endif
1797#else
1798# define TIME_OPT "NO_UTIME"
1799#endif
1800
1801#if !defined(S_ISDIR) && defined(S_IFDIR)
1802# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1803#endif
1804#if !defined(S_ISREG) && defined(S_IFREG)
1805# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1806#endif
1807
Erik Andersen61677fe2000-04-13 01:18:56 +00001808typedef RETSIGTYPE(*sig_type) (int);
Eric Andersencc8ed391999-10-05 16:24:54 +00001809
1810#ifndef O_BINARY
Erik Andersene49d5ec2000-02-08 19:58:47 +00001811# define O_BINARY 0 /* creation mode for open() */
Eric Andersencc8ed391999-10-05 16:24:54 +00001812#endif
1813
1814#ifndef O_CREAT
1815 /* Pure BSD system? */
1816# include <sys/file.h>
1817# ifndef O_CREAT
1818# define O_CREAT FCREAT
1819# endif
1820# ifndef O_EXCL
1821# define O_EXCL FEXCL
1822# endif
1823#endif
1824
1825#ifndef S_IRUSR
1826# define S_IRUSR 0400
1827#endif
1828#ifndef S_IWUSR
1829# define S_IWUSR 0200
1830#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00001831#define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */
Eric Andersencc8ed391999-10-05 16:24:54 +00001832
1833#ifndef MAX_PATH_LEN
Erik Andersene49d5ec2000-02-08 19:58:47 +00001834# define MAX_PATH_LEN 1024 /* max pathname length */
Eric Andersencc8ed391999-10-05 16:24:54 +00001835#endif
1836
1837#ifndef SEEK_END
1838# define SEEK_END 2
1839#endif
1840
1841#ifdef NO_OFF_T
Erik Andersene49d5ec2000-02-08 19:58:47 +00001842typedef long off_t;
Erik Andersen61677fe2000-04-13 01:18:56 +00001843off_t lseek (int fd, off_t offset, int whence);
Eric Andersencc8ed391999-10-05 16:24:54 +00001844#endif
1845
1846/* Separator for file name parts (see shorten_name()) */
1847#ifdef NO_MULTIPLE_DOTS
1848# define PART_SEP "-"
1849#else
1850# define PART_SEP "."
1851#endif
1852
1853 /* global buffers */
1854
Erik Andersene49d5ec2000-02-08 19:58:47 +00001855DECLARE(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
1856DECLARE(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
1857DECLARE(ush, d_buf, DIST_BUFSIZE);
1858DECLARE(uch, window, 2L * WSIZE);
Eric Andersencc8ed391999-10-05 16:24:54 +00001859#ifndef MAXSEG_64K
Erik Andersene49d5ec2000-02-08 19:58:47 +00001860DECLARE(ush, tab_prefix, 1L << BITS);
Eric Andersencc8ed391999-10-05 16:24:54 +00001861#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001862DECLARE(ush, tab_prefix0, 1L << (BITS - 1));
1863DECLARE(ush, tab_prefix1, 1L << (BITS - 1));
Eric Andersencc8ed391999-10-05 16:24:54 +00001864#endif
1865
1866 /* local variables */
1867
Eric Andersen63a86222000-11-07 06:52:13 +00001868static int foreground; /* set if program run in foreground */
Erik Andersene49d5ec2000-02-08 19:58:47 +00001869static int method = DEFLATED; /* compression method */
1870static int exit_code = OK; /* program exit code */
Eric Andersen63a86222000-11-07 06:52:13 +00001871static int part_nb; /* number of parts in .gz file */
1872static long time_stamp; /* original time stamp (modification time) */
1873static long ifile_size; /* input file size, -1 for devices (debug only) */
1874static char z_suffix[MAX_SUFFIX + 1]; /* default suffix (can be set with --suffix) */
1875static int z_len; /* strlen(z_suffix) */
Eric Andersencc8ed391999-10-05 16:24:54 +00001876
Eric Andersen63a86222000-11-07 06:52:13 +00001877static long bytes_in; /* number of input bytes */
1878static long bytes_out; /* number of output bytes */
1879static char ifname[MAX_PATH_LEN]; /* input file name */
1880static char ofname[MAX_PATH_LEN]; /* output file name */
1881static int ifd; /* input file descriptor */
1882static int ofd; /* output file descriptor */
1883static unsigned insize; /* valid bytes in inbuf */
1884static unsigned outcnt; /* bytes in output buffer */
Eric Andersencc8ed391999-10-05 16:24:54 +00001885
1886/* local functions */
1887
Eric Andersencc8ed391999-10-05 16:24:54 +00001888#define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
1889
1890/* ======================================================================== */
1891// int main (argc, argv)
1892// int argc;
1893// char **argv;
Erik Andersene49d5ec2000-02-08 19:58:47 +00001894int gzip_main(int argc, char **argv)
Eric Andersencc8ed391999-10-05 16:24:54 +00001895{
Erik Andersene49d5ec2000-02-08 19:58:47 +00001896 int result;
1897 int inFileNum;
1898 int outFileNum;
1899 struct stat statBuf;
1900 char *delFileName;
1901 int tostdout = 0;
1902 int fromstdin = 0;
Eric Andersenea824fb2000-07-21 22:17:39 +00001903 int force = 0;
Eric Andersen96bcfd31999-11-12 01:30:18 +00001904
Erik Andersene49d5ec2000-02-08 19:58:47 +00001905 /* Parse any options */
1906 while (--argc > 0 && **(++argv) == '-') {
1907 if (*((*argv) + 1) == '\0') {
Erik Andersene49d5ec2000-02-08 19:58:47 +00001908 tostdout = 1;
1909 }
1910 while (*(++(*argv))) {
1911 switch (**argv) {
1912 case 'c':
1913 tostdout = 1;
1914 break;
Eric Andersenea824fb2000-07-21 22:17:39 +00001915 case 'f':
1916 force = 1;
1917 break;
1918 /* Ignore 1-9 (compression level) options */
1919 case '1': case '2': case '3': case '4': case '5':
1920 case '6': case '7': case '8': case '9':
1921 break;
Eric Andersen02ced932000-12-13 17:55:11 +00001922 case 'd':
1923 exit(gunzip_main(argc, argv));
Erik Andersene49d5ec2000-02-08 19:58:47 +00001924 default:
Eric Andersen67991cf2001-02-14 21:23:06 +00001925 show_usage();
Erik Andersene49d5ec2000-02-08 19:58:47 +00001926 }
1927 }
1928 }
Eric Andersen5eb59122000-09-01 00:33:06 +00001929 if (argc <= 0 ) {
Eric Andersenea824fb2000-07-21 22:17:39 +00001930 fromstdin = 1;
Eric Andersen5eb59122000-09-01 00:33:06 +00001931 tostdout = 1;
1932 }
Eric Andersenea824fb2000-07-21 22:17:39 +00001933
1934 if (isatty(fileno(stdin)) && fromstdin==1 && force==0)
Matt Kraaidd19c692001-01-31 19:00:21 +00001935 error_msg_and_die( "data not read from terminal. Use -f to force it.");
Eric Andersenea824fb2000-07-21 22:17:39 +00001936 if (isatty(fileno(stdout)) && tostdout==1 && force==0)
Matt Kraaidd19c692001-01-31 19:00:21 +00001937 error_msg_and_die( "data not written to terminal. Use -f to force it.");
Erik Andersene49d5ec2000-02-08 19:58:47 +00001938
1939 foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
1940 if (foreground) {
1941 (void) signal(SIGINT, (sig_type) abort_gzip);
1942 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001943#ifdef SIGTERM
Erik Andersene49d5ec2000-02-08 19:58:47 +00001944 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
1945 (void) signal(SIGTERM, (sig_type) abort_gzip);
1946 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001947#endif
1948#ifdef SIGHUP
Erik Andersene49d5ec2000-02-08 19:58:47 +00001949 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
1950 (void) signal(SIGHUP, (sig_type) abort_gzip);
1951 }
Eric Andersencc8ed391999-10-05 16:24:54 +00001952#endif
1953
Erik Andersene49d5ec2000-02-08 19:58:47 +00001954 strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix) - 1);
1955 z_len = strlen(z_suffix);
Eric Andersencc8ed391999-10-05 16:24:54 +00001956
Erik Andersene49d5ec2000-02-08 19:58:47 +00001957 /* Allocate all global buffers (for DYN_ALLOC option) */
1958 ALLOC(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
1959 ALLOC(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
1960 ALLOC(ush, d_buf, DIST_BUFSIZE);
1961 ALLOC(uch, window, 2L * WSIZE);
Eric Andersencc8ed391999-10-05 16:24:54 +00001962#ifndef MAXSEG_64K
Erik Andersene49d5ec2000-02-08 19:58:47 +00001963 ALLOC(ush, tab_prefix, 1L << BITS);
Eric Andersencc8ed391999-10-05 16:24:54 +00001964#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00001965 ALLOC(ush, tab_prefix0, 1L << (BITS - 1));
1966 ALLOC(ush, tab_prefix1, 1L << (BITS - 1));
Eric Andersencc8ed391999-10-05 16:24:54 +00001967#endif
1968
Erik Andersene49d5ec2000-02-08 19:58:47 +00001969 if (fromstdin == 1) {
1970 strcpy(ofname, "stdin");
Eric Andersen96bcfd31999-11-12 01:30:18 +00001971
Erik Andersene49d5ec2000-02-08 19:58:47 +00001972 inFileNum = fileno(stdin);
1973 time_stamp = 0; /* time unknown by default */
1974 ifile_size = -1L; /* convention for unknown size */
1975 } else {
1976 /* Open up the input file */
Eric Andersenea824fb2000-07-21 22:17:39 +00001977 if (argc <= 0)
Eric Andersen67991cf2001-02-14 21:23:06 +00001978 show_usage();
Erik Andersene49d5ec2000-02-08 19:58:47 +00001979 strncpy(ifname, *argv, MAX_PATH_LEN);
Eric Andersen96bcfd31999-11-12 01:30:18 +00001980
Matt Kraaia9819b22000-12-22 01:48:07 +00001981 /* Open input file */
Erik Andersene49d5ec2000-02-08 19:58:47 +00001982 inFileNum = open(ifname, O_RDONLY);
Matt Kraaia9819b22000-12-22 01:48:07 +00001983 if (inFileNum < 0)
1984 perror_msg_and_die("%s", ifname);
Erik Andersene49d5ec2000-02-08 19:58:47 +00001985 /* Get the time stamp on the input file. */
Matt Kraaia9819b22000-12-22 01:48:07 +00001986 if (stat(ifname, &statBuf) < 0)
1987 perror_msg_and_die("%s", ifname);
Erik Andersene49d5ec2000-02-08 19:58:47 +00001988 time_stamp = statBuf.st_ctime;
1989 ifile_size = statBuf.st_size;
Eric Andersen96bcfd31999-11-12 01:30:18 +00001990 }
Eric Andersen96bcfd31999-11-12 01:30:18 +00001991
1992
Erik Andersene49d5ec2000-02-08 19:58:47 +00001993 if (tostdout == 1) {
1994 /* And get to work */
1995 strcpy(ofname, "stdout");
1996 outFileNum = fileno(stdout);
1997 SET_BINARY_MODE(fileno(stdout));
Eric Andersen0dfac6b1999-11-11 05:46:32 +00001998
Erik Andersene49d5ec2000-02-08 19:58:47 +00001999 clear_bufs(); /* clear input and output buffers */
2000 part_nb = 0;
Eric Andersen0dfac6b1999-11-11 05:46:32 +00002001
Erik Andersene49d5ec2000-02-08 19:58:47 +00002002 /* Actually do the compression/decompression. */
2003 zip(inFileNum, outFileNum);
Eric Andersen0dfac6b1999-11-11 05:46:32 +00002004
Erik Andersene49d5ec2000-02-08 19:58:47 +00002005 } else {
Eric Andersen0dfac6b1999-11-11 05:46:32 +00002006
Erik Andersene49d5ec2000-02-08 19:58:47 +00002007 /* And get to work */
2008 strncpy(ofname, ifname, MAX_PATH_LEN - 4);
2009 strcat(ofname, ".gz");
Eric Andersen0dfac6b1999-11-11 05:46:32 +00002010
Eric Andersen0dfac6b1999-11-11 05:46:32 +00002011
Erik Andersene49d5ec2000-02-08 19:58:47 +00002012 /* Open output fille */
Erik Andersen4d1d0111999-12-17 18:44:15 +00002013#if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002014 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
Erik Andersen4d1d0111999-12-17 18:44:15 +00002015#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00002016 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL);
Erik Andersen4d1d0111999-12-17 18:44:15 +00002017#endif
Matt Kraaia9819b22000-12-22 01:48:07 +00002018 if (outFileNum < 0)
2019 perror_msg_and_die("%s", ofname);
Erik Andersene49d5ec2000-02-08 19:58:47 +00002020 SET_BINARY_MODE(outFileNum);
2021 /* Set permissions on the file */
2022 fchmod(outFileNum, statBuf.st_mode);
2023
2024 clear_bufs(); /* clear input and output buffers */
2025 part_nb = 0;
2026
2027 /* Actually do the compression/decompression. */
2028 result = zip(inFileNum, outFileNum);
2029 close(outFileNum);
2030 close(inFileNum);
2031 /* Delete the original file */
2032 if (result == OK)
2033 delFileName = ifname;
2034 else
2035 delFileName = ofname;
2036
Matt Kraaia9819b22000-12-22 01:48:07 +00002037 if (unlink(delFileName) < 0)
2038 perror_msg_and_die("%s", delFileName);
Eric Andersen0dfac6b1999-11-11 05:46:32 +00002039 }
Eric Andersen0dfac6b1999-11-11 05:46:32 +00002040
Eric Andersenb6106152000-06-19 17:25:40 +00002041 return(exit_code);
Eric Andersencc8ed391999-10-05 16:24:54 +00002042}
2043
Eric Andersencc8ed391999-10-05 16:24:54 +00002044/* trees.c -- output deflated data using Huffman coding
2045 * Copyright (C) 1992-1993 Jean-loup Gailly
2046 * This is free software; you can redistribute it and/or modify it under the
2047 * terms of the GNU General Public License, see the file COPYING.
2048 */
2049
2050/*
2051 * PURPOSE
2052 *
2053 * Encode various sets of source values using variable-length
2054 * binary code trees.
2055 *
2056 * DISCUSSION
2057 *
2058 * The PKZIP "deflation" process uses several Huffman trees. The more
2059 * common source values are represented by shorter bit sequences.
2060 *
2061 * Each code tree is stored in the ZIP file in a compressed form
2062 * which is itself a Huffman encoding of the lengths of
2063 * all the code strings (in ascending order by source values).
2064 * The actual code strings are reconstructed from the lengths in
2065 * the UNZIP process, as described in the "application note"
2066 * (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
2067 *
2068 * REFERENCES
2069 *
2070 * Lynch, Thomas J.
2071 * Data Compression: Techniques and Applications, pp. 53-55.
2072 * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
2073 *
2074 * Storer, James A.
2075 * Data Compression: Methods and Theory, pp. 49-50.
2076 * Computer Science Press, 1988. ISBN 0-7167-8156-5.
2077 *
2078 * Sedgewick, R.
2079 * Algorithms, p290.
2080 * Addison-Wesley, 1983. ISBN 0-201-06672-6.
2081 *
2082 * INTERFACE
2083 *
2084 * void ct_init (ush *attr, int *methodp)
2085 * Allocate the match buffer, initialize the various tables and save
2086 * the location of the internal file attribute (ascii/binary) and
2087 * method (DEFLATE/STORE)
2088 *
2089 * void ct_tally (int dist, int lc);
2090 * Save the match info and tally the frequency counts.
2091 *
2092 * long flush_block (char *buf, ulg stored_len, int eof)
2093 * Determine the best encoding for the current block: dynamic trees,
2094 * static trees or store, and output the encoded block to the zip
2095 * file. Returns the total compressed length for the file so far.
2096 *
2097 */
2098
2099#include <ctype.h>
2100
Eric Andersencc8ed391999-10-05 16:24:54 +00002101/* ===========================================================================
2102 * Constants
2103 */
2104
2105#define MAX_BITS 15
2106/* All codes must not exceed MAX_BITS bits */
2107
2108#define MAX_BL_BITS 7
2109/* Bit length codes must not exceed MAX_BL_BITS bits */
2110
2111#define LENGTH_CODES 29
2112/* number of length codes, not counting the special END_BLOCK code */
2113
2114#define LITERALS 256
2115/* number of literal bytes 0..255 */
2116
2117#define END_BLOCK 256
2118/* end of block literal code */
2119
2120#define L_CODES (LITERALS+1+LENGTH_CODES)
2121/* number of Literal or Length codes, including the END_BLOCK code */
2122
2123#define D_CODES 30
2124/* number of distance codes */
2125
2126#define BL_CODES 19
2127/* number of codes used to transfer the bit lengths */
2128
2129
Erik Andersene49d5ec2000-02-08 19:58:47 +00002130local int near extra_lbits[LENGTH_CODES] /* extra bits for each length code */
2131 = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
2132 4, 4, 5, 5, 5, 5, 0 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002133
Erik Andersene49d5ec2000-02-08 19:58:47 +00002134local int near extra_dbits[D_CODES] /* extra bits for each distance code */
2135 = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,
2136 10, 10, 11, 11, 12, 12, 13, 13 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002137
Erik Andersene49d5ec2000-02-08 19:58:47 +00002138local int near extra_blbits[BL_CODES] /* extra bits for each bit length code */
2139= { 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 +00002140
2141#define STORED_BLOCK 0
2142#define STATIC_TREES 1
2143#define DYN_TREES 2
2144/* The three kinds of block type */
2145
2146#ifndef LIT_BUFSIZE
2147# ifdef SMALL_MEM
2148# define LIT_BUFSIZE 0x2000
2149# else
2150# ifdef MEDIUM_MEM
2151# define LIT_BUFSIZE 0x4000
2152# else
2153# define LIT_BUFSIZE 0x8000
2154# endif
2155# endif
2156#endif
2157#ifndef DIST_BUFSIZE
2158# define DIST_BUFSIZE LIT_BUFSIZE
2159#endif
2160/* Sizes of match buffers for literals/lengths and distances. There are
2161 * 4 reasons for limiting LIT_BUFSIZE to 64K:
2162 * - frequencies can be kept in 16 bit counters
2163 * - if compression is not successful for the first block, all input data is
2164 * still in the window so we can still emit a stored block even when input
2165 * comes from standard input. (This can also be done for all blocks if
2166 * LIT_BUFSIZE is not greater than 32K.)
2167 * - if compression is not successful for a file smaller than 64K, we can
2168 * even emit a stored file instead of a stored block (saving 5 bytes).
2169 * - creating new Huffman trees less frequently may not provide fast
2170 * adaptation to changes in the input data statistics. (Take for
2171 * example a binary file with poorly compressible code followed by
2172 * a highly compressible string table.) Smaller buffer sizes give
2173 * fast adaptation but have of course the overhead of transmitting trees
2174 * more frequently.
2175 * - I can't count above 4
2176 * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
2177 * memory at the expense of compression). Some optimizations would be possible
2178 * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
2179 */
2180#if LIT_BUFSIZE > INBUFSIZ
Erik Andersene49d5ec2000-02-08 19:58:47 +00002181error cannot overlay l_buf and inbuf
Eric Andersencc8ed391999-10-05 16:24:54 +00002182#endif
Eric Andersencc8ed391999-10-05 16:24:54 +00002183#define REP_3_6 16
2184/* repeat previous bit length 3-6 times (2 bits of repeat count) */
Eric Andersencc8ed391999-10-05 16:24:54 +00002185#define REPZ_3_10 17
2186/* repeat a zero length 3-10 times (3 bits of repeat count) */
Eric Andersencc8ed391999-10-05 16:24:54 +00002187#define REPZ_11_138 18
Erik Andersene49d5ec2000-02-08 19:58:47 +00002188/* repeat a zero length 11-138 times (7 bits of repeat count) *//* ===========================================================================
Eric Andersencc8ed391999-10-05 16:24:54 +00002189 * Local data
Erik Andersene49d5ec2000-02-08 19:58:47 +00002190 *//* Data structure describing a single value and its code string. */ typedef struct ct_data {
2191 union {
2192 ush freq; /* frequency count */
2193 ush code; /* bit string */
2194 } fc;
2195 union {
2196 ush dad; /* father node in Huffman tree */
2197 ush len; /* length of bit string */
2198 } dl;
Eric Andersencc8ed391999-10-05 16:24:54 +00002199} ct_data;
2200
2201#define Freq fc.freq
2202#define Code fc.code
2203#define Dad dl.dad
2204#define Len dl.len
2205
2206#define HEAP_SIZE (2*L_CODES+1)
2207/* maximum heap size */
2208
Erik Andersene49d5ec2000-02-08 19:58:47 +00002209local ct_data near dyn_ltree[HEAP_SIZE]; /* literal and length tree */
2210local ct_data near dyn_dtree[2 * D_CODES + 1]; /* distance tree */
Eric Andersencc8ed391999-10-05 16:24:54 +00002211
Erik Andersene49d5ec2000-02-08 19:58:47 +00002212local ct_data near static_ltree[L_CODES + 2];
2213
Eric Andersencc8ed391999-10-05 16:24:54 +00002214/* The static literal tree. Since the bit lengths are imposed, there is no
2215 * need for the L_CODES extra codes used during heap construction. However
2216 * The codes 286 and 287 are needed to build a canonical tree (see ct_init
2217 * below).
2218 */
2219
2220local ct_data near static_dtree[D_CODES];
Erik Andersene49d5ec2000-02-08 19:58:47 +00002221
Eric Andersencc8ed391999-10-05 16:24:54 +00002222/* The static distance tree. (Actually a trivial tree since all codes use
2223 * 5 bits.)
2224 */
2225
Erik Andersene49d5ec2000-02-08 19:58:47 +00002226local ct_data near bl_tree[2 * BL_CODES + 1];
2227
Eric Andersencc8ed391999-10-05 16:24:54 +00002228/* Huffman tree for the bit lengths */
2229
2230typedef struct tree_desc {
Erik Andersene49d5ec2000-02-08 19:58:47 +00002231 ct_data near *dyn_tree; /* the dynamic tree */
2232 ct_data near *static_tree; /* corresponding static tree or NULL */
2233 int near *extra_bits; /* extra bits for each code or NULL */
2234 int extra_base; /* base index for extra_bits */
2235 int elems; /* max number of elements in the tree */
2236 int max_length; /* max bit length for the codes */
2237 int max_code; /* largest code with non zero frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002238} tree_desc;
2239
2240local tree_desc near l_desc =
Erik Andersene49d5ec2000-02-08 19:58:47 +00002241 { dyn_ltree, static_ltree, extra_lbits, LITERALS + 1, L_CODES,
2242 MAX_BITS, 0 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002243
2244local tree_desc near d_desc =
Erik Andersene49d5ec2000-02-08 19:58:47 +00002245 { dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002246
2247local tree_desc near bl_desc =
Erik Andersene49d5ec2000-02-08 19:58:47 +00002248 { bl_tree, (ct_data near *) 0, extra_blbits, 0, BL_CODES, MAX_BL_BITS,
2249 0 };
Eric Andersencc8ed391999-10-05 16:24:54 +00002250
2251
Erik Andersene49d5ec2000-02-08 19:58:47 +00002252local ush near bl_count[MAX_BITS + 1];
2253
Eric Andersencc8ed391999-10-05 16:24:54 +00002254/* number of codes at each bit length for an optimal tree */
2255
2256local uch near bl_order[BL_CODES]
Erik Andersene49d5ec2000-02-08 19:58:47 +00002257= { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
2258
Eric Andersencc8ed391999-10-05 16:24:54 +00002259/* The lengths of the bit length codes are sent in order of decreasing
2260 * probability, to avoid transmitting the lengths for unused bit length codes.
2261 */
2262
Erik Andersene49d5ec2000-02-08 19:58:47 +00002263local int near heap[2 * L_CODES + 1]; /* heap used to build the Huffman trees */
2264local int heap_len; /* number of elements in the heap */
2265local int heap_max; /* element of largest frequency */
2266
Eric Andersencc8ed391999-10-05 16:24:54 +00002267/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
2268 * The same heap array is used to build all trees.
2269 */
2270
Erik Andersene49d5ec2000-02-08 19:58:47 +00002271local uch near depth[2 * L_CODES + 1];
2272
Eric Andersencc8ed391999-10-05 16:24:54 +00002273/* Depth of each subtree used as tie breaker for trees of equal frequency */
2274
Erik Andersene49d5ec2000-02-08 19:58:47 +00002275local uch length_code[MAX_MATCH - MIN_MATCH + 1];
2276
Eric Andersencc8ed391999-10-05 16:24:54 +00002277/* length code for each normalized match length (0 == MIN_MATCH) */
2278
2279local uch dist_code[512];
Erik Andersene49d5ec2000-02-08 19:58:47 +00002280
Eric Andersencc8ed391999-10-05 16:24:54 +00002281/* distance codes. The first 256 values correspond to the distances
2282 * 3 .. 258, the last 256 values correspond to the top 8 bits of
2283 * the 15 bit distances.
2284 */
2285
2286local int near base_length[LENGTH_CODES];
Erik Andersene49d5ec2000-02-08 19:58:47 +00002287
Eric Andersencc8ed391999-10-05 16:24:54 +00002288/* First normalized length for each code (0 = MIN_MATCH) */
2289
2290local int near base_dist[D_CODES];
Erik Andersene49d5ec2000-02-08 19:58:47 +00002291
Eric Andersencc8ed391999-10-05 16:24:54 +00002292/* First normalized distance for each code (0 = distance of 1) */
2293
2294#define l_buf inbuf
2295/* DECLARE(uch, l_buf, LIT_BUFSIZE); buffer for literals or lengths */
2296
2297/* DECLARE(ush, d_buf, DIST_BUFSIZE); buffer for distances */
2298
Erik Andersene49d5ec2000-02-08 19:58:47 +00002299local uch near flag_buf[(LIT_BUFSIZE / 8)];
2300
Eric Andersencc8ed391999-10-05 16:24:54 +00002301/* flag_buf is a bit array distinguishing literals from lengths in
2302 * l_buf, thus indicating the presence or absence of a distance.
2303 */
2304
Erik Andersene49d5ec2000-02-08 19:58:47 +00002305local unsigned last_lit; /* running index in l_buf */
2306local unsigned last_dist; /* running index in d_buf */
2307local unsigned last_flags; /* running index in flag_buf */
2308local uch flags; /* current flags not yet saved in flag_buf */
2309local uch flag_bit; /* current bit used in flags */
2310
Eric Andersencc8ed391999-10-05 16:24:54 +00002311/* bits are filled in flags starting at bit 0 (least significant).
2312 * Note: these flags are overkill in the current code since we don't
2313 * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
2314 */
2315
Erik Andersene49d5ec2000-02-08 19:58:47 +00002316local ulg opt_len; /* bit length of current block with optimal trees */
2317local ulg static_len; /* bit length of current block with static trees */
Eric Andersencc8ed391999-10-05 16:24:54 +00002318
Erik Andersene49d5ec2000-02-08 19:58:47 +00002319local ulg compressed_len; /* total bit length of compressed file */
Eric Andersencc8ed391999-10-05 16:24:54 +00002320
Erik Andersene49d5ec2000-02-08 19:58:47 +00002321local ulg input_len; /* total byte length of input file */
2322
Eric Andersencc8ed391999-10-05 16:24:54 +00002323/* input_len is for debugging only since we can get it by other means. */
2324
Erik Andersene49d5ec2000-02-08 19:58:47 +00002325ush *file_type; /* pointer to UNKNOWN, BINARY or ASCII */
2326int *file_method; /* pointer to DEFLATE or STORE */
Eric Andersencc8ed391999-10-05 16:24:54 +00002327
2328#ifdef DEBUG
Erik Andersene49d5ec2000-02-08 19:58:47 +00002329extern ulg bits_sent; /* bit length of the compressed data */
2330extern long isize; /* byte length of input file */
Eric Andersencc8ed391999-10-05 16:24:54 +00002331#endif
2332
Erik Andersene49d5ec2000-02-08 19:58:47 +00002333extern long block_start; /* window offset of current block */
2334extern unsigned near strstart; /* window offset of current string */
Eric Andersencc8ed391999-10-05 16:24:54 +00002335
2336/* ===========================================================================
2337 * Local (static) routines in this file.
2338 */
2339
Erik Andersen61677fe2000-04-13 01:18:56 +00002340local void init_block (void);
2341local void pqdownheap (ct_data near * tree, int k);
2342local void gen_bitlen (tree_desc near * desc);
2343local void gen_codes (ct_data near * tree, int max_code);
2344local void build_tree (tree_desc near * desc);
2345local void scan_tree (ct_data near * tree, int max_code);
2346local void send_tree (ct_data near * tree, int max_code);
2347local int build_bl_tree (void);
2348local void send_all_trees (int lcodes, int dcodes, int blcodes);
2349local void compress_block (ct_data near * ltree, ct_data near * dtree);
2350local void set_file_type (void);
Eric Andersencc8ed391999-10-05 16:24:54 +00002351
2352
2353#ifndef DEBUG
2354# define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
2355 /* Send a code of the given tree. c and tree must not have side effects */
2356
Erik Andersene49d5ec2000-02-08 19:58:47 +00002357#else /* DEBUG */
Eric Andersencc8ed391999-10-05 16:24:54 +00002358# define send_code(c, tree) \
2359 { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \
2360 send_bits(tree[c].Code, tree[c].Len); }
2361#endif
2362
2363#define d_code(dist) \
2364 ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
2365/* Mapping from a distance to a distance code. dist is the distance - 1 and
2366 * must not have side effects. dist_code[256] and dist_code[257] are never
2367 * used.
2368 */
2369
Eric Andersencc8ed391999-10-05 16:24:54 +00002370/* the arguments must not have side effects */
2371
2372/* ===========================================================================
2373 * Allocate the match buffer, initialize the various tables and save the
2374 * location of the internal file attribute (ascii/binary) and method
2375 * (DEFLATE/STORE).
2376 */
2377void ct_init(attr, methodp)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002378ush *attr; /* pointer to internal file attribute */
2379int *methodp; /* pointer to compression method */
Eric Andersencc8ed391999-10-05 16:24:54 +00002380{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002381 int n; /* iterates over tree elements */
2382 int bits; /* bit counter */
2383 int length; /* length value */
2384 int code; /* code value */
2385 int dist; /* distance index */
Eric Andersencc8ed391999-10-05 16:24:54 +00002386
Erik Andersene49d5ec2000-02-08 19:58:47 +00002387 file_type = attr;
2388 file_method = methodp;
2389 compressed_len = input_len = 0L;
Eric Andersencc8ed391999-10-05 16:24:54 +00002390
Erik Andersene49d5ec2000-02-08 19:58:47 +00002391 if (static_dtree[0].Len != 0)
2392 return; /* ct_init already called */
Eric Andersencc8ed391999-10-05 16:24:54 +00002393
Erik Andersene49d5ec2000-02-08 19:58:47 +00002394 /* Initialize the mapping length (0..255) -> length code (0..28) */
2395 length = 0;
2396 for (code = 0; code < LENGTH_CODES - 1; code++) {
2397 base_length[code] = length;
2398 for (n = 0; n < (1 << extra_lbits[code]); n++) {
2399 length_code[length++] = (uch) code;
2400 }
2401 }
2402 Assert(length == 256, "ct_init: length != 256");
2403 /* Note that the length 255 (match length 258) can be represented
2404 * in two different ways: code 284 + 5 bits or code 285, so we
2405 * overwrite length_code[255] to use the best encoding:
2406 */
2407 length_code[length - 1] = (uch) code;
Eric Andersencc8ed391999-10-05 16:24:54 +00002408
Erik Andersene49d5ec2000-02-08 19:58:47 +00002409 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
2410 dist = 0;
2411 for (code = 0; code < 16; code++) {
2412 base_dist[code] = dist;
2413 for (n = 0; n < (1 << extra_dbits[code]); n++) {
2414 dist_code[dist++] = (uch) code;
2415 }
2416 }
2417 Assert(dist == 256, "ct_init: dist != 256");
2418 dist >>= 7; /* from now on, all distances are divided by 128 */
2419 for (; code < D_CODES; code++) {
2420 base_dist[code] = dist << 7;
2421 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
2422 dist_code[256 + dist++] = (uch) code;
2423 }
2424 }
2425 Assert(dist == 256, "ct_init: 256+dist != 512");
Eric Andersencc8ed391999-10-05 16:24:54 +00002426
Erik Andersene49d5ec2000-02-08 19:58:47 +00002427 /* Construct the codes of the static literal tree */
2428 for (bits = 0; bits <= MAX_BITS; bits++)
2429 bl_count[bits] = 0;
2430 n = 0;
2431 while (n <= 143)
2432 static_ltree[n++].Len = 8, bl_count[8]++;
2433 while (n <= 255)
2434 static_ltree[n++].Len = 9, bl_count[9]++;
2435 while (n <= 279)
2436 static_ltree[n++].Len = 7, bl_count[7]++;
2437 while (n <= 287)
2438 static_ltree[n++].Len = 8, bl_count[8]++;
2439 /* Codes 286 and 287 do not exist, but we must include them in the
2440 * tree construction to get a canonical Huffman tree (longest code
2441 * all ones)
2442 */
2443 gen_codes((ct_data near *) static_ltree, L_CODES + 1);
Eric Andersencc8ed391999-10-05 16:24:54 +00002444
Erik Andersene49d5ec2000-02-08 19:58:47 +00002445 /* The static distance tree is trivial: */
2446 for (n = 0; n < D_CODES; n++) {
2447 static_dtree[n].Len = 5;
2448 static_dtree[n].Code = bi_reverse(n, 5);
2449 }
2450
2451 /* Initialize the first block of the first file: */
2452 init_block();
Eric Andersencc8ed391999-10-05 16:24:54 +00002453}
2454
2455/* ===========================================================================
2456 * Initialize a new block.
2457 */
2458local void init_block()
2459{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002460 int n; /* iterates over tree elements */
Eric Andersencc8ed391999-10-05 16:24:54 +00002461
Erik Andersene49d5ec2000-02-08 19:58:47 +00002462 /* Initialize the trees. */
2463 for (n = 0; n < L_CODES; n++)
2464 dyn_ltree[n].Freq = 0;
2465 for (n = 0; n < D_CODES; n++)
2466 dyn_dtree[n].Freq = 0;
2467 for (n = 0; n < BL_CODES; n++)
2468 bl_tree[n].Freq = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00002469
Erik Andersene49d5ec2000-02-08 19:58:47 +00002470 dyn_ltree[END_BLOCK].Freq = 1;
2471 opt_len = static_len = 0L;
2472 last_lit = last_dist = last_flags = 0;
2473 flags = 0;
2474 flag_bit = 1;
Eric Andersencc8ed391999-10-05 16:24:54 +00002475}
2476
2477#define SMALLEST 1
2478/* Index within the heap array of least frequent node in the Huffman tree */
2479
2480
2481/* ===========================================================================
2482 * Remove the smallest element from the heap and recreate the heap with
2483 * one less element. Updates heap and heap_len.
2484 */
2485#define pqremove(tree, top) \
2486{\
2487 top = heap[SMALLEST]; \
2488 heap[SMALLEST] = heap[heap_len--]; \
2489 pqdownheap(tree, SMALLEST); \
2490}
2491
2492/* ===========================================================================
2493 * Compares to subtrees, using the tree depth as tie breaker when
2494 * the subtrees have equal frequency. This minimizes the worst case length.
2495 */
2496#define smaller(tree, n, m) \
2497 (tree[n].Freq < tree[m].Freq || \
2498 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
2499
2500/* ===========================================================================
2501 * Restore the heap property by moving down the tree starting at node k,
2502 * exchanging a node with the smallest of its two sons if necessary, stopping
2503 * when the heap property is re-established (each father smaller than its
2504 * two sons).
2505 */
2506local void pqdownheap(tree, k)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002507ct_data near *tree; /* the tree to restore */
2508int k; /* node to move down */
Eric Andersencc8ed391999-10-05 16:24:54 +00002509{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002510 int v = heap[k];
2511 int j = k << 1; /* left son of k */
Eric Andersencc8ed391999-10-05 16:24:54 +00002512
Erik Andersene49d5ec2000-02-08 19:58:47 +00002513 while (j <= heap_len) {
2514 /* Set j to the smallest of the two sons: */
2515 if (j < heap_len && smaller(tree, heap[j + 1], heap[j]))
2516 j++;
Eric Andersencc8ed391999-10-05 16:24:54 +00002517
Erik Andersene49d5ec2000-02-08 19:58:47 +00002518 /* Exit if v is smaller than both sons */
2519 if (smaller(tree, v, heap[j]))
2520 break;
Eric Andersencc8ed391999-10-05 16:24:54 +00002521
Erik Andersene49d5ec2000-02-08 19:58:47 +00002522 /* Exchange v with the smallest son */
2523 heap[k] = heap[j];
2524 k = j;
2525
2526 /* And continue down the tree, setting j to the left son of k */
2527 j <<= 1;
2528 }
2529 heap[k] = v;
Eric Andersencc8ed391999-10-05 16:24:54 +00002530}
2531
2532/* ===========================================================================
2533 * Compute the optimal bit lengths for a tree and update the total bit length
2534 * for the current block.
2535 * IN assertion: the fields freq and dad are set, heap[heap_max] and
2536 * above are the tree nodes sorted by increasing frequency.
2537 * OUT assertions: the field len is set to the optimal bit length, the
2538 * array bl_count contains the frequencies for each bit length.
2539 * The length opt_len is updated; static_len is also updated if stree is
2540 * not null.
2541 */
2542local void gen_bitlen(desc)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002543tree_desc near *desc; /* the tree descriptor */
Eric Andersencc8ed391999-10-05 16:24:54 +00002544{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002545 ct_data near *tree = desc->dyn_tree;
2546 int near *extra = desc->extra_bits;
2547 int base = desc->extra_base;
2548 int max_code = desc->max_code;
2549 int max_length = desc->max_length;
2550 ct_data near *stree = desc->static_tree;
2551 int h; /* heap index */
2552 int n, m; /* iterate over the tree elements */
2553 int bits; /* bit length */
2554 int xbits; /* extra bits */
2555 ush f; /* frequency */
2556 int overflow = 0; /* number of elements with bit length too large */
Eric Andersencc8ed391999-10-05 16:24:54 +00002557
Erik Andersene49d5ec2000-02-08 19:58:47 +00002558 for (bits = 0; bits <= MAX_BITS; bits++)
2559 bl_count[bits] = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00002560
Erik Andersene49d5ec2000-02-08 19:58:47 +00002561 /* In a first pass, compute the optimal bit lengths (which may
2562 * overflow in the case of the bit length tree).
2563 */
2564 tree[heap[heap_max]].Len = 0; /* root of the heap */
Eric Andersencc8ed391999-10-05 16:24:54 +00002565
Erik Andersene49d5ec2000-02-08 19:58:47 +00002566 for (h = heap_max + 1; h < HEAP_SIZE; h++) {
2567 n = heap[h];
2568 bits = tree[tree[n].Dad].Len + 1;
2569 if (bits > max_length)
2570 bits = max_length, overflow++;
2571 tree[n].Len = (ush) bits;
2572 /* We overwrite tree[n].Dad which is no longer needed */
Eric Andersencc8ed391999-10-05 16:24:54 +00002573
Erik Andersene49d5ec2000-02-08 19:58:47 +00002574 if (n > max_code)
2575 continue; /* not a leaf node */
Eric Andersencc8ed391999-10-05 16:24:54 +00002576
Erik Andersene49d5ec2000-02-08 19:58:47 +00002577 bl_count[bits]++;
2578 xbits = 0;
2579 if (n >= base)
2580 xbits = extra[n - base];
2581 f = tree[n].Freq;
2582 opt_len += (ulg) f *(bits + xbits);
Eric Andersencc8ed391999-10-05 16:24:54 +00002583
Erik Andersene49d5ec2000-02-08 19:58:47 +00002584 if (stree)
2585 static_len += (ulg) f *(stree[n].Len + xbits);
2586 }
2587 if (overflow == 0)
2588 return;
Eric Andersencc8ed391999-10-05 16:24:54 +00002589
Erik Andersene49d5ec2000-02-08 19:58:47 +00002590 Trace((stderr, "\nbit length overflow\n"));
2591 /* This happens for example on obj2 and pic of the Calgary corpus */
Eric Andersencc8ed391999-10-05 16:24:54 +00002592
Erik Andersene49d5ec2000-02-08 19:58:47 +00002593 /* Find the first bit length which could increase: */
2594 do {
2595 bits = max_length - 1;
2596 while (bl_count[bits] == 0)
2597 bits--;
2598 bl_count[bits]--; /* move one leaf down the tree */
2599 bl_count[bits + 1] += 2; /* move one overflow item as its brother */
2600 bl_count[max_length]--;
2601 /* The brother of the overflow item also moves one step up,
2602 * but this does not affect bl_count[max_length]
2603 */
2604 overflow -= 2;
2605 } while (overflow > 0);
2606
2607 /* Now recompute all bit lengths, scanning in increasing frequency.
2608 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
2609 * lengths instead of fixing only the wrong ones. This idea is taken
2610 * from 'ar' written by Haruhiko Okumura.)
2611 */
2612 for (bits = max_length; bits != 0; bits--) {
2613 n = bl_count[bits];
2614 while (n != 0) {
2615 m = heap[--h];
2616 if (m > max_code)
2617 continue;
2618 if (tree[m].Len != (unsigned) bits) {
2619 Trace(
2620 (stderr, "code %d bits %d->%d\n", m, tree[m].Len,
2621 bits));
2622 opt_len +=
2623 ((long) bits -
2624 (long) tree[m].Len) * (long) tree[m].Freq;
2625 tree[m].Len = (ush) bits;
2626 }
2627 n--;
2628 }
2629 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002630}
2631
2632/* ===========================================================================
2633 * Generate the codes for a given tree and bit counts (which need not be
2634 * optimal).
2635 * IN assertion: the array bl_count contains the bit length statistics for
2636 * the given tree and the field len is set for all tree elements.
2637 * OUT assertion: the field code is set for all tree elements of non
2638 * zero code length.
2639 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00002640local void gen_codes(tree, max_code)
2641ct_data near *tree; /* the tree to decorate */
2642int max_code; /* largest code with non zero frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002643{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002644 ush next_code[MAX_BITS + 1]; /* next code value for each bit length */
2645 ush code = 0; /* running code value */
2646 int bits; /* bit index */
2647 int n; /* code index */
Eric Andersencc8ed391999-10-05 16:24:54 +00002648
Erik Andersene49d5ec2000-02-08 19:58:47 +00002649 /* The distribution counts are first used to generate the code values
2650 * without bit reversal.
2651 */
2652 for (bits = 1; bits <= MAX_BITS; bits++) {
2653 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
2654 }
2655 /* Check that the bit counts in bl_count are consistent. The last code
2656 * must be all ones.
2657 */
2658 Assert(code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
2659 "inconsistent bit counts");
2660 Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
Eric Andersencc8ed391999-10-05 16:24:54 +00002661
Erik Andersene49d5ec2000-02-08 19:58:47 +00002662 for (n = 0; n <= max_code; n++) {
2663 int len = tree[n].Len;
Eric Andersencc8ed391999-10-05 16:24:54 +00002664
Erik Andersene49d5ec2000-02-08 19:58:47 +00002665 if (len == 0)
2666 continue;
2667 /* Now reverse the bits */
2668 tree[n].Code = bi_reverse(next_code[len]++, len);
2669
2670 Tracec(tree != static_ltree,
2671 (stderr, "\nn %3d %c l %2d c %4x (%x) ", n,
2672 (isgraph(n) ? n : ' '), len, tree[n].Code,
2673 next_code[len] - 1));
2674 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002675}
2676
2677/* ===========================================================================
2678 * Construct one Huffman tree and assigns the code bit strings and lengths.
2679 * Update the total bit length for the current block.
2680 * IN assertion: the field freq is set for all tree elements.
2681 * OUT assertions: the fields len and code are set to the optimal bit length
2682 * and corresponding code. The length opt_len is updated; static_len is
2683 * also updated if stree is not null. The field max_code is set.
2684 */
2685local void build_tree(desc)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002686tree_desc near *desc; /* the tree descriptor */
Eric Andersencc8ed391999-10-05 16:24:54 +00002687{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002688 ct_data near *tree = desc->dyn_tree;
2689 ct_data near *stree = desc->static_tree;
2690 int elems = desc->elems;
2691 int n, m; /* iterate over heap elements */
2692 int max_code = -1; /* largest code with non zero frequency */
2693 int node = elems; /* next internal node of the tree */
Eric Andersencc8ed391999-10-05 16:24:54 +00002694
Erik Andersene49d5ec2000-02-08 19:58:47 +00002695 /* Construct the initial heap, with least frequent element in
2696 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
2697 * heap[0] is not used.
2698 */
2699 heap_len = 0, heap_max = HEAP_SIZE;
Eric Andersencc8ed391999-10-05 16:24:54 +00002700
Erik Andersene49d5ec2000-02-08 19:58:47 +00002701 for (n = 0; n < elems; n++) {
2702 if (tree[n].Freq != 0) {
2703 heap[++heap_len] = max_code = n;
2704 depth[n] = 0;
2705 } else {
2706 tree[n].Len = 0;
2707 }
2708 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002709
Erik Andersene49d5ec2000-02-08 19:58:47 +00002710 /* The pkzip format requires that at least one distance code exists,
2711 * and that at least one bit should be sent even if there is only one
2712 * possible code. So to avoid special checks later on we force at least
2713 * two codes of non zero frequency.
2714 */
2715 while (heap_len < 2) {
2716 int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
Eric Andersencc8ed391999-10-05 16:24:54 +00002717
Erik Andersene49d5ec2000-02-08 19:58:47 +00002718 tree[new].Freq = 1;
2719 depth[new] = 0;
2720 opt_len--;
2721 if (stree)
2722 static_len -= stree[new].Len;
2723 /* new is 0 or 1 so it does not have extra bits */
2724 }
2725 desc->max_code = max_code;
Eric Andersencc8ed391999-10-05 16:24:54 +00002726
Erik Andersene49d5ec2000-02-08 19:58:47 +00002727 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
2728 * establish sub-heaps of increasing lengths:
2729 */
2730 for (n = heap_len / 2; n >= 1; n--)
2731 pqdownheap(tree, n);
Eric Andersencc8ed391999-10-05 16:24:54 +00002732
Erik Andersene49d5ec2000-02-08 19:58:47 +00002733 /* Construct the Huffman tree by repeatedly combining the least two
2734 * frequent nodes.
2735 */
2736 do {
2737 pqremove(tree, n); /* n = node of least frequency */
2738 m = heap[SMALLEST]; /* m = node of next least frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002739
Erik Andersene49d5ec2000-02-08 19:58:47 +00002740 heap[--heap_max] = n; /* keep the nodes sorted by frequency */
2741 heap[--heap_max] = m;
2742
2743 /* Create a new node father of n and m */
2744 tree[node].Freq = tree[n].Freq + tree[m].Freq;
2745 depth[node] = (uch) (MAX(depth[n], depth[m]) + 1);
2746 tree[n].Dad = tree[m].Dad = (ush) node;
Eric Andersencc8ed391999-10-05 16:24:54 +00002747#ifdef DUMP_BL_TREE
Erik Andersene49d5ec2000-02-08 19:58:47 +00002748 if (tree == bl_tree) {
2749 fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)",
2750 node, tree[node].Freq, n, tree[n].Freq, m,
2751 tree[m].Freq);
2752 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002753#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00002754 /* and insert the new node in the heap */
2755 heap[SMALLEST] = node++;
2756 pqdownheap(tree, SMALLEST);
Eric Andersencc8ed391999-10-05 16:24:54 +00002757
Erik Andersene49d5ec2000-02-08 19:58:47 +00002758 } while (heap_len >= 2);
Eric Andersencc8ed391999-10-05 16:24:54 +00002759
Erik Andersene49d5ec2000-02-08 19:58:47 +00002760 heap[--heap_max] = heap[SMALLEST];
Eric Andersencc8ed391999-10-05 16:24:54 +00002761
Erik Andersene49d5ec2000-02-08 19:58:47 +00002762 /* At this point, the fields freq and dad are set. We can now
2763 * generate the bit lengths.
2764 */
2765 gen_bitlen((tree_desc near *) desc);
Eric Andersencc8ed391999-10-05 16:24:54 +00002766
Erik Andersene49d5ec2000-02-08 19:58:47 +00002767 /* The field len is now set, we can generate the bit codes */
2768 gen_codes((ct_data near *) tree, max_code);
Eric Andersencc8ed391999-10-05 16:24:54 +00002769}
2770
2771/* ===========================================================================
2772 * Scan a literal or distance tree to determine the frequencies of the codes
2773 * in the bit length tree. Updates opt_len to take into account the repeat
2774 * counts. (The contribution of the bit length codes will be added later
2775 * during the construction of bl_tree.)
2776 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00002777local void scan_tree(tree, max_code)
2778ct_data near *tree; /* the tree to be scanned */
2779int max_code; /* and its largest code of non zero frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002780{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002781 int n; /* iterates over all tree elements */
2782 int prevlen = -1; /* last emitted length */
2783 int curlen; /* length of current code */
2784 int nextlen = tree[0].Len; /* length of next code */
2785 int count = 0; /* repeat count of the current code */
2786 int max_count = 7; /* max repeat count */
2787 int min_count = 4; /* min repeat count */
Eric Andersencc8ed391999-10-05 16:24:54 +00002788
Erik Andersene49d5ec2000-02-08 19:58:47 +00002789 if (nextlen == 0)
2790 max_count = 138, min_count = 3;
2791 tree[max_code + 1].Len = (ush) 0xffff; /* guard */
Eric Andersencc8ed391999-10-05 16:24:54 +00002792
Erik Andersene49d5ec2000-02-08 19:58:47 +00002793 for (n = 0; n <= max_code; n++) {
2794 curlen = nextlen;
2795 nextlen = tree[n + 1].Len;
2796 if (++count < max_count && curlen == nextlen) {
2797 continue;
2798 } else if (count < min_count) {
2799 bl_tree[curlen].Freq += count;
2800 } else if (curlen != 0) {
2801 if (curlen != prevlen)
2802 bl_tree[curlen].Freq++;
2803 bl_tree[REP_3_6].Freq++;
2804 } else if (count <= 10) {
2805 bl_tree[REPZ_3_10].Freq++;
2806 } else {
2807 bl_tree[REPZ_11_138].Freq++;
2808 }
2809 count = 0;
2810 prevlen = curlen;
2811 if (nextlen == 0) {
2812 max_count = 138, min_count = 3;
2813 } else if (curlen == nextlen) {
2814 max_count = 6, min_count = 3;
2815 } else {
2816 max_count = 7, min_count = 4;
2817 }
2818 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002819}
2820
2821/* ===========================================================================
2822 * Send a literal or distance tree in compressed form, using the codes in
2823 * bl_tree.
2824 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00002825local void send_tree(tree, max_code)
2826ct_data near *tree; /* the tree to be scanned */
2827int max_code; /* and its largest code of non zero frequency */
Eric Andersencc8ed391999-10-05 16:24:54 +00002828{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002829 int n; /* iterates over all tree elements */
2830 int prevlen = -1; /* last emitted length */
2831 int curlen; /* length of current code */
2832 int nextlen = tree[0].Len; /* length of next code */
2833 int count = 0; /* repeat count of the current code */
2834 int max_count = 7; /* max repeat count */
2835 int min_count = 4; /* min repeat count */
Eric Andersencc8ed391999-10-05 16:24:54 +00002836
Erik Andersene49d5ec2000-02-08 19:58:47 +00002837/* tree[max_code+1].Len = -1; *//* guard already set */
2838 if (nextlen == 0)
2839 max_count = 138, min_count = 3;
Eric Andersencc8ed391999-10-05 16:24:54 +00002840
Erik Andersene49d5ec2000-02-08 19:58:47 +00002841 for (n = 0; n <= max_code; n++) {
2842 curlen = nextlen;
2843 nextlen = tree[n + 1].Len;
2844 if (++count < max_count && curlen == nextlen) {
2845 continue;
2846 } else if (count < min_count) {
2847 do {
2848 send_code(curlen, bl_tree);
2849 } while (--count != 0);
Eric Andersencc8ed391999-10-05 16:24:54 +00002850
Erik Andersene49d5ec2000-02-08 19:58:47 +00002851 } else if (curlen != 0) {
2852 if (curlen != prevlen) {
2853 send_code(curlen, bl_tree);
2854 count--;
2855 }
2856 Assert(count >= 3 && count <= 6, " 3_6?");
2857 send_code(REP_3_6, bl_tree);
2858 send_bits(count - 3, 2);
Eric Andersencc8ed391999-10-05 16:24:54 +00002859
Erik Andersene49d5ec2000-02-08 19:58:47 +00002860 } else if (count <= 10) {
2861 send_code(REPZ_3_10, bl_tree);
2862 send_bits(count - 3, 3);
Eric Andersencc8ed391999-10-05 16:24:54 +00002863
Erik Andersene49d5ec2000-02-08 19:58:47 +00002864 } else {
2865 send_code(REPZ_11_138, bl_tree);
2866 send_bits(count - 11, 7);
2867 }
2868 count = 0;
2869 prevlen = curlen;
2870 if (nextlen == 0) {
2871 max_count = 138, min_count = 3;
2872 } else if (curlen == nextlen) {
2873 max_count = 6, min_count = 3;
2874 } else {
2875 max_count = 7, min_count = 4;
2876 }
2877 }
Eric Andersencc8ed391999-10-05 16:24:54 +00002878}
2879
2880/* ===========================================================================
2881 * Construct the Huffman tree for the bit lengths and return the index in
2882 * bl_order of the last bit length code to send.
2883 */
2884local int build_bl_tree()
2885{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002886 int max_blindex; /* index of last bit length code of non zero freq */
Eric Andersencc8ed391999-10-05 16:24:54 +00002887
Erik Andersene49d5ec2000-02-08 19:58:47 +00002888 /* Determine the bit length frequencies for literal and distance trees */
2889 scan_tree((ct_data near *) dyn_ltree, l_desc.max_code);
2890 scan_tree((ct_data near *) dyn_dtree, d_desc.max_code);
Eric Andersencc8ed391999-10-05 16:24:54 +00002891
Erik Andersene49d5ec2000-02-08 19:58:47 +00002892 /* Build the bit length tree: */
2893 build_tree((tree_desc near *) (&bl_desc));
2894 /* opt_len now includes the length of the tree representations, except
2895 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
2896 */
Eric Andersencc8ed391999-10-05 16:24:54 +00002897
Erik Andersene49d5ec2000-02-08 19:58:47 +00002898 /* Determine the number of bit length codes to send. The pkzip format
2899 * requires that at least 4 bit length codes be sent. (appnote.txt says
2900 * 3 but the actual value used is 4.)
2901 */
2902 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
2903 if (bl_tree[bl_order[max_blindex]].Len != 0)
2904 break;
2905 }
2906 /* Update opt_len to include the bit length tree and counts */
2907 opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
2908 Tracev(
2909 (stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len,
2910 static_len));
Eric Andersencc8ed391999-10-05 16:24:54 +00002911
Erik Andersene49d5ec2000-02-08 19:58:47 +00002912 return max_blindex;
Eric Andersencc8ed391999-10-05 16:24:54 +00002913}
2914
2915/* ===========================================================================
2916 * Send the header for a block using dynamic Huffman trees: the counts, the
2917 * lengths of the bit length codes, the literal tree and the distance tree.
2918 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
2919 */
2920local void send_all_trees(lcodes, dcodes, blcodes)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002921int lcodes, dcodes, blcodes; /* number of codes for each tree */
Eric Andersencc8ed391999-10-05 16:24:54 +00002922{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002923 int rank; /* index in bl_order */
Eric Andersencc8ed391999-10-05 16:24:54 +00002924
Erik Andersene49d5ec2000-02-08 19:58:47 +00002925 Assert(lcodes >= 257 && dcodes >= 1
2926 && blcodes >= 4, "not enough codes");
2927 Assert(lcodes <= L_CODES && dcodes <= D_CODES
2928 && blcodes <= BL_CODES, "too many codes");
2929 Tracev((stderr, "\nbl counts: "));
2930 send_bits(lcodes - 257, 5); /* not +255 as stated in appnote.txt */
2931 send_bits(dcodes - 1, 5);
2932 send_bits(blcodes - 4, 4); /* not -3 as stated in appnote.txt */
2933 for (rank = 0; rank < blcodes; rank++) {
2934 Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
2935 send_bits(bl_tree[bl_order[rank]].Len, 3);
2936 }
2937 Tracev((stderr, "\nbl tree: sent %ld", bits_sent));
Eric Andersencc8ed391999-10-05 16:24:54 +00002938
Erik Andersene49d5ec2000-02-08 19:58:47 +00002939 send_tree((ct_data near *) dyn_ltree, lcodes - 1); /* send the literal tree */
2940 Tracev((stderr, "\nlit tree: sent %ld", bits_sent));
Eric Andersencc8ed391999-10-05 16:24:54 +00002941
Erik Andersene49d5ec2000-02-08 19:58:47 +00002942 send_tree((ct_data near *) dyn_dtree, dcodes - 1); /* send the distance tree */
2943 Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
Eric Andersencc8ed391999-10-05 16:24:54 +00002944}
2945
2946/* ===========================================================================
2947 * Determine the best encoding for the current block: dynamic trees, static
2948 * trees or store, and output the encoded block to the zip file. This function
2949 * returns the total compressed length for the file so far.
2950 */
2951ulg flush_block(buf, stored_len, eof)
Erik Andersene49d5ec2000-02-08 19:58:47 +00002952char *buf; /* input block, or NULL if too old */
2953ulg stored_len; /* length of input block */
2954int eof; /* true if this is the last block for a file */
Eric Andersencc8ed391999-10-05 16:24:54 +00002955{
Erik Andersene49d5ec2000-02-08 19:58:47 +00002956 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
2957 int max_blindex; /* index of last bit length code of non zero freq */
Eric Andersencc8ed391999-10-05 16:24:54 +00002958
Erik Andersene49d5ec2000-02-08 19:58:47 +00002959 flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
Eric Andersencc8ed391999-10-05 16:24:54 +00002960
Erik Andersene49d5ec2000-02-08 19:58:47 +00002961 /* Check if the file is ascii or binary */
2962 if (*file_type == (ush) UNKNOWN)
2963 set_file_type();
Eric Andersencc8ed391999-10-05 16:24:54 +00002964
Erik Andersene49d5ec2000-02-08 19:58:47 +00002965 /* Construct the literal and distance trees */
2966 build_tree((tree_desc near *) (&l_desc));
2967 Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
Eric Andersencc8ed391999-10-05 16:24:54 +00002968
Erik Andersene49d5ec2000-02-08 19:58:47 +00002969 build_tree((tree_desc near *) (&d_desc));
2970 Tracev(
2971 (stderr, "\ndist data: dyn %ld, stat %ld", opt_len,
2972 static_len));
2973 /* At this point, opt_len and static_len are the total bit lengths of
2974 * the compressed block data, excluding the tree representations.
2975 */
Eric Andersencc8ed391999-10-05 16:24:54 +00002976
Erik Andersene49d5ec2000-02-08 19:58:47 +00002977 /* Build the bit length tree for the above two trees, and get the index
2978 * in bl_order of the last bit length code to send.
2979 */
2980 max_blindex = build_bl_tree();
Eric Andersencc8ed391999-10-05 16:24:54 +00002981
Erik Andersene49d5ec2000-02-08 19:58:47 +00002982 /* Determine the best encoding. Compute first the block length in bytes */
2983 opt_lenb = (opt_len + 3 + 7) >> 3;
2984 static_lenb = (static_len + 3 + 7) >> 3;
2985 input_len += stored_len; /* for debugging only */
Eric Andersencc8ed391999-10-05 16:24:54 +00002986
Erik Andersene49d5ec2000-02-08 19:58:47 +00002987 Trace(
2988 (stderr,
2989 "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
2990 opt_lenb, opt_len, static_lenb, static_len, stored_len,
2991 last_lit, last_dist));
Eric Andersencc8ed391999-10-05 16:24:54 +00002992
Erik Andersene49d5ec2000-02-08 19:58:47 +00002993 if (static_lenb <= opt_lenb)
2994 opt_lenb = static_lenb;
Eric Andersencc8ed391999-10-05 16:24:54 +00002995
Erik Andersene49d5ec2000-02-08 19:58:47 +00002996 /* If compression failed and this is the first and last block,
2997 * and if the zip file can be seeked (to rewrite the local header),
2998 * the whole file is transformed into a stored file:
2999 */
Eric Andersencc8ed391999-10-05 16:24:54 +00003000#ifdef FORCE_METHOD
3001#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00003002 if (stored_len <= opt_lenb && eof && compressed_len == 0L
3003 && seekable()) {
Eric Andersencc8ed391999-10-05 16:24:54 +00003004#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00003005 /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
3006 if (buf == (char *) 0)
Matt Kraaidd19c692001-01-31 19:00:21 +00003007 error_msg("block vanished");
Eric Andersencc8ed391999-10-05 16:24:54 +00003008
Erik Andersene49d5ec2000-02-08 19:58:47 +00003009 copy_block(buf, (unsigned) stored_len, 0); /* without header */
3010 compressed_len = stored_len << 3;
3011 *file_method = STORED;
Eric Andersencc8ed391999-10-05 16:24:54 +00003012
3013#ifdef FORCE_METHOD
3014#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00003015 } else if (stored_len + 4 <= opt_lenb && buf != (char *) 0) {
3016 /* 4: two words for the lengths */
Eric Andersencc8ed391999-10-05 16:24:54 +00003017#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00003018 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
3019 * Otherwise we can't have processed more than WSIZE input bytes since
3020 * the last block flush, because compression would have been
3021 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
3022 * transform a block into a stored block.
3023 */
3024 send_bits((STORED_BLOCK << 1) + eof, 3); /* send block type */
3025 compressed_len = (compressed_len + 3 + 7) & ~7L;
3026 compressed_len += (stored_len + 4) << 3;
Eric Andersencc8ed391999-10-05 16:24:54 +00003027
Erik Andersene49d5ec2000-02-08 19:58:47 +00003028 copy_block(buf, (unsigned) stored_len, 1); /* with header */
Eric Andersencc8ed391999-10-05 16:24:54 +00003029
3030#ifdef FORCE_METHOD
3031#else
Erik Andersene49d5ec2000-02-08 19:58:47 +00003032 } else if (static_lenb == opt_lenb) {
Eric Andersencc8ed391999-10-05 16:24:54 +00003033#endif
Erik Andersene49d5ec2000-02-08 19:58:47 +00003034 send_bits((STATIC_TREES << 1) + eof, 3);
3035 compress_block((ct_data near *) static_ltree,
3036 (ct_data near *) static_dtree);
3037 compressed_len += 3 + static_len;
3038 } else {
3039 send_bits((DYN_TREES << 1) + eof, 3);
3040 send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1,
3041 max_blindex + 1);
3042 compress_block((ct_data near *) dyn_ltree,
3043 (ct_data near *) dyn_dtree);
3044 compressed_len += 3 + opt_len;
3045 }
3046 Assert(compressed_len == bits_sent, "bad compressed size");
3047 init_block();
Eric Andersencc8ed391999-10-05 16:24:54 +00003048
Erik Andersene49d5ec2000-02-08 19:58:47 +00003049 if (eof) {
3050 Assert(input_len == isize, "bad input size");
3051 bi_windup();
3052 compressed_len += 7; /* align on byte boundary */
3053 }
3054 Tracev((stderr, "\ncomprlen %lu(%lu) ", compressed_len >> 3,
3055 compressed_len - 7 * eof));
Eric Andersencc8ed391999-10-05 16:24:54 +00003056
Erik Andersene49d5ec2000-02-08 19:58:47 +00003057 return compressed_len >> 3;
Eric Andersencc8ed391999-10-05 16:24:54 +00003058}
3059
3060/* ===========================================================================
3061 * Save the match info and tally the frequency counts. Return true if
3062 * the current block must be flushed.
3063 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00003064int ct_tally(dist, lc)
3065int dist; /* distance of matched string */
3066int lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
Eric Andersencc8ed391999-10-05 16:24:54 +00003067{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003068 l_buf[last_lit++] = (uch) lc;
3069 if (dist == 0) {
3070 /* lc is the unmatched char */
3071 dyn_ltree[lc].Freq++;
3072 } else {
3073 /* Here, lc is the match length - MIN_MATCH */
3074 dist--; /* dist = match distance - 1 */
3075 Assert((ush) dist < (ush) MAX_DIST &&
3076 (ush) lc <= (ush) (MAX_MATCH - MIN_MATCH) &&
3077 (ush) d_code(dist) < (ush) D_CODES, "ct_tally: bad match");
Eric Andersencc8ed391999-10-05 16:24:54 +00003078
Erik Andersene49d5ec2000-02-08 19:58:47 +00003079 dyn_ltree[length_code[lc] + LITERALS + 1].Freq++;
3080 dyn_dtree[d_code(dist)].Freq++;
Eric Andersencc8ed391999-10-05 16:24:54 +00003081
Erik Andersene49d5ec2000-02-08 19:58:47 +00003082 d_buf[last_dist++] = (ush) dist;
3083 flags |= flag_bit;
3084 }
3085 flag_bit <<= 1;
Eric Andersencc8ed391999-10-05 16:24:54 +00003086
Erik Andersene49d5ec2000-02-08 19:58:47 +00003087 /* Output the flags if they fill a byte: */
3088 if ((last_lit & 7) == 0) {
3089 flag_buf[last_flags++] = flags;
3090 flags = 0, flag_bit = 1;
3091 }
3092 /* Try to guess if it is profitable to stop the current block here */
3093 if ((last_lit & 0xfff) == 0) {
3094 /* Compute an upper bound for the compressed length */
3095 ulg out_length = (ulg) last_lit * 8L;
3096 ulg in_length = (ulg) strstart - block_start;
3097 int dcode;
3098
3099 for (dcode = 0; dcode < D_CODES; dcode++) {
3100 out_length +=
3101 (ulg) dyn_dtree[dcode].Freq * (5L + extra_dbits[dcode]);
3102 }
3103 out_length >>= 3;
3104 Trace(
3105 (stderr,
3106 "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
3107 last_lit, last_dist, in_length, out_length,
3108 100L - out_length * 100L / in_length));
3109 if (last_dist < last_lit / 2 && out_length < in_length / 2)
3110 return 1;
3111 }
3112 return (last_lit == LIT_BUFSIZE - 1 || last_dist == DIST_BUFSIZE);
3113 /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
3114 * on 16 bit machines and because stored blocks are restricted to
3115 * 64K-1 bytes.
3116 */
Eric Andersencc8ed391999-10-05 16:24:54 +00003117}
3118
3119/* ===========================================================================
3120 * Send the block data compressed using the given Huffman trees
3121 */
3122local void compress_block(ltree, dtree)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003123ct_data near *ltree; /* literal tree */
3124ct_data near *dtree; /* distance tree */
Eric Andersencc8ed391999-10-05 16:24:54 +00003125{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003126 unsigned dist; /* distance of matched string */
3127 int lc; /* match length or unmatched char (if dist == 0) */
3128 unsigned lx = 0; /* running index in l_buf */
3129 unsigned dx = 0; /* running index in d_buf */
3130 unsigned fx = 0; /* running index in flag_buf */
3131 uch flag = 0; /* current flags */
3132 unsigned code; /* the code to send */
3133 int extra; /* number of extra bits to send */
Eric Andersencc8ed391999-10-05 16:24:54 +00003134
Erik Andersene49d5ec2000-02-08 19:58:47 +00003135 if (last_lit != 0)
3136 do {
3137 if ((lx & 7) == 0)
3138 flag = flag_buf[fx++];
3139 lc = l_buf[lx++];
3140 if ((flag & 1) == 0) {
3141 send_code(lc, ltree); /* send a literal byte */
3142 Tracecv(isgraph(lc), (stderr, " '%c' ", lc));
3143 } else {
3144 /* Here, lc is the match length - MIN_MATCH */
3145 code = length_code[lc];
3146 send_code(code + LITERALS + 1, ltree); /* send the length code */
3147 extra = extra_lbits[code];
3148 if (extra != 0) {
3149 lc -= base_length[code];
3150 send_bits(lc, extra); /* send the extra length bits */
3151 }
3152 dist = d_buf[dx++];
3153 /* Here, dist is the match distance - 1 */
3154 code = d_code(dist);
3155 Assert(code < D_CODES, "bad d_code");
Eric Andersencc8ed391999-10-05 16:24:54 +00003156
Erik Andersene49d5ec2000-02-08 19:58:47 +00003157 send_code(code, dtree); /* send the distance code */
3158 extra = extra_dbits[code];
3159 if (extra != 0) {
3160 dist -= base_dist[code];
3161 send_bits(dist, extra); /* send the extra distance bits */
3162 }
3163 } /* literal or match pair ? */
3164 flag >>= 1;
3165 } while (lx < last_lit);
Eric Andersencc8ed391999-10-05 16:24:54 +00003166
Erik Andersene49d5ec2000-02-08 19:58:47 +00003167 send_code(END_BLOCK, ltree);
Eric Andersencc8ed391999-10-05 16:24:54 +00003168}
3169
3170/* ===========================================================================
3171 * Set the file type to ASCII or BINARY, using a crude approximation:
3172 * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
3173 * IN assertion: the fields freq of dyn_ltree are set and the total of all
3174 * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
3175 */
3176local void set_file_type()
3177{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003178 int n = 0;
3179 unsigned ascii_freq = 0;
3180 unsigned bin_freq = 0;
3181
3182 while (n < 7)
3183 bin_freq += dyn_ltree[n++].Freq;
3184 while (n < 128)
3185 ascii_freq += dyn_ltree[n++].Freq;
3186 while (n < LITERALS)
3187 bin_freq += dyn_ltree[n++].Freq;
3188 *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
3189 if (*file_type == BINARY && translate_eol) {
Matt Kraaidd19c692001-01-31 19:00:21 +00003190 error_msg("-l used on binary file");
Erik Andersene49d5ec2000-02-08 19:58:47 +00003191 }
Eric Andersencc8ed391999-10-05 16:24:54 +00003192}
Erik Andersene49d5ec2000-02-08 19:58:47 +00003193
Eric Andersencc8ed391999-10-05 16:24:54 +00003194/* util.c -- utility functions for gzip support
3195 * Copyright (C) 1992-1993 Jean-loup Gailly
3196 * This is free software; you can redistribute it and/or modify it under the
3197 * terms of the GNU General Public License, see the file COPYING.
3198 */
3199
Eric Andersencc8ed391999-10-05 16:24:54 +00003200#include <ctype.h>
3201#include <errno.h>
3202#include <sys/types.h>
3203
3204#ifdef HAVE_UNISTD_H
3205# include <unistd.h>
3206#endif
3207#ifndef NO_FCNTL_H
3208# include <fcntl.h>
3209#endif
3210
Eric Andersencc8ed391999-10-05 16:24:54 +00003211/* ===========================================================================
3212 * Copy input to output unchanged: zcat == cat with --force.
3213 * IN assertion: insize bytes have already been read in inbuf.
3214 */
3215int copy(in, out)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003216int in, out; /* input and output file descriptors */
Eric Andersencc8ed391999-10-05 16:24:54 +00003217{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003218 errno = 0;
3219 while (insize != 0 && (int) insize != EOF) {
3220 write_buf(out, (char *) inbuf, insize);
3221 bytes_out += insize;
3222 insize = read(in, (char *) inbuf, INBUFSIZ);
3223 }
3224 if ((int) insize == EOF && errno != 0) {
Erik Andersen330fd2b2000-05-19 05:35:19 +00003225 read_error_msg();
Erik Andersene49d5ec2000-02-08 19:58:47 +00003226 }
3227 bytes_in = bytes_out;
3228 return OK;
Eric Andersencc8ed391999-10-05 16:24:54 +00003229}
3230
3231/* ========================================================================
3232 * Put string s in lower case, return s.
3233 */
3234char *strlwr(s)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003235char *s;
Eric Andersencc8ed391999-10-05 16:24:54 +00003236{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003237 char *t;
3238
3239 for (t = s; *t; t++)
3240 *t = tolow(*t);
3241 return s;
Eric Andersencc8ed391999-10-05 16:24:54 +00003242}
3243
3244#if defined(NO_STRING_H) && !defined(STDC_HEADERS)
3245
3246/* Provide missing strspn and strcspn functions. */
3247
Erik Andersen61677fe2000-04-13 01:18:56 +00003248int strspn (const char *s, const char *accept);
3249int strcspn (const char *s, const char *reject);
Eric Andersencc8ed391999-10-05 16:24:54 +00003250
3251/* ========================================================================
3252 * Return the length of the maximum initial segment
3253 * of s which contains only characters in accept.
3254 */
3255int strspn(s, accept)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003256const char *s;
3257const char *accept;
Eric Andersencc8ed391999-10-05 16:24:54 +00003258{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003259 register const char *p;
3260 register const char *a;
3261 register int count = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00003262
Erik Andersene49d5ec2000-02-08 19:58:47 +00003263 for (p = s; *p != '\0'; ++p) {
3264 for (a = accept; *a != '\0'; ++a) {
3265 if (*p == *a)
3266 break;
3267 }
3268 if (*a == '\0')
3269 return count;
3270 ++count;
Eric Andersencc8ed391999-10-05 16:24:54 +00003271 }
Erik Andersene49d5ec2000-02-08 19:58:47 +00003272 return count;
Eric Andersencc8ed391999-10-05 16:24:54 +00003273}
3274
3275/* ========================================================================
3276 * Return the length of the maximum inital segment of s
3277 * which contains no characters from reject.
3278 */
3279int strcspn(s, reject)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003280const char *s;
3281const char *reject;
Eric Andersencc8ed391999-10-05 16:24:54 +00003282{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003283 register int count = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00003284
Erik Andersene49d5ec2000-02-08 19:58:47 +00003285 while (*s != '\0') {
3286 if (strchr(reject, *s++) != NULL)
3287 return count;
3288 ++count;
3289 }
3290 return count;
Eric Andersencc8ed391999-10-05 16:24:54 +00003291}
3292
Erik Andersene49d5ec2000-02-08 19:58:47 +00003293#endif /* NO_STRING_H */
Eric Andersencc8ed391999-10-05 16:24:54 +00003294
3295/* ========================================================================
3296 * Add an environment variable (if any) before argv, and update argc.
3297 * Return the expanded environment variable to be freed later, or NULL
3298 * if no options were added to argv.
3299 */
Erik Andersene49d5ec2000-02-08 19:58:47 +00003300#define SEPARATOR " \t" /* separators in env variable */
Eric Andersencc8ed391999-10-05 16:24:54 +00003301
3302char *add_envopt(argcp, argvp, env)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003303int *argcp; /* pointer to argc */
3304char ***argvp; /* pointer to argv */
3305char *env; /* name of environment variable */
Eric Andersencc8ed391999-10-05 16:24:54 +00003306{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003307 char *p; /* running pointer through env variable */
3308 char **oargv; /* runs through old argv array */
3309 char **nargv; /* runs through new argv array */
3310 int oargc = *argcp; /* old argc */
3311 int nargc = 0; /* number of arguments in env variable */
Eric Andersencc8ed391999-10-05 16:24:54 +00003312
Erik Andersene49d5ec2000-02-08 19:58:47 +00003313 env = (char *) getenv(env);
3314 if (env == NULL)
3315 return NULL;
Eric Andersencc8ed391999-10-05 16:24:54 +00003316
Erik Andersene49d5ec2000-02-08 19:58:47 +00003317 p = (char *) xmalloc(strlen(env) + 1);
3318 env = strcpy(p, env); /* keep env variable intact */
Eric Andersencc8ed391999-10-05 16:24:54 +00003319
Erik Andersene49d5ec2000-02-08 19:58:47 +00003320 for (p = env; *p; nargc++) { /* move through env */
3321 p += strspn(p, SEPARATOR); /* skip leading separators */
3322 if (*p == '\0')
3323 break;
Eric Andersencc8ed391999-10-05 16:24:54 +00003324
Erik Andersene49d5ec2000-02-08 19:58:47 +00003325 p += strcspn(p, SEPARATOR); /* find end of word */
3326 if (*p)
3327 *p++ = '\0'; /* mark it */
3328 }
3329 if (nargc == 0) {
3330 free(env);
3331 return NULL;
3332 }
3333 *argcp += nargc;
3334 /* Allocate the new argv array, with an extra element just in case
3335 * the original arg list did not end with a NULL.
3336 */
3337 nargv = (char **) calloc(*argcp + 1, sizeof(char *));
Eric Andersencc8ed391999-10-05 16:24:54 +00003338
Erik Andersene49d5ec2000-02-08 19:58:47 +00003339 if (nargv == NULL)
Mark Whitleyf57c9442000-12-07 19:56:48 +00003340 error_msg(memory_exhausted);
Erik Andersene49d5ec2000-02-08 19:58:47 +00003341 oargv = *argvp;
3342 *argvp = nargv;
Eric Andersencc8ed391999-10-05 16:24:54 +00003343
Erik Andersene49d5ec2000-02-08 19:58:47 +00003344 /* Copy the program name first */
3345 if (oargc-- < 0)
Matt Kraaidd19c692001-01-31 19:00:21 +00003346 error_msg("argc<=0");
Erik Andersene49d5ec2000-02-08 19:58:47 +00003347 *(nargv++) = *(oargv++);
Eric Andersencc8ed391999-10-05 16:24:54 +00003348
Erik Andersene49d5ec2000-02-08 19:58:47 +00003349 /* Then copy the environment args */
3350 for (p = env; nargc > 0; nargc--) {
3351 p += strspn(p, SEPARATOR); /* skip separators */
3352 *(nargv++) = p; /* store start */
3353 while (*p++); /* skip over word */
3354 }
3355
3356 /* Finally copy the old args and add a NULL (usual convention) */
3357 while (oargc--)
3358 *(nargv++) = *(oargv++);
3359 *nargv = NULL;
3360 return env;
Eric Andersencc8ed391999-10-05 16:24:54 +00003361}
Erik Andersene49d5ec2000-02-08 19:58:47 +00003362
Eric Andersencc8ed391999-10-05 16:24:54 +00003363/* ========================================================================
3364 * Display compression ratio on the given stream on 6 characters.
3365 */
3366void display_ratio(num, den, file)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003367long num;
3368long den;
3369FILE *file;
Eric Andersencc8ed391999-10-05 16:24:54 +00003370{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003371 long ratio; /* 1000 times the compression ratio */
Eric Andersencc8ed391999-10-05 16:24:54 +00003372
Erik Andersene49d5ec2000-02-08 19:58:47 +00003373 if (den == 0) {
3374 ratio = 0; /* no compression */
3375 } else if (den < 2147483L) { /* (2**31 -1)/1000 */
3376 ratio = 1000L * num / den;
3377 } else {
3378 ratio = num / (den / 1000L);
3379 }
3380 if (ratio < 0) {
3381 putc('-', file);
3382 ratio = -ratio;
3383 } else {
3384 putc(' ', file);
3385 }
3386 fprintf(file, "%2ld.%1ld%%", ratio / 10L, ratio % 10L);
Eric Andersencc8ed391999-10-05 16:24:54 +00003387}
3388
3389
3390/* zip.c -- compress files to the gzip or pkzip format
3391 * Copyright (C) 1992-1993 Jean-loup Gailly
3392 * This is free software; you can redistribute it and/or modify it under the
3393 * terms of the GNU General Public License, see the file COPYING.
3394 */
3395
Eric Andersencc8ed391999-10-05 16:24:54 +00003396#include <ctype.h>
3397#include <sys/types.h>
3398
3399#ifdef HAVE_UNISTD_H
3400# include <unistd.h>
3401#endif
3402#ifndef NO_FCNTL_H
3403# include <fcntl.h>
3404#endif
3405
Erik Andersene49d5ec2000-02-08 19:58:47 +00003406local ulg crc; /* crc on uncompressed file data */
3407long header_bytes; /* number of bytes in gzip header */
Eric Andersencc8ed391999-10-05 16:24:54 +00003408
3409/* ===========================================================================
3410 * Deflate in to out.
3411 * IN assertions: the input and output buffers are cleared.
3412 * The variables time_stamp and save_orig_name are initialized.
3413 */
3414int zip(in, out)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003415int in, out; /* input and output file descriptors */
Eric Andersencc8ed391999-10-05 16:24:54 +00003416{
Eric Andersen851895a2001-03-21 21:52:25 +00003417 uch my_flags = 0; /* general purpose bit flags */
Erik Andersene49d5ec2000-02-08 19:58:47 +00003418 ush attr = 0; /* ascii/binary flag */
3419 ush deflate_flags = 0; /* pkzip -es, -en or -ex equivalent */
Eric Andersencc8ed391999-10-05 16:24:54 +00003420
Erik Andersene49d5ec2000-02-08 19:58:47 +00003421 ifd = in;
3422 ofd = out;
3423 outcnt = 0;
Eric Andersencc8ed391999-10-05 16:24:54 +00003424
Erik Andersene49d5ec2000-02-08 19:58:47 +00003425 /* Write the header to the gzip file. See algorithm.doc for the format */
Eric Andersencc8ed391999-10-05 16:24:54 +00003426
Eric Andersen96bcfd31999-11-12 01:30:18 +00003427
Erik Andersene49d5ec2000-02-08 19:58:47 +00003428 method = DEFLATED;
3429 put_byte(GZIP_MAGIC[0]); /* magic header */
3430 put_byte(GZIP_MAGIC[1]);
3431 put_byte(DEFLATED); /* compression method */
Eric Andersencc8ed391999-10-05 16:24:54 +00003432
Eric Andersen851895a2001-03-21 21:52:25 +00003433 put_byte(my_flags); /* general flags */
Erik Andersene49d5ec2000-02-08 19:58:47 +00003434 put_long(time_stamp);
Eric Andersencc8ed391999-10-05 16:24:54 +00003435
Erik Andersene49d5ec2000-02-08 19:58:47 +00003436 /* Write deflated file to zip file */
3437 crc = updcrc(0, 0);
Eric Andersencc8ed391999-10-05 16:24:54 +00003438
Erik Andersene49d5ec2000-02-08 19:58:47 +00003439 bi_init(out);
3440 ct_init(&attr, &method);
3441 lm_init(&deflate_flags);
Eric Andersencc8ed391999-10-05 16:24:54 +00003442
Erik Andersene49d5ec2000-02-08 19:58:47 +00003443 put_byte((uch) deflate_flags); /* extra flags */
3444 put_byte(OS_CODE); /* OS identifier */
Eric Andersencc8ed391999-10-05 16:24:54 +00003445
Erik Andersene49d5ec2000-02-08 19:58:47 +00003446 header_bytes = (long) outcnt;
Eric Andersencc8ed391999-10-05 16:24:54 +00003447
Erik Andersene49d5ec2000-02-08 19:58:47 +00003448 (void) deflate();
Eric Andersencc8ed391999-10-05 16:24:54 +00003449
Erik Andersene49d5ec2000-02-08 19:58:47 +00003450 /* Write the crc and uncompressed size */
3451 put_long(crc);
3452 put_long(isize);
3453 header_bytes += 2 * sizeof(long);
Eric Andersencc8ed391999-10-05 16:24:54 +00003454
Erik Andersene49d5ec2000-02-08 19:58:47 +00003455 flush_outbuf();
3456 return OK;
Eric Andersencc8ed391999-10-05 16:24:54 +00003457}
3458
3459
3460/* ===========================================================================
3461 * Read a new buffer from the current input file, perform end-of-line
3462 * translation, and update the crc and input file size.
3463 * IN assertion: size >= 2 (for end-of-line translation)
3464 */
3465int file_read(buf, size)
Erik Andersene49d5ec2000-02-08 19:58:47 +00003466char *buf;
3467unsigned size;
Eric Andersencc8ed391999-10-05 16:24:54 +00003468{
Erik Andersene49d5ec2000-02-08 19:58:47 +00003469 unsigned len;
Eric Andersencc8ed391999-10-05 16:24:54 +00003470
Erik Andersene49d5ec2000-02-08 19:58:47 +00003471 Assert(insize == 0, "inbuf not empty");
Eric Andersencc8ed391999-10-05 16:24:54 +00003472
Erik Andersene49d5ec2000-02-08 19:58:47 +00003473 len = read(ifd, buf, size);
3474 if (len == (unsigned) (-1) || len == 0)
3475 return (int) len;
Eric Andersencc8ed391999-10-05 16:24:54 +00003476
Erik Andersene49d5ec2000-02-08 19:58:47 +00003477 crc = updcrc((uch *) buf, len);
3478 isize += (ulg) len;
3479 return (int) len;
Eric Andersencc8ed391999-10-05 16:24:54 +00003480}
Matt Kraai7918e1f2000-11-08 06:52:57 +00003481
3482/* ===========================================================================
3483 * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
3484 * (used for the compressed data only)
3485 */
3486void flush_outbuf()
3487{
3488 if (outcnt == 0)
3489 return;
3490
3491 write_buf(ofd, (char *) outbuf, outcnt);
3492 bytes_out += (ulg) outcnt;
3493 outcnt = 0;
3494}