1 /* 2 * Copyright 2007 Sun Microsystems, Inc. All rights reserved. 3 * Use is subject to license terms. 4 */ 5 6 /* 7 * Updated from zlib-1.0.4 to zlib-1.1.3 by James Carlson. 8 * 9 * This file is derived from various .h and .c files from the zlib-1.0.4 10 * distribution by Jean-loup Gailly and Mark Adler, with some additions 11 * by Paul Mackerras to aid in implementing Deflate compression and 12 * decompression for PPP packets. See zlib.h for conditions of 13 * distribution and use. 14 * 15 * Changes that have been made include: 16 * - added Z_PACKET_FLUSH (see zlib.h for details) 17 * - added inflateIncomp and deflateOutputPending 18 * - allow strm->next_out to be NULL, meaning discard the output 19 * 20 * $Id: zlib.c,v 1.11 1998/09/13 23:37:12 paulus Exp $ 21 */ 22 23 /* 24 * ==FILEVERSION 971210== 25 * 26 * This marker is used by the Linux installation script to determine 27 * whether an up-to-date version of this file is already installed. 28 */ 29 30 #define NO_DUMMY_DECL 31 #define NO_ZCFUNCS 32 #define MY_ZCALLOC 33 34 #if defined(__FreeBSD__) && (defined(KERNEL) || defined(_KERNEL)) 35 #define inflate inflate_ppp /* FreeBSD already has an inflate :-( */ 36 #endif 37 38 39 /* +++ zutil.h */ 40 /* 41 * 42 * zutil.h -- internal interface and configuration of the compression library 43 * Copyright (C) 1995-1998 Jean-loup Gailly. 44 * For conditions of distribution and use, see copyright notice in zlib.h 45 */ 46 47 /* 48 * WARNING: this file should *not* be used by applications. It is part 49 * of the implementation of the compression library and is subject to 50 * change. Applications should only use zlib.h. 51 */ 52 53 /* From: zutil.h,v 1.16 1996/07/24 13:41:13 me Exp $ */ 54 55 #ifndef _Z_UTIL_H 56 #define _Z_UTIL_H 57 58 #include "zlib.h" 59 60 #if defined(KERNEL) || defined(_KERNEL) 61 /* Assume this is a *BSD or SVR4 kernel */ 62 #include <sys/types.h> 63 #include <sys/time.h> 64 #include <sys/systm.h> 65 #ifdef SOL2 66 #include <sys/cmn_err.h> 67 #endif 68 #define HAVE_MEMCPY 69 #define memcmp bcmp 70 71 #else 72 #if defined(__KERNEL__) 73 /* Assume this is a Linux kernel */ 74 #include <linux/string.h> 75 #define HAVE_MEMCPY 76 77 #else /* not kernel */ 78 79 #include <stddef.h> 80 #ifdef NO_ERRNO_H 81 extern int errno; 82 #else 83 #include <errno.h> 84 #endif 85 #ifdef STDC 86 #include <string.h> 87 #include <stdlib.h> 88 #endif 89 #endif /* __KERNEL__ */ 90 #endif /* _KERNEL || KERNEL */ 91 92 #ifndef local 93 #define local static 94 #endif 95 /* compile with -Dlocal if your debugger can't find static symbols */ 96 97 typedef unsigned char uch; 98 typedef uch FAR uchf; 99 typedef unsigned short ush; 100 typedef ush FAR ushf; 101 typedef unsigned long ulg; 102 103 static const char *z_errmsg[10]; /* indexed by 2-zlib_error */ 104 /* (size given to avoid silly warnings with Visual C++) */ 105 106 #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] 107 108 #define ERR_RETURN(strm, err) \ 109 return (strm->msg = ERR_MSG(err), (err)) 110 /* To be used only when the state is known to be valid */ 111 112 /* common constants */ 113 114 #ifndef DEF_WBITS 115 #define DEF_WBITS MAX_WBITS 116 #endif 117 /* default windowBits for decompression. MAX_WBITS is for compression only */ 118 119 #if MAX_MEM_LEVEL >= 8 120 #define DEF_MEM_LEVEL 8 121 #else 122 #define DEF_MEM_LEVEL MAX_MEM_LEVEL 123 #endif 124 /* default memLevel */ 125 126 #define STORED_BLOCK 0 127 #define STATIC_TREES 1 128 #define DYN_TREES 2 129 /* The three kinds of block type */ 130 131 #define MIN_MATCH 3 132 #define MAX_MATCH 258 133 /* The minimum and maximum match lengths */ 134 135 #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ 136 137 /* target dependencies */ 138 139 #ifdef MSDOS 140 #define OS_CODE 0x00 141 #ifdef __TURBOC__ 142 #include <alloc.h> 143 #else /* MSC or DJGPP */ 144 #include <malloc.h> 145 #endif 146 #endif 147 148 #ifdef OS2 149 #define OS_CODE 0x06 150 #endif 151 152 #ifdef WIN32 /* Window 95 & Windows NT */ 153 #define OS_CODE 0x0b 154 #endif 155 156 #if defined(VAXC) || defined(VMS) 157 #define OS_CODE 0x02 158 #define F_OPEN(name, mode) \ 159 fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") 160 #endif 161 162 #ifdef AMIGA 163 #define OS_CODE 0x01 164 #endif 165 166 #if defined(ATARI) || defined(atarist) 167 #define OS_CODE 0x05 168 #endif 169 170 #ifdef MACOS 171 #define OS_CODE 0x07 172 #endif 173 174 #ifdef __50SERIES /* Prime/PRIMOS */ 175 #define OS_CODE 0x0F 176 #endif 177 178 #ifdef TOPS20 179 #define OS_CODE 0x0a 180 #endif 181 182 #if defined(_BEOS_) || defined(RISCOS) 183 #define fdopen(fd, mode) NULL /* No fdopen() */ 184 #endif 185 186 /* Common defaults */ 187 188 #ifndef OS_CODE 189 #define OS_CODE 0x03 /* assume Unix */ 190 #endif 191 192 #ifndef F_OPEN 193 #define F_OPEN(name, mode) fopen((name), (mode)) 194 #endif 195 196 /* functions */ 197 198 #ifdef HAVE_STRERROR 199 extern char *strerror OF((int)); 200 #define zstrerror(errnum) strerror(errnum) 201 #else 202 #define zstrerror(errnum) "" 203 #endif 204 205 #if defined(pyr) 206 #define NO_MEMCPY 207 #endif 208 #if (defined(M_I86SM) || defined(M_I86MM)) && !defined(_MSC_VER) 209 /* 210 * Use our own functions for small and medium model with MSC <= 5.0. 211 * You may have to use the same strategy for Borland C (untested). 212 */ 213 #define NO_MEMCPY 214 #endif 215 #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) 216 #define HAVE_MEMCPY 217 #endif 218 #ifdef HAVE_MEMCPY 219 #ifdef SMALL_MEDIUM /* MSDOS small or medium model */ 220 #define zmemcpy _fmemcpy 221 #define zmemcmp _fmemcmp 222 #define zmemzero(dest, len) _fmemset(dest, 0, len) 223 #else 224 #define zmemcpy (void) memcpy 225 #define zmemcmp memcmp 226 #define zmemzero(dest, len) (void) memset(dest, 0, len) 227 #endif 228 #else 229 extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); 230 extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); 231 extern void zmemzero OF((Bytef* dest, uInt len)); 232 #endif 233 234 /* Diagnostic functions */ 235 #ifdef DEBUG_ZLIB 236 #include <stdio.h> 237 #ifndef verbose 238 #define verbose 0 239 #endif 240 extern void z_error OF((char *m)); 241 #define Assert(cond, msg) { if (!(cond)) z_error(msg); } 242 #define Trace(x) {if (z_verbose >= 0) fprintf x; } 243 #define Tracev(x) {if (z_verbose > 0) fprintf x; } 244 #define Tracevv(x) {if (z_verbose > 1) fprintf x; } 245 #define Tracec(c, x) {if (z_verbose > 0 && (c)) fprintf x; } 246 #define Tracecv(c, x) {if (z_verbose > 1 && (c)) fprintf x; } 247 #else 248 #if defined(SOL2) && defined(DEBUG) 249 #define Assert(cond, msg) ((cond) ? ((void)0) : panic(msg)) 250 #else 251 #define Assert(cond, msg) ((void)0) 252 #endif 253 #define Trace(x) ((void)0) 254 #define Tracev(x) ((void)0) 255 #define Tracevv(x) ((void)0) 256 #define Tracec(c, x) ((void)0) 257 #define Tracecv(c, x) ((void)0) 258 #endif 259 260 261 typedef uLong (*check_func) OF((uLong check, const Bytef *buf, uInt len)); 262 263 /* voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); */ 264 /* void zcfree OF((voidpf opaque, voidpf ptr)); */ 265 266 #define ZALLOC(strm, items, size) \ 267 (*((strm)->zalloc))((strm)->opaque, (items), (size)) 268 #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) 269 #define TRY_FREE(s, p) {if (p) ZFREE(s, p); } 270 271 #endif /* _Z_UTIL_H */ 272 /* --- zutil.h */ 273 274 /* +++ deflate.h */ 275 /* 276 * deflate.h -- internal compression state 277 * Copyright (C) 1995-1998 Jean-loup Gailly 278 * For conditions of distribution and use, see copyright notice in zlib.h 279 */ 280 281 /* 282 * WARNING: this file should *not* be used by applications. It is part 283 * of the implementation of the compression library and is subject to 284 * change. Applications should only use zlib.h. 285 */ 286 287 /* From: deflate.h,v 1.10 1996/07/02 12:41:00 me Exp $ */ 288 289 #ifndef _DEFLATE_H 290 #define _DEFLATE_H 291 292 /* #include "zutil.h" */ 293 294 /* 295 * =========================================================================== 296 * Internal compression state. 297 */ 298 299 #define LENGTH_CODES 29 300 /* number of length codes, not counting the special END_BLOCK code */ 301 302 #define LITERALS 256 303 /* number of literal bytes 0..255 */ 304 305 #define L_CODES (LITERALS+1+LENGTH_CODES) 306 /* number of Literal or Length codes, including the END_BLOCK code */ 307 308 #define D_CODES 30 309 /* number of distance codes */ 310 311 #define BL_CODES 19 312 /* number of codes used to transfer the bit lengths */ 313 314 #define HEAP_SIZE (2*L_CODES+1) 315 /* maximum heap size */ 316 317 #define MAX_BITS 15 318 /* All codes must not exceed MAX_BITS bits */ 319 320 #define INIT_STATE 42 321 #define BUSY_STATE 113 322 #define FINISH_STATE 666 323 /* Stream status */ 324 325 326 /* Data structure describing a single value and its code string. */ 327 typedef struct ct_data_s { 328 union { 329 ush freq; /* frequency count */ 330 ush code; /* bit string */ 331 } fc; 332 union { 333 ush dad; /* father node in Huffman tree */ 334 ush len; /* length of bit string */ 335 } dl; 336 } FAR ct_data; 337 338 #define Freq fc.freq 339 #define Code fc.code 340 #define Dad dl.dad 341 #define Len dl.len 342 343 typedef struct static_tree_desc_s static_tree_desc; 344 345 typedef struct tree_desc_s { 346 ct_data *dyn_tree; /* the dynamic tree */ 347 int max_code; /* largest code with non zero frequency */ 348 static_tree_desc *stat_desc; /* the corresponding static tree */ 349 } FAR tree_desc; 350 351 typedef ush Pos; 352 typedef Pos FAR Posf; 353 typedef unsigned IPos; 354 355 /* 356 * A Pos is an index in the character window. We use short instead of 357 * int to save space in the various tables. IPos is used only for 358 * parameter passing. 359 */ 360 361 typedef struct deflate_state { 362 z_streamp strm; /* pointer back to this zlib stream */ 363 int status; /* as the name implies */ 364 Bytef *pending_buf; /* output still pending */ 365 ulg pending_buf_size; /* size of pending_buf */ 366 Bytef *pending_out; /* next pending byte to output to the stream */ 367 int pending; /* nb of bytes in the pending buffer */ 368 int noheader; /* suppress zlib header and adler32 */ 369 Byte data_type; /* UNKNOWN, BINARY or ASCII */ 370 Byte method; /* STORED (for zip only) or DEFLATED */ 371 /* value of flush param for previous deflate call */ 372 int last_flush; 373 374 /* used by deflate.c: */ 375 376 uInt w_size; /* LZ77 window size (32K by default) */ 377 uInt w_bits; /* log2(w_size) (8..16) */ 378 uInt w_mask; /* w_size - 1 */ 379 380 Bytef *window; 381 /* 382 * Sliding window. Input bytes are read into the second half 383 * of the window, and move to the first half later to keep a 384 * dictionary of at least wSize bytes. With this organization, 385 * matches are limited to a distance of wSize-MAX_MATCH bytes, 386 * but this ensures that IO is always performed with a length 387 * multiple of the block size. Also, it limits the window size 388 * to 64K, which is quite useful on MSDOS. To do: use the 389 * user input buffer as sliding window. 390 */ 391 392 ulg window_size; 393 /* 394 * Actual size of window: 2*wSize, except when the user input 395 * buffer is directly used as sliding window. 396 */ 397 398 Posf *prev; 399 /* 400 * Link to older string with same hash index. To limit the 401 * size of this array to 64K, this link is maintained only for 402 * the last 32K strings. An index in this array is thus a 403 * window index modulo 32K. 404 */ 405 406 Posf *head; /* Heads of the hash chains or NIL. */ 407 408 uInt ins_h; /* hash index of string to be inserted */ 409 uInt hash_size; /* number of elements in hash table */ 410 uInt hash_bits; /* log2(hash_size) */ 411 uInt hash_mask; /* hash_size-1 */ 412 413 uInt hash_shift; 414 /* 415 * Number of bits by which ins_h must be shifted at each input 416 * step. It must be such that after MIN_MATCH steps, the 417 * oldest byte no longer takes part in the hash key, that is: 418 * hash_shift * MIN_MATCH >= hash_bits 419 */ 420 421 long block_start; 422 /* 423 * Window position at the beginning of the current output 424 * block. Gets negative when the window is moved backwards. 425 */ 426 427 uInt match_length; /* length of best match */ 428 IPos prev_match; /* previous match */ 429 int match_available; /* set if previous match exists */ 430 uInt strstart; /* start of string to insert */ 431 uInt match_start; /* start of matching string */ 432 uInt lookahead; /* number of valid bytes ahead in window */ 433 434 uInt prev_length; 435 /* 436 * Length of the best match at previous step. Matches not 437 * greater than this are discarded. This is used in the lazy 438 * match evaluation. 439 */ 440 441 uInt max_chain_length; 442 /* 443 * To speed up deflation, hash chains are never searched 444 * beyond *this length. A higher limit improves compression 445 * ratio but *degrades the speed. 446 */ 447 448 uInt max_lazy_match; 449 /* 450 * Attempt to find a better match only when the current match 451 * is strictly smaller than this value. This mechanism is used 452 * only for compression levels >= 4. 453 */ 454 #define max_insert_length max_lazy_match 455 /* 456 * Insert new strings in the hash table only if the match 457 * length is not greater than this length. This saves time but 458 * degrades compression. max_insert_length is used only for 459 * compression levels <= 3. 460 */ 461 462 int level; /* compression level (1..9) */ 463 int strategy; /* favor or force Huffman coding */ 464 465 uInt good_match; 466 /* Use a faster search when the previous match is longer than this */ 467 468 int nice_match; /* Stop searching when current match exceeds this */ 469 470 /* used by trees.c: */ 471 /* Didn't use ct_data typedef below to supress compiler warning */ 472 struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ 473 struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ 474 /* Huffman tree for bit lengths */ 475 struct ct_data_s bl_tree[2*BL_CODES+1]; 476 477 struct tree_desc_s l_desc; /* desc. for literal tree */ 478 struct tree_desc_s d_desc; /* desc. for distance tree */ 479 struct tree_desc_s bl_desc; /* desc. for bit length tree */ 480 481 ush bl_count[MAX_BITS+1]; 482 /* number of codes at each bit length for an optimal tree */ 483 484 int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ 485 int heap_len; /* number of elements in the heap */ 486 int heap_max; /* element of largest frequency */ 487 /* 488 * The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] 489 * is not used. The same heap array is used to build all 490 * trees. 491 */ 492 493 uch depth[2*L_CODES+1]; 494 /* 495 * Depth of each subtree used as tie breaker for trees of 496 * equal frequency 497 */ 498 499 uchf *l_buf; /* buffer for literals or lengths */ 500 501 uInt lit_bufsize; 502 /* 503 * Size of match buffer for literals/lengths. There are 4 504 * reasons for limiting lit_bufsize to 64K: 505 * 506 * - frequencies can be kept in 16 bit counters 507 * 508 * - if compression is not successful for the first block, 509 * all input data is still in the window so we can still 510 * emit a stored block even when input comes from standard 511 * input. (This can also be done for all blocks if 512 * lit_bufsize is not greater than 32K.) 513 * 514 * - if compression is not successful for a file smaller 515 * than 64K, we can even emit a stored file instead of a 516 * stored block (saving 5 bytes). This is applicable only 517 * for zip (not gzip or zlib). 518 * 519 * - creating new Huffman trees less frequently may not 520 * provide fast adaptation to changes in the input data 521 * statistics. (Take for example a binary file with poorly 522 * compressible code followed by a highly compressible 523 * string table.) Smaller buffer sizes give fast adaptation 524 * but have of course the overhead of transmitting trees 525 * more frequently. 526 * 527 * - I can't count above 4 528 */ 529 530 uInt last_lit; /* running index in l_buf */ 531 532 ushf *d_buf; 533 /* 534 * Buffer for distances. To simplify the code, d_buf and l_buf 535 * have the same number of elements. To use different lengths, 536 * an extra flag array would be necessary. 537 */ 538 539 ulg opt_len; /* bit length of current block with optimal trees */ 540 ulg static_len; /* bit length of current block with static trees */ 541 uInt matches; /* number of string matches in current block */ 542 int last_eob_len; /* bit length of EOB code for last block */ 543 544 ulg compressed_len; /* total bit length of compressed file PPP */ 545 #ifdef DEBUG_ZLIB 546 ulg bits_sent; /* bit length of the compressed data */ 547 #endif 548 549 ush bi_buf; 550 /* 551 * Output buffer. bits are inserted starting at the bottom 552 * (least significant bits). 553 */ 554 int bi_valid; 555 /* 556 * Number of valid bits in bi_buf. All bits above the last 557 * valid bit are always zero. 558 */ 559 560 } FAR deflate_state; 561 562 /* 563 * Output a byte on the stream. IN assertion: there is enough room in 564 * pending_buf. 565 */ 566 #define put_byte(s, c) {s->pending_buf[s->pending++] = (c); } 567 568 569 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) 570 /* 571 * Minimum amount of lookahead, except at the end of the input file. 572 * See deflate.c for comments about the MIN_MATCH+1. 573 */ 574 575 #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) 576 /* 577 * In order to simplify the code, particularly on 16 bit machines, 578 * match distances are limited to MAX_DIST instead of WSIZE. 579 */ 580 581 /* in trees.c */ 582 void _tr_init OF((deflate_state *s)); 583 int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); 584 void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, 585 int eof)); 586 void _tr_align OF((deflate_state *s)); 587 void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, 588 int eof)); 589 void _tr_stored_type_only OF((deflate_state *)); /* PPP */ 590 591 #define d_code(dist) \ 592 ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) 593 /* 594 * Mapping from a distance to a distance code. dist is the distance - 1 and 595 * must not have side effects. _dist_code[256] and _dist_code[257] are never 596 * used. 597 */ 598 599 #ifndef DEBUG_ZLIB 600 /* Inline versions of _tr_tally for speed: */ 601 602 local uch _length_code[]; 603 local uch _dist_code[]; 604 605 #define _tr_tally_lit(s, c, flush) \ 606 { uch cc = (c); \ 607 s->d_buf[s->last_lit] = 0; \ 608 s->l_buf[s->last_lit++] = cc; \ 609 s->dyn_ltree[cc].Freq++; \ 610 flush = (s->last_lit == s->lit_bufsize-1); \ 611 } 612 #define _tr_tally_dist(s, distance, length, flush) \ 613 { uch len = (length); \ 614 ush dist = (distance); \ 615 s->d_buf[s->last_lit] = dist; \ 616 s->l_buf[s->last_lit++] = len; \ 617 dist--; \ 618 s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ 619 s->dyn_dtree[d_code(dist)].Freq++; \ 620 flush = (s->last_lit == s->lit_bufsize-1); \ 621 } 622 #else 623 #define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) 624 #define _tr_tally_dist(s, distance, length, flush) \ 625 flush = _tr_tally(s, distance, length) 626 #endif 627 628 #endif 629 /* --- deflate.h */ 630 631 /* +++ deflate.c */ 632 /* 633 * deflate.c -- compress data using the deflation algorithm 634 * Copyright (C) 1995-1998 Jean-loup Gailly. 635 * For conditions of distribution and use, see copyright notice in zlib.h 636 */ 637 638 /* 639 * ALGORITHM 640 * 641 * The "deflation" process depends on being able to identify portions 642 * of the input text which are identical to earlier input (within a 643 * sliding window trailing behind the input currently being processed). 644 * 645 * The most straightforward technique turns out to be the fastest for 646 * most input files: try all possible matches and select the longest. 647 * The key feature of this algorithm is that insertions into the string 648 * dictionary are very simple and thus fast, and deletions are avoided 649 * completely. Insertions are performed at each input character, whereas 650 * string matches are performed only when the previous match ends. So it 651 * is preferable to spend more time in matches to allow very fast string 652 * insertions and avoid deletions. The matching algorithm for small 653 * strings is inspired from that of Rabin & Karp. A brute force approach 654 * is used to find longer strings when a small match has been found. 655 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze 656 * (by Leonid Broukhis). 657 * A previous version of this file used a more sophisticated algorithm 658 * (by Fiala and Greene) which is guaranteed to run in linear amortized 659 * time, but has a larger average cost, uses more memory and is patented. 660 * However the F&G algorithm may be faster for some highly redundant 661 * files if the parameter max_chain_length (described below) is too large. 662 * 663 * ACKNOWLEDGEMENTS 664 * 665 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and 666 * I found it in 'freeze' written by Leonid Broukhis. 667 * Thanks to many people for bug reports and testing. 668 * 669 * REFERENCES 670 * 671 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". 672 * Available in ftp://ds.internic.net/rfc/rfc1951.txt 673 * 674 * A description of the Rabin and Karp algorithm is given in the book 675 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. 676 * 677 * Fiala,E.R., and Greene,D.H. 678 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 679 * 680 */ 681 682 /* From: deflate.c,v 1.15 1996/07/24 13:40:58 me Exp $ */ 683 684 /* #include "deflate.h" */ 685 686 const char deflate_copyright[] = 687 " deflate 1.1.3 Copyright 1995-1998 Jean-loup Gailly "; 688 /* 689 * If you use the zlib library in a product, an acknowledgment is 690 * welcome in the documentation of your product. If for some reason 691 * you cannot include such an acknowledgment, I would appreciate that 692 * you keep this copyright string in the executable of your product. 693 */ 694 695 /* 696 * =========================================================================== 697 * Function prototypes. 698 */ 699 typedef enum { 700 /* block not completed, need more input or more output */ 701 need_more, 702 block_done, /* block flush performed */ 703 /* finish started, need only more output at next deflate */ 704 finish_started, 705 finish_done /* finish done, accept no more input or output */ 706 } block_state; 707 708 typedef block_state (*compress_func) OF((deflate_state *s, int flush)); 709 /* Compression function. Returns the block state after the call. */ 710 711 local void fill_window OF((deflate_state *s)); 712 local block_state deflate_stored OF((deflate_state *s, int flush)); 713 local block_state deflate_fast OF((deflate_state *s, int flush)); 714 local block_state deflate_slow OF((deflate_state *s, int flush)); 715 local void lm_init OF((deflate_state *s)); 716 local void putShortMSB OF((deflate_state *s, uInt b)); 717 local void flush_pending OF((z_streamp strm)); 718 local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); 719 #ifdef ASMV 720 void match_init OF((void)); /* asm code initialization */ 721 uInt longest_match OF((deflate_state *s, IPos cur_match)); 722 #else 723 local uInt longest_match OF((deflate_state *s, IPos cur_match)); 724 #endif 725 726 #ifdef DEBUG_ZLIB 727 local void check_match OF((deflate_state *s, IPos start, IPos match, 728 int length)); 729 #endif 730 731 /* 732 * =========================================================================== 733 * Local data 734 */ 735 736 #define NIL 0 737 /* Tail of hash chains */ 738 739 #ifndef TOO_FAR 740 #define TOO_FAR 4096 741 #endif 742 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ 743 744 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) 745 /* 746 * Minimum amount of lookahead, except at the end of the input file. 747 * See deflate.c for comments about the MIN_MATCH+1. 748 */ 749 750 /* 751 * Values for max_lazy_match, good_match and max_chain_length, 752 * depending on the desired pack level (0..9). The values given below 753 * have been tuned to exclude worst case performance for pathological 754 * files. Better values may be found for specific files. 755 */ 756 typedef struct config_s { 757 ush good_length; /* reduce lazy search above this match length */ 758 ush max_lazy; /* do not perform lazy search above this match length */ 759 ush nice_length; /* quit search above this match length */ 760 ush max_chain; 761 compress_func func; 762 } config; 763 764 local const config configuration_table[10] = { 765 /* good lazy nice chain */ 766 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ 767 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */ 768 /* 2 */ {4, 5, 16, 8, deflate_fast}, 769 /* 3 */ {4, 6, 32, 32, deflate_fast}, 770 771 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ 772 /* 5 */ {8, 16, 32, 32, deflate_slow}, 773 /* 6 */ {8, 16, 128, 128, deflate_slow}, 774 /* 7 */ {8, 32, 128, 256, deflate_slow}, 775 /* 8 */ {32, 128, 258, 1024, deflate_slow}, 776 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */ 777 778 /* 779 * Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 780 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different 781 * meaning. 782 */ 783 784 #define EQUAL 0 785 /* result of memcmp for equal strings */ 786 787 #ifndef NO_DUMMY_DECL 788 struct static_tree_desc_s {int dummy; }; /* for buggy compilers */ 789 #endif 790 791 /* 792 * =========================================================================== 793 * Update a hash value with the given input byte 794 * IN assertion: all calls to to UPDATE_HASH are made with consecutive 795 * input characters, so that a running hash key can be computed from the 796 * previous key instead of complete recalculation each time. 797 */ 798 #define UPDATE_HASH(s, h, c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) 799 800 801 /* 802 * =========================================================================== 803 * Insert string str in the dictionary and set match_head to the previous head 804 * of the hash chain (the most recent string with same hash key). Return 805 * the previous length of the hash chain. 806 * If this file is compiled with -DFASTEST, the compression level is forced 807 * to 1, and no hash chains are maintained. 808 * IN assertion: all calls to to INSERT_STRING are made with consecutive 809 * input characters and the first MIN_MATCH bytes of str are valid 810 * (except for the last MIN_MATCH-1 bytes of the input file). 811 */ 812 #ifdef FASTEST 813 #define INSERT_STRING(s, str, match_head) \ 814 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ 815 match_head = s->head[s->ins_h], \ 816 s->head[s->ins_h] = (Pos)(str)) 817 #else 818 #define INSERT_STRING(s, str, match_head) \ 819 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ 820 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \ 821 s->head[s->ins_h] = (Pos)(str)) 822 #endif 823 824 /* 825 * =========================================================================== 826 * Initialize the hash table (avoiding 64K overflow for 16 bit systems). 827 * prev[] will be initialized on the fly. 828 */ 829 #define CLEAR_HASH(s) \ 830 s->head[s->hash_size-1] = NIL; \ 831 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof (*s->head)); 832 833 /* ========================================================================= */ 834 int 835 deflateInit_(strm, level, version, stream_size) 836 z_streamp strm; 837 int level; 838 const char *version; 839 int stream_size; 840 { 841 (void) deflate_copyright; 842 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, 843 Z_DEFAULT_STRATEGY, version, stream_size); 844 /* To do: ignore strm->next_in if we use it as window */ 845 } 846 847 /* ========================================================================= */ 848 int deflateInit2_(strm, level, method, windowBits, memLevel, strategy, 849 version, stream_size) 850 z_streamp strm; 851 int level; 852 int method; 853 int windowBits; 854 int memLevel; 855 int strategy; 856 const char *version; 857 int stream_size; 858 { 859 deflate_state *s; 860 int noheader = 0; 861 static const char *my_version = ZLIB_VERSION; 862 863 ushf *overlay; 864 /* 865 * We overlay pending_buf and d_buf+l_buf. This works since 866 * the average output size for (length, distance) codes is <= 867 * 24 bits. 868 */ 869 870 if (version == Z_NULL || version[0] != my_version[0] || 871 stream_size != sizeof (z_stream)) { 872 return (Z_VERSION_ERROR); 873 } 874 if (strm == Z_NULL) 875 return (Z_STREAM_ERROR); 876 877 strm->msg = Z_NULL; 878 #ifndef NO_ZCFUNCS 879 if (strm->zalloc == Z_NULL) { 880 strm->zalloc = zcalloc; 881 strm->opaque = (voidpf)0; 882 } 883 if (strm->zfree == Z_NULL) strm->zfree = zcfree; 884 #endif 885 886 if (level == Z_DEFAULT_COMPRESSION) level = 6; 887 #ifdef FASTEST 888 level = 1; 889 #endif 890 891 if (windowBits < 0) { /* undocumented feature: suppress zlib header */ 892 noheader = 1; 893 windowBits = -windowBits; 894 } 895 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || 896 windowBits <= 8 || windowBits > 15 || level < 0 || level > 9 || 897 strategy < 0 || strategy > Z_HUFFMAN_ONLY) { 898 return (Z_STREAM_ERROR); 899 } 900 s = (deflate_state *) ZALLOC(strm, 1, sizeof (deflate_state)); 901 if (s == Z_NULL) 902 return (Z_MEM_ERROR); 903 strm->state = (struct internal_state FAR *)s; 904 s->strm = strm; 905 906 s->noheader = noheader; 907 s->w_bits = windowBits; 908 s->w_size = 1 << s->w_bits; 909 s->w_mask = s->w_size - 1; 910 911 s->hash_bits = memLevel + 7; 912 s->hash_size = 1 << s->hash_bits; 913 s->hash_mask = s->hash_size - 1; 914 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); 915 916 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof (Byte)); 917 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof (Pos)); 918 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof (Pos)); 919 920 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ 921 922 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof (ush)+2); 923 s->pending_buf = (uchf *) overlay; 924 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof (ush)+2L); 925 926 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || 927 s->pending_buf == Z_NULL) { 928 strm->msg = ERR_MSG(Z_MEM_ERROR); 929 s->status = INIT_STATE; 930 (void) deflateEnd(strm); 931 return (Z_MEM_ERROR); 932 } 933 s->d_buf = overlay + s->lit_bufsize/sizeof (ush); 934 s->l_buf = s->pending_buf + (1+sizeof (ush))*s->lit_bufsize; 935 936 s->level = level; 937 s->strategy = strategy; 938 s->method = (Byte)method; 939 940 return (deflateReset(strm)); 941 } 942 943 /* ========================================================================= */ 944 int 945 deflateSetDictionary(strm, dictionary, dictLength) 946 z_streamp strm; 947 const Bytef *dictionary; 948 uInt dictLength; 949 { 950 deflate_state *s; 951 uInt length = dictLength; 952 uInt n; 953 IPos hash_head = 0; 954 955 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL) 956 return (Z_STREAM_ERROR); 957 958 s = (deflate_state *) strm->state; 959 if (s->status != INIT_STATE) 960 return (Z_STREAM_ERROR); 961 962 strm->adler = adler32(strm->adler, dictionary, dictLength); 963 964 if (length < MIN_MATCH) 965 return (Z_OK); 966 if (length > MAX_DIST(s)) { 967 length = MAX_DIST(s); 968 #ifndef USE_DICT_HEAD 969 /* use the tail of the dictionary */ 970 dictionary += dictLength - length; 971 #endif 972 } 973 Assert(length <= s->window_size, "dict copy"); 974 zmemcpy(s->window, dictionary, length); 975 s->strstart = length; 976 s->block_start = (long)length; 977 978 /* 979 * Insert all strings in the hash table (except for the last 980 * two bytes). s->lookahead stays null, so s->ins_h will be 981 * recomputed at the next call of fill_window. 982 */ 983 s->ins_h = s->window[0]; 984 UPDATE_HASH(s, s->ins_h, s->window[1]); 985 for (n = 0; n <= length - MIN_MATCH; n++) { 986 INSERT_STRING(s, n, hash_head); 987 } 988 if (hash_head) hash_head = 0; /* to make compiler happy */ 989 return (Z_OK); 990 } 991 992 /* ========================================================================= */ 993 int 994 deflateReset(strm) 995 z_streamp strm; 996 { 997 deflate_state *s; 998 999 if (strm == Z_NULL || strm->state == Z_NULL || 1000 strm->zalloc == Z_NULL || strm->zfree == Z_NULL) 1001 return (Z_STREAM_ERROR); 1002 1003 strm->total_in = strm->total_out = 0; 1004 /* use zfree if we ever allocate msg dynamically */ 1005 strm->msg = Z_NULL; 1006 strm->data_type = Z_UNKNOWN; 1007 1008 s = (deflate_state *)strm->state; 1009 s->pending = 0; 1010 s->pending_out = s->pending_buf; 1011 1012 if (s->noheader < 0) { 1013 /* was set to -1 by deflate(..., Z_FINISH); */ 1014 s->noheader = 0; 1015 } 1016 s->status = s->noheader ? BUSY_STATE : INIT_STATE; 1017 strm->adler = 1; 1018 s->last_flush = Z_NO_FLUSH; 1019 1020 _tr_init(s); 1021 lm_init(s); 1022 1023 return (Z_OK); 1024 } 1025 1026 /* ========================================================================= */ 1027 int 1028 deflateParams(strm, level, strategy) 1029 z_streamp strm; 1030 int level; 1031 int strategy; 1032 { 1033 deflate_state *s; 1034 compress_func func; 1035 int err = Z_OK; 1036 1037 if (strm == Z_NULL || strm->state == Z_NULL) 1038 return (Z_STREAM_ERROR); 1039 s = (deflate_state *) strm->state; 1040 1041 if (level == Z_DEFAULT_COMPRESSION) { 1042 level = 6; 1043 } 1044 if (level < 0 || level > 9 || strategy < 0 || 1045 strategy > Z_HUFFMAN_ONLY) { 1046 return (Z_STREAM_ERROR); 1047 } 1048 func = configuration_table[s->level].func; 1049 1050 if (func != configuration_table[level].func && strm->total_in != 0) { 1051 /* Flush the last buffer: */ 1052 err = deflate(strm, Z_PARTIAL_FLUSH); 1053 } 1054 if (s->level != level) { 1055 s->level = level; 1056 s->max_lazy_match = configuration_table[level].max_lazy; 1057 s->good_match = configuration_table[level].good_length; 1058 s->nice_match = configuration_table[level].nice_length; 1059 s->max_chain_length = configuration_table[level].max_chain; 1060 } 1061 s->strategy = strategy; 1062 return (err); 1063 } 1064 1065 /* 1066 * ========================================================================= 1067 * Put a short in the pending buffer. The 16-bit value is put in MSB order. 1068 * IN assertion: the stream state is correct and there is enough room in 1069 * pending_buf. 1070 */ 1071 local void 1072 putShortMSB(s, b) 1073 deflate_state *s; 1074 uInt b; 1075 { 1076 put_byte(s, (Byte)(b >> 8)); 1077 put_byte(s, (Byte)(b & 0xff)); 1078 } 1079 1080 /* 1081 * ========================================================================= 1082 * Flush as much pending output as possible. All deflate() output goes 1083 * through this function so some applications may wish to modify it 1084 * to avoid allocating a large strm->next_out buffer and copying into it. 1085 * (See also read_buf()). 1086 */ 1087 local void 1088 flush_pending(strm) 1089 z_streamp strm; 1090 { 1091 deflate_state *s = (deflate_state *) strm->state; 1092 unsigned len = s->pending; 1093 1094 if (len > strm->avail_out) len = strm->avail_out; 1095 if (len == 0) 1096 return; 1097 1098 if (strm->next_out != Z_NULL) { /* PPP */ 1099 zmemcpy(strm->next_out, s->pending_out, len); 1100 strm->next_out += len; 1101 } /* PPP */ 1102 s->pending_out += len; 1103 strm->total_out += len; 1104 strm->avail_out -= len; 1105 s->pending -= len; 1106 if (s->pending == 0) { 1107 s->pending_out = s->pending_buf; 1108 } 1109 } 1110 1111 /* ========================================================================= */ 1112 int 1113 deflate(strm, flush) 1114 z_streamp strm; 1115 int flush; 1116 { 1117 int old_flush; /* value of flush param for previous deflate call */ 1118 deflate_state *s; 1119 1120 if (strm == Z_NULL || strm->state == Z_NULL || 1121 flush > Z_FINISH || flush < 0) { 1122 return (Z_STREAM_ERROR); 1123 } 1124 s = (deflate_state *) strm->state; 1125 1126 if (/* strm->next_out == Z_NULL || --- we allow null --- PPP */ 1127 (strm->next_in == Z_NULL && strm->avail_in != 0) || 1128 (s->status == FINISH_STATE && flush != Z_FINISH)) { 1129 ERR_RETURN(strm, Z_STREAM_ERROR); 1130 } 1131 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); 1132 1133 s->strm = strm; /* just in case */ 1134 old_flush = s->last_flush; 1135 s->last_flush = flush; 1136 1137 /* Write the zlib header */ 1138 if (s->status == INIT_STATE) { 1139 1140 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; 1141 uInt level_flags = (s->level-1) >> 1; 1142 1143 if (level_flags > 3) level_flags = 3; 1144 header |= (level_flags << 6); 1145 if (s->strstart != 0) header |= PRESET_DICT; 1146 header += 31 - (header % 31); 1147 1148 s->status = BUSY_STATE; 1149 putShortMSB(s, header); 1150 1151 /* Save the adler32 of the preset dictionary: */ 1152 if (s->strstart != 0) { 1153 putShortMSB(s, (uInt)(strm->adler >> 16)); 1154 putShortMSB(s, (uInt)(strm->adler & 0xffff)); 1155 } 1156 strm->adler = 1L; 1157 } 1158 1159 /* Flush as much pending output as possible */ 1160 if (s->pending != 0) { 1161 flush_pending(strm); 1162 if (strm->avail_out == 0) { 1163 /* 1164 * Since avail_out is 0, deflate will be 1165 * called again with more output space, but 1166 * possibly with both pending and avail_in 1167 * equal to zero. There won't be anything to 1168 * do, but this is not an error situation so 1169 * make sure we return OK instead of BUF_ERROR 1170 * at next call of deflate: 1171 */ 1172 s->last_flush = -1; 1173 return (Z_OK); 1174 } 1175 1176 /* 1177 * Make sure there is something to do and avoid 1178 * duplicate consecutive flushes. For repeated and 1179 * useless calls with Z_FINISH, we keep returning 1180 * Z_STREAM_END instead of Z_BUFF_ERROR. 1181 */ 1182 } else if (strm->avail_in == 0 && flush <= old_flush && 1183 flush != Z_FINISH) { 1184 ERR_RETURN(strm, Z_BUF_ERROR); 1185 } 1186 1187 /* User must not provide more input after the first FINISH: */ 1188 if (s->status == FINISH_STATE && strm->avail_in != 0) { 1189 ERR_RETURN(strm, Z_BUF_ERROR); 1190 } 1191 1192 /* Start a new block or continue the current one. */ 1193 if (strm->avail_in != 0 || s->lookahead != 0 || 1194 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { 1195 block_state bstate; 1196 1197 bstate = (*(configuration_table[s->level].func))(s, flush); 1198 1199 if (bstate == finish_started || bstate == finish_done) { 1200 s->status = FINISH_STATE; 1201 } 1202 if (bstate == need_more || bstate == finish_started) { 1203 if (strm->avail_out == 0) { 1204 /* avoid BUF_ERROR next call, see above */ 1205 s->last_flush = -1; 1206 } 1207 return (Z_OK); 1208 /* 1209 * If flush != Z_NO_FLUSH && avail_out == 0, 1210 * the next call of deflate should use the 1211 * same flush parameter to make sure that the 1212 * flush is complete. So we don't have to 1213 * output an empty block here, this will be 1214 * done at next call. This also ensures that 1215 * for a very small output buffer, we emit at 1216 * most one empty block. 1217 */ 1218 } 1219 if (bstate == block_done) { 1220 if (flush == Z_PARTIAL_FLUSH) { 1221 _tr_align(s); 1222 } else if (flush == Z_PACKET_FLUSH) { /* PPP */ 1223 /* 1224 * Output just the 3-bit `stored' 1225 * block type value, but not a zero 1226 * length. Added for PPP. 1227 */ 1228 _tr_stored_type_only(s); /* PPP */ 1229 } else { /* FULL_FLUSH or SYNC_FLUSH */ 1230 _tr_stored_block(s, (char *)0, 0L, 0); 1231 /* 1232 * For a full flush, this empty block 1233 * will be recognized as a special 1234 * marker by inflate_sync(). 1235 */ 1236 if (flush == Z_FULL_FLUSH) { 1237 CLEAR_HASH(s); /* forget history */ 1238 } 1239 } 1240 flush_pending(strm); 1241 if (strm->avail_out == 0) { 1242 /* avoid BUF_ERROR at next call, see above */ 1243 s->last_flush = -1; 1244 return (Z_OK); 1245 } 1246 } 1247 } 1248 Assert(strm->avail_out > 0, "bug2"); 1249 1250 if (flush != Z_FINISH) 1251 return (Z_OK); 1252 if (s->noheader) 1253 return (Z_STREAM_END); 1254 1255 /* Write the zlib trailer (adler32) */ 1256 putShortMSB(s, (uInt)(strm->adler >> 16)); 1257 putShortMSB(s, (uInt)(strm->adler & 0xffff)); 1258 flush_pending(strm); 1259 /* 1260 * If avail_out is zero, the application will call deflate 1261 * again to flush the rest. 1262 */ 1263 s->noheader = -1; /* write the trailer only once! */ 1264 return (s->pending != 0 ? Z_OK : Z_STREAM_END); 1265 } 1266 1267 /* ========================================================================= */ 1268 int 1269 deflateEnd(strm) 1270 z_streamp strm; 1271 { 1272 int status; 1273 deflate_state *s; 1274 1275 if (strm == Z_NULL || strm->state == Z_NULL) 1276 return (Z_STREAM_ERROR); 1277 s = (deflate_state *) strm->state; 1278 1279 status = s->status; 1280 if (status != INIT_STATE && status != BUSY_STATE && 1281 status != FINISH_STATE) { 1282 return (Z_STREAM_ERROR); 1283 } 1284 1285 /* Deallocate in reverse order of allocations: */ 1286 TRY_FREE(strm, s->pending_buf); 1287 TRY_FREE(strm, s->head); 1288 TRY_FREE(strm, s->prev); 1289 TRY_FREE(strm, s->window); 1290 1291 ZFREE(strm, s); 1292 strm->state = Z_NULL; 1293 1294 return (status == BUSY_STATE ? Z_DATA_ERROR : Z_OK); 1295 } 1296 1297 /* 1298 * ========================================================================= 1299 * Copy the source state to the destination state. 1300 * To simplify the source, this is not supported for 16-bit MSDOS (which 1301 * doesn't have enough memory anyway to duplicate compression states). 1302 */ 1303 int 1304 deflateCopy(dest, source) 1305 z_streamp dest; 1306 z_streamp source; 1307 { 1308 #ifdef MAXSEG_64K 1309 return (Z_STREAM_ERROR); 1310 #else 1311 deflate_state *ds; 1312 deflate_state *ss; 1313 ushf *overlay; 1314 1315 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) 1316 return (Z_STREAM_ERROR); 1317 ss = (deflate_state *) source->state; 1318 1319 zmemcpy(dest, source, sizeof (*dest)); 1320 1321 ds = (deflate_state *) ZALLOC(dest, 1, sizeof (deflate_state)); 1322 if (ds == Z_NULL) 1323 return (Z_MEM_ERROR); 1324 dest->state = (struct internal_state FAR *) ds; 1325 zmemcpy(ds, ss, sizeof (*ds)); 1326 ds->strm = dest; 1327 1328 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof (Byte)); 1329 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof (Pos)); 1330 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof (Pos)); 1331 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof (ush)+2); 1332 ds->pending_buf = (uchf *) overlay; 1333 1334 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || 1335 ds->pending_buf == Z_NULL) { 1336 ds->status = INIT_STATE; 1337 (void) deflateEnd(dest); 1338 return (Z_MEM_ERROR); 1339 } 1340 /* following zmemcpy doesn't work for 16-bit MSDOS */ 1341 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof (Byte)); 1342 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof (Pos)); 1343 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof (Pos)); 1344 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); 1345 1346 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); 1347 ds->d_buf = overlay + ds->lit_bufsize/sizeof (ush); 1348 ds->l_buf = ds->pending_buf + (1+sizeof (ush))*ds->lit_bufsize; 1349 1350 ds->l_desc.dyn_tree = ds->dyn_ltree; 1351 ds->d_desc.dyn_tree = ds->dyn_dtree; 1352 ds->bl_desc.dyn_tree = ds->bl_tree; 1353 1354 return (Z_OK); 1355 #endif 1356 } 1357 1358 /* 1359 * =========================================================================== 1360 * Return the number of bytes of output which are immediately available 1361 * for output from the decompressor. ---PPP--- 1362 */ 1363 int 1364 deflateOutputPending(strm) 1365 z_streamp strm; 1366 { 1367 if (strm == Z_NULL || strm->state == Z_NULL) 1368 return (0); 1369 1370 return (((deflate_state *)(strm->state))->pending); 1371 } 1372 1373 /* 1374 * =========================================================================== 1375 * Read a new buffer from the current input stream, update the adler32 1376 * and total number of bytes read. All deflate() input goes through 1377 * this function so some applications may wish to modify it to avoid 1378 * allocating a large strm->next_in buffer and copying from it. 1379 * (See also flush_pending()). 1380 */ 1381 local int 1382 read_buf(strm, buf, size) 1383 z_streamp strm; 1384 Bytef *buf; 1385 unsigned size; 1386 { 1387 unsigned len = strm->avail_in; 1388 1389 if (len > size) len = size; 1390 if (len == 0) 1391 return (0); 1392 1393 strm->avail_in -= len; 1394 1395 if (!((deflate_state *)(strm->state))->noheader) { 1396 strm->adler = adler32(strm->adler, strm->next_in, len); 1397 } 1398 zmemcpy(buf, strm->next_in, len); 1399 strm->next_in += len; 1400 strm->total_in += len; 1401 1402 return ((int)len); 1403 } 1404 1405 /* 1406 * =========================================================================== 1407 * Initialize the "longest match" routines for a new zlib stream 1408 */ 1409 local void 1410 lm_init(s) 1411 deflate_state *s; 1412 { 1413 s->window_size = (ulg)2L*s->w_size; 1414 1415 CLEAR_HASH(s); 1416 1417 /* Set the default configuration parameters: */ 1418 s->max_lazy_match = configuration_table[s->level].max_lazy; 1419 s->good_match = configuration_table[s->level].good_length; 1420 s->nice_match = configuration_table[s->level].nice_length; 1421 s->max_chain_length = configuration_table[s->level].max_chain; 1422 1423 s->strstart = 0; 1424 s->block_start = 0L; 1425 s->lookahead = 0; 1426 s->match_length = s->prev_length = MIN_MATCH-1; 1427 s->match_available = 0; 1428 s->ins_h = 0; 1429 #ifdef ASMV 1430 match_init(); /* initialize the asm code */ 1431 #endif 1432 } 1433 1434 /* 1435 * =========================================================================== 1436 * Set match_start to the longest match starting at the given string and 1437 * return its length. Matches shorter or equal to prev_length are discarded, 1438 * in which case the result is equal to prev_length and match_start is 1439 * garbage. 1440 * IN assertions: cur_match is the head of the hash chain for the current 1441 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 1442 * OUT assertion: the match length is not greater than s->lookahead. 1443 */ 1444 #ifndef ASMV 1445 /* 1446 * For 80x86 and 680x0, an optimized version will be provided in 1447 * match.asm or match.S. The code will be functionally equivalent. 1448 */ 1449 #ifndef FASTEST 1450 local uInt 1451 longest_match(s, cur_match) 1452 deflate_state *s; 1453 IPos cur_match; /* current match */ 1454 { 1455 /* max hash chain length */ 1456 unsigned chain_length = s->max_chain_length; 1457 register Bytef *scan = s->window + s->strstart; /* current string */ 1458 register Bytef *match; /* matched string */ 1459 register int len; /* length of current match */ 1460 int best_len = s->prev_length; /* best match length so far */ 1461 int nice_match = s->nice_match; /* stop if match long enough */ 1462 IPos limit = s->strstart > (IPos)MAX_DIST(s) ? 1463 s->strstart - (IPos)MAX_DIST(s) : NIL; 1464 /* 1465 * Stop when cur_match becomes <= limit. To simplify the code, 1466 * we prevent matches with the string of window index 0. 1467 */ 1468 Posf *prev = s->prev; 1469 uInt wmask = s->w_mask; 1470 1471 #ifdef UNALIGNED_OK 1472 /* 1473 * Compare two bytes at a time. Note: this is not always 1474 * beneficial. Try with and without -DUNALIGNED_OK to check. 1475 */ 1476 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; 1477 register ush scan_start = *(ushf*)scan; 1478 register ush scan_end = *(ushf*)(scan+best_len-1); 1479 #else 1480 register Bytef *strend = s->window + s->strstart + MAX_MATCH; 1481 register Byte scan_end1 = scan[best_len-1]; 1482 register Byte scan_end = scan[best_len]; 1483 #endif 1484 1485 /* 1486 * The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 1487 * multiple of 16. It is easy to get rid of this optimization 1488 * if necessary. 1489 */ 1490 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); 1491 1492 /* Do not waste too much time if we already have a good match: */ 1493 if (s->prev_length >= s->good_match) { 1494 chain_length >>= 2; 1495 } 1496 /* 1497 * Do not look for matches beyond the end of the input. This 1498 * is necessary to make deflate deterministic. 1499 */ 1500 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; 1501 1502 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, 1503 "need lookahead"); 1504 1505 do { 1506 Assert(cur_match <= s->strstart, "no future"); 1507 match = s->window + cur_match; 1508 1509 /* 1510 * Skip to next match if the match length cannot 1511 * increase or if the match length is less than 2: 1512 */ 1513 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) 1514 /* 1515 * This code assumes sizeof (unsigned short) == 2. Do 1516 * not use UNALIGNED_OK if your compiler uses a 1517 * different size. 1518 */ 1519 if (*(ushf*)(match+best_len-1) != scan_end || 1520 *(ushf*)match != scan_start) continue; 1521 1522 /* 1523 * It is not necessary to compare scan[2] and match[2] 1524 * since they are always equal when the other bytes 1525 * match, given that the hash keys are equal and that 1526 * HASH_BITS >= 8. Compare 2 bytes at a time at 1527 * strstart+3, +5, ... up to strstart+257. We check 1528 * for insufficient lookahead only every 4th 1529 * comparison; the 128th check will be made at 1530 * strstart+257. If MAX_MATCH-2 is not a multiple of 1531 * 8, it is necessary to put more guard bytes at the 1532 * end of the window, or to check more often for 1533 * insufficient lookahead. 1534 */ 1535 Assert(scan[2] == match[2], "scan[2]?"); 1536 scan++, match++; 1537 do { 1538 } while (*(ushf *)(scan += 2) == *(ushf *)(match += 2) && 1539 *(ushf *)(scan += 2) == *(ushf *)(match += 2) && 1540 *(ushf *)(scan += 2) == *(ushf *)(match += 2) && 1541 *(ushf *)(scan += 2) == *(ushf *)(match += 2) && 1542 scan < strend); 1543 /* The funny "do {}" generates better code on most compilers */ 1544 1545 /* Here, scan <= window+strstart+257 */ 1546 Assert(scan <= s->window+(unsigned)(s->window_size-1), 1547 "wild scan"); 1548 if (*scan == *match) scan++; 1549 1550 len = (MAX_MATCH - 1) - (int)(strend-scan); 1551 scan = strend - (MAX_MATCH-1); 1552 1553 #else /* UNALIGNED_OK */ 1554 1555 if (match[best_len] != scan_end || 1556 match[best_len-1] != scan_end1 || 1557 *match != *scan || 1558 *++match != scan[1]) 1559 continue; 1560 1561 /* 1562 * The check at best_len-1 can be removed because it 1563 * will be made again later. (This heuristic is not 1564 * always a win.) It is not necessary to compare 1565 * scan[2] and match[2] since they are always equal 1566 * when the other bytes match, given that the hash 1567 * keys are equal and that HASH_BITS >= 8. 1568 */ 1569 scan += 2, match++; 1570 Assert(*scan == *match, "match[2]?"); 1571 1572 /* 1573 * We check for insufficient lookahead only every 8th 1574 * comparison; the 256th check will be made at 1575 * strstart+258. 1576 */ 1577 do { 1578 } while (*++scan == *++match && *++scan == *++match && 1579 *++scan == *++match && *++scan == *++match && 1580 *++scan == *++match && *++scan == *++match && 1581 *++scan == *++match && *++scan == *++match && 1582 scan < strend); 1583 1584 Assert(scan <= s->window+(unsigned)(s->window_size-1), 1585 "wild scan"); 1586 1587 len = MAX_MATCH - (int)(strend - scan); 1588 scan = strend - MAX_MATCH; 1589 1590 #endif /* UNALIGNED_OK */ 1591 1592 if (len > best_len) { 1593 s->match_start = cur_match; 1594 best_len = len; 1595 if (len >= nice_match) break; 1596 #ifdef UNALIGNED_OK 1597 scan_end = *(ushf*)(scan+best_len-1); 1598 #else 1599 scan_end1 = scan[best_len-1]; 1600 scan_end = scan[best_len]; 1601 #endif 1602 } 1603 } while ((cur_match = prev[cur_match & wmask]) > limit && 1604 --chain_length != 0); 1605 1606 if ((uInt)best_len <= s->lookahead) 1607 return (best_len); 1608 return (s->lookahead); 1609 } 1610 #else /* FASTEST */ 1611 /* 1612 * --------------------------------------------------------------------------- 1613 * Optimized version for level == 1 only 1614 */ 1615 local uInt 1616 longest_match(s, cur_match) 1617 deflate_state *s; 1618 IPos cur_match; /* current match */ 1619 { 1620 register Bytef *scan = s->window + s->strstart; /* current string */ 1621 register Bytef *match; /* matched string */ 1622 register int len; /* length of current match */ 1623 register Bytef *strend = s->window + s->strstart + MAX_MATCH; 1624 1625 /* 1626 * The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 1627 * multiple of 16. It is easy to get rid of this optimization 1628 * if necessary. 1629 */ 1630 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); 1631 1632 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, 1633 "need lookahead"); 1634 1635 Assert(cur_match <= s->strstart, "no future"); 1636 1637 match = s->window + cur_match; 1638 1639 /* Return failure if the match length is less than 2: */ 1640 if (match[0] != scan[0] || match[1] != scan[1]) 1641 return (MIN_MATCH-1); 1642 1643 /* 1644 * The check at best_len-1 can be removed because it will be 1645 * made again later. (This heuristic is not always a win.) It 1646 * is not necessary to compare scan[2] and match[2] since they 1647 * are always equal when the other bytes match, given that the 1648 * hash keys are equal and that HASH_BITS >= 8. 1649 */ 1650 scan += 2, match += 2; 1651 Assert(*scan == *match, "match[2]?"); 1652 1653 /* 1654 * We check for insufficient lookahead only every 8th comparison; 1655 * the 256th check will be made at strstart+258. 1656 */ 1657 do { 1658 } while (*++scan == *++match && *++scan == *++match && 1659 *++scan == *++match && *++scan == *++match && 1660 *++scan == *++match && *++scan == *++match && 1661 *++scan == *++match && *++scan == *++match && 1662 scan < strend); 1663 1664 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 1665 1666 len = MAX_MATCH - (int)(strend - scan); 1667 1668 if (len < MIN_MATCH) 1669 return (MIN_MATCH - 1); 1670 1671 s->match_start = cur_match; 1672 return (len <= s->lookahead ? len : s->lookahead); 1673 } 1674 #endif /* FASTEST */ 1675 #endif /* ASMV */ 1676 1677 #ifdef DEBUG_ZLIB 1678 /* 1679 * =========================================================================== 1680 * Check that the match at match_start is indeed a match. 1681 */ 1682 local void 1683 check_match(s, start, match, length) 1684 deflate_state *s; 1685 IPos start, match; 1686 int length; 1687 { 1688 /* check that the match is indeed a match */ 1689 if (zmemcmp(s->window + match, s->window + start, length) != EQUAL) { 1690 fprintf(stderr, " start %u, match %u, length %d\n", 1691 start, match, length); 1692 do { 1693 fprintf(stderr, "%c%c", s->window[match++], 1694 s->window[start++]); 1695 } while (--length != 0); 1696 z_error("invalid match"); 1697 } 1698 if (z_verbose > 1) { 1699 fprintf(stderr, "\\[%d,%d]", start-match, length); 1700 do { putc(s->window[start++], stderr); } while (--length != 0); 1701 } 1702 } 1703 #else 1704 #define check_match(s, start, match, length) 1705 #endif 1706 1707 /* 1708 * =========================================================================== 1709 * Fill the window when the lookahead becomes insufficient. 1710 * Updates strstart and lookahead. 1711 * 1712 * IN assertion: lookahead < MIN_LOOKAHEAD 1713 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD 1714 * At least one byte has been read, or avail_in == 0; reads are 1715 * performed for at least two bytes (required for the zip translate_eol 1716 * option -- not supported here). 1717 */ 1718 local void 1719 fill_window(s) 1720 deflate_state *s; 1721 { 1722 register unsigned n, m; 1723 register Posf *p; 1724 unsigned more; /* Amount of free space at the end of the window. */ 1725 uInt wsize = s->w_size; 1726 1727 do { 1728 more = (unsigned)(s->window_size -(ulg)s->lookahead - 1729 (ulg)s->strstart); 1730 1731 /* Deal with !@#$% 64K limit: */ 1732 if (more == 0 && s->strstart == 0 && s->lookahead == 0) { 1733 more = wsize; 1734 1735 } else if (more == (unsigned)(-1)) { 1736 /* 1737 * Very unlikely, but possible on 16 bit 1738 * machine if strstart == 0 and lookahead == 1 1739 * (input done one byte at time) 1740 */ 1741 more--; 1742 1743 /* 1744 * If the window is almost full and there is 1745 * insufficient lookahead, move the upper half 1746 * to the lower one to make room in the upper 1747 * half. 1748 */ 1749 } else if (s->strstart >= wsize+MAX_DIST(s)) { 1750 1751 Assert(wsize+wsize <= s->window_size, "wsize*2"); 1752 zmemcpy(s->window, s->window+wsize, (unsigned)wsize); 1753 s->match_start -= wsize; 1754 /* we now have strstart >= MAX_DIST */ 1755 s->strstart -= wsize; 1756 s->block_start -= (long)wsize; 1757 1758 /* 1759 * Slide the hash table (could be avoided with 1760 * 32 bit values at the expense of memory 1761 * usage). We slide even when level == 0 to 1762 * keep the hash table consistent if we switch 1763 * back to level > 0 later. (Using level 0 1764 * permanently is not an optimal usage of 1765 * zlib, so we don't care about this 1766 * pathological case.) 1767 */ 1768 n = s->hash_size; 1769 p = &s->head[n]; 1770 do { 1771 m = *--p; 1772 *p = (Pos)(m >= wsize ? m-wsize : NIL); 1773 } while (--n); 1774 1775 n = wsize; 1776 #ifndef FASTEST 1777 p = &s->prev[n]; 1778 do { 1779 m = *--p; 1780 *p = (Pos)(m >= wsize ? m-wsize : NIL); 1781 /* 1782 * If n is not on any hash chain, 1783 * prev[n] is garbage but its value 1784 * will never be used. 1785 */ 1786 } while (--n); 1787 #endif 1788 more += wsize; 1789 } 1790 if (s->strm->avail_in == 0) 1791 return; 1792 1793 /* 1794 * If there was no sliding: 1795 * strstart <= WSIZE+MAX_DIST-1 && 1796 * lookahead <= MIN_LOOKAHEAD - 1 && 1797 * more == window_size - lookahead - strstart 1798 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + 1799 * MAX_DIST-1) 1800 * => more >= window_size - 2*WSIZE + 2 1801 * In the BIG_MEM or MMAP case (not yet supported), 1802 * window_size == input_size + MIN_LOOKAHEAD && 1803 * strstart + s->lookahead <= input_size => 1804 * more >= MIN_LOOKAHEAD. 1805 * Otherwise, window_size == 2*WSIZE so more >= 2. 1806 * If there was sliding, more >= WSIZE. So in all cases, 1807 * more >= 2. 1808 */ 1809 Assert(more >= 2, "more < 2"); 1810 Assert(s->strstart + s->lookahead + more <= s->window_size, 1811 "read too much"); 1812 1813 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, 1814 more); 1815 s->lookahead += n; 1816 1817 /* Initialize the hash value now that we have some input: */ 1818 if (s->lookahead >= MIN_MATCH) { 1819 s->ins_h = s->window[s->strstart]; 1820 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); 1821 #if MIN_MATCH != 3 1822 Call UPDATE_HASH() MIN_MATCH-3 more times 1823 #endif 1824 } 1825 /* 1826 * If the whole input has less than MIN_MATCH bytes, 1827 * ins_h is garbage, but this is not important since 1828 * only literal bytes will be emitted. 1829 */ 1830 1831 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); 1832 } 1833 1834 /* 1835 * =========================================================================== 1836 * Flush the current block, with given end-of-file flag. 1837 * IN assertion: strstart is set to the end of the current match. 1838 */ 1839 #define FLUSH_BLOCK_ONLY(s, eof) { \ 1840 _tr_flush_block(s, (s->block_start >= 0L ? \ 1841 (charf *)&s->window[(unsigned)s->block_start] : \ 1842 (charf *)Z_NULL), \ 1843 (ulg)((long)s->strstart - s->block_start), \ 1844 (eof)); \ 1845 s->block_start = s->strstart; \ 1846 flush_pending(s->strm); \ 1847 Tracev((stderr, "[FLUSH]")); \ 1848 } 1849 1850 /* Same but force premature exit if necessary. */ 1851 #define FLUSH_BLOCK(s, eof) { \ 1852 FLUSH_BLOCK_ONLY(s, eof); \ 1853 if (s->strm->avail_out == 0) \ 1854 return ((eof) ? finish_started : need_more); \ 1855 } 1856 1857 /* 1858 * =========================================================================== 1859 * Copy without compression as much as possible from the input stream, return 1860 * the current block state. 1861 * This function does not insert new strings in the dictionary since 1862 * uncompressible data is probably not useful. This function is used 1863 * only for the level=0 compression option. 1864 * NOTE: this function should be optimized to avoid extra copying from 1865 * window to pending_buf. 1866 */ 1867 local block_state 1868 deflate_stored(s, flush) 1869 deflate_state *s; 1870 int flush; 1871 { 1872 /* 1873 * Stored blocks are limited to 0xffff bytes, pending_buf is 1874 * limited to pending_buf_size, and each stored block has a 5 1875 * byte header: 1876 */ 1877 ulg max_block_size = 0xffff; 1878 ulg max_start; 1879 1880 if (max_block_size > s->pending_buf_size - 5) { 1881 max_block_size = s->pending_buf_size - 5; 1882 } 1883 1884 /* Copy as much as possible from input to output: */ 1885 for (;;) { 1886 /* Fill the window as much as possible: */ 1887 if (s->lookahead <= 1) { 1888 1889 Assert(s->strstart < s->w_size+MAX_DIST(s) || 1890 s->block_start >= (long)s->w_size, 1891 "slide too late"); 1892 1893 fill_window(s); 1894 if (s->lookahead == 0 && flush == Z_NO_FLUSH) 1895 return (need_more); 1896 1897 if (s->lookahead == 0) 1898 break; /* flush the current block */ 1899 } 1900 Assert(s->block_start >= 0L, "block gone"); 1901 1902 s->strstart += s->lookahead; 1903 s->lookahead = 0; 1904 1905 /* Emit a stored block if pending_buf will be full: */ 1906 max_start = s->block_start + max_block_size; 1907 if (s->strstart == 0 || (ulg)s->strstart >= max_start) { 1908 /* 1909 * strstart == 0 is possible when wraparound 1910 * on 16-bit machine 1911 */ 1912 s->lookahead = (uInt)(s->strstart - max_start); 1913 s->strstart = (uInt)max_start; 1914 FLUSH_BLOCK(s, 0); 1915 } 1916 /* 1917 * Flush if we may have to slide, otherwise 1918 * block_start may become negative and the data will 1919 * be gone: 1920 */ 1921 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { 1922 FLUSH_BLOCK(s, 0); 1923 } 1924 } 1925 FLUSH_BLOCK(s, flush == Z_FINISH); 1926 return (flush == Z_FINISH ? finish_done : block_done); 1927 } 1928 1929 /* 1930 * =========================================================================== 1931 * Compress as much as possible from the input stream, return the current 1932 * block state. 1933 * This function does not perform lazy evaluation of matches and inserts 1934 * new strings in the dictionary only for unmatched strings or for short 1935 * matches. It is used only for the fast compression options. 1936 */ 1937 local block_state 1938 deflate_fast(s, flush) 1939 deflate_state *s; 1940 int flush; 1941 { 1942 IPos hash_head = NIL; /* head of the hash chain */ 1943 int bflush; /* set if current block must be flushed */ 1944 1945 for (;;) { 1946 /* 1947 * Make sure that we always have enough lookahead, 1948 * except at the end of the input file. We need 1949 * MAX_MATCH bytes for the next match, plus MIN_MATCH 1950 * bytes to insert the string following the next 1951 * match. 1952 */ 1953 if (s->lookahead < MIN_LOOKAHEAD) { 1954 fill_window(s); 1955 if (s->lookahead < MIN_LOOKAHEAD && 1956 flush == Z_NO_FLUSH) { 1957 return (need_more); 1958 } 1959 if (s->lookahead == 0) 1960 break; /* flush the current block */ 1961 } 1962 1963 /* 1964 * Insert the string window[strstart .. strstart+2] in 1965 * the dictionary, and set hash_head to the head of 1966 * the hash chain: 1967 */ 1968 if (s->lookahead >= MIN_MATCH) { 1969 INSERT_STRING(s, s->strstart, hash_head); 1970 } 1971 1972 /* 1973 * Find the longest match, discarding those <= 1974 * prev_length. At this point we have always 1975 * match_length < MIN_MATCH 1976 */ 1977 if (hash_head != NIL && s->strstart - hash_head <= 1978 MAX_DIST(s)) { 1979 /* 1980 * To simplify the code, we prevent matches 1981 * with the string of window index 0 (in 1982 * particular we have to avoid a match of the 1983 * string with itself at the start of the 1984 * input file). 1985 */ 1986 if (s->strategy != Z_HUFFMAN_ONLY) { 1987 s->match_length = longest_match(s, hash_head); 1988 } 1989 /* longest_match() sets match_start */ 1990 } 1991 if (s->match_length >= MIN_MATCH) { 1992 check_match(s, s->strstart, s->match_start, 1993 s->match_length); 1994 1995 _tr_tally_dist(s, s->strstart - s->match_start, 1996 s->match_length - MIN_MATCH, bflush); 1997 1998 s->lookahead -= s->match_length; 1999 2000 /* 2001 * Insert new strings in the hash table only 2002 * if the match length is not too large. This 2003 * saves time but degrades compression. 2004 */ 2005 #ifndef FASTEST 2006 if (s->match_length <= s->max_insert_length && 2007 s->lookahead >= MIN_MATCH) { 2008 /* string at strstart already in hash table */ 2009 s->match_length--; 2010 do { 2011 s->strstart++; 2012 INSERT_STRING(s, s->strstart, 2013 hash_head); 2014 /* 2015 * strstart never exceeds 2016 * WSIZE-MAX_MATCH, so there 2017 * are always MIN_MATCH bytes 2018 * ahead. 2019 */ 2020 } while (--s->match_length != 0); 2021 s->strstart++; 2022 } else 2023 #endif 2024 { 2025 s->strstart += s->match_length; 2026 s->match_length = 0; 2027 s->ins_h = s->window[s->strstart]; 2028 UPDATE_HASH(s, s->ins_h, 2029 s->window[s->strstart+1]); 2030 #if MIN_MATCH != 3 2031 Call UPDATE_HASH() MIN_MATCH-3 more times 2032 #endif 2033 /* 2034 * If lookahead < MIN_MATCH, ins_h is 2035 * garbage, but it does not matter 2036 * since it will be recomputed at next 2037 * deflate call. 2038 */ 2039 } 2040 } else { 2041 /* No match, output a literal byte */ 2042 Tracevv((stderr, "%c", s->window[s->strstart])); 2043 _tr_tally_lit(s, s->window[s->strstart], bflush); 2044 s->lookahead--; 2045 s->strstart++; 2046 } 2047 if (bflush) FLUSH_BLOCK(s, 0); 2048 } 2049 FLUSH_BLOCK(s, flush == Z_FINISH); 2050 return (flush == Z_FINISH ? finish_done : block_done); 2051 } 2052 2053 /* 2054 * =========================================================================== 2055 * Same as above, but achieves better compression. We use a lazy 2056 * evaluation for matches: a match is finally adopted only if there is 2057 * no better match at the next window position. 2058 */ 2059 local block_state 2060 deflate_slow(s, flush) 2061 deflate_state *s; 2062 int flush; 2063 { 2064 IPos hash_head = NIL; /* head of hash chain */ 2065 int bflush; /* set if current block must be flushed */ 2066 2067 /* Process the input block. */ 2068 for (;;) { 2069 /* 2070 * Make sure that we always have enough lookahead, 2071 * except at the end of the input file. We need 2072 * MAX_MATCH bytes for the next match, plus MIN_MATCH 2073 * bytes to insert the string following the next 2074 * match. 2075 */ 2076 if (s->lookahead < MIN_LOOKAHEAD) { 2077 fill_window(s); 2078 if (s->lookahead < MIN_LOOKAHEAD && 2079 flush == Z_NO_FLUSH) { 2080 return (need_more); 2081 } 2082 /* flush the current block */ 2083 if (s->lookahead == 0) 2084 break; 2085 } 2086 2087 /* 2088 * Insert the string window[strstart .. strstart+2] in 2089 * the dictionary, and set hash_head to the head of 2090 * the hash chain: 2091 */ 2092 if (s->lookahead >= MIN_MATCH) { 2093 INSERT_STRING(s, s->strstart, hash_head); 2094 } 2095 2096 /* 2097 * Find the longest match, discarding those <= 2098 * prev_length. 2099 */ 2100 s->prev_length = s->match_length; 2101 s->prev_match = s->match_start; 2102 s->match_length = MIN_MATCH-1; 2103 2104 if (hash_head != NIL && s->prev_length < s->max_lazy_match && 2105 s->strstart - hash_head <= MAX_DIST(s)) { 2106 /* 2107 * To simplify the code, we prevent matches 2108 * with the string of window index 0 (in 2109 * particular we have to avoid a match of the 2110 * string with itself at the start of the 2111 * input file). 2112 */ 2113 if (s->strategy != Z_HUFFMAN_ONLY) { 2114 s->match_length = longest_match(s, hash_head); 2115 } 2116 /* longest_match() sets match_start */ 2117 2118 if (s->match_length <= 5 && 2119 (s->strategy == Z_FILTERED || 2120 (s->match_length == MIN_MATCH && 2121 s->strstart - s->match_start > TOO_FAR))) { 2122 2123 /* 2124 * If prev_match is also MIN_MATCH, 2125 * match_start is garbage but we will 2126 * ignore the current match anyway. 2127 */ 2128 s->match_length = MIN_MATCH-1; 2129 } 2130 } 2131 /* 2132 * If there was a match at the previous step and the 2133 * current match is not better, output the previous 2134 * match: 2135 */ 2136 if (s->prev_length >= MIN_MATCH && 2137 s->match_length <= s->prev_length) { 2138 uInt max_insert = s->strstart + s->lookahead - 2139 MIN_MATCH; 2140 /* Do not insert strings in hash table beyond this. */ 2141 2142 check_match(s, s->strstart-1, s->prev_match, 2143 s->prev_length); 2144 2145 _tr_tally_dist(s, s->strstart -1 - s->prev_match, 2146 s->prev_length - MIN_MATCH, bflush); 2147 2148 /* 2149 * Insert in hash table all strings up to the 2150 * end of the match. strstart-1 and strstart 2151 * are already inserted. If there is not 2152 * enough lookahead, the last two strings are 2153 * not inserted in the hash table. 2154 */ 2155 s->lookahead -= s->prev_length-1; 2156 s->prev_length -= 2; 2157 do { 2158 if (++s->strstart <= max_insert) { 2159 INSERT_STRING(s, s->strstart, 2160 hash_head); 2161 } 2162 } while (--s->prev_length != 0); 2163 s->match_available = 0; 2164 s->match_length = MIN_MATCH-1; 2165 s->strstart++; 2166 2167 if (bflush) FLUSH_BLOCK(s, 0); 2168 2169 } else if (s->match_available) { 2170 /* 2171 * If there was no match at the previous 2172 * position, output a single literal. If there 2173 * was a match but the current match is 2174 * longer, truncate the previous match to a 2175 * single literal. 2176 */ 2177 Tracevv((stderr, "%c", s->window[s->strstart-1])); 2178 _tr_tally_lit(s, s->window[s->strstart-1], bflush); 2179 if (bflush) { 2180 FLUSH_BLOCK_ONLY(s, 0); 2181 } 2182 s->strstart++; 2183 s->lookahead--; 2184 if (s->strm->avail_out == 0) 2185 return (need_more); 2186 } else { 2187 /* 2188 * There is no previous match to compare with, 2189 * wait for the next step to decide. 2190 */ 2191 s->match_available = 1; 2192 s->strstart++; 2193 s->lookahead--; 2194 } 2195 } 2196 Assert(flush != Z_NO_FLUSH, "no flush?"); 2197 if (s->match_available) { 2198 Tracevv((stderr, "%c", s->window[s->strstart-1])); 2199 _tr_tally_lit(s, s->window[s->strstart-1], bflush); 2200 s->match_available = 0; 2201 } 2202 FLUSH_BLOCK(s, flush == Z_FINISH); 2203 return (flush == Z_FINISH ? finish_done : block_done); 2204 } 2205 /* --- deflate.c */ 2206 2207 /* +++ trees.c */ 2208 /* 2209 * trees.c -- output deflated data using Huffman coding 2210 * Copyright (C) 1995-1998 Jean-loup Gailly 2211 * For conditions of distribution and use, see copyright notice in zlib.h 2212 */ 2213 2214 /* 2215 * ALGORITHM 2216 * 2217 * The "deflation" process uses several Huffman trees. The more 2218 * common source values are represented by shorter bit sequences. 2219 * 2220 * Each code tree is stored in a compressed form which is itself 2221 * a Huffman encoding of the lengths of all the code strings (in 2222 * ascending order by source values). The actual code strings are 2223 * reconstructed from the lengths in the inflate process, as described 2224 * in the deflate specification. 2225 * 2226 * REFERENCES 2227 * 2228 * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". 2229 * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc 2230 * 2231 * Storer, James A. 2232 * Data Compression: Methods and Theory, pp. 49-50. 2233 * Computer Science Press, 1988. ISBN 0-7167-8156-5. 2234 * 2235 * Sedgewick, R. 2236 * Algorithms, p290. 2237 * Addison-Wesley, 1983. ISBN 0-201-06672-6. 2238 */ 2239 2240 /* From: trees.c,v 1.11 1996/07/24 13:41:06 me Exp $ */ 2241 2242 /* #include "deflate.h" */ 2243 2244 #ifdef DEBUG_ZLIB 2245 #include <ctype.h> 2246 #endif 2247 2248 /* 2249 * =========================================================================== 2250 * Constants 2251 */ 2252 2253 #define MAX_BL_BITS 7 2254 /* Bit length codes must not exceed MAX_BL_BITS bits */ 2255 2256 #define END_BLOCK 256 2257 /* end of block literal code */ 2258 2259 #define REP_3_6 16 2260 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ 2261 2262 #define REPZ_3_10 17 2263 /* repeat a zero length 3-10 times (3 bits of repeat count) */ 2264 2265 #define REPZ_11_138 18 2266 /* repeat a zero length 11-138 times (7 bits of repeat count) */ 2267 2268 /* extra bits for each length code */ 2269 local const int extra_lbits[LENGTH_CODES] = { 2270 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 2271 4, 4, 4, 5, 5, 5, 5, 0}; 2272 2273 /* extra bits for each distance code */ 2274 local const int extra_dbits[D_CODES] = { 2275 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 2276 9, 10, 10, 11, 11, 12, 12, 13, 13}; 2277 2278 /* extra bits for each bit length code */ 2279 local const int extra_blbits[BL_CODES] = { 2280 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; 2281 2282 local const uch bl_order[BL_CODES] = { 2283 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; 2284 2285 /* 2286 * The lengths of the bit length codes are sent in order of decreasing 2287 * probability, to avoid transmitting the lengths for unused bit 2288 * length codes. 2289 */ 2290 2291 #define Buf_size (8 * 2*sizeof (char)) 2292 /* 2293 * Number of bits used within bi_buf. (bi_buf might be implemented on 2294 * more than 16 bits on some systems.) 2295 */ 2296 2297 /* 2298 * =========================================================================== 2299 * Local data. These are initialized only once. 2300 */ 2301 #define DIST_CODE_LEN 512 /* see definition of array dist_code below */ 2302 2303 local ct_data static_ltree[L_CODES+2]; 2304 /* 2305 * The static literal tree. Since the bit lengths are imposed, there 2306 * is no need for the L_CODES extra codes used during heap 2307 * construction. However The codes 286 and 287 are needed to build a 2308 * canonical tree (see _tr_init below). 2309 */ 2310 2311 local ct_data static_dtree[D_CODES]; 2312 /* 2313 * The static distance tree. (Actually a trivial tree since all codes 2314 * use 5 bits.) 2315 */ 2316 2317 local uch _dist_code[512]; 2318 /* 2319 * distance codes. The first 256 values correspond to the distances 3 2320 * .. 258, the last 256 values correspond to the top 8 bits of the 15 2321 * bit distances. 2322 */ 2323 2324 local uch _length_code[MAX_MATCH-MIN_MATCH+1]; 2325 /* length code for each normalized match length (0 == MIN_MATCH) */ 2326 2327 local int base_length[LENGTH_CODES]; 2328 /* First normalized length for each code (0 = MIN_MATCH) */ 2329 2330 local int base_dist[D_CODES]; 2331 /* First normalized distance for each code (0 = distance of 1) */ 2332 2333 struct static_tree_desc_s { 2334 const ct_data *static_tree; /* static tree or NULL */ 2335 const intf *extra_bits; /* extra bits for each code or NULL */ 2336 int extra_base; /* base index for extra_bits */ 2337 int elems; /* max number of elements in the tree */ 2338 int max_length; /* max bit length for the codes */ 2339 }; 2340 2341 local static_tree_desc static_l_desc = { 2342 static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; 2343 2344 local static_tree_desc static_d_desc = { 2345 static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; 2346 2347 local static_tree_desc static_bl_desc = { 2348 (const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; 2349 2350 /* 2351 * =========================================================================== 2352 * Local (static) routines in this file. 2353 */ 2354 2355 local void tr_static_init OF((void)); 2356 local void init_block OF((deflate_state *s)); 2357 local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); 2358 local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); 2359 local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); 2360 local void build_tree OF((deflate_state *s, tree_desc *desc)); 2361 local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); 2362 local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); 2363 local int build_bl_tree OF((deflate_state *s)); 2364 local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, 2365 int blcodes)); 2366 local void compress_block OF((deflate_state *s, ct_data *ltree, 2367 ct_data *dtree)); 2368 local void set_data_type OF((deflate_state *s)); 2369 local unsigned bi_reverse OF((unsigned value, int length)); 2370 local void bi_windup OF((deflate_state *s)); 2371 local void bi_flush OF((deflate_state *s)); 2372 local void copy_block OF((deflate_state *s, charf *buf, unsigned len, 2373 int header)); 2374 2375 #ifndef DEBUG_ZLIB 2376 #define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) 2377 /* Send a code of the given tree. c and tree must not have side effects */ 2378 2379 #else /* DEBUG_ZLIB */ 2380 #define send_code(s, c, tree) \ 2381 { if (z_verbose > 2) fprintf(stderr, "\ncd %3d ", (c)); \ 2382 send_bits(s, tree[c].Code, tree[c].Len); } 2383 #endif 2384 2385 /* 2386 * =========================================================================== 2387 * Output a short LSB first on the stream. 2388 * IN assertion: there is enough room in pendingBuf. 2389 */ 2390 #define put_short(s, w) { \ 2391 put_byte(s, (uch)((w) & 0xff)); \ 2392 put_byte(s, (uch)((ush)(w) >> 8)); \ 2393 } 2394 2395 /* 2396 * =========================================================================== 2397 * Send a value on a given number of bits. 2398 * IN assertion: length <= 16 and value fits in length bits. 2399 */ 2400 #ifdef DEBUG_ZLIB 2401 local void send_bits OF((deflate_state *s, int value, int length)); 2402 2403 local void 2404 send_bits(s, value, length) 2405 deflate_state *s; 2406 int value; /* value to send */ 2407 int length; /* number of bits */ 2408 { 2409 Tracevv((stderr, " l %2d v %4x ", length, value)); 2410 Assert(length > 0 && length <= 15, "invalid length"); 2411 s->bits_sent += (ulg)length; 2412 2413 /* 2414 * If not enough room in bi_buf, use (valid) bits from bi_buf 2415 * and (16 - bi_valid) bits from value, leaving (width - 2416 * (16-bi_valid)) unused bits in value. 2417 */ 2418 if (s->bi_valid > (int)Buf_size - length) { 2419 s->bi_buf |= (value << s->bi_valid); 2420 put_short(s, s->bi_buf); 2421 s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); 2422 s->bi_valid += length - Buf_size; 2423 } else { 2424 s->bi_buf |= value << s->bi_valid; 2425 s->bi_valid += length; 2426 } 2427 } 2428 #else /* !DEBUG_ZLIB */ 2429 2430 #define send_bits(s, value, length) \ 2431 { int len = length; \ 2432 if (s->bi_valid > (int)Buf_size - len) {\ 2433 int val = value; \ 2434 s->bi_buf |= (val << s->bi_valid); \ 2435 put_short(s, s->bi_buf); \ 2436 s->bi_buf = (ush)val >> (Buf_size - s->bi_valid); \ 2437 s->bi_valid += len - Buf_size; \ 2438 } else {\ 2439 s->bi_buf |= (value) << s->bi_valid; \ 2440 s->bi_valid += len; \ 2441 }\ 2442 } 2443 #endif /* DEBUG_ZLIB */ 2444 2445 2446 #define MAX(a, b) (a >= b ? a : b) 2447 /* the arguments must not have side effects */ 2448 2449 /* 2450 * =========================================================================== 2451 * Initialize the various 'constant' tables. In a multi-threaded environment, 2452 * this function may be called by two threads concurrently, but this is 2453 * harmless since both invocations do exactly the same thing. 2454 */ 2455 local void 2456 tr_static_init() 2457 { 2458 static int static_init_done = 0; 2459 int n; /* iterates over tree elements */ 2460 int bits; /* bit counter */ 2461 int length; /* length value */ 2462 int code; /* code value */ 2463 int dist; /* distance index */ 2464 ush bl_count[MAX_BITS+1]; 2465 /* number of codes at each bit length for an optimal tree */ 2466 2467 if (static_init_done) 2468 return; 2469 2470 /* For some embedded targets, global variables are not initialized: */ 2471 static_l_desc.static_tree = static_ltree; 2472 static_l_desc.extra_bits = extra_lbits; 2473 static_d_desc.static_tree = static_dtree; 2474 static_d_desc.extra_bits = extra_dbits; 2475 static_bl_desc.extra_bits = extra_blbits; 2476 2477 /* Initialize the mapping length (0..255) -> length code (0..28) */ 2478 length = 0; 2479 for (code = 0; code < LENGTH_CODES-1; code++) { 2480 base_length[code] = length; 2481 for (n = 0; n < (1<<extra_lbits[code]); n++) { 2482 _length_code[length++] = (uch)code; 2483 } 2484 } 2485 Assert(length == 256, "tr_static_init: length != 256"); 2486 /* 2487 * Note that the length 255 (match length 258) can be 2488 * represented in two different ways: code 284 + 5 bits or 2489 * code 285, so we overwrite _length_code[255] to use the best 2490 * encoding: 2491 */ 2492 _length_code[length-1] = (uch)code; 2493 2494 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ 2495 dist = 0; 2496 for (code = 0; code < 16; code++) { 2497 base_dist[code] = dist; 2498 for (n = 0; n < (1<<extra_dbits[code]); n++) { 2499 _dist_code[dist++] = (uch)code; 2500 } 2501 } 2502 Assert(dist == 256, "tr_static_init: dist != 256"); 2503 dist >>= 7; /* from now on, all distances are divided by 128 */ 2504 for (; code < D_CODES; code++) { 2505 base_dist[code] = dist << 7; 2506 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { 2507 _dist_code[256 + dist++] = (uch)code; 2508 } 2509 } 2510 Assert(dist == 256, "tr_static_init: 256+dist != 512"); 2511 2512 /* Construct the codes of the static literal tree */ 2513 for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; 2514 n = 0; 2515 while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; 2516 while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; 2517 while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; 2518 while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; 2519 /* 2520 * Codes 286 and 287 do not exist, but we must include them in the 2521 * tree construction to get a canonical Huffman tree (longest code 2522 * all ones) 2523 */ 2524 gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); 2525 2526 /* The static distance tree is trivial: */ 2527 for (n = 0; n < D_CODES; n++) { 2528 static_dtree[n].Len = 5; 2529 static_dtree[n].Code = bi_reverse((unsigned)n, 5); 2530 } 2531 static_init_done = 1; 2532 } 2533 2534 /* 2535 * =========================================================================== 2536 * Initialize the tree data structures for a new zlib stream. 2537 */ 2538 void 2539 _tr_init(s) 2540 deflate_state *s; 2541 { 2542 tr_static_init(); 2543 2544 s->l_desc.dyn_tree = s->dyn_ltree; 2545 s->l_desc.stat_desc = &static_l_desc; 2546 2547 s->d_desc.dyn_tree = s->dyn_dtree; 2548 s->d_desc.stat_desc = &static_d_desc; 2549 2550 s->bl_desc.dyn_tree = s->bl_tree; 2551 s->bl_desc.stat_desc = &static_bl_desc; 2552 2553 s->bi_buf = 0; 2554 s->bi_valid = 0; 2555 s->last_eob_len = 8; /* enough lookahead for inflate */ 2556 s->compressed_len = 0L; /* PPP */ 2557 #ifdef DEBUG_ZLIB 2558 s->bits_sent = 0L; 2559 #endif 2560 2561 /* Initialize the first block of the first file: */ 2562 init_block(s); 2563 } 2564 2565 /* 2566 * =========================================================================== 2567 * Initialize a new block. 2568 */ 2569 local void 2570 init_block(s) 2571 deflate_state *s; 2572 { 2573 int n; /* iterates over tree elements */ 2574 2575 /* Initialize the trees. */ 2576 for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; 2577 for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; 2578 for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; 2579 2580 s->dyn_ltree[END_BLOCK].Freq = 1; 2581 s->opt_len = s->static_len = 0L; 2582 s->last_lit = s->matches = 0; 2583 } 2584 2585 #define SMALLEST 1 2586 /* Index within the heap array of least frequent node in the Huffman tree */ 2587 2588 2589 /* 2590 * =========================================================================== 2591 * Remove the smallest element from the heap and recreate the heap with 2592 * one less element. Updates heap and heap_len. 2593 */ 2594 #define pqremove(s, tree, top) \ 2595 {\ 2596 top = s->heap[SMALLEST]; \ 2597 s->heap[SMALLEST] = s->heap[s->heap_len--]; \ 2598 pqdownheap(s, tree, SMALLEST); \ 2599 } 2600 2601 /* 2602 * =========================================================================== 2603 * Compares to subtrees, using the tree depth as tie breaker when 2604 * the subtrees have equal frequency. This minimizes the worst case length. 2605 */ 2606 #define smaller(tree, n, m, depth) \ 2607 (tree[n].Freq < tree[m].Freq || \ 2608 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) 2609 /* 2610 * =========================================================================== 2611 * Restore the heap property by moving down the tree starting at node k, 2612 * exchanging a node with the smallest of its two sons if necessary, stopping 2613 * when the heap property is re-established (each father smaller than its 2614 * two sons). 2615 */ 2616 local void 2617 pqdownheap(s, tree, k) 2618 deflate_state *s; 2619 ct_data *tree; /* the tree to restore */ 2620 int k; /* node to move down */ 2621 { 2622 int v = s->heap[k]; 2623 int j = k << 1; /* left son of k */ 2624 while (j <= s->heap_len) { 2625 /* Set j to the smallest of the two sons: */ 2626 if (j < s->heap_len && 2627 smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { 2628 j++; 2629 } 2630 /* Exit if v is smaller than both sons */ 2631 if (smaller(tree, v, s->heap[j], s->depth)) break; 2632 2633 /* Exchange v with the smallest son */ 2634 s->heap[k] = s->heap[j]; k = j; 2635 2636 /* And continue down the tree, setting j to the left son of k */ 2637 j <<= 1; 2638 } 2639 s->heap[k] = v; 2640 } 2641 2642 /* 2643 * =========================================================================== 2644 * Compute the optimal bit lengths for a tree and update the total bit length 2645 * for the current block. 2646 * IN assertion: the fields freq and dad are set, heap[heap_max] and 2647 * above are the tree nodes sorted by increasing frequency. 2648 * OUT assertions: the field len is set to the optimal bit length, the 2649 * array bl_count contains the frequencies for each bit length. 2650 * The length opt_len is updated; static_len is also updated if stree is 2651 * not null. 2652 */ 2653 local void 2654 gen_bitlen(s, desc) 2655 deflate_state *s; 2656 tree_desc *desc; /* the tree descriptor */ 2657 { 2658 ct_data *tree = desc->dyn_tree; 2659 int max_code = desc->max_code; 2660 const ct_data *stree = desc->stat_desc->static_tree; 2661 const intf *extra = desc->stat_desc->extra_bits; 2662 int base = desc->stat_desc->extra_base; 2663 int max_length = desc->stat_desc->max_length; 2664 int h; /* heap index */ 2665 int n, m; /* iterate over the tree elements */ 2666 int bits; /* bit length */ 2667 int xbits; /* extra bits */ 2668 ush f; /* frequency */ 2669 /* number of elements with bit length too large */ 2670 int overflow = 0; 2671 2672 for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; 2673 2674 /* 2675 * In a first pass, compute the optimal bit lengths (which may 2676 * overflow in the case of the bit length tree). 2677 */ 2678 tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ 2679 2680 for (h = s->heap_max+1; h < HEAP_SIZE; h++) { 2681 n = s->heap[h]; 2682 bits = tree[tree[n].Dad].Len + 1; 2683 if (bits > max_length) bits = max_length, overflow++; 2684 tree[n].Len = (ush)bits; 2685 /* We overwrite tree[n].Dad which is no longer needed */ 2686 2687 if (n > max_code) continue; /* not a leaf node */ 2688 2689 s->bl_count[bits]++; 2690 xbits = 0; 2691 if (n >= base) xbits = extra[n-base]; 2692 f = tree[n].Freq; 2693 s->opt_len += (ulg)f * (bits + xbits); 2694 if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); 2695 } 2696 if (overflow == 0) 2697 return; 2698 2699 Trace((stderr, "\nbit length overflow\n")); 2700 /* This happens for example on obj2 and pic of the Calgary corpus */ 2701 2702 /* Find the first bit length which could increase: */ 2703 do { 2704 bits = max_length-1; 2705 while (s->bl_count[bits] == 0) bits--; 2706 s->bl_count[bits]--; /* move one leaf down the tree */ 2707 /* move one overflow item as its brother */ 2708 s->bl_count[bits+1] += 2; 2709 s->bl_count[max_length]--; 2710 /* 2711 * The brother of the overflow item also moves one 2712 * step up, but this does not affect 2713 * bl_count[max_length] 2714 */ 2715 overflow -= 2; 2716 } while (overflow > 0); 2717 2718 /* 2719 * Now recompute all bit lengths, scanning in increasing 2720 * frequency. h is still equal to HEAP_SIZE. (It is simpler 2721 * to reconstruct all lengths instead of fixing only the wrong 2722 * ones. This idea is taken from 'ar' written by Haruhiko 2723 * Okumura.) 2724 */ 2725 for (bits = max_length; bits != 0; bits--) { 2726 n = s->bl_count[bits]; 2727 while (n != 0) { 2728 m = s->heap[--h]; 2729 if (m > max_code) continue; 2730 if (tree[m].Len != (unsigned)bits) { 2731 Trace((stderr, "code %d bits %d->%d\n", m, 2732 tree[m].Len, bits)); 2733 s->opt_len += ((long)bits - (long)tree[m].Len) 2734 *(long)tree[m].Freq; 2735 tree[m].Len = (ush)bits; 2736 } 2737 n--; 2738 } 2739 } 2740 } 2741 2742 /* 2743 * =========================================================================== 2744 * Generate the codes for a given tree and bit counts (which need not be 2745 * optimal). 2746 * IN assertion: the array bl_count contains the bit length statistics for 2747 * the given tree and the field len is set for all tree elements. 2748 * OUT assertion: the field code is set for all tree elements of non 2749 * zero code length. 2750 */ 2751 local void 2752 gen_codes(tree, max_code, bl_count) 2753 ct_data *tree; /* the tree to decorate */ 2754 int max_code; /* largest code with non zero frequency */ 2755 ushf *bl_count; /* number of codes at each bit length */ 2756 { 2757 /* next code value for each bit length */ 2758 ush next_code[MAX_BITS+1]; 2759 ush code = 0; /* running code value */ 2760 int bits; /* bit index */ 2761 int n; /* code index */ 2762 2763 /* 2764 * The distribution counts are first used to generate the code 2765 * values without bit reversal. 2766 */ 2767 for (bits = 1; bits <= MAX_BITS; bits++) { 2768 next_code[bits] = code = (code + bl_count[bits-1]) << 1; 2769 } 2770 /* 2771 * Check that the bit counts in bl_count are consistent. The 2772 * last code must be all ones. 2773 */ 2774 Assert(code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, 2775 "inconsistent bit counts"); 2776 Tracev((stderr, "\ngen_codes: max_code %d ", max_code)); 2777 2778 for (n = 0; n <= max_code; n++) { 2779 int len = tree[n].Len; 2780 if (len == 0) continue; 2781 /* Now reverse the bits */ 2782 tree[n].Code = bi_reverse(next_code[len]++, len); 2783 2784 Tracecv(tree != static_ltree, 2785 (stderr, "\nn %3d %c l %2d c %4x (%x) ", 2786 n, (isgraph(n) ? n : ' '), len, tree[n].Code, 2787 next_code[len]-1)); 2788 } 2789 } 2790 2791 /* 2792 * =========================================================================== 2793 * Construct one Huffman tree and assigns the code bit strings and lengths. 2794 * Update the total bit length for the current block. 2795 * IN assertion: the field freq is set for all tree elements. 2796 * OUT assertions: the fields len and code are set to the optimal bit length 2797 * and corresponding code. The length opt_len is updated; static_len is 2798 * also updated if stree is not null. The field max_code is set. 2799 */ 2800 local void 2801 build_tree(s, desc) 2802 deflate_state *s; 2803 tree_desc *desc; /* the tree descriptor */ 2804 { 2805 ct_data *tree = desc->dyn_tree; 2806 const ct_data *stree = desc->stat_desc->static_tree; 2807 int elems = desc->stat_desc->elems; 2808 int n, m; /* iterate over heap elements */ 2809 int max_code = -1; /* largest code with non zero frequency */ 2810 int node; /* new node being created */ 2811 2812 /* 2813 * Construct the initial heap, with least frequent element in 2814 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and 2815 * heap[2*n+1]. heap[0] is not used. 2816 */ 2817 s->heap_len = 0, s->heap_max = HEAP_SIZE; 2818 2819 for (n = 0; n < elems; n++) { 2820 if (tree[n].Freq != 0) { 2821 s->heap[++(s->heap_len)] = max_code = n; 2822 s->depth[n] = 0; 2823 } else { 2824 tree[n].Len = 0; 2825 } 2826 } 2827 2828 /* 2829 * The pkzip format requires that at least one distance code 2830 * exists, and that at least one bit should be sent even if 2831 * there is only one possible code. So to avoid special checks 2832 * later on we force at least two codes of non zero frequency. 2833 */ 2834 while (s->heap_len < 2) { 2835 node = s->heap[++(s->heap_len)] = (max_code < 2 ? 2836 ++max_code : 0); 2837 tree[node].Freq = 1; 2838 s->depth[node] = 0; 2839 s->opt_len--; if (stree) s->static_len -= stree[node].Len; 2840 /* node is 0 or 1 so it does not have extra bits */ 2841 } 2842 desc->max_code = max_code; 2843 2844 /* 2845 * The elements heap[heap_len/2+1 .. heap_len] are leaves of 2846 * the tree, establish sub-heaps of increasing lengths: 2847 */ 2848 for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); 2849 2850 /* 2851 * Construct the Huffman tree by repeatedly combining the 2852 * least two frequent nodes. 2853 */ 2854 node = elems; /* next internal node of the tree */ 2855 do { 2856 pqremove(s, tree, n); /* n = node of least frequency */ 2857 m = s->heap[SMALLEST]; /* m = node of next least frequency */ 2858 2859 /* keep the nodes sorted by frequency */ 2860 s->heap[--(s->heap_max)] = n; 2861 s->heap[--(s->heap_max)] = m; 2862 2863 /* Create a new node father of n and m */ 2864 tree[node].Freq = tree[n].Freq + tree[m].Freq; 2865 s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1); 2866 tree[n].Dad = tree[m].Dad = (ush)node; 2867 #ifdef DUMP_BL_TREE 2868 if (tree == s->bl_tree) { 2869 fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)", 2870 node, tree[node].Freq, n, tree[n].Freq, m, 2871 tree[m].Freq); 2872 } 2873 #endif 2874 /* and insert the new node in the heap */ 2875 s->heap[SMALLEST] = node++; 2876 pqdownheap(s, tree, SMALLEST); 2877 2878 } while (s->heap_len >= 2); 2879 2880 s->heap[--(s->heap_max)] = s->heap[SMALLEST]; 2881 2882 /* 2883 * At this point, the fields freq and dad are set. We can now 2884 * generate the bit lengths. 2885 */ 2886 gen_bitlen(s, (tree_desc *)desc); 2887 2888 /* The field len is now set, we can generate the bit codes */ 2889 gen_codes((ct_data *)tree, max_code, s->bl_count); 2890 } 2891 2892 /* 2893 * =========================================================================== 2894 * Scan a literal or distance tree to determine the frequencies of the codes 2895 * in the bit length tree. 2896 */ 2897 local void 2898 scan_tree(s, tree, max_code) 2899 deflate_state *s; 2900 ct_data *tree; /* the tree to be scanned */ 2901 int max_code; /* and its largest code of non zero frequency */ 2902 { 2903 int n; /* iterates over all tree elements */ 2904 int prevlen = -1; /* last emitted length */ 2905 int curlen; /* length of current code */ 2906 int nextlen = tree[0].Len; /* length of next code */ 2907 int count = 0; /* repeat count of the current code */ 2908 int max_count = 7; /* max repeat count */ 2909 int min_count = 4; /* min repeat count */ 2910 2911 if (nextlen == 0) max_count = 138, min_count = 3; 2912 tree[max_code+1].Len = (ush)0xffff; /* guard */ 2913 2914 for (n = 0; n <= max_code; n++) { 2915 curlen = nextlen; nextlen = tree[n+1].Len; 2916 if (++count < max_count && curlen == nextlen) { 2917 continue; 2918 } else if (count < min_count) { 2919 s->bl_tree[curlen].Freq += count; 2920 } else if (curlen != 0) { 2921 if (curlen != prevlen) s->bl_tree[curlen].Freq++; 2922 s->bl_tree[REP_3_6].Freq++; 2923 } else if (count <= 10) { 2924 s->bl_tree[REPZ_3_10].Freq++; 2925 } else { 2926 s->bl_tree[REPZ_11_138].Freq++; 2927 } 2928 count = 0; prevlen = curlen; 2929 if (nextlen == 0) { 2930 max_count = 138, min_count = 3; 2931 } else if (curlen == nextlen) { 2932 max_count = 6, min_count = 3; 2933 } else { 2934 max_count = 7, min_count = 4; 2935 } 2936 } 2937 } 2938 2939 /* 2940 * =========================================================================== 2941 * Send a literal or distance tree in compressed form, using the codes in 2942 * bl_tree. 2943 */ 2944 local void 2945 send_tree(s, tree, max_code) 2946 deflate_state *s; 2947 ct_data *tree; /* the tree to be scanned */ 2948 int max_code; /* and its largest code of non zero frequency */ 2949 { 2950 int n; /* iterates over all tree elements */ 2951 int prevlen = -1; /* last emitted length */ 2952 int curlen; /* length of current code */ 2953 int nextlen = tree[0].Len; /* length of next code */ 2954 int count = 0; /* repeat count of the current code */ 2955 int max_count = 7; /* max repeat count */ 2956 int min_count = 4; /* min repeat count */ 2957 2958 /* tree[max_code+1].Len = -1; */ /* guard already set */ 2959 if (nextlen == 0) max_count = 138, min_count = 3; 2960 2961 for (n = 0; n <= max_code; n++) { 2962 curlen = nextlen; nextlen = tree[n+1].Len; 2963 if (++count < max_count && curlen == nextlen) { 2964 continue; 2965 } else if (count < min_count) { 2966 do { send_code(s, curlen, s->bl_tree); } 2967 while (--count != 0); 2968 2969 } else if (curlen != 0) { 2970 if (curlen != prevlen) { 2971 send_code(s, curlen, s->bl_tree); count--; 2972 } 2973 Assert(count >= 3 && count <= 6, " 3_6?"); 2974 send_code(s, REP_3_6, s->bl_tree); 2975 send_bits(s, count-3, 2); 2976 2977 } else if (count <= 10) { 2978 send_code(s, REPZ_3_10, s->bl_tree); 2979 send_bits(s, count-3, 3); 2980 2981 } else { 2982 send_code(s, REPZ_11_138, s->bl_tree); 2983 send_bits(s, count-11, 7); 2984 } 2985 count = 0; prevlen = curlen; 2986 if (nextlen == 0) { 2987 max_count = 138, min_count = 3; 2988 } else if (curlen == nextlen) { 2989 max_count = 6, min_count = 3; 2990 } else { 2991 max_count = 7, min_count = 4; 2992 } 2993 } 2994 } 2995 2996 /* 2997 * =========================================================================== 2998 * Construct the Huffman tree for the bit lengths and return the index in 2999 * bl_order of the last bit length code to send. 3000 */ 3001 local int 3002 build_bl_tree(s) 3003 deflate_state *s; 3004 { 3005 /* index of last bit length code of non zero freq */ 3006 int max_blindex; 3007 3008 /* 3009 * Determine the bit length frequencies for literal and 3010 * distance trees 3011 */ 3012 scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); 3013 scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); 3014 3015 /* Build the bit length tree: */ 3016 build_tree(s, (tree_desc *)(&(s->bl_desc))); 3017 /* 3018 * opt_len now includes the length of the tree 3019 * representations, except the lengths of the bit lengths 3020 * codes and the 5+5+4 bits for the counts. 3021 */ 3022 3023 /* 3024 * Determine the number of bit length codes to send. The pkzip 3025 * format requires that at least 4 bit length codes be 3026 * sent. (appnote.txt says 3 but the actual value used is 4.) 3027 */ 3028 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { 3029 if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; 3030 } 3031 /* Update opt_len to include the bit length tree and counts */ 3032 s->opt_len += 3*(max_blindex+1) + 5+5+4; 3033 Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", 3034 s->opt_len, s->static_len)); 3035 3036 return (max_blindex); 3037 } 3038 3039 /* 3040 * =========================================================================== 3041 * Send the header for a block using dynamic Huffman trees: the counts, the 3042 * lengths of the bit length codes, the literal tree and the distance tree. 3043 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. 3044 */ 3045 local void 3046 send_all_trees(s, lcodes, dcodes, blcodes) 3047 deflate_state *s; 3048 int lcodes, dcodes, blcodes; /* number of codes for each tree */ 3049 { 3050 int rank; /* index in bl_order */ 3051 3052 Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, 3053 "not enough codes"); 3054 Assert(lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, 3055 "too many codes"); 3056 Tracev((stderr, "\nbl counts: ")); 3057 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ 3058 send_bits(s, dcodes-1, 5); 3059 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ 3060 for (rank = 0; rank < blcodes; rank++) { 3061 Tracev((stderr, "\nbl code %2d ", bl_order[rank])); 3062 send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); 3063 } 3064 #ifdef DEBUG_ZLIB 3065 Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); 3066 #endif 3067 3068 /* literal tree */ 3069 send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); 3070 #ifdef DEBUG_ZLIB 3071 Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); 3072 #endif 3073 3074 /* distance tree */ 3075 send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); 3076 #ifdef DEBUG_ZLIB 3077 Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); 3078 #endif 3079 } 3080 3081 /* 3082 * =========================================================================== 3083 * Send a stored block 3084 */ 3085 void 3086 _tr_stored_block(s, buf, stored_len, eof) 3087 deflate_state *s; 3088 charf *buf; /* input block */ 3089 ulg stored_len; /* length of input block */ 3090 int eof; /* true if this is the last block for a file */ 3091 { 3092 send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ 3093 s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; /* PPP */ 3094 s->compressed_len += (stored_len + 4) << 3; /* PPP */ 3095 3096 copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ 3097 } 3098 3099 /* 3100 * Send just the `stored block' type code without any length bytes or data. 3101 * ---PPP--- 3102 */ 3103 void 3104 _tr_stored_type_only(s) 3105 deflate_state *s; 3106 { 3107 send_bits(s, (STORED_BLOCK << 1), 3); 3108 bi_windup(s); 3109 s->compressed_len = (s->compressed_len + 3) & ~7L; /* PPP */ 3110 } 3111 3112 3113 /* 3114 * =========================================================================== 3115 * Send one empty static block to give enough lookahead for inflate. 3116 * This takes 10 bits, of which 7 may remain in the bit buffer. 3117 * The current inflate code requires 9 bits of lookahead. If the 3118 * last two codes for the previous block (real code plus EOB) were coded 3119 * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode 3120 * the last real code. In this case we send two empty static blocks instead 3121 * of one. (There are no problems if the previous block is stored or fixed.) 3122 * To simplify the code, we assume the worst case of last real code encoded 3123 * on one bit only. 3124 */ 3125 void 3126 _tr_align(s) 3127 deflate_state *s; 3128 { 3129 send_bits(s, STATIC_TREES<<1, 3); 3130 send_code(s, END_BLOCK, static_ltree); 3131 s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ 3132 bi_flush(s); 3133 /* 3134 * Of the 10 bits for the empty block, we have already sent 3135 * (10 - bi_valid) bits. The lookahead for the last real code 3136 * (before the EOB of the previous block) was thus at least 3137 * one plus the length of the EOB plus what we have just sent 3138 * of the empty static block. 3139 */ 3140 if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { 3141 send_bits(s, STATIC_TREES<<1, 3); 3142 send_code(s, END_BLOCK, static_ltree); 3143 s->compressed_len += 10L; 3144 bi_flush(s); 3145 } 3146 s->last_eob_len = 7; 3147 } 3148 3149 /* 3150 * =========================================================================== 3151 * Determine the best encoding for the current block: dynamic trees, static 3152 * trees or store, and output the encoded block to the zip file. 3153 */ 3154 void 3155 _tr_flush_block(s, buf, stored_len, eof) 3156 deflate_state *s; 3157 charf *buf; /* input block, or NULL if too old */ 3158 ulg stored_len; /* length of input block */ 3159 int eof; /* true if this is the last block for a file */ 3160 { 3161 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ 3162 /* index of last bit length code of non zero freq */ 3163 int max_blindex = 0; 3164 3165 /* Build the Huffman trees unless a stored block is forced */ 3166 if (s->level > 0) { 3167 3168 /* Check if the file is ascii or binary */ 3169 if (s->data_type == Z_UNKNOWN) set_data_type(s); 3170 3171 /* Construct the literal and distance trees */ 3172 build_tree(s, (tree_desc *)(&(s->l_desc))); 3173 Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, 3174 s->static_len)); 3175 3176 build_tree(s, (tree_desc *)(&(s->d_desc))); 3177 Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, 3178 s->static_len)); 3179 /* 3180 * At this point, opt_len and static_len are the total 3181 * bit lengths of the compressed block data, excluding 3182 * the tree representations. 3183 */ 3184 3185 /* 3186 * Build the bit length tree for the above two trees, 3187 * and get the index in bl_order of the last bit 3188 * length code to send. 3189 */ 3190 max_blindex = build_bl_tree(s); 3191 3192 /* 3193 * Determine the best encoding. Compute first the 3194 * block length in bytes 3195 */ 3196 opt_lenb = (s->opt_len+3+7)>>3; 3197 static_lenb = (s->static_len+3+7)>>3; 3198 3199 Tracev((stderr, 3200 "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", 3201 opt_lenb, s->opt_len, static_lenb, s->static_len, 3202 stored_len, s->last_lit)); 3203 3204 if (static_lenb <= opt_lenb) opt_lenb = static_lenb; 3205 3206 } else { 3207 Assert(buf != (char *)0, "lost buf"); 3208 /* force a stored block */ 3209 opt_lenb = static_lenb = stored_len + 5; 3210 } 3211 3212 /* 3213 * If compression failed and this is the first and last block, 3214 * and if the .zip file can be seeked (to rewrite the local 3215 * header), the whole file is transformed into a stored file: 3216 */ 3217 #ifdef STORED_FILE_OK 3218 #ifdef FORCE_STORED_FILE 3219 #define FRC_STR_COND eof && s->compressed_len == 0L /* force stored file */ 3220 #else 3221 #define FRC_STR_COND stored_len <= opt_lenb && eof && \ 3222 s->compressed_len == 0L && seekable() 3223 #endif 3224 if (FRC_STR_COND) { 3225 #undef FRC_STR_COND 3226 /* 3227 * Since LIT_BUFSIZE <= 2*WSIZE, the input data must 3228 * be there: 3229 */ 3230 if (buf == (charf*)0) error("block vanished"); 3231 3232 /* without header */ 3233 copy_block(s, buf, (unsigned)stored_len, 0); 3234 s->compressed_len = stored_len << 3; 3235 s->method = STORED; 3236 } else 3237 #endif /* STORED_FILE_OK */ 3238 3239 #ifdef FORCE_STORED 3240 #define FRC_STR_COND buf != (char *)0 /* force stored block */ 3241 #else 3242 /* 4: two words for the lengths */ 3243 #define FRC_STR_COND stored_len+4 <= opt_lenb && buf != (char *)0 3244 #endif 3245 if (FRC_STR_COND) { 3246 #undef FRC_STR_COND 3247 /* 3248 * The test buf != NULL is only necessary if 3249 * LIT_BUFSIZE > WSIZE. Otherwise we can't 3250 * have processed more than WSIZE input bytes 3251 * since the last block flush, because 3252 * compression would have been successful. If 3253 * LIT_BUFSIZE <= WSIZE, it is never too late 3254 * to transform a block into a stored block. 3255 */ 3256 _tr_stored_block(s, buf, stored_len, eof); 3257 #ifdef FORCE_STATIC 3258 #define FRC_STAT_COND static_lenb >= 0 /* force static trees */ 3259 #else 3260 #define FRC_STAT_COND static_lenb == opt_lenb 3261 #endif 3262 } else if (FRC_STAT_COND) { 3263 #undef FRC_STAT_COND 3264 send_bits(s, (STATIC_TREES<<1)+eof, 3); 3265 compress_block(s, (ct_data *)static_ltree, 3266 (ct_data *)static_dtree); 3267 s->compressed_len += 3 + s->static_len; /* PPP */ 3268 } else { 3269 send_bits(s, (DYN_TREES<<1)+eof, 3); 3270 send_all_trees(s, s->l_desc.max_code+1, 3271 s->d_desc.max_code+1, 3272 max_blindex+1); 3273 compress_block(s, (ct_data *)s->dyn_ltree, 3274 (ct_data *)s->dyn_dtree); 3275 s->compressed_len += 3 + s->opt_len; /* PPP */ 3276 } 3277 #ifdef DEBUG_ZLIB 3278 Assert(s->compressed_len == s->bits_sent, "bad compressed size"); 3279 #endif 3280 /* 3281 * The above check is made mod 2^32, for files larger than 512 3282 * MB and uLong implemented on 32 bits. 3283 */ 3284 init_block(s); 3285 3286 if (eof) { 3287 bi_windup(s); 3288 s->compressed_len += 7; /* align on byte boundary PPP */ 3289 } 3290 Tracev((stderr, "\ncomprlen %lu(%lu) ", s->compressed_len>>3, 3291 s->compressed_len-7*eof)); 3292 3293 /* return (s->compressed_len >> 3); */ 3294 } 3295 3296 /* 3297 * =========================================================================== 3298 * Save the match info and tally the frequency counts. Return true if 3299 * the current block must be flushed. 3300 */ 3301 int 3302 _tr_tally(s, dist, lc) 3303 deflate_state *s; 3304 unsigned dist; /* distance of matched string */ 3305 /* match length-MIN_MATCH or unmatched char (if dist==0) */ 3306 unsigned lc; 3307 { 3308 s->d_buf[s->last_lit] = (ush)dist; 3309 s->l_buf[s->last_lit++] = (uch)lc; 3310 if (dist == 0) { 3311 /* lc is the unmatched char */ 3312 s->dyn_ltree[lc].Freq++; 3313 } else { 3314 s->matches++; 3315 /* Here, lc is the match length - MIN_MATCH */ 3316 dist--; /* dist = match distance - 1 */ 3317 Assert((ush)dist < (ush)MAX_DIST(s) && 3318 (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && 3319 (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); 3320 3321 s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; 3322 s->dyn_dtree[d_code(dist)].Freq++; 3323 } 3324 3325 #ifdef TRUNCATE_BLOCK 3326 /* Try to guess if it is profitable to stop the current block here */ 3327 if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { 3328 /* Compute an upper bound for the compressed length */ 3329 ulg out_length = (ulg)s->last_lit*8L; 3330 ulg in_length = (ulg)((long)s->strstart - s->block_start); 3331 int dcode; 3332 for (dcode = 0; dcode < D_CODES; dcode++) { 3333 out_length += (ulg)s->dyn_dtree[dcode].Freq * 3334 (5L+extra_dbits[dcode]); 3335 } 3336 out_length >>= 3; 3337 Tracev((stderr, "\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", 3338 s->last_lit, in_length, out_length, 3339 100L - out_length*100L/in_length)); 3340 if (s->matches < s->last_lit/2 && out_length < in_length/2) 3341 return (1); 3342 } 3343 #endif 3344 return (s->last_lit == s->lit_bufsize-1); 3345 /* 3346 * We avoid equality with lit_bufsize because of wraparound at 64K 3347 * on 16 bit machines and because stored blocks are restricted to 3348 * 64K-1 bytes. 3349 */ 3350 } 3351 3352 /* 3353 * =========================================================================== 3354 * Send the block data compressed using the given Huffman trees 3355 */ 3356 local void 3357 compress_block(s, ltree, dtree) 3358 deflate_state *s; 3359 ct_data *ltree; /* literal tree */ 3360 ct_data *dtree; /* distance tree */ 3361 { 3362 unsigned dist; /* distance of matched string */ 3363 int lc; /* match length or unmatched char (if dist == 0) */ 3364 unsigned lx = 0; /* running index in l_buf */ 3365 unsigned code; /* the code to send */ 3366 int extra; /* number of extra bits to send */ 3367 3368 if (s->last_lit != 0) do { 3369 dist = s->d_buf[lx]; 3370 lc = s->l_buf[lx++]; 3371 if (dist == 0) { 3372 /* send a literal byte */ 3373 send_code(s, lc, ltree); 3374 Tracecv(isgraph(lc), (stderr, " '%c' ", lc)); 3375 } else { 3376 /* Here, lc is the match length - MIN_MATCH */ 3377 code = _length_code[lc]; 3378 /* send the length code */ 3379 send_code(s, code+LITERALS+1, ltree); 3380 extra = extra_lbits[code]; 3381 if (extra != 0) { 3382 lc -= base_length[code]; 3383 /* send the extra length bits */ 3384 send_bits(s, lc, extra); 3385 } 3386 /* dist is now the match distance - 1 */ 3387 dist--; 3388 code = d_code(dist); 3389 Assert(code < D_CODES, "bad d_code"); 3390 3391 /* send the distance code */ 3392 send_code(s, code, dtree); 3393 extra = extra_dbits[code]; 3394 if (extra != 0) { 3395 dist -= base_dist[code]; 3396 /* send the extra distance bits */ 3397 send_bits(s, dist, extra); 3398 } 3399 } /* literal or match pair ? */ 3400 3401 /* 3402 * Check that the overlay between pending_buf and 3403 * d_buf+l_buf is ok: 3404 */ 3405 Assert(s->pending < s->lit_bufsize + 2*lx, 3406 "pendingBuf overflow"); 3407 3408 } while (lx < s->last_lit); 3409 3410 send_code(s, END_BLOCK, ltree); 3411 s->last_eob_len = ltree[END_BLOCK].Len; 3412 } 3413 3414 /* 3415 * =========================================================================== 3416 * Set the data type to ASCII or BINARY, using a crude approximation: 3417 * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. 3418 * IN assertion: the fields freq of dyn_ltree are set and the total of all 3419 * frequencies does not exceed 64K (to fit in an int on 16 bit machines). 3420 */ 3421 local void 3422 set_data_type(s) 3423 deflate_state *s; 3424 { 3425 int n = 0; 3426 unsigned ascii_freq = 0; 3427 unsigned bin_freq = 0; 3428 while (n < 7) bin_freq += s->dyn_ltree[n++].Freq; 3429 while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq; 3430 while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq; 3431 s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? 3432 Z_BINARY : Z_ASCII); 3433 } 3434 3435 /* 3436 * =========================================================================== 3437 * Reverse the first len bits of a code, using straightforward code (a faster 3438 * method would use a table) 3439 * IN assertion: 1 <= len <= 15 3440 */ 3441 local unsigned 3442 bi_reverse(code, len) 3443 unsigned code; /* the value to invert */ 3444 int len; /* its bit length */ 3445 { 3446 register unsigned res = 0; 3447 do { 3448 res |= code & 1; 3449 code >>= 1, res <<= 1; 3450 } while (--len > 0); 3451 return (res >> 1); 3452 } 3453 3454 /* 3455 * =========================================================================== 3456 * Flush the bit buffer, keeping at most 7 bits in it. 3457 */ 3458 local void 3459 bi_flush(s) 3460 deflate_state *s; 3461 { 3462 if (s->bi_valid == 16) { 3463 put_short(s, s->bi_buf); 3464 s->bi_buf = 0; 3465 s->bi_valid = 0; 3466 } else if (s->bi_valid >= 8) { 3467 put_byte(s, (Byte)s->bi_buf); 3468 s->bi_buf >>= 8; 3469 s->bi_valid -= 8; 3470 } 3471 } 3472 3473 /* 3474 * =========================================================================== 3475 * Flush the bit buffer and align the output on a byte boundary 3476 */ 3477 local void 3478 bi_windup(s) 3479 deflate_state *s; 3480 { 3481 if (s->bi_valid > 8) { 3482 put_short(s, s->bi_buf); 3483 } else if (s->bi_valid > 0) { 3484 put_byte(s, (Byte)s->bi_buf); 3485 } 3486 s->bi_buf = 0; 3487 s->bi_valid = 0; 3488 #ifdef DEBUG_ZLIB 3489 s->bits_sent = (s->bits_sent+7) & ~7; 3490 #endif 3491 } 3492 3493 /* 3494 * =========================================================================== 3495 * Copy a stored block, storing first the length and its 3496 * one's complement if requested. 3497 */ 3498 local void 3499 copy_block(s, buf, len, header) 3500 deflate_state *s; 3501 charf *buf; /* the input data */ 3502 unsigned len; /* its length */ 3503 int header; /* true if block header must be written */ 3504 { 3505 bi_windup(s); /* align on byte boundary */ 3506 s->last_eob_len = 8; /* enough lookahead for inflate */ 3507 3508 if (header) { 3509 put_short(s, (ush)len); 3510 put_short(s, (ush)~len); 3511 #ifdef DEBUG_ZLIB 3512 s->bits_sent += 2*16; 3513 #endif 3514 } 3515 #ifdef DEBUG_ZLIB 3516 s->bits_sent += (ulg)len<<3; 3517 #endif 3518 /* bundle up the put_byte(s, *buf++) calls PPP */ 3519 Assert(s->pending + len < s->pending_buf_size, "pending_buf overrun"); 3520 zmemcpy(&s->pending_buf[s->pending], buf, len); /* PPP */ 3521 s->pending += len; /* PPP */ 3522 } 3523 /* --- trees.c */ 3524 3525 /* +++ inflate.c */ 3526 /* 3527 * inflate.c -- zlib interface to inflate modules 3528 * Copyright (C) 1995-1998 Mark Adler 3529 * For conditions of distribution and use, see copyright notice in zlib.h 3530 */ 3531 3532 /* #include "zutil.h" */ 3533 3534 /* +++ infblock.h */ 3535 /* 3536 * infblock.h -- header to use infblock.c 3537 * Copyright (C) 1995-1998 Mark Adler 3538 * For conditions of distribution and use, see copyright notice in zlib.h 3539 */ 3540 3541 /* 3542 * WARNING: this file should *not* be used by applications. It is part 3543 * of the implementation of the compression library and is subject to 3544 * change. Applications should only use zlib.h. 3545 */ 3546 3547 struct inflate_blocks_state; 3548 typedef struct inflate_blocks_state FAR inflate_blocks_statef; 3549 3550 extern inflate_blocks_statef * inflate_blocks_new OF(( 3551 z_streamp z, 3552 check_func c, /* check function */ 3553 uInt w)); /* window size */ 3554 3555 extern int inflate_blocks OF(( 3556 inflate_blocks_statef *, 3557 z_streamp, 3558 int)); /* initial return code */ 3559 3560 extern void inflate_blocks_reset OF(( 3561 inflate_blocks_statef *, 3562 z_streamp, 3563 uLongf *)); /* check value on output */ 3564 3565 extern int inflate_blocks_free OF(( 3566 inflate_blocks_statef *, 3567 z_streamp)); 3568 3569 extern void inflate_set_dictionary OF(( 3570 inflate_blocks_statef *s, 3571 const Bytef *d, /* dictionary */ 3572 uInt n)); /* dictionary length */ 3573 3574 extern int inflate_blocks_sync_point OF(( 3575 inflate_blocks_statef *s)); 3576 3577 /* PPP -- added function */ 3578 extern int inflate_addhistory OF(( 3579 inflate_blocks_statef *, 3580 z_streamp)); 3581 3582 /* PPP -- added function */ 3583 extern int inflate_packet_flush OF(( 3584 inflate_blocks_statef *)); 3585 /* --- infblock.h */ 3586 3587 #ifndef NO_DUMMY_DECL 3588 struct inflate_blocks_state {int dummy; }; /* for buggy compilers */ 3589 #endif 3590 3591 /* inflate private state */ 3592 struct internal_state { 3593 3594 /* mode */ 3595 enum { 3596 METHOD, /* waiting for method byte */ 3597 FLAG, /* waiting for flag byte */ 3598 DICT4, /* four dictionary check bytes to go */ 3599 DICT3, /* three dictionary check bytes to go */ 3600 DICT2, /* two dictionary check bytes to go */ 3601 DICT1, /* one dictionary check byte to go */ 3602 DICT0, /* waiting for inflateSetDictionary */ 3603 BLOCKS, /* decompressing blocks */ 3604 CHECK4, /* four check bytes to go */ 3605 CHECK3, /* three check bytes to go */ 3606 CHECK2, /* two check bytes to go */ 3607 CHECK1, /* one check byte to go */ 3608 DONE, /* finished check, done */ 3609 BAD} /* got an error--stay here */ 3610 mode; /* current inflate mode */ 3611 3612 /* mode dependent information */ 3613 union { 3614 uInt method; /* if FLAGS, method byte */ 3615 struct { 3616 uLong was; /* computed check value */ 3617 uLong need; /* stream check value */ 3618 } check; /* if CHECK, check values to compare */ 3619 uInt marker; /* if BAD, inflateSync's marker bytes count */ 3620 } sub; /* submode */ 3621 3622 /* mode independent information */ 3623 int nowrap; /* flag for no wrapper */ 3624 uInt wbits; /* log2(window size) (8..15, defaults to 15) */ 3625 /* current inflate_blocks state */ 3626 inflate_blocks_statef *blocks; 3627 }; 3628 3629 3630 int 3631 inflateReset(z) 3632 z_streamp z; 3633 { 3634 if (z == Z_NULL || z->state == Z_NULL) 3635 return (Z_STREAM_ERROR); 3636 z->total_in = z->total_out = 0; 3637 z->msg = Z_NULL; 3638 z->state->mode = z->state->nowrap ? BLOCKS : METHOD; 3639 inflate_blocks_reset(z->state->blocks, z, Z_NULL); 3640 Trace((stderr, "inflate: reset\n")); 3641 return (Z_OK); 3642 } 3643 3644 3645 int 3646 inflateEnd(z) 3647 z_streamp z; 3648 { 3649 if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL) 3650 return (Z_STREAM_ERROR); 3651 if (z->state->blocks != Z_NULL) { 3652 (void) inflate_blocks_free(z->state->blocks, z); 3653 z->state->blocks = Z_NULL; 3654 } 3655 ZFREE(z, z->state); 3656 z->state = Z_NULL; 3657 Trace((stderr, "inflate: end\n")); 3658 return (Z_OK); 3659 } 3660 3661 3662 int 3663 inflateInit2_(z, w, version, stream_size) 3664 z_streamp z; 3665 int w; 3666 const char *version; 3667 int stream_size; 3668 { 3669 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || 3670 stream_size != sizeof (z_stream)) 3671 return (Z_VERSION_ERROR); 3672 3673 /* initialize state */ 3674 if (z == Z_NULL) 3675 return (Z_STREAM_ERROR); 3676 z->msg = Z_NULL; 3677 #ifndef NO_ZCFUNCS 3678 if (z->zalloc == Z_NULL) 3679 { 3680 z->zalloc = zcalloc; 3681 z->opaque = (voidpf)0; 3682 } 3683 if (z->zfree == Z_NULL) z->zfree = zcfree; 3684 #endif 3685 if ((z->state = (struct internal_state FAR *) 3686 ZALLOC(z, 1, sizeof (struct internal_state))) == Z_NULL) 3687 return (Z_MEM_ERROR); 3688 z->state->blocks = Z_NULL; 3689 3690 /* handle undocumented nowrap option (no zlib header or check) */ 3691 z->state->nowrap = 0; 3692 if (w < 0) 3693 { 3694 w = - w; 3695 z->state->nowrap = 1; 3696 } 3697 3698 /* set window size */ 3699 if (w < 8 || w > 15) 3700 { 3701 (void) inflateEnd(z); 3702 return (Z_STREAM_ERROR); 3703 } 3704 z->state->wbits = (uInt)w; 3705 3706 /* create inflate_blocks state */ 3707 if ((z->state->blocks = 3708 inflate_blocks_new(z, z->state->nowrap ? 3709 Z_NULL : adler32, (uInt)1 << w)) 3710 == Z_NULL) 3711 { 3712 (void) inflateEnd(z); 3713 return (Z_MEM_ERROR); 3714 } 3715 Trace((stderr, "inflate: allocated\n")); 3716 3717 /* reset state */ 3718 (void) inflateReset(z); 3719 return (Z_OK); 3720 } 3721 3722 3723 int 3724 inflateInit_(z, version, stream_size) 3725 z_streamp z; 3726 const char *version; 3727 int stream_size; 3728 { 3729 return (inflateInit2_(z, DEF_WBITS, version, stream_size)); 3730 } 3731 3732 /* PPP -- added "empty" label and changed f to Z_OK */ 3733 #define NEEDBYTE {if (z->avail_in == 0) goto empty; r = Z_OK; } ((void)0) 3734 #define NEXTBYTE (z->avail_in--, z->total_in++, *z->next_in++) 3735 3736 int 3737 inflate(z, f) 3738 z_streamp z; 3739 int f; 3740 { 3741 int r; 3742 uInt b; 3743 3744 if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL) 3745 return (Z_STREAM_ERROR); 3746 /* f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; -- PPP; Z_FINISH unused */ 3747 r = Z_BUF_ERROR; 3748 /* CONSTCOND */ 3749 while (1) 3750 switch (z->state->mode) 3751 { 3752 case METHOD: 3753 NEEDBYTE; 3754 if (((z->state->sub.method = NEXTBYTE) & 0xf) != Z_DEFLATED) 3755 { 3756 z->state->mode = BAD; 3757 z->msg = "unknown compression method"; 3758 /* can't try inflateSync */ 3759 z->state->sub.marker = 5; 3760 break; 3761 } 3762 if ((z->state->sub.method >> 4) + 8 > z->state->wbits) 3763 { 3764 z->state->mode = BAD; 3765 z->msg = "invalid window size"; 3766 /* can't try inflateSync */ 3767 z->state->sub.marker = 5; 3768 break; 3769 } 3770 z->state->mode = FLAG; 3771 /* FALLTHRU */ 3772 case FLAG: 3773 NEEDBYTE; 3774 b = NEXTBYTE; 3775 if (((z->state->sub.method << 8) + b) % 31) 3776 { 3777 z->state->mode = BAD; 3778 z->msg = "incorrect header check"; 3779 /* can't try inflateSync */ 3780 z->state->sub.marker = 5; 3781 break; 3782 } 3783 Trace((stderr, "inflate: zlib header ok\n")); 3784 if (!(b & PRESET_DICT)) 3785 { 3786 z->state->mode = BLOCKS; 3787 break; 3788 } 3789 z->state->mode = DICT4; 3790 /* FALLTHRU */ 3791 case DICT4: 3792 NEEDBYTE; 3793 z->state->sub.check.need = (uLong)NEXTBYTE << 24; 3794 z->state->mode = DICT3; 3795 /* FALLTHRU */ 3796 case DICT3: 3797 NEEDBYTE; 3798 z->state->sub.check.need += (uLong)NEXTBYTE << 16; 3799 z->state->mode = DICT2; 3800 /* FALLTHRU */ 3801 case DICT2: 3802 NEEDBYTE; 3803 z->state->sub.check.need += (uLong)NEXTBYTE << 8; 3804 z->state->mode = DICT1; 3805 /* FALLTHRU */ 3806 case DICT1: 3807 NEEDBYTE; 3808 z->state->sub.check.need += (uLong)NEXTBYTE; 3809 z->adler = z->state->sub.check.need; 3810 z->state->mode = DICT0; 3811 return (Z_NEED_DICT); 3812 case DICT0: 3813 z->state->mode = BAD; 3814 z->msg = "need dictionary"; 3815 z->state->sub.marker = 0; /* can try inflateSync */ 3816 return (Z_STREAM_ERROR); 3817 case BLOCKS: 3818 r = inflate_blocks(z->state->blocks, z, r); 3819 if (f == Z_PACKET_FLUSH && z->avail_in == 0 && /* PPP */ 3820 z->avail_out != 0) /* PPP */ 3821 r = inflate_packet_flush(z->state->blocks); /* PPP */ 3822 if (r == Z_DATA_ERROR) 3823 { 3824 z->state->mode = BAD; 3825 /* can try inflateSync */ 3826 z->state->sub.marker = 0; 3827 break; 3828 } 3829 /* PPP */ 3830 if (r != Z_STREAM_END) 3831 return (r); 3832 r = Z_OK; /* PPP */ 3833 inflate_blocks_reset(z->state->blocks, z, 3834 &z->state->sub.check.was); 3835 if (z->state->nowrap) 3836 { 3837 z->state->mode = DONE; 3838 break; 3839 } 3840 z->state->mode = CHECK4; 3841 /* FALLTHRU */ 3842 case CHECK4: 3843 NEEDBYTE; 3844 z->state->sub.check.need = (uLong)NEXTBYTE << 24; 3845 z->state->mode = CHECK3; 3846 /* FALLTHRU */ 3847 case CHECK3: 3848 NEEDBYTE; 3849 z->state->sub.check.need += (uLong)NEXTBYTE << 16; 3850 z->state->mode = CHECK2; 3851 /* FALLTHRU */ 3852 case CHECK2: 3853 NEEDBYTE; 3854 z->state->sub.check.need += (uLong)NEXTBYTE << 8; 3855 z->state->mode = CHECK1; 3856 /* FALLTHRU */ 3857 case CHECK1: 3858 NEEDBYTE; 3859 z->state->sub.check.need += (uLong)NEXTBYTE; 3860 3861 if (z->state->sub.check.was != z->state->sub.check.need) 3862 { 3863 z->state->mode = BAD; 3864 z->msg = "incorrect data check"; 3865 /* can't try inflateSync */ 3866 z->state->sub.marker = 5; 3867 break; 3868 } 3869 Trace((stderr, "inflate: zlib check ok\n")); 3870 z->state->mode = DONE; 3871 /* FALLTHRU */ 3872 case DONE: 3873 return (Z_STREAM_END); 3874 case BAD: 3875 return (Z_DATA_ERROR); 3876 default: 3877 return (Z_STREAM_ERROR); 3878 } 3879 3880 /* PPP -- packet flush handling */ 3881 empty: 3882 if (f != Z_PACKET_FLUSH) 3883 return (r); 3884 z->state->mode = BAD; 3885 z->msg = "need more for packet flush"; 3886 z->state->sub.marker = 0; /* can try inflateSync */ 3887 return (Z_DATA_ERROR); 3888 } 3889 3890 3891 int 3892 inflateSetDictionary(z, dictionary, dictLength) 3893 z_streamp z; 3894 const Bytef *dictionary; 3895 uInt dictLength; 3896 { 3897 uInt length = dictLength; 3898 3899 if (z == Z_NULL || z->state == Z_NULL || z->state->mode != DICT0) 3900 return (Z_STREAM_ERROR); 3901 3902 if (adler32(1L, dictionary, dictLength) != z->adler) 3903 return (Z_DATA_ERROR); 3904 z->adler = 1L; 3905 3906 if (length >= ((uInt)1<<z->state->wbits)) 3907 { 3908 length = (1<<z->state->wbits)-1; 3909 dictionary += dictLength - length; 3910 } 3911 inflate_set_dictionary(z->state->blocks, dictionary, length); 3912 z->state->mode = BLOCKS; 3913 return (Z_OK); 3914 } 3915 3916 /* 3917 * This subroutine adds the data at next_in/avail_in to the output history 3918 * without performing any output. The output buffer must be "caught up"; 3919 * i.e. no pending output (hence s->read equals s->write), and the state must 3920 * be BLOCKS (i.e. we should be willing to see the start of a series of 3921 * BLOCKS). On exit, the output will also be caught up, and the checksum 3922 * will have been updated if need be. 3923 * 3924 * Added for PPP. 3925 */ 3926 3927 int 3928 inflateIncomp(z) 3929 z_stream *z; 3930 { 3931 if (z->state->mode != BLOCKS) 3932 return (Z_DATA_ERROR); 3933 return (inflate_addhistory(z->state->blocks, z)); 3934 } 3935 3936 3937 int 3938 inflateSync(z) 3939 z_streamp z; 3940 { 3941 uInt n; /* number of bytes to look at */ 3942 Bytef *p; /* pointer to bytes */ 3943 uInt m; /* number of marker bytes found in a row */ 3944 uLong r, w; /* temporaries to save total_in and total_out */ 3945 3946 /* set up */ 3947 if (z == Z_NULL || z->state == Z_NULL) 3948 return (Z_STREAM_ERROR); 3949 if (z->state->mode != BAD) 3950 { 3951 z->state->mode = BAD; 3952 z->state->sub.marker = 0; 3953 } 3954 if ((n = z->avail_in) == 0) 3955 return (Z_BUF_ERROR); 3956 p = z->next_in; 3957 m = z->state->sub.marker; 3958 3959 /* search */ 3960 while (n && m < 4) 3961 { 3962 static const Byte mark[4] = { 0, 0, 0xff, 0xff }; 3963 if (*p == mark[m]) 3964 m++; 3965 else if (*p) 3966 m = 0; 3967 else 3968 /* 3969 * This statement maps 2->2 and 3->1 because a 3970 * mismatch with input byte 0x00 on the first 3971 * 0xFF in the pattern means that we still 3972 * have two contiguous zeros matched (thus 3973 * offset 2 is kept), but a mismatch on the 3974 * second 0xFF means that only one 0x00 byte 3975 * has been matched. (Boyer-Moore like 3976 * search.) 3977 */ 3978 m = 4 - m; 3979 p++, n--; 3980 } 3981 3982 /* restore */ 3983 z->total_in += p - z->next_in; 3984 z->next_in = p; 3985 z->avail_in = n; 3986 z->state->sub.marker = m; 3987 3988 /* return no joy or set up to restart on a new block */ 3989 if (m != 4) 3990 return (Z_DATA_ERROR); 3991 r = z->total_in; w = z->total_out; 3992 (void) inflateReset(z); 3993 z->total_in = r; z->total_out = w; 3994 z->state->mode = BLOCKS; 3995 return (Z_OK); 3996 } 3997 3998 /* 3999 * Returns true if inflate is currently at the end of a block 4000 * generated by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by 4001 * one PPP implementation to provide an additional safety check. PPP 4002 * uses Z_SYNC_FLUSH but removes the length bytes of the resulting 4003 * empty stored block. When decompressing, PPP checks that at the end 4004 * of input packet, inflate is waiting for these length bytes. 4005 */ 4006 int 4007 inflateSyncPoint(z) 4008 z_streamp z; 4009 { 4010 if (z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL) 4011 return (Z_STREAM_ERROR); 4012 return (inflate_blocks_sync_point(z->state->blocks)); 4013 } 4014 4015 #undef NEEDBYTE 4016 #undef NEXTBYTE 4017 /* --- inflate.c */ 4018 4019 /* +++ infblock.c */ 4020 /* 4021 * infblock.c -- interpret and process block types to last block 4022 * Copyright (C) 1995-1998 Mark Adler 4023 * For conditions of distribution and use, see copyright notice in zlib.h 4024 */ 4025 4026 /* #include "zutil.h" */ 4027 /* #include "infblock.h" */ 4028 4029 /* +++ inftrees.h */ 4030 /* 4031 * inftrees.h -- header to use inftrees.c 4032 * Copyright (C) 1995-1998 Mark Adler 4033 * For conditions of distribution and use, see copyright notice in zlib.h 4034 */ 4035 4036 /* 4037 * WARNING: this file should *not* be used by applications. It is part 4038 * of the implementation of the compression library and is subject to 4039 * change. Applications should only use zlib.h. 4040 */ 4041 4042 /* 4043 * Huffman code lookup table entry--this entry is four bytes for 4044 * machines that have 16-bit pointers (e.g. PC's in the small or 4045 * medium model). 4046 */ 4047 4048 typedef struct inflate_huft_s FAR inflate_huft; 4049 4050 struct inflate_huft_s { 4051 union { 4052 struct { 4053 Byte Exop; /* number of extra bits or operation */ 4054 /* number of bits in this code or subcode */ 4055 Byte Bits; 4056 } what; 4057 Bytef *pad; /* pad structure to a power of 2 (4 bytes for */ 4058 } word; /* 16-bit, 8 bytes for 32-bit machines) */ 4059 /* literal, length base, distance base, or table offset */ 4060 uInt base; 4061 }; 4062 4063 /* 4064 * Maximum size of dynamic tree. The maximum found in a long but non- 4065 * exhaustive search was 1004 huft structures (850 for length/literals 4066 * and 154 for distances, the latter actually the result of an 4067 * exhaustive search). The actual maximum is not known, but the value 4068 * below is more than safe. 4069 */ 4070 #define MANY 1440 4071 4072 extern int inflate_trees_bits OF(( 4073 uIntf *, /* 19 code lengths */ 4074 uIntf *, /* bits tree desired/actual depth */ 4075 inflate_huft * FAR *, /* bits tree result */ 4076 inflate_huft *, /* space for trees */ 4077 z_streamp)); /* for zalloc, zfree functions */ 4078 4079 extern int inflate_trees_dynamic OF(( 4080 uInt, /* number of literal/length codes */ 4081 uInt, /* number of distance codes */ 4082 uIntf *, /* that many (total) code lengths */ 4083 uIntf *, /* literal desired/actual bit depth */ 4084 uIntf *, /* distance desired/actual bit depth */ 4085 inflate_huft * FAR *, /* literal/length tree result */ 4086 inflate_huft * FAR *, /* distance tree result */ 4087 inflate_huft *, /* space for trees */ 4088 z_streamp)); /* for zalloc, zfree functions */ 4089 4090 extern int inflate_trees_fixed OF(( 4091 uIntf *, /* literal desired/actual bit depth */ 4092 uIntf *, /* distance desired/actual bit depth */ 4093 const inflate_huft * FAR *, /* literal/length tree result */ 4094 const inflate_huft * FAR *, /* distance tree result */ 4095 z_streamp)); 4096 4097 /* --- inftrees.h */ 4098 4099 /* +++ infcodes.h */ 4100 /* 4101 * infcodes.h -- header to use infcodes.c 4102 * Copyright (C) 1995-1998 Mark Adler 4103 * For conditions of distribution and use, see copyright notice in zlib.h 4104 */ 4105 4106 /* 4107 * WARNING: this file should *not* be used by applications. It is part 4108 * of the implementation of the compression library and is subject to 4109 * change. Applications should only use zlib.h. 4110 */ 4111 4112 struct inflate_codes_state; 4113 typedef struct inflate_codes_state FAR inflate_codes_statef; 4114 4115 extern inflate_codes_statef *inflate_codes_new OF(( 4116 uInt, uInt, 4117 const inflate_huft *, const inflate_huft *, 4118 z_streamp)); 4119 4120 extern int inflate_codes OF(( 4121 inflate_blocks_statef *, 4122 z_streamp, 4123 int)); 4124 4125 extern void inflate_codes_free OF(( 4126 inflate_codes_statef *, 4127 z_streamp)); 4128 4129 /* --- infcodes.h */ 4130 4131 /* +++ infutil.h */ 4132 /* 4133 * infutil.h -- types and macros common to blocks and codes 4134 * Copyright (C) 1995-1998 Mark Adler 4135 * For conditions of distribution and use, see copyright notice in zlib.h 4136 */ 4137 4138 /* 4139 * WARNING: this file should *not* be used by applications. It is part 4140 * of the implementation of the compression library and is subject to 4141 * change. Applications should only use zlib.h. 4142 */ 4143 4144 #ifndef _INFUTIL_H 4145 #define _INFUTIL_H 4146 4147 typedef enum { 4148 TYPE, /* get type bits (3, including end bit) */ 4149 LENS, /* get lengths for stored */ 4150 STORED, /* processing stored block */ 4151 TABLE, /* get table lengths */ 4152 BTREE, /* get bit lengths tree for a dynamic block */ 4153 DTREE, /* get length, distance trees for a dynamic block */ 4154 CODES, /* processing fixed or dynamic block */ 4155 DRY, /* output remaining window bytes */ 4156 DONEB, /* finished last block, done */ 4157 BADB} /* got a data error--stuck here */ 4158 inflate_block_mode; 4159 4160 /* inflate blocks semi-private state */ 4161 struct inflate_blocks_state { 4162 4163 /* mode */ 4164 inflate_block_mode mode; /* current inflate_block mode */ 4165 4166 /* mode dependent information */ 4167 union { 4168 uInt left; /* if STORED, bytes left to copy */ 4169 struct { 4170 uInt table; /* table lengths (14 bits) */ 4171 uInt index; /* index into blens (or border) */ 4172 uIntf *blens; /* bit lengths of codes */ 4173 uInt bb; /* bit length tree depth */ 4174 inflate_huft *tb; /* bit length decoding tree */ 4175 } trees; /* if DTREE, decoding info for trees */ 4176 struct { 4177 inflate_codes_statef *codes; 4178 } decode; /* if CODES, current state */ 4179 } sub; /* submode */ 4180 uInt last; /* true if this block is the last block */ 4181 4182 /* mode independent information */ 4183 uInt bitk; /* bits in bit buffer */ 4184 uLong bitb; /* bit buffer */ 4185 inflate_huft *hufts; /* single malloc for tree space */ 4186 Bytef *window; /* sliding window */ 4187 Bytef *end; /* one byte after sliding window */ 4188 Bytef *read; /* window read pointer */ 4189 Bytef *write; /* window write pointer */ 4190 check_func checkfn; /* check function */ 4191 uLong check; /* check on output */ 4192 4193 }; 4194 4195 4196 /* defines for inflate input/output */ 4197 /* update pointers and return */ 4198 #define UPDBITS {s->bitb = b; s->bitk = k; } 4199 #define UPDIN {z->avail_in = n; z->total_in += p-z->next_in; z->next_in = p; } 4200 #define UPDOUT {s->write = q; } 4201 #define UPDATE {UPDBITS UPDIN UPDOUT} 4202 #define LEAVE {UPDATE return (inflate_flush(s, z, r)); } 4203 /* get bytes and bits */ 4204 #define LOADIN {p = z->next_in; n = z->avail_in; b = s->bitb; k = s->bitk; } 4205 #define NEEDBYTE { if (n) r = Z_OK; else LEAVE } 4206 #define NEXTBYTE (n--, *p++) 4207 #define NEEDBITS(j) { while (k < (j)) { NEEDBYTE; b |= ((uLong)NEXTBYTE)<<k; \ 4208 k += 8; }} 4209 #define DUMPBITS(j) {b >>= (j); k -= (j); } 4210 /* output bytes */ 4211 #define WAVAIL (uInt)(q < s->read ? s->read-q-1 : s->end-q) 4212 #define LOADOUT {q = s->write; m = (uInt)WAVAIL; } 4213 #define WWRAP {if (q == s->end && s->read != s->window) {q = s->window; \ 4214 m = (uInt)WAVAIL; }} 4215 #define FLUSH {UPDOUT r = inflate_flush(s, z, r); LOADOUT} 4216 #define NEEDOUT {if (m == 0) {WWRAP if (m == 0) { FLUSH WWRAP \ 4217 if (m == 0) LEAVE }} r = Z_OK; } 4218 #define OUTBYTE(a) {*q++ = (Byte)(a); m--; } 4219 /* load local pointers */ 4220 #define LOAD {LOADIN LOADOUT} 4221 4222 /* masks for lower bits (size given to avoid silly warnings with Visual C++) */ 4223 extern uInt inflate_mask[17]; 4224 4225 /* copy as much as possible from the sliding window to the output area */ 4226 extern int inflate_flush OF(( 4227 inflate_blocks_statef *, 4228 z_streamp, 4229 int)); 4230 4231 #ifndef NO_DUMMY_DECL 4232 struct internal_state {int dummy; }; /* for buggy compilers */ 4233 #endif 4234 4235 #endif 4236 /* --- infutil.h */ 4237 4238 #ifndef NO_DUMMY_DECL 4239 struct inflate_codes_state {int dummy; }; /* for buggy compilers */ 4240 #endif 4241 4242 /* Table for deflate from PKZIP's appnote.txt. */ 4243 local const uInt border[] = { /* Order of the bit length code lengths */ 4244 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; 4245 4246 /* 4247 * Notes beyond the 1.93a appnote.txt: 4248 * 4249 * 1. Distance pointers never point before the beginning of the output 4250 * stream. 4251 * 2. Distance pointers can point back across blocks, up to 32k away. 4252 * 3. There is an implied maximum of 7 bits for the bit length table and 4253 * 15 bits for the actual data. 4254 * 4. If only one code exists, then it is encoded using one bit. (Zero 4255 * would be more efficient, but perhaps a little confusing.) If two 4256 * codes exist, they are coded using one bit each (0 and 1). 4257 * 5. There is no way of sending zero distance codes--a dummy must be 4258 * sent if there are none. (History: a pre 2.0 version of PKZIP would 4259 * store blocks with no distance codes, but this was discovered to be 4260 * too harsh a criterion.) Valid only for 1.93a. 2.04c does allow 4261 * zero distance codes, which is sent as one code of zero bits in 4262 * length. 4263 * 6. There are up to 286 literal/length codes. Code 256 represents the 4264 * end-of-block. Note however that the static length tree defines 4265 * 288 codes just to fill out the Huffman codes. Codes 286 and 287 4266 * cannot be used though, since there is no length base or extra bits 4267 * defined for them. Similarily, there are up to 30 distance codes. 4268 * However, static trees define 32 codes (all 5 bits) to fill out the 4269 * Huffman codes, but the last two had better not show up in the data. 4270 * 7. Unzip can check dynamic Huffman blocks for complete code sets. 4271 * The exception is that a single code would not be complete (see #4). 4272 * 8. The five bits following the block type is really the number of 4273 * literal codes sent minus 257. 4274 * 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits 4275 * (1+6+6). Therefore, to output three times the length, you output 4276 * three codes (1+1+1), whereas to output four times the same length, 4277 * you only need two codes (1+3). Hmm. 4278 * 10. In the tree reconstruction algorithm, Code = Code + Increment 4279 * only if BitLength(i) is not zero. (Pretty obvious.) 4280 * 11. Correction: 4 Bits: #of Bit Length codes - 4 (4 - 19) 4281 * 12. Note: length code 284 can represent 227-258, but length code 285 4282 * really is 258. The last length deserves its own, short code 4283 * since it gets used a lot in very redundant files. The length 4284 * 258 is special since 258 - 3 (the min match length) is 255. 4285 * 13. The literal/length and distance code bit lengths are read as a 4286 * single stream of lengths. It is possible (and advantageous) for 4287 * a repeat code (16, 17, or 18) to go across the boundary between 4288 * the two sets of lengths. 4289 */ 4290 4291 4292 void 4293 inflate_blocks_reset(s, z, c) 4294 inflate_blocks_statef *s; 4295 z_streamp z; 4296 uLongf *c; 4297 { 4298 if (c != Z_NULL) 4299 *c = s->check; 4300 if ((s->mode == BTREE || s->mode == DTREE) && 4301 s->sub.trees.blens != Z_NULL) { 4302 ZFREE(z, s->sub.trees.blens); 4303 s->sub.trees.blens = Z_NULL; 4304 } 4305 if (s->mode == CODES && s->sub.decode.codes != Z_NULL) { 4306 (void) inflate_codes_free(s->sub.decode.codes, z); 4307 s->sub.decode.codes = Z_NULL; 4308 } 4309 s->mode = TYPE; 4310 s->bitk = 0; 4311 s->bitb = 0; 4312 s->read = s->write = s->window; 4313 if (s->checkfn != Z_NULL) 4314 z->adler = s->check = (*s->checkfn)(0L, Z_NULL, 0); 4315 Trace((stderr, "inflate: blocks reset\n")); 4316 } 4317 4318 inflate_blocks_statef * 4319 inflate_blocks_new(z, c, w) 4320 z_streamp z; 4321 check_func c; 4322 uInt w; 4323 { 4324 inflate_blocks_statef *s; 4325 4326 if ((s = (inflate_blocks_statef *)ZALLOC 4327 (z, 1, sizeof (struct inflate_blocks_state))) == Z_NULL) 4328 return (s); 4329 s->hufts = (inflate_huft *)ZALLOC(z, MANY, sizeof (inflate_huft)); 4330 if (s->hufts == Z_NULL) { 4331 ZFREE(z, s); 4332 return (Z_NULL); 4333 } 4334 if ((s->window = (Bytef *)ZALLOC(z, 1, w)) == Z_NULL) 4335 { 4336 ZFREE(z, s->hufts); 4337 ZFREE(z, s); 4338 return (Z_NULL); 4339 } 4340 s->end = s->window + w; 4341 s->checkfn = c; 4342 s->mode = TYPE; 4343 Trace((stderr, "inflate: blocks allocated\n")); 4344 inflate_blocks_reset(s, z, Z_NULL); 4345 return (s); 4346 } 4347 4348 4349 int 4350 inflate_blocks(s, z, r) 4351 inflate_blocks_statef *s; 4352 z_streamp z; 4353 int r; 4354 { 4355 uInt t; /* temporary storage */ 4356 uLong b; /* bit buffer */ 4357 uInt k; /* bits in bit buffer */ 4358 Bytef *p; /* input data pointer */ 4359 uInt n; /* bytes available there */ 4360 Bytef *q; /* output window write pointer */ 4361 uInt m; /* bytes to end of window or read pointer */ 4362 4363 /* copy input/output information to locals (UPDATE macro restores) */ 4364 LOAD; 4365 4366 /* process input based on current state */ 4367 /* CONSTCOND */ 4368 while (1) 4369 switch (s->mode) 4370 { 4371 case TYPE: 4372 NEEDBITS(3); 4373 t = (uInt)b & 7; 4374 s->last = t & 1; 4375 switch (t >> 1) 4376 { 4377 case 0: /* stored */ 4378 Trace((stderr, "inflate: stored block%s\n", 4379 s->last ? " (last)" : "")); 4380 DUMPBITS(3); 4381 t = k & 7; /* go to byte boundary */ 4382 DUMPBITS(t); 4383 s->mode = LENS; /* get length of stored block */ 4384 break; 4385 case 1: /* fixed */ 4386 Trace((stderr, "inflate: fixed codes block%s\n", 4387 s->last ? " (last)" : "")); 4388 { 4389 uInt bl, bd; 4390 const inflate_huft *tl, *td; 4391 4392 (void) inflate_trees_fixed(&bl, &bd, &tl, &td, 4393 z); 4394 s->sub.decode.codes = inflate_codes_new(bl, 4395 bd, tl, td, z); 4396 if (s->sub.decode.codes == Z_NULL) 4397 { 4398 r = Z_MEM_ERROR; 4399 LEAVE 4400 } 4401 } 4402 DUMPBITS(3); 4403 s->mode = CODES; 4404 break; 4405 case 2: /* dynamic */ 4406 Trace((stderr, "inflate: dynamic codes block%s\n", 4407 s->last ? " (last)" : "")); 4408 DUMPBITS(3); 4409 s->mode = TABLE; 4410 break; 4411 case 3: /* illegal */ 4412 DUMPBITS(3); 4413 s->mode = BADB; 4414 z->msg = "invalid block type"; 4415 r = Z_DATA_ERROR; 4416 LEAVE 4417 } 4418 break; 4419 case LENS: 4420 NEEDBITS(32); 4421 if ((((~b) >> 16) & 0xffff) != (b & 0xffff)) 4422 { 4423 s->mode = BADB; 4424 z->msg = "invalid stored block lengths"; 4425 r = Z_DATA_ERROR; 4426 LEAVE 4427 } 4428 s->sub.left = (uInt)b & 0xffff; 4429 b = k = 0; /* dump bits */ 4430 Tracev((stderr, "inflate: stored length %u\n", 4431 s->sub.left)); 4432 s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE); 4433 break; 4434 case STORED: 4435 if (n == 0) 4436 LEAVE 4437 NEEDOUT; 4438 t = s->sub.left; 4439 if (t > n) t = n; 4440 if (t > m) t = m; 4441 zmemcpy(q, p, t); 4442 p += t; n -= t; 4443 q += t; m -= t; 4444 if ((s->sub.left -= t) != 0) 4445 break; 4446 Tracev((stderr, 4447 "inflate: stored end, %lu total out\n", 4448 z->total_out + (q >= s->read ? q - s->read : 4449 (s->end - s->read) + (q - s->window)))); 4450 s->mode = s->last ? DRY : TYPE; 4451 break; 4452 case TABLE: 4453 NEEDBITS(14); 4454 s->sub.trees.table = t = (uInt)b & 0x3fff; 4455 #ifndef PKZIP_BUG_WORKAROUND 4456 if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) 4457 { 4458 s->mode = BADB; 4459 z->msg = 4460 (char *)"too many length or distance symbols"; 4461 r = Z_DATA_ERROR; 4462 LEAVE 4463 } 4464 #endif 4465 t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); 4466 /* if (t < 19) t = 19; */ 4467 if ((s->sub.trees.blens = (uIntf*)ZALLOC(z, t, 4468 sizeof (uInt))) == Z_NULL) 4469 { 4470 r = Z_MEM_ERROR; 4471 LEAVE 4472 } 4473 DUMPBITS(14); 4474 s->sub.trees.index = 0; 4475 Tracev((stderr, "inflate: table sizes ok\n")); 4476 s->mode = BTREE; 4477 /* FALLTHRU */ 4478 case BTREE: 4479 while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10)) 4480 { 4481 NEEDBITS(3); 4482 s->sub.trees.blens[border[s->sub.trees.index++]] = 4483 (uInt)b & 7; 4484 DUMPBITS(3); 4485 } 4486 while (s->sub.trees.index < 19) 4487 s->sub.trees.blens[border[s->sub.trees.index++]] = 4488 0; 4489 s->sub.trees.bb = 7; 4490 t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb, 4491 &s->sub.trees.tb, s->hufts, z); 4492 if (t != Z_OK) 4493 { 4494 ZFREE(z, s->sub.trees.blens); 4495 s->sub.trees.blens = Z_NULL; 4496 r = t; 4497 if (r == Z_DATA_ERROR) 4498 s->mode = BADB; 4499 LEAVE 4500 } 4501 s->sub.trees.index = 0; 4502 Tracev((stderr, "inflate: bits tree ok\n")); 4503 s->mode = DTREE; 4504 /* FALLTHRU */ 4505 case DTREE: 4506 while (t = s->sub.trees.table, 4507 s->sub.trees.index < 258 + (t & 0x1f) + 4508 ((t >> 5) & 0x1f)) 4509 { 4510 inflate_huft *h; 4511 uInt i, j, c; 4512 4513 t = s->sub.trees.bb; 4514 NEEDBITS(t); 4515 h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]); 4516 t = h->word.what.Bits; 4517 c = h->base; 4518 if (c < 16) 4519 { 4520 DUMPBITS(t); 4521 s->sub.trees.blens[s->sub.trees.index++] = 4522 c; 4523 } else { /* c == 16..18 */ 4524 i = c == 18 ? 7 : c - 14; 4525 j = c == 18 ? 11 : 3; 4526 NEEDBITS(t + i); 4527 DUMPBITS(t); 4528 j += (uInt)b & inflate_mask[i]; 4529 DUMPBITS(i); 4530 i = s->sub.trees.index; 4531 t = s->sub.trees.table; 4532 if (i + j > 258 + (t & 0x1f) + 4533 ((t >> 5) & 0x1f) || 4534 (c == 16 && i < 1)) 4535 { 4536 ZFREE(z, s->sub.trees.blens); 4537 s->sub.trees.blens = Z_NULL; 4538 s->mode = BADB; 4539 z->msg = "invalid bit length repeat"; 4540 r = Z_DATA_ERROR; 4541 LEAVE 4542 } 4543 c = c == 16 ? s->sub.trees.blens[i - 1] : 0; 4544 do { 4545 s->sub.trees.blens[i++] = c; 4546 } while (--j); 4547 s->sub.trees.index = i; 4548 } 4549 } 4550 s->sub.trees.tb = Z_NULL; 4551 { 4552 uInt bl, bd; 4553 inflate_huft *tl, *td; 4554 inflate_codes_statef *c; 4555 4556 /* must be <= 9 for lookahead assumptions */ 4557 bl = 9; 4558 /* must be <= 9 for lookahead assumptions */ 4559 bd = 6; 4560 t = s->sub.trees.table; 4561 t = inflate_trees_dynamic(257 + (t & 0x1f), 4562 1 + ((t >> 5) & 0x1f), 4563 s->sub.trees.blens, &bl, &bd, &tl, &td, 4564 s->hufts, z); 4565 ZFREE(z, s->sub.trees.blens); 4566 s->sub.trees.blens = Z_NULL; 4567 if (t != Z_OK) 4568 { 4569 if (t == (uInt)Z_DATA_ERROR) 4570 s->mode = BADB; 4571 r = t; 4572 LEAVE 4573 } 4574 Tracev((stderr, "inflate: trees ok\n")); 4575 if ((c = inflate_codes_new(bl, bd, tl, td, z)) == 4576 Z_NULL) 4577 { 4578 r = Z_MEM_ERROR; 4579 LEAVE 4580 } 4581 s->sub.decode.codes = c; 4582 } 4583 s->mode = CODES; 4584 /* FALLTHRU */ 4585 case CODES: 4586 UPDATE; 4587 if ((r = inflate_codes(s, z, r)) != Z_STREAM_END) 4588 return (inflate_flush(s, z, r)); 4589 r = Z_OK; 4590 (void) inflate_codes_free(s->sub.decode.codes, z); 4591 LOAD; 4592 Tracev((stderr, "inflate: codes end, %lu total out\n", 4593 z->total_out + (q >= s->read ? q - s->read : 4594 (s->end - s->read) + (q - s->window)))); 4595 if (!s->last) 4596 { 4597 s->mode = TYPE; 4598 break; 4599 } 4600 s->mode = DRY; 4601 /* FALLTHRU */ 4602 case DRY: 4603 FLUSH; 4604 if (s->read != s->write) 4605 LEAVE 4606 s->mode = DONEB; 4607 /* FALLTHRU */ 4608 case DONEB: 4609 r = Z_STREAM_END; 4610 LEAVE 4611 case BADB: 4612 r = Z_DATA_ERROR; 4613 LEAVE 4614 default: 4615 r = Z_STREAM_ERROR; 4616 LEAVE 4617 } 4618 /* NOTREACHED */ 4619 /* otherwise lint complains */ 4620 } 4621 4622 4623 int 4624 inflate_blocks_free(s, z) 4625 inflate_blocks_statef *s; 4626 z_streamp z; 4627 { 4628 inflate_blocks_reset(s, z, Z_NULL); 4629 ZFREE(z, s->window); 4630 s->window = Z_NULL; 4631 ZFREE(z, s->hufts); 4632 s->hufts = Z_NULL; 4633 ZFREE(z, s); 4634 Trace((stderr, "inflate: blocks freed\n")); 4635 return (Z_OK); 4636 } 4637 4638 4639 void 4640 inflate_set_dictionary(s, d, n) 4641 inflate_blocks_statef *s; 4642 const Bytef *d; 4643 uInt n; 4644 { 4645 Assert(s->window + n <= s->end, "set dict"); 4646 zmemcpy((charf *)s->window, d, n); 4647 s->read = s->write = s->window + n; 4648 } 4649 4650 /* 4651 * Returns true if inflate is currently at the end of a block 4652 * generated by Z_SYNC_FLUSH or Z_FULL_FLUSH. 4653 * IN assertion: s != Z_NULL 4654 */ 4655 int 4656 inflate_blocks_sync_point(s) 4657 inflate_blocks_statef *s; 4658 { 4659 return (s->mode == LENS); 4660 } 4661 4662 /* 4663 * This subroutine adds the data at next_in/avail_in to the output history 4664 * without performing any output. The output buffer must be "caught up"; 4665 * i.e. no pending output (hence s->read equals s->write), and the state must 4666 * be BLOCKS (i.e. we should be willing to see the start of a series of 4667 * BLOCKS). On exit, the output will also be caught up, and the checksum 4668 * will have been updated if need be. 4669 */ 4670 int 4671 inflate_addhistory(s, z) 4672 inflate_blocks_statef *s; 4673 z_stream *z; 4674 { 4675 uLong b; /* bit buffer */ /* NOT USED HERE */ 4676 uInt k; /* bits in bit buffer */ /* NOT USED HERE */ 4677 uInt t; /* temporary storage */ 4678 Bytef *p; /* input data pointer */ 4679 uInt n; /* bytes available there */ 4680 Bytef *q; /* output window write pointer */ 4681 uInt m; /* bytes to end of window or read pointer */ 4682 4683 if (s->read != s->write) 4684 return (Z_STREAM_ERROR); 4685 if (s->mode != TYPE) 4686 return (Z_DATA_ERROR); 4687 4688 /* we're ready to rock */ 4689 LOAD; 4690 /* 4691 * while there is input ready, copy to output buffer, moving 4692 * pointers as needed. 4693 */ 4694 while (n) { 4695 t = n; /* how many to do */ 4696 /* is there room until end of buffer? */ 4697 if (t > m) t = m; 4698 /* update check information */ 4699 if (s->checkfn != Z_NULL) 4700 s->check = (*s->checkfn)(s->check, q, t); 4701 zmemcpy(q, p, t); 4702 q += t; 4703 p += t; 4704 n -= t; 4705 z->total_out += t; 4706 s->read = q; /* drag read pointer forward */ 4707 /* WWRAP */ /* expand WWRAP macro by hand to handle s->read */ 4708 if (q == s->end) { 4709 s->read = q = s->window; 4710 m = WAVAIL; 4711 } 4712 } 4713 UPDATE; 4714 return (Z_OK); 4715 } 4716 4717 4718 /* 4719 * At the end of a Deflate-compressed PPP packet, we expect to have seen 4720 * a `stored' block type value but not the (zero) length bytes. 4721 */ 4722 int 4723 inflate_packet_flush(s) 4724 inflate_blocks_statef *s; 4725 { 4726 if (s->mode != LENS) 4727 return (Z_DATA_ERROR); 4728 s->mode = TYPE; 4729 return (Z_OK); 4730 } 4731 /* --- infblock.c */ 4732 4733 /* +++ inftrees.c */ 4734 /* 4735 * inftrees.c -- generate Huffman trees for efficient decoding 4736 * Copyright (C) 1995-1998 Mark Adler 4737 * For conditions of distribution and use, see copyright notice in zlib.h 4738 */ 4739 4740 /* #include "zutil.h" */ 4741 /* #include "inftrees.h" */ 4742 4743 const char inflate_copyright[] = 4744 " inflate 1.1.3 Copyright 1995-1998 Mark Adler "; 4745 /* 4746 * If you use the zlib library in a product, an acknowledgment is 4747 * welcome in the documentation of your product. If for some reason 4748 * you cannot include such an acknowledgment, I would appreciate that 4749 * you keep this copyright string in the executable of your product. 4750 */ 4751 4752 #ifndef NO_DUMMY_DECL 4753 struct internal_state {int dummy; }; /* for buggy compilers */ 4754 #endif 4755 4756 /* simplify the use of the inflate_huft type with some defines */ 4757 #define exop word.what.Exop 4758 #define bits word.what.Bits 4759 4760 4761 local int huft_build OF(( 4762 uIntf *, /* code lengths in bits */ 4763 uInt, /* number of codes */ 4764 uInt, /* number of "simple" codes */ 4765 const uIntf *, /* list of base values for non-simple codes */ 4766 const uIntf *, /* list of extra bits for non-simple codes */ 4767 inflate_huft * FAR*, /* result: starting table */ 4768 uIntf *, /* maximum lookup bits (returns actual) */ 4769 inflate_huft *hp, /* space for trees */ 4770 uInt *hn, /* hufts used in space */ 4771 uIntf *v)); /* working area: values in order of bit length */ 4772 4773 /* Tables for deflate from PKZIP's appnote.txt. */ 4774 local const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */ 4775 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 4776 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; 4777 /* see note #13 above about 258 */ 4778 local const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */ 4779 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 4780 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; 4781 /* 112==invalid */ 4782 local const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */ 4783 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 4784 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 4785 8193, 12289, 16385, 24577}; 4786 local const uInt cpdext[30] = { /* Extra bits for distance codes */ 4787 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 4788 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 4789 12, 12, 13, 13}; 4790 4791 /* 4792 * Huffman code decoding is performed using a multi-level table 4793 * lookup. The fastest way to decode is to simply build a lookup 4794 * table whose size is determined by the longest code. However, the 4795 * time it takes to build this table can also be a factor if the data 4796 * being decoded is not very long. The most common codes are 4797 * necessarily the shortest codes, so those codes dominate the 4798 * decoding time, and hence the speed. The idea is you can have a 4799 * shorter table that decodes the shorter, more probable codes, and 4800 * then point to subsidiary tables for the longer codes. The time it 4801 * costs to decode the longer codes is then traded against the time it 4802 * takes to make longer tables. 4803 * 4804 * This results of this trade are in the variables lbits and dbits 4805 * below. lbits is the number of bits the first level table for 4806 * literal/ length codes can decode in one step, and dbits is the same 4807 * thing for the distance codes. Subsequent tables are also less than 4808 * or equal to those sizes. These values may be adjusted either when 4809 * all of the codes are shorter than that, in which case the longest 4810 * code length in bits is used, or when the shortest code is *longer* 4811 * than the requested table size, in which case the length of the 4812 * shortest code in bits is used. 4813 * 4814 * There are two different values for the two tables, since they code 4815 * a different number of possibilities each. The literal/length table 4816 * codes 286 possible values, or in a flat code, a little over eight 4817 * bits. The distance table codes 30 possible values, or a little 4818 * less than five bits, flat. The optimum values for speed end up 4819 * being about one bit more than those, so lbits is 8+1 and dbits is 4820 * 5+1. The optimum values may differ though from machine to machine, 4821 * and possibly even between compilers. Your mileage may vary. 4822 */ 4823 4824 4825 /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */ 4826 #define BMAX 15 /* maximum bit length of any code */ 4827 4828 4829 local int 4830 huft_build(b, n, s, d, e, t, m, hp, hn, v) 4831 uIntf *b; /* code lengths in bits (all assumed <= BMAX) */ 4832 uInt n; /* number of codes (assumed <= 288) */ 4833 uInt s; /* number of simple-valued codes (0..s-1) */ 4834 const uIntf *d; /* list of base values for non-simple codes */ 4835 const uIntf *e; /* list of extra bits for non-simple codes */ 4836 inflate_huft * FAR *t; /* result: starting table */ 4837 uIntf *m; /* maximum lookup bits, returns actual */ 4838 inflate_huft *hp; /* space for trees */ 4839 uInt *hn; /* hufts used in space */ 4840 uIntf *v; /* working area: values in order of bit length */ 4841 /* 4842 * Given a list of code lengths and a maximum table size, make a set 4843 * of tables to decode that set of codes. Return Z_OK on success, 4844 * Z_BUF_ERROR if the given code set is incomplete (the tables are 4845 * still built in this case), Z_DATA_ERROR if the input is invalid (an 4846 * over-subscribed set of lengths), or Z_MEM_ERROR if not enough 4847 * memory. 4848 */ 4849 { 4850 4851 uInt a; /* counter for codes of length k */ 4852 uInt c[BMAX+1]; /* bit length count table */ 4853 uInt f; /* i repeats in table every f entries */ 4854 int g; /* maximum code length */ 4855 int h; /* table level */ 4856 register uInt i; /* counter, current code */ 4857 register uInt j; /* counter */ 4858 register int k; /* number of bits in current code */ 4859 int l; /* bits per table (returned in m) */ 4860 register uIntf *p; /* pointer into c[], b[], or v[] */ 4861 inflate_huft *q; /* points to current table */ 4862 struct inflate_huft_s r; /* table entry for structure assignment */ 4863 inflate_huft *u[BMAX]; /* table stack */ 4864 uInt mask; /* (1 << w) - 1, to avoid cc -O bug on HP */ 4865 register int w; /* bits before this table == (l * h) */ 4866 uInt x[BMAX+1]; /* bit offsets, then code stack */ 4867 uIntf *xp; /* pointer into x */ 4868 int y; /* number of dummy codes added */ 4869 uInt z; /* number of entries in current table */ 4870 4871 (void) inflate_copyright; 4872 /* Generate counts for each bit length */ 4873 p = c; 4874 #define C0 *p++ = 0; 4875 #define C2 C0 C0 C0 C0 4876 #define C4 C2 C2 C2 C2 4877 C4 /* clear c[]--assume BMAX+1 is 16 */ 4878 p = b; i = n; 4879 do { 4880 c[*p++]++; /* assume all entries <= BMAX */ 4881 } while (--i); 4882 if (c[0] == n) /* null input--all zero length codes */ 4883 { 4884 *t = (inflate_huft *)Z_NULL; 4885 *m = 0; 4886 return (Z_OK); 4887 } 4888 4889 4890 /* Find minimum and maximum length, bound *m by those */ 4891 l = *m; 4892 for (j = 1; j <= BMAX; j++) 4893 if (c[j]) 4894 break; 4895 k = j; /* minimum code length */ 4896 if ((uInt)l < j) 4897 l = j; 4898 for (i = BMAX; i; i--) 4899 if (c[i]) 4900 break; 4901 g = i; /* maximum code length */ 4902 if ((uInt)l > i) 4903 l = i; 4904 *m = l; 4905 4906 4907 /* Adjust last length count to fill out codes, if needed */ 4908 for (y = 1 << j; j < i; j++, y <<= 1) 4909 if ((y -= c[j]) < 0) 4910 return (Z_DATA_ERROR); 4911 if ((y -= c[i]) < 0) 4912 return (Z_DATA_ERROR); 4913 c[i] += y; 4914 4915 4916 /* Generate starting offsets into the value table for each length */ 4917 x[1] = j = 0; 4918 p = c + 1; xp = x + 2; 4919 while (--i) { /* note that i == g from above */ 4920 *xp++ = (j += *p++); 4921 } 4922 4923 4924 /* Make a table of values in order of bit lengths */ 4925 p = b; i = 0; 4926 do { 4927 if ((j = *p++) != 0) 4928 v[x[j]++] = i; 4929 } while (++i < n); 4930 n = x[g]; /* set n to length of v */ 4931 4932 4933 /* Generate the Huffman codes and for each, make the table entries */ 4934 x[0] = i = 0; /* first Huffman code is zero */ 4935 p = v; /* grab values in bit order */ 4936 h = -1; /* no tables yet--level -1 */ 4937 w = -l; /* bits decoded == (l * h) */ 4938 u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */ 4939 q = (inflate_huft *)Z_NULL; /* ditto */ 4940 z = 0; /* ditto */ 4941 4942 /* go through the bit lengths (k already is bits in shortest code) */ 4943 for (; k <= g; k++) { 4944 a = c[k]; 4945 while (a--) { 4946 /* 4947 * here i is the Huffman code of length k bits 4948 * for value *p. make tables up to required 4949 * level. 4950 */ 4951 while (k > w + l) { 4952 h++; 4953 w += l; /* previous table always l bits */ 4954 4955 /* 4956 * compute minimum size table less 4957 * than or equal to l bits 4958 */ 4959 z = g - w; 4960 /* table size upper limit */ 4961 z = z > (uInt)l ? l : z; 4962 /* try a k-w bit table */ 4963 if ((f = 1 << (j = k - w)) > a + 1) { 4964 /* too few codes for k-w bit table */ 4965 /* deduct codes from patterns left */ 4966 f -= a + 1; 4967 xp = c + k; 4968 if (j < z) 4969 /* 4970 * try smaller tables 4971 * up to z bits 4972 */ 4973 while (++j < z) { 4974 /* 4975 * enough 4976 * codes to 4977 * use up j 4978 * bits 4979 */ 4980 if ((f <<= 1) <= *++xp) 4981 break; 4982 f -= *xp; 4983 /* 4984 * else deduct 4985 * codes from 4986 * patterns 4987 */ 4988 } 4989 } 4990 /* table entries for j-bit table */ 4991 z = 1 << j; 4992 4993 /* allocate new table */ 4994 /* (note: doesn't matter for fixed) */ 4995 /* not enough memory */ 4996 if (*hn + z > MANY) 4997 return (Z_MEM_ERROR); 4998 u[h] = q = hp + *hn; 4999 *hn += z; 5000 5001 /* connect to last table, if there is one */ 5002 if (h) { 5003 /* save pattern for backing up */ 5004 x[h] = i; 5005 /* bits to dump before this table */ 5006 r.bits = (Byte)l; 5007 /* bits in this table */ 5008 r.exop = (Byte)j; 5009 j = i >> (w - l); 5010 /* offset to this table */ 5011 r.base = (uInt)(q - u[h-1] - j); 5012 /* connect to last table */ 5013 u[h-1][j] = r; 5014 } else 5015 /* first table is returned result */ 5016 *t = q; 5017 } 5018 5019 /* set up table entry in r */ 5020 r.bits = (Byte)(k - w); 5021 if (p >= v + n) 5022 /* out of values--invalid code */ 5023 r.exop = 128 + 64; 5024 else if (*p < s) 5025 { 5026 /* 256 is end-of-block */ 5027 r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); 5028 /* simple code is just the value */ 5029 r.base = *p++; 5030 } 5031 else 5032 { 5033 /* non-simple--look up in lists */ 5034 r.exop = (Byte)(e[*p - s] + 16 + 64); 5035 r.base = d[*p++ - s]; 5036 } 5037 5038 /* fill code-like entries with r */ 5039 f = 1 << (k - w); 5040 for (j = i >> w; j < z; j += f) 5041 q[j] = r; 5042 5043 /* backwards increment the k-bit code i */ 5044 for (j = 1 << (k - 1); i & j; j >>= 1) 5045 i ^= j; 5046 i ^= j; 5047 5048 /* backup over finished tables */ 5049 mask = (1 << w) - 1; /* needed on HP, cc -O bug */ 5050 while ((i & mask) != x[h]) 5051 { 5052 h--; /* don't need to update q */ 5053 w -= l; 5054 mask = (1 << w) - 1; 5055 } 5056 } 5057 } 5058 5059 5060 /* Return Z_BUF_ERROR if we were given an incomplete table */ 5061 return (y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK); 5062 } 5063 5064 5065 int 5066 inflate_trees_bits(c, bb, tb, hp, z) 5067 uIntf *c; /* 19 code lengths */ 5068 uIntf *bb; /* bits tree desired/actual depth */ 5069 inflate_huft * FAR *tb; /* bits tree result */ 5070 inflate_huft *hp; /* space for trees */ 5071 z_streamp z; /* for zfree function */ 5072 { 5073 int r; 5074 uInt hn = 0; /* hufts used in space */ 5075 uIntf v[19]; /* work area for huft_build */ 5076 5077 r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL, tb, bb, 5078 hp, &hn, v); 5079 if (r == Z_DATA_ERROR) 5080 z->msg = "oversubscribed dynamic bit lengths tree"; 5081 else if (r == Z_BUF_ERROR || *bb == 0) 5082 { 5083 z->msg = "incomplete dynamic bit lengths tree"; 5084 r = Z_DATA_ERROR; 5085 } 5086 return (r); 5087 } 5088 5089 5090 int 5091 inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, hp, z) 5092 uInt nl; /* number of literal/length codes */ 5093 uInt nd; /* number of distance codes */ 5094 uIntf *c; /* that many (total) code lengths */ 5095 uIntf *bl; /* literal desired/actual bit depth */ 5096 uIntf *bd; /* distance desired/actual bit depth */ 5097 inflate_huft * FAR *tl; /* literal/length tree result */ 5098 inflate_huft * FAR *td; /* distance tree result */ 5099 inflate_huft *hp; /* space for trees */ 5100 z_streamp z; /* for zfree function */ 5101 { 5102 int r; 5103 uInt hn = 0; /* hufts used in space */ 5104 uIntf v[288]; /* work area for huft_build */ 5105 5106 /* build literal/length tree */ 5107 r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v); 5108 if (r != Z_OK || *bl == 0) 5109 { 5110 if (r == Z_DATA_ERROR) 5111 z->msg = "oversubscribed literal/length tree"; 5112 else if (r != Z_MEM_ERROR) 5113 { 5114 z->msg = "incomplete literal/length tree"; 5115 r = Z_DATA_ERROR; 5116 } 5117 return (r); 5118 } 5119 5120 /* build distance tree */ 5121 r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v); 5122 if (r != Z_OK || (*bd == 0 && nl > 257)) 5123 { 5124 if (r == Z_DATA_ERROR) 5125 z->msg = "oversubscribed distance tree"; 5126 else if (r == Z_BUF_ERROR) { 5127 #ifdef PKZIP_BUG_WORKAROUND 5128 r = Z_OK; 5129 #else 5130 z->msg = "incomplete distance tree"; 5131 r = Z_DATA_ERROR; 5132 } else if (r != Z_MEM_ERROR) { 5133 z->msg = "empty distance tree with lengths"; 5134 r = Z_DATA_ERROR; 5135 #endif 5136 } 5137 return (r); 5138 } 5139 5140 /* done */ 5141 return (Z_OK); 5142 } 5143 5144 5145 /* build fixed tables only once--keep them here */ 5146 /* #define BUILDFIXED */ 5147 #ifdef BUILDFIXED 5148 local int fixed_built = 0; 5149 #define FIXEDH 544 /* number of hufts used by fixed tables */ 5150 local inflate_huft fixed_mem[FIXEDH]; 5151 local uInt fixed_bl; 5152 local uInt fixed_bd; 5153 local inflate_huft *fixed_tl; 5154 local inflate_huft *fixed_td; 5155 #else 5156 #include "inffixed.h" 5157 #endif 5158 5159 /*ARGSUSED*/ 5160 int 5161 inflate_trees_fixed(bl, bd, tl, td, z) 5162 uIntf *bl; /* literal desired/actual bit depth */ 5163 uIntf *bd; /* distance desired/actual bit depth */ 5164 const inflate_huft * FAR *tl; /* literal/length tree result */ 5165 const inflate_huft * FAR *td; /* distance tree result */ 5166 z_streamp z; /* for memory allocation */ 5167 { 5168 #ifdef BUILDFIXED 5169 /* 5170 * build fixed tables if not already (multiple overlapped 5171 * executions ok) 5172 */ 5173 if (!fixed_built) 5174 { 5175 int k; /* temporary variable */ 5176 uInt f = 0; /* number of hufts used in fixed_mem */ 5177 uIntf *c; /* length list for huft_build */ 5178 uIntf *v; 5179 5180 /* allocate memory */ 5181 if ((c = (uIntf*)ZALLOC(z, 288, sizeof (uInt))) == Z_NULL) 5182 return (Z_MEM_ERROR); 5183 if ((v = (uIntf*)ZALLOC(z, 288, sizeof (uInt))) == Z_NULL) 5184 { 5185 ZFREE(z, c); 5186 return (Z_MEM_ERROR); 5187 } 5188 /* literal table */ 5189 for (k = 0; k < 144; k++) 5190 c[k] = 8; 5191 for (; k < 256; k++) 5192 c[k] = 9; 5193 for (; k < 280; k++) 5194 c[k] = 7; 5195 for (; k < 288; k++) 5196 c[k] = 8; 5197 fixed_bl = 9; 5198 (void) huft_build(c, 288, 257, cplens, cplext, &fixed_tl, 5199 &fixed_bl, fixed_mem, &f, v); 5200 5201 /* distance table */ 5202 for (k = 0; k < 30; k++) 5203 c[k] = 5; 5204 fixed_bd = 5; 5205 (void) huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, 5206 &fixed_bd, fixed_mem, &f, v); 5207 5208 /* done */ 5209 ZFREE(z, v); 5210 ZFREE(z, c); 5211 fixed_built = 1; 5212 } 5213 #endif 5214 *bl = fixed_bl; 5215 *bd = fixed_bd; 5216 *tl = fixed_tl; 5217 *td = fixed_td; 5218 return (Z_OK); 5219 } 5220 /* --- inftrees.c */ 5221 5222 /* +++ infcodes.c */ 5223 /* 5224 * infcodes.c -- process literals and length/distance pairs 5225 * Copyright (C) 1995-1998 Mark Adler 5226 * For conditions of distribution and use, see copyright notice in zlib.h 5227 */ 5228 5229 /* #include "zutil.h" */ 5230 /* #include "inftrees.h" */ 5231 /* #include "infblock.h" */ 5232 /* #include "infcodes.h" */ 5233 /* #include "infutil.h" */ 5234 5235 /* +++ inffast.h */ 5236 /* 5237 * inffast.h -- header to use inffast.c 5238 * Copyright (C) 1995-1998 Mark Adler 5239 * For conditions of distribution and use, see copyright notice in zlib.h 5240 */ 5241 5242 /* 5243 * WARNING: this file should *not* be used by applications. It is part 5244 * of the implementation of the compression library and is subject to 5245 * change. Applications should only use zlib.h. 5246 */ 5247 5248 extern int inflate_fast OF(( 5249 uInt, 5250 uInt, 5251 const inflate_huft *, 5252 const inflate_huft *, 5253 inflate_blocks_statef *, 5254 z_streamp)); 5255 /* --- inffast.h */ 5256 5257 /* simplify the use of the inflate_huft type with some defines */ 5258 #define exop word.what.Exop 5259 #define bits word.what.Bits 5260 5261 /* inflate codes private state */ 5262 struct inflate_codes_state { 5263 5264 /* mode */ 5265 enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */ 5266 START, /* x: set up for LEN */ 5267 LEN, /* i: get length/literal/eob next */ 5268 LENEXT, /* i: getting length extra (have base) */ 5269 DIST, /* i: get distance next */ 5270 DISTEXT, /* i: getting distance extra */ 5271 COPY, /* o: copying bytes in window, waiting for space */ 5272 LIT, /* o: got literal, waiting for output space */ 5273 WASH, /* o: got eob, possibly still output waiting */ 5274 END, /* x: got eob and all data flushed */ 5275 BADCODE} /* x: got error */ 5276 mode; /* current inflate_codes mode */ 5277 5278 /* mode dependent information */ 5279 uInt len; 5280 union { 5281 struct { 5282 const inflate_huft *tree; /* pointer into tree */ 5283 uInt need; /* bits needed */ 5284 } code; /* if LEN or DIST, where in tree */ 5285 uInt lit; /* if LIT, literal */ 5286 struct { 5287 uInt get; /* bits to get for extra */ 5288 uInt dist; /* distance back to copy from */ 5289 } copy; /* if EXT or COPY, where and how much */ 5290 } sub; /* submode */ 5291 5292 /* mode independent information */ 5293 Byte lbits; /* ltree bits decoded per branch */ 5294 Byte dbits; /* dtree bits decoder per branch */ 5295 const inflate_huft *ltree; /* literal/length/eob tree */ 5296 const inflate_huft *dtree; /* distance tree */ 5297 5298 }; 5299 5300 5301 inflate_codes_statef * 5302 inflate_codes_new(bl, bd, tl, td, z) 5303 uInt bl, bd; 5304 const inflate_huft *tl; 5305 const inflate_huft *td; /* need separate declaration for Borland C++ */ 5306 z_streamp z; 5307 { 5308 inflate_codes_statef *c; 5309 5310 if ((c = (inflate_codes_statef *) 5311 ZALLOC(z, 1, sizeof (struct inflate_codes_state))) != Z_NULL) 5312 { 5313 c->mode = START; 5314 c->lbits = (Byte)bl; 5315 c->dbits = (Byte)bd; 5316 c->ltree = tl; 5317 c->dtree = td; 5318 Tracev((stderr, "inflate: codes new\n")); 5319 } 5320 return (c); 5321 } 5322 5323 5324 int 5325 inflate_codes(s, z, r) 5326 inflate_blocks_statef *s; 5327 z_streamp z; 5328 int r; 5329 { 5330 uInt j; /* temporary storage */ 5331 const inflate_huft *t; /* temporary pointer */ 5332 uInt e; /* extra bits or operation */ 5333 uLong b; /* bit buffer */ 5334 uInt k; /* bits in bit buffer */ 5335 Bytef *p; /* input data pointer */ 5336 uInt n; /* bytes available there */ 5337 Bytef *q; /* output window write pointer */ 5338 uInt m; /* bytes to end of window or read pointer */ 5339 Bytef *f; /* pointer to copy strings from */ 5340 inflate_codes_statef *c = s->sub.decode.codes; /* codes state */ 5341 5342 /* copy input/output information to locals (UPDATE macro restores) */ 5343 LOAD; 5344 5345 /* process input and output based on current state */ 5346 /* CONSTCOND */ 5347 while (1) 5348 /* waiting for "i:"=input, "o:"=output, "x:"=nothing */ 5349 switch (c->mode) { 5350 case START: /* x: set up for LEN */ 5351 #ifndef SLOW 5352 if (m >= 258 && n >= 10) 5353 { 5354 UPDATE; 5355 r = inflate_fast(c->lbits, c->dbits, 5356 c->ltree, c->dtree, s, z); 5357 LOAD; 5358 if (r != Z_OK) { 5359 c->mode = r == Z_STREAM_END ? 5360 WASH : BADCODE; 5361 break; 5362 } 5363 } 5364 #endif /* !SLOW */ 5365 c->sub.code.need = c->lbits; 5366 c->sub.code.tree = c->ltree; 5367 c->mode = LEN; 5368 /* FALLTHRU */ 5369 case LEN: /* i: get length/literal/eob next */ 5370 j = c->sub.code.need; 5371 NEEDBITS(j); 5372 t = c->sub.code.tree + 5373 ((uInt)b & inflate_mask[j]); 5374 DUMPBITS(t->bits); 5375 e = (uInt)(t->exop); 5376 if (e == 0) { /* literal */ 5377 c->sub.lit = t->base; 5378 Tracevv((stderr, t->base >= 0x20 && 5379 t->base < 0x7f ? 5380 "inflate: literal '%c'\n" : 5381 "inflate: literal 0x%02x\n", 5382 t->base)); 5383 c->mode = LIT; 5384 break; 5385 } 5386 if (e & 16) { /* length */ 5387 c->sub.copy.get = e & 15; 5388 c->len = t->base; 5389 c->mode = LENEXT; 5390 break; 5391 } 5392 if ((e & 64) == 0) { /* next table */ 5393 c->sub.code.need = e; 5394 c->sub.code.tree = t + t->base; 5395 break; 5396 } 5397 if (e & 32) { /* end of block */ 5398 Tracevv((stderr, 5399 "inflate: end of block\n")); 5400 c->mode = WASH; 5401 break; 5402 } 5403 c->mode = BADCODE; /* invalid code */ 5404 z->msg = "invalid literal/length code"; 5405 r = Z_DATA_ERROR; 5406 LEAVE 5407 case LENEXT: /* i: getting length extra (have base) */ 5408 j = c->sub.copy.get; 5409 NEEDBITS(j); 5410 c->len += (uInt)b & inflate_mask[j]; 5411 DUMPBITS(j); 5412 c->sub.code.need = c->dbits; 5413 c->sub.code.tree = c->dtree; 5414 Tracevv((stderr, 5415 "inflate: length %u\n", c->len)); 5416 c->mode = DIST; 5417 /* FALLTHRU */ 5418 case DIST: /* i: get distance next */ 5419 j = c->sub.code.need; 5420 NEEDBITS(j); 5421 t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); 5422 DUMPBITS(t->bits); 5423 e = (uInt)(t->exop); 5424 if (e & 16) { /* distance */ 5425 c->sub.copy.get = e & 15; 5426 c->sub.copy.dist = t->base; 5427 c->mode = DISTEXT; 5428 break; 5429 } 5430 if ((e & 64) == 0) { /* next table */ 5431 c->sub.code.need = e; 5432 c->sub.code.tree = t + t->base; 5433 break; 5434 } 5435 c->mode = BADCODE; /* invalid code */ 5436 z->msg = "invalid distance code"; 5437 r = Z_DATA_ERROR; 5438 LEAVE 5439 case DISTEXT: /* i: getting distance extra */ 5440 j = c->sub.copy.get; 5441 NEEDBITS(j); 5442 c->sub.copy.dist += (uInt)b & inflate_mask[j]; 5443 DUMPBITS(j); 5444 Tracevv((stderr, 5445 "inflate: distance %u\n", 5446 c->sub.copy.dist)); 5447 c->mode = COPY; 5448 /* FALLTHRU */ 5449 case COPY: 5450 /* o: copying bytes in window, waiting for space */ 5451 #ifndef __TURBOC__ /* Turbo C bug for following expression */ 5452 f = (uInt)(q - s->window) < c->sub.copy.dist ? 5453 s->end - (c->sub.copy.dist - (q - s->window)) : 5454 q - c->sub.copy.dist; 5455 #else 5456 f = q - c->sub.copy.dist; 5457 if ((uInt)(q - s->window) < c->sub.copy.dist) 5458 f = s->end - (c->sub.copy.dist - 5459 (uInt)(q - s->window)); 5460 #endif 5461 while (c->len) 5462 { 5463 NEEDOUT; 5464 OUTBYTE(*f++); 5465 if (f == s->end) 5466 f = s->window; 5467 c->len--; 5468 } 5469 c->mode = START; 5470 break; 5471 case LIT: /* o: got literal, waiting for output space */ 5472 NEEDOUT; 5473 OUTBYTE(c->sub.lit); 5474 c->mode = START; 5475 break; 5476 case WASH: /* o: got eob, possibly more output */ 5477 if (k > 7) { /* return unused byte, if any */ 5478 Assert(k < 16, 5479 "inflate_codes grabbed too many bytes"); 5480 k -= 8; 5481 n++; 5482 p--; /* can always return one */ 5483 } 5484 FLUSH; 5485 if (s->read != s->write) 5486 LEAVE 5487 c->mode = END; 5488 /* FALLTHRU */ 5489 case END: 5490 r = Z_STREAM_END; 5491 LEAVE 5492 case BADCODE: /* x: got error */ 5493 r = Z_DATA_ERROR; 5494 LEAVE 5495 default: 5496 r = Z_STREAM_ERROR; 5497 LEAVE 5498 } 5499 /* NOTREACHED */ 5500 /* otherwise lint complains */ 5501 } 5502 5503 5504 void 5505 inflate_codes_free(c, z) 5506 inflate_codes_statef *c; 5507 z_streamp z; 5508 { 5509 ZFREE(z, c); 5510 Tracev((stderr, "inflate: codes free\n")); 5511 } 5512 /* --- infcodes.c */ 5513 5514 /* +++ infutil.c */ 5515 /* 5516 * inflate_util.c -- data and routines common to blocks and codes 5517 * Copyright (C) 1995-1998 Mark Adler 5518 * For conditions of distribution and use, see copyright notice in zlib.h 5519 */ 5520 5521 /* #include "zutil.h" */ 5522 /* #include "infblock.h" */ 5523 /* #include "inftrees.h" */ 5524 /* #include "infcodes.h" */ 5525 /* #include "infutil.h" */ 5526 5527 #ifndef NO_DUMMY_DECL 5528 struct inflate_codes_state {int dummy; }; /* for buggy compilers */ 5529 #endif 5530 5531 /* And'ing with mask[n] masks the lower n bits */ 5532 uInt inflate_mask[17] = { 5533 0x0000, 5534 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 5535 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff 5536 }; 5537 5538 5539 /* copy as much as possible from the sliding window to the output area */ 5540 int 5541 inflate_flush(s, z, r) 5542 inflate_blocks_statef *s; 5543 z_streamp z; 5544 int r; 5545 { 5546 uInt n; 5547 Bytef *p; 5548 Bytef *q; 5549 5550 /* local copies of source and destination pointers */ 5551 p = z->next_out; 5552 q = s->read; 5553 5554 /* compute number of bytes to copy as far as end of window */ 5555 n = (uInt)((q <= s->write ? s->write : s->end) - q); 5556 if (n > z->avail_out) n = z->avail_out; 5557 if (n && r == Z_BUF_ERROR) r = Z_OK; 5558 5559 /* update counters */ 5560 z->avail_out -= n; 5561 z->total_out += n; 5562 5563 /* update check information */ 5564 if (s->checkfn != Z_NULL) 5565 z->adler = s->check = (*s->checkfn)(s->check, q, n); 5566 5567 /* copy as far as end of window */ 5568 if (p != Z_NULL) { /* PPP */ 5569 zmemcpy(p, q, n); 5570 p += n; 5571 } /* PPP */ 5572 q += n; 5573 5574 /* see if more to copy at beginning of window */ 5575 if (q == s->end) 5576 { 5577 /* wrap pointers */ 5578 q = s->window; 5579 if (s->write == s->end) 5580 s->write = s->window; 5581 5582 /* compute bytes to copy */ 5583 n = (uInt)(s->write - q); 5584 if (n > z->avail_out) n = z->avail_out; 5585 if (n && r == Z_BUF_ERROR) r = Z_OK; 5586 5587 /* update counters */ 5588 z->avail_out -= n; 5589 z->total_out += n; 5590 5591 /* update check information */ 5592 if (s->checkfn != Z_NULL) 5593 z->adler = s->check = (*s->checkfn)(s->check, q, n); 5594 5595 /* copy */ 5596 if (p != Z_NULL) { /* PPP */ 5597 zmemcpy(p, q, n); 5598 p += n; 5599 } /* PPP */ 5600 q += n; 5601 } 5602 5603 /* update pointers */ 5604 z->next_out = p; 5605 s->read = q; 5606 5607 /* done */ 5608 return (r); 5609 } 5610 /* --- infutil.c */ 5611 5612 /* +++ inffast.c */ 5613 /* 5614 * inffast.c -- process literals and length/distance pairs fast 5615 * Copyright (C) 1995-1998 Mark Adler 5616 * For conditions of distribution and use, see copyright notice in zlib.h 5617 */ 5618 5619 /* #include "zutil.h" */ 5620 /* #include "inftrees.h" */ 5621 /* #include "infblock.h" */ 5622 /* #include "infcodes.h" */ 5623 /* #include "infutil.h" */ 5624 /* #include "inffast.h" */ 5625 5626 #ifndef NO_DUMMY_DECL 5627 struct inflate_codes_state {int dummy; }; /* for buggy compilers */ 5628 #endif 5629 5630 /* simplify the use of the inflate_huft type with some defines */ 5631 #define exop word.what.Exop 5632 #define bits word.what.Bits 5633 5634 /* macros for bit input with no checking and for returning unused bytes */ 5635 #define GRABBITS(j) { while (k < (j)) {b |= ((uLong)NEXTBYTE)<<k; k += 8; }} 5636 #define UNGRAB {c = z->avail_in-n; c = (k>>3) < c?k>>3:c; n += c; p -= c; \ 5637 k -= c<<3; } 5638 5639 /* 5640 * Called with number of bytes left to write in window at least 258 5641 * (the maximum string length) and number of input bytes available at 5642 * least ten. The ten bytes are six bytes for the longest length/ 5643 * distance pair plus four bytes for overloading the bit buffer. 5644 */ 5645 5646 int 5647 inflate_fast(bl, bd, tl, td, s, z) 5648 uInt bl, bd; 5649 const inflate_huft *tl; 5650 const inflate_huft *td; /* need separate declaration for Borland C++ */ 5651 inflate_blocks_statef *s; 5652 z_streamp z; 5653 { 5654 const inflate_huft *t; /* temporary pointer */ 5655 uInt e; /* extra bits or operation */ 5656 uLong b; /* bit buffer */ 5657 uInt k; /* bits in bit buffer */ 5658 Bytef *p; /* input data pointer */ 5659 uInt n; /* bytes available there */ 5660 Bytef *q; /* output window write pointer */ 5661 uInt m; /* bytes to end of window or read pointer */ 5662 uInt ml; /* mask for literal/length tree */ 5663 uInt md; /* mask for distance tree */ 5664 uInt c; /* bytes to copy */ 5665 uInt d; /* distance back to copy from */ 5666 Bytef *r; /* copy source pointer */ 5667 5668 /* load input, output, bit values */ 5669 LOAD; 5670 5671 /* initialize masks */ 5672 ml = inflate_mask[bl]; 5673 md = inflate_mask[bd]; 5674 5675 /* do until not enough input or output space for fast loop */ 5676 do { /* assume called with m >= 258 && n >= 10 */ 5677 /* get literal/length code */ 5678 /* max bits for literal/length code */ 5679 GRABBITS(20); 5680 if ((e = (t = tl + ((uInt)b & ml))->exop) == 0) { 5681 DUMPBITS(t->bits); 5682 Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? 5683 "inflate: * literal '%c'\n" : 5684 "inflate: * literal 0x%02x\n", t->base)); 5685 *q++ = (Byte)t->base; 5686 m--; 5687 continue; 5688 } 5689 do { 5690 DUMPBITS(t->bits); 5691 if (e & 16) { 5692 /* get extra bits for length */ 5693 e &= 15; 5694 c = t->base + ((uInt)b & inflate_mask[e]); 5695 DUMPBITS(e); 5696 Tracevv((stderr, 5697 "inflate: * length %u\n", c)); 5698 5699 /* decode distance base of block to copy */ 5700 GRABBITS(15); /* max bits for distance code */ 5701 e = (t = td + ((uInt)b & md))->exop; 5702 do { 5703 DUMPBITS(t->bits); 5704 if (e & 16) { 5705 /* 5706 * get extra bits to 5707 * add to distance 5708 * base 5709 */ 5710 e &= 15; 5711 /* get extra bits (up to 13) */ 5712 GRABBITS(e); 5713 d = t->base + ((uInt)b & 5714 inflate_mask[e]); 5715 DUMPBITS(e); 5716 Tracevv((stderr, 5717 "inflate: * " 5718 "distance %u\n", d)); 5719 5720 /* do the copy */ 5721 m -= c; 5722 /* offset before dest */ 5723 if ((uInt)(q - s->window) >= d) 5724 /* just copy */ 5725 { 5726 r = q - d; 5727 /* 5728 * minimum 5729 * count is 5730 * three, so 5731 * unroll loop 5732 * a little 5733 */ 5734 *q++ = *r++; c--; 5735 *q++ = *r++; c--; 5736 } 5737 /* else offset after destination */ 5738 else { 5739 /* bytes from offset to end */ 5740 e = d - (uInt)(q - 5741 s->window); 5742 /* pointer to offset */ 5743 r = s->end - e; 5744 /* if source crosses */ 5745 if (c > e) { 5746 /* copy to end of window */ 5747 c -= e; 5748 do { 5749 *q++ = 5750 *r 5751 ++; 5752 } while (--e); 5753 /* copy rest from start of window */ 5754 r = s->window; 5755 } 5756 } 5757 /* copy all or what's left */ 5758 do { 5759 *q++ = *r++; 5760 } while (--c); 5761 break; 5762 } else if ((e & 64) == 0) { 5763 t += t->base; 5764 e = (t += ((uInt)b & 5765 inflate_mask[e]))->exop; 5766 } else { 5767 z->msg = 5768 "invalid distance code"; 5769 UNGRAB; 5770 UPDATE; 5771 return (Z_DATA_ERROR); 5772 } 5773 /* CONSTCOND */ 5774 } while (1); 5775 break; 5776 } 5777 if ((e & 64) == 0) 5778 { 5779 t += t->base; 5780 if ((e = (t += ((uInt)b & 5781 inflate_mask[e]))->exop) == 0) 5782 { 5783 DUMPBITS(t->bits); 5784 Tracevv((stderr, t->base >= 0x20 && 5785 t->base < 0x7f ? 5786 "inflate: * literal '%c'\n" 5787 : 5788 "inflate: * literal " 5789 "0x%02x\n", t->base)); 5790 *q++ = (Byte)t->base; 5791 m--; 5792 break; 5793 } 5794 } else if (e & 32) { 5795 Tracevv((stderr, 5796 "inflate: * end of block\n")); 5797 UNGRAB; 5798 UPDATE; 5799 return (Z_STREAM_END); 5800 } else { 5801 z->msg = "invalid literal/length code"; 5802 UNGRAB; 5803 UPDATE; 5804 return (Z_DATA_ERROR); 5805 } 5806 /* CONSTCOND */ 5807 } while (1); 5808 } while (m >= 258 && n >= 10); 5809 5810 /* not enough input or output--restore pointers and return */ 5811 UNGRAB; 5812 UPDATE; 5813 return (Z_OK); 5814 } 5815 /* --- inffast.c */ 5816 5817 /* +++ zutil.c */ 5818 /* 5819 * zutil.c -- target dependent utility functions for the compression library 5820 * Copyright (C) 1995-1998 Jean-loup Gailly. 5821 * For conditions of distribution and use, see copyright notice in zlib.h 5822 */ 5823 5824 /* From: zutil.c,v 1.17 1996/07/24 13:41:12 me Exp $ */ 5825 5826 #ifdef DEBUG_ZLIB 5827 #include <stdio.h> 5828 #endif 5829 5830 /* #include "zutil.h" */ 5831 5832 #ifndef NO_DUMMY_DECL 5833 struct internal_state {int dummy; }; /* for buggy compilers */ 5834 #endif 5835 5836 #ifndef STDC 5837 extern void exit OF((int)); 5838 #endif 5839 5840 static const char *z_errmsg[10] = { 5841 "need dictionary", /* Z_NEED_DICT 2 */ 5842 "stream end", /* Z_STREAM_END 1 */ 5843 "", /* Z_OK 0 */ 5844 "file error", /* Z_ERRNO (-1) */ 5845 "stream error", /* Z_STREAM_ERROR (-2) */ 5846 "data error", /* Z_DATA_ERROR (-3) */ 5847 "insufficient memory", /* Z_MEM_ERROR (-4) */ 5848 "buffer error", /* Z_BUF_ERROR (-5) */ 5849 "incompatible version", /* Z_VERSION_ERROR (-6) */ 5850 ""}; 5851 5852 5853 const char * 5854 zlibVersion() 5855 { 5856 return (ZLIB_VERSION); 5857 } 5858 5859 #ifdef DEBUG_ZLIB 5860 void 5861 z_error(m) 5862 char *m; 5863 { 5864 fprintf(stderr, "%s\n", m); 5865 exit(1); 5866 } 5867 #endif 5868 5869 #ifndef HAVE_MEMCPY 5870 5871 void 5872 zmemcpy(dest, source, len) 5873 Bytef* dest; 5874 const Bytef* source; 5875 uInt len; 5876 { 5877 if (len == 0) 5878 return; 5879 do { 5880 *dest++ = *source++; /* ??? to be unrolled */ 5881 } while (--len != 0); 5882 } 5883 5884 int 5885 zmemcmp(s1, s2, len) 5886 const Bytef* s1; 5887 const Bytef* s2; 5888 uInt len; 5889 { 5890 uInt j; 5891 5892 for (j = 0; j < len; j++) { 5893 if (s1[j] != s2[j]) 5894 return (2*(s1[j] > s2[j])-1); 5895 } 5896 return (0); 5897 } 5898 5899 void 5900 zmemzero(dest, len) 5901 Bytef* dest; 5902 uInt len; 5903 { 5904 if (len == 0) 5905 return; 5906 do { 5907 *dest++ = 0; /* ??? to be unrolled */ 5908 } while (--len != 0); 5909 } 5910 #endif 5911 5912 #ifdef __TURBOC__ 5913 #if (defined(__BORLANDC__) || !defined(SMALL_MEDIUM)) && !defined(__32BIT__) 5914 /* 5915 * Small and medium model in Turbo C are for now limited to near 5916 * allocation with reduced MAX_WBITS and MAX_MEM_LEVEL 5917 */ 5918 #define MY_ZCALLOC 5919 5920 /* 5921 * Turbo C malloc() does not allow dynamic allocation of 64K bytes and 5922 * farmalloc(64K) returns a pointer with an offset of 8, so we must 5923 * fix the pointer. Warning: the pointer must be put back to its 5924 * original form in order to free it, use zcfree(). 5925 */ 5926 5927 #define MAX_PTR 10 5928 /* 10*64K = 640K */ 5929 5930 local int next_ptr = 0; 5931 5932 typedef struct ptr_table_s { 5933 voidpf org_ptr; 5934 voidpf new_ptr; 5935 } ptr_table; 5936 5937 local ptr_table table[MAX_PTR]; 5938 /* 5939 * This table is used to remember the original form of pointers to 5940 * large buffers (64K). Such pointers are normalized with a zero 5941 * offset. Since MSDOS is not a preemptive multitasking OS, this 5942 * table is not protected from concurrent access. This hack doesn't 5943 * work anyway on a protected system like OS/2. Use Microsoft C 5944 * instead. 5945 */ 5946 5947 voidpf 5948 zcalloc(voidpf opaque, unsigned items, unsigned size) 5949 { 5950 voidpf buf = opaque; /* just to make some compilers happy */ 5951 ulg bsize = (ulg)items*size; 5952 5953 /* 5954 * If we allocate less than 65520 bytes, we assume that 5955 * farmalloc will return a usable pointer which doesn't have 5956 * to be normalized. 5957 */ 5958 if (bsize < 65520L) { 5959 buf = farmalloc(bsize); 5960 if (*(ush *)&buf != 0) 5961 return (buf); 5962 } else { 5963 buf = farmalloc(bsize + 16L); 5964 } 5965 if (buf == NULL || next_ptr >= MAX_PTR) 5966 return (NULL); 5967 table[next_ptr].org_ptr = buf; 5968 5969 /* Normalize the pointer to seg:0 */ 5970 *((ush *)&buf+1) += ((ush)((uch *)buf-0) + 15) >> 4; 5971 *(ush *)&buf = 0; 5972 table[next_ptr++].new_ptr = buf; 5973 return (buf); 5974 } 5975 5976 void 5977 zcfree(voidpf opaque, voidpf ptr) 5978 { 5979 int n; 5980 if (*(ush*)&ptr != 0) { /* object < 64K */ 5981 farfree(ptr); 5982 return; 5983 } 5984 /* Find the original pointer */ 5985 for (n = 0; n < next_ptr; n++) { 5986 if (ptr != table[n].new_ptr) 5987 continue; 5988 5989 farfree(table[n].org_ptr); 5990 while (++n < next_ptr) { 5991 table[n-1] = table[n]; 5992 } 5993 next_ptr--; 5994 return; 5995 } 5996 ptr = opaque; /* just to make some compilers happy */ 5997 Assert(0, "zcfree: ptr not found"); 5998 } 5999 #endif 6000 #endif /* __TURBOC__ */ 6001 6002 6003 #if defined(M_I86) && !defined(__32BIT__) 6004 /* Microsoft C in 16-bit mode */ 6005 6006 #define MY_ZCALLOC 6007 6008 #if (!defined(_MSC_VER) || (_MSC_VER <= 600)) 6009 #define _halloc halloc 6010 #define _hfree hfree 6011 #endif 6012 6013 voidpf 6014 zcalloc(voidpf opaque, unsigned items, unsigned size) 6015 { 6016 if (opaque) opaque = 0; /* to make compiler happy */ 6017 return (_halloc((long)items, size)); 6018 } 6019 6020 void 6021 zcfree(voidpf opaque, voidpf ptr) 6022 { 6023 if (opaque) opaque = 0; /* to make compiler happy */ 6024 _hfree(ptr); 6025 } 6026 6027 #endif /* MSC */ 6028 6029 6030 #ifndef MY_ZCALLOC /* Any system without a special alloc function */ 6031 6032 #ifndef STDC 6033 extern voidp calloc OF((uInt items, uInt size)); 6034 extern void free OF((voidpf ptr)); 6035 #endif 6036 6037 voidpf 6038 zcalloc(opaque, items, size) 6039 voidpf opaque; 6040 unsigned items; 6041 unsigned size; 6042 { 6043 if (opaque) items += size - size; /* make compiler happy */ 6044 return ((voidpf)calloc(items, size)); 6045 } 6046 6047 /*ARGSUSED*/ 6048 void 6049 zcfree(opaque, ptr) 6050 voidpf opaque; 6051 voidpf ptr; 6052 { 6053 free(ptr); 6054 } 6055 6056 #endif /* MY_ZCALLOC */ 6057 /* --- zutil.c */ 6058 6059 /* +++ adler32.c */ 6060 /* 6061 * adler32.c -- compute the Adler-32 checksum of a data stream 6062 * Copyright (C) 1995-1998 Mark Adler 6063 * For conditions of distribution and use, see copyright notice in zlib.h 6064 */ 6065 6066 /* From: adler32.c,v 1.10 1996/05/22 11:52:18 me Exp $ */ 6067 6068 /* #include "zlib.h" */ 6069 6070 #define BASE 65521L /* largest prime smaller than 65536 */ 6071 #define NMAX 5552 6072 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ 6073 6074 #define DO1(buf, i) {s1 += buf[i]; s2 += s1; } 6075 #define DO2(buf, i) DO1(buf, i); DO1(buf, i+1); 6076 #define DO4(buf, i) DO2(buf, i); DO2(buf, i+2); 6077 #define DO8(buf, i) DO4(buf, i); DO4(buf, i+4); 6078 #define DO16(buf) DO8(buf, 0); DO8(buf, 8); 6079 6080 /* ========================================================================= */ 6081 uLong 6082 adler32(adler, buf, len) 6083 uLong adler; 6084 const Bytef *buf; 6085 uInt len; 6086 { 6087 unsigned long s1 = adler & 0xffff; 6088 unsigned long s2 = (adler >> 16) & 0xffff; 6089 int k; 6090 6091 if (buf == Z_NULL) 6092 return (1L); 6093 6094 while (len > 0) { 6095 k = len < NMAX ? len : NMAX; 6096 len -= k; 6097 while (k >= 16) { 6098 DO16(buf); 6099 buf += 16; 6100 k -= 16; 6101 } 6102 if (k != 0) do { 6103 s1 += *buf++; 6104 s2 += s1; 6105 } while (--k); 6106 s1 %= BASE; 6107 s2 %= BASE; 6108 } 6109 return ((s2 << 16) | s1); 6110 } 6111 /* --- adler32.c */ 6112