Previous 15994 Revisions Next

r15678 Thursday 26th July, 2012 at 15:35:27 UTC by Firewave
updated zlib to 1.2.7 / renamed zconf.in.h to zconf.h.in [Oliver St?\195?\182neberg]
[src/lib/zlib]Makefile Makefile.in adler32.c compress.c crc32.c crc32.h deflate.c deflate.h example.c gzclose.c* gzguts.h* gzio.c gzlib.c* gzread.c* gzwrite.c* infback.c inffast.c inffast.h inffixed.h inflate.c inflate.h inftrees.c inftrees.h minigzip.c readme trees.c trees.h uncompr.c zconf.h zconf.h.in* zconf.in.h zlib.h zutil.c zutil.h

src/lib/zlib/gzio.c
r15677r15678
1/* gzio.c -- IO on .gz files
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 *
5 * Compile this file with -DNO_GZCOMPRESS to avoid the compression code.
6 */
7
8/* @(#) $Id$ */
9
10#include <stdio.h>
11
12#include "zutil.h"
13
14#ifdef NO_DEFLATE       /* for compatibility with old definition */
15#  define NO_GZCOMPRESS
16#endif
17
18#ifndef NO_DUMMY_DECL
19struct internal_state {int dummy;}; /* for buggy compilers */
20#endif
21
22#ifndef Z_BUFSIZE
23#  ifdef MAXSEG_64K
24#    define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
25#  else
26#    define Z_BUFSIZE 16384
27#  endif
28#endif
29#ifndef Z_PRINTF_BUFSIZE
30#  define Z_PRINTF_BUFSIZE 4096
31#endif
32
33#ifdef __MVS__
34#  pragma map (fdopen , "\174\174FDOPEN")
35   FILE *fdopen(int, const char *);
36#endif
37
38#ifndef STDC
39extern voidp  malloc OF((uInt size));
40extern void   free   OF((voidpf ptr));
41#endif
42
43#define ALLOC(size) malloc(size)
44#define TRYFREE(p) {if (p) free(p);}
45
46static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
47
48/* gzip flag byte */
49#define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
50#define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
51#define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
52#define ORIG_NAME    0x08 /* bit 3 set: original file name present */
53#define COMMENT      0x10 /* bit 4 set: file comment present */
54#define RESERVED     0xE0 /* bits 5..7: reserved */
55
56typedef struct gz_stream {
57    z_stream stream;
58    int      z_err;   /* error code for last stream operation */
59    int      z_eof;   /* set if end of input file */
60    FILE     *file;   /* .gz file */
61    Byte     *inbuf;  /* input buffer */
62    Byte     *outbuf; /* output buffer */
63    uLong    crc;     /* crc32 of uncompressed data */
64    char     *msg;    /* error message */
65    char     *path;   /* path name for debugging only */
66    int      transparent; /* 1 if input file is not a .gz file */
67    char     mode;    /* 'w' or 'r' */
68    z_off_t  start;   /* start of compressed data in file (header skipped) */
69    z_off_t  in;      /* bytes into deflate or inflate */
70    z_off_t  out;     /* bytes out of deflate or inflate */
71    int      back;    /* one character push-back */
72    int      last;    /* true if push-back is last character */
73} gz_stream;
74
75
76local gzFile gz_open      OF((const char *path, const char *mode, int  fd));
77local int do_flush        OF((gzFile file, int flush));
78local int    get_byte     OF((gz_stream *s));
79local void   check_header OF((gz_stream *s));
80local int    destroy      OF((gz_stream *s));
81local void   putLong      OF((FILE *file, uLong x));
82local uLong  getLong      OF((gz_stream *s));
83
84/* ===========================================================================
85     Opens a gzip (.gz) file for reading or writing. The mode parameter
86   is as in fopen ("rb" or "wb"). The file is given either by file descriptor
87   or path name (if fd == -1).
88     gz_open returns NULL if the file could not be opened or if there was
89   insufficient memory to allocate the (de)compression state; errno
90   can be checked to distinguish the two cases (if errno is zero, the
91   zlib error is Z_MEM_ERROR).
92*/
93local gzFile gz_open (path, mode, fd)
94    const char *path;
95    const char *mode;
96    int  fd;
97{
98    int err;
99    int level = Z_DEFAULT_COMPRESSION; /* compression level */
100    int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
101    char *p = (char*)mode;
102    gz_stream *s;
103    char fmode[80]; /* copy of mode, without the compression level */
104    char *m = fmode;
105
106    if (!path || !mode) return Z_NULL;
107
108    s = (gz_stream *)ALLOC(sizeof(gz_stream));
109    if (!s) return Z_NULL;
110
111    s->stream.zalloc = (alloc_func)0;
112    s->stream.zfree = (free_func)0;
113    s->stream.opaque = (voidpf)0;
114    s->stream.next_in = s->inbuf = Z_NULL;
115    s->stream.next_out = s->outbuf = Z_NULL;
116    s->stream.avail_in = s->stream.avail_out = 0;
117    s->file = NULL;
118    s->z_err = Z_OK;
119    s->z_eof = 0;
120    s->in = 0;
121    s->out = 0;
122    s->back = EOF;
123    s->crc = crc32(0L, Z_NULL, 0);
124    s->msg = NULL;
125    s->transparent = 0;
126
127    s->path = (char*)ALLOC(strlen(path)+1);
128    if (s->path == NULL) {
129        return destroy(s), (gzFile)Z_NULL;
130    }
131    strcpy(s->path, path); /* do this early for debugging */
132
133    s->mode = '\0';
134    do {
135        if (*p == 'r') s->mode = 'r';
136        if (*p == 'w' || *p == 'a') s->mode = 'w';
137        if (*p >= '0' && *p <= '9') {
138            level = *p - '0';
139        } else if (*p == 'f') {
140          strategy = Z_FILTERED;
141        } else if (*p == 'h') {
142          strategy = Z_HUFFMAN_ONLY;
143        } else if (*p == 'R') {
144          strategy = Z_RLE;
145        } else {
146            *m++ = *p; /* copy the mode */
147        }
148    } while (*p++ && m != fmode + sizeof(fmode));
149    if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
150
151    if (s->mode == 'w') {
152#ifdef NO_GZCOMPRESS
153        err = Z_STREAM_ERROR;
154#else
155        err = deflateInit2(&(s->stream), level,
156                           Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
157        /* windowBits is passed < 0 to suppress zlib header */
158
159        s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
160#endif
161        if (err != Z_OK || s->outbuf == Z_NULL) {
162            return destroy(s), (gzFile)Z_NULL;
163        }
164    } else {
165        s->stream.next_in  = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
166
167        err = inflateInit2(&(s->stream), -MAX_WBITS);
168        /* windowBits is passed < 0 to tell that there is no zlib header.
169         * Note that in this case inflate *requires* an extra "dummy" byte
170         * after the compressed stream in order to complete decompression and
171         * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
172         * present after the compressed stream.
173         */
174        if (err != Z_OK || s->inbuf == Z_NULL) {
175            return destroy(s), (gzFile)Z_NULL;
176        }
177    }
178    s->stream.avail_out = Z_BUFSIZE;
179
180    errno = 0;
181    s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
182
183    if (s->file == NULL) {
184        return destroy(s), (gzFile)Z_NULL;
185    }
186    if (s->mode == 'w') {
187        /* Write a very simple .gz header:
188         */
189        fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
190             Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
191        s->start = 10L;
192        /* We use 10L instead of ftell(s->file) to because ftell causes an
193         * fflush on some systems. This version of the library doesn't use
194         * start anyway in write mode, so this initialization is not
195         * necessary.
196         */
197    } else {
198        check_header(s); /* skip the .gz header */
199        s->start = ftell(s->file) - s->stream.avail_in;
200    }
201
202    return (gzFile)s;
203}
204
205/* ===========================================================================
206     Opens a gzip (.gz) file for reading or writing.
207*/
208gzFile ZEXPORT gzopen (path, mode)
209    const char *path;
210    const char *mode;
211{
212    return gz_open (path, mode, -1);
213}
214
215/* ===========================================================================
216     Associate a gzFile with the file descriptor fd. fd is not dup'ed here
217   to mimic the behavio(u)r of fdopen.
218*/
219gzFile ZEXPORT gzdopen (fd, mode)
220    int fd;
221    const char *mode;
222{
223    char name[46];      /* allow for up to 128-bit integers */
224
225    if (fd < 0) return (gzFile)Z_NULL;
226    sprintf(name, "<fd:%d>", fd); /* for debugging */
227
228    return gz_open (name, mode, fd);
229}
230
231/* ===========================================================================
232 * Update the compression level and strategy
233 */
234int ZEXPORT gzsetparams (file, level, strategy)
235    gzFile file;
236    int level;
237    int strategy;
238{
239    gz_stream *s = (gz_stream*)file;
240
241    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
242
243    /* Make room to allow flushing */
244    if (s->stream.avail_out == 0) {
245
246        s->stream.next_out = s->outbuf;
247        if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
248            s->z_err = Z_ERRNO;
249        }
250        s->stream.avail_out = Z_BUFSIZE;
251    }
252
253    return deflateParams (&(s->stream), level, strategy);
254}
255
256/* ===========================================================================
257     Read a byte from a gz_stream; update next_in and avail_in. Return EOF
258   for end of file.
259   IN assertion: the stream s has been sucessfully opened for reading.
260*/
261local int get_byte(s)
262    gz_stream *s;
263{
264    if (s->z_eof) return EOF;
265    if (s->stream.avail_in == 0) {
266        errno = 0;
267        s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
268        if (s->stream.avail_in == 0) {
269            s->z_eof = 1;
270            if (ferror(s->file)) s->z_err = Z_ERRNO;
271            return EOF;
272        }
273        s->stream.next_in = s->inbuf;
274    }
275    s->stream.avail_in--;
276    return *(s->stream.next_in)++;
277}
278
279/* ===========================================================================
280      Check the gzip header of a gz_stream opened for reading. Set the stream
281    mode to transparent if the gzip magic header is not present; set s->err
282    to Z_DATA_ERROR if the magic header is present but the rest of the header
283    is incorrect.
284    IN assertion: the stream s has already been created sucessfully;
285       s->stream.avail_in is zero for the first time, but may be non-zero
286       for concatenated .gz files.
287*/
288local void check_header(s)
289    gz_stream *s;
290{
291    int method; /* method byte */
292    int flags;  /* flags byte */
293    uInt len;
294    int c;
295
296    /* Assure two bytes in the buffer so we can peek ahead -- handle case
297       where first byte of header is at the end of the buffer after the last
298       gzip segment */
299    len = s->stream.avail_in;
300    if (len < 2) {
301        if (len) s->inbuf[0] = s->stream.next_in[0];
302        errno = 0;
303        len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
304        if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
305        s->stream.avail_in += len;
306        s->stream.next_in = s->inbuf;
307        if (s->stream.avail_in < 2) {
308            s->transparent = s->stream.avail_in;
309            return;
310        }
311    }
312
313    /* Peek ahead to check the gzip magic header */
314    if (s->stream.next_in[0] != gz_magic[0] ||
315        s->stream.next_in[1] != gz_magic[1]) {
316        s->transparent = 1;
317        return;
318    }
319    s->stream.avail_in -= 2;
320    s->stream.next_in += 2;
321
322    /* Check the rest of the gzip header */
323    method = get_byte(s);
324    flags = get_byte(s);
325    if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
326        s->z_err = Z_DATA_ERROR;
327        return;
328    }
329
330    /* Discard time, xflags and OS code: */
331    for (len = 0; len < 6; len++) (void)get_byte(s);
332
333    if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
334        len  =  (uInt)get_byte(s);
335        len += ((uInt)get_byte(s))<<8;
336        /* len is garbage if EOF but the loop below will quit anyway */
337        while (len-- != 0 && get_byte(s) != EOF) ;
338    }
339    if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
340        while ((c = get_byte(s)) != 0 && c != EOF) ;
341    }
342    if ((flags & COMMENT) != 0) {   /* skip the .gz file comment */
343        while ((c = get_byte(s)) != 0 && c != EOF) ;
344    }
345    if ((flags & HEAD_CRC) != 0) {  /* skip the header crc */
346        for (len = 0; len < 2; len++) (void)get_byte(s);
347    }
348    s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
349}
350
351 /* ===========================================================================
352 * Cleanup then free the given gz_stream. Return a zlib error code.
353   Try freeing in the reverse order of allocations.
354 */
355local int destroy (s)
356    gz_stream *s;
357{
358    int err = Z_OK;
359
360    if (!s) return Z_STREAM_ERROR;
361
362    TRYFREE(s->msg);
363
364    if (s->stream.state != NULL) {
365        if (s->mode == 'w') {
366#ifdef NO_GZCOMPRESS
367            err = Z_STREAM_ERROR;
368#else
369            err = deflateEnd(&(s->stream));
370#endif
371        } else if (s->mode == 'r') {
372            err = inflateEnd(&(s->stream));
373        }
374    }
375    if (s->file != NULL && fclose(s->file)) {
376#ifdef ESPIPE
377        if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
378#endif
379            err = Z_ERRNO;
380    }
381    if (s->z_err < 0) err = s->z_err;
382
383    TRYFREE(s->inbuf);
384    TRYFREE(s->outbuf);
385    TRYFREE(s->path);
386    TRYFREE(s);
387    return err;
388}
389
390/* ===========================================================================
391     Reads the given number of uncompressed bytes from the compressed file.
392   gzread returns the number of bytes actually read (0 for end of file).
393*/
394int ZEXPORT gzread (file, buf, len)
395    gzFile file;
396    voidp buf;
397    unsigned len;
398{
399    gz_stream *s = (gz_stream*)file;
400    Bytef *start = (Bytef*)buf; /* starting point for crc computation */
401    Byte  *next_out; /* == stream.next_out but not forced far (for MSDOS) */
402
403    if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
404
405    if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
406    if (s->z_err == Z_STREAM_END) return 0;  /* EOF */
407
408    next_out = (Byte*)buf;
409    s->stream.next_out = (Bytef*)buf;
410    s->stream.avail_out = len;
411
412    if (s->stream.avail_out && s->back != EOF) {
413        *next_out++ = s->back;
414        s->stream.next_out++;
415        s->stream.avail_out--;
416        s->back = EOF;
417        s->out++;
418        start++;
419        if (s->last) {
420            s->z_err = Z_STREAM_END;
421            return 1;
422        }
423    }
424
425    while (s->stream.avail_out != 0) {
426
427        if (s->transparent) {
428            /* Copy first the lookahead bytes: */
429            uInt n = s->stream.avail_in;
430            if (n > s->stream.avail_out) n = s->stream.avail_out;
431            if (n > 0) {
432                zmemcpy(s->stream.next_out, s->stream.next_in, n);
433                next_out += n;
434                s->stream.next_out = next_out;
435                s->stream.next_in   += n;
436                s->stream.avail_out -= n;
437                s->stream.avail_in  -= n;
438            }
439            if (s->stream.avail_out > 0) {
440                s->stream.avail_out -=
441                    (uInt)fread(next_out, 1, s->stream.avail_out, s->file);
442            }
443            len -= s->stream.avail_out;
444            s->in  += len;
445            s->out += len;
446            if (len == 0) s->z_eof = 1;
447            return (int)len;
448        }
449        if (s->stream.avail_in == 0 && !s->z_eof) {
450
451            errno = 0;
452            s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
453            if (s->stream.avail_in == 0) {
454                s->z_eof = 1;
455                if (ferror(s->file)) {
456                    s->z_err = Z_ERRNO;
457                    break;
458                }
459            }
460            s->stream.next_in = s->inbuf;
461        }
462        s->in += s->stream.avail_in;
463        s->out += s->stream.avail_out;
464        s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
465        s->in -= s->stream.avail_in;
466        s->out -= s->stream.avail_out;
467
468        if (s->z_err == Z_STREAM_END) {
469            /* Check CRC and original size */
470            s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
471            start = s->stream.next_out;
472
473            if (getLong(s) != s->crc) {
474                s->z_err = Z_DATA_ERROR;
475            } else {
476                (void)getLong(s);
477                /* The uncompressed length returned by above getlong() may be
478                 * different from s->out in case of concatenated .gz files.
479                 * Check for such files:
480                 */
481                check_header(s);
482                if (s->z_err == Z_OK) {
483                    inflateReset(&(s->stream));
484                    s->crc = crc32(0L, Z_NULL, 0);
485                }
486            }
487        }
488        if (s->z_err != Z_OK || s->z_eof) break;
489    }
490    s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
491
492    if (len == s->stream.avail_out &&
493        (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO))
494        return -1;
495    return (int)(len - s->stream.avail_out);
496}
497
498
499/* ===========================================================================
500      Reads one byte from the compressed file. gzgetc returns this byte
501   or -1 in case of end of file or error.
502*/
503int ZEXPORT gzgetc(file)
504    gzFile file;
505{
506    unsigned char c;
507
508    return gzread(file, &c, 1) == 1 ? c : -1;
509}
510
511
512/* ===========================================================================
513      Push one byte back onto the stream.
514*/
515int ZEXPORT gzungetc(c, file)
516    int c;
517    gzFile file;
518{
519    gz_stream *s = (gz_stream*)file;
520
521    if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF;
522    s->back = c;
523    s->out--;
524    s->last = (s->z_err == Z_STREAM_END);
525    if (s->last) s->z_err = Z_OK;
526    s->z_eof = 0;
527    return c;
528}
529
530
531/* ===========================================================================
532      Reads bytes from the compressed file until len-1 characters are
533   read, or a newline character is read and transferred to buf, or an
534   end-of-file condition is encountered.  The string is then terminated
535   with a null character.
536      gzgets returns buf, or Z_NULL in case of error.
537
538      The current implementation is not optimized at all.
539*/
540char * ZEXPORT gzgets(file, buf, len)
541    gzFile file;
542    char *buf;
543    int len;
544{
545    char *b = buf;
546    if (buf == Z_NULL || len <= 0) return Z_NULL;
547
548    while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ;
549    *buf = '\0';
550    return b == buf && len > 0 ? Z_NULL : b;
551}
552
553
554#ifndef NO_GZCOMPRESS
555/* ===========================================================================
556     Writes the given number of uncompressed bytes into the compressed file.
557   gzwrite returns the number of bytes actually written (0 in case of error).
558*/
559int ZEXPORT gzwrite (file, buf, len)
560    gzFile file;
561    voidpc buf;
562    unsigned len;
563{
564    gz_stream *s = (gz_stream*)file;
565
566    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
567
568    s->stream.next_in = (Bytef*)buf;
569    s->stream.avail_in = len;
570
571    while (s->stream.avail_in != 0) {
572
573        if (s->stream.avail_out == 0) {
574
575            s->stream.next_out = s->outbuf;
576            if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
577                s->z_err = Z_ERRNO;
578                break;
579            }
580            s->stream.avail_out = Z_BUFSIZE;
581        }
582        s->in += s->stream.avail_in;
583        s->out += s->stream.avail_out;
584        s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
585        s->in -= s->stream.avail_in;
586        s->out -= s->stream.avail_out;
587        if (s->z_err != Z_OK) break;
588    }
589    s->crc = crc32(s->crc, (const Bytef *)buf, len);
590
591    return (int)(len - s->stream.avail_in);
592}
593
594
595/* ===========================================================================
596     Converts, formats, and writes the args to the compressed file under
597   control of the format string, as in fprintf. gzprintf returns the number of
598   uncompressed bytes actually written (0 in case of error).
599*/
600#ifdef STDC
601#include <stdarg.h>
602
603int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
604{
605    char buf[Z_PRINTF_BUFSIZE];
606    va_list va;
607    int len;
608
609    buf[sizeof(buf) - 1] = 0;
610    va_start(va, format);
611#ifdef NO_vsnprintf
612#  ifdef HAS_vsprintf_void
613    (void)vsprintf(buf, format, va);
614    va_end(va);
615    for (len = 0; len < sizeof(buf); len++)
616        if (buf[len] == 0) break;
617#  else
618    len = vsprintf(buf, format, va);
619    va_end(va);
620#  endif
621#else
622#  ifdef HAS_vsnprintf_void
623    (void)vsnprintf(buf, sizeof(buf), format, va);
624    va_end(va);
625    len = strlen(buf);
626#  else
627    len = vsnprintf(buf, sizeof(buf), format, va);
628    va_end(va);
629#  endif
630#endif
631    if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0)
632        return 0;
633    return gzwrite(file, buf, (unsigned)len);
634}
635#else /* not ANSI C */
636
637int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
638                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
639    gzFile file;
640    const char *format;
641    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
642        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
643{
644    char buf[Z_PRINTF_BUFSIZE];
645    int len;
646
647    buf[sizeof(buf) - 1] = 0;
648#ifdef NO_snprintf
649#  ifdef HAS_sprintf_void
650    sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
651            a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
652    for (len = 0; len < sizeof(buf); len++)
653        if (buf[len] == 0) break;
654#  else
655    len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
656                a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
657#  endif
658#else
659#  ifdef HAS_snprintf_void
660    snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
661             a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
662    len = strlen(buf);
663#  else
664    len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
665                 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
666#  endif
667#endif
668    if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0)
669        return 0;
670    return gzwrite(file, buf, len);
671}
672#endif
673
674/* ===========================================================================
675      Writes c, converted to an unsigned char, into the compressed file.
676   gzputc returns the value that was written, or -1 in case of error.
677*/
678int ZEXPORT gzputc(file, c)
679    gzFile file;
680    int c;
681{
682    unsigned char cc = (unsigned char) c; /* required for big endian systems */
683
684    return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1;
685}
686
687
688/* ===========================================================================
689      Writes the given null-terminated string to the compressed file, excluding
690   the terminating null character.
691      gzputs returns the number of characters written, or -1 in case of error.
692*/
693int ZEXPORT gzputs(file, s)
694    gzFile file;
695    const char *s;
696{
697    return gzwrite(file, (char*)s, (unsigned)strlen(s));
698}
699
700
701/* ===========================================================================
702     Flushes all pending output into the compressed file. The parameter
703   flush is as in the deflate() function.
704*/
705local int do_flush (file, flush)
706    gzFile file;
707    int flush;
708{
709    uInt len;
710    int done = 0;
711    gz_stream *s = (gz_stream*)file;
712
713    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
714
715    s->stream.avail_in = 0; /* should be zero already anyway */
716
717    for (;;) {
718        len = Z_BUFSIZE - s->stream.avail_out;
719
720        if (len != 0) {
721            if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
722                s->z_err = Z_ERRNO;
723                return Z_ERRNO;
724            }
725            s->stream.next_out = s->outbuf;
726            s->stream.avail_out = Z_BUFSIZE;
727        }
728        if (done) break;
729        s->out += s->stream.avail_out;
730        s->z_err = deflate(&(s->stream), flush);
731        s->out -= s->stream.avail_out;
732
733        /* Ignore the second of two consecutive flushes: */
734        if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
735
736        /* deflate has finished flushing only when it hasn't used up
737         * all the available space in the output buffer:
738         */
739        done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
740
741        if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
742    }
743    return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
744}
745
746int ZEXPORT gzflush (file, flush)
747     gzFile file;
748     int flush;
749{
750    gz_stream *s = (gz_stream*)file;
751    int err = do_flush (file, flush);
752
753    if (err) return err;
754    fflush(s->file);
755    return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
756}
757#endif /* NO_GZCOMPRESS */
758
759/* ===========================================================================
760      Sets the starting position for the next gzread or gzwrite on the given
761   compressed file. The offset represents a number of bytes in the
762      gzseek returns the resulting offset location as measured in bytes from
763   the beginning of the uncompressed stream, or -1 in case of error.
764      SEEK_END is not implemented, returns error.
765      In this version of the library, gzseek can be extremely slow.
766*/
767z_off_t ZEXPORT gzseek (file, offset, whence)
768    gzFile file;
769    z_off_t offset;
770    int whence;
771{
772    gz_stream *s = (gz_stream*)file;
773
774    if (s == NULL || whence == SEEK_END ||
775        s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
776        return -1L;
777    }
778
779    if (s->mode == 'w') {
780#ifdef NO_GZCOMPRESS
781        return -1L;
782#else
783        if (whence == SEEK_SET) {
784            offset -= s->in;
785        }
786        if (offset < 0) return -1L;
787
788        /* At this point, offset is the number of zero bytes to write. */
789        if (s->inbuf == Z_NULL) {
790            s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
791            if (s->inbuf == Z_NULL) return -1L;
792            zmemzero(s->inbuf, Z_BUFSIZE);
793        }
794        while (offset > 0)  {
795            uInt size = Z_BUFSIZE;
796            if (offset < Z_BUFSIZE) size = (uInt)offset;
797
798            size = gzwrite(file, s->inbuf, size);
799            if (size == 0) return -1L;
800
801            offset -= size;
802        }
803        return s->in;
804#endif
805    }
806    /* Rest of function is for reading only */
807
808    /* compute absolute position */
809    if (whence == SEEK_CUR) {
810        offset += s->out;
811    }
812    if (offset < 0) return -1L;
813
814    if (s->transparent) {
815        /* map to fseek */
816        s->back = EOF;
817        s->stream.avail_in = 0;
818        s->stream.next_in = s->inbuf;
819        if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
820
821        s->in = s->out = offset;
822        return offset;
823    }
824
825    /* For a negative seek, rewind and use positive seek */
826    if (offset >= s->out) {
827        offset -= s->out;
828    } else if (gzrewind(file) < 0) {
829        return -1L;
830    }
831    /* offset is now the number of bytes to skip. */
832
833    if (offset != 0 && s->outbuf == Z_NULL) {
834        s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
835        if (s->outbuf == Z_NULL) return -1L;
836    }
837    if (offset && s->back != EOF) {
838        s->back = EOF;
839        s->out++;
840        offset--;
841        if (s->last) s->z_err = Z_STREAM_END;
842    }
843    while (offset > 0)  {
844        int size = Z_BUFSIZE;
845        if (offset < Z_BUFSIZE) size = (int)offset;
846
847        size = gzread(file, s->outbuf, (uInt)size);
848        if (size <= 0) return -1L;
849        offset -= size;
850    }
851    return s->out;
852}
853
854/* ===========================================================================
855     Rewinds input file.
856*/
857int ZEXPORT gzrewind (file)
858    gzFile file;
859{
860    gz_stream *s = (gz_stream*)file;
861
862    if (s == NULL || s->mode != 'r') return -1;
863
864    s->z_err = Z_OK;
865    s->z_eof = 0;
866    s->back = EOF;
867    s->stream.avail_in = 0;
868    s->stream.next_in = s->inbuf;
869    s->crc = crc32(0L, Z_NULL, 0);
870    if (!s->transparent) (void)inflateReset(&s->stream);
871    s->in = 0;
872    s->out = 0;
873    return fseek(s->file, s->start, SEEK_SET);
874}
875
876/* ===========================================================================
877     Returns the starting position for the next gzread or gzwrite on the
878   given compressed file. This position represents a number of bytes in the
879   uncompressed data stream.
880*/
881z_off_t ZEXPORT gztell (file)
882    gzFile file;
883{
884    return gzseek(file, 0L, SEEK_CUR);
885}
886
887/* ===========================================================================
888     Returns 1 when EOF has previously been detected reading the given
889   input stream, otherwise zero.
890*/
891int ZEXPORT gzeof (file)
892    gzFile file;
893{
894    gz_stream *s = (gz_stream*)file;
895
896    /* With concatenated compressed files that can have embedded
897     * crc trailers, z_eof is no longer the only/best indicator of EOF
898     * on a gz_stream. Handle end-of-stream error explicitly here.
899     */
900    if (s == NULL || s->mode != 'r') return 0;
901    if (s->z_eof) return 1;
902    return s->z_err == Z_STREAM_END;
903}
904
905/* ===========================================================================
906     Returns 1 if reading and doing so transparently, otherwise zero.
907*/
908int ZEXPORT gzdirect (file)
909    gzFile file;
910{
911    gz_stream *s = (gz_stream*)file;
912
913    if (s == NULL || s->mode != 'r') return 0;
914    return s->transparent;
915}
916
917/* ===========================================================================
918   Outputs a long in LSB order to the given file
919*/
920local void putLong (file, x)
921    FILE *file;
922    uLong x;
923{
924    int n;
925    for (n = 0; n < 4; n++) {
926        fputc((int)(x & 0xff), file);
927        x >>= 8;
928    }
929}
930
931/* ===========================================================================
932   Reads a long in LSB order from the given gz_stream. Sets z_err in case
933   of error.
934*/
935local uLong getLong (s)
936    gz_stream *s;
937{
938    uLong x = (uLong)get_byte(s);
939    int c;
940
941    x += ((uLong)get_byte(s))<<8;
942    x += ((uLong)get_byte(s))<<16;
943    c = get_byte(s);
944    if (c == EOF) s->z_err = Z_DATA_ERROR;
945    x += ((uLong)c)<<24;
946    return x;
947}
948
949/* ===========================================================================
950     Flushes all pending output if necessary, closes the compressed file
951   and deallocates all the (de)compression state.
952*/
953int ZEXPORT gzclose (file)
954    gzFile file;
955{
956    gz_stream *s = (gz_stream*)file;
957
958    if (s == NULL) return Z_STREAM_ERROR;
959
960    if (s->mode == 'w') {
961#ifdef NO_GZCOMPRESS
962        return Z_STREAM_ERROR;
963#else
964        if (do_flush (file, Z_FINISH) != Z_OK)
965            return destroy((gz_stream*)file);
966
967        putLong (s->file, s->crc);
968        putLong (s->file, (uLong)(s->in & 0xffffffff));
969#endif
970    }
971    return destroy((gz_stream*)file);
972}
973
974#ifdef STDC
975#  define zstrerror(errnum) strerror(errnum)
976#else
977#  define zstrerror(errnum) ""
978#endif
979
980/* ===========================================================================
981     Returns the error message for the last error which occurred on the
982   given compressed file. errnum is set to zlib error number. If an
983   error occurred in the file system and not in the compression library,
984   errnum is set to Z_ERRNO and the application may consult errno
985   to get the exact error code.
986*/
987const char * ZEXPORT gzerror (file, errnum)
988    gzFile file;
989    int *errnum;
990{
991    char *m;
992    gz_stream *s = (gz_stream*)file;
993
994    if (s == NULL) {
995        *errnum = Z_STREAM_ERROR;
996        return (const char*)ERR_MSG(Z_STREAM_ERROR);
997    }
998    *errnum = s->z_err;
999    if (*errnum == Z_OK) return (const char*)"";
1000
1001    m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
1002
1003    if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
1004
1005    TRYFREE(s->msg);
1006    s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
1007    if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR);
1008    strcpy(s->msg, s->path);
1009    strcat(s->msg, ": ");
1010    strcat(s->msg, m);
1011    return (const char*)s->msg;
1012}
1013
1014/* ===========================================================================
1015     Clear the error and end-of-file flags, and do the same for the real file.
1016*/
1017void ZEXPORT gzclearerr (file)
1018    gzFile file;
1019{
1020    gz_stream *s = (gz_stream*)file;
1021
1022    if (s == NULL) return;
1023    if (s->z_err != Z_STREAM_END) s->z_err = Z_OK;
1024    s->z_eof = 0;
1025    clearerr(s->file);
1026}
src/lib/zlib/zconf.in.h
r15677r15678
1/* zconf.h -- configuration of the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#ifndef ZCONF_H
9#define ZCONF_H
10
11/*
12 * If you *really* need a unique prefix for all types and library functions,
13 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
14 */
15#ifdef Z_PREFIX
16#  define deflateInit_          z_deflateInit_
17#  define deflate               z_deflate
18#  define deflateEnd            z_deflateEnd
19#  define inflateInit_          z_inflateInit_
20#  define inflate               z_inflate
21#  define inflateEnd            z_inflateEnd
22#  define deflateInit2_         z_deflateInit2_
23#  define deflateSetDictionary  z_deflateSetDictionary
24#  define deflateCopy           z_deflateCopy
25#  define deflateReset          z_deflateReset
26#  define deflateParams         z_deflateParams
27#  define deflateBound          z_deflateBound
28#  define deflatePrime          z_deflatePrime
29#  define inflateInit2_         z_inflateInit2_
30#  define inflateSetDictionary  z_inflateSetDictionary
31#  define inflateSync           z_inflateSync
32#  define inflateSyncPoint      z_inflateSyncPoint
33#  define inflateCopy           z_inflateCopy
34#  define inflateReset          z_inflateReset
35#  define inflateBack           z_inflateBack
36#  define inflateBackEnd        z_inflateBackEnd
37#  define compress              z_compress
38#  define compress2             z_compress2
39#  define compressBound         z_compressBound
40#  define uncompress            z_uncompress
41#  define adler32               z_adler32
42#  define crc32                 z_crc32
43#  define get_crc_table         z_get_crc_table
44#  define zError                z_zError
45
46#  define alloc_func            z_alloc_func
47#  define free_func             z_free_func
48#  define in_func               z_in_func
49#  define out_func              z_out_func
50#  define Byte                  z_Byte
51#  define uInt                  z_uInt
52#  define uLong                 z_uLong
53#  define Bytef                 z_Bytef
54#  define charf                 z_charf
55#  define intf                  z_intf
56#  define uIntf                 z_uIntf
57#  define uLongf                z_uLongf
58#  define voidpf                z_voidpf
59#  define voidp                 z_voidp
60#endif
61
62#if defined(__MSDOS__) && !defined(MSDOS)
63#  define MSDOS
64#endif
65#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
66#  define OS2
67#endif
68#if defined(_WINDOWS) && !defined(WINDOWS)
69#  define WINDOWS
70#endif
71#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
72#  ifndef WIN32
73#    define WIN32
74#  endif
75#endif
76#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
77#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
78#    ifndef SYS16BIT
79#      define SYS16BIT
80#    endif
81#  endif
82#endif
83
84/*
85 * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
86 * than 64k bytes at a time (needed on systems with 16-bit int).
87 */
88#ifdef SYS16BIT
89#  define MAXSEG_64K
90#endif
91#ifdef MSDOS
92#  define UNALIGNED_OK
93#endif
94
95#ifdef __STDC_VERSION__
96#  ifndef STDC
97#    define STDC
98#  endif
99#  if __STDC_VERSION__ >= 199901L
100#    ifndef STDC99
101#      define STDC99
102#    endif
103#  endif
104#endif
105#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
106#  define STDC
107#endif
108#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
109#  define STDC
110#endif
111#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
112#  define STDC
113#endif
114#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
115#  define STDC
116#endif
117
118#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
119#  define STDC
120#endif
121
122#ifndef STDC
123#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
124#    define const       /* note: need a more gentle solution here */
125#  endif
126#endif
127
128/* Some Mac compilers merge all .h files incorrectly: */
129#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
130#  define NO_DUMMY_DECL
131#endif
132
133/* Maximum value for memLevel in deflateInit2 */
134#ifndef MAX_MEM_LEVEL
135#  ifdef MAXSEG_64K
136#    define MAX_MEM_LEVEL 8
137#  else
138#    define MAX_MEM_LEVEL 9
139#  endif
140#endif
141
142/* Maximum value for windowBits in deflateInit2 and inflateInit2.
143 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
144 * created by gzip. (Files created by minigzip can still be extracted by
145 * gzip.)
146 */
147#ifndef MAX_WBITS
148#  define MAX_WBITS   15 /* 32K LZ77 window */
149#endif
150
151/* The memory requirements for deflate are (in bytes):
152            (1 << (windowBits+2)) +  (1 << (memLevel+9))
153 that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
154 plus a few kilobytes for small objects. For example, if you want to reduce
155 the default memory requirements from 256K to 128K, compile with
156     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
157 Of course this will generally degrade compression (there's no free lunch).
158
159   The memory requirements for inflate are (in bytes) 1 << windowBits
160 that is, 32K for windowBits=15 (default value) plus a few kilobytes
161 for small objects.
162*/
163
164                        /* Type declarations */
165
166#ifndef OF /* function prototypes */
167#  ifdef STDC
168#    define OF(args)  args
169#  else
170#    define OF(args)  ()
171#  endif
172#endif
173
174/* The following definitions for FAR are needed only for MSDOS mixed
175 * model programming (small or medium model with some far allocations).
176 * This was tested only with MSC; for other MSDOS compilers you may have
177 * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
178 * just define FAR to be empty.
179 */
180#ifdef SYS16BIT
181#  if defined(M_I86SM) || defined(M_I86MM)
182     /* MSC small or medium model */
183#    define SMALL_MEDIUM
184#    ifdef _MSC_VER
185#      define FAR _far
186#    else
187#      define FAR far
188#    endif
189#  endif
190#  if (defined(__SMALL__) || defined(__MEDIUM__))
191     /* Turbo C small or medium model */
192#    define SMALL_MEDIUM
193#    ifdef __BORLANDC__
194#      define FAR _far
195#    else
196#      define FAR far
197#    endif
198#  endif
199#endif
200
201#if defined(WINDOWS) || defined(WIN32)
202   /* If building or using zlib as a DLL, define ZLIB_DLL.
203    * This is not mandatory, but it offers a little performance increase.
204    */
205#  ifdef ZLIB_DLL
206#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
207#      ifdef ZLIB_INTERNAL
208#        define ZEXTERN extern __declspec(dllexport)
209#      else
210#        define ZEXTERN extern __declspec(dllimport)
211#      endif
212#    endif
213#  endif  /* ZLIB_DLL */
214   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
215    * define ZLIB_WINAPI.
216    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
217    */
218#  ifdef ZLIB_WINAPI
219#    ifdef FAR
220#      undef FAR
221#    endif
222#    include <windows.h>
223     /* No need for _export, use ZLIB.DEF instead. */
224     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
225#    define ZEXPORT WINAPI
226#    ifdef WIN32
227#      define ZEXPORTVA WINAPIV
228#    else
229#      define ZEXPORTVA FAR CDECL
230#    endif
231#  endif
232#endif
233
234#if defined (__BEOS__)
235#  ifdef ZLIB_DLL
236#    ifdef ZLIB_INTERNAL
237#      define ZEXPORT   __declspec(dllexport)
238#      define ZEXPORTVA __declspec(dllexport)
239#    else
240#      define ZEXPORT   __declspec(dllimport)
241#      define ZEXPORTVA __declspec(dllimport)
242#    endif
243#  endif
244#endif
245
246#ifndef ZEXTERN
247#  define ZEXTERN extern
248#endif
249#ifndef ZEXPORT
250#  define ZEXPORT
251#endif
252#ifndef ZEXPORTVA
253#  define ZEXPORTVA
254#endif
255
256#ifndef FAR
257#  define FAR
258#endif
259
260#if !defined(__MACTYPES__)
261typedef unsigned char  Byte;  /* 8 bits */
262#endif
263typedef unsigned int   uInt;  /* 16 bits or more */
264typedef unsigned long  uLong; /* 32 bits or more */
265
266#ifdef SMALL_MEDIUM
267   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
268#  define Bytef Byte FAR
269#else
270   typedef Byte  FAR Bytef;
271#endif
272typedef char  FAR charf;
273typedef int   FAR intf;
274typedef uInt  FAR uIntf;
275typedef uLong FAR uLongf;
276
277#ifdef STDC
278   typedef void const *voidpc;
279   typedef void FAR   *voidpf;
280   typedef void       *voidp;
281#else
282   typedef Byte const *voidpc;
283   typedef Byte FAR   *voidpf;
284   typedef Byte       *voidp;
285#endif
286
287#if 0           /* HAVE_UNISTD_H -- this line is updated by ./configure */
288#  include <sys/types.h> /* for off_t */
289#  include <unistd.h>    /* for SEEK_* and off_t */
290#  ifdef VMS
291#    include <unixio.h>   /* for off_t */
292#  endif
293#  define z_off_t off_t
294#endif
295#ifndef SEEK_SET
296#  define SEEK_SET        0       /* Seek from beginning of file.  */
297#  define SEEK_CUR        1       /* Seek from current position.  */
298#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
299#endif
300#ifndef z_off_t
301#  define z_off_t long
302#endif
303
304#if defined(__OS400__)
305#  define NO_vsnprintf
306#endif
307
308#if defined(__MVS__)
309#  define NO_vsnprintf
310#  ifdef FAR
311#    undef FAR
312#  endif
313#endif
314
315/* MVS linker does not support external names larger than 8 bytes */
316#if defined(__MVS__)
317#   pragma map(deflateInit_,"DEIN")
318#   pragma map(deflateInit2_,"DEIN2")
319#   pragma map(deflateEnd,"DEEND")
320#   pragma map(deflateBound,"DEBND")
321#   pragma map(inflateInit_,"ININ")
322#   pragma map(inflateInit2_,"ININ2")
323#   pragma map(inflateEnd,"INEND")
324#   pragma map(inflateSync,"INSY")
325#   pragma map(inflateSetDictionary,"INSEDI")
326#   pragma map(compressBound,"CMBND")
327#   pragma map(inflate_table,"INTABL")
328#   pragma map(inflate_fast,"INFA")
329#   pragma map(inflate_copyright,"INCOPY")
330#endif
331
332#endif /* ZCONF_H */
src/lib/zlib/inffixed.h
r15677r15678
22     * Generated automatically by makefixed().
33     */
44
5    /* WARNING: this file should *not* be used by applications. It
6       is part of the implementation of the compression library and
7       is subject to change. Applications should only use zlib.h.
5    /* WARNING: this file should *not* be used by applications.
6       It is part of the implementation of this library and is
7       subject to change. Applications should only use zlib.h.
88     */
99
1010    static const code lenfix[512] = {
src/lib/zlib/Makefile.in
r15677r15678
11# Makefile for zlib
2# Copyright (C) 1995-2005 Jean-loup Gailly.
2# Copyright (C) 1995-2011 Jean-loup Gailly.
33# For conditions of distribution and use, see copyright notice in zlib.h
44
55# To compile and test, type:
66#    ./configure; make test
7# The call of configure is optional if you don't have special requirements
8# If you wish to build zlib as a shared library, use: ./configure -s
7# Normally configure builds both a static and a shared library.
8# If you want to build just a static library, use: ./configure --static
99
1010# To use the asm code, type:
1111#    cp contrib/asm?86/match.S ./match.S
r15677r15678
2424#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
2525#           -Wstrict-prototypes -Wmissing-prototypes
2626
27LDFLAGS=libz.a
27SFLAGS=-O
28LDFLAGS=
29TEST_LDFLAGS=-L. libz.a
2830LDSHARED=$(CC)
2931CPP=$(CC) -E
3032
31LIBS=libz.a
33STATICLIB=libz.a
3234SHAREDLIB=libz.so
33SHAREDLIBV=libz.so.1.2.3
35SHAREDLIBV=libz.so.1.2.7
3436SHAREDLIBM=libz.so.1
37LIBS=$(STATICLIB) $(SHAREDLIBV)
3538
36AR=ar rc
39AR=ar
40ARFLAGS=rc
3741RANLIB=ranlib
42LDCONFIG=ldconfig
43LDSHAREDLIBC=-lc
3844TAR=tar
3945SHELL=/bin/sh
4046EXE=
r15677r15678
4248prefix = /usr/local
4349exec_prefix = ${prefix}
4450libdir = ${exec_prefix}/lib
51sharedlibdir = ${libdir}
4552includedir = ${prefix}/include
4653mandir = ${prefix}/share/man
4754man3dir = ${mandir}/man3
55pkgconfigdir = ${libdir}/pkgconfig
4856
49OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
50       zutil.o inflate.o infback.o inftrees.o inffast.o
57OBJZ = adler32.o crc32.o deflate.o infback.o inffast.o inflate.o inftrees.o trees.o zutil.o
58OBJG = compress.o uncompr.o gzclose.o gzlib.o gzread.o gzwrite.o
59OBJC = $(OBJZ) $(OBJG)
5160
61PIC_OBJZ = adler32.lo crc32.lo deflate.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo zutil.lo
62PIC_OBJG = compress.lo uncompr.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo
63PIC_OBJC = $(PIC_OBJZ) $(PIC_OBJG)
64
65# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo
5266OBJA =
53# to use the asm code: make OBJA=match.o
67PIC_OBJA =
5468
55TEST_OBJS = example.o minigzip.o
69OBJS = $(OBJC) $(OBJA)
5670
57all: example$(EXE) minigzip$(EXE)
71PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA)
5872
73all: static shared
74
75static: example$(EXE) minigzip$(EXE)
76
77shared: examplesh$(EXE) minigzipsh$(EXE)
78
79all64: example64$(EXE) minigzip64$(EXE)
80
5981check: test
60test: all
61   @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
62   echo hello world | ./minigzip | ./minigzip -d || \
63     echo '      *** minigzip test FAILED ***' ; \
64   if ./example; then \
82
83test: all teststatic testshared
84
85teststatic: static
86   @TMPST=`mktemp fooXXXXXX`; \
87   if echo hello world | ./minigzip | ./minigzip -d && ./example $$TMPST ; then \
6588     echo '      *** zlib test OK ***'; \
6689   else \
67     echo '      *** zlib test FAILED ***'; \
68   fi
90     echo '      *** zlib test FAILED ***'; false; \
91   fi; \
92   rm -f $$TMPST
6993
70libz.a: $(OBJS) $(OBJA)
71   $(AR) $@ $(OBJS) $(OBJA)
94testshared: shared
95   @LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
96   LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \
97   DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \
98   SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \
99   TMPSH=`mktemp fooXXXXXX`; \
100   if echo hello world | ./minigzipsh | ./minigzipsh -d && ./examplesh $$TMPSH; then \
101     echo '      *** zlib shared test OK ***'; \
102   else \
103     echo '      *** zlib shared test FAILED ***'; false; \
104   fi; \
105   rm -f $$TMPSH
106
107test64: all64
108   @TMP64=`mktemp fooXXXXXX`; \
109   if echo hello world | ./minigzip64 | ./minigzip64 -d && ./example64 $$TMP64; then \
110     echo '      *** zlib 64-bit test OK ***'; \
111   else \
112     echo '      *** zlib 64-bit test FAILED ***'; false; \
113   fi; \
114   rm -f $$TMP64
115
116infcover.o: test/infcover.c zlib.h zconf.h
117   $(CC) $(CFLAGS) -I. -c -o $@ test/infcover.c
118
119infcover: infcover.o libz.a
120   $(CC) $(CFLAGS) -o $@ infcover.o libz.a
121
122cover: infcover
123   rm -f *.gcda
124   ./infcover
125   gcov inf*.c
126
127libz.a: $(OBJS)
128   $(AR) $(ARFLAGS) $@ $(OBJS)
72129   -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
73130
74131match.o: match.S
r15677r15678
77134   mv _match.o match.o
78135   rm -f _match.s
79136
80$(SHAREDLIBV): $(OBJS)
81   $(LDSHARED) -o $@ $(OBJS)
137match.lo: match.S
138   $(CPP) match.S > _match.s
139   $(CC) -c -fPIC _match.s
140   mv _match.o match.lo
141   rm -f _match.s
142
143example.o: test/example.c zlib.h zconf.h
144   $(CC) $(CFLAGS) -I. -c -o $@ test/example.c
145
146minigzip.o: test/minigzip.c zlib.h zconf.h
147   $(CC) $(CFLAGS) -I. -c -o $@ test/minigzip.c
148
149example64.o: test/example.c zlib.h zconf.h
150   $(CC) $(CFLAGS) -I. -D_FILE_OFFSET_BITS=64 -c -o $@ test/example.c
151
152minigzip64.o: test/minigzip.c zlib.h zconf.h
153   $(CC) $(CFLAGS) -I. -D_FILE_OFFSET_BITS=64 -c -o $@ test/minigzip.c
154
155.SUFFIXES: .lo
156
157.c.lo:
158   -@mkdir objs 2>/dev/null || test -d objs
159   $(CC) $(SFLAGS) -DPIC -c -o objs/$*.o $<
160   -@mv objs/$*.o $@
161
162placebo $(SHAREDLIBV): $(PIC_OBJS) libz.a
163   $(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) $(LDSHAREDLIBC) $(LDFLAGS)
82164   rm -f $(SHAREDLIB) $(SHAREDLIBM)
83165   ln -s $@ $(SHAREDLIB)
84166   ln -s $@ $(SHAREDLIBM)
167   -@rmdir objs
85168
86example$(EXE): example.o $(LIBS)
87   $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
169example$(EXE): example.o $(STATICLIB)
170   $(CC) $(CFLAGS) -o $@ example.o $(TEST_LDFLAGS)
88171
89minigzip$(EXE): minigzip.o $(LIBS)
90   $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
172minigzip$(EXE): minigzip.o $(STATICLIB)
173   $(CC) $(CFLAGS) -o $@ minigzip.o $(TEST_LDFLAGS)
91174
92install: $(LIBS)
93   -@if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi
94   -@if [ ! -d $(includedir)  ]; then mkdir -p $(includedir); fi
95   -@if [ ! -d $(libdir)      ]; then mkdir -p $(libdir); fi
96   -@if [ ! -d $(man3dir)     ]; then mkdir -p $(man3dir); fi
97   cp zlib.h zconf.h $(includedir)
98   chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h
99   cp $(LIBS) $(libdir)
100   cd $(libdir); chmod 755 $(LIBS)
101   -@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
102   cd $(libdir); if test -f $(SHAREDLIBV); then \
103     rm -f $(SHAREDLIB) $(SHAREDLIBM); \
104     ln -s $(SHAREDLIBV) $(SHAREDLIB); \
105     ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
106     (ldconfig || true)  >/dev/null 2>&1; \
175examplesh$(EXE): example.o $(SHAREDLIBV)
176   $(CC) $(CFLAGS) -o $@ example.o -L. $(SHAREDLIBV)
177
178minigzipsh$(EXE): minigzip.o $(SHAREDLIBV)
179   $(CC) $(CFLAGS) -o $@ minigzip.o -L. $(SHAREDLIBV)
180
181example64$(EXE): example64.o $(STATICLIB)
182   $(CC) $(CFLAGS) -o $@ example64.o $(TEST_LDFLAGS)
183
184minigzip64$(EXE): minigzip64.o $(STATICLIB)
185   $(CC) $(CFLAGS) -o $@ minigzip64.o $(TEST_LDFLAGS)
186
187install-libs: $(LIBS)
188   -@if [ ! -d $(DESTDIR)$(exec_prefix)  ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi
189   -@if [ ! -d $(DESTDIR)$(libdir)       ]; then mkdir -p $(DESTDIR)$(libdir); fi
190   -@if [ ! -d $(DESTDIR)$(sharedlibdir) ]; then mkdir -p $(DESTDIR)$(sharedlibdir); fi
191   -@if [ ! -d $(DESTDIR)$(man3dir)      ]; then mkdir -p $(DESTDIR)$(man3dir); fi
192   -@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi
193   cp $(STATICLIB) $(DESTDIR)$(libdir)
194   chmod 644 $(DESTDIR)$(libdir)/$(STATICLIB)
195   -@($(RANLIB) $(DESTDIR)$(libdir)/libz.a || true) >/dev/null 2>&1
196   -@if test -n "$(SHAREDLIBV)"; then \
197     cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir); \
198     echo "cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)"; \
199     chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \
200     echo "chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV)"; \
201     rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \
202     ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB); \
203     ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \
204     ($(LDCONFIG) || true)  >/dev/null 2>&1; \
107205   fi
108   cp zlib.3 $(man3dir)
109   chmod 644 $(man3dir)/zlib.3
206   cp zlib.3 $(DESTDIR)$(man3dir)
207   chmod 644 $(DESTDIR)$(man3dir)/zlib.3
208   cp zlib.pc $(DESTDIR)$(pkgconfigdir)
209   chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc
110210# The ranlib in install is needed on NeXTSTEP which checks file times
111211# ldconfig is for Linux
112212
213install: install-libs
214   -@if [ ! -d $(DESTDIR)$(includedir)   ]; then mkdir -p $(DESTDIR)$(includedir); fi
215   cp zlib.h zconf.h $(DESTDIR)$(includedir)
216   chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
217
113218uninstall:
114   cd $(includedir); \
115   cd $(libdir); rm -f libz.a; \
116   if test -f $(SHAREDLIBV); then \
219   cd $(DESTDIR)$(includedir); rm -f zlib.h zconf.h
220   cd $(DESTDIR)$(libdir); rm -f libz.a; \
221   if test -n "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \
117222     rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
118223   fi
119   cd $(man3dir); rm -f zlib.3
224   cd $(DESTDIR)$(man3dir); rm -f zlib.3
225   cd $(DESTDIR)$(pkgconfigdir); rm -f zlib.pc
120226
227docs: zlib.3.pdf
228
229zlib.3.pdf: zlib.3
230   groff -mandoc -f H -T ps zlib.3 | ps2pdf - zlib.3.pdf
231
232zconf.h.cmakein: zconf.h.in
233   -@ TEMPFILE=`mktemp __XXXXXX`; \
234   echo "/#define ZCONF_H/ a\\\\\n#cmakedefine Z_PREFIX\\\\\n#cmakedefine Z_HAVE_UNISTD_H\n" >> $$TEMPFILE &&\
235   sed -f $$TEMPFILE zconf.h.in > zconf.h.cmakein &&\
236   touch -r zconf.h.in zconf.h.cmakein &&\
237   rm $$TEMPFILE
238
239zconf: zconf.h.in
240   cp -p zconf.h.in zconf.h
241
121242mostlyclean: clean
122243clean:
123   rm -f *.o *~ example$(EXE) minigzip$(EXE) \
244   rm -f *.o *.lo *~ \
245      example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \
246      example64$(EXE) minigzip64$(EXE) \
247      infcover \
124248      libz.* foo.gz so_locations \
125249      _match.s maketree contrib/infback9/*.o
250   rm -rf objs
251   rm -f *.gcda *.gcno *.gcov
252   rm -f contrib/infback9/*.gcda contrib/infback9/*.gcno contrib/infback9/*.gcov
126253
127254maintainer-clean: distclean
128distclean: clean
129   cp -p Makefile.in Makefile
130   cp -p zconf.in.h zconf.h
131   rm -f .DS_Store
255distclean: clean zconf zconf.h.cmakein docs
256   rm -f Makefile zlib.pc configure.log
257   -@rm -f .DS_Store
258   -@printf 'all:\n\t-@echo "Please use ./configure first.  Thank you."\n' > Makefile
259   -@printf '\ndistclean:\n\tmake -f Makefile.in distclean\n' >> Makefile
260   -@touch -r Makefile.in Makefile
132261
133262tags:
134263   etags *.[ch]
r15677r15678
138267
139268# DO NOT DELETE THIS LINE -- make depend depends on it.
140269
141adler32.o: zlib.h zconf.h
142compress.o: zlib.h zconf.h
143crc32.o: crc32.h zlib.h zconf.h
270adler32.o zutil.o: zutil.h zlib.h zconf.h
271gzclose.o gzlib.o gzread.o gzwrite.o: zlib.h zconf.h gzguts.h
272compress.o example.o minigzip.o uncompr.o: zlib.h zconf.h
273crc32.o: zutil.h zlib.h zconf.h crc32.h
144274deflate.o: deflate.h zutil.h zlib.h zconf.h
145example.o: zlib.h zconf.h
146gzio.o: zutil.h zlib.h zconf.h
275infback.o inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffixed.h
147276inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
148inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
149infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
150277inftrees.o: zutil.h zlib.h zconf.h inftrees.h
151minigzip.o: zlib.h zconf.h
152278trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
153uncompr.o: zlib.h zconf.h
154zutil.o: zutil.h zlib.h zconf.h
279
280adler32.lo zutil.lo: zutil.h zlib.h zconf.h
281gzclose.lo gzlib.lo gzread.lo gzwrite.lo: zlib.h zconf.h gzguts.h
282compress.lo example.lo minigzip.lo uncompr.lo: zlib.h zconf.h
283crc32.lo: zutil.h zlib.h zconf.h crc32.h
284deflate.lo: deflate.h zutil.h zlib.h zconf.h
285infback.lo inflate.lo: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffixed.h
286inffast.lo: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
287inftrees.lo: zutil.h zlib.h zconf.h inftrees.h
288trees.lo: deflate.h zutil.h zlib.h zconf.h trees.h
src/lib/zlib/deflate.c
r15677r15678
11/* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
2 * Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
3737 *  REFERENCES
3838 *
3939 *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 *      Available in http://www.ietf.org/rfc/rfc1951.txt
40 *      Available in http://tools.ietf.org/html/rfc1951
4141 *
4242 *      A description of the Rabin and Karp algorithm is given in the book
4343 *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
r15677r15678
5252#include "deflate.h"
5353
5454const char deflate_copyright[] =
55   " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
55   " deflate 1.2.7 Copyright 1995-2012 Jean-loup Gailly and Mark Adler ";
5656/*
5757  If you use the zlib library in a product, an acknowledgment is welcome
5858  in the documentation of your product. If for some reason you cannot
r15677r15678
7979#ifndef FASTEST
8080local block_state deflate_slow   OF((deflate_state *s, int flush));
8181#endif
82local block_state deflate_rle    OF((deflate_state *s, int flush));
83local block_state deflate_huff   OF((deflate_state *s, int flush));
8284local void lm_init        OF((deflate_state *s));
8385local void putShortMSB    OF((deflate_state *s, uInt b));
8486local void flush_pending  OF((z_streamp strm));
8587local int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
86#ifndef FASTEST
8788#ifdef ASMV
8889      void match_init OF((void)); /* asm code initialization */
8990      uInt longest_match  OF((deflate_state *s, IPos cur_match));
9091#else
9192local uInt longest_match  OF((deflate_state *s, IPos cur_match));
9293#endif
93#endif
94local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
9594
9695#ifdef DEBUG
9796local  void check_match OF((deflate_state *s, IPos start, IPos match,
r15677r15678
110109#endif
111110/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
112111
113#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
114/* Minimum amount of lookahead, except at the end of the input file.
115 * See deflate.c for comments about the MIN_MATCH+1.
116 */
117
118112/* Values for max_lazy_match, good_match and max_chain_length, depending on
119113 * the desired pack level (0..9). The values given below have been tuned to
120114 * exclude worst case performance for pathological files. Better values may be
r15677r15678
161155struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
162156#endif
163157
158/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
159#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0))
160
164161/* ===========================================================================
165162 * Update a hash value with the given input byte
166163 * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
r15677r15678
241238
242239    strm->msg = Z_NULL;
243240    if (strm->zalloc == (alloc_func)0) {
241#ifdef Z_SOLO
242        return Z_STREAM_ERROR;
243#else
244244        strm->zalloc = zcalloc;
245245        strm->opaque = (voidpf)0;
246#endif
246247    }
247    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
248    if (strm->zfree == (free_func)0)
249#ifdef Z_SOLO
250        return Z_STREAM_ERROR;
251#else
252        strm->zfree = zcfree;
253#endif
248254
249255#ifdef FASTEST
250256    if (level != 0) level = 1;
r15677r15678
288294    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
289295    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
290296
297    s->high_water = 0;      /* nothing written to s->window yet */
298
291299    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
292300
293301    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
r15677r15678
318326    uInt  dictLength;
319327{
320328    deflate_state *s;
321    uInt length = dictLength;
322    uInt n;
323    IPos hash_head = 0;
329    uInt str, n;
330    int wrap;
331    unsigned avail;
332    unsigned char *next;
324333
325    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
326        strm->state->wrap == 2 ||
327        (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
334    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL)
328335        return Z_STREAM_ERROR;
336    s = strm->state;
337    wrap = s->wrap;
338    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
339        return Z_STREAM_ERROR;
329340
330    s = strm->state;
331    if (s->wrap)
341    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
342    if (wrap == 1)
332343        strm->adler = adler32(strm->adler, dictionary, dictLength);
344    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
333345
334    if (length < MIN_MATCH) return Z_OK;
335    if (length > MAX_DIST(s)) {
336        length = MAX_DIST(s);
337        dictionary += dictLength - length; /* use the tail of the dictionary */
346    /* if dictionary would fill window, just replace the history */
347    if (dictLength >= s->w_size) {
348        if (wrap == 0) {            /* already empty otherwise */
349            CLEAR_HASH(s);
350            s->strstart = 0;
351            s->block_start = 0L;
352            s->insert = 0;
353        }
354        dictionary += dictLength - s->w_size;  /* use the tail */
355        dictLength = s->w_size;
338356    }
339    zmemcpy(s->window, dictionary, length);
340    s->strstart = length;
341    s->block_start = (long)length;
342357
343    /* Insert all strings in the hash table (except for the last two bytes).
344     * s->lookahead stays null, so s->ins_h will be recomputed at the next
345     * call of fill_window.
346     */
347    s->ins_h = s->window[0];
348    UPDATE_HASH(s, s->ins_h, s->window[1]);
349    for (n = 0; n <= length - MIN_MATCH; n++) {
350        INSERT_STRING(s, n, hash_head);
358    /* insert dictionary into window and hash */
359    avail = strm->avail_in;
360    next = strm->next_in;
361    strm->avail_in = dictLength;
362    strm->next_in = (Bytef *)dictionary;
363    fill_window(s);
364    while (s->lookahead >= MIN_MATCH) {
365        str = s->strstart;
366        n = s->lookahead - (MIN_MATCH-1);
367        do {
368            UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
369#ifndef FASTEST
370            s->prev[str & s->w_mask] = s->head[s->ins_h];
371#endif
372            s->head[s->ins_h] = (Pos)str;
373            str++;
374        } while (--n);
375        s->strstart = str;
376        s->lookahead = MIN_MATCH-1;
377        fill_window(s);
351378    }
352    if (hash_head) hash_head = 0;  /* to make compiler happy */
379    s->strstart += s->lookahead;
380    s->block_start = (long)s->strstart;
381    s->insert = s->lookahead;
382    s->lookahead = 0;
383    s->match_length = s->prev_length = MIN_MATCH-1;
384    s->match_available = 0;
385    strm->next_in = next;
386    strm->avail_in = avail;
387    s->wrap = wrap;
353388    return Z_OK;
354389}
355390
356391/* ========================================================================= */
357int ZEXPORT deflateReset (strm)
392int ZEXPORT deflateResetKeep (strm)
358393    z_streamp strm;
359394{
360395    deflate_state *s;
r15677r15678
384419    s->last_flush = Z_NO_FLUSH;
385420
386421    _tr_init(s);
387    lm_init(s);
388422
389423    return Z_OK;
390424}
391425
392426/* ========================================================================= */
427int ZEXPORT deflateReset (strm)
428    z_streamp strm;
429{
430    int ret;
431
432    ret = deflateResetKeep(strm);
433    if (ret == Z_OK)
434        lm_init(strm->state);
435    return ret;
436}
437
438/* ========================================================================= */
393439int ZEXPORT deflateSetHeader (strm, head)
394440    z_streamp strm;
395441    gz_headerp head;
r15677r15678
401447}
402448
403449/* ========================================================================= */
450int ZEXPORT deflatePending (strm, pending, bits)
451    unsigned *pending;
452    int *bits;
453    z_streamp strm;
454{
455    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
456    if (pending != Z_NULL)
457        *pending = strm->state->pending;
458    if (bits != Z_NULL)
459        *bits = strm->state->bi_valid;
460    return Z_OK;
461}
462
463/* ========================================================================= */
404464int ZEXPORT deflatePrime (strm, bits, value)
405465    z_streamp strm;
406466    int bits;
407467    int value;
408468{
469    deflate_state *s;
470    int put;
471
409472    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
410    strm->state->bi_valid = bits;
411    strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
473    s = strm->state;
474    if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
475        return Z_BUF_ERROR;
476    do {
477        put = Buf_size - s->bi_valid;
478        if (put > bits)
479            put = bits;
480        s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
481        s->bi_valid += put;
482        _tr_flush_bits(s);
483        value >>= put;
484        bits -= put;
485    } while (bits);
412486    return Z_OK;
413487}
414488
r15677r15678
435509    }
436510    func = configuration_table[s->level].func;
437511
438    if (func != configuration_table[level].func && strm->total_in != 0) {
512    if ((strategy != s->strategy || func != configuration_table[level].func) &&
513        strm->total_in != 0) {
439514        /* Flush the last buffer: */
440        err = deflate(strm, Z_PARTIAL_FLUSH);
515        err = deflate(strm, Z_BLOCK);
441516    }
442517    if (s->level != level) {
443518        s->level = level;
r15677r15678
481556 * resulting from using fixed blocks instead of stored blocks, which deflate
482557 * can emit on compressed data for some combinations of the parameters.
483558 *
484 * This function could be more sophisticated to provide closer upper bounds
485 * for every combination of windowBits and memLevel, as well as wrap.
486 * But even the conservative upper bound of about 14% expansion does not
487 * seem onerous for output buffer allocation.
559 * This function could be more sophisticated to provide closer upper bounds for
560 * every combination of windowBits and memLevel.  But even the conservative
561 * upper bound of about 14% expansion does not seem onerous for output buffer
562 * allocation.
488563 */
489564uLong ZEXPORT deflateBound(strm, sourceLen)
490565    z_streamp strm;
491566    uLong sourceLen;
492567{
493568    deflate_state *s;
494    uLong destLen;
569    uLong complen, wraplen;
570    Bytef *str;
495571
496    /* conservative upper bound */
497    destLen = sourceLen +
498              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
572    /* conservative upper bound for compressed data */
573    complen = sourceLen +
574              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
499575
500    /* if can't get parameters, return conservative bound */
576    /* if can't get parameters, return conservative bound plus zlib wrapper */
501577    if (strm == Z_NULL || strm->state == Z_NULL)
502        return destLen;
578        return complen + 6;
503579
580    /* compute wrapper length */
581    s = strm->state;
582    switch (s->wrap) {
583    case 0:                                 /* raw deflate */
584        wraplen = 0;
585        break;
586    case 1:                                 /* zlib wrapper */
587        wraplen = 6 + (s->strstart ? 4 : 0);
588        break;
589    case 2:                                 /* gzip wrapper */
590        wraplen = 18;
591        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
592            if (s->gzhead->extra != Z_NULL)
593                wraplen += 2 + s->gzhead->extra_len;
594            str = s->gzhead->name;
595            if (str != Z_NULL)
596                do {
597                    wraplen++;
598                } while (*str++);
599            str = s->gzhead->comment;
600            if (str != Z_NULL)
601                do {
602                    wraplen++;
603                } while (*str++);
604            if (s->gzhead->hcrc)
605                wraplen += 2;
606        }
607        break;
608    default:                                /* for compiler happiness */
609        wraplen = 6;
610    }
611
504612    /* if not default parameters, return conservative bound */
505    s = strm->state;
506613    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
507        return destLen;
614        return complen + wraplen;
508615
509616    /* default settings: return tight bound for that case */
510    return compressBound(sourceLen);
617    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
618           (sourceLen >> 25) + 13 - 6 + wraplen;
511619}
512620
513621/* =========================================================================
r15677r15678
532640local void flush_pending(strm)
533641    z_streamp strm;
534642{
535    unsigned len = strm->state->pending;
643    unsigned len;
644    deflate_state *s = strm->state;
536645
646    _tr_flush_bits(s);
647    len = s->pending;
537648    if (len > strm->avail_out) len = strm->avail_out;
538649    if (len == 0) return;
539650
540    zmemcpy(strm->next_out, strm->state->pending_out, len);
651    zmemcpy(strm->next_out, s->pending_out, len);
541652    strm->next_out  += len;
542    strm->state->pending_out  += len;
653    s->pending_out  += len;
543654    strm->total_out += len;
544655    strm->avail_out  -= len;
545    strm->state->pending -= len;
546    if (strm->state->pending == 0) {
547        strm->state->pending_out = strm->state->pending_buf;
656    s->pending -= len;
657    if (s->pending == 0) {
658        s->pending_out = s->pending_buf;
548659    }
549660}
550661
r15677r15678
557668    deflate_state *s;
558669
559670    if (strm == Z_NULL || strm->state == Z_NULL ||
560        flush > Z_FINISH || flush < 0) {
671        flush > Z_BLOCK || flush < 0) {
561672        return Z_STREAM_ERROR;
562673    }
563674    s = strm->state;
r15677r15678
581692            put_byte(s, 31);
582693            put_byte(s, 139);
583694            put_byte(s, 8);
584            if (s->gzhead == NULL) {
695            if (s->gzhead == Z_NULL) {
585696                put_byte(s, 0);
586697                put_byte(s, 0);
587698                put_byte(s, 0);
r15677r15678
608719                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
609720                             4 : 0));
610721                put_byte(s, s->gzhead->os & 0xff);
611                if (s->gzhead->extra != NULL) {
722                if (s->gzhead->extra != Z_NULL) {
612723                    put_byte(s, s->gzhead->extra_len & 0xff);
613724                    put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
614725                }
r15677r15678
650761    }
651762#ifdef GZIP
652763    if (s->status == EXTRA_STATE) {
653        if (s->gzhead->extra != NULL) {
764        if (s->gzhead->extra != Z_NULL) {
654765            uInt beg = s->pending;  /* start of bytes to update crc */
655766
656767            while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
r15677r15678
678789            s->status = NAME_STATE;
679790    }
680791    if (s->status == NAME_STATE) {
681        if (s->gzhead->name != NULL) {
792        if (s->gzhead->name != Z_NULL) {
682793            uInt beg = s->pending;  /* start of bytes to update crc */
683794            int val;
684795
r15677r15678
709820            s->status = COMMENT_STATE;
710821    }
711822    if (s->status == COMMENT_STATE) {
712        if (s->gzhead->comment != NULL) {
823        if (s->gzhead->comment != Z_NULL) {
713824            uInt beg = s->pending;  /* start of bytes to update crc */
714825            int val;
715826
r15677r15678
771882     * flushes. For repeated and useless calls with Z_FINISH, we keep
772883     * returning Z_STREAM_END instead of Z_BUF_ERROR.
773884     */
774    } else if (strm->avail_in == 0 && flush <= old_flush &&
885    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
775886               flush != Z_FINISH) {
776887        ERR_RETURN(strm, Z_BUF_ERROR);
777888    }
r15677r15678
787898        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
788899        block_state bstate;
789900
790        bstate = (*(configuration_table[s->level].func))(s, flush);
901        bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
902                    (s->strategy == Z_RLE ? deflate_rle(s, flush) :
903                        (*(configuration_table[s->level].func))(s, flush));
791904
792905        if (bstate == finish_started || bstate == finish_done) {
793906            s->status = FINISH_STATE;
r15677r15678
808921        if (bstate == block_done) {
809922            if (flush == Z_PARTIAL_FLUSH) {
810923                _tr_align(s);
811            } else { /* FULL_FLUSH or SYNC_FLUSH */
924            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
812925                _tr_stored_block(s, (char*)0, 0L, 0);
813926                /* For a full flush, this empty block will be recognized
814927                 * as a special marker by inflate_sync().
815928                 */
816929                if (flush == Z_FULL_FLUSH) {
817930                    CLEAR_HASH(s);             /* forget history */
931                    if (s->lookahead == 0) {
932                        s->strstart = 0;
933                        s->block_start = 0L;
934                        s->insert = 0;
935                    }
818936                }
819937            }
820938            flush_pending(strm);
r15677r15678
9091027
9101028    ss = source->state;
9111029
912    zmemcpy(dest, source, sizeof(z_stream));
1030    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
9131031
9141032    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
9151033    if (ds == Z_NULL) return Z_MEM_ERROR;
9161034    dest->state = (struct internal_state FAR *) ds;
917    zmemcpy(ds, ss, sizeof(deflate_state));
1035    zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
9181036    ds->strm = dest;
9191037
9201038    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
r15677r15678
9301048    }
9311049    /* following zmemcpy do not work for 16-bit MSDOS */
9321050    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
933    zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
934    zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
1051    zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1052    zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
9351053    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
9361054
9371055    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
r15677r15678
9651083
9661084    strm->avail_in  -= len;
9671085
1086    zmemcpy(buf, strm->next_in, len);
9681087    if (strm->state->wrap == 1) {
969        strm->adler = adler32(strm->adler, strm->next_in, len);
1088        strm->adler = adler32(strm->adler, buf, len);
9701089    }
9711090#ifdef GZIP
9721091    else if (strm->state->wrap == 2) {
973        strm->adler = crc32(strm->adler, strm->next_in, len);
1092        strm->adler = crc32(strm->adler, buf, len);
9741093    }
9751094#endif
976    zmemcpy(buf, strm->next_in, len);
9771095    strm->next_in  += len;
9781096    strm->total_in += len;
9791097
r15677r15678
10001118    s->strstart = 0;
10011119    s->block_start = 0L;
10021120    s->lookahead = 0;
1121    s->insert = 0;
10031122    s->match_length = s->prev_length = MIN_MATCH-1;
10041123    s->match_available = 0;
10051124    s->ins_h = 0;
r15677r15678
11671286    return s->lookahead;
11681287}
11691288#endif /* ASMV */
1170#endif /* FASTEST */
11711289
1290#else /* FASTEST */
1291
11721292/* ---------------------------------------------------------------------------
1173 * Optimized version for level == 1 or strategy == Z_RLE only
1293 * Optimized version for FASTEST only
11741294 */
1175local uInt longest_match_fast(s, cur_match)
1295local uInt longest_match(s, cur_match)
11761296    deflate_state *s;
11771297    IPos cur_match;                             /* current match */
11781298{
r15677r15678
12251345    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
12261346}
12271347
1348#endif /* FASTEST */
1349
12281350#ifdef DEBUG
12291351/* ===========================================================================
12301352 * Check that the match at match_start is indeed a match.
r15677r15678
12711393    unsigned more;    /* Amount of free space at the end of the window. */
12721394    uInt wsize = s->w_size;
12731395
1396    Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1397
12741398    do {
12751399        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
12761400
r15677r15678
13031427               later. (Using level 0 permanently is not an optimal usage of
13041428               zlib, so we don't care about this pathological case.)
13051429             */
1306            /* %%% avoid this when Z_RLE */
13071430            n = s->hash_size;
13081431            p = &s->head[n];
13091432            do {
r15677r15678
13241447#endif
13251448            more += wsize;
13261449        }
1327        if (s->strm->avail_in == 0) return;
1450        if (s->strm->avail_in == 0) break;
13281451
13291452        /* If there was no sliding:
13301453         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
r15677r15678
13431466        s->lookahead += n;
13441467
13451468        /* Initialize the hash value now that we have some input: */
1346        if (s->lookahead >= MIN_MATCH) {
1347            s->ins_h = s->window[s->strstart];
1348            UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1469        if (s->lookahead + s->insert >= MIN_MATCH) {
1470            uInt str = s->strstart - s->insert;
1471            s->ins_h = s->window[str];
1472            UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
13491473#if MIN_MATCH != 3
13501474            Call UPDATE_HASH() MIN_MATCH-3 more times
13511475#endif
1476            while (s->insert) {
1477                UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1478#ifndef FASTEST
1479                s->prev[str & s->w_mask] = s->head[s->ins_h];
1480#endif
1481                s->head[s->ins_h] = (Pos)str;
1482                str++;
1483                s->insert--;
1484                if (s->lookahead + s->insert < MIN_MATCH)
1485                    break;
1486            }
13521487        }
13531488        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
13541489         * but this is not important since only literal bytes will be emitted.
13551490         */
13561491
13571492    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1493
1494    /* If the WIN_INIT bytes after the end of the current data have never been
1495     * written, then zero those bytes in order to avoid memory check reports of
1496     * the use of uninitialized (or uninitialised as Julian writes) bytes by
1497     * the longest match routines.  Update the high water mark for the next
1498     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1499     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1500     */
1501    if (s->high_water < s->window_size) {
1502        ulg curr = s->strstart + (ulg)(s->lookahead);
1503        ulg init;
1504
1505        if (s->high_water < curr) {
1506            /* Previous high water mark below current data -- zero WIN_INIT
1507             * bytes or up to end of window, whichever is less.
1508             */
1509            init = s->window_size - curr;
1510            if (init > WIN_INIT)
1511                init = WIN_INIT;
1512            zmemzero(s->window + curr, (unsigned)init);
1513            s->high_water = curr + init;
1514        }
1515        else if (s->high_water < (ulg)curr + WIN_INIT) {
1516            /* High water mark at or above current data, but below current data
1517             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1518             * to end of window, whichever is less.
1519             */
1520            init = (ulg)curr + WIN_INIT - s->high_water;
1521            if (init > s->window_size - s->high_water)
1522                init = s->window_size - s->high_water;
1523            zmemzero(s->window + s->high_water, (unsigned)init);
1524            s->high_water += init;
1525        }
1526    }
1527
1528    Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1529           "not enough room for search");
13581530}
13591531
13601532/* ===========================================================================
13611533 * Flush the current block, with given end-of-file flag.
13621534 * IN assertion: strstart is set to the end of the current match.
13631535 */
1364#define FLUSH_BLOCK_ONLY(s, eof) { \
1536#define FLUSH_BLOCK_ONLY(s, last) { \
13651537   _tr_flush_block(s, (s->block_start >= 0L ? \
13661538                   (charf *)&s->window[(unsigned)s->block_start] : \
13671539                   (charf *)Z_NULL), \
13681540                (ulg)((long)s->strstart - s->block_start), \
1369                (eof)); \
1541                (last)); \
13701542   s->block_start = s->strstart; \
13711543   flush_pending(s->strm); \
13721544   Tracev((stderr,"[FLUSH]")); \
13731545}
13741546
13751547/* Same but force premature exit if necessary. */
1376#define FLUSH_BLOCK(s, eof) { \
1377   FLUSH_BLOCK_ONLY(s, eof); \
1378   if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1548#define FLUSH_BLOCK(s, last) { \
1549   FLUSH_BLOCK_ONLY(s, last); \
1550   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
13791551}
13801552
13811553/* ===========================================================================
r15677r15678
14341606            FLUSH_BLOCK(s, 0);
14351607        }
14361608    }
1437    FLUSH_BLOCK(s, flush == Z_FINISH);
1438    return flush == Z_FINISH ? finish_done : block_done;
1609    s->insert = 0;
1610    if (flush == Z_FINISH) {
1611        FLUSH_BLOCK(s, 1);
1612        return finish_done;
1613    }
1614    if ((long)s->strstart > s->block_start)
1615        FLUSH_BLOCK(s, 0);
1616    return block_done;
14391617}
14401618
14411619/* ===========================================================================
r15677r15678
14491627    deflate_state *s;
14501628    int flush;
14511629{
1452    IPos hash_head = NIL; /* head of the hash chain */
1630    IPos hash_head;     /* head of the hash chain */
14531631    int bflush;           /* set if current block must be flushed */
14541632
14551633    for (;;) {
r15677r15678
14691647        /* Insert the string window[strstart .. strstart+2] in the
14701648         * dictionary, and set hash_head to the head of the hash chain:
14711649         */
1650        hash_head = NIL;
14721651        if (s->lookahead >= MIN_MATCH) {
14731652            INSERT_STRING(s, s->strstart, hash_head);
14741653        }
r15677r15678
14811660             * of window index 0 (in particular we have to avoid a match
14821661             * of the string with itself at the start of the input file).
14831662             */
1484#ifdef FASTEST
1485            if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
1486                (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
1487                s->match_length = longest_match_fast (s, hash_head);
1488            }
1489#else
1490            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1491                s->match_length = longest_match (s, hash_head);
1492            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1493                s->match_length = longest_match_fast (s, hash_head);
1494            }
1495#endif
1496            /* longest_match() or longest_match_fast() sets match_start */
1663            s->match_length = longest_match (s, hash_head);
1664            /* longest_match() sets match_start */
14971665        }
14981666        if (s->match_length >= MIN_MATCH) {
14991667            check_match(s, s->strstart, s->match_start, s->match_length);
r15677r15678
15411709        }
15421710        if (bflush) FLUSH_BLOCK(s, 0);
15431711    }
1544    FLUSH_BLOCK(s, flush == Z_FINISH);
1545    return flush == Z_FINISH ? finish_done : block_done;
1712    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1713    if (flush == Z_FINISH) {
1714        FLUSH_BLOCK(s, 1);
1715        return finish_done;
1716    }
1717    if (s->last_lit)
1718        FLUSH_BLOCK(s, 0);
1719    return block_done;
15461720}
15471721
15481722#ifndef FASTEST
r15677r15678
15551729    deflate_state *s;
15561730    int flush;
15571731{
1558    IPos hash_head = NIL;    /* head of hash chain */
1732    IPos hash_head;         /* head of hash chain */
15591733    int bflush;              /* set if current block must be flushed */
15601734
15611735    /* Process the input block. */
r15677r15678
15761750        /* Insert the string window[strstart .. strstart+2] in the
15771751         * dictionary, and set hash_head to the head of the hash chain:
15781752         */
1753        hash_head = NIL;
15791754        if (s->lookahead >= MIN_MATCH) {
15801755            INSERT_STRING(s, s->strstart, hash_head);
15811756        }
r15677r15678
15911766             * of window index 0 (in particular we have to avoid a match
15921767             * of the string with itself at the start of the input file).
15931768             */
1594            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1595                s->match_length = longest_match (s, hash_head);
1596            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1597                s->match_length = longest_match_fast (s, hash_head);
1598            }
1599            /* longest_match() or longest_match_fast() sets match_start */
1769            s->match_length = longest_match (s, hash_head);
1770            /* longest_match() sets match_start */
16001771
16011772            if (s->match_length <= 5 && (s->strategy == Z_FILTERED
16021773#if TOO_FAR <= 32767
r15677r15678
16691840        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
16701841        s->match_available = 0;
16711842    }
1672    FLUSH_BLOCK(s, flush == Z_FINISH);
1673    return flush == Z_FINISH ? finish_done : block_done;
1843    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1844    if (flush == Z_FINISH) {
1845        FLUSH_BLOCK(s, 1);
1846        return finish_done;
1847    }
1848    if (s->last_lit)
1849        FLUSH_BLOCK(s, 0);
1850    return block_done;
16741851}
16751852#endif /* FASTEST */
16761853
1677#if 0
16781854/* ===========================================================================
16791855 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
16801856 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
r15677r15678
16841860    deflate_state *s;
16851861    int flush;
16861862{
1687    int bflush;         /* set if current block must be flushed */
1688    uInt run;           /* length of run */
1689    uInt max;           /* maximum length of run */
1690    uInt prev;          /* byte at distance one to match */
1691    Bytef *scan;        /* scan for end of run */
1863    int bflush;             /* set if current block must be flushed */
1864    uInt prev;              /* byte at distance one to match */
1865    Bytef *scan, *strend;   /* scan goes up to strend for length of run */
16921866
16931867    for (;;) {
16941868        /* Make sure that we always have enough lookahead, except
16951869         * at the end of the input file. We need MAX_MATCH bytes
1696         * for the longest encodable run.
1870         * for the longest run, plus one for the unrolled loop.
16971871         */
1698        if (s->lookahead < MAX_MATCH) {
1872        if (s->lookahead <= MAX_MATCH) {
16991873            fill_window(s);
1700            if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
1874            if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
17011875                return need_more;
17021876            }
17031877            if (s->lookahead == 0) break; /* flush the current block */
17041878        }
17051879
17061880        /* See how many times the previous byte repeats */
1707        run = 0;
1708        if (s->strstart > 0) {      /* if there is a previous byte, that is */
1709            max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
1881        s->match_length = 0;
1882        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
17101883            scan = s->window + s->strstart - 1;
1711            prev = *scan++;
1712            do {
1713                if (*scan++ != prev)
1714                    break;
1715            } while (++run < max);
1884            prev = *scan;
1885            if (prev == *++scan && prev == *++scan && prev == *++scan) {
1886                strend = s->window + s->strstart + MAX_MATCH;
1887                do {
1888                } while (prev == *++scan && prev == *++scan &&
1889                         prev == *++scan && prev == *++scan &&
1890                         prev == *++scan && prev == *++scan &&
1891                         prev == *++scan && prev == *++scan &&
1892                         scan < strend);
1893                s->match_length = MAX_MATCH - (int)(strend - scan);
1894                if (s->match_length > s->lookahead)
1895                    s->match_length = s->lookahead;
1896            }
1897            Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
17161898        }
17171899
17181900        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1719        if (run >= MIN_MATCH) {
1720            check_match(s, s->strstart, s->strstart - 1, run);
1721            _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
1722            s->lookahead -= run;
1723            s->strstart += run;
1901        if (s->match_length >= MIN_MATCH) {
1902            check_match(s, s->strstart, s->strstart - 1, s->match_length);
1903
1904            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
1905
1906            s->lookahead -= s->match_length;
1907            s->strstart += s->match_length;
1908            s->match_length = 0;
17241909        } else {
17251910            /* No match, output a literal byte */
17261911            Tracevv((stderr,"%c", s->window[s->strstart]));
r15677r15678
17301915        }
17311916        if (bflush) FLUSH_BLOCK(s, 0);
17321917    }
1733    FLUSH_BLOCK(s, flush == Z_FINISH);
1734    return flush == Z_FINISH ? finish_done : block_done;
1918    s->insert = 0;
1919    if (flush == Z_FINISH) {
1920        FLUSH_BLOCK(s, 1);
1921        return finish_done;
1922    }
1923    if (s->last_lit)
1924        FLUSH_BLOCK(s, 0);
1925    return block_done;
17351926}
1736#endif
1927
1928/* ===========================================================================
1929 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
1930 * (It will be regenerated if this run of deflate switches away from Huffman.)
1931 */
1932local block_state deflate_huff(s, flush)
1933    deflate_state *s;
1934    int flush;
1935{
1936    int bflush;             /* set if current block must be flushed */
1937
1938    for (;;) {
1939        /* Make sure that we have a literal to write. */
1940        if (s->lookahead == 0) {
1941            fill_window(s);
1942            if (s->lookahead == 0) {
1943                if (flush == Z_NO_FLUSH)
1944                    return need_more;
1945                break;      /* flush the current block */
1946            }
1947        }
1948
1949        /* Output a literal byte */
1950        s->match_length = 0;
1951        Tracevv((stderr,"%c", s->window[s->strstart]));
1952        _tr_tally_lit (s, s->window[s->strstart], bflush);
1953        s->lookahead--;
1954        s->strstart++;
1955        if (bflush) FLUSH_BLOCK(s, 0);
1956    }
1957    s->insert = 0;
1958    if (flush == Z_FINISH) {
1959        FLUSH_BLOCK(s, 1);
1960        return finish_done;
1961    }
1962    if (s->last_lit)
1963        FLUSH_BLOCK(s, 0);
1964    return block_done;
1965}
src/lib/zlib/zutil.c
r15677r15678
11/* zutil.c -- target dependent utility functions for the compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
2 * Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly.
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
66/* @(#) $Id$ */
77
88#include "zutil.h"
9#ifndef Z_SOLO
10#  include "gzguts.h"
11#endif
912
1013#ifndef NO_DUMMY_DECL
1114struct internal_state      {int dummy;}; /* for buggy compilers */
r15677r15678
3437    uLong flags;
3538
3639    flags = 0;
37    switch (sizeof(uInt)) {
40    switch ((int)(sizeof(uInt))) {
3841    case 2:     break;
3942    case 4:     flags += 1;     break;
4043    case 8:     flags += 2;     break;
4144    default:    flags += 3;
4245    }
43    switch (sizeof(uLong)) {
46    switch ((int)(sizeof(uLong))) {
4447    case 2:     break;
4548    case 4:     flags += 1 << 2;        break;
4649    case 8:     flags += 2 << 2;        break;
4750    default:    flags += 3 << 2;
4851    }
49    switch (sizeof(voidpf)) {
52    switch ((int)(sizeof(voidpf))) {
5053    case 2:     break;
5154    case 4:     flags += 1 << 4;        break;
5255    case 8:     flags += 2 << 4;        break;
5356    default:    flags += 3 << 4;
5457    }
55    switch (sizeof(z_off_t)) {
58    switch ((int)(sizeof(z_off_t))) {
5659    case 2:     break;
5760    case 4:     flags += 1 << 6;        break;
5861    case 8:     flags += 2 << 6;        break;
r15677r15678
8588#ifdef FASTEST
8689    flags += 1L << 21;
8790#endif
88#ifdef STDC
91#if defined(STDC) || defined(Z_HAVE_STDARG_H)
8992#  ifdef NO_vsnprintf
90        flags += 1L << 25;
93    flags += 1L << 25;
9194#    ifdef HAS_vsprintf_void
92        flags += 1L << 26;
95    flags += 1L << 26;
9396#    endif
9497#  else
9598#    ifdef HAS_vsnprintf_void
96        flags += 1L << 26;
99    flags += 1L << 26;
97100#    endif
98101#  endif
99102#else
100        flags += 1L << 24;
103    flags += 1L << 24;
101104#  ifdef NO_snprintf
102        flags += 1L << 25;
105    flags += 1L << 25;
103106#    ifdef HAS_sprintf_void
104        flags += 1L << 26;
107    flags += 1L << 26;
105108#    endif
106109#  else
107110#    ifdef HAS_snprintf_void
108        flags += 1L << 26;
111    flags += 1L << 26;
109112#    endif
110113#  endif
111114#endif
r15677r15678
117120#  ifndef verbose
118121#    define verbose 0
119122#  endif
120int z_verbose = verbose;
123int ZLIB_INTERNAL z_verbose = verbose;
121124
122void z_error (m)
125void ZLIB_INTERNAL z_error (m)
123126    char *m;
124127{
125128    fprintf(stderr, "%s\n", m);
r15677r15678
146149
147150#ifndef HAVE_MEMCPY
148151
149void zmemcpy(dest, source, len)
152void ZLIB_INTERNAL zmemcpy(dest, source, len)
150153    Bytef* dest;
151154    const Bytef* source;
152155    uInt  len;
r15677r15678
157160    } while (--len != 0);
158161}
159162
160int zmemcmp(s1, s2, len)
163int ZLIB_INTERNAL zmemcmp(s1, s2, len)
161164    const Bytef* s1;
162165    const Bytef* s2;
163166    uInt  len;
r15677r15678
170173    return 0;
171174}
172175
173void zmemzero(dest, len)
176void ZLIB_INTERNAL zmemzero(dest, len)
174177    Bytef* dest;
175178    uInt  len;
176179{
r15677r15678
181184}
182185#endif
183186
187#ifndef Z_SOLO
184188
185189#ifdef SYS16BIT
186190
r15677r15678
213217 * a protected system like OS/2. Use Microsoft C instead.
214218 */
215219
216voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
220voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)
217221{
218222    voidpf buf = opaque; /* just to make some compilers happy */
219223    ulg bsize = (ulg)items*size;
r15677r15678
237241    return buf;
238242}
239243
240void zcfree (voidpf opaque, voidpf ptr)
244void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
241245{
242246    int n;
243247    if (*(ush*)&ptr != 0) { /* object < 64K */
r15677r15678
272276#  define _hfree   hfree
273277#endif
274278
275voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
279voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)
276280{
277281    if (opaque) opaque = 0; /* to make compiler happy */
278282    return _halloc((long)items, size);
279283}
280284
281void zcfree (voidpf opaque, voidpf ptr)
285void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
282286{
283287    if (opaque) opaque = 0; /* to make compiler happy */
284288    _hfree(ptr);
r15677r15678
297301extern void   free   OF((voidpf ptr));
298302#endif
299303
300voidpf zcalloc (opaque, items, size)
304voidpf ZLIB_INTERNAL zcalloc (opaque, items, size)
301305    voidpf opaque;
302306    unsigned items;
303307    unsigned size;
r15677r15678
307311                              (voidpf)calloc(items, size);
308312}
309313
310void zcfree (opaque, ptr)
314void ZLIB_INTERNAL zcfree (opaque, ptr)
311315    voidpf opaque;
312316    voidpf ptr;
313317{
r15677r15678
316320}
317321
318322#endif /* MY_ZCALLOC */
323
324#endif /* !Z_SOLO */
src/lib/zlib/gzlib.c
r0r15678
1/* gzlib.c -- zlib functions common to reading and writing gzip files
2 * Copyright (C) 2004, 2010, 2011, 2012 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6#include "gzguts.h"
7
8#if defined(_WIN32) && !defined(__BORLANDC__)
9#  define LSEEK _lseeki64
10#else
11#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
12#  define LSEEK lseek64
13#else
14#  define LSEEK lseek
15#endif
16#endif
17
18/* Local functions */
19local void gz_reset OF((gz_statep));
20local gzFile gz_open OF((const void *, int, const char *));
21
22#if defined UNDER_CE
23
24/* Map the Windows error number in ERROR to a locale-dependent error message
25   string and return a pointer to it.  Typically, the values for ERROR come
26   from GetLastError.
27
28   The string pointed to shall not be modified by the application, but may be
29   overwritten by a subsequent call to gz_strwinerror
30
31   The gz_strwinerror function does not change the current setting of
32   GetLastError. */
33char ZLIB_INTERNAL *gz_strwinerror (error)
34     DWORD error;
35{
36    static char buf[1024];
37
38    wchar_t *msgbuf;
39    DWORD lasterr = GetLastError();
40    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
41        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
42        NULL,
43        error,
44        0, /* Default language */
45        (LPVOID)&msgbuf,
46        0,
47        NULL);
48    if (chars != 0) {
49        /* If there is an \r\n appended, zap it.  */
50        if (chars >= 2
51            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
52            chars -= 2;
53            msgbuf[chars] = 0;
54        }
55
56        if (chars > sizeof (buf) - 1) {
57            chars = sizeof (buf) - 1;
58            msgbuf[chars] = 0;
59        }
60
61        wcstombs(buf, msgbuf, chars + 1);
62        LocalFree(msgbuf);
63    }
64    else {
65        sprintf(buf, "unknown win32 error (%ld)", error);
66    }
67
68    SetLastError(lasterr);
69    return buf;
70}
71
72#endif /* UNDER_CE */
73
74/* Reset gzip file state */
75local void gz_reset(state)
76    gz_statep state;
77{
78    state->x.have = 0;              /* no output data available */
79    if (state->mode == GZ_READ) {   /* for reading ... */
80        state->eof = 0;             /* not at end of file */
81        state->past = 0;            /* have not read past end yet */
82        state->how = LOOK;          /* look for gzip header */
83    }
84    state->seek = 0;                /* no seek request pending */
85    gz_error(state, Z_OK, NULL);    /* clear error */
86    state->x.pos = 0;               /* no uncompressed data yet */
87    state->strm.avail_in = 0;       /* no input data yet */
88}
89
90/* Open a gzip file either by name or file descriptor. */
91local gzFile gz_open(path, fd, mode)
92    const void *path;
93    int fd;
94    const char *mode;
95{
96    gz_statep state;
97    size_t len;
98    int oflag;
99#ifdef O_CLOEXEC
100    int cloexec = 0;
101#endif
102#ifdef O_EXCL
103    int exclusive = 0;
104#endif
105
106    /* check input */
107    if (path == NULL)
108        return NULL;
109
110    /* allocate gzFile structure to return */
111    state = malloc(sizeof(gz_state));
112    if (state == NULL)
113        return NULL;
114    state->size = 0;            /* no buffers allocated yet */
115    state->want = GZBUFSIZE;    /* requested buffer size */
116    state->msg = NULL;          /* no error message yet */
117
118    /* interpret mode */
119    state->mode = GZ_NONE;
120    state->level = Z_DEFAULT_COMPRESSION;
121    state->strategy = Z_DEFAULT_STRATEGY;
122    state->direct = 0;
123    while (*mode) {
124        if (*mode >= '0' && *mode <= '9')
125            state->level = *mode - '0';
126        else
127            switch (*mode) {
128            case 'r':
129                state->mode = GZ_READ;
130                break;
131#ifndef NO_GZCOMPRESS
132            case 'w':
133                state->mode = GZ_WRITE;
134                break;
135            case 'a':
136                state->mode = GZ_APPEND;
137                break;
138#endif
139            case '+':       /* can't read and write at the same time */
140                free(state);
141                return NULL;
142            case 'b':       /* ignore -- will request binary anyway */
143                break;
144#ifdef O_CLOEXEC
145            case 'e':
146                cloexec = 1;
147                break;
148#endif
149#ifdef O_EXCL
150            case 'x':
151                exclusive = 1;
152                break;
153#endif
154            case 'f':
155                state->strategy = Z_FILTERED;
156                break;
157            case 'h':
158                state->strategy = Z_HUFFMAN_ONLY;
159                break;
160            case 'R':
161                state->strategy = Z_RLE;
162                break;
163            case 'F':
164                state->strategy = Z_FIXED;
165            case 'T':
166                state->direct = 1;
167            default:        /* could consider as an error, but just ignore */
168                ;
169            }
170        mode++;
171    }
172
173    /* must provide an "r", "w", or "a" */
174    if (state->mode == GZ_NONE) {
175        free(state);
176        return NULL;
177    }
178
179    /* can't force transparent read */
180    if (state->mode == GZ_READ) {
181        if (state->direct) {
182            free(state);
183            return NULL;
184        }
185        state->direct = 1;      /* for empty file */
186    }
187
188    /* save the path name for error messages */
189#ifdef _WIN32
190    if (fd == -2) {
191        len = wcstombs(NULL, path, 0);
192        if (len == (size_t)-1)
193            len = 0;
194    }
195    else
196#endif
197        len = strlen(path);
198    state->path = malloc(len + 1);
199    if (state->path == NULL) {
200        free(state);
201        return NULL;
202    }
203#ifdef _WIN32
204    if (fd == -2)
205        if (len)
206            wcstombs(state->path, path, len + 1);
207        else
208            *(state->path) = 0;
209    else
210#endif
211        strcpy(state->path, path);
212
213    /* compute the flags for open() */
214    oflag =
215#ifdef O_LARGEFILE
216        O_LARGEFILE |
217#endif
218#ifdef O_BINARY
219        O_BINARY |
220#endif
221#ifdef O_CLOEXEC
222        (cloexec ? O_CLOEXEC : 0) |
223#endif
224        (state->mode == GZ_READ ?
225         O_RDONLY :
226         (O_WRONLY | O_CREAT |
227#ifdef O_EXCL
228          (exclusive ? O_EXCL : 0) |
229#endif
230          (state->mode == GZ_WRITE ?
231           O_TRUNC :
232           O_APPEND)));
233
234    /* open the file with the appropriate flags (or just use fd) */
235    state->fd = fd > -1 ? fd : (
236#ifdef _WIN32
237        fd == -2 ? _wopen(path, oflag, 0666) :
238#endif
239        open(path, oflag, 0666));
240    if (state->fd == -1) {
241        free(state->path);
242        free(state);
243        return NULL;
244    }
245    if (state->mode == GZ_APPEND)
246        state->mode = GZ_WRITE;         /* simplify later checks */
247
248    /* save the current position for rewinding (only if reading) */
249    if (state->mode == GZ_READ) {
250        state->start = LSEEK(state->fd, 0, SEEK_CUR);
251        if (state->start == -1) state->start = 0;
252    }
253
254    /* initialize stream */
255    gz_reset(state);
256
257    /* return stream */
258    return (gzFile)state;
259}
260
261/* -- see zlib.h -- */
262gzFile ZEXPORT gzopen(path, mode)
263    const char *path;
264    const char *mode;
265{
266    return gz_open(path, -1, mode);
267}
268
269/* -- see zlib.h -- */
270gzFile ZEXPORT gzopen64(path, mode)
271    const char *path;
272    const char *mode;
273{
274    return gz_open(path, -1, mode);
275}
276
277/* -- see zlib.h -- */
278gzFile ZEXPORT gzdopen(fd, mode)
279    int fd;
280    const char *mode;
281{
282    char *path;         /* identifier for error messages */
283    gzFile gz;
284
285    if (fd == -1 || (path = malloc(7 + 3 * sizeof(int))) == NULL)
286        return NULL;
287    sprintf(path, "<fd:%d>", fd);   /* for debugging */
288    gz = gz_open(path, fd, mode);
289    free(path);
290    return gz;
291}
292
293/* -- see zlib.h -- */
294#ifdef _WIN32
295gzFile ZEXPORT gzopen_w(path, mode)
296    const wchar_t *path;
297    const char *mode;
298{
299    return gz_open(path, -2, mode);
300}
301#endif
302
303/* -- see zlib.h -- */
304int ZEXPORT gzbuffer(file, size)
305    gzFile file;
306    unsigned size;
307{
308    gz_statep state;
309
310    /* get internal structure and check integrity */
311    if (file == NULL)
312        return -1;
313    state = (gz_statep)file;
314    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
315        return -1;
316
317    /* make sure we haven't already allocated memory */
318    if (state->size != 0)
319        return -1;
320
321    /* check and set requested size */
322    if (size < 2)
323        size = 2;               /* need two bytes to check magic header */
324    state->want = size;
325    return 0;
326}
327
328/* -- see zlib.h -- */
329int ZEXPORT gzrewind(file)
330    gzFile file;
331{
332    gz_statep state;
333
334    /* get internal structure */
335    if (file == NULL)
336        return -1;
337    state = (gz_statep)file;
338
339    /* check that we're reading and that there's no error */
340    if (state->mode != GZ_READ ||
341            (state->err != Z_OK && state->err != Z_BUF_ERROR))
342        return -1;
343
344    /* back up and start over */
345    if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
346        return -1;
347    gz_reset(state);
348    return 0;
349}
350
351/* -- see zlib.h -- */
352z_off64_t ZEXPORT gzseek64(file, offset, whence)
353    gzFile file;
354    z_off64_t offset;
355    int whence;
356{
357    unsigned n;
358    z_off64_t ret;
359    gz_statep state;
360
361    /* get internal structure and check integrity */
362    if (file == NULL)
363        return -1;
364    state = (gz_statep)file;
365    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
366        return -1;
367
368    /* check that there's no error */
369    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
370        return -1;
371
372    /* can only seek from start or relative to current position */
373    if (whence != SEEK_SET && whence != SEEK_CUR)
374        return -1;
375
376    /* normalize offset to a SEEK_CUR specification */
377    if (whence == SEEK_SET)
378        offset -= state->x.pos;
379    else if (state->seek)
380        offset += state->skip;
381    state->seek = 0;
382
383    /* if within raw area while reading, just go there */
384    if (state->mode == GZ_READ && state->how == COPY &&
385            state->x.pos + offset >= 0) {
386        ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR);
387        if (ret == -1)
388            return -1;
389        state->x.have = 0;
390        state->eof = 0;
391        state->past = 0;
392        state->seek = 0;
393        gz_error(state, Z_OK, NULL);
394        state->strm.avail_in = 0;
395        state->x.pos += offset;
396        return state->x.pos;
397    }
398
399    /* calculate skip amount, rewinding if needed for back seek when reading */
400    if (offset < 0) {
401        if (state->mode != GZ_READ)         /* writing -- can't go backwards */
402            return -1;
403        offset += state->x.pos;
404        if (offset < 0)                     /* before start of file! */
405            return -1;
406        if (gzrewind(file) == -1)           /* rewind, then skip to offset */
407            return -1;
408    }
409
410    /* if reading, skip what's in output buffer (one less gzgetc() check) */
411    if (state->mode == GZ_READ) {
412        n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
413            (unsigned)offset : state->x.have;
414        state->x.have -= n;
415        state->x.next += n;
416        state->x.pos += n;
417        offset -= n;
418    }
419
420    /* request skip (if not zero) */
421    if (offset) {
422        state->seek = 1;
423        state->skip = offset;
424    }
425    return state->x.pos + offset;
426}
427
428/* -- see zlib.h -- */
429z_off_t ZEXPORT gzseek(file, offset, whence)
430    gzFile file;
431    z_off_t offset;
432    int whence;
433{
434    z_off64_t ret;
435
436    ret = gzseek64(file, (z_off64_t)offset, whence);
437    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
438}
439
440/* -- see zlib.h -- */
441z_off64_t ZEXPORT gztell64(file)
442    gzFile file;
443{
444    gz_statep state;
445
446    /* get internal structure and check integrity */
447    if (file == NULL)
448        return -1;
449    state = (gz_statep)file;
450    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
451        return -1;
452
453    /* return position */
454    return state->x.pos + (state->seek ? state->skip : 0);
455}
456
457/* -- see zlib.h -- */
458z_off_t ZEXPORT gztell(file)
459    gzFile file;
460{
461    z_off64_t ret;
462
463    ret = gztell64(file);
464    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
465}
466
467/* -- see zlib.h -- */
468z_off64_t ZEXPORT gzoffset64(file)
469    gzFile file;
470{
471    z_off64_t offset;
472    gz_statep state;
473
474    /* get internal structure and check integrity */
475    if (file == NULL)
476        return -1;
477    state = (gz_statep)file;
478    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
479        return -1;
480
481    /* compute and return effective offset in file */
482    offset = LSEEK(state->fd, 0, SEEK_CUR);
483    if (offset == -1)
484        return -1;
485    if (state->mode == GZ_READ)             /* reading */
486        offset -= state->strm.avail_in;     /* don't count buffered input */
487    return offset;
488}
489
490/* -- see zlib.h -- */
491z_off_t ZEXPORT gzoffset(file)
492    gzFile file;
493{
494    z_off64_t ret;
495
496    ret = gzoffset64(file);
497    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
498}
499
500/* -- see zlib.h -- */
501int ZEXPORT gzeof(file)
502    gzFile file;
503{
504    gz_statep state;
505
506    /* get internal structure and check integrity */
507    if (file == NULL)
508        return 0;
509    state = (gz_statep)file;
510    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
511        return 0;
512
513    /* return end-of-file state */
514    return state->mode == GZ_READ ? state->past : 0;
515}
516
517/* -- see zlib.h -- */
518const char * ZEXPORT gzerror(file, errnum)
519    gzFile file;
520    int *errnum;
521{
522    gz_statep state;
523
524    /* get internal structure and check integrity */
525    if (file == NULL)
526        return NULL;
527    state = (gz_statep)file;
528    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
529        return NULL;
530
531    /* return error information */
532    if (errnum != NULL)
533        *errnum = state->err;
534    return state->msg == NULL ? "" : state->msg;
535}
536
537/* -- see zlib.h -- */
538void ZEXPORT gzclearerr(file)
539    gzFile file;
540{
541    gz_statep state;
542
543    /* get internal structure and check integrity */
544    if (file == NULL)
545        return;
546    state = (gz_statep)file;
547    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
548        return;
549
550    /* clear error and end-of-file */
551    if (state->mode == GZ_READ) {
552        state->eof = 0;
553        state->past = 0;
554    }
555    gz_error(state, Z_OK, NULL);
556}
557
558/* Create an error message in allocated memory and set state->err and
559   state->msg accordingly.  Free any previous error message already there.  Do
560   not try to free or allocate space if the error is Z_MEM_ERROR (out of
561   memory).  Simply save the error message as a static string.  If there is an
562   allocation failure constructing the error message, then convert the error to
563   out of memory. */
564void ZLIB_INTERNAL gz_error(state, err, msg)
565    gz_statep state;
566    int err;
567    const char *msg;
568{
569    /* free previously allocated message and clear */
570    if (state->msg != NULL) {
571        if (state->err != Z_MEM_ERROR)
572            free(state->msg);
573        state->msg = NULL;
574    }
575
576    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
577    if (err != Z_OK && err != Z_BUF_ERROR)
578        state->x.have = 0;
579
580    /* set error code, and if no message, then done */
581    state->err = err;
582    if (msg == NULL)
583        return;
584
585    /* for an out of memory error, save as static string */
586    if (err == Z_MEM_ERROR) {
587        state->msg = (char *)msg;
588        return;
589    }
590
591    /* construct error message with path */
592    if ((state->msg = malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) {
593        state->err = Z_MEM_ERROR;
594        state->msg = (char *)"out of memory";
595        return;
596    }
597    strcpy(state->msg, state->path);
598    strcat(state->msg, ": ");
599    strcat(state->msg, msg);
600    return;
601}
602
603#ifndef INT_MAX
604/* portably return maximum value for an int (when limits.h presumed not
605   available) -- we need to do this to cover cases where 2's complement not
606   used, since C standard permits 1's complement and sign-bit representations,
607   otherwise we could just use ((unsigned)-1) >> 1 */
608unsigned ZLIB_INTERNAL gz_intmax()
609{
610    unsigned p, q;
611
612    p = 1;
613    do {
614        q = p;
615        p <<= 1;
616        p++;
617    } while (p > q);
618    return q >> 1;
619}
620#endif
src/lib/zlib/deflate.h
r15677r15678
11/* deflate.h -- internal compression state
2 * Copyright (C) 1995-2004 Jean-loup Gailly
2 * Copyright (C) 1995-2012 Jean-loup Gailly
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
4848#define MAX_BITS 15
4949/* All codes must not exceed MAX_BITS bits */
5050
51#define Buf_size 16
52/* size of bit buffer in bi_buf */
53
5154#define INIT_STATE    42
5255#define EXTRA_STATE   69
5356#define NAME_STATE    73
r15677r15678
188191    int nice_match; /* Stop searching when current match exceeds this */
189192
190193                /* used by trees.c: */
191    /* Didn't use ct_data typedef below to supress compiler warning */
194    /* Didn't use ct_data typedef below to suppress compiler warning */
192195    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
193196    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
194197    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
r15677r15678
244247    ulg opt_len;        /* bit length of current block with optimal trees */
245248    ulg static_len;     /* bit length of current block with static trees */
246249    uInt matches;       /* number of string matches in current block */
247    int last_eob_len;   /* bit length of EOB code for last block */
250    uInt insert;        /* bytes at end of window left to insert */
248251
249252#ifdef DEBUG
250253    ulg compressed_len; /* total bit length of compressed file mod 2^32 */
r15677r15678
260263     * are always zero.
261264     */
262265
266    ulg high_water;
267    /* High water mark offset in window for initialized bytes -- bytes above
268     * this are set to zero in order to avoid memory check warnings when
269     * longest match routines access bytes past the input.  This is then
270     * updated to the new high water mark.
271     */
272
263273} FAR deflate_state;
264274
265275/* Output a byte on the stream.
r15677r15678
278288 * distances are limited to MAX_DIST instead of WSIZE.
279289 */
280290
291#define WIN_INIT MAX_MATCH
292/* Number of bytes after end of data in window to initialize in order to avoid
293   memory checker errors from longest match routines */
294
281295        /* in trees.c */
282void _tr_init         OF((deflate_state *s));
283int  _tr_tally        OF((deflate_state *s, unsigned dist, unsigned lc));
284void _tr_flush_block  OF((deflate_state *s, charf *buf, ulg stored_len,
285                          int eof));
286void _tr_align        OF((deflate_state *s));
287void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
288                          int eof));
296void ZLIB_INTERNAL _tr_init OF((deflate_state *s));
297int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
298void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
299                        ulg stored_len, int last));
300void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));
301void ZLIB_INTERNAL _tr_align OF((deflate_state *s));
302void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
303                        ulg stored_len, int last));
289304
290305#define d_code(dist) \
291306   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
r15677r15678
298313/* Inline versions of _tr_tally for speed: */
299314
300315#if defined(GEN_TREES_H) || !defined(STDC)
301  extern uch _length_code[];
302  extern uch _dist_code[];
316  extern uch ZLIB_INTERNAL _length_code[];
317  extern uch ZLIB_INTERNAL _dist_code[];
303318#else
304  extern const uch _length_code[];
305  extern const uch _dist_code[];
319  extern const uch ZLIB_INTERNAL _length_code[];
320  extern const uch ZLIB_INTERNAL _dist_code[];
306321#endif
307322
308323# define _tr_tally_lit(s, c, flush) \
src/lib/zlib/zutil.h
r15677r15678
11/* zutil.h -- internal interface and configuration of the compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
2 * Copyright (C) 1995-2012 Jean-loup Gailly.
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
1313#ifndef ZUTIL_H
1414#define ZUTIL_H
1515
16#define ZLIB_INTERNAL
16#ifdef HAVE_HIDDEN
17#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
18#else
19#  define ZLIB_INTERNAL
20#endif
21
1722#include "zlib.h"
1823
19#ifdef STDC
20#  ifndef _WIN32_WCE
24#if defined(STDC) && !defined(Z_SOLO)
25#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
2126#    include <stddef.h>
2227#  endif
2328#  include <string.h>
2429#  include <stdlib.h>
2530#endif
26#ifdef NO_ERRNO_H
27#   ifdef _WIN32_WCE
28      /* The Microsoft C Run-Time Library for Windows CE doesn't have
29       * errno.  We define it as a global variable to simplify porting.
30       * Its value is always 0 and should not be used.  We rename it to
31       * avoid conflict with other libraries that use the same workaround.
32       */
33#     define errno z_errno
34#   endif
35    extern int errno;
36#else
37#  ifndef _WIN32_WCE
38#    include <errno.h>
39#  endif
31
32#ifdef Z_SOLO
33   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */
4034#endif
4135
4236#ifndef local
r15677r15678
8882
8983#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
9084#  define OS_CODE  0x00
91#  if defined(__TURBOC__) || defined(__BORLANDC__)
92#    if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
93       /* Allow compilation with ANSI keywords only enabled */
94       void _Cdecl farfree( void *block );
95       void *_Cdecl farmalloc( unsigned long nbytes );
96#    else
97#      include <alloc.h>
85#  ifndef Z_SOLO
86#    if defined(__TURBOC__) || defined(__BORLANDC__)
87#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
88         /* Allow compilation with ANSI keywords only enabled */
89         void _Cdecl farfree( void *block );
90         void *_Cdecl farmalloc( unsigned long nbytes );
91#      else
92#        include <alloc.h>
93#      endif
94#    else /* MSC or DJGPP */
95#      include <malloc.h>
9896#    endif
99#  else /* MSC or DJGPP */
100#    include <malloc.h>
10197#  endif
10298#endif
10399
r15677r15678
117113
118114#ifdef OS2
119115#  define OS_CODE  0x06
120#  ifdef M_I86
121     #include <malloc.h>
116#  if defined(M_I86) && !defined(Z_SOLO)
117#    include <malloc.h>
122118#  endif
123119#endif
124120
125121#if defined(MACOS) || defined(TARGET_OS_MAC)
126122#  define OS_CODE  0x07
127#  if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
128#    include <unix.h> /* for fdopen */
129#  else
130#    ifndef fdopen
131#      define fdopen(fd,mode) NULL /* No fdopen() */
123#  ifndef Z_SOLO
124#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
125#      include <unix.h> /* for fdopen */
126#    else
127#      ifndef fdopen
128#        define fdopen(fd,mode) NULL /* No fdopen() */
129#      endif
132130#    endif
133131#  endif
134132#endif
r15677r15678
151149#  define fdopen(fd,mode) NULL /* No fdopen() */
152150#endif
153151
154#if (defined(_MSC_VER) && (_MSC_VER > 600))
152#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
155153#  if defined(_WIN32_WCE)
156154#    define fdopen(fd,mode) NULL /* No fdopen() */
157155#    ifndef _PTRDIFF_T_DEFINED
r15677r15678
163161#  endif
164162#endif
165163
164#if defined(__BORLANDC__) && !defined(MSDOS)
165  #pragma warn -8004
166  #pragma warn -8008
167  #pragma warn -8066
168#endif
169
170/* provide prototypes for these when building zlib without LFS */
171#if !defined(_WIN32) && (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
172    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
173    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
174#endif
175
166176        /* common defaults */
167177
168178#ifndef OS_CODE
r15677r15678
175185
176186         /* functions */
177187
178#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
179#  ifndef HAVE_VSNPRINTF
180#    define HAVE_VSNPRINTF
181#  endif
182#endif
183#if defined(__CYGWIN__)
184#  ifndef HAVE_VSNPRINTF
185#    define HAVE_VSNPRINTF
186#  endif
187#endif
188#ifndef HAVE_VSNPRINTF
189#  ifdef MSDOS
190     /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
191        but for now we just assume it doesn't. */
192#    define NO_vsnprintf
193#  endif
194#  ifdef __TURBOC__
195#    define NO_vsnprintf
196#  endif
197#  ifdef WIN32
198     /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
199#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
200#      define vsnprintf _vsnprintf
201#    endif
202#  endif
203#  ifdef __SASC
204#    define NO_vsnprintf
205#  endif
206#endif
207#ifdef VMS
208#  define NO_vsnprintf
209#endif
210
211#if defined(pyr)
188#if defined(pyr) || defined(Z_SOLO)
212189#  define NO_MEMCPY
213190#endif
214191#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
r15677r15678
232209#    define zmemzero(dest, len) memset(dest, 0, len)
233210#  endif
234211#else
235   extern void zmemcpy  OF((Bytef* dest, const Bytef* source, uInt len));
236   extern int  zmemcmp  OF((const Bytef* s1, const Bytef* s2, uInt len));
237   extern void zmemzero OF((Bytef* dest, uInt len));
212   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
213   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
214   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
238215#endif
239216
240217/* Diagnostic functions */
241218#ifdef DEBUG
242219#  include <stdio.h>
243   extern int z_verbose;
244   extern void z_error    OF((char *m));
220   extern int ZLIB_INTERNAL z_verbose;
221   extern void ZLIB_INTERNAL z_error OF((char *m));
245222#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
246223#  define Trace(x) {if (z_verbose>=0) fprintf x ;}
247224#  define Tracev(x) {if (z_verbose>0) fprintf x ;}
r15677r15678
257234#  define Tracecv(c,x)
258235#endif
259236
237#ifndef Z_SOLO
238   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
239                                    unsigned size));
240   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
241#endif
260242
261voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
262void   zcfree  OF((voidpf opaque, voidpf ptr));
263
264243#define ZALLOC(strm, items, size) \
265244           (*((strm)->zalloc))((strm)->opaque, (items), (size))
266245#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
267246#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
268247
248/* Reverse the bytes in a 32-bit value */
249#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
250                    (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
251
269252#endif /* ZUTIL_H */
src/lib/zlib/crc32.c
r15677r15678
11/* crc32.c -- compute the CRC-32 of a data stream
2 * Copyright (C) 1995-2005 Mark Adler
2 * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 *
55 * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
r15677r15678
1717  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
1818  first call get_crc_table() to initialize the tables before allowing more than
1919  one thread to use crc32().
20
21  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.
2022 */
2123
2224#ifdef MAKECRCH
r15677r15678
3032
3133#define local static
3234
33/* Find a four-byte integer type for crc32_little() and crc32_big(). */
34#ifndef NOBYFOUR
35#  ifdef STDC           /* need ANSI C limits.h to determine sizes */
36#    include <limits.h>
37#    define BYFOUR
38#    if (UINT_MAX == 0xffffffffUL)
39       typedef unsigned int u4;
40#    else
41#      if (ULONG_MAX == 0xffffffffUL)
42         typedef unsigned long u4;
43#      else
44#        if (USHRT_MAX == 0xffffffffUL)
45           typedef unsigned short u4;
46#        else
47#          undef BYFOUR     /* can't find a four-byte integer type! */
48#        endif
49#      endif
50#    endif
51#  endif /* STDC */
52#endif /* !NOBYFOUR */
53
5435/* Definitions for doing the crc four data bytes at a time. */
36#if !defined(NOBYFOUR) && defined(Z_U4)
37#  define BYFOUR
38#endif
5539#ifdef BYFOUR
56#  define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
57                (((w)&0xff00)<<8)+(((w)&0xff)<<24))
5840   local unsigned long crc32_little OF((unsigned long,
5941                        const unsigned char FAR *, unsigned));
6042   local unsigned long crc32_big OF((unsigned long,
r15677r15678
6850local unsigned long gf2_matrix_times OF((unsigned long *mat,
6951                                         unsigned long vec));
7052local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
53local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));
7154
55
7256#ifdef DYNAMIC_CRC_TABLE
7357
7458local volatile int crc_table_empty = 1;
75local unsigned long FAR crc_table[TBLS][256];
59local z_crc_t FAR crc_table[TBLS][256];
7660local void make_crc_table OF((void));
7761#ifdef MAKECRCH
78   local void write_table OF((FILE *, const unsigned long FAR *));
62   local void write_table OF((FILE *, const z_crc_t FAR *));
7963#endif /* MAKECRCH */
8064/*
8165  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
r15677r15678
10589*/
10690local void make_crc_table()
10791{
108    unsigned long c;
92    z_crc_t c;
10993    int n, k;
110    unsigned long poly;                 /* polynomial exclusive-or pattern */
94    z_crc_t poly;                       /* polynomial exclusive-or pattern */
11195    /* terms of polynomial defining this crc (except x^32): */
11296    static volatile int first = 1;      /* flag to limit concurrent making */
11397    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
r15677r15678
119103        first = 0;
120104
121105        /* make exclusive-or pattern from polynomial (0xedb88320UL) */
122        poly = 0UL;
123        for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
124            poly |= 1UL << (31 - p[n]);
106        poly = 0;
107        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)
108            poly |= (z_crc_t)1 << (31 - p[n]);
125109
126110        /* generate a crc for every 8-bit value */
127111        for (n = 0; n < 256; n++) {
128            c = (unsigned long)n;
112            c = (z_crc_t)n;
129113            for (k = 0; k < 8; k++)
130114                c = c & 1 ? poly ^ (c >> 1) : c >> 1;
131115            crc_table[0][n] = c;
r15677r15678
136120           and then the byte reversal of those as well as the first table */
137121        for (n = 0; n < 256; n++) {
138122            c = crc_table[0][n];
139            crc_table[4][n] = REV(c);
123            crc_table[4][n] = ZSWAP32(c);
140124            for (k = 1; k < 4; k++) {
141125                c = crc_table[0][c & 0xff] ^ (c >> 8);
142126                crc_table[k][n] = c;
143                crc_table[k + 4][n] = REV(c);
127                crc_table[k + 4][n] = ZSWAP32(c);
144128            }
145129        }
146130#endif /* BYFOUR */
r15677r15678
162146        if (out == NULL) return;
163147        fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
164148        fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
165        fprintf(out, "local const unsigned long FAR ");
149        fprintf(out, "local const z_crc_t FAR ");
166150        fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
167151        write_table(out, crc_table[0]);
168152#  ifdef BYFOUR
r15677r15678
182166#ifdef MAKECRCH
183167local void write_table(out, table)
184168    FILE *out;
185    const unsigned long FAR *table;
169    const z_crc_t FAR *table;
186170{
187171    int n;
188172
189173    for (n = 0; n < 256; n++)
190        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ", table[n],
174        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ",
175                (unsigned long)(table[n]),
191176                n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
192177}
193178#endif /* MAKECRCH */
r15677r15678
202187/* =========================================================================
203188 * This function can be used by asm versions of crc32()
204189 */
205const unsigned long FAR * ZEXPORT get_crc_table()
190const z_crc_t FAR * ZEXPORT get_crc_table()
206191{
207192#ifdef DYNAMIC_CRC_TABLE
208193    if (crc_table_empty)
209194        make_crc_table();
210195#endif /* DYNAMIC_CRC_TABLE */
211    return (const unsigned long FAR *)crc_table;
196    return (const z_crc_t FAR *)crc_table;
212197}
213198
214199/* ========================================================================= */
r15677r15678
219204unsigned long ZEXPORT crc32(crc, buf, len)
220205    unsigned long crc;
221206    const unsigned char FAR *buf;
222    unsigned len;
207    uInt len;
223208{
224209    if (buf == Z_NULL) return 0UL;
225210
r15677r15678
230215
231216#ifdef BYFOUR
232217    if (sizeof(void *) == sizeof(ptrdiff_t)) {
233        u4 endian;
218        z_crc_t endian;
234219
235220        endian = 1;
236221        if (*((unsigned char *)(&endian)))
r15677r15678
264249    const unsigned char FAR *buf;
265250    unsigned len;
266251{
267    register u4 c;
268    register const u4 FAR *buf4;
252    register z_crc_t c;
253    register const z_crc_t FAR *buf4;
269254
270    c = (u4)crc;
255    c = (z_crc_t)crc;
271256    c = ~c;
272257    while (len && ((ptrdiff_t)buf & 3)) {
273258        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
274259        len--;
275260    }
276261
277    buf4 = (const u4 FAR *)(const void FAR *)buf;
262    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
278263    while (len >= 32) {
279264        DOLIT32;
280265        len -= 32;
r15677r15678
304289    const unsigned char FAR *buf;
305290    unsigned len;
306291{
307    register u4 c;
308    register const u4 FAR *buf4;
292    register z_crc_t c;
293    register const z_crc_t FAR *buf4;
309294
310    c = REV((u4)crc);
295    c = ZSWAP32((z_crc_t)crc);
311296    c = ~c;
312297    while (len && ((ptrdiff_t)buf & 3)) {
313298        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
314299        len--;
315300    }
316301
317    buf4 = (const u4 FAR *)(const void FAR *)buf;
302    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
318303    buf4--;
319304    while (len >= 32) {
320305        DOBIG32;
r15677r15678
331316        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
332317    } while (--len);
333318    c = ~c;
334    return (unsigned long)(REV(c));
319    return (unsigned long)(ZSWAP32(c));
335320}
336321
337322#endif /* BYFOUR */
r15677r15678
367352}
368353
369354/* ========================================================================= */
370uLong ZEXPORT crc32_combine(crc1, crc2, len2)
355local uLong crc32_combine_(crc1, crc2, len2)
371356    uLong crc1;
372357    uLong crc2;
373    z_off_t len2;
358    z_off64_t len2;
374359{
375360    int n;
376361    unsigned long row;
377362    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
378363    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
379364
380    /* degenerate case */
381    if (len2 == 0)
365    /* degenerate case (also disallow negative lengths) */
366    if (len2 <= 0)
382367        return crc1;
383368
384369    /* put operator for one zero bit in odd */
385    odd[0] = 0xedb88320L;           /* CRC-32 polynomial */
370    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
386371    row = 1;
387372    for (n = 1; n < GF2_DIM; n++) {
388373        odd[n] = row;
r15677r15678
421406    crc1 ^= crc2;
422407    return crc1;
423408}
409
410/* ========================================================================= */
411uLong ZEXPORT crc32_combine(crc1, crc2, len2)
412    uLong crc1;
413    uLong crc2;
414    z_off_t len2;
415{
416    return crc32_combine_(crc1, crc2, len2);
417}
418
419uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
420    uLong crc1;
421    uLong crc2;
422    z_off64_t len2;
423{
424    return crc32_combine_(crc1, crc2, len2);
425}
src/lib/zlib/gzread.c
r0r15678
1/* gzread.c -- zlib functions for reading gzip files
2 * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6#include "gzguts.h"
7
8/* Local functions */
9local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));
10local int gz_avail OF((gz_statep));
11local int gz_look OF((gz_statep));
12local int gz_decomp OF((gz_statep));
13local int gz_fetch OF((gz_statep));
14local int gz_skip OF((gz_statep, z_off64_t));
15
16/* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from
17   state->fd, and update state->eof, state->err, and state->msg as appropriate.
18   This function needs to loop on read(), since read() is not guaranteed to
19   read the number of bytes requested, depending on the type of descriptor. */
20local int gz_load(state, buf, len, have)
21    gz_statep state;
22    unsigned char *buf;
23    unsigned len;
24    unsigned *have;
25{
26    int ret;
27
28    *have = 0;
29    do {
30        ret = read(state->fd, buf + *have, len - *have);
31        if (ret <= 0)
32            break;
33        *have += ret;
34    } while (*have < len);
35    if (ret < 0) {
36        gz_error(state, Z_ERRNO, zstrerror());
37        return -1;
38    }
39    if (ret == 0)
40        state->eof = 1;
41    return 0;
42}
43
44/* Load up input buffer and set eof flag if last data loaded -- return -1 on
45   error, 0 otherwise.  Note that the eof flag is set when the end of the input
46   file is reached, even though there may be unused data in the buffer.  Once
47   that data has been used, no more attempts will be made to read the file.
48   If strm->avail_in != 0, then the current data is moved to the beginning of
49   the input buffer, and then the remainder of the buffer is loaded with the
50   available data from the input file. */
51local int gz_avail(state)
52    gz_statep state;
53{
54    unsigned got;
55    z_streamp strm = &(state->strm);
56
57    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
58        return -1;
59    if (state->eof == 0) {
60        if (strm->avail_in) {       /* copy what's there to the start */
61            unsigned char *p = state->in, *q = strm->next_in;
62            unsigned n = strm->avail_in;
63            do {
64                *p++ = *q++;
65            } while (--n);
66        }
67        if (gz_load(state, state->in + strm->avail_in,
68                    state->size - strm->avail_in, &got) == -1)
69            return -1;
70        strm->avail_in += got;
71        strm->next_in = state->in;
72    }
73    return 0;
74}
75
76/* Look for gzip header, set up for inflate or copy.  state->x.have must be 0.
77   If this is the first time in, allocate required memory.  state->how will be
78   left unchanged if there is no more input data available, will be set to COPY
79   if there is no gzip header and direct copying will be performed, or it will
80   be set to GZIP for decompression.  If direct copying, then leftover input
81   data from the input buffer will be copied to the output buffer.  In that
82   case, all further file reads will be directly to either the output buffer or
83   a user buffer.  If decompressing, the inflate state will be initialized.
84   gz_look() will return 0 on success or -1 on failure. */
85local int gz_look(state)
86    gz_statep state;
87{
88    z_streamp strm = &(state->strm);
89
90    /* allocate read buffers and inflate memory */
91    if (state->size == 0) {
92        /* allocate buffers */
93        state->in = malloc(state->want);
94        state->out = malloc(state->want << 1);
95        if (state->in == NULL || state->out == NULL) {
96            if (state->out != NULL)
97                free(state->out);
98            if (state->in != NULL)
99                free(state->in);
100            gz_error(state, Z_MEM_ERROR, "out of memory");
101            return -1;
102        }
103        state->size = state->want;
104
105        /* allocate inflate memory */
106        state->strm.zalloc = Z_NULL;
107        state->strm.zfree = Z_NULL;
108        state->strm.opaque = Z_NULL;
109        state->strm.avail_in = 0;
110        state->strm.next_in = Z_NULL;
111        if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) {    /* gunzip */
112            free(state->out);
113            free(state->in);
114            state->size = 0;
115            gz_error(state, Z_MEM_ERROR, "out of memory");
116            return -1;
117        }
118    }
119
120    /* get at least the magic bytes in the input buffer */
121    if (strm->avail_in < 2) {
122        if (gz_avail(state) == -1)
123            return -1;
124        if (strm->avail_in == 0)
125            return 0;
126    }
127
128    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is
129       a logical dilemma here when considering the case of a partially written
130       gzip file, to wit, if a single 31 byte is written, then we cannot tell
131       whether this is a single-byte file, or just a partially written gzip
132       file -- for here we assume that if a gzip file is being written, then
133       the header will be written in a single operation, so that reading a
134       single byte is sufficient indication that it is not a gzip file) */
135    if (strm->avail_in > 1 &&
136            strm->next_in[0] == 31 && strm->next_in[1] == 139) {
137        inflateReset(strm);
138        state->how = GZIP;
139        state->direct = 0;
140        return 0;
141    }
142
143    /* no gzip header -- if we were decoding gzip before, then this is trailing
144       garbage.  Ignore the trailing garbage and finish. */
145    if (state->direct == 0) {
146        strm->avail_in = 0;
147        state->eof = 1;
148        state->x.have = 0;
149        return 0;
150    }
151
152    /* doing raw i/o, copy any leftover input to output -- this assumes that
153       the output buffer is larger than the input buffer, which also assures
154       space for gzungetc() */
155    state->x.next = state->out;
156    if (strm->avail_in) {
157        memcpy(state->x.next, strm->next_in, strm->avail_in);
158        state->x.have = strm->avail_in;
159        strm->avail_in = 0;
160    }
161    state->how = COPY;
162    state->direct = 1;
163    return 0;
164}
165
166/* Decompress from input to the provided next_out and avail_out in the state.
167   On return, state->x.have and state->x.next point to the just decompressed
168   data.  If the gzip stream completes, state->how is reset to LOOK to look for
169   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0
170   on success, -1 on failure. */
171local int gz_decomp(state)
172    gz_statep state;
173{
174    int ret = Z_OK;
175    unsigned had;
176    z_streamp strm = &(state->strm);
177
178    /* fill output buffer up to end of deflate stream */
179    had = strm->avail_out;
180    do {
181        /* get more input for inflate() */
182        if (strm->avail_in == 0 && gz_avail(state) == -1)
183            return -1;
184        if (strm->avail_in == 0) {
185            gz_error(state, Z_BUF_ERROR, "unexpected end of file");
186            break;
187        }
188
189        /* decompress and handle errors */
190        ret = inflate(strm, Z_NO_FLUSH);
191        if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
192            gz_error(state, Z_STREAM_ERROR,
193                     "internal error: inflate stream corrupt");
194            return -1;
195        }
196        if (ret == Z_MEM_ERROR) {
197            gz_error(state, Z_MEM_ERROR, "out of memory");
198            return -1;
199        }
200        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */
201            gz_error(state, Z_DATA_ERROR,
202                     strm->msg == NULL ? "compressed data error" : strm->msg);
203            return -1;
204        }
205    } while (strm->avail_out && ret != Z_STREAM_END);
206
207    /* update available output */
208    state->x.have = had - strm->avail_out;
209    state->x.next = strm->next_out - state->x.have;
210
211    /* if the gzip stream completed successfully, look for another */
212    if (ret == Z_STREAM_END)
213        state->how = LOOK;
214
215    /* good decompression */
216    return 0;
217}
218
219/* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.
220   Data is either copied from the input file or decompressed from the input
221   file depending on state->how.  If state->how is LOOK, then a gzip header is
222   looked for to determine whether to copy or decompress.  Returns -1 on error,
223   otherwise 0.  gz_fetch() will leave state->how as COPY or GZIP unless the
224   end of the input file has been reached and all data has been processed.  */
225local int gz_fetch(state)
226    gz_statep state;
227{
228    z_streamp strm = &(state->strm);
229
230    do {
231        switch(state->how) {
232        case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */
233            if (gz_look(state) == -1)
234                return -1;
235            if (state->how == LOOK)
236                return 0;
237            break;
238        case COPY:      /* -> COPY */
239            if (gz_load(state, state->out, state->size << 1, &(state->x.have))
240                    == -1)
241                return -1;
242            state->x.next = state->out;
243            return 0;
244        case GZIP:      /* -> GZIP or LOOK (if end of gzip stream) */
245            strm->avail_out = state->size << 1;
246            strm->next_out = state->out;
247            if (gz_decomp(state) == -1)
248                return -1;
249        }
250    } while (state->x.have == 0 && (!state->eof || strm->avail_in));
251    return 0;
252}
253
254/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */
255local int gz_skip(state, len)
256    gz_statep state;
257    z_off64_t len;
258{
259    unsigned n;
260
261    /* skip over len bytes or reach end-of-file, whichever comes first */
262    while (len)
263        /* skip over whatever is in output buffer */
264        if (state->x.have) {
265            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?
266                (unsigned)len : state->x.have;
267            state->x.have -= n;
268            state->x.next += n;
269            state->x.pos += n;
270            len -= n;
271        }
272
273        /* output buffer empty -- return if we're at the end of the input */
274        else if (state->eof && state->strm.avail_in == 0)
275            break;
276
277        /* need more data to skip -- load up output buffer */
278        else {
279            /* get more output, looking for header if required */
280            if (gz_fetch(state) == -1)
281                return -1;
282        }
283    return 0;
284}
285
286/* -- see zlib.h -- */
287int ZEXPORT gzread(file, buf, len)
288    gzFile file;
289    voidp buf;
290    unsigned len;
291{
292    unsigned got, n;
293    gz_statep state;
294    z_streamp strm;
295
296    /* get internal structure */
297    if (file == NULL)
298        return -1;
299    state = (gz_statep)file;
300    strm = &(state->strm);
301
302    /* check that we're reading and that there's no (serious) error */
303    if (state->mode != GZ_READ ||
304            (state->err != Z_OK && state->err != Z_BUF_ERROR))
305        return -1;
306
307    /* since an int is returned, make sure len fits in one, otherwise return
308       with an error (this avoids the flaw in the interface) */
309    if ((int)len < 0) {
310        gz_error(state, Z_DATA_ERROR, "requested length does not fit in int");
311        return -1;
312    }
313
314    /* if len is zero, avoid unnecessary operations */
315    if (len == 0)
316        return 0;
317
318    /* process a skip request */
319    if (state->seek) {
320        state->seek = 0;
321        if (gz_skip(state, state->skip) == -1)
322            return -1;
323    }
324
325    /* get len bytes to buf, or less than len if at the end */
326    got = 0;
327    do {
328        /* first just try copying data from the output buffer */
329        if (state->x.have) {
330            n = state->x.have > len ? len : state->x.have;
331            memcpy(buf, state->x.next, n);
332            state->x.next += n;
333            state->x.have -= n;
334        }
335
336        /* output buffer empty -- return if we're at the end of the input */
337        else if (state->eof && strm->avail_in == 0) {
338            state->past = 1;        /* tried to read past end */
339            break;
340        }
341
342        /* need output data -- for small len or new stream load up our output
343           buffer */
344        else if (state->how == LOOK || len < (state->size << 1)) {
345            /* get more output, looking for header if required */
346            if (gz_fetch(state) == -1)
347                return -1;
348            continue;       /* no progress yet -- go back to copy above */
349            /* the copy above assures that we will leave with space in the
350               output buffer, allowing at least one gzungetc() to succeed */
351        }
352
353        /* large len -- read directly into user buffer */
354        else if (state->how == COPY) {      /* read directly */
355            if (gz_load(state, buf, len, &n) == -1)
356                return -1;
357        }
358
359        /* large len -- decompress directly into user buffer */
360        else {  /* state->how == GZIP */
361            strm->avail_out = len;
362            strm->next_out = buf;
363            if (gz_decomp(state) == -1)
364                return -1;
365            n = state->x.have;
366            state->x.have = 0;
367        }
368
369        /* update progress */
370        len -= n;
371        buf = (char *)buf + n;
372        got += n;
373        state->x.pos += n;
374    } while (len);
375
376    /* return number of bytes read into user buffer (will fit in int) */
377    return (int)got;
378}
379
380/* -- see zlib.h -- */
381#undef gzgetc
382int ZEXPORT gzgetc(file)
383    gzFile file;
384{
385    int ret;
386    unsigned char buf[1];
387    gz_statep state;
388
389    /* get internal structure */
390    if (file == NULL)
391        return -1;
392    state = (gz_statep)file;
393
394    /* check that we're reading and that there's no (serious) error */
395    if (state->mode != GZ_READ ||
396        (state->err != Z_OK && state->err != Z_BUF_ERROR))
397        return -1;
398
399    /* try output buffer (no need to check for skip request) */
400    if (state->x.have) {
401        state->x.have--;
402        state->x.pos++;
403        return *(state->x.next)++;
404    }
405
406    /* nothing there -- try gzread() */
407    ret = gzread(file, buf, 1);
408    return ret < 1 ? -1 : buf[0];
409}
410
411int ZEXPORT gzgetc_(file)
412gzFile file;
413{
414    return gzgetc(file);
415}
416
417/* -- see zlib.h -- */
418int ZEXPORT gzungetc(c, file)
419    int c;
420    gzFile file;
421{
422    gz_statep state;
423
424    /* get internal structure */
425    if (file == NULL)
426        return -1;
427    state = (gz_statep)file;
428
429    /* check that we're reading and that there's no (serious) error */
430    if (state->mode != GZ_READ ||
431        (state->err != Z_OK && state->err != Z_BUF_ERROR))
432        return -1;
433
434    /* process a skip request */
435    if (state->seek) {
436        state->seek = 0;
437        if (gz_skip(state, state->skip) == -1)
438            return -1;
439    }
440
441    /* can't push EOF */
442    if (c < 0)
443        return -1;
444
445    /* if output buffer empty, put byte at end (allows more pushing) */
446    if (state->x.have == 0) {
447        state->x.have = 1;
448        state->x.next = state->out + (state->size << 1) - 1;
449        state->x.next[0] = c;
450        state->x.pos--;
451        state->past = 0;
452        return c;
453    }
454
455    /* if no room, give up (must have already done a gzungetc()) */
456    if (state->x.have == (state->size << 1)) {
457        gz_error(state, Z_DATA_ERROR, "out of room to push characters");
458        return -1;
459    }
460
461    /* slide output data if needed and insert byte before existing data */
462    if (state->x.next == state->out) {
463        unsigned char *src = state->out + state->x.have;
464        unsigned char *dest = state->out + (state->size << 1);
465        while (src > state->out)
466            *--dest = *--src;
467        state->x.next = dest;
468    }
469    state->x.have++;
470    state->x.next--;
471    state->x.next[0] = c;
472    state->x.pos--;
473    state->past = 0;
474    return c;
475}
476
477/* -- see zlib.h -- */
478char * ZEXPORT gzgets(file, buf, len)
479    gzFile file;
480    char *buf;
481    int len;
482{
483    unsigned left, n;
484    char *str;
485    unsigned char *eol;
486    gz_statep state;
487
488    /* check parameters and get internal structure */
489    if (file == NULL || buf == NULL || len < 1)
490        return NULL;
491    state = (gz_statep)file;
492
493    /* check that we're reading and that there's no (serious) error */
494    if (state->mode != GZ_READ ||
495        (state->err != Z_OK && state->err != Z_BUF_ERROR))
496        return NULL;
497
498    /* process a skip request */
499    if (state->seek) {
500        state->seek = 0;
501        if (gz_skip(state, state->skip) == -1)
502            return NULL;
503    }
504
505    /* copy output bytes up to new line or len - 1, whichever comes first --
506       append a terminating zero to the string (we don't check for a zero in
507       the contents, let the user worry about that) */
508    str = buf;
509    left = (unsigned)len - 1;
510    if (left) do {
511        /* assure that something is in the output buffer */
512        if (state->x.have == 0 && gz_fetch(state) == -1)
513            return NULL;                /* error */
514        if (state->x.have == 0) {       /* end of file */
515            state->past = 1;            /* read past end */
516            break;                      /* return what we have */
517        }
518
519        /* look for end-of-line in current output buffer */
520        n = state->x.have > left ? left : state->x.have;
521        eol = memchr(state->x.next, '\n', n);
522        if (eol != NULL)
523            n = (unsigned)(eol - state->x.next) + 1;
524
525        /* copy through end-of-line, or remainder if not found */
526        memcpy(buf, state->x.next, n);
527        state->x.have -= n;
528        state->x.next += n;
529        state->x.pos += n;
530        left -= n;
531        buf += n;
532    } while (left && eol == NULL);
533
534    /* return terminated string, or if nothing, end of file */
535    if (buf == str)
536        return NULL;
537    buf[0] = 0;
538    return str;
539}
540
541/* -- see zlib.h -- */
542int ZEXPORT gzdirect(file)
543    gzFile file;
544{
545    gz_statep state;
546
547    /* get internal structure */
548    if (file == NULL)
549        return 0;
550    state = (gz_statep)file;
551
552    /* if the state is not known, but we can find out, then do so (this is
553       mainly for right after a gzopen() or gzdopen()) */
554    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)
555        (void)gz_look(state);
556
557    /* return 1 if transparent, 0 if processing a gzip stream */
558    return state->direct;
559}
560
561/* -- see zlib.h -- */
562int ZEXPORT gzclose_r(file)
563    gzFile file;
564{
565    int ret, err;
566    gz_statep state;
567
568    /* get internal structure */
569    if (file == NULL)
570        return Z_STREAM_ERROR;
571    state = (gz_statep)file;
572
573    /* check that we're reading */
574    if (state->mode != GZ_READ)
575        return Z_STREAM_ERROR;
576
577    /* free memory and close file */
578    if (state->size) {
579        inflateEnd(&(state->strm));
580        free(state->out);
581        free(state->in);
582    }
583    err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;
584    gz_error(state, Z_OK, NULL);
585    free(state->path);
586    ret = close(state->fd);
587    free(state);
588    return ret ? Z_ERRNO : err;
589}
src/lib/zlib/crc32.h
r15677r15678
22 * Generated automatically by crc32.c
33 */
44
5local const unsigned long FAR crc_table[TBLS][256] =
5local const z_crc_t FAR crc_table[TBLS][256] =
66{
77  {
88    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
src/lib/zlib/trees.c
r15677r15678
11/* trees.c -- output deflated data using Huffman coding
2 * Copyright (C) 1995-2005 Jean-loup Gailly
2 * Copyright (C) 1995-2012 Jean-loup Gailly
3 * detect_data_type() function provided freely by Cosmin Truta, 2006
34 * For conditions of distribution and use, see copyright notice in zlib.h
45 */
56
r15677r15678
7374 * probability, to avoid transmitting the lengths for unused bit length codes.
7475 */
7576
76#define Buf_size (8 * 2*sizeof(char))
77/* Number of bits used within bi_buf. (bi_buf might be implemented on
78 * more than 16 bits on some systems.)
79 */
80
8177/* ===========================================================================
8278 * Local data. These are initialized only once.
8379 */
r15677r15678
152148                              int blcodes));
153149local void compress_block OF((deflate_state *s, ct_data *ltree,
154150                              ct_data *dtree));
155local void set_data_type OF((deflate_state *s));
151local int detect_data_type OF((deflate_state *s));
156152local unsigned bi_reverse OF((unsigned value, int length));
157153local void bi_windup      OF((deflate_state *s));
158154local void bi_flush       OF((deflate_state *s));
r15677r15678
203199     * unused bits in value.
204200     */
205201    if (s->bi_valid > (int)Buf_size - length) {
206        s->bi_buf |= (value << s->bi_valid);
202        s->bi_buf |= (ush)value << s->bi_valid;
207203        put_short(s, s->bi_buf);
208204        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
209205        s->bi_valid += length - Buf_size;
210206    } else {
211        s->bi_buf |= value << s->bi_valid;
207        s->bi_buf |= (ush)value << s->bi_valid;
212208        s->bi_valid += length;
213209    }
214210}
r15677r15678
218214{ int len = length;\
219215  if (s->bi_valid > (int)Buf_size - len) {\
220216    int val = value;\
221    s->bi_buf |= (val << s->bi_valid);\
217    s->bi_buf |= (ush)val << s->bi_valid;\
222218    put_short(s, s->bi_buf);\
223219    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
224220    s->bi_valid += len - Buf_size;\
225221  } else {\
226    s->bi_buf |= (value) << s->bi_valid;\
222    s->bi_buf |= (ush)(value) << s->bi_valid;\
227223    s->bi_valid += len;\
228224  }\
229225}
r15677r15678
250246    if (static_init_done) return;
251247
252248    /* For some embedded targets, global variables are not initialized: */
249#ifdef NO_INIT_GLOBAL_POINTERS
253250    static_l_desc.static_tree = static_ltree;
254251    static_l_desc.extra_bits = extra_lbits;
255252    static_d_desc.static_tree = static_dtree;
256253    static_d_desc.extra_bits = extra_dbits;
257254    static_bl_desc.extra_bits = extra_blbits;
255#endif
258256
259257    /* Initialize the mapping length (0..255) -> length code (0..28) */
260258    length = 0;
r15677r15678
348346                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
349347    }
350348
351    fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
349    fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
352350    for (i = 0; i < DIST_CODE_LEN; i++) {
353351        fprintf(header, "%2u%s", _dist_code[i],
354352                SEPARATOR(i, DIST_CODE_LEN-1, 20));
355353    }
356354
357    fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
355    fprintf(header,
356        "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
358357    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
359358        fprintf(header, "%2u%s", _length_code[i],
360359                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
r15677r15678
379378/* ===========================================================================
380379 * Initialize the tree data structures for a new zlib stream.
381380 */
382void _tr_init(s)
381void ZLIB_INTERNAL _tr_init(s)
383382    deflate_state *s;
384383{
385384    tr_static_init();
r15677r15678
395394
396395    s->bi_buf = 0;
397396    s->bi_valid = 0;
398    s->last_eob_len = 8; /* enough lookahead for inflate */
399397#ifdef DEBUG
400398    s->compressed_len = 0L;
401399    s->bits_sent = 0L;
r15677r15678
864862/* ===========================================================================
865863 * Send a stored block
866864 */
867void _tr_stored_block(s, buf, stored_len, eof)
865void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
868866    deflate_state *s;
869867    charf *buf;       /* input block */
870868    ulg stored_len;   /* length of input block */
871    int eof;          /* true if this is the last block for a file */
869    int last;         /* one if this is the last block for a file */
872870{
873    send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
871    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
874872#ifdef DEBUG
875873    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
876874    s->compressed_len += (stored_len + 4) << 3;
r15677r15678
879877}
880878
881879/* ===========================================================================
880 * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
881 */
882void ZLIB_INTERNAL _tr_flush_bits(s)
883    deflate_state *s;
884{
885    bi_flush(s);
886}
887
888/* ===========================================================================
882889 * Send one empty static block to give enough lookahead for inflate.
883890 * This takes 10 bits, of which 7 may remain in the bit buffer.
884 * The current inflate code requires 9 bits of lookahead. If the
885 * last two codes for the previous block (real code plus EOB) were coded
886 * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
887 * the last real code. In this case we send two empty static blocks instead
888 * of one. (There are no problems if the previous block is stored or fixed.)
889 * To simplify the code, we assume the worst case of last real code encoded
890 * on one bit only.
891891 */
892void _tr_align(s)
892void ZLIB_INTERNAL _tr_align(s)
893893    deflate_state *s;
894894{
895895    send_bits(s, STATIC_TREES<<1, 3);
r15677r15678
898898    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
899899#endif
900900    bi_flush(s);
901    /* Of the 10 bits for the empty block, we have already sent
902     * (10 - bi_valid) bits. The lookahead for the last real code (before
903     * the EOB of the previous block) was thus at least one plus the length
904     * of the EOB plus what we have just sent of the empty static block.
905     */
906    if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
907        send_bits(s, STATIC_TREES<<1, 3);
908        send_code(s, END_BLOCK, static_ltree);
909#ifdef DEBUG
910        s->compressed_len += 10L;
911#endif
912        bi_flush(s);
913    }
914    s->last_eob_len = 7;
915901}
916902
917903/* ===========================================================================
918904 * Determine the best encoding for the current block: dynamic trees, static
919905 * trees or store, and output the encoded block to the zip file.
920906 */
921void _tr_flush_block(s, buf, stored_len, eof)
907void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
922908    deflate_state *s;
923909    charf *buf;       /* input block, or NULL if too old */
924910    ulg stored_len;   /* length of input block */
925    int eof;          /* true if this is the last block for a file */
911    int last;         /* one if this is the last block for a file */
926912{
927913    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
928914    int max_blindex = 0;  /* index of last bit length code of non zero freq */
r15677r15678
931917    if (s->level > 0) {
932918
933919        /* Check if the file is binary or text */
934        if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
935            set_data_type(s);
920        if (s->strm->data_type == Z_UNKNOWN)
921            s->strm->data_type = detect_data_type(s);
936922
937923        /* Construct the literal and distance trees */
938924        build_tree(s, (tree_desc *)(&(s->l_desc)));
r15677r15678
978964         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
979965         * transform a block into a stored block.
980966         */
981        _tr_stored_block(s, buf, stored_len, eof);
967        _tr_stored_block(s, buf, stored_len, last);
982968
983969#ifdef FORCE_STATIC
984970    } else if (static_lenb >= 0) { /* force static trees */
985971#else
986972    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
987973#endif
988        send_bits(s, (STATIC_TREES<<1)+eof, 3);
974        send_bits(s, (STATIC_TREES<<1)+last, 3);
989975        compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
990976#ifdef DEBUG
991977        s->compressed_len += 3 + s->static_len;
992978#endif
993979    } else {
994        send_bits(s, (DYN_TREES<<1)+eof, 3);
980        send_bits(s, (DYN_TREES<<1)+last, 3);
995981        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
996982                       max_blindex+1);
997983        compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
r15677r15678
1005991     */
1006992    init_block(s);
1007993
1008    if (eof) {
994    if (last) {
1009995        bi_windup(s);
1010996#ifdef DEBUG
1011997        s->compressed_len += 7;  /* align on byte boundary */
1012998#endif
1013999    }
10141000    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1015           s->compressed_len-7*eof));
1001           s->compressed_len-7*last));
10161002}
10171003
10181004/* ===========================================================================
10191005 * Save the match info and tally the frequency counts. Return true if
10201006 * the current block must be flushed.
10211007 */
1022int _tr_tally (s, dist, lc)
1008int ZLIB_INTERNAL _tr_tally (s, dist, lc)
10231009    deflate_state *s;
10241010    unsigned dist;  /* distance of matched string */
10251011    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
r15677r15678
11141100    } while (lx < s->last_lit);
11151101
11161102    send_code(s, END_BLOCK, ltree);
1117    s->last_eob_len = ltree[END_BLOCK].Len;
11181103}
11191104
11201105/* ===========================================================================
1121 * Set the data type to BINARY or TEXT, using a crude approximation:
1122 * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
1123 * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
1106 * Check if the data type is TEXT or BINARY, using the following algorithm:
1107 * - TEXT if the two conditions below are satisfied:
1108 *    a) There are no non-portable control characters belonging to the
1109 *       "black list" (0..6, 14..25, 28..31).
1110 *    b) There is at least one printable character belonging to the
1111 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
1112 * - BINARY otherwise.
1113 * - The following partially-portable control characters form a
1114 *   "gray list" that is ignored in this detection algorithm:
1115 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
11241116 * IN assertion: the fields Freq of dyn_ltree are set.
11251117 */
1126local void set_data_type(s)
1118local int detect_data_type(s)
11271119    deflate_state *s;
11281120{
1121    /* black_mask is the bit mask of black-listed bytes
1122     * set bits 0..6, 14..25, and 28..31
1123     * 0xf3ffc07f = binary 11110011111111111100000001111111
1124     */
1125    unsigned long black_mask = 0xf3ffc07fUL;
11291126    int n;
11301127
1131    for (n = 0; n < 9; n++)
1128    /* Check for non-textual ("black-listed") bytes. */
1129    for (n = 0; n <= 31; n++, black_mask >>= 1)
1130        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
1131            return Z_BINARY;
1132
1133    /* Check for textual ("white-listed") bytes. */
1134    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
1135            || s->dyn_ltree[13].Freq != 0)
1136        return Z_TEXT;
1137    for (n = 32; n < LITERALS; n++)
11321138        if (s->dyn_ltree[n].Freq != 0)
1133            break;
1134    if (n == 9)
1135        for (n = 14; n < 32; n++)
1136            if (s->dyn_ltree[n].Freq != 0)
1137                break;
1138    s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
1139            return Z_TEXT;
1140
1141    /* There are no "black-listed" or "white-listed" bytes:
1142     * this stream either is empty or has tolerated ("gray-listed") bytes only.
1143     */
1144    return Z_BINARY;
11391145}
11401146
11411147/* ===========================================================================
r15677r15678
12011207    int      header;  /* true if block header must be written */
12021208{
12031209    bi_windup(s);        /* align on byte boundary */
1204    s->last_eob_len = 8; /* enough lookahead for inflate */
12051210
12061211    if (header) {
12071212        put_short(s, (ush)len);
src/lib/zlib/zconf.h
r15677r15678
11/* zconf.h -- configuration of the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
2 * Copyright (C) 1995-2012 Jean-loup Gailly.
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
1111/*
1212 * If you *really* need a unique prefix for all types and library functions,
1313 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
14 * Even better than compiling with -DZ_PREFIX would be to use configure to set
15 * this permanently in zconf.h using "./configure --zprefix".
1416 */
15#ifdef Z_PREFIX
16#  define deflateInit_          z_deflateInit_
17#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
18#  define Z_PREFIX_SET
19
20/* all linked symbols */
21#  define _dist_code            z__dist_code
22#  define _length_code          z__length_code
23#  define _tr_align             z__tr_align
24#  define _tr_flush_block       z__tr_flush_block
25#  define _tr_init              z__tr_init
26#  define _tr_stored_block      z__tr_stored_block
27#  define _tr_tally             z__tr_tally
28#  define adler32               z_adler32
29#  define adler32_combine       z_adler32_combine
30#  define adler32_combine64     z_adler32_combine64
31#  ifndef Z_SOLO
32#    define compress              z_compress
33#    define compress2             z_compress2
34#    define compressBound         z_compressBound
35#  endif
36#  define crc32                 z_crc32
37#  define crc32_combine         z_crc32_combine
38#  define crc32_combine64       z_crc32_combine64
1739#  define deflate               z_deflate
40#  define deflateBound          z_deflateBound
41#  define deflateCopy           z_deflateCopy
1842#  define deflateEnd            z_deflateEnd
19#  define inflateInit_          z_inflateInit_
20#  define inflate               z_inflate
21#  define inflateEnd            z_inflateEnd
2243#  define deflateInit2_         z_deflateInit2_
23#  define deflateSetDictionary  z_deflateSetDictionary
24#  define deflateCopy           z_deflateCopy
25#  define deflateReset          z_deflateReset
44#  define deflateInit_          z_deflateInit_
2645#  define deflateParams         z_deflateParams
27#  define deflateBound          z_deflateBound
46#  define deflatePending        z_deflatePending
2847#  define deflatePrime          z_deflatePrime
48#  define deflateReset          z_deflateReset
49#  define deflateResetKeep      z_deflateResetKeep
50#  define deflateSetDictionary  z_deflateSetDictionary
51#  define deflateSetHeader      z_deflateSetHeader
52#  define deflateTune           z_deflateTune
53#  define deflate_copyright     z_deflate_copyright
54#  define get_crc_table         z_get_crc_table
55#  ifndef Z_SOLO
56#    define gz_error              z_gz_error
57#    define gz_intmax             z_gz_intmax
58#    define gz_strwinerror        z_gz_strwinerror
59#    define gzbuffer              z_gzbuffer
60#    define gzclearerr            z_gzclearerr
61#    define gzclose               z_gzclose
62#    define gzclose_r             z_gzclose_r
63#    define gzclose_w             z_gzclose_w
64#    define gzdirect              z_gzdirect
65#    define gzdopen               z_gzdopen
66#    define gzeof                 z_gzeof
67#    define gzerror               z_gzerror
68#    define gzflush               z_gzflush
69#    define gzgetc                z_gzgetc
70#    define gzgetc_               z_gzgetc_
71#    define gzgets                z_gzgets
72#    define gzoffset              z_gzoffset
73#    define gzoffset64            z_gzoffset64
74#    define gzopen                z_gzopen
75#    define gzopen64              z_gzopen64
76#    ifdef _WIN32
77#      define gzopen_w              z_gzopen_w
78#    endif
79#    define gzprintf              z_gzprintf
80#    define gzputc                z_gzputc
81#    define gzputs                z_gzputs
82#    define gzread                z_gzread
83#    define gzrewind              z_gzrewind
84#    define gzseek                z_gzseek
85#    define gzseek64              z_gzseek64
86#    define gzsetparams           z_gzsetparams
87#    define gztell                z_gztell
88#    define gztell64              z_gztell64
89#    define gzungetc              z_gzungetc
90#    define gzwrite               z_gzwrite
91#  endif
92#  define inflate               z_inflate
93#  define inflateBack           z_inflateBack
94#  define inflateBackEnd        z_inflateBackEnd
95#  define inflateBackInit_      z_inflateBackInit_
96#  define inflateCopy           z_inflateCopy
97#  define inflateEnd            z_inflateEnd
98#  define inflateGetHeader      z_inflateGetHeader
2999#  define inflateInit2_         z_inflateInit2_
100#  define inflateInit_          z_inflateInit_
101#  define inflateMark           z_inflateMark
102#  define inflatePrime          z_inflatePrime
103#  define inflateReset          z_inflateReset
104#  define inflateReset2         z_inflateReset2
30105#  define inflateSetDictionary  z_inflateSetDictionary
31106#  define inflateSync           z_inflateSync
32107#  define inflateSyncPoint      z_inflateSyncPoint
33#  define inflateCopy           z_inflateCopy
34#  define inflateReset          z_inflateReset
35#  define inflateBack           z_inflateBack
36#  define inflateBackEnd        z_inflateBackEnd
37#  define compress              z_compress
38#  define compress2             z_compress2
39#  define compressBound         z_compressBound
40#  define uncompress            z_uncompress
41#  define adler32               z_adler32
42#  define crc32                 z_crc32
43#  define get_crc_table         z_get_crc_table
108#  define inflateUndermine      z_inflateUndermine
109#  define inflateResetKeep      z_inflateResetKeep
110#  define inflate_copyright     z_inflate_copyright
111#  define inflate_fast          z_inflate_fast
112#  define inflate_table         z_inflate_table
113#  ifndef Z_SOLO
114#    define uncompress            z_uncompress
115#  endif
44116#  define zError                z_zError
117#  ifndef Z_SOLO
118#    define zcalloc               z_zcalloc
119#    define zcfree                z_zcfree
120#  endif
121#  define zlibCompileFlags      z_zlibCompileFlags
122#  define zlibVersion           z_zlibVersion
45123
124/* all zlib typedefs in zlib.h and zconf.h */
125#  define Byte                  z_Byte
126#  define Bytef                 z_Bytef
46127#  define alloc_func            z_alloc_func
128#  define charf                 z_charf
47129#  define free_func             z_free_func
130#  ifndef Z_SOLO
131#    define gzFile                z_gzFile
132#  endif
133#  define gz_header             z_gz_header
134#  define gz_headerp            z_gz_headerp
48135#  define in_func               z_in_func
136#  define intf                  z_intf
49137#  define out_func              z_out_func
50#  define Byte                  z_Byte
51138#  define uInt                  z_uInt
139#  define uIntf                 z_uIntf
52140#  define uLong                 z_uLong
53#  define Bytef                 z_Bytef
54#  define charf                 z_charf
55#  define intf                  z_intf
56#  define uIntf                 z_uIntf
57141#  define uLongf                z_uLongf
142#  define voidp                 z_voidp
143#  define voidpc                z_voidpc
58144#  define voidpf                z_voidpf
59#  define voidp                 z_voidp
145
146/* all zlib structs in zlib.h and zconf.h */
147#  define gz_header_s           z_gz_header_s
148#  define internal_state        z_internal_state
149
60150#endif
61151
62152#if defined(__MSDOS__) && !defined(MSDOS)
r15677r15678
125215#  endif
126216#endif
127217
218#if defined(ZLIB_CONST) && !defined(z_const)
219#  define z_const const
220#else
221#  define z_const
222#endif
223
128224/* Some Mac compilers merge all .h files incorrectly: */
129225#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
130226#  define NO_DUMMY_DECL
r15677r15678
171267#  endif
172268#endif
173269
270#ifndef Z_ARG /* function prototypes for stdarg */
271#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
272#    define Z_ARG(args)  args
273#  else
274#    define Z_ARG(args)  ()
275#  endif
276#endif
277
174278/* The following definitions for FAR are needed only for MSDOS mixed
175279 * model programming (small or medium model with some far allocations).
176280 * This was tested only with MSC; for other MSDOS compilers you may have
r15677r15678
284388   typedef Byte       *voidp;
285389#endif
286390
287#if 0           /* HAVE_UNISTD_H -- this line is updated by ./configure */
288#  include <sys/types.h> /* for off_t */
289#  include <unistd.h>    /* for SEEK_* and off_t */
290#  ifdef VMS
291#    include <unixio.h>   /* for off_t */
391/* ./configure may #define Z_U4 here */
392
393#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
394#  include <limits.h>
395#  if (UINT_MAX == 0xffffffffUL)
396#    define Z_U4 unsigned
397#  else
398#    if (ULONG_MAX == 0xffffffffUL)
399#      define Z_U4 unsigned long
400#    else
401#      if (USHRT_MAX == 0xffffffffUL)
402#        define Z_U4 unsigned short
403#      endif
404#    endif
292405#  endif
293#  define z_off_t off_t
294406#endif
295#ifndef SEEK_SET
407
408#ifdef Z_U4
409   typedef Z_U4 z_crc_t;
410#else
411   typedef unsigned long z_crc_t;
412#endif
413
414#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
415#  define Z_HAVE_UNISTD_H
416#endif
417
418#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
419#  define Z_HAVE_STDARG_H
420#endif
421
422#ifdef STDC
423#  ifndef Z_SOLO
424#    include <sys/types.h>      /* for off_t */
425#  endif
426#endif
427
428#ifdef _WIN32
429#  include <stddef.h>           /* for wchar_t */
430#endif
431
432/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
433 * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
434 * though the former does not conform to the LFS document), but considering
435 * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
436 * equivalently requesting no 64-bit operations
437 */
438#if defined(LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
439#  undef _LARGEFILE64_SOURCE
440#endif
441
442#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)
443#  define Z_HAVE_UNISTD_H
444#endif
445#ifndef Z_SOLO
446#  if defined(Z_HAVE_UNISTD_H) || defined(LARGEFILE64_SOURCE)
447#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
448#    ifdef VMS
449#      include <unixio.h>       /* for off_t */
450#    endif
451#    ifndef z_off_t
452#      define z_off_t off_t
453#    endif
454#  endif
455#endif
456
457#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
458#  define Z_LFS64
459#endif
460
461#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
462#  define Z_LARGE64
463#endif
464
465#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
466#  define Z_WANT64
467#endif
468
469#if !defined(SEEK_SET) && !defined(Z_SOLO)
296470#  define SEEK_SET        0       /* Seek from beginning of file.  */
297471#  define SEEK_CUR        1       /* Seek from current position.  */
298472#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
299473#endif
474
300475#ifndef z_off_t
301476#  define z_off_t long
302477#endif
303478
304#if defined(__OS400__)
305#  define NO_vsnprintf
306#endif
307
308#if defined(__MVS__)
309#  define NO_vsnprintf
310#  ifdef FAR
311#    undef FAR
479#if !defined(_WIN32) && defined(Z_LARGE64)
480#  define z_off64_t off64_t
481#else
482#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)
483#    define z_off64_t __int64
484#  else
485#    define z_off64_t z_off_t
312486#  endif
313487#endif
314488
315489/* MVS linker does not support external names larger than 8 bytes */
316490#if defined(__MVS__)
317#   pragma map(deflateInit_,"DEIN")
318#   pragma map(deflateInit2_,"DEIN2")
319#   pragma map(deflateEnd,"DEEND")
320#   pragma map(deflateBound,"DEBND")
321#   pragma map(inflateInit_,"ININ")
322#   pragma map(inflateInit2_,"ININ2")
323#   pragma map(inflateEnd,"INEND")
324#   pragma map(inflateSync,"INSY")
325#   pragma map(inflateSetDictionary,"INSEDI")
326#   pragma map(compressBound,"CMBND")
327#   pragma map(inflate_table,"INTABL")
328#   pragma map(inflate_fast,"INFA")
329#   pragma map(inflate_copyright,"INCOPY")
491  #pragma map(deflateInit_,"DEIN")
492  #pragma map(deflateInit2_,"DEIN2")
493  #pragma map(deflateEnd,"DEEND")
494  #pragma map(deflateBound,"DEBND")
495  #pragma map(inflateInit_,"ININ")
496  #pragma map(inflateInit2_,"ININ2")
497  #pragma map(inflateEnd,"INEND")
498  #pragma map(inflateSync,"INSY")
499  #pragma map(inflateSetDictionary,"INSEDI")
500  #pragma map(compressBound,"CMBND")
501  #pragma map(inflate_table,"INTABL")
502  #pragma map(inflate_fast,"INFA")
503  #pragma map(inflate_copyright,"INCOPY")
330504#endif
331505
332506#endif /* ZCONF_H */
src/lib/zlib/minigzip.c
r15677r15678
11/* minigzip.c -- simulate gzip using the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
2 * Copyright (C) 1995-2006, 2010, 2011 Jean-loup Gailly.
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
1515
1616/* @(#) $Id$ */
1717
18#include "zlib.h"
1819#include <stdio.h>
19#include "zlib.h"
2020
2121#ifdef STDC
2222#  include <string.h>
r15677r15678
3232#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
3333#  include <fcntl.h>
3434#  include <io.h>
35#  ifdef UNDER_CE
36#    include <stdlib.h>
37#  endif
3538#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
3639#else
3740#  define SET_BINARY_MODE(file)
r15677r15678
5053#  include <unix.h> /* for fileno */
5154#endif
5255
56#if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE)
5357#ifndef WIN32 /* unlink already in stdio.h for WIN32 */
5458  extern int unlink OF((const char *));
5559#endif
60#endif
5661
62#if defined(UNDER_CE)
63#  include <windows.h>
64#  define perror(s) pwinerror(s)
65
66/* Map the Windows error number in ERROR to a locale-dependent error
67   message string and return a pointer to it.  Typically, the values
68   for ERROR come from GetLastError.
69
70   The string pointed to shall not be modified by the application,
71   but may be overwritten by a subsequent call to strwinerror
72
73   The strwinerror function does not change the current setting
74   of GetLastError.  */
75
76static char *strwinerror (error)
77     DWORD error;
78{
79    static char buf[1024];
80
81    wchar_t *msgbuf;
82    DWORD lasterr = GetLastError();
83    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
84        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
85        NULL,
86        error,
87        0, /* Default language */
88        (LPVOID)&msgbuf,
89        0,
90        NULL);
91    if (chars != 0) {
92        /* If there is an \r\n appended, zap it.  */
93        if (chars >= 2
94            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
95            chars -= 2;
96            msgbuf[chars] = 0;
97        }
98
99        if (chars > sizeof (buf) - 1) {
100            chars = sizeof (buf) - 1;
101            msgbuf[chars] = 0;
102        }
103
104        wcstombs(buf, msgbuf, chars + 1);
105        LocalFree(msgbuf);
106    }
107    else {
108        sprintf(buf, "unknown win32 error (%ld)", error);
109    }
110
111    SetLastError(lasterr);
112    return buf;
113}
114
115static void pwinerror (s)
116    const char *s;
117{
118    if (s && *s)
119        fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ()));
120    else
121        fprintf(stderr, "%s\n", strwinerror(GetLastError ()));
122}
123
124#endif /* UNDER_CE */
125
57126#ifndef GZ_SUFFIX
58127#  define GZ_SUFFIX ".gz"
59128#endif
r15677r15678
69138#  define local
70139#endif
71140
141#ifdef Z_SOLO
142/* for Z_SOLO, create simplified gz* functions using deflate and inflate */
143
144#if defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE)
145#  include <unistd.h>       /* for unlink() */
146#endif
147
148void *myalloc OF((void *, unsigned, unsigned));
149void myfree OF((void *, void *));
150
151void *myalloc(q, n, m)
152    void *q;
153    unsigned n, m;
154{
155    q = Z_NULL;
156    return calloc(n, m);
157}
158
159void myfree(q, p)
160    void *q, *p;
161{
162    q = Z_NULL;
163    free(p);
164}
165
166typedef struct gzFile_s {
167    FILE *file;
168    int write;
169    int err;
170    char *msg;
171    z_stream strm;
172} *gzFile;
173
174gzFile gzopen OF((const char *, const char *));
175gzFile gzdopen OF((int, const char *));
176gzFile gz_open OF((const char *, int, const char *));
177
178gzFile gzopen(path, mode)
179const char *path;
180const char *mode;
181{
182    return gz_open(path, -1, mode);
183}
184
185gzFile gzdopen(fd, mode)
186int fd;
187const char *mode;
188{
189    return gz_open(NULL, fd, mode);
190}
191
192gzFile gz_open(path, fd, mode)
193    const char *path;
194    int fd;
195    const char *mode;
196{
197    gzFile gz;
198    int ret;
199
200    gz = malloc(sizeof(struct gzFile_s));
201    if (gz == NULL)
202        return NULL;
203    gz->write = strchr(mode, 'w') != NULL;
204    gz->strm.zalloc = myalloc;
205    gz->strm.zfree = myfree;
206    gz->strm.opaque = Z_NULL;
207    if (gz->write)
208        ret = deflateInit2(&(gz->strm), -1, 8, 15 + 16, 8, 0);
209    else {
210        gz->strm.next_in = 0;
211        gz->strm.avail_in = Z_NULL;
212        ret = inflateInit2(&(gz->strm), 15 + 16);
213    }
214    if (ret != Z_OK) {
215        free(gz);
216        return NULL;
217    }
218    gz->file = path == NULL ? fdopen(fd, gz->write ? "wb" : "rb") :
219                              fopen(path, gz->write ? "wb" : "rb");
220    if (gz->file == NULL) {
221        gz->write ? deflateEnd(&(gz->strm)) : inflateEnd(&(gz->strm));
222        free(gz);
223        return NULL;
224    }
225    gz->err = 0;
226    gz->msg = "";
227    return gz;
228}
229
230int gzwrite OF((gzFile, const void *, unsigned));
231
232int gzwrite(gz, buf, len)
233    gzFile gz;
234    const void *buf;
235    unsigned len;
236{
237    z_stream *strm;
238    unsigned char out[BUFLEN];
239
240    if (gz == NULL || !gz->write)
241        return 0;
242    strm = &(gz->strm);
243    strm->next_in = (void *)buf;
244    strm->avail_in = len;
245    do {
246        strm->next_out = out;
247        strm->avail_out = BUFLEN;
248        (void)deflate(strm, Z_NO_FLUSH);
249        fwrite(out, 1, BUFLEN - strm->avail_out, gz->file);
250    } while (strm->avail_out == 0);
251    return len;
252}
253
254int gzread OF((gzFile, void *, unsigned));
255
256int gzread(gz, buf, len)
257    gzFile gz;
258    void *buf;
259    unsigned len;
260{
261    int ret;
262    unsigned got;
263    unsigned char in[1];
264    z_stream *strm;
265
266    if (gz == NULL || gz->write)
267        return 0;
268    if (gz->err)
269        return 0;
270    strm = &(gz->strm);
271    strm->next_out = (void *)buf;
272    strm->avail_out = len;
273    do {
274        got = fread(in, 1, 1, gz->file);
275        if (got == 0)
276            break;
277        strm->next_in = in;
278        strm->avail_in = 1;
279        ret = inflate(strm, Z_NO_FLUSH);
280        if (ret == Z_DATA_ERROR) {
281            gz->err = Z_DATA_ERROR;
282            gz->msg = strm->msg;
283            return 0;
284        }
285        if (ret == Z_STREAM_END)
286            inflateReset(strm);
287    } while (strm->avail_out);
288    return len - strm->avail_out;
289}
290
291int gzclose OF((gzFile));
292
293int gzclose(gz)
294    gzFile gz;
295{
296    z_stream *strm;
297    unsigned char out[BUFLEN];
298
299    if (gz == NULL)
300        return Z_STREAM_ERROR;
301    strm = &(gz->strm);
302    if (gz->write) {
303        strm->next_in = Z_NULL;
304        strm->avail_in = 0;
305        do {
306            strm->next_out = out;
307            strm->avail_out = BUFLEN;
308            (void)deflate(strm, Z_FINISH);
309            fwrite(out, 1, BUFLEN - strm->avail_out, gz->file);
310        } while (strm->avail_out == 0);
311        deflateEnd(strm);
312    }
313    else
314        inflateEnd(strm);
315    fclose(gz->file);
316    free(gz);
317    return Z_OK;
318}
319
320const char *gzerror OF((gzFile, int *));
321
322const char *gzerror(gz, err)
323    gzFile gz;
324    int *err;
325{
326    *err = gz->err;
327    return gz->msg;
328}
329
330#endif
331
72332char *prog;
73333
74334void error            OF((const char *msg));
r15677r15678
198458    FILE  *in;
199459    gzFile out;
200460
461    if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) {
462        fprintf(stderr, "%s: filename too long\n", prog);
463        exit(1);
464    }
465
201466    strcpy(outfile, file);
202467    strcat(outfile, GZ_SUFFIX);
203468
r15677r15678
227492    char *infile, *outfile;
228493    FILE  *out;
229494    gzFile in;
230    uInt len = (uInt)strlen(file);
495    size_t len = strlen(file);
231496
497    if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) {
498        fprintf(stderr, "%s: filename too long\n", prog);
499        exit(1);
500    }
501
232502    strcpy(buf, file);
233503
234504    if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) {
r15677r15678
258528
259529
260530/* ===========================================================================
261 * Usage:  minigzip [-d] [-f] [-h] [-r] [-1 to -9] [files...]
531 * Usage:  minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...]
532 *   -c : write to standard output
262533 *   -d : decompress
263534 *   -f : compress with Z_FILTERED
264535 *   -h : compress with Z_HUFFMAN_ONLY
r15677r15678
270541    int argc;
271542    char *argv[];
272543{
544    int copyout = 0;
273545    int uncompr = 0;
274546    gzFile file;
275    char outmode[20];
547    char *bname, outmode[20];
276548
277549    strcpy(outmode, "wb6 ");
278550
279551    prog = argv[0];
552    bname = strrchr(argv[0], '/');
553    if (bname)
554      bname++;
555    else
556      bname = argv[0];
280557    argc--, argv++;
281558
559    if (!strcmp(bname, "gunzip"))
560      uncompr = 1;
561    else if (!strcmp(bname, "zcat"))
562      copyout = uncompr = 1;
563
282564    while (argc > 0) {
283      if (strcmp(*argv, "-d") == 0)
565      if (strcmp(*argv, "-c") == 0)
566        copyout = 1;
567      else if (strcmp(*argv, "-d") == 0)
284568        uncompr = 1;
285569      else if (strcmp(*argv, "-f") == 0)
286570        outmode[3] = 'f';
r15677r15678
310594            gz_compress(stdin, file);
311595        }
312596    } else {
597        if (copyout) {
598            SET_BINARY_MODE(stdout);
599        }
313600        do {
314601            if (uncompr) {
315                file_uncompress(*argv);
602                if (copyout) {
603                    file = gzopen(*argv, "rb");
604                    if (file == NULL)
605                        fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv);
606                    else
607                        gz_uncompress(file, stdout);
608                } else {
609                    file_uncompress(*argv);
610                }
316611            } else {
317                file_compress(*argv, outmode);
612                if (copyout) {
613                    FILE * in = fopen(*argv, "rb");
614
615                    if (in == NULL) {
616                        perror(*argv);
617                    } else {
618                        file = gzdopen(fileno(stdout), outmode);
619                        if (file == NULL) error("can't gzdopen stdout");
620
621                        gz_compress(in, file);
622                    }
623
624                } else {
625                    file_compress(*argv, outmode);
626                }
318627            }
319628        } while (argv++, --argc);
320629    }
src/lib/zlib/trees.h
r15677r15678
7070{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
7171};
7272
73const uch _dist_code[DIST_CODE_LEN] = {
73const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
7474 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
7575 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
767610, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
r15677r15678
999929, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
100100};
101101
102const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
102const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
103103 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
10410413, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
10510517, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
src/lib/zlib/inffast.c
r15677r15678
11/* inffast.c -- fast decoding
2 * Copyright (C) 1995-2004 Mark Adler
2 * Copyright (C) 1995-2008, 2010 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
6464      requires strm->avail_out >= 258 for each loop to avoid checking for
6565      output space.
6666 */
67void inflate_fast(strm, start)
67void ZLIB_INTERNAL inflate_fast(strm, start)
6868z_streamp strm;
6969unsigned start;         /* inflate()'s starting value for strm->avail_out */
7070{
r15677r15678
7979#endif
8080    unsigned wsize;             /* window size or zero if not using window */
8181    unsigned whave;             /* valid bytes in the window */
82    unsigned write;             /* window write index */
82    unsigned wnext;             /* window write index */
8383    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
8484    unsigned long hold;         /* local strm->hold */
8585    unsigned bits;              /* local strm->bits */
r15677r15678
8787    code const FAR *dcode;      /* local strm->distcode */
8888    unsigned lmask;             /* mask for first level of length codes */
8989    unsigned dmask;             /* mask for first level of distance codes */
90    code this;                  /* retrieved table entry */
90    code here;                  /* retrieved table entry */
9191    unsigned op;                /* code bits, operation, extra bits, or */
9292                                /*  window position, window bytes to copy */
9393    unsigned len;               /* match length, unused bytes */
r15677r15678
106106#endif
107107    wsize = state->wsize;
108108    whave = state->whave;
109    write = state->write;
109    wnext = state->wnext;
110110    window = state->window;
111111    hold = state->hold;
112112    bits = state->bits;
r15677r15678
124124            hold += (unsigned long)(PUP(in)) << bits;
125125            bits += 8;
126126        }
127        this = lcode[hold & lmask];
127        here = lcode[hold & lmask];
128128      dolen:
129        op = (unsigned)(this.bits);
129        op = (unsigned)(here.bits);
130130        hold >>= op;
131131        bits -= op;
132        op = (unsigned)(this.op);
132        op = (unsigned)(here.op);
133133        if (op == 0) {                          /* literal */
134            Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
134            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
135135                    "inflate:         literal '%c'\n" :
136                    "inflate:         literal 0x%02x\n", this.val));
137            PUP(out) = (unsigned char)(this.val);
136                    "inflate:         literal 0x%02x\n", here.val));
137            PUP(out) = (unsigned char)(here.val);
138138        }
139139        else if (op & 16) {                     /* length base */
140            len = (unsigned)(this.val);
140            len = (unsigned)(here.val);
141141            op &= 15;                           /* number of extra bits */
142142            if (op) {
143143                if (bits < op) {
r15677r15678
155155                hold += (unsigned long)(PUP(in)) << bits;
156156                bits += 8;
157157            }
158            this = dcode[hold & dmask];
158            here = dcode[hold & dmask];
159159          dodist:
160            op = (unsigned)(this.bits);
160            op = (unsigned)(here.bits);
161161            hold >>= op;
162162            bits -= op;
163            op = (unsigned)(this.op);
163            op = (unsigned)(here.op);
164164            if (op & 16) {                      /* distance base */
165                dist = (unsigned)(this.val);
165                dist = (unsigned)(here.val);
166166                op &= 15;                       /* number of extra bits */
167167                if (bits < op) {
168168                    hold += (unsigned long)(PUP(in)) << bits;
r15677r15678
187187                if (dist > op) {                /* see if copy from window */
188188                    op = dist - op;             /* distance back in window */
189189                    if (op > whave) {
190                        strm->msg = (char *)"invalid distance too far back";
191                        state->mode = BAD;
192                        break;
190                        if (state->sane) {
191                            strm->msg =
192                                (char *)"invalid distance too far back";
193                            state->mode = BAD;
194                            break;
195                        }
196#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
197                        if (len <= op - whave) {
198                            do {
199                                PUP(out) = 0;
200                            } while (--len);
201                            continue;
202                        }
203                        len -= op - whave;
204                        do {
205                            PUP(out) = 0;
206                        } while (--op > whave);
207                        if (op == 0) {
208                            from = out - dist;
209                            do {
210                                PUP(out) = PUP(from);
211                            } while (--len);
212                            continue;
213                        }
214#endif
193215                    }
194216                    from = window - OFF;
195                    if (write == 0) {           /* very common case */
217                    if (wnext == 0) {           /* very common case */
196218                        from += wsize - op;
197219                        if (op < len) {         /* some from window */
198220                            len -= op;
r15677r15678
202224                            from = out - dist;  /* rest from output */
203225                        }
204226                    }
205                    else if (write < op) {      /* wrap around window */
206                        from += wsize + write - op;
207                        op -= write;
227                    else if (wnext < op) {      /* wrap around window */
228                        from += wsize + wnext - op;
229                        op -= wnext;
208230                        if (op < len) {         /* some from end of window */
209231                            len -= op;
210232                            do {
211233                                PUP(out) = PUP(from);
212234                            } while (--op);
213235                            from = window - OFF;
214                            if (write < len) {  /* some from start of window */
215                                op = write;
236                            if (wnext < len) {  /* some from start of window */
237                                op = wnext;
216238                                len -= op;
217239                                do {
218240                                    PUP(out) = PUP(from);
r15677r15678
222244                        }
223245                    }
224246                    else {                      /* contiguous in window */
225                        from += write - op;
247                        from += wnext - op;
226248                        if (op < len) {         /* some from window */
227249                            len -= op;
228250                            do {
r15677r15678
259281                }
260282            }
261283            else if ((op & 64) == 0) {          /* 2nd level distance code */
262                this = dcode[this.val + (hold & ((1U << op) - 1))];
284                here = dcode[here.val + (hold & ((1U << op) - 1))];
263285                goto dodist;
264286            }
265287            else {
r15677r15678
269291            }
270292        }
271293        else if ((op & 64) == 0) {              /* 2nd level length code */
272            this = lcode[this.val + (hold & ((1U << op) - 1))];
294            here = lcode[here.val + (hold & ((1U << op) - 1))];
273295            goto dolen;
274296        }
275297        else if (op & 32) {                     /* end-of-block */
r15677r15678
305327   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
306328   - Using bit fields for code structure
307329   - Different op definition to avoid & for extra bits (do & for table bits)
308   - Three separate decoding do-loops for direct, window, and write == 0
330   - Three separate decoding do-loops for direct, window, and wnext == 0
309331   - Special case for distance > 1 copies to do overlapped load and store copy
310332   - Explicit branch predictions (based on measured branch probabilities)
311333   - Deferring match copy and interspersed it with decoding subsequent codes
src/lib/zlib/gzwrite.c
r0r15678
1/* gzwrite.c -- zlib functions for writing gzip files
2 * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6#include "gzguts.h"
7
8/* Local functions */
9local int gz_init OF((gz_statep));
10local int gz_comp OF((gz_statep, int));
11local int gz_zero OF((gz_statep, z_off64_t));
12
13/* Initialize state for writing a gzip file.  Mark initialization by setting
14   state->size to non-zero.  Return -1 on failure or 0 on success. */
15local int gz_init(state)
16    gz_statep state;
17{
18    int ret;
19    z_streamp strm = &(state->strm);
20
21    /* allocate input buffer */
22    state->in = malloc(state->want);
23    if (state->in == NULL) {
24        gz_error(state, Z_MEM_ERROR, "out of memory");
25        return -1;
26    }
27
28    /* only need output buffer and deflate state if compressing */
29    if (!state->direct) {
30        /* allocate output buffer */
31        state->out = malloc(state->want);
32        if (state->out == NULL) {
33            free(state->in);
34            gz_error(state, Z_MEM_ERROR, "out of memory");
35            return -1;
36        }
37
38        /* allocate deflate memory, set up for gzip compression */
39        strm->zalloc = Z_NULL;
40        strm->zfree = Z_NULL;
41        strm->opaque = Z_NULL;
42        ret = deflateInit2(strm, state->level, Z_DEFLATED,
43                           MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy);
44        if (ret != Z_OK) {
45            free(state->out);
46            free(state->in);
47            gz_error(state, Z_MEM_ERROR, "out of memory");
48            return -1;
49        }
50    }
51
52    /* mark state as initialized */
53    state->size = state->want;
54
55    /* initialize write buffer if compressing */
56    if (!state->direct) {
57        strm->avail_out = state->size;
58        strm->next_out = state->out;
59        state->x.next = strm->next_out;
60    }
61    return 0;
62}
63
64/* Compress whatever is at avail_in and next_in and write to the output file.
65   Return -1 if there is an error writing to the output file, otherwise 0.
66   flush is assumed to be a valid deflate() flush value.  If flush is Z_FINISH,
67   then the deflate() state is reset to start a new gzip stream.  If gz->direct
68   is true, then simply write to the output file without compressing, and
69   ignore flush. */
70local int gz_comp(state, flush)
71    gz_statep state;
72    int flush;
73{
74    int ret, got;
75    unsigned have;
76    z_streamp strm = &(state->strm);
77
78    /* allocate memory if this is the first time through */
79    if (state->size == 0 && gz_init(state) == -1)
80        return -1;
81
82    /* write directly if requested */
83    if (state->direct) {
84        got = write(state->fd, strm->next_in, strm->avail_in);
85        if (got < 0 || (unsigned)got != strm->avail_in) {
86            gz_error(state, Z_ERRNO, zstrerror());
87            return -1;
88        }
89        strm->avail_in = 0;
90        return 0;
91    }
92
93    /* run deflate() on provided input until it produces no more output */
94    ret = Z_OK;
95    do {
96        /* write out current buffer contents if full, or if flushing, but if
97           doing Z_FINISH then don't write until we get to Z_STREAM_END */
98        if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
99            (flush != Z_FINISH || ret == Z_STREAM_END))) {
100            have = (unsigned)(strm->next_out - state->x.next);
101            if (have && ((got = write(state->fd, state->x.next, have)) < 0 ||
102                         (unsigned)got != have)) {
103                gz_error(state, Z_ERRNO, zstrerror());
104                return -1;
105            }
106            if (strm->avail_out == 0) {
107                strm->avail_out = state->size;
108                strm->next_out = state->out;
109            }
110            state->x.next = strm->next_out;
111        }
112
113        /* compress */
114        have = strm->avail_out;
115        ret = deflate(strm, flush);
116        if (ret == Z_STREAM_ERROR) {
117            gz_error(state, Z_STREAM_ERROR,
118                      "internal error: deflate stream corrupt");
119            return -1;
120        }
121        have -= strm->avail_out;
122    } while (have);
123
124    /* if that completed a deflate stream, allow another to start */
125    if (flush == Z_FINISH)
126        deflateReset(strm);
127
128    /* all done, no errors */
129    return 0;
130}
131
132/* Compress len zeros to output.  Return -1 on error, 0 on success. */
133local int gz_zero(state, len)
134    gz_statep state;
135    z_off64_t len;
136{
137    int first;
138    unsigned n;
139    z_streamp strm = &(state->strm);
140
141    /* consume whatever's left in the input buffer */
142    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
143        return -1;
144
145    /* compress len zeros (len guaranteed > 0) */
146    first = 1;
147    while (len) {
148        n = GT_OFF(state->size) || (z_off64_t)state->size > len ?
149            (unsigned)len : state->size;
150        if (first) {
151            memset(state->in, 0, n);
152            first = 0;
153        }
154        strm->avail_in = n;
155        strm->next_in = state->in;
156        state->x.pos += n;
157        if (gz_comp(state, Z_NO_FLUSH) == -1)
158            return -1;
159        len -= n;
160    }
161    return 0;
162}
163
164/* -- see zlib.h -- */
165int ZEXPORT gzwrite(file, buf, len)
166    gzFile file;
167    voidpc buf;
168    unsigned len;
169{
170    unsigned put = len;
171    unsigned n;
172    gz_statep state;
173    z_streamp strm;
174
175    /* get internal structure */
176    if (file == NULL)
177        return 0;
178    state = (gz_statep)file;
179    strm = &(state->strm);
180
181    /* check that we're writing and that there's no error */
182    if (state->mode != GZ_WRITE || state->err != Z_OK)
183        return 0;
184
185    /* since an int is returned, make sure len fits in one, otherwise return
186       with an error (this avoids the flaw in the interface) */
187    if ((int)len < 0) {
188        gz_error(state, Z_DATA_ERROR, "requested length does not fit in int");
189        return 0;
190    }
191
192    /* if len is zero, avoid unnecessary operations */
193    if (len == 0)
194        return 0;
195
196    /* allocate memory if this is the first time through */
197    if (state->size == 0 && gz_init(state) == -1)
198        return 0;
199
200    /* check for seek request */
201    if (state->seek) {
202        state->seek = 0;
203        if (gz_zero(state, state->skip) == -1)
204            return 0;
205    }
206
207    /* for small len, copy to input buffer, otherwise compress directly */
208    if (len < state->size) {
209        /* copy to input buffer, compress when full */
210        do {
211            if (strm->avail_in == 0)
212                strm->next_in = state->in;
213            n = state->size - strm->avail_in;
214            if (n > len)
215                n = len;
216            memcpy(strm->next_in + strm->avail_in, buf, n);
217            strm->avail_in += n;
218            state->x.pos += n;
219            buf = (char *)buf + n;
220            len -= n;
221            if (len && gz_comp(state, Z_NO_FLUSH) == -1)
222                return 0;
223        } while (len);
224    }
225    else {
226        /* consume whatever's left in the input buffer */
227        if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
228            return 0;
229
230        /* directly compress user buffer to file */
231        strm->avail_in = len;
232        strm->next_in = (voidp)buf;
233        state->x.pos += len;
234        if (gz_comp(state, Z_NO_FLUSH) == -1)
235            return 0;
236    }
237
238    /* input was all buffered or compressed (put will fit in int) */
239    return (int)put;
240}
241
242/* -- see zlib.h -- */
243int ZEXPORT gzputc(file, c)
244    gzFile file;
245    int c;
246{
247    unsigned char buf[1];
248    gz_statep state;
249    z_streamp strm;
250
251    /* get internal structure */
252    if (file == NULL)
253        return -1;
254    state = (gz_statep)file;
255    strm = &(state->strm);
256
257    /* check that we're writing and that there's no error */
258    if (state->mode != GZ_WRITE || state->err != Z_OK)
259        return -1;
260
261    /* check for seek request */
262    if (state->seek) {
263        state->seek = 0;
264        if (gz_zero(state, state->skip) == -1)
265            return -1;
266    }
267
268    /* try writing to input buffer for speed (state->size == 0 if buffer not
269       initialized) */
270    if (strm->avail_in < state->size) {
271        if (strm->avail_in == 0)
272            strm->next_in = state->in;
273        strm->next_in[strm->avail_in++] = c;
274        state->x.pos++;
275        return c & 0xff;
276    }
277
278    /* no room in buffer or not initialized, use gz_write() */
279    buf[0] = c;
280    if (gzwrite(file, buf, 1) != 1)
281        return -1;
282    return c & 0xff;
283}
284
285/* -- see zlib.h -- */
286int ZEXPORT gzputs(file, str)
287    gzFile file;
288    const char *str;
289{
290    int ret;
291    unsigned len;
292
293    /* write string */
294    len = (unsigned)strlen(str);
295    ret = gzwrite(file, str, len);
296    return ret == 0 && len != 0 ? -1 : ret;
297}
298
299#if defined(STDC) || defined(Z_HAVE_STDARG_H)
300#include <stdarg.h>
301
302/* -- see zlib.h -- */
303int ZEXPORTVA gzprintf (gzFile file, const char *format, ...)
304{
305    int size, len;
306    gz_statep state;
307    z_streamp strm;
308    va_list va;
309
310    /* get internal structure */
311    if (file == NULL)
312        return -1;
313    state = (gz_statep)file;
314    strm = &(state->strm);
315
316    /* check that we're writing and that there's no error */
317    if (state->mode != GZ_WRITE || state->err != Z_OK)
318        return 0;
319
320    /* make sure we have some buffer space */
321    if (state->size == 0 && gz_init(state) == -1)
322        return 0;
323
324    /* check for seek request */
325    if (state->seek) {
326        state->seek = 0;
327        if (gz_zero(state, state->skip) == -1)
328            return 0;
329    }
330
331    /* consume whatever's left in the input buffer */
332    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
333        return 0;
334
335    /* do the printf() into the input buffer, put length in len */
336    size = (int)(state->size);
337    state->in[size - 1] = 0;
338    va_start(va, format);
339#ifdef NO_vsnprintf
340#  ifdef HAS_vsprintf_void
341    (void)vsprintf((char *)(state->in), format, va);
342    va_end(va);
343    for (len = 0; len < size; len++)
344        if (state->in[len] == 0) break;
345#  else
346    len = vsprintf((char *)(state->in), format, va);
347    va_end(va);
348#  endif
349#else
350#  ifdef HAS_vsnprintf_void
351    (void)vsnprintf((char *)(state->in), size, format, va);
352    va_end(va);
353    len = strlen((char *)(state->in));
354#  else
355    len = vsnprintf((char *)(state->in), size, format, va);
356    va_end(va);
357#  endif
358#endif
359
360    /* check that printf() results fit in buffer */
361    if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
362        return 0;
363
364    /* update buffer and position, defer compression until needed */
365    strm->avail_in = (unsigned)len;
366    strm->next_in = state->in;
367    state->x.pos += len;
368    return len;
369}
370
371#else /* !STDC && !Z_HAVE_STDARG_H */
372
373/* -- see zlib.h -- */
374int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
375                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
376    gzFile file;
377    const char *format;
378    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
379        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
380{
381    int size, len;
382    gz_statep state;
383    z_streamp strm;
384
385    /* get internal structure */
386    if (file == NULL)
387        return -1;
388    state = (gz_statep)file;
389    strm = &(state->strm);
390
391    /* check that can really pass pointer in ints */
392    if (sizeof(int) != sizeof(void *))
393        return 0;
394
395    /* check that we're writing and that there's no error */
396    if (state->mode != GZ_WRITE || state->err != Z_OK)
397        return 0;
398
399    /* make sure we have some buffer space */
400    if (state->size == 0 && gz_init(state) == -1)
401        return 0;
402
403    /* check for seek request */
404    if (state->seek) {
405        state->seek = 0;
406        if (gz_zero(state, state->skip) == -1)
407            return 0;
408    }
409
410    /* consume whatever's left in the input buffer */
411    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
412        return 0;
413
414    /* do the printf() into the input buffer, put length in len */
415    size = (int)(state->size);
416    state->in[size - 1] = 0;
417#ifdef NO_snprintf
418#  ifdef HAS_sprintf_void
419    sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8,
420            a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
421    for (len = 0; len < size; len++)
422        if (state->in[len] == 0) break;
423#  else
424    len = sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8,
425                  a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
426#  endif
427#else
428#  ifdef HAS_snprintf_void
429    snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, a7, a8,
430             a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
431    len = strlen((char *)(state->in));
432#  else
433    len = snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6,
434                   a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18,
435                   a19, a20);
436#  endif
437#endif
438
439    /* check that printf() results fit in buffer */
440    if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
441        return 0;
442
443    /* update buffer and position, defer compression until needed */
444    strm->avail_in = (unsigned)len;
445    strm->next_in = state->in;
446    state->x.pos += len;
447    return len;
448}
449
450#endif
451
452/* -- see zlib.h -- */
453int ZEXPORT gzflush(file, flush)
454    gzFile file;
455    int flush;
456{
457    gz_statep state;
458
459    /* get internal structure */
460    if (file == NULL)
461        return -1;
462    state = (gz_statep)file;
463
464    /* check that we're writing and that there's no error */
465    if (state->mode != GZ_WRITE || state->err != Z_OK)
466        return Z_STREAM_ERROR;
467
468    /* check flush parameter */
469    if (flush < 0 || flush > Z_FINISH)
470        return Z_STREAM_ERROR;
471
472    /* check for seek request */
473    if (state->seek) {
474        state->seek = 0;
475        if (gz_zero(state, state->skip) == -1)
476            return -1;
477    }
478
479    /* compress remaining data with requested flush */
480    gz_comp(state, flush);
481    return state->err;
482}
483
484/* -- see zlib.h -- */
485int ZEXPORT gzsetparams(file, level, strategy)
486    gzFile file;
487    int level;
488    int strategy;
489{
490    gz_statep state;
491    z_streamp strm;
492
493    /* get internal structure */
494    if (file == NULL)
495        return Z_STREAM_ERROR;
496    state = (gz_statep)file;
497    strm = &(state->strm);
498
499    /* check that we're writing and that there's no error */
500    if (state->mode != GZ_WRITE || state->err != Z_OK)
501        return Z_STREAM_ERROR;
502
503    /* if no change is requested, then do nothing */
504    if (level == state->level && strategy == state->strategy)
505        return Z_OK;
506
507    /* check for seek request */
508    if (state->seek) {
509        state->seek = 0;
510        if (gz_zero(state, state->skip) == -1)
511            return -1;
512    }
513
514    /* change compression parameters for subsequent input */
515    if (state->size) {
516        /* flush previous input with previous parameters before changing */
517        if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1)
518            return state->err;
519        deflateParams(strm, level, strategy);
520    }
521    state->level = level;
522    state->strategy = strategy;
523    return Z_OK;
524}
525
526/* -- see zlib.h -- */
527int ZEXPORT gzclose_w(file)
528    gzFile file;
529{
530    int ret = Z_OK;
531    gz_statep state;
532
533    /* get internal structure */
534    if (file == NULL)
535        return Z_STREAM_ERROR;
536    state = (gz_statep)file;
537
538    /* check that we're writing */
539    if (state->mode != GZ_WRITE)
540        return Z_STREAM_ERROR;
541
542    /* check for seek request */
543    if (state->seek) {
544        state->seek = 0;
545        if (gz_zero(state, state->skip) == -1)
546            ret = state->err;
547    }
548
549    /* flush, free memory, and close file */
550    if (state->size) {
551        if (gz_comp(state, Z_FINISH) == -1)
552            ret = state->err;
553        if (!state->direct) {
554            (void)deflateEnd(&(state->strm));
555            free(state->out);
556        }
557        free(state->in);
558    }
559    gz_error(state, Z_OK, NULL);
560    free(state->path);
561    if (close(state->fd) == -1)
562        ret = Z_ERRNO;
563    free(state);
564    return ret;
565}
src/lib/zlib/example.c
r15677r15678
11/* example.c -- usage example of the zlib compression library
2 * Copyright (C) 1995-2004 Jean-loup Gailly.
2 * Copyright (C) 1995-2006, 2011 Jean-loup Gailly.
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
66/* @(#) $Id$ */
77
8#include "zlib.h"
89#include <stdio.h>
9#include "zlib.h"
1010
1111#ifdef STDC
1212#  include <string.h>
r15677r15678
3434const char dictionary[] = "hello";
3535uLong dictId; /* Adler32 value of the dictionary */
3636
37void test_compress      OF((Byte *compr, uLong comprLen,
38                            Byte *uncompr, uLong uncomprLen));
39void test_gzio          OF((const char *fname,
40                            Byte *uncompr, uLong uncomprLen));
4137void test_deflate       OF((Byte *compr, uLong comprLen));
4238void test_inflate       OF((Byte *compr, uLong comprLen,
4339                            Byte *uncompr, uLong uncomprLen));
r15677r15678
5349                            Byte *uncompr, uLong uncomprLen));
5450int  main               OF((int argc, char *argv[]));
5551
52
53#ifdef Z_SOLO
54
55void *myalloc OF((void *, unsigned, unsigned));
56void myfree OF((void *, void *));
57
58void *myalloc(q, n, m)
59    void *q;
60    unsigned n, m;
61{
62    q = Z_NULL;
63    return calloc(n, m);
64}
65
66void myfree(void *q, void *p)
67{
68    q = Z_NULL;
69    free(p);
70}
71
72static alloc_func zalloc = myalloc;
73static free_func zfree = myfree;
74
75#else /* !Z_SOLO */
76
77static alloc_func zalloc = (alloc_func)0;
78static free_func zfree = (free_func)0;
79
80void test_compress      OF((Byte *compr, uLong comprLen,
81                            Byte *uncompr, uLong uncomprLen));
82void test_gzio          OF((const char *fname,
83                            Byte *uncompr, uLong uncomprLen));
84
5685/* ===========================================================================
5786 * Test compress() and uncompress()
5887 */
r15677r15678
163192#endif
164193}
165194
195#endif /* Z_SOLO */
196
166197/* ===========================================================================
167198 * Test deflate() with small buffers
168199 */
r15677r15678
174205    int err;
175206    uLong len = (uLong)strlen(hello)+1;
176207
177    c_stream.zalloc = (alloc_func)0;
178    c_stream.zfree = (free_func)0;
208    c_stream.zalloc = zalloc;
209    c_stream.zfree = zfree;
179210    c_stream.opaque = (voidpf)0;
180211
181212    err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
r15677r15678
213244
214245    strcpy((char*)uncompr, "garbage");
215246
216    d_stream.zalloc = (alloc_func)0;
217    d_stream.zfree = (free_func)0;
247    d_stream.zalloc = zalloc;
248    d_stream.zfree = zfree;
218249    d_stream.opaque = (voidpf)0;
219250
220251    d_stream.next_in  = compr;
r15677r15678
252283    z_stream c_stream; /* compression stream */
253284    int err;
254285
255    c_stream.zalloc = (alloc_func)0;
256    c_stream.zfree = (free_func)0;
286    c_stream.zalloc = zalloc;
287    c_stream.zfree = zfree;
257288    c_stream.opaque = (voidpf)0;
258289
259290    err = deflateInit(&c_stream, Z_BEST_SPEED);
r15677r15678
309340
310341    strcpy((char*)uncompr, "garbage");
311342
312    d_stream.zalloc = (alloc_func)0;
313    d_stream.zfree = (free_func)0;
343    d_stream.zalloc = zalloc;
344    d_stream.zfree = zfree;
314345    d_stream.opaque = (voidpf)0;
315346
316347    d_stream.next_in  = compr;
r15677r15678
349380    int err;
350381    uInt len = (uInt)strlen(hello)+1;
351382
352    c_stream.zalloc = (alloc_func)0;
353    c_stream.zfree = (free_func)0;
383    c_stream.zalloc = zalloc;
384    c_stream.zfree = zfree;
354385    c_stream.opaque = (voidpf)0;
355386
356387    err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
r15677r15678
388419
389420    strcpy((char*)uncompr, "garbage");
390421
391    d_stream.zalloc = (alloc_func)0;
392    d_stream.zfree = (free_func)0;
422    d_stream.zalloc = zalloc;
423    d_stream.zfree = zfree;
393424    d_stream.opaque = (voidpf)0;
394425
395426    d_stream.next_in  = compr;
r15677r15678
430461    z_stream c_stream; /* compression stream */
431462    int err;
432463
433    c_stream.zalloc = (alloc_func)0;
434    c_stream.zfree = (free_func)0;
464    c_stream.zalloc = zalloc;
465    c_stream.zfree = zfree;
435466    c_stream.opaque = (voidpf)0;
436467
437468    err = deflateInit(&c_stream, Z_BEST_COMPRESSION);
438469    CHECK_ERR(err, "deflateInit");
439470
440471    err = deflateSetDictionary(&c_stream,
441                               (const Bytef*)dictionary, sizeof(dictionary));
472                (const Bytef*)dictionary, (int)sizeof(dictionary));
442473    CHECK_ERR(err, "deflateSetDictionary");
443474
444475    dictId = c_stream.adler;
r15677r15678
469500
470501    strcpy((char*)uncompr, "garbage");
471502
472    d_stream.zalloc = (alloc_func)0;
473    d_stream.zfree = (free_func)0;
503    d_stream.zalloc = zalloc;
504    d_stream.zfree = zfree;
474505    d_stream.opaque = (voidpf)0;
475506
476507    d_stream.next_in  = compr;
r15677r15678
491522                exit(1);
492523            }
493524            err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
494                                       sizeof(dictionary));
525                                       (int)sizeof(dictionary));
495526        }
496527        CHECK_ERR(err, "inflate with dict");
497528    }
r15677r15678
540571        printf("out of memory\n");
541572        exit(1);
542573    }
574
575#ifdef Z_SOLO
576    argc = strlen(argv[0]);
577#else
543578    test_compress(compr, comprLen, uncompr, uncomprLen);
544579
545580    test_gzio((argc > 1 ? argv[1] : TESTFILE),
546581              uncompr, uncomprLen);
582#endif
547583
548584    test_deflate(compr, comprLen);
549585    test_inflate(compr, comprLen, uncompr, uncomprLen);
src/lib/zlib/compress.c
r15677r15678
11/* compress.c -- compress a memory buffer
2 * Copyright (C) 1995-2003 Jean-loup Gailly.
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
7575uLong ZEXPORT compressBound (sourceLen)
7676    uLong sourceLen;
7777{
78    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
78    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
79           (sourceLen >> 25) + 13;
7980}
src/lib/zlib/Makefile
r15677r15678
1# Makefile for zlib
2# Copyright (C) 1995-2005 Jean-loup Gailly.
3# For conditions of distribution and use, see copyright notice in zlib.h
1all:
2   -@echo "Please use ./configure first.  Thank you."
43
5# To compile and test, type:
6#    ./configure; make test
7# The call of configure is optional if you don't have special requirements
8# If you wish to build zlib as a shared library, use: ./configure -s
9
10# To use the asm code, type:
11#    cp contrib/asm?86/match.S ./match.S
12#    make LOC=-DASMV OBJA=match.o
13
14# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
15#    make install
16# To install in $HOME instead of /usr/local, use:
17#    make install prefix=$HOME
18
19CC=cc
20
21CFLAGS=-O
22#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
23#CFLAGS=-g -DDEBUG
24#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
25#           -Wstrict-prototypes -Wmissing-prototypes
26
27LDFLAGS=libz.a
28LDSHARED=$(CC)
29CPP=$(CC) -E
30
31LIBS=libz.a
32SHAREDLIB=libz.so
33SHAREDLIBV=libz.so.1.2.3
34SHAREDLIBM=libz.so.1
35
36AR=ar rc
37RANLIB=ranlib
38TAR=tar
39SHELL=/bin/sh
40EXE=
41
42prefix = /usr/local
43exec_prefix = ${prefix}
44libdir = ${exec_prefix}/lib
45includedir = ${prefix}/include
46mandir = ${prefix}/share/man
47man3dir = ${mandir}/man3
48
49OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
50       zutil.o inflate.o infback.o inftrees.o inffast.o
51
52OBJA =
53# to use the asm code: make OBJA=match.o
54
55TEST_OBJS = example.o minigzip.o
56
57all: example$(EXE) minigzip$(EXE)
58
59check: test
60test: all
61   @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
62   echo hello world | ./minigzip | ./minigzip -d || \
63     echo '      *** minigzip test FAILED ***' ; \
64   if ./example; then \
65     echo '      *** zlib test OK ***'; \
66   else \
67     echo '      *** zlib test FAILED ***'; \
68   fi
69
70libz.a: $(OBJS) $(OBJA)
71   $(AR) $@ $(OBJS) $(OBJA)
72   -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
73
74match.o: match.S
75   $(CPP) match.S > _match.s
76   $(CC) -c _match.s
77   mv _match.o match.o
78   rm -f _match.s
79
80$(SHAREDLIBV): $(OBJS)
81   $(LDSHARED) -o $@ $(OBJS)
82   rm -f $(SHAREDLIB) $(SHAREDLIBM)
83   ln -s $@ $(SHAREDLIB)
84   ln -s $@ $(SHAREDLIBM)
85
86example$(EXE): example.o $(LIBS)
87   $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
88
89minigzip$(EXE): minigzip.o $(LIBS)
90   $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
91
92install: $(LIBS)
93   -@if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi
94   -@if [ ! -d $(includedir)  ]; then mkdir -p $(includedir); fi
95   -@if [ ! -d $(libdir)      ]; then mkdir -p $(libdir); fi
96   -@if [ ! -d $(man3dir)     ]; then mkdir -p $(man3dir); fi
97   cp zlib.h zconf.h $(includedir)
98   chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h
99   cp $(LIBS) $(libdir)
100   cd $(libdir); chmod 755 $(LIBS)
101   -@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
102   cd $(libdir); if test -f $(SHAREDLIBV); then \
103     rm -f $(SHAREDLIB) $(SHAREDLIBM); \
104     ln -s $(SHAREDLIBV) $(SHAREDLIB); \
105     ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
106     (ldconfig || true)  >/dev/null 2>&1; \
107   fi
108   cp zlib.3 $(man3dir)
109   chmod 644 $(man3dir)/zlib.3
110# The ranlib in install is needed on NeXTSTEP which checks file times
111# ldconfig is for Linux
112
113uninstall:
114   cd $(includedir); \
115   cd $(libdir); rm -f libz.a; \
116   if test -f $(SHAREDLIBV); then \
117     rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
118   fi
119   cd $(man3dir); rm -f zlib.3
120
121mostlyclean: clean
122clean:
123   rm -f *.o *~ example$(EXE) minigzip$(EXE) \
124      libz.* foo.gz so_locations \
125      _match.s maketree contrib/infback9/*.o
126
127maintainer-clean: distclean
128distclean: clean
129   cp -p Makefile.in Makefile
130   cp -p zconf.in.h zconf.h
131   rm -f .DS_Store
132
133tags:
134   etags *.[ch]
135
136depend:
137   makedepend -- $(CFLAGS) -- *.[ch]
138
139# DO NOT DELETE THIS LINE -- make depend depends on it.
140
141adler32.o: zlib.h zconf.h
142compress.o: zlib.h zconf.h
143crc32.o: crc32.h zlib.h zconf.h
144deflate.o: deflate.h zutil.h zlib.h zconf.h
145example.o: zlib.h zconf.h
146gzio.o: zutil.h zlib.h zconf.h
147inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
148inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
149infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
150inftrees.o: zutil.h zlib.h zconf.h inftrees.h
151minigzip.o: zlib.h zconf.h
152trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
153uncompr.o: zlib.h zconf.h
154zutil.o: zutil.h zlib.h zconf.h
4distclean:
5   make -f Makefile.in distclean
src/lib/zlib/inffast.h
r15677r15678
11/* inffast.h -- header to use inffast.c
2 * Copyright (C) 1995-2003 Mark Adler
2 * Copyright (C) 1995-2003, 2010 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
88   subject to change. Applications should only use zlib.h.
99 */
1010
11void inflate_fast OF((z_streamp strm, unsigned start));
11void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));
src/lib/zlib/zlib.h
r15677r15678
11/* zlib.h -- interface of the 'zlib' general purpose compression library
2  version 1.2.3, July 18th, 2005
2  version 1.2.7, May 2nd, 2012
33
4  Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
4  Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler
55
66  This software is provided 'as-is', without any express or implied
77  warranty.  In no event will the authors be held liable for any damages
r15677r15678
2424
2525
2626  The data format used by the zlib library is described by RFCs (Request for
27  Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
28  (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
27  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
28  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
2929*/
3030
3131#ifndef ZLIB_H
r15677r15678
3737extern "C" {
3838#endif
3939
40#define ZLIB_VERSION "1.2.3"
41#define ZLIB_VERNUM 0x1230
40#define ZLIB_VERSION "1.2.7"
41#define ZLIB_VERNUM 0x1270
42#define ZLIB_VER_MAJOR 1
43#define ZLIB_VER_MINOR 2
44#define ZLIB_VER_REVISION 7
45#define ZLIB_VER_SUBREVISION 0
4246
4347/*
44     The 'zlib' compression library provides in-memory compression and
45  decompression functions, including integrity checks of the uncompressed
46  data.  This version of the library supports only one compression method
47  (deflation) but other algorithms will be added later and will have the same
48  stream interface.
48    The 'zlib' compression library provides in-memory compression and
49  decompression functions, including integrity checks of the uncompressed data.
50  This version of the library supports only one compression method (deflation)
51  but other algorithms will be added later and will have the same stream
52  interface.
4953
50     Compression can be done in a single step if the buffers are large
51  enough (for example if an input file is mmap'ed), or can be done by
52  repeated calls of the compression function.  In the latter case, the
53  application must provide more input and/or consume the output
54    Compression can be done in a single step if the buffers are large enough,
55  or can be done by repeated calls of the compression function.  In the latter
56  case, the application must provide more input and/or consume the output
5457  (providing more output space) before each call.
5558
56    The compressed data format used by default by the in-memory functions is
59    The compressed data format used by default by the in-memory functions is
5760  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
5861  around a deflate stream, which is itself documented in RFC 1951.
5962
60    The library also supports reading and writing files in gzip (.gz) format
63    The library also supports reading and writing files in gzip (.gz) format
6164  with an interface similar to that of stdio using the functions that start
6265  with "gz".  The gzip format is different from the zlib format.  gzip is a
6366  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
6467
65    This library can optionally read and write gzip streams in memory as well.
68    This library can optionally read and write gzip streams in memory as well.
6669
67    The zlib format was designed to be compact and fast for use in memory
70    The zlib format was designed to be compact and fast for use in memory
6871  and on communications channels.  The gzip format was designed for single-
6972  file compression on file systems, has a larger header than zlib to maintain
7073  directory information, and uses a different, slower check method than zlib.
7174
72     The library does not install any signal handler. The decoder checks
73  the consistency of the compressed data, so the library should never
74  crash even in case of corrupted input.
75    The library does not install any signal handler.  The decoder checks
76  the consistency of the compressed data, so the library should never crash
77  even in case of corrupted input.
7578*/
7679
7780typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
r15677r15678
8083struct internal_state;
8184
8285typedef struct z_stream_s {
83    Bytef    *next_in;  /* next input byte */
86    z_const Bytef *next_in;     /* next input byte */
8487    uInt     avail_in;  /* number of bytes available at next_in */
85    uLong    total_in;  /* total nb of input bytes read so far */
88    uLong    total_in;  /* total number of input bytes read so far */
8689
8790    Bytef    *next_out; /* next output byte should be put there */
8891    uInt     avail_out; /* remaining free space at next_out */
89    uLong    total_out; /* total nb of bytes output so far */
92    uLong    total_out; /* total number of bytes output so far */
9093
91    char     *msg;      /* last error message, NULL if no error */
94    z_const char *msg;  /* last error message, NULL if no error */
9295    struct internal_state FAR *state; /* not visible by applications */
9396
9497    alloc_func zalloc;  /* used to allocate the internal state */
r15677r15678
126129typedef gz_header FAR *gz_headerp;
127130
128131/*
129   The application must update next_in and avail_in when avail_in has
130   dropped to zero. It must update next_out and avail_out when avail_out
131   has dropped to zero. The application must initialize zalloc, zfree and
132   opaque before calling the init function. All other fields are set by the
133   compression library and must not be updated by the application.
132     The application must update next_in and avail_in when avail_in has dropped
133   to zero.  It must update next_out and avail_out when avail_out has dropped
134   to zero.  The application must initialize zalloc, zfree and opaque before
135   calling the init function.  All other fields are set by the compression
136   library and must not be updated by the application.
134137
135   The opaque value provided by the application will be passed as the first
136   parameter for calls of zalloc and zfree. This can be useful for custom
137   memory management. The compression library attaches no meaning to the
138     The opaque value provided by the application will be passed as the first
139   parameter for calls of zalloc and zfree.  This can be useful for custom
140   memory management.  The compression library attaches no meaning to the
138141   opaque value.
139142
140   zalloc must return Z_NULL if there is not enough memory for the object.
143     zalloc must return Z_NULL if there is not enough memory for the object.
141144   If zlib is used in a multi-threaded application, zalloc and zfree must be
142145   thread safe.
143146
144   On 16-bit systems, the functions zalloc and zfree must be able to allocate
145   exactly 65536 bytes, but will not be required to allocate more than this
146   if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
147   pointers returned by zalloc for objects of exactly 65536 bytes *must*
148   have their offset normalized to zero. The default allocation function
149   provided by this library ensures this (see zutil.c). To reduce memory
150   requirements and avoid any allocation of 64K objects, at the expense of
151   compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
147     On 16-bit systems, the functions zalloc and zfree must be able to allocate
148   exactly 65536 bytes, but will not be required to allocate more than this if
149   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers
150   returned by zalloc for objects of exactly 65536 bytes *must* have their
151   offset normalized to zero.  The default allocation function provided by this
152   library ensures this (see zutil.c).  To reduce memory requirements and avoid
153   any allocation of 64K objects, at the expense of compression ratio, compile
154   the library with -DMAX_WBITS=14 (see zconf.h).
152155
153   The fields total_in and total_out can be used for statistics or
154   progress reports. After compression, total_in holds the total size of
155   the uncompressed data and may be saved for use in the decompressor
156   (particularly if the decompressor wants to decompress everything in
157   a single step).
156     The fields total_in and total_out can be used for statistics or progress
157   reports.  After compression, total_in holds the total size of the
158   uncompressed data and may be saved for use in the decompressor (particularly
159   if the decompressor wants to decompress everything in a single step).
158160*/
159161
160162                        /* constants */
161163
162164#define Z_NO_FLUSH      0
163#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
165#define Z_PARTIAL_FLUSH 1
164166#define Z_SYNC_FLUSH    2
165167#define Z_FULL_FLUSH    3
166168#define Z_FINISH        4
167169#define Z_BLOCK         5
170#define Z_TREES         6
168171/* Allowed flush values; see deflate() and inflate() below for details */
169172
170173#define Z_OK            0
r15677r15678
176179#define Z_MEM_ERROR    (-4)
177180#define Z_BUF_ERROR    (-5)
178181#define Z_VERSION_ERROR (-6)
179/* Return codes for the compression/decompression functions. Negative
180 * values are errors, positive values are used for special but normal events.
182/* Return codes for the compression/decompression functions. Negative values
183 * are errors, positive values are used for special but normal events.
181184 */
182185
183186#define Z_NO_COMPRESSION         0
r15677r15678
207210#define zlib_version zlibVersion()
208211/* for compatibility with versions < 1.0.2 */
209212
213
210214                        /* basic functions */
211215
212216ZEXTERN const char * ZEXPORT zlibVersion OF((void));
213217/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
214   If the first character differs, the library code actually used is
215   not compatible with the zlib.h header file used by the application.
216   This check is automatically made by deflateInit and inflateInit.
218   If the first character differs, the library code actually used is not
219   compatible with the zlib.h header file used by the application.  This check
220   is automatically made by deflateInit and inflateInit.
217221 */
218222
219223/*
220224ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
221225
222     Initializes the internal stream state for compression. The fields
223   zalloc, zfree and opaque must be initialized before by the caller.
224   If zalloc and zfree are set to Z_NULL, deflateInit updates them to
225   use default allocation functions.
226     Initializes the internal stream state for compression.  The fields
227   zalloc, zfree and opaque must be initialized before by the caller.  If
228   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
229   allocation functions.
226230
227231     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
228   1 gives best speed, 9 gives best compression, 0 gives no compression at
229   all (the input data is simply copied a block at a time).
230   Z_DEFAULT_COMPRESSION requests a default compromise between speed and
231   compression (currently equivalent to level 6).
232   1 gives best speed, 9 gives best compression, 0 gives no compression at all
233   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION
234   requests a default compromise between speed and compression (currently
235   equivalent to level 6).
232236
233     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
234   enough memory, Z_STREAM_ERROR if level is not a valid compression level,
237     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
238   memory, Z_STREAM_ERROR if level is not a valid compression level, or
235239   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
236   with the version assumed by the caller (ZLIB_VERSION).
237   msg is set to null if there is no error message.  deflateInit does not
238   perform any compression: this will be done by deflate().
240   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null
241   if there is no error message.  deflateInit does not perform any compression:
242   this will be done by deflate().
239243*/
240244
241245
242246ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
243247/*
244248    deflate compresses as much data as possible, and stops when the input
245  buffer becomes empty or the output buffer becomes full. It may introduce some
246  output latency (reading input without producing any output) except when
249  buffer becomes empty or the output buffer becomes full.  It may introduce
250  some output latency (reading input without producing any output) except when
247251  forced to flush.
248252
249    The detailed semantics are as follows. deflate performs one or both of the
253    The detailed semantics are as follows. deflate performs one or both of the
250254  following actions:
251255
252256  - Compress more input starting at next_in and update next_in and avail_in
253    accordingly. If not all input can be processed (because there is not
257    accordingly. If not all input can be processed (because there is not
254258    enough room in the output buffer), next_in and avail_in are updated and
255259    processing will resume at this point for the next call of deflate().
256260
257261  - Provide more output starting at next_out and update next_out and avail_out
258    accordingly. This action is forced if the parameter flush is non zero.
262    accordingly. This action is forced if the parameter flush is non zero.
259263    Forcing flush frequently degrades the compression ratio, so this parameter
260    should be set only when necessary (in interactive applications).
261    Some output may be provided even if flush is not set.
264    should be set only when necessary (in interactive applications).  Some
265    output may be provided even if flush is not set.
262266
263  Before the call of deflate(), the application should ensure that at least
264  one of the actions is possible, by providing more input and/or consuming
265  more output, and updating avail_in or avail_out accordingly; avail_out
266  should never be zero before the call. The application can consume the
267  compressed output when it wants, for example when the output buffer is full
268  (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
269  and with zero avail_out, it must be called again after making room in the
270  output buffer because there might be more output pending.
267    Before the call of deflate(), the application should ensure that at least
268  one of the actions is possible, by providing more input and/or consuming more
269  output, and updating avail_in or avail_out accordingly; avail_out should
270  never be zero before the call.  The application can consume the compressed
271  output when it wants, for example when the output buffer is full (avail_out
272  == 0), or after each call of deflate().  If deflate returns Z_OK and with
273  zero avail_out, it must be called again after making room in the output
274  buffer because there might be more output pending.
271275
272276    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
273  decide how much data to accumualte before producing output, in order to
277  decide how much data to accumulate before producing output, in order to
274278  maximize compression.
275279
276280    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
277281  flushed to the output buffer and the output is aligned on a byte boundary, so
278  that the decompressor can get all input data available so far. (In particular
279  avail_in is zero after the call if enough output space has been provided
280  before the call.)  Flushing may degrade compression for some compression
281  algorithms and so it should be used only when necessary.
282  that the decompressor can get all input data available so far.  (In
283  particular avail_in is zero after the call if enough output space has been
284  provided before the call.) Flushing may degrade compression for some
285  compression algorithms and so it should be used only when necessary.  This
286  completes the current deflate block and follows it with an empty stored block
287  that is three bits plus filler bits to the next byte, followed by four bytes
288  (00 00 ff ff).
282289
290    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
291  output buffer, but the output is not aligned to a byte boundary.  All of the
292  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
293  This completes the current deflate block and follows it with an empty fixed
294  codes block that is 10 bits long.  This assures that enough bytes are output
295  in order for the decompressor to finish the block before the empty fixed code
296  block.
297
298    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
299  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
300  seven bits of the current block are held to be written as the next byte after
301  the next deflate block is completed.  In this case, the decompressor may not
302  be provided enough bits at this point in order to complete decompression of
303  the data provided so far to the compressor.  It may need to wait for the next
304  block to be emitted.  This is for advanced applications that need to control
305  the emission of deflate blocks.
306
283307    If flush is set to Z_FULL_FLUSH, all output is flushed as with
284308  Z_SYNC_FLUSH, and the compression state is reset so that decompression can
285309  restart from this point if previous compressed data has been damaged or if
286  random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
310  random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
287311  compression.
288312
289313    If deflate returns with avail_out == 0, this function must be called again
290314  with the same value of the flush parameter and more output space (updated
291315  avail_out), until the flush is complete (deflate returns with non-zero
292  avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
316  avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
293317  avail_out is greater than six to avoid repeated flush markers due to
294318  avail_out == 0 on return.
295319
296320    If the parameter flush is set to Z_FINISH, pending input is processed,
297  pending output is flushed and deflate returns with Z_STREAM_END if there
298  was enough output space; if deflate returns with Z_OK, this function must be
321  pending output is flushed and deflate returns with Z_STREAM_END if there was
322  enough output space; if deflate returns with Z_OK, this function must be
299323  called again with Z_FINISH and more output space (updated avail_out) but no
300  more input data, until it returns with Z_STREAM_END or an error. After
301  deflate has returned Z_STREAM_END, the only possible operations on the
302  stream are deflateReset or deflateEnd.
324  more input data, until it returns with Z_STREAM_END or an error.  After
325  deflate has returned Z_STREAM_END, the only possible operations on the stream
326  are deflateReset or deflateEnd.
303327
304328    Z_FINISH can be used immediately after deflateInit if all the compression
305  is to be done in a single step. In this case, avail_out must be at least
306  the value returned by deflateBound (see below). If deflate does not return
307  Z_STREAM_END, then it must be called again as described above.
329  is to be done in a single step.  In this case, avail_out must be at least the
330  value returned by deflateBound (see below).  Then deflate is guaranteed to
331  return Z_STREAM_END.  If not enough output space is provided, deflate will
332  not return Z_STREAM_END, and it must be called again as described above.
308333
309334    deflate() sets strm->adler to the adler32 checksum of all input read
310335  so far (that is, total_in bytes).
311336
312337    deflate() may update strm->data_type if it can make a good guess about
313  the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
314  binary. This field is only for information purposes and does not affect
315  the compression algorithm in any manner.
338  the input data type (Z_BINARY or Z_TEXT).  In doubt, the data is considered
339  binary.  This field is only for information purposes and does not affect the
340  compression algorithm in any manner.
316341
317342    deflate() returns Z_OK if some progress has been made (more input
318343  processed or more output produced), Z_STREAM_END if all input has been
319344  consumed and all output has been produced (only when flush is set to
320345  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
321  if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
322  (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
346  if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible
347  (for example avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not
323348  fatal, and deflate() can be called again with more input and more output
324349  space to continue compressing.
325350*/
r15677r15678
328353ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
329354/*
330355     All dynamically allocated data structures for this stream are freed.
331   This function discards any unprocessed input and does not flush any
332   pending output.
356   This function discards any unprocessed input and does not flush any pending
357   output.
333358
334359     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
335360   stream state was inconsistent, Z_DATA_ERROR if the stream was freed
336   prematurely (some input or output was discarded). In the error case,
337   msg may be set but then points to a static string (which must not be
361   prematurely (some input or output was discarded).  In the error case, msg
362   may be set but then points to a static string (which must not be
338363   deallocated).
339364*/
340365
r15677r15678
342367/*
343368ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
344369
345     Initializes the internal stream state for decompression. The fields
370     Initializes the internal stream state for decompression. The fields
346371   next_in, avail_in, zalloc, zfree and opaque must be initialized before by
347   the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
348   value depends on the compression method), inflateInit determines the
372   the caller.  If next_in is not Z_NULL and avail_in is large enough (the
373   exact value depends on the compression method), inflateInit determines the
349374   compression method from the zlib header and allocates all data structures
350375   accordingly; otherwise the allocation will be deferred to the first call of
351376   inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
r15677r15678
353378
354379     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
355380   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
356   version assumed by the caller.  msg is set to null if there is no error
357   message. inflateInit does not perform any decompression apart from reading
358   the zlib header if present: this will be done by inflate().  (So next_in and
359   avail_in may be modified, but next_out and avail_out are unchanged.)
381   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
382   invalid, such as a null pointer to the structure.  msg is set to null if
383   there is no error message.  inflateInit does not perform any decompression
384   apart from possibly reading the zlib header if present: actual decompression
385   will be done by inflate().  (So next_in and avail_in may be modified, but
386   next_out and avail_out are unused and unchanged.) The current implementation
387   of inflateInit() does not process any header information -- that is deferred
388   until inflate() is called.
360389*/
361390
362391
363392ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
364393/*
365394    inflate decompresses as much data as possible, and stops when the input
366  buffer becomes empty or the output buffer becomes full. It may introduce
395  buffer becomes empty or the output buffer becomes full. It may introduce
367396  some output latency (reading input without producing any output) except when
368397  forced to flush.
369398
370  The detailed semantics are as follows. inflate performs one or both of the
399  The detailed semantics are as follows. inflate performs one or both of the
371400  following actions:
372401
373402  - Decompress more input starting at next_in and update next_in and avail_in
374    accordingly. If not all input can be processed (because there is not
375    enough room in the output buffer), next_in is updated and processing
376    will resume at this point for the next call of inflate().
403    accordingly.  If not all input can be processed (because there is not
404    enough room in the output buffer), next_in is updated and processing will
405    resume at this point for the next call of inflate().
377406
378407  - Provide more output starting at next_out and update next_out and avail_out
379    accordingly.  inflate() provides as much output as possible, until there
380    is no more input data or no more space in the output buffer (see below
381    about the flush parameter).
408    accordingly.  inflate() provides as much output as possible, until there is
409    no more input data or no more space in the output buffer (see below about
410    the flush parameter).
382411
383  Before the call of inflate(), the application should ensure that at least
384  one of the actions is possible, by providing more input and/or consuming
385  more output, and updating the next_* and avail_* values accordingly.
386  The application can consume the uncompressed output when it wants, for
387  example when the output buffer is full (avail_out == 0), or after each
388  call of inflate(). If inflate returns Z_OK and with zero avail_out, it
389  must be called again after making room in the output buffer because there
390  might be more output pending.
412    Before the call of inflate(), the application should ensure that at least
413  one of the actions is possible, by providing more input and/or consuming more
414  output, and updating the next_* and avail_* values accordingly.  The
415  application can consume the uncompressed output when it wants, for example
416  when the output buffer is full (avail_out == 0), or after each call of
417  inflate().  If inflate returns Z_OK and with zero avail_out, it must be
418  called again after making room in the output buffer because there might be
419  more output pending.
391420
392    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
393  Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
394  output as possible to the output buffer. Z_BLOCK requests that inflate() stop
395  if and when it gets to the next deflate block boundary. When decoding the
396  zlib or gzip format, this will cause inflate() to return immediately after
397  the header and before the first block. When doing a raw inflate, inflate()
398  will go ahead and process the first block, and will return when it gets to
399  the end of that block, or when it runs out of data.
421    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
422  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
423  output as possible to the output buffer.  Z_BLOCK requests that inflate()
424  stop if and when it gets to the next deflate block boundary.  When decoding
425  the zlib or gzip format, this will cause inflate() to return immediately
426  after the header and before the first block.  When doing a raw inflate,
427  inflate() will go ahead and process the first block, and will return when it
428  gets to the end of that block, or when it runs out of data.
400429
401430    The Z_BLOCK option assists in appending to or combining deflate streams.
402431  Also to assist in this, on return inflate() will set strm->data_type to the
403  number of unused bits in the last byte taken from strm->next_in, plus 64
404  if inflate() is currently decoding the last block in the deflate stream,
405  plus 128 if inflate() returned immediately after decoding an end-of-block
406  code or decoding the complete header up to just before the first byte of the
407  deflate stream. The end-of-block will not be indicated until all of the
408  uncompressed data from that block has been written to strm->next_out.  The
409  number of unused bits may in general be greater than seven, except when
410  bit 7 of data_type is set, in which case the number of unused bits will be
411  less than eight.
432  number of unused bits in the last byte taken from strm->next_in, plus 64 if
433  inflate() is currently decoding the last block in the deflate stream, plus
434  128 if inflate() returned immediately after decoding an end-of-block code or
435  decoding the complete header up to just before the first byte of the deflate
436  stream.  The end-of-block will not be indicated until all of the uncompressed
437  data from that block has been written to strm->next_out.  The number of
438  unused bits may in general be greater than seven, except when bit 7 of
439  data_type is set, in which case the number of unused bits will be less than
440  eight.  data_type is set as noted here every time inflate() returns for all
441  flush options, and so can be used to determine the amount of currently
442  consumed input in bits.
412443
444    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
445  end of each deflate block header is reached, before any actual data in that
446  block is decoded.  This allows the caller to determine the length of the
447  deflate block header for later use in random access within a deflate block.
448  256 is added to the value of strm->data_type when inflate() returns
449  immediately after reaching the end of the deflate block header.
450
413451    inflate() should normally be called until it returns Z_STREAM_END or an
414  error. However if all decompression is to be performed in a single step
415  (a single call of inflate), the parameter flush should be set to
416  Z_FINISH. In this case all pending input is processed and all pending
417  output is flushed; avail_out must be large enough to hold all the
418  uncompressed data. (The size of the uncompressed data may have been saved
419  by the compressor for this purpose.) The next operation on this stream must
420  be inflateEnd to deallocate the decompression state. The use of Z_FINISH
421  is never required, but can be used to inform inflate that a faster approach
422  may be used for the single inflate() call.
452  error.  However if all decompression is to be performed in a single step (a
453  single call of inflate), the parameter flush should be set to Z_FINISH.  In
454  this case all pending input is processed and all pending output is flushed;
455  avail_out must be large enough to hold all of the uncompressed data for the
456  operation to complete.  (The size of the uncompressed data may have been
457  saved by the compressor for this purpose.) The use of Z_FINISH is not
458  required to perform an inflation in one step.  However it may be used to
459  inform inflate that a faster approach can be used for the single inflate()
460  call.  Z_FINISH also informs inflate to not maintain a sliding window if the
461  stream completes, which reduces inflate's memory footprint.  If the stream
462  does not complete, either because not all of the stream is provided or not
463  enough output space is provided, then a sliding window will be allocated and
464  inflate() can be called again to continue the operation as if Z_NO_FLUSH had
465  been used.
423466
424467     In this implementation, inflate() always flushes as much output as
425468  possible to the output buffer, and always uses the faster approach on the
426  first call. So the only effect of the flush parameter in this implementation
427  is on the return value of inflate(), as noted below, or when it returns early
428  because Z_BLOCK is used.
469  first call.  So the effects of the flush parameter in this implementation are
470  on the return value of inflate() as noted below, when inflate() returns early
471  when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
472  memory for a sliding window when Z_FINISH is used.
429473
430474     If a preset dictionary is needed after this call (see inflateSetDictionary
431  below), inflate sets strm->adler to the adler32 checksum of the dictionary
475  below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
432476  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
433  strm->adler to the adler32 checksum of all output produced so far (that is,
477  strm->adler to the Adler-32 checksum of all output produced so far (that is,
434478  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
435  below. At the end of the stream, inflate() checks that its computed adler32
479  below. At the end of the stream, inflate() checks that its computed adler32
436480  checksum is equal to that saved by the compressor and returns Z_STREAM_END
437481  only if the checksum is correct.
438482
439    inflate() will decompress and check either zlib-wrapped or gzip-wrapped
440  deflate data.  The header type is detected automatically.  Any information
441  contained in the gzip header is not retained, so applications that need that
442  information should instead use raw inflate, see inflateInit2() below, or
443  inflateBack() and perform their own processing of the gzip header and
444  trailer.
483    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
484  deflate data.  The header type is detected automatically, if requested when
485  initializing with inflateInit2().  Any information contained in the gzip
486  header is not retained, so applications that need that information should
487  instead use raw inflate, see inflateInit2() below, or inflateBack() and
488  perform their own processing of the gzip header and trailer.  When processing
489  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
490  producted so far.  The CRC-32 is checked against the gzip trailer.
445491
446492    inflate() returns Z_OK if some progress has been made (more input processed
447493  or more output produced), Z_STREAM_END if the end of the compressed data has
r15677r15678
449495  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
450496  corrupted (input stream not conforming to the zlib format or incorrect check
451497  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
452  if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
498  next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory,
453499  Z_BUF_ERROR if no progress is possible or if there was not enough room in the
454  output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
500  output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
455501  inflate() can be called again with more input and more output space to
456  continue decompressing. If Z_DATA_ERROR is returned, the application may then
457  call inflateSync() to look for a good compression block if a partial recovery
458  of the data is desired.
502  continue decompressing.  If Z_DATA_ERROR is returned, the application may
503  then call inflateSync() to look for a good compression block if a partial
504  recovery of the data is desired.
459505*/
460506
461507
462508ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
463509/*
464510     All dynamically allocated data structures for this stream are freed.
465   This function discards any unprocessed input and does not flush any
466   pending output.
511   This function discards any unprocessed input and does not flush any pending
512   output.
467513
468514     inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
469   was inconsistent. In the error case, msg may be set but then points to a
515   was inconsistent. In the error case, msg may be set but then points to a
470516   static string (which must not be deallocated).
471517*/
472518
519
473520                        /* Advanced functions */
474521
475522/*
r15677r15678
484531                                     int  memLevel,
485532                                     int  strategy));
486533
487     This is another version of deflateInit with more compression options. The
488   fields next_in, zalloc, zfree and opaque must be initialized before by
489   the caller.
534     This is another version of deflateInit with more compression options.  The
535   fields next_in, zalloc, zfree and opaque must be initialized before by the
536   caller.
490537
491     The method parameter is the compression method. It must be Z_DEFLATED in
538     The method parameter is the compression method. It must be Z_DEFLATED in
492539   this version of the library.
493540
494541     The windowBits parameter is the base two logarithm of the window size
495   (the size of the history buffer). It should be in the range 8..15 for this
496   version of the library. Larger values of this parameter result in better
497   compression at the expense of memory usage. The default value is 15 if
542   (the size of the history buffer).  It should be in the range 8..15 for this
543   version of the library.  Larger values of this parameter result in better
544   compression at the expense of memory usage.  The default value is 15 if
498545   deflateInit is used instead.
499546
500     windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
501   determines the window size. deflate() will then generate raw deflate data
547     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits
548   determines the window size.  deflate() will then generate raw deflate data
502549   with no zlib header or trailer, and will not compute an adler32 check value.
503550
504     windowBits can also be greater than 15 for optional gzip encoding. Add
551     windowBits can also be greater than 15 for optional gzip encoding. Add
505552   16 to windowBits to write a simple gzip header and trailer around the
506   compressed data instead of a zlib wrapper. The gzip header will have no
507   file name, no extra data, no comment, no modification time (set to zero),
508   no header crc, and the operating system will be set to 255 (unknown).  If a
553   compressed data instead of a zlib wrapper.  The gzip header will have no
554   file name, no extra data, no comment, no modification time (set to zero), no
555   header crc, and the operating system will be set to 255 (unknown).  If a
509556   gzip stream is being written, strm->adler is a crc32 instead of an adler32.
510557
511558     The memLevel parameter specifies how much memory should be allocated
512   for the internal compression state. memLevel=1 uses minimum memory but
513   is slow and reduces compression ratio; memLevel=9 uses maximum memory
514   for optimal speed. The default value is 8. See zconf.h for total memory
515   usage as a function of windowBits and memLevel.
559   for the internal compression state.  memLevel=1 uses minimum memory but is
560   slow and reduces compression ratio; memLevel=9 uses maximum memory for
561   optimal speed.  The default value is 8.  See zconf.h for total memory usage
562   as a function of windowBits and memLevel.
516563
517     The strategy parameter is used to tune the compression algorithm. Use the
564     The strategy parameter is used to tune the compression algorithm. Use the
518565   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
519566   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
520567   string match), or Z_RLE to limit match distances to one (run-length
521   encoding). Filtered data consists mostly of small values with a somewhat
522   random distribution. In this case, the compression algorithm is tuned to
523   compress them better. The effect of Z_FILTERED is to force more Huffman
568   encoding).  Filtered data consists mostly of small values with a somewhat
569   random distribution.  In this case, the compression algorithm is tuned to
570   compress them better.  The effect of Z_FILTERED is to force more Huffman
524571   coding and less string matching; it is somewhat intermediate between
525   Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
526   Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
527   parameter only affects the compression ratio but not the correctness of the
528   compressed output even if it is not set appropriately.  Z_FIXED prevents the
529   use of dynamic Huffman codes, allowing for a simpler decoder for special
530   applications.
572   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
573   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
574   strategy parameter only affects the compression ratio but not the
575   correctness of the compressed output even if it is not set appropriately.
576   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
577   decoder for special applications.
531578
532      deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
533   memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
534   method). msg is set to null if there is no error message.  deflateInit2 does
535   not perform any compression: this will be done by deflate().
579     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
580   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
581   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
582   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
583   set to null if there is no error message.  deflateInit2 does not perform any
584   compression: this will be done by deflate().
536585*/
537586
538587ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
r15677r15678
540589                                             uInt  dictLength));
541590/*
542591     Initializes the compression dictionary from the given byte sequence
543   without producing any compressed output. This function must be called
544   immediately after deflateInit, deflateInit2 or deflateReset, before any
545   call of deflate. The compressor and decompressor must use exactly the same
546   dictionary (see inflateSetDictionary).
592   without producing any compressed output.  When using the zlib format, this
593   function must be called immediately after deflateInit, deflateInit2 or
594   deflateReset, and before any call of deflate.  When doing raw deflate, this
595   function must be called either before any call of deflate, or immediately
596   after the completion of a deflate block, i.e. after all input has been
597   consumed and all output has been delivered when using any of the flush
598   options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH.  The
599   compressor and decompressor must use exactly the same dictionary (see
600   inflateSetDictionary).
547601
548602     The dictionary should consist of strings (byte sequences) that are likely
549603   to be encountered later in the data to be compressed, with the most commonly
550   used strings preferably put towards the end of the dictionary. Using a
604   used strings preferably put towards the end of the dictionary. Using a
551605   dictionary is most useful when the data to be compressed is short and can be
552606   predicted with good accuracy; the data can then be compressed better than
553607   with the default empty dictionary.
554608
555609     Depending on the size of the compression data structures selected by
556610   deflateInit or deflateInit2, a part of the dictionary may in effect be
557   discarded, for example if the dictionary is larger than the window size in
558   deflate or deflate2. Thus the strings most likely to be useful should be
559   put at the end of the dictionary, not at the front. In addition, the
560   current implementation of deflate will use at most the window size minus
561   262 bytes of the provided dictionary.
611   discarded, for example if the dictionary is larger than the window size
612   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
613   useful should be put at the end of the dictionary, not at the front.  In
614   addition, the current implementation of deflate will use at most the window
615   size minus 262 bytes of the provided dictionary.
562616
563617     Upon return of this function, strm->adler is set to the adler32 value
564618   of the dictionary; the decompressor may later use this value to determine
565   which dictionary has been used by the compressor. (The adler32 value
619   which dictionary has been used by the compressor. (The adler32 value
566620   applies to the whole dictionary even if only a subset of the dictionary is
567621   actually used by the compressor.) If a raw deflate was requested, then the
568622   adler32 value is not computed and strm->adler is not set.
569623
570624     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
571   parameter is invalid (such as NULL dictionary) or the stream state is
625   parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
572626   inconsistent (for example if deflate has already been called for this stream
573   or if the compression method is bsort). deflateSetDictionary does not
574   perform any compression: this will be done by deflate().
627   or if not at a block boundary for raw deflate).  deflateSetDictionary does
628   not perform any compression: this will be done by deflate().
575629*/
576630
577631ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
r15677r15678
581635
582636     This function can be useful when several compression strategies will be
583637   tried, for example when there are several ways of pre-processing the input
584   data with a filter. The streams that will be discarded should then be freed
638   data with a filter. The streams that will be discarded should then be freed
585639   by calling deflateEnd.  Note that deflateCopy duplicates the internal
586   compression state which can be quite large, so this strategy is slow and
587   can consume lots of memory.
640   compression state which can be quite large, so this strategy is slow and can
641   consume lots of memory.
588642
589643     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
590644   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
591   (such as zalloc being NULL). msg is left unchanged in both source and
645   (such as zalloc being Z_NULL). msg is left unchanged in both source and
592646   destination.
593647*/
594648
595649ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
596650/*
597651     This function is equivalent to deflateEnd followed by deflateInit,
598   but does not free and reallocate all the internal compression state.
599   The stream will keep the same compression level and any other attributes
600   that may have been set by deflateInit2.
652   but does not free and reallocate all the internal compression state.  The
653   stream will keep the same compression level and any other attributes that
654   may have been set by deflateInit2.
601655
602      deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
603   stream state was inconsistent (such as zalloc or state being NULL).
656     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
657   stream state was inconsistent (such as zalloc or state being Z_NULL).
604658*/
605659
606660ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
r15677r15678
610664     Dynamically update the compression level and compression strategy.  The
611665   interpretation of level and strategy is as in deflateInit2.  This can be
612666   used to switch between compression and straight copy of the input data, or
613   to switch to a different kind of input data requiring a different
614   strategy. If the compression level is changed, the input available so far
615   is compressed with the old level (and may be flushed); the new level will
616   take effect only at the next call of deflate().
667   to switch to a different kind of input data requiring a different strategy.
668   If the compression level is changed, the input available so far is
669   compressed with the old level (and may be flushed); the new level will take
670   effect only at the next call of deflate().
617671
618672     Before the call of deflateParams, the stream state must be set as for
619   a call of deflate(), since the currently available input may have to
620   be compressed and flushed. In particular, strm->avail_out must be non-zero.
673   a call of deflate(), since the currently available input may have to be
674   compressed and flushed.  In particular, strm->avail_out must be non-zero.
621675
622676     deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
623   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
624   if strm->avail_out was zero.
677   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if
678   strm->avail_out was zero.
625679*/
626680
627681ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
r15677r15678
645699                                       uLong sourceLen));
646700/*
647701     deflateBound() returns an upper bound on the compressed size after
648   deflation of sourceLen bytes.  It must be called after deflateInit()
649   or deflateInit2().  This would be used to allocate an output buffer
650   for deflation in a single pass, and so would be called before deflate().
702   deflation of sourceLen bytes.  It must be called after deflateInit() or
703   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
704   to allocate an output buffer for deflation in a single pass, and so would be
705   called before deflate().  If that first deflate() call is provided the
706   sourceLen input bytes, an output buffer allocated to the size returned by
707   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
708   to return Z_STREAM_END.  Note that it is possible for the compressed size to
709   be larger than the value returned by deflateBound() if flush options other
710   than Z_FINISH or Z_NO_FLUSH are used.
651711*/
652712
713ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm,
714                                       unsigned *pending,
715                                       int *bits));
716/*
717     deflatePending() returns the number of bytes and bits of output that have
718   been generated, but not yet provided in the available output.  The bytes not
719   provided would be due to the available output space having being consumed.
720   The number of bits of output not provided are between 0 and 7, where they
721   await more bits to join them in order to fill out a full byte.  If pending
722   or bits are Z_NULL, then those values are not set.
723
724     deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
725   stream state was inconsistent.
726 */
727
653728ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
654729                                     int bits,
655730                                     int value));
656731/*
657732     deflatePrime() inserts bits in the deflate output stream.  The intent
658  is that this function is used to start off the deflate output with the
659  bits leftover from a previous deflate stream when appending to it.  As such,
660  this function can only be used for raw deflate, and must be used before the
661  first deflate() call after a deflateInit2() or deflateReset().  bits must be
662  less than or equal to 16, and that many of the least significant bits of
663  value will be inserted in the output.
733   is that this function is used to start off the deflate output with the bits
734   leftover from a previous deflate stream when appending to it.  As such, this
735   function can only be used for raw deflate, and must be used before the first
736   deflate() call after a deflateInit2() or deflateReset().  bits must be less
737   than or equal to 16, and that many of the least significant bits of value
738   will be inserted in the output.
664739
665      deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
666   stream state was inconsistent.
740     deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
741   room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
742   source stream state was inconsistent.
667743*/
668744
669745ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
670746                                         gz_headerp head));
671747/*
672      deflateSetHeader() provides gzip header information for when a gzip
748     deflateSetHeader() provides gzip header information for when a gzip
673749   stream is requested by deflateInit2().  deflateSetHeader() may be called
674750   after deflateInit2() or deflateReset() and before the first call of
675751   deflate().  The text, time, os, extra field, name, and comment information
r15677r15678
682758   1.3.x) do not support header crc's, and will report that it is a "multi-part
683759   gzip file" and give up.
684760
685      If deflateSetHeader is not used, the default gzip header has text false,
761     If deflateSetHeader is not used, the default gzip header has text false,
686762   the time set to zero, and os set to 255, with no extra, name, or comment
687763   fields.  The gzip header is returned to the default state by deflateReset().
688764
689      deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
765     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
690766   stream state was inconsistent.
691767*/
692768
r15677r15678
694770ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
695771                                     int  windowBits));
696772
697     This is another version of inflateInit with an extra parameter. The
773     This is another version of inflateInit with an extra parameter. The
698774   fields next_in, avail_in, zalloc, zfree and opaque must be initialized
699775   before by the caller.
700776
701777     The windowBits parameter is the base two logarithm of the maximum window
702778   size (the size of the history buffer).  It should be in the range 8..15 for
703   this version of the library. The default value is 15 if inflateInit is used
704   instead. windowBits must be greater than or equal to the windowBits value
779   this version of the library.  The default value is 15 if inflateInit is used
780   instead.  windowBits must be greater than or equal to the windowBits value
705781   provided to deflateInit2() while compressing, or it must be equal to 15 if
706   deflateInit2() was not used. If a compressed stream with a larger window
782   deflateInit2() was not used. If a compressed stream with a larger window
707783   size is given as input, inflate() will return with the error code
708784   Z_DATA_ERROR instead of trying to allocate a larger window.
709785
710     windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
711   determines the window size. inflate() will then process raw deflate data,
786     windowBits can also be zero to request that inflate use the window size in
787   the zlib header of the compressed stream.
788
789     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
790   determines the window size.  inflate() will then process raw deflate data,
712791   not looking for a zlib or gzip header, not generating a check value, and not
713   looking for any check values for comparison at the end of the stream. This
792   looking for any check values for comparison at the end of the stream. This
714793   is for use with other formats that use the deflate compressed data format
715   such as zip.  Those formats provide their own check values. If a custom
794   such as zip.  Those formats provide their own check values. If a custom
716795   format is developed using the raw deflate format for compressed data, it is
717796   recommended that a check value such as an adler32 or a crc32 be applied to
718797   the uncompressed data as is done in the zlib, gzip, and zip formats.  For
719   most applications, the zlib format should be used as is. Note that comments
798   most applications, the zlib format should be used as is. Note that comments
720799   above on the use in deflateInit2() applies to the magnitude of windowBits.
721800
722     windowBits can also be greater than 15 for optional gzip decoding. Add
801     windowBits can also be greater than 15 for optional gzip decoding. Add
723802   32 to windowBits to enable zlib and gzip decoding with automatic header
724803   detection, or add 16 to decode only the gzip format (the zlib format will
725   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is
726   a crc32 instead of an adler32.
804   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a
805   crc32 instead of an adler32.
727806
728807     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
729   memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
730   is set to null if there is no error message.  inflateInit2 does not perform
731   any decompression apart from reading the zlib header if present: this will
732   be done by inflate(). (So next_in and avail_in may be modified, but next_out
733   and avail_out are unchanged.)
808   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
809   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
810   invalid, such as a null pointer to the structure.  msg is set to null if
811   there is no error message.  inflateInit2 does not perform any decompression
812   apart from possibly reading the zlib header if present: actual decompression
813   will be done by inflate().  (So next_in and avail_in may be modified, but
814   next_out and avail_out are unused and unchanged.) The current implementation
815   of inflateInit2() does not process any header information -- that is
816   deferred until inflate() is called.
734817*/
735818
736819ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
r15677r15678
738821                                             uInt  dictLength));
739822/*
740823     Initializes the decompression dictionary from the given uncompressed byte
741   sequence. This function must be called immediately after a call of inflate,
742   if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
824   sequence.  This function must be called immediately after a call of inflate,
825   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor
743826   can be determined from the adler32 value returned by that call of inflate.
744827   The compressor and decompressor must use exactly the same dictionary (see
745   deflateSetDictionary).  For raw inflate, this function can be called
746   immediately after inflateInit2() or inflateReset() and before any call of
747   inflate() to set the dictionary.  The application must insure that the
748   dictionary that was used for compression is provided.
828   deflateSetDictionary).  For raw inflate, this function can be called at any
829   time to set the dictionary.  If the provided dictionary is smaller than the
830   window and there is already data in the window, then the provided dictionary
831   will amend what's there.  The application must insure that the dictionary
832   that was used for compression is provided.
749833
750834     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
751   parameter is invalid (such as NULL dictionary) or the stream state is
835   parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
752836   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
753   expected one (incorrect adler32 value). inflateSetDictionary does not
837   expected one (incorrect adler32 value). inflateSetDictionary does not
754838   perform any decompression: this will be done by subsequent calls of
755839   inflate().
756840*/
757841
758842ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
759843/*
760    Skips invalid compressed data until a full flush point (see above the
761  description of deflate with Z_FULL_FLUSH) can be found, or until all
762  available input is skipped. No output is provided.
844     Skips invalid compressed data until a possible full flush point (see above
845   for the description of deflate with Z_FULL_FLUSH) can be found, or until all
846   available input is skipped.  No output is provided.
763847
764    inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
765  if no more input was provided, Z_DATA_ERROR if no flush point has been found,
766  or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
767  case, the application may save the current current value of total_in which
768  indicates where valid compressed data was found. In the error case, the
769  application may repeatedly call inflateSync, providing more input each time,
770  until success or end of the input data.
848     inflateSync searches for a 00 00 FF FF pattern in the compressed data.
849   All full flush points have this pattern, but not all occurences of this
850   pattern are full flush points.
851
852     inflateSync returns Z_OK if a possible full flush point has been found,
853   Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
854   has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
855   In the success case, the application may save the current current value of
856   total_in which indicates where valid compressed data was found.  In the
857   error case, the application may repeatedly call inflateSync, providing more
858   input each time, until success or end of the input data.
771859*/
772860
773861ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
r15677r15678
782870
783871     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
784872   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
785   (such as zalloc being NULL). msg is left unchanged in both source and
873   (such as zalloc being Z_NULL). msg is left unchanged in both source and
786874   destination.
787875*/
788876
789877ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
790878/*
791879     This function is equivalent to inflateEnd followed by inflateInit,
792   but does not free and reallocate all the internal decompression state.
793   The stream will keep attributes that may have been set by inflateInit2.
880   but does not free and reallocate all the internal decompression state.  The
881   stream will keep attributes that may have been set by inflateInit2.
794882
795      inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
796   stream state was inconsistent (such as zalloc or state being NULL).
883     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
884   stream state was inconsistent (such as zalloc or state being Z_NULL).
797885*/
798886
887ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
888                                      int windowBits));
889/*
890     This function is the same as inflateReset, but it also permits changing
891   the wrap and window size requests.  The windowBits parameter is interpreted
892   the same as it is for inflateInit2.
893
894     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
895   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
896   the windowBits parameter is invalid.
897*/
898
799899ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
800900                                     int bits,
801901                                     int value));
802902/*
803903     This function inserts bits in the inflate input stream.  The intent is
804  that this function is used to start inflating at a bit position in the
805  middle of a byte.  The provided bits will be used before any bytes are used
806  from next_in.  This function should only be used with raw inflate, and
807  should be used before the first inflate() call after inflateInit2() or
808  inflateReset().  bits must be less than or equal to 16, and that many of the
809  least significant bits of value will be inserted in the input.
904   that this function is used to start inflating at a bit position in the
905   middle of a byte.  The provided bits will be used before any bytes are used
906   from next_in.  This function should only be used with raw inflate, and
907   should be used before the first inflate() call after inflateInit2() or
908   inflateReset().  bits must be less than or equal to 16, and that many of the
909   least significant bits of value will be inserted in the input.
810910
811      inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
911     If bits is negative, then the input stream bit buffer is emptied.  Then
912   inflatePrime() can be called again to put bits in the buffer.  This is used
913   to clear out bits leftover after feeding inflate a block description prior
914   to feeding inflate codes.
915
916     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
812917   stream state was inconsistent.
813918*/
814919
920ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
921/*
922     This function returns two values, one in the lower 16 bits of the return
923   value, and the other in the remaining upper bits, obtained by shifting the
924   return value down 16 bits.  If the upper value is -1 and the lower value is
925   zero, then inflate() is currently decoding information outside of a block.
926   If the upper value is -1 and the lower value is non-zero, then inflate is in
927   the middle of a stored block, with the lower value equaling the number of
928   bytes from the input remaining to copy.  If the upper value is not -1, then
929   it is the number of bits back from the current bit position in the input of
930   the code (literal or length/distance pair) currently being processed.  In
931   that case the lower value is the number of bytes already emitted for that
932   code.
933
934     A code is being processed if inflate is waiting for more input to complete
935   decoding of the code, or if it has completed decoding but is waiting for
936   more output space to write the literal or match data.
937
938     inflateMark() is used to mark locations in the input data for random
939   access, which may be at bit positions, and to note those cases where the
940   output of a code may span boundaries of random access blocks.  The current
941   location in the input stream can be determined from avail_in and data_type
942   as noted in the description for the Z_BLOCK flush parameter for inflate.
943
944     inflateMark returns the value noted above or -1 << 16 if the provided
945   source stream state was inconsistent.
946*/
947
815948ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
816949                                         gz_headerp head));
817950/*
818      inflateGetHeader() requests that gzip header information be stored in the
951     inflateGetHeader() requests that gzip header information be stored in the
819952   provided gz_header structure.  inflateGetHeader() may be called after
820953   inflateInit2() or inflateReset(), and before the first call of inflate().
821954   As inflate() processes the gzip stream, head->done is zero until the header
822955   is completed, at which time head->done is set to one.  If a zlib stream is
823956   being decoded, then head->done is set to -1 to indicate that there will be
824   no gzip header information forthcoming.  Note that Z_BLOCK can be used to
825   force inflate() to return immediately after header processing is complete
826   and before any actual data is decompressed.
957   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
958   used to force inflate() to return immediately after header processing is
959   complete and before any actual data is decompressed.
827960
828      The text, time, xflags, and os fields are filled in with the gzip header
961     The text, time, xflags, and os fields are filled in with the gzip header
829962   contents.  hcrc is set to true if there is a header CRC.  (The header CRC
830   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
963   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
831964   contains the maximum number of bytes to write to extra.  Once done is true,
832965   extra_len contains the actual extra field length, and extra contains the
833966   extra field, or that field truncated if extra_max is less than extra_len.
834967   If name is not Z_NULL, then up to name_max characters are written there,
835968   terminated with a zero unless the length is greater than name_max.  If
836969   comment is not Z_NULL, then up to comm_max characters are written there,
837   terminated with a zero unless the length is greater than comm_max.  When
838   any of extra, name, or comment are not Z_NULL and the respective field is
839   not present in the header, then that field is set to Z_NULL to signal its
970   terminated with a zero unless the length is greater than comm_max.  When any
971   of extra, name, or comment are not Z_NULL and the respective field is not
972   present in the header, then that field is set to Z_NULL to signal its
840973   absence.  This allows the use of deflateSetHeader() with the returned
841974   structure to duplicate the header.  However if those fields are set to
842975   allocated memory, then the application will need to save those pointers
843976   elsewhere so that they can be eventually freed.
844977
845      If inflateGetHeader is not used, then the header information is simply
978     If inflateGetHeader is not used, then the header information is simply
846979   discarded.  The header is always checked for validity, including the header
847980   CRC if present.  inflateReset() will reset the process to discard the header
848981   information.  The application would need to call inflateGetHeader() again to
849982   retrieve the header from the next gzip stream.
850983
851      inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
984     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
852985   stream state was inconsistent.
853986*/
854987
r15677r15678
8691002     See inflateBack() for the usage of these routines.
8701003
8711004     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
872   the paramaters are invalid, Z_MEM_ERROR if the internal state could not
873   be allocated, or Z_VERSION_ERROR if the version of the library does not
874   match the version of the header file.
1005   the parameters are invalid, Z_MEM_ERROR if the internal state could not be
1006   allocated, or Z_VERSION_ERROR if the version of the library does not match
1007   the version of the header file.
8751008*/
8761009
8771010typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
r15677r15678
8911024     inflateBackInit() must be called first to allocate the internal state
8921025   and to initialize the state with the user-provided window buffer.
8931026   inflateBack() may then be used multiple times to inflate a complete, raw
894   deflate stream with each call.  inflateBackEnd() is then called to free
895   the allocated state.
1027   deflate stream with each call.  inflateBackEnd() is then called to free the
1028   allocated state.
8961029
8971030     A raw deflate stream is one with no zlib or gzip header or trailer.
8981031   This routine would normally be used in a utility that reads zip or gzip
8991032   files and writes out uncompressed files.  The utility would decode the
900   header and process the trailer on its own, hence this routine expects
901   only the raw deflate stream to decompress.  This is different from the
902   normal behavior of inflate(), which expects either a zlib or gzip header and
1033   header and process the trailer on its own, hence this routine expects only
1034   the raw deflate stream to decompress.  This is different from the normal
1035   behavior of inflate(), which expects either a zlib or gzip header and
9031036   trailer around the deflate stream.
9041037
9051038     inflateBack() uses two subroutines supplied by the caller that are then
r15677r15678
9251058   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
9261059   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
9271060   must also be initialized, and then if strm->avail_in is not zero, input will
928   initially be taken from strm->next_in[0 .. strm->avail_in - 1].
1061   initially be taken from strm->next_in[0 .. strm->avail_in - 1].
9291062
9301063     The in_desc and out_desc parameters of inflateBack() is passed as the
9311064   first parameter of in() and out() respectively when they are called.  These
r15677r15678
9351068     On return, inflateBack() will set strm->next_in and strm->avail_in to
9361069   pass back any unused input that was provided by the last in() call.  The
9371070   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
938   if in() or out() returned an error, Z_DATA_ERROR if there was a format
939   error in the deflate stream (in which case strm->msg is set to indicate the
940   nature of the error), or Z_STREAM_ERROR if the stream was not properly
941   initialized.  In the case of Z_BUF_ERROR, an input or output error can be
942   distinguished using strm->next_in which will be Z_NULL only if in() returned
943   an error.  If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
944   out() returning non-zero.  (in() will always be called before out(), so
945   strm->next_in is assured to be defined if out() returns non-zero.)  Note
946   that inflateBack() cannot return Z_OK.
1071   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
1072   in the deflate stream (in which case strm->msg is set to indicate the nature
1073   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
1074   In the case of Z_BUF_ERROR, an input or output error can be distinguished
1075   using strm->next_in which will be Z_NULL only if in() returned an error.  If
1076   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
1077   non-zero.  (in() will always be called before out(), so strm->next_in is
1078   assured to be defined if out() returns non-zero.) Note that inflateBack()
1079   cannot return Z_OK.
9471080*/
9481081
9491082ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
r15677r15678
9951128     27-31: 0 (reserved)
9961129 */
9971130
1131#ifndef Z_SOLO
9981132
9991133                        /* utility functions */
10001134
10011135/*
1002     The following utility functions are implemented on top of the
1003   basic stream-oriented functions. To simplify the interface, some
1004   default options are assumed (compression level and memory usage,
1005   standard memory allocation functions). The source code of these
1006   utility functions can easily be modified if you need special options.
1136     The following utility functions are implemented on top of the basic
1137   stream-oriented functions.  To simplify the interface, some default options
1138   are assumed (compression level and memory usage, standard memory allocation
1139   functions).  The source code of these utility functions can be modified if
1140   you need special options.
10071141*/
10081142
10091143ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
10101144                                 const Bytef *source, uLong sourceLen));
10111145/*
10121146     Compresses the source buffer into the destination buffer.  sourceLen is
1013   the byte length of the source buffer. Upon entry, destLen is the total
1014   size of the destination buffer, which must be at least the value returned
1015   by compressBound(sourceLen). Upon exit, destLen is the actual size of the
1147   the byte length of the source buffer.  Upon entry, destLen is the total size
1148   of the destination buffer, which must be at least the value returned by
1149   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
10161150   compressed buffer.
1017     This function can be used to compress a whole file at once if the
1018   input file is mmap'ed.
1151
10191152     compress returns Z_OK if success, Z_MEM_ERROR if there was not
10201153   enough memory, Z_BUF_ERROR if there was not enough room in the output
10211154   buffer.
r15677r15678
10251158                                  const Bytef *source, uLong sourceLen,
10261159                                  int level));
10271160/*
1028     Compresses the source buffer into the destination buffer. The level
1161     Compresses the source buffer into the destination buffer. The level
10291162   parameter has the same meaning as in deflateInit.  sourceLen is the byte
1030   length of the source buffer. Upon entry, destLen is the total size of the
1163   length of the source buffer. Upon entry, destLen is the total size of the
10311164   destination buffer, which must be at least the value returned by
1032   compressBound(sourceLen). Upon exit, destLen is the actual size of the
1165   compressBound(sourceLen). Upon exit, destLen is the actual size of the
10331166   compressed buffer.
10341167
10351168     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
r15677r15678
10401173ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
10411174/*
10421175     compressBound() returns an upper bound on the compressed size after
1043   compress() or compress2() on sourceLen bytes.  It would be used before
1044   a compress() or compress2() call to allocate the destination buffer.
1176   compress() or compress2() on sourceLen bytes.  It would be used before a
1177   compress() or compress2() call to allocate the destination buffer.
10451178*/
10461179
10471180ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
10481181                                   const Bytef *source, uLong sourceLen));
10491182/*
10501183     Decompresses the source buffer into the destination buffer.  sourceLen is
1051   the byte length of the source buffer. Upon entry, destLen is the total
1052   size of the destination buffer, which must be large enough to hold the
1053   entire uncompressed data. (The size of the uncompressed data must have
1054   been saved previously by the compressor and transmitted to the decompressor
1055   by some mechanism outside the scope of this compression library.)
1056   Upon exit, destLen is the actual size of the compressed buffer.
1057     This function can be used to decompress a whole file at once if the
1058   input file is mmap'ed.
1184   the byte length of the source buffer.  Upon entry, destLen is the total size
1185   of the destination buffer, which must be large enough to hold the entire
1186   uncompressed data.  (The size of the uncompressed data must have been saved
1187   previously by the compressor and transmitted to the decompressor by some
1188   mechanism outside the scope of this compression library.) Upon exit, destLen
1189   is the actual size of the uncompressed buffer.
10591190
10601191     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
10611192   enough memory, Z_BUF_ERROR if there was not enough room in the output
1062   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
1193   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In
1194   the case where there is not enough room, uncompress() will fill the output
1195   buffer with the uncompressed data up to that point.
10631196*/
10641197
1198                        /* gzip file access functions */
10651199
1066typedef voidp gzFile;
1200/*
1201     This library supports reading and writing files in gzip (.gz) format with
1202   an interface similar to that of stdio, using the functions that start with
1203   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
1204   wrapper, documented in RFC 1952, wrapped around a deflate stream.
1205*/
10671206
1068ZEXTERN gzFile ZEXPORT gzopen  OF((const char *path, const char *mode));
1207typedef struct gzFile_s *gzFile;    /* semi-opaque gzip file descriptor */
1208
10691209/*
1070     Opens a gzip (.gz) file for reading or writing. The mode parameter
1071   is as in fopen ("rb" or "wb") but can also include a compression level
1072   ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
1073   Huffman only compression as in "wb1h", or 'R' for run-length encoding
1074   as in "wb1R". (See the description of deflateInit2 for more information
1075   about the strategy parameter.)
1210ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
10761211
1212     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
1213   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
1214   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
1215   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
1216   for fixed code compression as in "wb9F".  (See the description of
1217   deflateInit2 for more information about the strategy parameter.)  'T' will
1218   request transparent writing or appending with no compression and not using
1219   the gzip format.
1220
1221     "a" can be used instead of "w" to request that the gzip stream that will
1222   be written be appended to the file.  "+" will result in an error, since
1223   reading and writing to the same gzip file is not supported.  The addition of
1224   "x" when writing will create the file exclusively, which fails if the file
1225   already exists.  On systems that support it, the addition of "e" when
1226   reading or writing will set the flag to close the file on an execve() call.
1227
1228     These functions, as well as gzip, will read and decode a sequence of gzip
1229   streams in a file.  The append function of gzopen() can be used to create
1230   such a file.  (Also see gzflush() for another way to do this.)  When
1231   appending, gzopen does not test whether the file begins with a gzip stream,
1232   nor does it look for the end of the gzip streams to begin appending.  gzopen
1233   will simply append a gzip stream to the existing file.
1234
10771235     gzopen can be used to read a file which is not in gzip format; in this
1078   case gzread will directly read from the file without decompression.
1236   case gzread will directly read from the file without decompression.  When
1237   reading, this will be detected automatically by looking for the magic two-
1238   byte gzip header.
10791239
1080     gzopen returns NULL if the file could not be opened or if there was
1081   insufficient memory to allocate the (de)compression state; errno
1082   can be checked to distinguish the two cases (if errno is zero, the
1083   zlib error is Z_MEM_ERROR).  */
1240     gzopen returns NULL if the file could not be opened, if there was
1241   insufficient memory to allocate the gzFile state, or if an invalid mode was
1242   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
1243   errno can be checked to determine if the reason gzopen failed was that the
1244   file could not be opened.
1245*/
10841246
1085ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
1247ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
10861248/*
1087     gzdopen() associates a gzFile with the file descriptor fd.  File
1088   descriptors are obtained from calls like open, dup, creat, pipe or
1089   fileno (in the file has been previously opened with fopen).
1090   The mode parameter is as in gzopen.
1091     The next call of gzclose on the returned gzFile will also close the
1092   file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
1093   descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
1094     gzdopen returns NULL if there was insufficient memory to allocate
1095   the (de)compression state.
1249     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
1250   are obtained from calls like open, dup, creat, pipe or fileno (if the file
1251   has been previously opened with fopen).  The mode parameter is as in gzopen.
1252
1253     The next call of gzclose on the returned gzFile will also close the file
1254   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
1255   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
1256   mode);.  The duplicated descriptor should be saved to avoid a leak, since
1257   gzdopen does not close fd if it fails.  If you are using fileno() to get the
1258   file descriptor from a FILE *, then you will have to use dup() to avoid
1259   double-close()ing the file descriptor.  Both gzclose() and fclose() will
1260   close the associated file descriptor, so they need to have different file
1261   descriptors.
1262
1263     gzdopen returns NULL if there was insufficient memory to allocate the
1264   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
1265   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
1266   used until the next gz* read, write, seek, or close operation, so gzdopen
1267   will not detect if fd is invalid (unless fd is -1).
10961268*/
10971269
1270ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
1271/*
1272     Set the internal buffer size used by this library's functions.  The
1273   default buffer size is 8192 bytes.  This function must be called after
1274   gzopen() or gzdopen(), and before any other calls that read or write the
1275   file.  The buffer memory allocation is always deferred to the first read or
1276   write.  Two buffers are allocated, either both of the specified size when
1277   writing, or one of the specified size and the other twice that size when
1278   reading.  A larger buffer size of, for example, 64K or 128K bytes will
1279   noticeably increase the speed of decompression (reading).
1280
1281     The new buffer size also affects the maximum length for gzprintf().
1282
1283     gzbuffer() returns 0 on success, or -1 on failure, such as being called
1284   too late.
1285*/
1286
10981287ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
10991288/*
1100     Dynamically update the compression level or strategy. See the description
1289     Dynamically update the compression level or strategy. See the description
11011290   of deflateInit2 for the meaning of these parameters.
1291
11021292     gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
11031293   opened for writing.
11041294*/
11051295
1106ZEXTERN int ZEXPORT    gzread OF((gzFile file, voidp buf, unsigned len));
1296ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
11071297/*
1108     Reads the given number of uncompressed bytes from the compressed file.
1109   If the input file was not in gzip format, gzread copies the given number
1110   of bytes into the buffer.
1111     gzread returns the number of uncompressed bytes actually read (0 for
1112   end of file, -1 for error). */
1298     Reads the given number of uncompressed bytes from the compressed file.  If
1299   the input file is not in gzip format, gzread copies the given number of
1300   bytes into the buffer directly from the file.
11131301
1114ZEXTERN int ZEXPORT    gzwrite OF((gzFile file,
1115                                   voidpc buf, unsigned len));
1302     After reaching the end of a gzip stream in the input, gzread will continue
1303   to read, looking for another gzip stream.  Any number of gzip streams may be
1304   concatenated in the input file, and will all be decompressed by gzread().
1305   If something other than a gzip stream is encountered after a gzip stream,
1306   that remaining trailing garbage is ignored (and no error is returned).
1307
1308     gzread can be used to read a gzip file that is being concurrently written.
1309   Upon reaching the end of the input, gzread will return with the available
1310   data.  If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
1311   gzclearerr can be used to clear the end of file indicator in order to permit
1312   gzread to be tried again.  Z_OK indicates that a gzip stream was completed
1313   on the last gzread.  Z_BUF_ERROR indicates that the input file ended in the
1314   middle of a gzip stream.  Note that gzread does not return -1 in the event
1315   of an incomplete gzip stream.  This error is deferred until gzclose(), which
1316   will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
1317   stream.  Alternatively, gzerror can be used before gzclose to detect this
1318   case.
1319
1320     gzread returns the number of uncompressed bytes actually read, less than
1321   len for end of file, or -1 for error.
1322*/
1323
1324ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
1325                                voidpc buf, unsigned len));
11161326/*
11171327     Writes the given number of uncompressed bytes into the compressed file.
1118   gzwrite returns the number of uncompressed bytes actually written
1119   (0 in case of error).
1328   gzwrite returns the number of uncompressed bytes written or 0 in case of
1329   error.
11201330*/
11211331
1122ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
1332ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...));
11231333/*
1124     Converts, formats, and writes the args to the compressed file under
1125   control of the format string, as in fprintf. gzprintf returns the number of
1126   uncompressed bytes actually written (0 in case of error).  The number of
1127   uncompressed bytes written is limited to 4095. The caller should assure that
1128   this limit is not exceeded. If it is exceeded, then gzprintf() will return
1129   return an error (0) with nothing written. In this case, there may also be a
1130   buffer overflow with unpredictable consequences, which is possible only if
1131   zlib was compiled with the insecure functions sprintf() or vsprintf()
1132   because the secure snprintf() or vsnprintf() functions were not available.
1334     Converts, formats, and writes the arguments to the compressed file under
1335   control of the format string, as in fprintf.  gzprintf returns the number of
1336   uncompressed bytes actually written, or 0 in case of error.  The number of
1337   uncompressed bytes written is limited to 8191, or one less than the buffer
1338   size given to gzbuffer().  The caller should assure that this limit is not
1339   exceeded.  If it is exceeded, then gzprintf() will return an error (0) with
1340   nothing written.  In this case, there may also be a buffer overflow with
1341   unpredictable consequences, which is possible only if zlib was compiled with
1342   the insecure functions sprintf() or vsprintf() because the secure snprintf()
1343   or vsnprintf() functions were not available.  This can be determined using
1344   zlibCompileFlags().
11331345*/
11341346
11351347ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
11361348/*
1137      Writes the given null-terminated string to the compressed file, excluding
1349     Writes the given null-terminated string to the compressed file, excluding
11381350   the terminating null character.
1139      gzputs returns the number of characters written, or -1 in case of error.
1351
1352     gzputs returns the number of characters written, or -1 in case of error.
11401353*/
11411354
11421355ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
11431356/*
1144      Reads bytes from the compressed file until len-1 characters are read, or
1145   a newline character is read and transferred to buf, or an end-of-file
1146   condition is encountered.  The string is then terminated with a null
1147   character.
1148      gzgets returns buf, or Z_NULL in case of error.
1357     Reads bytes from the compressed file until len-1 characters are read, or a
1358   newline character is read and transferred to buf, or an end-of-file
1359   condition is encountered.  If any characters are read or if len == 1, the
1360   string is terminated with a null character.  If no characters are read due
1361   to an end-of-file or len < 1, then the buffer is left untouched.
1362
1363     gzgets returns buf which is a null-terminated string, or it returns NULL
1364   for end-of-file or in case of error.  If there was an error, the contents at
1365   buf are indeterminate.
11491366*/
11501367
1151ZEXTERN int ZEXPORT    gzputc OF((gzFile file, int c));
1368ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
11521369/*
1153      Writes c, converted to an unsigned char, into the compressed file.
1154   gzputc returns the value that was written, or -1 in case of error.
1370     Writes c, converted to an unsigned char, into the compressed file.  gzputc
1371   returns the value that was written, or -1 in case of error.
11551372*/
11561373
1157ZEXTERN int ZEXPORT    gzgetc OF((gzFile file));
1374ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
11581375/*
1159      Reads one byte from the compressed file. gzgetc returns this byte
1160   or -1 in case of end of file or error.
1376     Reads one byte from the compressed file.  gzgetc returns this byte or -1
1377   in case of end of file or error.  This is implemented as a macro for speed.
1378   As such, it does not do all of the checking the other functions do.  I.e.
1379   it does not check to see if file is NULL, nor whether the structure file
1380   points to has been clobbered or not.
11611381*/
11621382
1163ZEXTERN int ZEXPORT    gzungetc OF((int c, gzFile file));
1383ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
11641384/*
1165      Push one character back onto the stream to be read again later.
1166   Only one character of push-back is allowed.  gzungetc() returns the
1167   character pushed, or -1 on failure.  gzungetc() will fail if a
1168   character has been pushed but not read yet, or if c is -1. The pushed
1169   character will be discarded if the stream is repositioned with gzseek()
1170   or gzrewind().
1385     Push one character back onto the stream to be read as the first character
1386   on the next read.  At least one character of push-back is allowed.
1387   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
1388   fail if c is -1, and may fail if a character has been pushed but not read
1389   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
1390   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
1391   The pushed character will be discarded if the stream is repositioned with
1392   gzseek() or gzrewind().
11711393*/
11721394
1173ZEXTERN int ZEXPORT    gzflush OF((gzFile file, int flush));
1395ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
11741396/*
1175     Flushes all pending output into the compressed file. The parameter
1176   flush is as in the deflate() function. The return value is the zlib
1177   error number (see function gzerror below). gzflush returns Z_OK if
1178   the flush parameter is Z_FINISH and all output could be flushed.
1179     gzflush should be called only when strictly necessary because it can
1180   degrade compression.
1397     Flushes all pending output into the compressed file.  The parameter flush
1398   is as in the deflate() function.  The return value is the zlib error number
1399   (see function gzerror below).  gzflush is only permitted when writing.
1400
1401     If the flush parameter is Z_FINISH, the remaining data is written and the
1402   gzip stream is completed in the output.  If gzwrite() is called again, a new
1403   gzip stream will be started in the output.  gzread() is able to read such
1404   concatented gzip streams.
1405
1406     gzflush should be called only when strictly necessary because it will
1407   degrade compression if called too often.
11811408*/
11821409
1183ZEXTERN z_off_t ZEXPORT    gzseek OF((gzFile file,
1184                                      z_off_t offset, int whence));
11851410/*
1186      Sets the starting position for the next gzread or gzwrite on the
1187   given compressed file. The offset represents a number of bytes in the
1188   uncompressed data stream. The whence parameter is defined as in lseek(2);
1411ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
1412                                   z_off_t offset, int whence));
1413
1414     Sets the starting position for the next gzread or gzwrite on the given
1415   compressed file.  The offset represents a number of bytes in the
1416   uncompressed data stream.  The whence parameter is defined as in lseek(2);
11891417   the value SEEK_END is not supported.
1418
11901419     If the file is opened for reading, this function is emulated but can be
1191   extremely slow. If the file is opened for writing, only forward seeks are
1420   extremely slow. If the file is opened for writing, only forward seeks are
11921421   supported; gzseek then compresses a sequence of zeroes up to the new
11931422   starting position.
11941423
1195      gzseek returns the resulting offset location as measured in bytes from
1424     gzseek returns the resulting offset location as measured in bytes from
11961425   the beginning of the uncompressed stream, or -1 in case of error, in
11971426   particular if the file is opened for writing and the new starting position
11981427   would be before the current position.
r15677r15678
12021431/*
12031432     Rewinds the given file. This function is supported only for reading.
12041433
1205   gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
1434     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
12061435*/
12071436
1437/*
12081438ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
1439
1440     Returns the starting position for the next gzread or gzwrite on the given
1441   compressed file.  This position represents a number of bytes in the
1442   uncompressed data stream, and is zero when starting, even if appending or
1443   reading a gzip stream from the middle of a file using gzdopen().
1444
1445     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
1446*/
1447
12091448/*
1210     Returns the starting position for the next gzread or gzwrite on the
1211   given compressed file. This position represents a number of bytes in the
1212   uncompressed data stream.
1449ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
12131450
1214   gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
1451     Returns the current offset in the file being read or written.  This offset
1452   includes the count of bytes that precede the gzip stream, for example when
1453   appending or when using gzdopen() for reading.  When reading, the offset
1454   does not include as yet unused buffered input.  This information can be used
1455   for a progress indicator.  On error, gzoffset() returns -1.
12151456*/
12161457
12171458ZEXTERN int ZEXPORT gzeof OF((gzFile file));
12181459/*
1219     Returns 1 when EOF has previously been detected reading the given
1220   input stream, otherwise zero.
1460     Returns true (1) if the end-of-file indicator has been set while reading,
1461   false (0) otherwise.  Note that the end-of-file indicator is set only if the
1462   read tried to go past the end of the input, but came up short.  Therefore,
1463   just like feof(), gzeof() may return false even if there is no more data to
1464   read, in the event that the last read request was for the exact number of
1465   bytes remaining in the input file.  This will happen if the input file size
1466   is an exact multiple of the buffer size.
1467
1468     If gzeof() returns true, then the read functions will return no more data,
1469   unless the end-of-file indicator is reset by gzclearerr() and the input file
1470   has grown since the previous end of file was detected.
12211471*/
12221472
12231473ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
12241474/*
1225     Returns 1 if file is being read directly without decompression, otherwise
1226   zero.
1475     Returns true (1) if file is being copied directly while reading, or false
1476   (0) if file is a gzip stream being decompressed.
1477
1478     If the input file is empty, gzdirect() will return true, since the input
1479   does not contain a gzip stream.
1480
1481     If gzdirect() is used immediately after gzopen() or gzdopen() it will
1482   cause buffers to be allocated to allow reading the file to determine if it
1483   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
1484   gzdirect().
1485
1486     When writing, gzdirect() returns true (1) if transparent writing was
1487   requested ("wT" for the gzopen() mode), or false (0) otherwise.  (Note:
1488   gzdirect() is not needed when writing.  Transparent writing must be
1489   explicitly requested, so the application already knows the answer.  When
1490   linking statically, using gzdirect() will include all of the zlib code for
1491   gzip file reading and decompression, which may not be desired.)
12271492*/
12281493
12291494ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
12301495/*
1231     Flushes all pending output if necessary, closes the compressed file
1232   and deallocates all the (de)compression state. The return value is the zlib
1233   error number (see function gzerror below).
1496     Flushes all pending output if necessary, closes the compressed file and
1497   deallocates the (de)compression state.  Note that once file is closed, you
1498   cannot call gzerror with file, since its structures have been deallocated.
1499   gzclose must not be called more than once on the same file, just as free
1500   must not be called more than once on the same allocation.
1501
1502     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
1503   file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
1504   last read ended in the middle of a gzip stream, or Z_OK on success.
12341505*/
12351506
1507ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
1508ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
1509/*
1510     Same as gzclose(), but gzclose_r() is only for use when reading, and
1511   gzclose_w() is only for use when writing or appending.  The advantage to
1512   using these instead of gzclose() is that they avoid linking in zlib
1513   compression or decompression code that is not used when only reading or only
1514   writing respectively.  If gzclose() is used, then both compression and
1515   decompression code will be included the application when linking to a static
1516   zlib library.
1517*/
1518
12361519ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
12371520/*
1238     Returns the error message for the last error which occurred on the
1239   given compressed file. errnum is set to zlib error number. If an
1240   error occurred in the file system and not in the compression library,
1241   errnum is set to Z_ERRNO and the application may consult errno
1242   to get the exact error code.
1521     Returns the error message for the last error which occurred on the given
1522   compressed file.  errnum is set to zlib error number.  If an error occurred
1523   in the file system and not in the compression library, errnum is set to
1524   Z_ERRNO and the application may consult errno to get the exact error code.
1525
1526     The application must not modify the returned string.  Future calls to
1527   this function may invalidate the previously returned string.  If file is
1528   closed, then the string previously returned by gzerror will no longer be
1529   available.
1530
1531     gzerror() should be used to distinguish errors from end-of-file for those
1532   functions above that do not distinguish those cases in their return values.
12431533*/
12441534
12451535ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
12461536/*
1247     Clears the error and end-of-file flags for file. This is analogous to the
1248   clearerr() function in stdio. This is useful for continuing to read a gzip
1537     Clears the error and end-of-file flags for file.  This is analogous to the
1538   clearerr() function in stdio.  This is useful for continuing to read a gzip
12491539   file that is being written concurrently.
12501540*/
12511541
1542#endif /* !Z_SOLO */
1543
12521544                        /* checksum functions */
12531545
12541546/*
12551547     These functions are not related to compression but are exported
1256   anyway because they might be useful in applications using the
1257   compression library.
1548   anyway because they might be useful in applications using the compression
1549   library.
12581550*/
12591551
12601552ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
12611553/*
12621554     Update a running Adler-32 checksum with the bytes buf[0..len-1] and
1263   return the updated checksum. If buf is NULL, this function returns
1264   the required initial value for the checksum.
1265   An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
1266   much faster. Usage example:
1555   return the updated checksum.  If buf is Z_NULL, this function returns the
1556   required initial value for the checksum.
12671557
1558     An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
1559   much faster.
1560
1561   Usage example:
1562
12681563     uLong adler = adler32(0L, Z_NULL, 0);
12691564
12701565     while (read_buffer(buffer, length) != EOF) {
r15677r15678
12731568     if (adler != original_adler) error();
12741569*/
12751570
1571/*
12761572ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
12771573                                          z_off_t len2));
1278/*
1574
12791575     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
12801576   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
12811577   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
1282   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
1578   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.  Note
1579   that the z_off_t type (like off_t) is a signed integer.  If len2 is
1580   negative, the result has no meaning or utility.
12831581*/
12841582
12851583ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
12861584/*
12871585     Update a running CRC-32 with the bytes buf[0..len-1] and return the
1288   updated CRC-32. If buf is NULL, this function returns the required initial
1289   value for the for the crc. Pre- and post-conditioning (one's complement) is
1586   updated CRC-32.  If buf is Z_NULL, this function returns the required
1587   initial value for the crc.  Pre- and post-conditioning (one's complement) is
12901588   performed within this function so it shouldn't be done by the application.
1589
12911590   Usage example:
12921591
12931592     uLong crc = crc32(0L, Z_NULL, 0);
r15677r15678
12981597     if (crc != original_crc) error();
12991598*/
13001599
1600/*
13011601ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
13021602
1303/*
13041603     Combine two CRC-32 check values into one.  For two sequences of bytes,
13051604   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
13061605   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
r15677r15678
13291628                                         const char *version,
13301629                                         int stream_size));
13311630#define deflateInit(strm, level) \
1332        deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))
1631        deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
13331632#define inflateInit(strm) \
1334        inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))
1633        inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
13351634#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
13361635        deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
1337                      (strategy),           ZLIB_VERSION, sizeof(z_stream))
1636                      (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
13381637#define inflateInit2(strm, windowBits) \
1339        inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
1638        inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
1639                      (int)sizeof(z_stream))
13401640#define inflateBackInit(strm, windowBits, window) \
13411641        inflateBackInit_((strm), (windowBits), (window), \
1342        ZLIB_VERSION, sizeof(z_stream))
1642                      ZLIB_VERSION, (int)sizeof(z_stream))
13431643
1644#ifndef Z_SOLO
13441645
1646/* gzgetc() macro and its supporting function and exposed data structure.  Note
1647 * that the real internal state is much larger than the exposed structure.
1648 * This abbreviated structure exposes just enough for the gzgetc() macro.  The
1649 * user should not mess with these exposed elements, since their names or
1650 * behavior could change in the future, perhaps even capriciously.  They can
1651 * only be used by the gzgetc() macro.  You have been warned.
1652 */
1653struct gzFile_s {
1654    unsigned have;
1655    unsigned char *next;
1656    z_off64_t pos;
1657};
1658ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file));  /* backward compatibility */
1659#ifdef Z_PREFIX_SET
1660#  undef z_gzgetc
1661#  define z_gzgetc(g) \
1662          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g))
1663#else
1664#  define gzgetc(g) \
1665          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g))
1666#endif
1667
1668/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
1669 * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
1670 * both are true, the application gets the *64 functions, and the regular
1671 * functions are changed to 64 bits) -- in case these are set on systems
1672 * without large file support, _LFS64_LARGEFILE must also be true
1673 */
1674#ifdef Z_LARGE64
1675   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
1676   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
1677   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
1678   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
1679   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
1680   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
1681#endif
1682
1683#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)
1684#  ifdef Z_PREFIX_SET
1685#    define z_gzopen z_gzopen64
1686#    define z_gzseek z_gzseek64
1687#    define z_gztell z_gztell64
1688#    define z_gzoffset z_gzoffset64
1689#    define z_adler32_combine z_adler32_combine64
1690#    define z_crc32_combine z_crc32_combine64
1691#  else
1692#    define gzopen gzopen64
1693#    define gzseek gzseek64
1694#    define gztell gztell64
1695#    define gzoffset gzoffset64
1696#    define adler32_combine adler32_combine64
1697#    define crc32_combine crc32_combine64
1698#  endif
1699#  ifndef Z_LARGE64
1700     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
1701     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
1702     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
1703     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
1704     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
1705     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
1706#  endif
1707#else
1708   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
1709   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
1710   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
1711   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
1712   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
1713   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
1714#endif
1715
1716#else /* Z_SOLO */
1717
1718   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
1719   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
1720
1721#endif /* !Z_SOLO */
1722
1723/* hack for buggy compilers */
13451724#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
1346    struct internal_state {int dummy;}; /* hack for buggy compilers */
1725    struct internal_state {int dummy;};
13471726#endif
13481727
1728/* undocumented functions */
13491729ZEXTERN const char   * ZEXPORT zError           OF((int));
1350ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
1351ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
1730ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
1731ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table    OF((void));
1732ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
1733ZEXTERN int            ZEXPORT inflateResetKeep OF((z_streamp));
1734ZEXTERN int            ZEXPORT deflateResetKeep OF((z_streamp));
1735#if defined(_WIN32) && !defined(Z_SOLO)
1736ZEXTERN gzFile         ZEXPORT gzopen_w OF((const wchar_t *path,
1737                                            const char *mode));
1738#endif
13521739
13531740#ifdef __cplusplus
13541741}
src/lib/zlib/gzclose.c
r0r15678
1/* gzclose.c -- zlib gzclose() function
2 * Copyright (C) 2004, 2010 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6#include "gzguts.h"
7
8/* gzclose() is in a separate file so that it is linked in only if it is used.
9   That way the other gzclose functions can be used instead to avoid linking in
10   unneeded compression or decompression routines. */
11int ZEXPORT gzclose(file)
12    gzFile file;
13{
14#ifndef NO_GZCOMPRESS
15    gz_statep state;
16
17    if (file == NULL)
18        return Z_STREAM_ERROR;
19    state = (gz_statep)file;
20
21    return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file);
22#else
23    return gzclose_r(file);
24#endif
25}
src/lib/zlib/readme
r15677r15678
11ZLIB DATA COMPRESSION LIBRARY
22
3zlib 1.2.3 is a general purpose data compression library.  All the code is
3zlib 1.2.7 is a general purpose data compression library.  All the code is
44thread safe.  The data format used by the zlib library is described by RFCs
55(Request for Comments) 1950 to 1952 in the files
6http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format)
7and rfc1952.txt (gzip format). These documents are also available in other
8formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html
6http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and
7rfc1952 (gzip format).
98
109All functions of the compression library are documented in the file zlib.h
11(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example
12of the library is given in the file example.c which also tests that the library
13is working correctly. Another example is given in the file minigzip.c. The
14compression library itself is composed of all source files except example.c and
15minigzip.c.
10(volunteer to write man pages welcome, contact zlib@gzip.org).  A usage example
11of the library is given in the file test/example.c which also tests that
12the library is working correctly.  Another example is given in the file
13test/minigzip.c.  The compression library itself is composed of all source
14files in the root directory.
1615
1716To compile all files and run the test program, follow the instructions given at
18the top of Makefile. In short "make test; make install" should work for most
19machines. For Unix: "./configure; make test; make install". For MSDOS, use one
20of the special makefiles such as Makefile.msc. For VMS, use make_vms.com.
17the top of Makefile.in.  In short "./configure; make test", and if that goes
18well, "make install" should work for most flavors of Unix.  For Windows, use
19one of the special makefiles in win32/ or contrib/vstudio/ .  For VMS, use
20make_vms.com.
2121
2222Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
23<info@winimage.com> for the Windows DLL version. The zlib home page is
24http://www.zlib.org or http://www.gzip.org/zlib/ Before reporting a problem,
25please check this site to verify that you have the latest version of zlib;
26otherwise get the latest version and check whether the problem still exists or
27not.
23<info@winimage.com> for the Windows DLL version.  The zlib home page is
24http://zlib.net/ .  Before reporting a problem, please check this site to
25verify that you have the latest version of zlib; otherwise get the latest
26version and check whether the problem still exists or not.
2827
29PLEASE read the zlib FAQ http://www.gzip.org/zlib/zlib_faq.html before asking
30for help.
28PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
3129
32Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997
33issue of  Dr. Dobb's Journal; a copy of the article is available in
34http://dogma.net/markn/articles/zlibtool/zlibtool.htm
30Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan.  1997
31issue of Dr.  Dobb's Journal; a copy of the article is available at
32http://marknelson.us/1997/01/01/zlib-engine/ .
3533
36The changes made in version 1.2.3 are documented in the file ChangeLog.
34The changes made in version 1.2.7 are documented in the file ChangeLog.
3735
38Unsupported third party contributions are provided in directory "contrib".
36Unsupported third party contributions are provided in directory contrib/ .
3937
40A Java implementation of zlib is available in the Java Development Kit
41http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/package-summary.html
42See the zlib home page http://www.zlib.org for details.
38zlib is available in Java using the java.util.zip package, documented at
39http://java.sun.com/developer/technicalArticles/Programming/compression/ .
4340
44A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is in the
45CPAN (Comprehensive Perl Archive Network) sites
46http://www.cpan.org/modules/by-module/Compress/
41A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is available
42at CPAN (Comprehensive Perl Archive Network) sites, including
43http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .
4744
4845A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
4946available in Python 1.5 and later versions, see
50http://www.python.org/doc/lib/module-zlib.html
47http://docs.python.org/library/zlib.html .
5148
52A zlib binding for TCL written by Andreas Kupries <a.kupries@westend.com> is
53availlable at http://www.oche.de/~akupries/soft/trf/trf_zip.html
49zlib is built into tcl: http://wiki.tcl.tk/4610 .
5450
5551An experimental package to read and write files in .zip format, written on top
5652of zlib by Gilles Vollant <info@winimage.com>, is available in the
r15677r15678
7470- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
7571  other compilers. Use "make test" to check your compiler.
7672
77- gzdopen is not supported on RISCOS, BEOS and by some Mac compilers.
73- gzdopen is not supported on RISCOS or BEOS.
7874
7975- For PalmOs, see http://palmzlib.sourceforge.net/
8076
81- When building a shared, i.e. dynamic library on Mac OS X, the library must be
82  installed before testing (do "make install" before "make test"), since the
83  library location is specified in the library.
8477
85
8678Acknowledgments:
8779
88  The deflate format used by zlib was defined by Phil Katz. The deflate
89  and zlib specifications were written by L. Peter Deutsch. Thanks to all the
90  people who reported problems and suggested various improvements in zlib;
91  they are too numerous to cite here.
80  The deflate format used by zlib was defined by Phil Katz.  The deflate and
81  zlib specifications were written by L.  Peter Deutsch.  Thanks to all the
82  people who reported problems and suggested various improvements in zlib; they
83  are too numerous to cite here.
9284
9385Copyright notice:
9486
95 (C) 1995-2004 Jean-loup Gailly and Mark Adler
87 (C) 1995-2012 Jean-loup Gailly and Mark Adler
9688
9789  This software is provided 'as-is', without any express or implied
9890  warranty.  In no event will the authors be held liable for any damages
r15677r15678
113105  Jean-loup Gailly        Mark Adler
114106  jloup@gzip.org          madler@alumni.caltech.edu
115107
116If you use the zlib library in a product, we would appreciate *not*
117receiving lengthy legal documents to sign. The sources are provided
118for free but without warranty of any kind.  The library has been
119entirely written by Jean-loup Gailly and Mark Adler; it does not
120include third-party code.
108If you use the zlib library in a product, we would appreciate *not* receiving
109lengthy legal documents to sign.  The sources are provided for free but without
110warranty of any kind.  The library has been entirely written by Jean-loup
111Gailly and Mark Adler; it does not include third-party code.
121112
122If you redistribute modified sources, we would appreciate that you include
123in the file ChangeLog history information documenting your changes. Please
124read the FAQ for more information on the distribution of modified source
125versions.
113If you redistribute modified sources, we would appreciate that you include in
114the file ChangeLog history information documenting your changes.  Please read
115the FAQ for more information on the distribution of modified source versions.
src/lib/zlib/inftrees.c
r15677r15678
11/* inftrees.c -- generate Huffman trees for efficient decoding
2 * Copyright (C) 1995-2005 Mark Adler
2 * Copyright (C) 1995-2012 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
99#define MAXBITS 15
1010
1111const char inflate_copyright[] =
12   " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
12   " inflate 1.2.7 Copyright 1995-2012 Mark Adler ";
1313/*
1414  If you use the zlib library in a product, an acknowledgment is welcome
1515  in the documentation of your product. If for some reason you cannot
r15677r15678
2929   table index bits.  It will differ if the request is greater than the
3030   longest code or if it is less than the shortest code.
3131 */
32int inflate_table(type, lens, codes, table, bits, work)
32int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
3333codetype type;
3434unsigned short FAR *lens;
3535unsigned codes;
r15677r15678
5050    unsigned fill;              /* index for replicating entries */
5151    unsigned low;               /* low bits for current root entry */
5252    unsigned mask;              /* mask for low root bits */
53    code this;                  /* table entry for duplication */
53    code here;                  /* table entry for duplication */
5454    code FAR *next;             /* next available space in table */
5555    const unsigned short FAR *base;     /* base value table to use */
5656    const unsigned short FAR *extra;    /* extra bits table to use */
r15677r15678
6262        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
6363    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
6464        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
65        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
65        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 78, 68};
6666    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
6767        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
6868        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
r15677r15678
115115        if (count[max] != 0) break;
116116    if (root > max) root = max;
117117    if (max == 0) {                     /* no symbols to code at all */
118        this.op = (unsigned char)64;    /* invalid code marker */
119        this.bits = (unsigned char)1;
120        this.val = (unsigned short)0;
121        *(*table)++ = this;             /* make a table to force an error */
122        *(*table)++ = this;
118        here.op = (unsigned char)64;    /* invalid code marker */
119        here.bits = (unsigned char)1;
120        here.val = (unsigned short)0;
121        *(*table)++ = here;             /* make a table to force an error */
122        *(*table)++ = here;
123123        *bits = 1;
124124        return 0;     /* no symbols, but wait for decoding to report error */
125125    }
126    for (min = 1; min <= MAXBITS; min++)
126    for (min = 1; min < max; min++)
127127        if (count[min] != 0) break;
128128    if (root < min) root = min;
129129
r15677r15678
166166       entered in the tables.
167167
168168       used keeps track of how many table entries have been allocated from the
169       provided *table space.  It is checked when a LENS table is being made
170       against the space in *table, ENOUGH, minus the maximum space needed by
171       the worst case distance code, MAXD.  This should never happen, but the
172       sufficiency of ENOUGH has not been proven exhaustively, hence the check.
173       This assumes that when type == LENS, bits == 9.
169       provided *table space.  It is checked for LENS and DIST tables against
170       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
171       the initial root table size constants.  See the comments in inftrees.h
172       for more information.
174173
175174       sym increments through all symbols, and the loop terminates when
176175       all codes of length max, i.e. all codes, have been processed.  This
r15677r15678
209208    mask = used - 1;            /* mask for comparing low */
210209
211210    /* check available table space */
212    if (type == LENS && used >= ENOUGH - MAXD)
211    if ((type == LENS && used >= ENOUGH_LENS) ||
212        (type == DISTS && used >= ENOUGH_DISTS))
213213        return 1;
214214
215215    /* process all codes and make table entries */
216216    for (;;) {
217217        /* create table entry */
218        this.bits = (unsigned char)(len - drop);
218        here.bits = (unsigned char)(len - drop);
219219        if ((int)(work[sym]) < end) {
220            this.op = (unsigned char)0;
221            this.val = work[sym];
220            here.op = (unsigned char)0;
221            here.val = work[sym];
222222        }
223223        else if ((int)(work[sym]) > end) {
224            this.op = (unsigned char)(extra[work[sym]]);
225            this.val = base[work[sym]];
224            here.op = (unsigned char)(extra[work[sym]]);
225            here.val = base[work[sym]];
226226        }
227227        else {
228            this.op = (unsigned char)(32 + 64);         /* end of block */
229            this.val = 0;
228            here.op = (unsigned char)(32 + 64);         /* end of block */
229            here.val = 0;
230230        }
231231
232232        /* replicate for those indices with low len bits equal to huff */
r15677r15678
235235        min = fill;                 /* save offset to next table */
236236        do {
237237            fill -= incr;
238            next[(huff >> drop) + fill] = this;
238            next[(huff >> drop) + fill] = here;
239239        } while (fill != 0);
240240
241241        /* backwards increment the len-bit code huff */
r15677r15678
277277
278278            /* check for enough space */
279279            used += 1U << curr;
280            if (type == LENS && used >= ENOUGH - MAXD)
280            if ((type == LENS && used >= ENOUGH_LENS) ||
281                (type == DISTS && used >= ENOUGH_DISTS))
281282                return 1;
282283
283284            /* point entry in root table to sub-table */
r15677r15678
288289        }
289290    }
290291
291    /*
292       Fill in rest of table for incomplete codes.  This loop is similar to the
293       loop above in incrementing huff for table indices.  It is assumed that
294       len is equal to curr + drop, so there is no loop needed to increment
295       through high index bits.  When the current sub-table is filled, the loop
296       drops back to the root table to fill in any remaining entries there.
297     */
298    this.op = (unsigned char)64;                /* invalid code marker */
299    this.bits = (unsigned char)(len - drop);
300    this.val = (unsigned short)0;
301    while (huff != 0) {
302        /* when done with sub-table, drop back to root table */
303        if (drop != 0 && (huff & mask) != low) {
304            drop = 0;
305            len = root;
306            next = *table;
307            this.bits = (unsigned char)len;
308        }
309
310        /* put invalid code marker in table */
311        next[huff >> drop] = this;
312
313        /* backwards increment the len-bit code huff */
314        incr = 1U << (len - 1);
315        while (huff & incr)
316            incr >>= 1;
317        if (incr != 0) {
318            huff &= incr - 1;
319            huff += incr;
320        }
321        else
322            huff = 0;
292    /* fill in remaining table entry if code is incomplete (guaranteed to have
293       at most one remaining entry, since if the code is incomplete, the
294       maximum code length that was allowed to get this far is one bit) */
295    if (huff != 0) {
296        here.op = (unsigned char)64;            /* invalid code marker */
297        here.bits = (unsigned char)(len - drop);
298        here.val = (unsigned short)0;
299        next[huff] = here;
323300    }
324301
325302    /* set return parameters */
src/lib/zlib/inflate.c
r15677r15678
11/* inflate.c -- zlib decompression
2 * Copyright (C) 1995-2005 Mark Adler
2 * Copyright (C) 1995-2012 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
4545 * - Rearrange window copies in inflate_fast() for speed and simplification
4646 * - Unroll last copy for window match in inflate_fast()
4747 * - Use local copies of window variables in inflate_fast() for speed
48 * - Pull out common write == 0 case for speed in inflate_fast()
48 * - Pull out common wnext == 0 case for speed in inflate_fast()
4949 * - Make op and len in inflate_fast() unsigned for consistency
5050 * - Add FAR to lcode and dcode declarations in inflate_fast()
5151 * - Simplified bad distance check in inflate_fast()
r15677r15678
100100local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
101101                              unsigned len));
102102
103int ZEXPORT inflateReset(strm)
103int ZEXPORT inflateResetKeep(strm)
104104z_streamp strm;
105105{
106106    struct inflate_state FAR *state;
r15677r15678
109109    state = (struct inflate_state FAR *)strm->state;
110110    strm->total_in = strm->total_out = state->total = 0;
111111    strm->msg = Z_NULL;
112    strm->adler = 1;        /* to support ill-conceived Java test suite */
112    if (state->wrap)        /* to support ill-conceived Java test suite */
113        strm->adler = state->wrap & 1;
113114    state->mode = HEAD;
114115    state->last = 0;
115116    state->havedict = 0;
116117    state->dmax = 32768U;
117118    state->head = Z_NULL;
118    state->wsize = 0;
119    state->whave = 0;
120    state->write = 0;
121119    state->hold = 0;
122120    state->bits = 0;
123121    state->lencode = state->distcode = state->next = state->codes;
122    state->sane = 1;
123    state->back = -1;
124124    Tracev((stderr, "inflate: reset\n"));
125125    return Z_OK;
126126}
127127
128int ZEXPORT inflatePrime(strm, bits, value)
128int ZEXPORT inflateReset(strm)
129129z_streamp strm;
130int bits;
131int value;
132130{
133131    struct inflate_state FAR *state;
134132
135133    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
136134    state = (struct inflate_state FAR *)strm->state;
137    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
138    value &= (1L << bits) - 1;
139    state->hold += value << state->bits;
140    state->bits += bits;
141    return Z_OK;
135    state->wsize = 0;
136    state->whave = 0;
137    state->wnext = 0;
138    return inflateResetKeep(strm);
142139}
143140
141int ZEXPORT inflateReset2(strm, windowBits)
142z_streamp strm;
143int windowBits;
144{
145    int wrap;
146    struct inflate_state FAR *state;
147
148    /* get the state */
149    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
150    state = (struct inflate_state FAR *)strm->state;
151
152    /* extract wrap request from windowBits parameter */
153    if (windowBits < 0) {
154        wrap = 0;
155        windowBits = -windowBits;
156    }
157    else {
158        wrap = (windowBits >> 4) + 1;
159#ifdef GUNZIP
160        if (windowBits < 48)
161            windowBits &= 15;
162#endif
163    }
164
165    /* set number of window bits, free window if different */
166    if (windowBits && (windowBits < 8 || windowBits > 15))
167        return Z_STREAM_ERROR;
168    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
169        ZFREE(strm, state->window);
170        state->window = Z_NULL;
171    }
172
173    /* update state and reset the rest of it */
174    state->wrap = wrap;
175    state->wbits = (unsigned)windowBits;
176    return inflateReset(strm);
177}
178
144179int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
145180z_streamp strm;
146181int windowBits;
147182const char *version;
148183int stream_size;
149184{
185    int ret;
150186    struct inflate_state FAR *state;
151187
152188    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
r15677r15678
155191    if (strm == Z_NULL) return Z_STREAM_ERROR;
156192    strm->msg = Z_NULL;                 /* in case we return an error */
157193    if (strm->zalloc == (alloc_func)0) {
194#ifdef Z_SOLO
195        return Z_STREAM_ERROR;
196#else
158197        strm->zalloc = zcalloc;
159198        strm->opaque = (voidpf)0;
199#endif
160200    }
161    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
201    if (strm->zfree == (free_func)0)
202#ifdef Z_SOLO
203        return Z_STREAM_ERROR;
204#else
205        strm->zfree = zcfree;
206#endif
162207    state = (struct inflate_state FAR *)
163208            ZALLOC(strm, 1, sizeof(struct inflate_state));
164209    if (state == Z_NULL) return Z_MEM_ERROR;
165210    Tracev((stderr, "inflate: allocated\n"));
166211    strm->state = (struct internal_state FAR *)state;
167    if (windowBits < 0) {
168        state->wrap = 0;
169        windowBits = -windowBits;
170    }
171    else {
172        state->wrap = (windowBits >> 4) + 1;
173#ifdef GUNZIP
174        if (windowBits < 48) windowBits &= 15;
175#endif
176    }
177    if (windowBits < 8 || windowBits > 15) {
212    state->window = Z_NULL;
213    ret = inflateReset2(strm, windowBits);
214    if (ret != Z_OK) {
178215        ZFREE(strm, state);
179216        strm->state = Z_NULL;
180        return Z_STREAM_ERROR;
181217    }
182    state->wbits = (unsigned)windowBits;
183    state->window = Z_NULL;
184    return inflateReset(strm);
218    return ret;
185219}
186220
187221int ZEXPORT inflateInit_(strm, version, stream_size)
r15677r15678
192226    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
193227}
194228
229int ZEXPORT inflatePrime(strm, bits, value)
230z_streamp strm;
231int bits;
232int value;
233{
234    struct inflate_state FAR *state;
235
236    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
237    state = (struct inflate_state FAR *)strm->state;
238    if (bits < 0) {
239        state->hold = 0;
240        state->bits = 0;
241        return Z_OK;
242    }
243    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
244    value &= (1L << bits) - 1;
245    state->hold += value << state->bits;
246    state->bits += bits;
247    return Z_OK;
248}
249
195250/*
196251   Return state with length and distance decoding tables and index sizes set to
197252   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
r15677r15678
286341    low = 0;
287342    for (;;) {
288343        if ((low % 7) == 0) printf("\n        ");
289        printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
290               state.lencode[low].val);
344        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
345               state.lencode[low].bits, state.lencode[low].val);
291346        if (++low == size) break;
292347        putchar(',');
293348    }
r15677r15678
340395    /* if window not in use yet, initialize */
341396    if (state->wsize == 0) {
342397        state->wsize = 1U << state->wbits;
343        state->write = 0;
398        state->wnext = 0;
344399        state->whave = 0;
345400    }
346401
r15677r15678
348403    copy = out - strm->avail_out;
349404    if (copy >= state->wsize) {
350405        zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
351        state->write = 0;
406        state->wnext = 0;
352407        state->whave = state->wsize;
353408    }
354409    else {
355        dist = state->wsize - state->write;
410        dist = state->wsize - state->wnext;
356411        if (dist > copy) dist = copy;
357        zmemcpy(state->window + state->write, strm->next_out - copy, dist);
412        zmemcpy(state->window + state->wnext, strm->next_out - copy, dist);
358413        copy -= dist;
359414        if (copy) {
360415            zmemcpy(state->window, strm->next_out - copy, copy);
361            state->write = copy;
416            state->wnext = copy;
362417            state->whave = state->wsize;
363418        }
364419        else {
365            state->write += dist;
366            if (state->write == state->wsize) state->write = 0;
420            state->wnext += dist;
421            if (state->wnext == state->wsize) state->wnext = 0;
367422            if (state->whave < state->wsize) state->whave += dist;
368423        }
369424    }
r15677r15678
464519        bits -= bits & 7; \
465520    } while (0)
466521
467/* Reverse the bytes in a 32-bit value */
468#define REVERSE(q) \
469    ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
470     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
471
472522/*
473523   inflate() uses a state machine to process as much input data and generate as
474524   much output data as possible before returning.  The state machine is
r15677r15678
564614    unsigned in, out;           /* save starting available input and output */
565615    unsigned copy;              /* number of stored or match bytes to copy */
566616    unsigned char FAR *from;    /* where to copy match bytes from */
567    code this;                  /* current decoding table entry */
617    code here;                  /* current decoding table entry */
568618    code last;                  /* parent table entry */
569619    unsigned len;               /* length to copy for repeats, bits to drop */
570620    int ret;                    /* return code */
r15677r15678
619669            }
620670            DROPBITS(4);
621671            len = BITS(4) + 8;
622            if (len > state->wbits) {
672            if (state->wbits == 0)
673                state->wbits = len;
674            else if (len > state->wbits) {
623675                strm->msg = (char *)"invalid window size";
624676                state->mode = BAD;
625677                break;
r15677r15678
760812#endif
761813        case DICTID:
762814            NEEDBITS(32);
763            strm->adler = state->check = REVERSE(hold);
815            strm->adler = state->check = ZSWAP32(hold);
764816            INITBITS();
765817            state->mode = DICT;
766818        case DICT:
r15677r15678
771823            strm->adler = state->check = adler32(0L, Z_NULL, 0);
772824            state->mode = TYPE;
773825        case TYPE:
774            if (flush == Z_BLOCK) goto inf_leave;
826            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
775827        case TYPEDO:
776828            if (state->last) {
777829                BYTEBITS();
r15677r15678
791843                fixedtables(state);
792844                Tracev((stderr, "inflate:     fixed codes block%s\n",
793845                        state->last ? " (last)" : ""));
794                state->mode = LEN;              /* decode codes */
846                state->mode = LEN_;             /* decode codes */
847                if (flush == Z_TREES) {
848                    DROPBITS(2);
849                    goto inf_leave;
850                }
795851                break;
796852            case 2:                             /* dynamic block */
797853                Tracev((stderr, "inflate:     dynamic codes block%s\n",
r15677r15678
816872            Tracev((stderr, "inflate:       stored length %u\n",
817873                    state->length));
818874            INITBITS();
875            state->mode = COPY_;
876            if (flush == Z_TREES) goto inf_leave;
877        case COPY_:
819878            state->mode = COPY;
820879        case COPY:
821880            copy = state->length;
r15677r15678
876935        case CODELENS:
877936            while (state->have < state->nlen + state->ndist) {
878937                for (;;) {
879                    this = state->lencode[BITS(state->lenbits)];
880                    if ((unsigned)(this.bits) <= bits) break;
938                    here = state->lencode[BITS(state->lenbits)];
939                    if ((unsigned)(here.bits) <= bits) break;
881940                    PULLBYTE();
882941                }
883                if (this.val < 16) {
884                    NEEDBITS(this.bits);
885                    DROPBITS(this.bits);
886                    state->lens[state->have++] = this.val;
942                if (here.val < 16) {
943                    DROPBITS(here.bits);
944                    state->lens[state->have++] = here.val;
887945                }
888946                else {
889                    if (this.val == 16) {
890                        NEEDBITS(this.bits + 2);
891                        DROPBITS(this.bits);
947                    if (here.val == 16) {
948                        NEEDBITS(here.bits + 2);
949                        DROPBITS(here.bits);
892950                        if (state->have == 0) {
893951                            strm->msg = (char *)"invalid bit length repeat";
894952                            state->mode = BAD;
r15677r15678
898956                        copy = 3 + BITS(2);
899957                        DROPBITS(2);
900958                    }
901                    else if (this.val == 17) {
902                        NEEDBITS(this.bits + 3);
903                        DROPBITS(this.bits);
959                    else if (here.val == 17) {
960                        NEEDBITS(here.bits + 3);
961                        DROPBITS(here.bits);
904962                        len = 0;
905963                        copy = 3 + BITS(3);
906964                        DROPBITS(3);
907965                    }
908966                    else {
909                        NEEDBITS(this.bits + 7);
910                        DROPBITS(this.bits);
967                        NEEDBITS(here.bits + 7);
968                        DROPBITS(here.bits);
911969                        len = 0;
912970                        copy = 11 + BITS(7);
913971                        DROPBITS(7);
r15677r15678
925983            /* handle error breaks in while */
926984            if (state->mode == BAD) break;
927985
928            /* build code tables */
986            /* check for end-of-block code (better have one) */
987            if (state->lens[256] == 0) {
988                strm->msg = (char *)"invalid code -- missing end-of-block";
989                state->mode = BAD;
990                break;
991            }
992
993            /* build code tables -- note: do not change the lenbits or distbits
994               values here (9 and 6) without reading the comments in inftrees.h
995               concerning the ENOUGH constants, which depend on those values */
929996            state->next = state->codes;
930997            state->lencode = (code const FAR *)(state->next);
931998            state->lenbits = 9;
r15677r15678
9461013                break;
9471014            }
9481015            Tracev((stderr, "inflate:       codes ok\n"));
1016            state->mode = LEN_;
1017            if (flush == Z_TREES) goto inf_leave;
1018        case LEN_:
9491019            state->mode = LEN;
9501020        case LEN:
9511021            if (have >= 6 && left >= 258) {
9521022                RESTORE();
9531023                inflate_fast(strm, out);
9541024                LOAD();
1025                if (state->mode == TYPE)
1026                    state->back = -1;
9551027                break;
9561028            }
1029            state->back = 0;
9571030            for (;;) {
958                this = state->lencode[BITS(state->lenbits)];
959                if ((unsigned)(this.bits) <= bits) break;
1031                here = state->lencode[BITS(state->lenbits)];
1032                if ((unsigned)(here.bits) <= bits) break;
9601033                PULLBYTE();
9611034            }
962            if (this.op && (this.op & 0xf0) == 0) {
963                last = this;
1035            if (here.op && (here.op & 0xf0) == 0) {
1036                last = here;
9641037                for (;;) {
965                    this = state->lencode[last.val +
1038                    here = state->lencode[last.val +
9661039                            (BITS(last.bits + last.op) >> last.bits)];
967                    if ((unsigned)(last.bits + this.bits) <= bits) break;
1040                    if ((unsigned)(last.bits + here.bits) <= bits) break;
9681041                    PULLBYTE();
9691042                }
9701043                DROPBITS(last.bits);
1044                state->back += last.bits;
9711045            }
972            DROPBITS(this.bits);
973            state->length = (unsigned)this.val;
974            if ((int)(this.op) == 0) {
975                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
1046            DROPBITS(here.bits);
1047            state->back += here.bits;
1048            state->length = (unsigned)here.val;
1049            if ((int)(here.op) == 0) {
1050                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
9761051                        "inflate:         literal '%c'\n" :
977                        "inflate:         literal 0x%02x\n", this.val));
1052                        "inflate:         literal 0x%02x\n", here.val));
9781053                state->mode = LIT;
9791054                break;
9801055            }
981            if (this.op & 32) {
1056            if (here.op & 32) {
9821057                Tracevv((stderr, "inflate:         end of block\n"));
1058                state->back = -1;
9831059                state->mode = TYPE;
9841060                break;
9851061            }
986            if (this.op & 64) {
1062            if (here.op & 64) {
9871063                strm->msg = (char *)"invalid literal/length code";
9881064                state->mode = BAD;
9891065                break;
9901066            }
991            state->extra = (unsigned)(this.op) & 15;
1067            state->extra = (unsigned)(here.op) & 15;
9921068            state->mode = LENEXT;
9931069        case LENEXT:
9941070            if (state->extra) {
9951071                NEEDBITS(state->extra);
9961072                state->length += BITS(state->extra);
9971073                DROPBITS(state->extra);
1074                state->back += state->extra;
9981075            }
9991076            Tracevv((stderr, "inflate:         length %u\n", state->length));
1077            state->was = state->length;
10001078            state->mode = DIST;
10011079        case DIST:
10021080            for (;;) {
1003                this = state->distcode[BITS(state->distbits)];
1004                if ((unsigned)(this.bits) <= bits) break;
1081                here = state->distcode[BITS(state->distbits)];
1082                if ((unsigned)(here.bits) <= bits) break;
10051083                PULLBYTE();
10061084            }
1007            if ((this.op & 0xf0) == 0) {
1008                last = this;
1085            if ((here.op & 0xf0) == 0) {
1086                last = here;
10091087                for (;;) {
1010                    this = state->distcode[last.val +
1088                    here = state->distcode[last.val +
10111089                            (BITS(last.bits + last.op) >> last.bits)];
1012                    if ((unsigned)(last.bits + this.bits) <= bits) break;
1090                    if ((unsigned)(last.bits + here.bits) <= bits) break;
10131091                    PULLBYTE();
10141092                }
10151093                DROPBITS(last.bits);
1094                state->back += last.bits;
10161095            }
1017            DROPBITS(this.bits);
1018            if (this.op & 64) {
1096            DROPBITS(here.bits);
1097            state->back += here.bits;
1098            if (here.op & 64) {
10191099                strm->msg = (char *)"invalid distance code";
10201100                state->mode = BAD;
10211101                break;
10221102            }
1023            state->offset = (unsigned)this.val;
1024            state->extra = (unsigned)(this.op) & 15;
1103            state->offset = (unsigned)here.val;
1104            state->extra = (unsigned)(here.op) & 15;
10251105            state->mode = DISTEXT;
10261106        case DISTEXT:
10271107            if (state->extra) {
10281108                NEEDBITS(state->extra);
10291109                state->offset += BITS(state->extra);
10301110                DROPBITS(state->extra);
1111                state->back += state->extra;
10311112            }
10321113#ifdef INFLATE_STRICT
10331114            if (state->offset > state->dmax) {
r15677r15678
10361117                break;
10371118            }
10381119#endif
1039            if (state->offset > state->whave + out - left) {
1040                strm->msg = (char *)"invalid distance too far back";
1041                state->mode = BAD;
1042                break;
1043            }
10441120            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
10451121            state->mode = MATCH;
10461122        case MATCH:
r15677r15678
10481124            copy = out - left;
10491125            if (state->offset > copy) {         /* copy from window */
10501126                copy = state->offset - copy;
1051                if (copy > state->write) {
1052                    copy -= state->write;
1127                if (copy > state->whave) {
1128                    if (state->sane) {
1129                        strm->msg = (char *)"invalid distance too far back";
1130                        state->mode = BAD;
1131                        break;
1132                    }
1133#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1134                    Trace((stderr, "inflate.c too far\n"));
1135                    copy -= state->whave;
1136                    if (copy > state->length) copy = state->length;
1137                    if (copy > left) copy = left;
1138                    left -= copy;
1139                    state->length -= copy;
1140                    do {
1141                        *put++ = 0;
1142                    } while (--copy);
1143                    if (state->length == 0) state->mode = LEN;
1144                    break;
1145#endif
1146                }
1147                if (copy > state->wnext) {
1148                    copy -= state->wnext;
10531149                    from = state->window + (state->wsize - copy);
10541150                }
10551151                else
1056                    from = state->window + (state->write - copy);
1152                    from = state->window + (state->wnext - copy);
10571153                if (copy > state->length) copy = state->length;
10581154            }
10591155            else {                              /* copy from output */
r15677r15678
10881184#ifdef GUNZIP
10891185                     state->flags ? hold :
10901186#endif
1091                     REVERSE(hold)) != state->check) {
1187                     ZSWAP32(hold)) != state->check) {
10921188                    strm->msg = (char *)"incorrect data check";
10931189                    state->mode = BAD;
10941190                    break;
r15677r15678
11321228     */
11331229  inf_leave:
11341230    RESTORE();
1135    if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
1231    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
1232            (state->mode < CHECK || flush != Z_FINISH)))
11361233        if (updatewindow(strm, out)) {
11371234            state->mode = MEM;
11381235            return Z_MEM_ERROR;
r15677r15678
11461243        strm->adler = state->check =
11471244            UPDATE(state->check, strm->next_out - out, out);
11481245    strm->data_type = state->bits + (state->last ? 64 : 0) +
1149                      (state->mode == TYPE ? 128 : 0);
1246                      (state->mode == TYPE ? 128 : 0) +
1247                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
11501248    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
11511249        ret = Z_BUF_ERROR;
11521250    return ret;
r15677r15678
11721270uInt dictLength;
11731271{
11741272    struct inflate_state FAR *state;
1175    unsigned long id;
1273    unsigned long dictid;
1274    unsigned char *next;
1275    unsigned avail;
1276    int ret;
11761277
11771278    /* check state */
11781279    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
r15677r15678
11801281    if (state->wrap != 0 && state->mode != DICT)
11811282        return Z_STREAM_ERROR;
11821283
1183    /* check for correct dictionary id */
1284    /* check for correct dictionary identifier */
11841285    if (state->mode == DICT) {
1185        id = adler32(0L, Z_NULL, 0);
1186        id = adler32(id, dictionary, dictLength);
1187        if (id != state->check)
1286        dictid = adler32(0L, Z_NULL, 0);
1287        dictid = adler32(dictid, dictionary, dictLength);
1288        if (dictid != state->check)
11881289            return Z_DATA_ERROR;
11891290    }
11901291
1191    /* copy dictionary to window */
1192    if (updatewindow(strm, strm->avail_out)) {
1292    /* copy dictionary to window using updatewindow(), which will amend the
1293       existing dictionary if appropriate */
1294    next = strm->next_out;
1295    avail = strm->avail_out;
1296    strm->next_out = (Bytef *)dictionary + dictLength;
1297    strm->avail_out = 0;
1298    ret = updatewindow(strm, dictLength);
1299    strm->avail_out = avail;
1300    strm->next_out = next;
1301    if (ret) {
11931302        state->mode = MEM;
11941303        return Z_MEM_ERROR;
11951304    }
1196    if (dictLength > state->wsize) {
1197        zmemcpy(state->window, dictionary + dictLength - state->wsize,
1198                state->wsize);
1199        state->whave = state->wsize;
1200    }
1201    else {
1202        zmemcpy(state->window + state->wsize - dictLength, dictionary,
1203                dictLength);
1204        state->whave = dictLength;
1205    }
12061305    state->havedict = 1;
12071306    Tracev((stderr, "inflate:   dictionary set\n"));
12081307    return Z_OK;
r15677r15678
13501449    }
13511450
13521451    /* copy state */
1353    zmemcpy(dest, source, sizeof(z_stream));
1354    zmemcpy(copy, state, sizeof(struct inflate_state));
1452    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1453    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
13551454    if (state->lencode >= state->codes &&
13561455        state->lencode <= state->codes + ENOUGH - 1) {
13571456        copy->lencode = copy->codes + (state->lencode - state->codes);
r15677r15678
13661465    dest->state = (struct internal_state FAR *)copy;
13671466    return Z_OK;
13681467}
1468
1469int ZEXPORT inflateUndermine(strm, subvert)
1470z_streamp strm;
1471int subvert;
1472{
1473    struct inflate_state FAR *state;
1474
1475    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1476    state = (struct inflate_state FAR *)strm->state;
1477    state->sane = !subvert;
1478#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1479    return Z_OK;
1480#else
1481    state->sane = 1;
1482    return Z_DATA_ERROR;
1483#endif
1484}
1485
1486long ZEXPORT inflateMark(strm)
1487z_streamp strm;
1488{
1489    struct inflate_state FAR *state;
1490
1491    if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;
1492    state = (struct inflate_state FAR *)strm->state;
1493    return ((long)(state->back) << 16) +
1494        (state->mode == COPY ? state->length :
1495            (state->mode == MATCH ? state->was - state->length : 0));
1496}
src/lib/zlib/uncompr.c
r15677r15678
11/* uncompr.c -- decompress a memory buffer
2 * Copyright (C) 1995-2003 Jean-loup Gailly.
2 * Copyright (C) 1995-2003, 2010 Jean-loup Gailly.
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
1616   been saved previously by the compressor and transmitted to the decompressor
1717   by some mechanism outside the scope of this compression library.)
1818   Upon exit, destLen is the actual size of the compressed buffer.
19     This function can be used to decompress a whole file at once if the
20   input file is mmap'ed.
2119
2220     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
2321   enough memory, Z_BUF_ERROR if there was not enough room in the output
src/lib/zlib/inftrees.h
r15677r15678
11/* inftrees.h -- header to use inftrees.c
2 * Copyright (C) 1995-2005 Mark Adler
2 * Copyright (C) 1995-2005, 2010 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
3535    01000000 - invalid code
3636 */
3737
38/* Maximum size of dynamic tree.  The maximum found in a long but non-
39   exhaustive search was 1444 code structures (852 for length/literals
40   and 592 for distances, the latter actually the result of an
41   exhaustive search).  The true maximum is not known, but the value
42   below is more than safe. */
43#define ENOUGH 2048
44#define MAXD 592
38/* Maximum size of the dynamic table.  The maximum number of code structures is
39   1444, which is the sum of 852 for literal/length codes and 592 for distance
40   codes.  These values were found by exhaustive searches using the program
41   examples/enough.c found in the zlib distribtution.  The arguments to that
42   program are the number of symbols, the initial root table size, and the
43   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
44   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
45   The initial root table size (9 or 6) is found in the fifth argument of the
46   inflate_table() calls in inflate.c and infback.c.  If the root table size is
47   changed, then these maximum sizes would be need to be recalculated and
48   updated. */
49#define ENOUGH_LENS 852
50#define ENOUGH_DISTS 592
51#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
4552
46/* Type of code to build for inftable() */
53/* Type of code to build for inflate_table() */
4754typedef enum {
4855    CODES,
4956    LENS,
5057    DISTS
5158} codetype;
5259
53extern int inflate_table OF((codetype type, unsigned short FAR *lens,
60int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
5461                             unsigned codes, code FAR * FAR *table,
5562                             unsigned FAR *bits, unsigned short FAR *work));
src/lib/zlib/inflate.h
r15677r15678
11/* inflate.h -- internal inflate state definition
2 * Copyright (C) 1995-2004 Mark Adler
2 * Copyright (C) 1995-2009 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
3232        TYPE,       /* i: waiting for type bits, including last-flag bit */
3333        TYPEDO,     /* i: same, but skip check to exit inflate on new block */
3434        STORED,     /* i: waiting for stored size (length and complement) */
35        COPY_,      /* i/o: same as COPY below, but only first time in */
3536        COPY,       /* i/o: waiting for input or output to copy stored block */
3637        TABLE,      /* i: waiting for dynamic block table lengths */
3738        LENLENS,    /* i: waiting for code length code lengths */
3839        CODELENS,   /* i: waiting for length/lit and distance code lengths */
39            LEN,        /* i: waiting for length/lit code */
40            LEN_,       /* i: same as LEN below, but only first time in */
41            LEN,        /* i: waiting for length/lit/eob code */
4042            LENEXT,     /* i: waiting for length extra bits */
4143            DIST,       /* i: waiting for distance code */
4244            DISTEXT,    /* i: waiting for distance extra bits */
r15677r15678
5355/*
5456    State transitions between above modes -
5557
56    (most modes can go to the BAD or MEM mode -- not shown for clarity)
58    (most modes can go to BAD or MEM on error -- not shown for clarity)
5759
5860    Process header:
59        HEAD -> (gzip) or (zlib)
60        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
61        NAME -> COMMENT -> HCRC -> TYPE
61        HEAD -> (gzip) or (zlib) or (raw)
62        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
63                  HCRC -> TYPE
6264        (zlib) -> DICTID or TYPE
6365        DICTID -> DICT -> TYPE
66        (raw) -> TYPEDO
6467    Read deflate blocks:
65            TYPE -> STORED or TABLE or LEN or CHECK
66            STORED -> COPY -> TYPE
67            TABLE -> LENLENS -> CODELENS -> LEN
68    Read deflate codes:
68            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
69            STORED -> COPY_ -> COPY -> TYPE
70            TABLE -> LENLENS -> CODELENS -> LEN_
71            LEN_ -> LEN
72    Read deflate codes in fixed or dynamic block:
6973                LEN -> LENEXT or LIT or TYPE
7074                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
7175                LIT -> LEN
r15677r15678
7377        CHECK -> LENGTH -> DONE
7478 */
7579
76/* state maintained between inflate() calls.  Approximately 7K bytes. */
80/* state maintained between inflate() calls.  Approximately 10K bytes. */
7781struct inflate_state {
7882    inflate_mode mode;          /* current inflate mode */
7983    int last;                   /* true if processing last block */
r15677r15678
8892    unsigned wbits;             /* log base 2 of requested window size */
8993    unsigned wsize;             /* window size or zero if not using window */
9094    unsigned whave;             /* valid bytes in the window */
91    unsigned write;             /* window write index */
95    unsigned wnext;             /* window write index */
9296    unsigned char FAR *window;  /* allocated sliding window, if needed */
9397        /* bit accumulator */
9498    unsigned long hold;         /* input bit accumulator */
r15677r15678
112116    unsigned short lens[320];   /* temporary storage for code lengths */
113117    unsigned short work[288];   /* work area for code table building */
114118    code codes[ENOUGH];         /* space for code tables */
119    int sane;                   /* if false, allow invalid distance too far */
120    int back;                   /* bits back of last unprocessed length/lit */
121    unsigned was;               /* initial length of match */
115122};
src/lib/zlib/gzguts.h
r0r15678
1/* gzguts.h -- zlib internal header definitions for gz* operations
2 * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6#ifdef _LARGEFILE64_SOURCE
7#  ifndef _LARGEFILE_SOURCE
8#    define _LARGEFILE_SOURCE 1
9#  endif
10#  ifdef _FILE_OFFSET_BITS
11#    undef _FILE_OFFSET_BITS
12#  endif
13#endif
14
15#ifdef HAVE_HIDDEN
16#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
17#else
18#  define ZLIB_INTERNAL
19#endif
20
21#include <stdio.h>
22#include "zlib.h"
23#ifdef STDC
24#  include <string.h>
25#  include <stdlib.h>
26#  include <limits.h>
27#endif
28#include <fcntl.h>
29
30#ifdef _WIN32
31#  include <stddef.h>
32#endif
33
34#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)
35#  include <io.h>
36#endif
37
38#ifdef NO_DEFLATE       /* for compatibility with old definition */
39#  define NO_GZCOMPRESS
40#endif
41
42#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
43#  ifndef HAVE_VSNPRINTF
44#    define HAVE_VSNPRINTF
45#  endif
46#endif
47
48#if defined(__CYGWIN__)
49#  ifndef HAVE_VSNPRINTF
50#    define HAVE_VSNPRINTF
51#  endif
52#endif
53
54#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)
55#  ifndef HAVE_VSNPRINTF
56#    define HAVE_VSNPRINTF
57#  endif
58#endif
59
60#ifndef HAVE_VSNPRINTF
61#  ifdef MSDOS
62/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
63 but for now we just assume it doesn't. */
64#    define NO_vsnprintf
65#  endif
66#  ifdef __TURBOC__
67#    define NO_vsnprintf
68#  endif
69#  ifdef WIN32
70/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
71#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
72#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
73#         define vsnprintf _vsnprintf
74#      endif
75#    endif
76#  endif
77#  ifdef __SASC
78#    define NO_vsnprintf
79#  endif
80#  ifdef VMS
81#    define NO_vsnprintf
82#  endif
83#  ifdef __OS400__
84#    define NO_vsnprintf
85#  endif
86#  ifdef __MVS__
87#    define NO_vsnprintf
88#  endif
89#endif
90
91#ifndef local
92#  define local static
93#endif
94/* compile with -Dlocal if your debugger can't find static symbols */
95
96/* gz* functions always use library allocation functions */
97#ifndef STDC
98  extern voidp  malloc OF((uInt size));
99  extern void   free   OF((voidpf ptr));
100#endif
101
102/* get errno and strerror definition */
103#if defined UNDER_CE
104#  include <windows.h>
105#  define zstrerror() gz_strwinerror((DWORD)GetLastError())
106#else
107#  ifndef NO_STRERROR
108#    include <errno.h>
109#    define zstrerror() strerror(errno)
110#  else
111#    define zstrerror() "stdio error (consult errno)"
112#  endif
113#endif
114
115/* provide prototypes for these when building zlib without LFS */
116#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
117    ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
118    ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
119    ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
120    ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
121#endif
122
123/* default memLevel */
124#if MAX_MEM_LEVEL >= 8
125#  define DEF_MEM_LEVEL 8
126#else
127#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
128#endif
129
130/* default i/o buffer size -- double this for output when reading */
131#define GZBUFSIZE 8192
132
133/* gzip modes, also provide a little integrity check on the passed structure */
134#define GZ_NONE 0
135#define GZ_READ 7247
136#define GZ_WRITE 31153
137#define GZ_APPEND 1     /* mode set to GZ_WRITE after the file is opened */
138
139/* values for gz_state how */
140#define LOOK 0      /* look for a gzip header */
141#define COPY 1      /* copy input directly */
142#define GZIP 2      /* decompress a gzip stream */
143
144/* internal gzip file state data structure */
145typedef struct {
146        /* exposed contents for gzgetc() macro */
147    struct gzFile_s x;      /* "x" for exposed */
148                            /* x.have: number of bytes available at x.next */
149                            /* x.next: next output data to deliver or write */
150                            /* x.pos: current position in uncompressed data */
151        /* used for both reading and writing */
152    int mode;               /* see gzip modes above */
153    int fd;                 /* file descriptor */
154    char *path;             /* path or fd for error messages */
155    unsigned size;          /* buffer size, zero if not allocated yet */
156    unsigned want;          /* requested buffer size, default is GZBUFSIZE */
157    unsigned char *in;      /* input buffer */
158    unsigned char *out;     /* output buffer (double-sized when reading) */
159    int direct;             /* 0 if processing gzip, 1 if transparent */
160        /* just for reading */
161    int how;                /* 0: get header, 1: copy, 2: decompress */
162    z_off64_t start;        /* where the gzip data started, for rewinding */
163    int eof;                /* true if end of input file reached */
164    int past;               /* true if read requested past end */
165        /* just for writing */
166    int level;              /* compression level */
167    int strategy;           /* compression strategy */
168        /* seek request */
169    z_off64_t skip;         /* amount to skip (already rewound if backwards) */
170    int seek;               /* true if seek request pending */
171        /* error information */
172    int err;                /* error code */
173    char *msg;              /* error message */
174        /* zlib inflate or deflate stream */
175    z_stream strm;          /* stream structure in-place (not a pointer) */
176} gz_state;
177typedef gz_state FAR *gz_statep;
178
179/* shared functions */
180void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *));
181#if defined UNDER_CE
182char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error));
183#endif
184
185/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t
186   value -- needed when comparing unsigned to z_off64_t, which is signed
187   (possible z_off64_t types off_t, off64_t, and long are all signed) */
188#ifdef INT_MAX
189#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)
190#else
191unsigned ZLIB_INTERNAL gz_intmax OF((void));
192#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
193#endif
src/lib/zlib/zconf.h.in
r0r15678
1/* zconf.h -- configuration of the zlib compression library
2 * Copyright (C) 1995-2012 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#ifndef ZCONF_H
9#define ZCONF_H
10
11/*
12 * If you *really* need a unique prefix for all types and library functions,
13 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
14 * Even better than compiling with -DZ_PREFIX would be to use configure to set
15 * this permanently in zconf.h using "./configure --zprefix".
16 */
17#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
18#  define Z_PREFIX_SET
19
20/* all linked symbols */
21#  define _dist_code            z__dist_code
22#  define _length_code          z__length_code
23#  define _tr_align             z__tr_align
24#  define _tr_flush_block       z__tr_flush_block
25#  define _tr_init              z__tr_init
26#  define _tr_stored_block      z__tr_stored_block
27#  define _tr_tally             z__tr_tally
28#  define adler32               z_adler32
29#  define adler32_combine       z_adler32_combine
30#  define adler32_combine64     z_adler32_combine64
31#  ifndef Z_SOLO
32#    define compress              z_compress
33#    define compress2             z_compress2
34#    define compressBound         z_compressBound
35#  endif
36#  define crc32                 z_crc32
37#  define crc32_combine         z_crc32_combine
38#  define crc32_combine64       z_crc32_combine64
39#  define deflate               z_deflate
40#  define deflateBound          z_deflateBound
41#  define deflateCopy           z_deflateCopy
42#  define deflateEnd            z_deflateEnd
43#  define deflateInit2_         z_deflateInit2_
44#  define deflateInit_          z_deflateInit_
45#  define deflateParams         z_deflateParams
46#  define deflatePending        z_deflatePending
47#  define deflatePrime          z_deflatePrime
48#  define deflateReset          z_deflateReset
49#  define deflateResetKeep      z_deflateResetKeep
50#  define deflateSetDictionary  z_deflateSetDictionary
51#  define deflateSetHeader      z_deflateSetHeader
52#  define deflateTune           z_deflateTune
53#  define deflate_copyright     z_deflate_copyright
54#  define get_crc_table         z_get_crc_table
55#  ifndef Z_SOLO
56#    define gz_error              z_gz_error
57#    define gz_intmax             z_gz_intmax
58#    define gz_strwinerror        z_gz_strwinerror
59#    define gzbuffer              z_gzbuffer
60#    define gzclearerr            z_gzclearerr
61#    define gzclose               z_gzclose
62#    define gzclose_r             z_gzclose_r
63#    define gzclose_w             z_gzclose_w
64#    define gzdirect              z_gzdirect
65#    define gzdopen               z_gzdopen
66#    define gzeof                 z_gzeof
67#    define gzerror               z_gzerror
68#    define gzflush               z_gzflush
69#    define gzgetc                z_gzgetc
70#    define gzgetc_               z_gzgetc_
71#    define gzgets                z_gzgets
72#    define gzoffset              z_gzoffset
73#    define gzoffset64            z_gzoffset64
74#    define gzopen                z_gzopen
75#    define gzopen64              z_gzopen64
76#    ifdef _WIN32
77#      define gzopen_w              z_gzopen_w
78#    endif
79#    define gzprintf              z_gzprintf
80#    define gzputc                z_gzputc
81#    define gzputs                z_gzputs
82#    define gzread                z_gzread
83#    define gzrewind              z_gzrewind
84#    define gzseek                z_gzseek
85#    define gzseek64              z_gzseek64
86#    define gzsetparams           z_gzsetparams
87#    define gztell                z_gztell
88#    define gztell64              z_gztell64
89#    define gzungetc              z_gzungetc
90#    define gzwrite               z_gzwrite
91#  endif
92#  define inflate               z_inflate
93#  define inflateBack           z_inflateBack
94#  define inflateBackEnd        z_inflateBackEnd
95#  define inflateBackInit_      z_inflateBackInit_
96#  define inflateCopy           z_inflateCopy
97#  define inflateEnd            z_inflateEnd
98#  define inflateGetHeader      z_inflateGetHeader
99#  define inflateInit2_         z_inflateInit2_
100#  define inflateInit_          z_inflateInit_
101#  define inflateMark           z_inflateMark
102#  define inflatePrime          z_inflatePrime
103#  define inflateReset          z_inflateReset
104#  define inflateReset2         z_inflateReset2
105#  define inflateSetDictionary  z_inflateSetDictionary
106#  define inflateSync           z_inflateSync
107#  define inflateSyncPoint      z_inflateSyncPoint
108#  define inflateUndermine      z_inflateUndermine
109#  define inflateResetKeep      z_inflateResetKeep
110#  define inflate_copyright     z_inflate_copyright
111#  define inflate_fast          z_inflate_fast
112#  define inflate_table         z_inflate_table
113#  ifndef Z_SOLO
114#    define uncompress            z_uncompress
115#  endif
116#  define zError                z_zError
117#  ifndef Z_SOLO
118#    define zcalloc               z_zcalloc
119#    define zcfree                z_zcfree
120#  endif
121#  define zlibCompileFlags      z_zlibCompileFlags
122#  define zlibVersion           z_zlibVersion
123
124/* all zlib typedefs in zlib.h and zconf.h */
125#  define Byte                  z_Byte
126#  define Bytef                 z_Bytef
127#  define alloc_func            z_alloc_func
128#  define charf                 z_charf
129#  define free_func             z_free_func
130#  ifndef Z_SOLO
131#    define gzFile                z_gzFile
132#  endif
133#  define gz_header             z_gz_header
134#  define gz_headerp            z_gz_headerp
135#  define in_func               z_in_func
136#  define intf                  z_intf
137#  define out_func              z_out_func
138#  define uInt                  z_uInt
139#  define uIntf                 z_uIntf
140#  define uLong                 z_uLong
141#  define uLongf                z_uLongf
142#  define voidp                 z_voidp
143#  define voidpc                z_voidpc
144#  define voidpf                z_voidpf
145
146/* all zlib structs in zlib.h and zconf.h */
147#  define gz_header_s           z_gz_header_s
148#  define internal_state        z_internal_state
149
150#endif
151
152#if defined(__MSDOS__) && !defined(MSDOS)
153#  define MSDOS
154#endif
155#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
156#  define OS2
157#endif
158#if defined(_WINDOWS) && !defined(WINDOWS)
159#  define WINDOWS
160#endif
161#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
162#  ifndef WIN32
163#    define WIN32
164#  endif
165#endif
166#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
167#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
168#    ifndef SYS16BIT
169#      define SYS16BIT
170#    endif
171#  endif
172#endif
173
174/*
175 * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
176 * than 64k bytes at a time (needed on systems with 16-bit int).
177 */
178#ifdef SYS16BIT
179#  define MAXSEG_64K
180#endif
181#ifdef MSDOS
182#  define UNALIGNED_OK
183#endif
184
185#ifdef __STDC_VERSION__
186#  ifndef STDC
187#    define STDC
188#  endif
189#  if __STDC_VERSION__ >= 199901L
190#    ifndef STDC99
191#      define STDC99
192#    endif
193#  endif
194#endif
195#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
196#  define STDC
197#endif
198#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
199#  define STDC
200#endif
201#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
202#  define STDC
203#endif
204#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
205#  define STDC
206#endif
207
208#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
209#  define STDC
210#endif
211
212#ifndef STDC
213#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
214#    define const       /* note: need a more gentle solution here */
215#  endif
216#endif
217
218#if defined(ZLIB_CONST) && !defined(z_const)
219#  define z_const const
220#else
221#  define z_const
222#endif
223
224/* Some Mac compilers merge all .h files incorrectly: */
225#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
226#  define NO_DUMMY_DECL
227#endif
228
229/* Maximum value for memLevel in deflateInit2 */
230#ifndef MAX_MEM_LEVEL
231#  ifdef MAXSEG_64K
232#    define MAX_MEM_LEVEL 8
233#  else
234#    define MAX_MEM_LEVEL 9
235#  endif
236#endif
237
238/* Maximum value for windowBits in deflateInit2 and inflateInit2.
239 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
240 * created by gzip. (Files created by minigzip can still be extracted by
241 * gzip.)
242 */
243#ifndef MAX_WBITS
244#  define MAX_WBITS   15 /* 32K LZ77 window */
245#endif
246
247/* The memory requirements for deflate are (in bytes):
248            (1 << (windowBits+2)) +  (1 << (memLevel+9))
249 that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
250 plus a few kilobytes for small objects. For example, if you want to reduce
251 the default memory requirements from 256K to 128K, compile with
252     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
253 Of course this will generally degrade compression (there's no free lunch).
254
255   The memory requirements for inflate are (in bytes) 1 << windowBits
256 that is, 32K for windowBits=15 (default value) plus a few kilobytes
257 for small objects.
258*/
259
260                        /* Type declarations */
261
262#ifndef OF /* function prototypes */
263#  ifdef STDC
264#    define OF(args)  args
265#  else
266#    define OF(args)  ()
267#  endif
268#endif
269
270#ifndef Z_ARG /* function prototypes for stdarg */
271#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
272#    define Z_ARG(args)  args
273#  else
274#    define Z_ARG(args)  ()
275#  endif
276#endif
277
278/* The following definitions for FAR are needed only for MSDOS mixed
279 * model programming (small or medium model with some far allocations).
280 * This was tested only with MSC; for other MSDOS compilers you may have
281 * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
282 * just define FAR to be empty.
283 */
284#ifdef SYS16BIT
285#  if defined(M_I86SM) || defined(M_I86MM)
286     /* MSC small or medium model */
287#    define SMALL_MEDIUM
288#    ifdef _MSC_VER
289#      define FAR _far
290#    else
291#      define FAR far
292#    endif
293#  endif
294#  if (defined(__SMALL__) || defined(__MEDIUM__))
295     /* Turbo C small or medium model */
296#    define SMALL_MEDIUM
297#    ifdef __BORLANDC__
298#      define FAR _far
299#    else
300#      define FAR far
301#    endif
302#  endif
303#endif
304
305#if defined(WINDOWS) || defined(WIN32)
306   /* If building or using zlib as a DLL, define ZLIB_DLL.
307    * This is not mandatory, but it offers a little performance increase.
308    */
309#  ifdef ZLIB_DLL
310#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
311#      ifdef ZLIB_INTERNAL
312#        define ZEXTERN extern __declspec(dllexport)
313#      else
314#        define ZEXTERN extern __declspec(dllimport)
315#      endif
316#    endif
317#  endif  /* ZLIB_DLL */
318   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
319    * define ZLIB_WINAPI.
320    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
321    */
322#  ifdef ZLIB_WINAPI
323#    ifdef FAR
324#      undef FAR
325#    endif
326#    include <windows.h>
327     /* No need for _export, use ZLIB.DEF instead. */
328     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
329#    define ZEXPORT WINAPI
330#    ifdef WIN32
331#      define ZEXPORTVA WINAPIV
332#    else
333#      define ZEXPORTVA FAR CDECL
334#    endif
335#  endif
336#endif
337
338#if defined (__BEOS__)
339#  ifdef ZLIB_DLL
340#    ifdef ZLIB_INTERNAL
341#      define ZEXPORT   __declspec(dllexport)
342#      define ZEXPORTVA __declspec(dllexport)
343#    else
344#      define ZEXPORT   __declspec(dllimport)
345#      define ZEXPORTVA __declspec(dllimport)
346#    endif
347#  endif
348#endif
349
350#ifndef ZEXTERN
351#  define ZEXTERN extern
352#endif
353#ifndef ZEXPORT
354#  define ZEXPORT
355#endif
356#ifndef ZEXPORTVA
357#  define ZEXPORTVA
358#endif
359
360#ifndef FAR
361#  define FAR
362#endif
363
364#if !defined(__MACTYPES__)
365typedef unsigned char  Byte;  /* 8 bits */
366#endif
367typedef unsigned int   uInt;  /* 16 bits or more */
368typedef unsigned long  uLong; /* 32 bits or more */
369
370#ifdef SMALL_MEDIUM
371   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
372#  define Bytef Byte FAR
373#else
374   typedef Byte  FAR Bytef;
375#endif
376typedef char  FAR charf;
377typedef int   FAR intf;
378typedef uInt  FAR uIntf;
379typedef uLong FAR uLongf;
380
381#ifdef STDC
382   typedef void const *voidpc;
383   typedef void FAR   *voidpf;
384   typedef void       *voidp;
385#else
386   typedef Byte const *voidpc;
387   typedef Byte FAR   *voidpf;
388   typedef Byte       *voidp;
389#endif
390
391/* ./configure may #define Z_U4 here */
392
393#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
394#  include <limits.h>
395#  if (UINT_MAX == 0xffffffffUL)
396#    define Z_U4 unsigned
397#  else
398#    if (ULONG_MAX == 0xffffffffUL)
399#      define Z_U4 unsigned long
400#    else
401#      if (USHRT_MAX == 0xffffffffUL)
402#        define Z_U4 unsigned short
403#      endif
404#    endif
405#  endif
406#endif
407
408#ifdef Z_U4
409   typedef Z_U4 z_crc_t;
410#else
411   typedef unsigned long z_crc_t;
412#endif
413
414#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
415#  define Z_HAVE_UNISTD_H
416#endif
417
418#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
419#  define Z_HAVE_STDARG_H
420#endif
421
422#ifdef STDC
423#  ifndef Z_SOLO
424#    include <sys/types.h>      /* for off_t */
425#  endif
426#endif
427
428#ifdef _WIN32
429#  include <stddef.h>           /* for wchar_t */
430#endif
431
432/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
433 * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
434 * though the former does not conform to the LFS document), but considering
435 * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
436 * equivalently requesting no 64-bit operations
437 */
438#if defined(LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
439#  undef _LARGEFILE64_SOURCE
440#endif
441
442#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)
443#  define Z_HAVE_UNISTD_H
444#endif
445#ifndef Z_SOLO
446#  if defined(Z_HAVE_UNISTD_H) || defined(LARGEFILE64_SOURCE)
447#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
448#    ifdef VMS
449#      include <unixio.h>       /* for off_t */
450#    endif
451#    ifndef z_off_t
452#      define z_off_t off_t
453#    endif
454#  endif
455#endif
456
457#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
458#  define Z_LFS64
459#endif
460
461#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
462#  define Z_LARGE64
463#endif
464
465#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
466#  define Z_WANT64
467#endif
468
469#if !defined(SEEK_SET) && !defined(Z_SOLO)
470#  define SEEK_SET        0       /* Seek from beginning of file.  */
471#  define SEEK_CUR        1       /* Seek from current position.  */
472#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
473#endif
474
475#ifndef z_off_t
476#  define z_off_t long
477#endif
478
479#if !defined(_WIN32) && defined(Z_LARGE64)
480#  define z_off64_t off64_t
481#else
482#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)
483#    define z_off64_t __int64
484#  else
485#    define z_off64_t z_off_t
486#  endif
487#endif
488
489/* MVS linker does not support external names larger than 8 bytes */
490#if defined(__MVS__)
491  #pragma map(deflateInit_,"DEIN")
492  #pragma map(deflateInit2_,"DEIN2")
493  #pragma map(deflateEnd,"DEEND")
494  #pragma map(deflateBound,"DEBND")
495  #pragma map(inflateInit_,"ININ")
496  #pragma map(inflateInit2_,"ININ2")
497  #pragma map(inflateEnd,"INEND")
498  #pragma map(inflateSync,"INSY")
499  #pragma map(inflateSetDictionary,"INSEDI")
500  #pragma map(compressBound,"CMBND")
501  #pragma map(inflate_table,"INTABL")
502  #pragma map(inflate_fast,"INFA")
503  #pragma map(inflate_copyright,"INCOPY")
504#endif
505
506#endif /* ZCONF_H */
src/lib/zlib/adler32.c
r15677r15678
11/* adler32.c -- compute the Adler-32 checksum of a data stream
2 * Copyright (C) 1995-2004 Mark Adler
2 * Copyright (C) 1995-2011 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
66/* @(#) $Id$ */
77
8#define ZLIB_INTERNAL
9#include "zlib.h"
8#include "zutil.h"
109
11#define BASE 65521UL    /* largest prime smaller than 65536 */
10#define local static
11
12local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));
13
14#define BASE 65521      /* largest prime smaller than 65536 */
1215#define NMAX 5552
1316/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
1417
r15677r15678
1821#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
1922#define DO16(buf)   DO8(buf,0); DO8(buf,8);
2023
21/* use NO_DIVIDE if your processor does not do division in hardware */
24/* use NO_DIVIDE if your processor does not do division in hardware --
25   try it both ways to see which is faster */
2226#ifdef NO_DIVIDE
23#  define MOD(a) \
27/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
28   (thank you to John Reiser for pointing this out) */
29#  define CHOP(a) \
2430    do { \
25        if (a >= (BASE << 16)) a -= (BASE << 16); \
26        if (a >= (BASE << 15)) a -= (BASE << 15); \
27        if (a >= (BASE << 14)) a -= (BASE << 14); \
28        if (a >= (BASE << 13)) a -= (BASE << 13); \
29        if (a >= (BASE << 12)) a -= (BASE << 12); \
30        if (a >= (BASE << 11)) a -= (BASE << 11); \
31        if (a >= (BASE << 10)) a -= (BASE << 10); \
32        if (a >= (BASE << 9)) a -= (BASE << 9); \
33        if (a >= (BASE << 8)) a -= (BASE << 8); \
34        if (a >= (BASE << 7)) a -= (BASE << 7); \
35        if (a >= (BASE << 6)) a -= (BASE << 6); \
36        if (a >= (BASE << 5)) a -= (BASE << 5); \
37        if (a >= (BASE << 4)) a -= (BASE << 4); \
38        if (a >= (BASE << 3)) a -= (BASE << 3); \
39        if (a >= (BASE << 2)) a -= (BASE << 2); \
40        if (a >= (BASE << 1)) a -= (BASE << 1); \
31        unsigned long tmp = a >> 16; \
32        a &= 0xffffUL; \
33        a += (tmp << 4) - tmp; \
34    } while (0)
35#  define MOD28(a) \
36    do { \
37        CHOP(a); \
4138        if (a >= BASE) a -= BASE; \
4239    } while (0)
43#  define MOD4(a) \
40#  define MOD(a) \
4441    do { \
45        if (a >= (BASE << 4)) a -= (BASE << 4); \
46        if (a >= (BASE << 3)) a -= (BASE << 3); \
47        if (a >= (BASE << 2)) a -= (BASE << 2); \
48        if (a >= (BASE << 1)) a -= (BASE << 1); \
42        CHOP(a); \
43        MOD28(a); \
44    } while (0)
45#  define MOD63(a) \
46    do { /* this assumes a is not negative */ \
47        z_off64_t tmp = a >> 32; \
48        a &= 0xffffffffL; \
49        a += (tmp << 8) - (tmp << 5) + tmp; \
50        tmp = a >> 16; \
51        a &= 0xffffL; \
52        a += (tmp << 4) - tmp; \
53        tmp = a >> 16; \
54        a &= 0xffffL; \
55        a += (tmp << 4) - tmp; \
4956        if (a >= BASE) a -= BASE; \
5057    } while (0)
5158#else
5259#  define MOD(a) a %= BASE
53#  define MOD4(a) a %= BASE
60#  define MOD28(a) a %= BASE
61#  define MOD63(a) a %= BASE
5462#endif
5563
5664/* ========================================================================= */
r15677r15678
8997        }
9098        if (adler >= BASE)
9199            adler -= BASE;
92        MOD4(sum2);             /* only added so many BASE's */
100        MOD28(sum2);            /* only added so many BASE's */
93101        return adler | (sum2 << 16);
94102    }
95103
r15677r15678
125133}
126134
127135/* ========================================================================= */
128uLong ZEXPORT adler32_combine(adler1, adler2, len2)
136local uLong adler32_combine_(adler1, adler2, len2)
129137    uLong adler1;
130138    uLong adler2;
131    z_off_t len2;
139    z_off64_t len2;
132140{
133141    unsigned long sum1;
134142    unsigned long sum2;
135143    unsigned rem;
136144
145    /* for negative len, return invalid adler32 as a clue for debugging */
146    if (len2 < 0)
147        return 0xffffffffUL;
148
137149    /* the derivation of this formula is left as an exercise for the reader */
138    rem = (unsigned)(len2 % BASE);
150    MOD63(len2);                /* assumes len2 >= 0 */
151    rem = (unsigned)len2;
139152    sum1 = adler1 & 0xffff;
140153    sum2 = rem * sum1;
141154    MOD(sum2);
142155    sum1 += (adler2 & 0xffff) + BASE - 1;
143156    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
144    if (sum1 > BASE) sum1 -= BASE;
145    if (sum1 > BASE) sum1 -= BASE;
146    if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
147    if (sum2 > BASE) sum2 -= BASE;
157    if (sum1 >= BASE) sum1 -= BASE;
158    if (sum1 >= BASE) sum1 -= BASE;
159    if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
160    if (sum2 >= BASE) sum2 -= BASE;
148161    return sum1 | (sum2 << 16);
149162}
163
164/* ========================================================================= */
165uLong ZEXPORT adler32_combine(adler1, adler2, len2)
166    uLong adler1;
167    uLong adler2;
168    z_off_t len2;
169{
170    return adler32_combine_(adler1, adler2, len2);
171}
172
173uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
174    uLong adler1;
175    uLong adler2;
176    z_off64_t len2;
177{
178    return adler32_combine_(adler1, adler2, len2);
179}
src/lib/zlib/infback.c
r15677r15678
11/* infback.c -- inflate using a call-back interface
2 * Copyright (C) 1995-2005 Mark Adler
2 * Copyright (C) 1995-2011 Mark Adler
33 * For conditions of distribution and use, see copyright notice in zlib.h
44 */
55
r15677r15678
4242        return Z_STREAM_ERROR;
4343    strm->msg = Z_NULL;                 /* in case we return an error */
4444    if (strm->zalloc == (alloc_func)0) {
45#ifdef Z_SOLO
46        return Z_STREAM_ERROR;
47#else
4548        strm->zalloc = zcalloc;
4649        strm->opaque = (voidpf)0;
50#endif
4751    }
48    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
52    if (strm->zfree == (free_func)0)
53#ifdef Z_SOLO
54        return Z_STREAM_ERROR;
55#else
56    strm->zfree = zcfree;
57#endif
4958    state = (struct inflate_state FAR *)ZALLOC(strm, 1,
5059                                               sizeof(struct inflate_state));
5160    if (state == Z_NULL) return Z_MEM_ERROR;
r15677r15678
5564    state->wbits = windowBits;
5665    state->wsize = 1U << windowBits;
5766    state->window = window;
58    state->write = 0;
67    state->wnext = 0;
5968    state->whave = 0;
6069    return Z_OK;
6170}
r15677r15678
253262    unsigned bits;              /* bits in bit buffer */
254263    unsigned copy;              /* number of stored or match bytes to copy */
255264    unsigned char FAR *from;    /* where to copy match bytes from */
256    code this;                  /* current decoding table entry */
265    code here;                  /* current decoding table entry */
257266    code last;                  /* parent table entry */
258267    unsigned len;               /* length to copy for repeats, bits to drop */
259268    int ret;                    /* return code */
r15677r15678
389398            state->have = 0;
390399            while (state->have < state->nlen + state->ndist) {
391400                for (;;) {
392                    this = state->lencode[BITS(state->lenbits)];
393                    if ((unsigned)(this.bits) <= bits) break;
401                    here = state->lencode[BITS(state->lenbits)];
402                    if ((unsigned)(here.bits) <= bits) break;
394403                    PULLBYTE();
395404                }
396                if (this.val < 16) {
397                    NEEDBITS(this.bits);
398                    DROPBITS(this.bits);
399                    state->lens[state->have++] = this.val;
405                if (here.val < 16) {
406                    DROPBITS(here.bits);
407                    state->lens[state->have++] = here.val;
400408                }
401409                else {
402                    if (this.val == 16) {
403                        NEEDBITS(this.bits + 2);
404                        DROPBITS(this.bits);
410                    if (here.val == 16) {
411                        NEEDBITS(here.bits + 2);
412                        DROPBITS(here.bits);
405413                        if (state->have == 0) {
406414                            strm->msg = (char *)"invalid bit length repeat";
407415                            state->mode = BAD;
r15677r15678
411419                        copy = 3 + BITS(2);
412420                        DROPBITS(2);
413421                    }
414                    else if (this.val == 17) {
415                        NEEDBITS(this.bits + 3);
416                        DROPBITS(this.bits);
422                    else if (here.val == 17) {
423                        NEEDBITS(here.bits + 3);
424                        DROPBITS(here.bits);
417425                        len = 0;
418426                        copy = 3 + BITS(3);
419427                        DROPBITS(3);
420428                    }
421429                    else {
422                        NEEDBITS(this.bits + 7);
423                        DROPBITS(this.bits);
430                        NEEDBITS(here.bits + 7);
431                        DROPBITS(here.bits);
424432                        len = 0;
425433                        copy = 11 + BITS(7);
426434                        DROPBITS(7);
r15677r15678
438446            /* handle error breaks in while */
439447            if (state->mode == BAD) break;
440448
441            /* build code tables */
449            /* check for end-of-block code (better have one) */
450            if (state->lens[256] == 0) {
451                strm->msg = (char *)"invalid code -- missing end-of-block";
452                state->mode = BAD;
453                break;
454            }
455
456            /* build code tables -- note: do not change the lenbits or distbits
457               values here (9 and 6) without reading the comments in inftrees.h
458               concerning the ENOUGH constants, which depend on those values */
442459            state->next = state->codes;
443460            state->lencode = (code const FAR *)(state->next);
444461            state->lenbits = 9;
r15677r15678
474491
475492            /* get a literal, length, or end-of-block code */
476493            for (;;) {
477                this = state->lencode[BITS(state->lenbits)];
478                if ((unsigned)(this.bits) <= bits) break;
494                here = state->lencode[BITS(state->lenbits)];
495                if ((unsigned)(here.bits) <= bits) break;
479496                PULLBYTE();
480497            }
481            if (this.op && (this.op & 0xf0) == 0) {
482                last = this;
498            if (here.op && (here.op & 0xf0) == 0) {
499                last = here;
483500                for (;;) {
484                    this = state->lencode[last.val +
501                    here = state->lencode[last.val +
485502                            (BITS(last.bits + last.op) >> last.bits)];
486                    if ((unsigned)(last.bits + this.bits) <= bits) break;
503                    if ((unsigned)(last.bits + here.bits) <= bits) break;
487504                    PULLBYTE();
488505                }
489506                DROPBITS(last.bits);
490507            }
491            DROPBITS(this.bits);
492            state->length = (unsigned)this.val;
508            DROPBITS(here.bits);
509            state->length = (unsigned)here.val;
493510
494511            /* process literal */
495            if (this.op == 0) {
496                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
512            if (here.op == 0) {
513                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
497514                        "inflate:         literal '%c'\n" :
498                        "inflate:         literal 0x%02x\n", this.val));
515                        "inflate:         literal 0x%02x\n", here.val));
499516                ROOM();
500517                *put++ = (unsigned char)(state->length);
501518                left--;
r15677r15678
504521            }
505522
506523            /* process end of block */
507            if (this.op & 32) {
524            if (here.op & 32) {
508525                Tracevv((stderr, "inflate:         end of block\n"));
509526                state->mode = TYPE;
510527                break;
511528            }
512529
513530            /* invalid code */
514            if (this.op & 64) {
531            if (here.op & 64) {
515532                strm->msg = (char *)"invalid literal/length code";
516533                state->mode = BAD;
517534                break;
518535            }
519536
520537            /* length code -- get extra bits, if any */
521            state->extra = (unsigned)(this.op) & 15;
538            state->extra = (unsigned)(here.op) & 15;
522539            if (state->extra != 0) {
523540                NEEDBITS(state->extra);
524541                state->length += BITS(state->extra);
r15677r15678
528545
529546            /* get distance code */
530547            for (;;) {
531                this = state->distcode[BITS(state->distbits)];
532                if ((unsigned)(this.bits) <= bits) break;
548                here = state->distcode[BITS(state->distbits)];
549                if ((unsigned)(here.bits) <= bits) break;
533550                PULLBYTE();
534551            }
535            if ((this.op & 0xf0) == 0) {
536                last = this;
552            if ((here.op & 0xf0) == 0) {
553                last = here;
537554                for (;;) {
538                    this = state->distcode[last.val +
555                    here = state->distcode[last.val +
539556                            (BITS(last.bits + last.op) >> last.bits)];
540                    if ((unsigned)(last.bits + this.bits) <= bits) break;
557                    if ((unsigned)(last.bits + here.bits) <= bits) break;
541558                    PULLBYTE();
542559                }
543560                DROPBITS(last.bits);
544561            }
545            DROPBITS(this.bits);
546            if (this.op & 64) {
562            DROPBITS(here.bits);
563            if (here.op & 64) {
547564                strm->msg = (char *)"invalid distance code";
548565                state->mode = BAD;
549566                break;
550567            }
551            state->offset = (unsigned)this.val;
568            state->offset = (unsigned)here.val;
552569
553570            /* get distance extra bits, if any */
554            state->extra = (unsigned)(this.op) & 15;
571            state->extra = (unsigned)(here.op) & 15;
555572            if (state->extra != 0) {
556573                NEEDBITS(state->extra);
557574                state->offset += BITS(state->extra);

Previous 15994 Revisions Next


© 1998-2018 The MESS Team