1 /* +++ deflate.c */ 2 /* deflate.c -- compress data using the deflation algorithm 3 * Copyright (C) 1995-1996 Jean-loup Gailly. 4 * For conditions of distribution and use, see copyright notice in zlib.h 5 */ 6 7 /* 8 * ALGORITHM 9 * 10 * The "deflation" process depends on being able to identify portions 11 * of the input text which are identical to earlier input (within a 12 * sliding window trailing behind the input currently being processed). 13 * 14 * The most straightforward technique turns out to be the fastest for 15 * most input files: try all possible matches and select the longest. 16 * The key feature of this algorithm is that insertions into the string 17 * dictionary are very simple and thus fast, and deletions are avoided 18 * completely. Insertions are performed at each input character, whereas 19 * string matches are performed only when the previous match ends. So it 20 * is preferable to spend more time in matches to allow very fast string 21 * insertions and avoid deletions. The matching algorithm for small 22 * strings is inspired from that of Rabin & Karp. A brute force approach 23 * is used to find longer strings when a small match has been found. 24 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze 25 * (by Leonid Broukhis). 26 * A previous version of this file used a more sophisticated algorithm 27 * (by Fiala and Greene) which is guaranteed to run in linear amortized 28 * time, but has a larger average cost, uses more memory and is patented. 29 * However the F&G algorithm may be faster for some highly redundant 30 * files if the parameter max_chain_length (described below) is too large. 31 * 32 * ACKNOWLEDGEMENTS 33 * 34 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and 35 * I found it in 'freeze' written by Leonid Broukhis. 36 * Thanks to many people for bug reports and testing. 37 * 38 * REFERENCES 39 * 40 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". 41 * Available in ftp://ds.internic.net/rfc/rfc1951.txt 42 * 43 * A description of the Rabin and Karp algorithm is given in the book 44 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. 45 * 46 * Fiala,E.R., and Greene,D.H. 47 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 48 * 49 */ 50 51 #include <linux/module.h> 52 #include <linux/zutil.h> 53 #include "defutil.h" 54 55 /* architecture-specific bits */ 56 #ifdef CONFIG_ZLIB_DFLTCC 57 # include "../zlib_dfltcc/dfltcc_deflate.h" 58 #else 59 #define DEFLATE_RESET_HOOK(strm) do {} while (0) 60 #define DEFLATE_HOOK(strm, flush, bstate) 0 61 #define DEFLATE_NEED_CHECKSUM(strm) 1 62 #define DEFLATE_DFLTCC_ENABLED() 0 63 #endif 64 65 /* =========================================================================== 66 * Function prototypes. 67 */ 68 69 typedef block_state (*compress_func) (deflate_state *s, int flush); 70 /* Compression function. Returns the block state after the call. */ 71 72 static void fill_window (deflate_state *s); 73 static block_state deflate_stored (deflate_state *s, int flush); 74 static block_state deflate_fast (deflate_state *s, int flush); 75 static block_state deflate_slow (deflate_state *s, int flush); 76 static void lm_init (deflate_state *s); 77 static void putShortMSB (deflate_state *s, uInt b); 78 static int read_buf (z_streamp strm, Byte *buf, unsigned size); 79 static uInt longest_match (deflate_state *s, IPos cur_match); 80 81 #ifdef DEBUG_ZLIB 82 static void check_match (deflate_state *s, IPos start, IPos match, 83 int length); 84 #endif 85 86 /* =========================================================================== 87 * Local data 88 */ 89 90 #define NIL 0 91 /* Tail of hash chains */ 92 93 #ifndef TOO_FAR 94 # define TOO_FAR 4096 95 #endif 96 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ 97 98 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) 99 /* Minimum amount of lookahead, except at the end of the input file. 100 * See deflate.c for comments about the MIN_MATCH+1. 101 */ 102 103 /* Workspace to be allocated for deflate processing */ 104 typedef struct deflate_workspace { 105 /* State memory for the deflator */ 106 deflate_state deflate_memory; 107 #ifdef CONFIG_ZLIB_DFLTCC 108 /* State memory for s390 hardware deflate */ 109 struct dfltcc_deflate_state dfltcc_memory; 110 #endif 111 Byte *window_memory; 112 Pos *prev_memory; 113 Pos *head_memory; 114 char *overlay_memory; 115 } deflate_workspace; 116 117 #ifdef CONFIG_ZLIB_DFLTCC 118 /* dfltcc_state must be doubleword aligned for DFLTCC call */ 119 static_assert(offsetof(struct deflate_workspace, dfltcc_memory) % 8 == 0); 120 #endif 121 122 /* Values for max_lazy_match, good_match and max_chain_length, depending on 123 * the desired pack level (0..9). The values given below have been tuned to 124 * exclude worst case performance for pathological files. Better values may be 125 * found for specific files. 126 */ 127 typedef struct config_s { 128 ush good_length; /* reduce lazy search above this match length */ 129 ush max_lazy; /* do not perform lazy search above this match length */ 130 ush nice_length; /* quit search above this match length */ 131 ush max_chain; 132 compress_func func; 133 } config; 134 135 static const config configuration_table[10] = { 136 /* good lazy nice chain */ 137 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ 138 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */ 139 /* 2 */ {4, 5, 16, 8, deflate_fast}, 140 /* 3 */ {4, 6, 32, 32, deflate_fast}, 141 142 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ 143 /* 5 */ {8, 16, 32, 32, deflate_slow}, 144 /* 6 */ {8, 16, 128, 128, deflate_slow}, 145 /* 7 */ {8, 32, 128, 256, deflate_slow}, 146 /* 8 */ {32, 128, 258, 1024, deflate_slow}, 147 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */ 148 149 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 150 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different 151 * meaning. 152 */ 153 154 /* =========================================================================== 155 * Update a hash value with the given input byte 156 * IN assertion: all calls to UPDATE_HASH are made with consecutive 157 * input characters, so that a running hash key can be computed from the 158 * previous key instead of complete recalculation each time. 159 */ 160 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) 161 162 163 /* =========================================================================== 164 * Insert string str in the dictionary and set match_head to the previous head 165 * of the hash chain (the most recent string with same hash key). Return 166 * the previous length of the hash chain. 167 * IN assertion: all calls to INSERT_STRING are made with consecutive 168 * input characters and the first MIN_MATCH bytes of str are valid 169 * (except for the last MIN_MATCH-1 bytes of the input file). 170 */ 171 #define INSERT_STRING(s, str, match_head) \ 172 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ 173 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \ 174 s->head[s->ins_h] = (Pos)(str)) 175 176 /* =========================================================================== 177 * Initialize the hash table (avoiding 64K overflow for 16 bit systems). 178 * prev[] will be initialized on the fly. 179 */ 180 #define CLEAR_HASH(s) \ 181 s->head[s->hash_size-1] = NIL; \ 182 memset((char *)s->head, 0, (unsigned)(s->hash_size-1)*sizeof(*s->head)); 183 184 /* ========================================================================= */ 185 int zlib_deflateInit2( 186 z_streamp strm, 187 int level, 188 int method, 189 int windowBits, 190 int memLevel, 191 int strategy 192 ) 193 { 194 deflate_state *s; 195 int noheader = 0; 196 deflate_workspace *mem; 197 char *next; 198 199 ush *overlay; 200 /* We overlay pending_buf and d_buf+l_buf. This works since the average 201 * output size for (length,distance) codes is <= 24 bits. 202 */ 203 204 if (strm == NULL) return Z_STREAM_ERROR; 205 206 strm->msg = NULL; 207 208 if (level == Z_DEFAULT_COMPRESSION) level = 6; 209 210 mem = (deflate_workspace *) strm->workspace; 211 212 if (windowBits < 0) { /* undocumented feature: suppress zlib header */ 213 noheader = 1; 214 windowBits = -windowBits; 215 } 216 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || 217 windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || 218 strategy < 0 || strategy > Z_HUFFMAN_ONLY) { 219 return Z_STREAM_ERROR; 220 } 221 222 /* 223 * Direct the workspace's pointers to the chunks that were allocated 224 * along with the deflate_workspace struct. 225 */ 226 next = (char *) mem; 227 next += sizeof(*mem); 228 #ifdef CONFIG_ZLIB_DFLTCC 229 /* 230 * DFLTCC requires the window to be page aligned. 231 * Thus, we overallocate and take the aligned portion of the buffer. 232 */ 233 mem->window_memory = (Byte *) PTR_ALIGN(next, PAGE_SIZE); 234 #else 235 mem->window_memory = (Byte *) next; 236 #endif 237 next += zlib_deflate_window_memsize(windowBits); 238 mem->prev_memory = (Pos *) next; 239 next += zlib_deflate_prev_memsize(windowBits); 240 mem->head_memory = (Pos *) next; 241 next += zlib_deflate_head_memsize(memLevel); 242 mem->overlay_memory = next; 243 244 s = (deflate_state *) &(mem->deflate_memory); 245 strm->state = (struct internal_state *)s; 246 s->strm = strm; 247 248 s->noheader = noheader; 249 s->w_bits = windowBits; 250 s->w_size = 1 << s->w_bits; 251 s->w_mask = s->w_size - 1; 252 253 s->hash_bits = memLevel + 7; 254 s->hash_size = 1 << s->hash_bits; 255 s->hash_mask = s->hash_size - 1; 256 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); 257 258 s->window = (Byte *) mem->window_memory; 259 s->prev = (Pos *) mem->prev_memory; 260 s->head = (Pos *) mem->head_memory; 261 262 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ 263 264 overlay = (ush *) mem->overlay_memory; 265 s->pending_buf = (uch *) overlay; 266 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); 267 268 s->d_buf = overlay + s->lit_bufsize/sizeof(ush); 269 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; 270 271 s->level = level; 272 s->strategy = strategy; 273 s->method = (Byte)method; 274 275 return zlib_deflateReset(strm); 276 } 277 278 /* ========================================================================= */ 279 int zlib_deflateReset( 280 z_streamp strm 281 ) 282 { 283 deflate_state *s; 284 285 if (strm == NULL || strm->state == NULL) 286 return Z_STREAM_ERROR; 287 288 strm->total_in = strm->total_out = 0; 289 strm->msg = NULL; 290 strm->data_type = Z_UNKNOWN; 291 292 s = (deflate_state *)strm->state; 293 s->pending = 0; 294 s->pending_out = s->pending_buf; 295 296 if (s->noheader < 0) { 297 s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */ 298 } 299 s->status = s->noheader ? BUSY_STATE : INIT_STATE; 300 strm->adler = 1; 301 s->last_flush = Z_NO_FLUSH; 302 303 zlib_tr_init(s); 304 lm_init(s); 305 306 DEFLATE_RESET_HOOK(strm); 307 308 return Z_OK; 309 } 310 311 /* ========================================================================= 312 * Put a short in the pending buffer. The 16-bit value is put in MSB order. 313 * IN assertion: the stream state is correct and there is enough room in 314 * pending_buf. 315 */ 316 static void putShortMSB( 317 deflate_state *s, 318 uInt b 319 ) 320 { 321 put_byte(s, (Byte)(b >> 8)); 322 put_byte(s, (Byte)(b & 0xff)); 323 } 324 325 /* ========================================================================= */ 326 int zlib_deflate( 327 z_streamp strm, 328 int flush 329 ) 330 { 331 int old_flush; /* value of flush param for previous deflate call */ 332 deflate_state *s; 333 334 if (strm == NULL || strm->state == NULL || 335 flush > Z_FINISH || flush < 0) { 336 return Z_STREAM_ERROR; 337 } 338 s = (deflate_state *) strm->state; 339 340 if ((strm->next_in == NULL && strm->avail_in != 0) || 341 (s->status == FINISH_STATE && flush != Z_FINISH)) { 342 return Z_STREAM_ERROR; 343 } 344 if (strm->avail_out == 0) return Z_BUF_ERROR; 345 346 s->strm = strm; /* just in case */ 347 old_flush = s->last_flush; 348 s->last_flush = flush; 349 350 /* Write the zlib header */ 351 if (s->status == INIT_STATE) { 352 353 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; 354 uInt level_flags = (s->level-1) >> 1; 355 356 if (level_flags > 3) level_flags = 3; 357 header |= (level_flags << 6); 358 if (s->strstart != 0) header |= PRESET_DICT; 359 header += 31 - (header % 31); 360 361 s->status = BUSY_STATE; 362 putShortMSB(s, header); 363 364 /* Save the adler32 of the preset dictionary: */ 365 if (s->strstart != 0) { 366 putShortMSB(s, (uInt)(strm->adler >> 16)); 367 putShortMSB(s, (uInt)(strm->adler & 0xffff)); 368 } 369 strm->adler = 1L; 370 } 371 372 /* Flush as much pending output as possible */ 373 if (s->pending != 0) { 374 flush_pending(strm); 375 if (strm->avail_out == 0) { 376 /* Since avail_out is 0, deflate will be called again with 377 * more output space, but possibly with both pending and 378 * avail_in equal to zero. There won't be anything to do, 379 * but this is not an error situation so make sure we 380 * return OK instead of BUF_ERROR at next call of deflate: 381 */ 382 s->last_flush = -1; 383 return Z_OK; 384 } 385 386 /* Make sure there is something to do and avoid duplicate consecutive 387 * flushes. For repeated and useless calls with Z_FINISH, we keep 388 * returning Z_STREAM_END instead of Z_BUFF_ERROR. 389 */ 390 } else if (strm->avail_in == 0 && flush <= old_flush && 391 flush != Z_FINISH) { 392 return Z_BUF_ERROR; 393 } 394 395 /* User must not provide more input after the first FINISH: */ 396 if (s->status == FINISH_STATE && strm->avail_in != 0) { 397 return Z_BUF_ERROR; 398 } 399 400 /* Start a new block or continue the current one. 401 */ 402 if (strm->avail_in != 0 || s->lookahead != 0 || 403 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { 404 block_state bstate; 405 406 bstate = DEFLATE_HOOK(strm, flush, &bstate) ? bstate : 407 (*(configuration_table[s->level].func))(s, flush); 408 409 if (bstate == finish_started || bstate == finish_done) { 410 s->status = FINISH_STATE; 411 } 412 if (bstate == need_more || bstate == finish_started) { 413 if (strm->avail_out == 0) { 414 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ 415 } 416 return Z_OK; 417 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call 418 * of deflate should use the same flush parameter to make sure 419 * that the flush is complete. So we don't have to output an 420 * empty block here, this will be done at next call. This also 421 * ensures that for a very small output buffer, we emit at most 422 * one empty block. 423 */ 424 } 425 if (bstate == block_done) { 426 if (flush == Z_PARTIAL_FLUSH) { 427 zlib_tr_align(s); 428 } else if (flush == Z_PACKET_FLUSH) { 429 /* Output just the 3-bit `stored' block type value, 430 but not a zero length. */ 431 zlib_tr_stored_type_only(s); 432 } else { /* FULL_FLUSH or SYNC_FLUSH */ 433 zlib_tr_stored_block(s, (char*)0, 0L, 0); 434 /* For a full flush, this empty block will be recognized 435 * as a special marker by inflate_sync(). 436 */ 437 if (flush == Z_FULL_FLUSH) { 438 CLEAR_HASH(s); /* forget history */ 439 } 440 } 441 flush_pending(strm); 442 if (strm->avail_out == 0) { 443 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ 444 return Z_OK; 445 } 446 } 447 } 448 Assert(strm->avail_out > 0, "bug2"); 449 450 if (flush != Z_FINISH) return Z_OK; 451 452 if (!s->noheader) { 453 /* Write zlib trailer (adler32) */ 454 putShortMSB(s, (uInt)(strm->adler >> 16)); 455 putShortMSB(s, (uInt)(strm->adler & 0xffff)); 456 } 457 flush_pending(strm); 458 /* If avail_out is zero, the application will call deflate again 459 * to flush the rest. 460 */ 461 if (!s->noheader) { 462 s->noheader = -1; /* write the trailer only once! */ 463 } 464 if (s->pending == 0) { 465 Assert(s->bi_valid == 0, "bi_buf not flushed"); 466 return Z_STREAM_END; 467 } 468 return Z_OK; 469 } 470 471 /* ========================================================================= */ 472 int zlib_deflateEnd( 473 z_streamp strm 474 ) 475 { 476 int status; 477 deflate_state *s; 478 479 if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR; 480 s = (deflate_state *) strm->state; 481 482 status = s->status; 483 if (status != INIT_STATE && status != BUSY_STATE && 484 status != FINISH_STATE) { 485 return Z_STREAM_ERROR; 486 } 487 488 strm->state = NULL; 489 490 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; 491 } 492 493 /* =========================================================================== 494 * Read a new buffer from the current input stream, update the adler32 495 * and total number of bytes read. All deflate() input goes through 496 * this function so some applications may wish to modify it to avoid 497 * allocating a large strm->next_in buffer and copying from it. 498 * (See also flush_pending()). 499 */ 500 static int read_buf( 501 z_streamp strm, 502 Byte *buf, 503 unsigned size 504 ) 505 { 506 unsigned len = strm->avail_in; 507 508 if (len > size) len = size; 509 if (len == 0) return 0; 510 511 strm->avail_in -= len; 512 513 if (!DEFLATE_NEED_CHECKSUM(strm)) {} 514 else if (!((deflate_state *)(strm->state))->noheader) { 515 strm->adler = zlib_adler32(strm->adler, strm->next_in, len); 516 } 517 memcpy(buf, strm->next_in, len); 518 strm->next_in += len; 519 strm->total_in += len; 520 521 return (int)len; 522 } 523 524 /* =========================================================================== 525 * Initialize the "longest match" routines for a new zlib stream 526 */ 527 static void lm_init( 528 deflate_state *s 529 ) 530 { 531 s->window_size = (ulg)2L*s->w_size; 532 533 CLEAR_HASH(s); 534 535 /* Set the default configuration parameters: 536 */ 537 s->max_lazy_match = configuration_table[s->level].max_lazy; 538 s->good_match = configuration_table[s->level].good_length; 539 s->nice_match = configuration_table[s->level].nice_length; 540 s->max_chain_length = configuration_table[s->level].max_chain; 541 542 s->strstart = 0; 543 s->block_start = 0L; 544 s->lookahead = 0; 545 s->match_length = s->prev_length = MIN_MATCH-1; 546 s->match_available = 0; 547 s->ins_h = 0; 548 } 549 550 /* =========================================================================== 551 * Set match_start to the longest match starting at the given string and 552 * return its length. Matches shorter or equal to prev_length are discarded, 553 * in which case the result is equal to prev_length and match_start is 554 * garbage. 555 * IN assertions: cur_match is the head of the hash chain for the current 556 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 557 * OUT assertion: the match length is not greater than s->lookahead. 558 */ 559 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or 560 * match.S. The code will be functionally equivalent. 561 */ 562 static uInt longest_match( 563 deflate_state *s, 564 IPos cur_match /* current match */ 565 ) 566 { 567 unsigned chain_length = s->max_chain_length;/* max hash chain length */ 568 register Byte *scan = s->window + s->strstart; /* current string */ 569 register Byte *match; /* matched string */ 570 register int len; /* length of current match */ 571 int best_len = s->prev_length; /* best match length so far */ 572 int nice_match = s->nice_match; /* stop if match long enough */ 573 IPos limit = s->strstart > (IPos)MAX_DIST(s) ? 574 s->strstart - (IPos)MAX_DIST(s) : NIL; 575 /* Stop when cur_match becomes <= limit. To simplify the code, 576 * we prevent matches with the string of window index 0. 577 */ 578 Pos *prev = s->prev; 579 uInt wmask = s->w_mask; 580 581 #ifdef UNALIGNED_OK 582 /* Compare two bytes at a time. Note: this is not always beneficial. 583 * Try with and without -DUNALIGNED_OK to check. 584 */ 585 register Byte *strend = s->window + s->strstart + MAX_MATCH - 1; 586 register ush scan_start = *(ush*)scan; 587 register ush scan_end = *(ush*)(scan+best_len-1); 588 #else 589 register Byte *strend = s->window + s->strstart + MAX_MATCH; 590 register Byte scan_end1 = scan[best_len-1]; 591 register Byte scan_end = scan[best_len]; 592 #endif 593 594 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. 595 * It is easy to get rid of this optimization if necessary. 596 */ 597 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); 598 599 /* Do not waste too much time if we already have a good match: */ 600 if (s->prev_length >= s->good_match) { 601 chain_length >>= 2; 602 } 603 /* Do not look for matches beyond the end of the input. This is necessary 604 * to make deflate deterministic. 605 */ 606 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; 607 608 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); 609 610 do { 611 Assert(cur_match < s->strstart, "no future"); 612 match = s->window + cur_match; 613 614 /* Skip to next match if the match length cannot increase 615 * or if the match length is less than 2: 616 */ 617 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) 618 /* This code assumes sizeof(unsigned short) == 2. Do not use 619 * UNALIGNED_OK if your compiler uses a different size. 620 */ 621 if (*(ush*)(match+best_len-1) != scan_end || 622 *(ush*)match != scan_start) continue; 623 624 /* It is not necessary to compare scan[2] and match[2] since they are 625 * always equal when the other bytes match, given that the hash keys 626 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at 627 * strstart+3, +5, ... up to strstart+257. We check for insufficient 628 * lookahead only every 4th comparison; the 128th check will be made 629 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is 630 * necessary to put more guard bytes at the end of the window, or 631 * to check more often for insufficient lookahead. 632 */ 633 Assert(scan[2] == match[2], "scan[2]?"); 634 scan++, match++; 635 do { 636 } while (*(ush*)(scan+=2) == *(ush*)(match+=2) && 637 *(ush*)(scan+=2) == *(ush*)(match+=2) && 638 *(ush*)(scan+=2) == *(ush*)(match+=2) && 639 *(ush*)(scan+=2) == *(ush*)(match+=2) && 640 scan < strend); 641 /* The funny "do {}" generates better code on most compilers */ 642 643 /* Here, scan <= window+strstart+257 */ 644 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 645 if (*scan == *match) scan++; 646 647 len = (MAX_MATCH - 1) - (int)(strend-scan); 648 scan = strend - (MAX_MATCH-1); 649 650 #else /* UNALIGNED_OK */ 651 652 if (match[best_len] != scan_end || 653 match[best_len-1] != scan_end1 || 654 *match != *scan || 655 *++match != scan[1]) continue; 656 657 /* The check at best_len-1 can be removed because it will be made 658 * again later. (This heuristic is not always a win.) 659 * It is not necessary to compare scan[2] and match[2] since they 660 * are always equal when the other bytes match, given that 661 * the hash keys are equal and that HASH_BITS >= 8. 662 */ 663 scan += 2, match++; 664 Assert(*scan == *match, "match[2]?"); 665 666 /* We check for insufficient lookahead only every 8th comparison; 667 * the 256th check will be made at strstart+258. 668 */ 669 do { 670 } while (*++scan == *++match && *++scan == *++match && 671 *++scan == *++match && *++scan == *++match && 672 *++scan == *++match && *++scan == *++match && 673 *++scan == *++match && *++scan == *++match && 674 scan < strend); 675 676 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 677 678 len = MAX_MATCH - (int)(strend - scan); 679 scan = strend - MAX_MATCH; 680 681 #endif /* UNALIGNED_OK */ 682 683 if (len > best_len) { 684 s->match_start = cur_match; 685 best_len = len; 686 if (len >= nice_match) break; 687 #ifdef UNALIGNED_OK 688 scan_end = *(ush*)(scan+best_len-1); 689 #else 690 scan_end1 = scan[best_len-1]; 691 scan_end = scan[best_len]; 692 #endif 693 } 694 } while ((cur_match = prev[cur_match & wmask]) > limit 695 && --chain_length != 0); 696 697 if ((uInt)best_len <= s->lookahead) return best_len; 698 return s->lookahead; 699 } 700 701 #ifdef DEBUG_ZLIB 702 /* =========================================================================== 703 * Check that the match at match_start is indeed a match. 704 */ 705 static void check_match( 706 deflate_state *s, 707 IPos start, 708 IPos match, 709 int length 710 ) 711 { 712 /* check that the match is indeed a match */ 713 if (memcmp((char *)s->window + match, (char *)s->window + start, length)) { 714 fprintf(stderr, " start %u, match %u, length %d\n", 715 start, match, length); 716 do { 717 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); 718 } while (--length != 0); 719 z_error("invalid match"); 720 } 721 if (z_verbose > 1) { 722 fprintf(stderr,"\\[%d,%d]", start-match, length); 723 do { putc(s->window[start++], stderr); } while (--length != 0); 724 } 725 } 726 #else 727 # define check_match(s, start, match, length) 728 #endif 729 730 /* =========================================================================== 731 * Fill the window when the lookahead becomes insufficient. 732 * Updates strstart and lookahead. 733 * 734 * IN assertion: lookahead < MIN_LOOKAHEAD 735 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD 736 * At least one byte has been read, or avail_in == 0; reads are 737 * performed for at least two bytes (required for the zip translate_eol 738 * option -- not supported here). 739 */ 740 static void fill_window( 741 deflate_state *s 742 ) 743 { 744 register unsigned n, m; 745 register Pos *p; 746 unsigned more; /* Amount of free space at the end of the window. */ 747 uInt wsize = s->w_size; 748 749 do { 750 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); 751 752 /* Deal with !@#$% 64K limit: */ 753 if (more == 0 && s->strstart == 0 && s->lookahead == 0) { 754 more = wsize; 755 756 } else if (more == (unsigned)(-1)) { 757 /* Very unlikely, but possible on 16 bit machine if strstart == 0 758 * and lookahead == 1 (input done one byte at time) 759 */ 760 more--; 761 762 /* If the window is almost full and there is insufficient lookahead, 763 * move the upper half to the lower one to make room in the upper half. 764 */ 765 } else if (s->strstart >= wsize+MAX_DIST(s)) { 766 767 memcpy((char *)s->window, (char *)s->window+wsize, 768 (unsigned)wsize); 769 s->match_start -= wsize; 770 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ 771 s->block_start -= (long) wsize; 772 773 /* Slide the hash table (could be avoided with 32 bit values 774 at the expense of memory usage). We slide even when level == 0 775 to keep the hash table consistent if we switch back to level > 0 776 later. (Using level 0 permanently is not an optimal usage of 777 zlib, so we don't care about this pathological case.) 778 */ 779 n = s->hash_size; 780 p = &s->head[n]; 781 do { 782 m = *--p; 783 *p = (Pos)(m >= wsize ? m-wsize : NIL); 784 } while (--n); 785 786 n = wsize; 787 p = &s->prev[n]; 788 do { 789 m = *--p; 790 *p = (Pos)(m >= wsize ? m-wsize : NIL); 791 /* If n is not on any hash chain, prev[n] is garbage but 792 * its value will never be used. 793 */ 794 } while (--n); 795 more += wsize; 796 } 797 if (s->strm->avail_in == 0) return; 798 799 /* If there was no sliding: 800 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && 801 * more == window_size - lookahead - strstart 802 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) 803 * => more >= window_size - 2*WSIZE + 2 804 * In the BIG_MEM or MMAP case (not yet supported), 805 * window_size == input_size + MIN_LOOKAHEAD && 806 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. 807 * Otherwise, window_size == 2*WSIZE so more >= 2. 808 * If there was sliding, more >= WSIZE. So in all cases, more >= 2. 809 */ 810 Assert(more >= 2, "more < 2"); 811 812 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); 813 s->lookahead += n; 814 815 /* Initialize the hash value now that we have some input: */ 816 if (s->lookahead >= MIN_MATCH) { 817 s->ins_h = s->window[s->strstart]; 818 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); 819 #if MIN_MATCH != 3 820 Call UPDATE_HASH() MIN_MATCH-3 more times 821 #endif 822 } 823 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, 824 * but this is not important since only literal bytes will be emitted. 825 */ 826 827 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); 828 } 829 830 /* =========================================================================== 831 * Flush the current block, with given end-of-file flag. 832 * IN assertion: strstart is set to the end of the current match. 833 */ 834 #define FLUSH_BLOCK_ONLY(s, eof) { \ 835 zlib_tr_flush_block(s, (s->block_start >= 0L ? \ 836 (char *)&s->window[(unsigned)s->block_start] : \ 837 NULL), \ 838 (ulg)((long)s->strstart - s->block_start), \ 839 (eof)); \ 840 s->block_start = s->strstart; \ 841 flush_pending(s->strm); \ 842 Tracev((stderr,"[FLUSH]")); \ 843 } 844 845 /* Same but force premature exit if necessary. */ 846 #define FLUSH_BLOCK(s, eof) { \ 847 FLUSH_BLOCK_ONLY(s, eof); \ 848 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ 849 } 850 851 /* =========================================================================== 852 * Copy without compression as much as possible from the input stream, return 853 * the current block state. 854 * This function does not insert new strings in the dictionary since 855 * uncompressible data is probably not useful. This function is used 856 * only for the level=0 compression option. 857 * NOTE: this function should be optimized to avoid extra copying from 858 * window to pending_buf. 859 */ 860 static block_state deflate_stored( 861 deflate_state *s, 862 int flush 863 ) 864 { 865 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited 866 * to pending_buf_size, and each stored block has a 5 byte header: 867 */ 868 ulg max_block_size = 0xffff; 869 ulg max_start; 870 871 if (max_block_size > s->pending_buf_size - 5) { 872 max_block_size = s->pending_buf_size - 5; 873 } 874 875 /* Copy as much as possible from input to output: */ 876 for (;;) { 877 /* Fill the window as much as possible: */ 878 if (s->lookahead <= 1) { 879 880 Assert(s->strstart < s->w_size+MAX_DIST(s) || 881 s->block_start >= (long)s->w_size, "slide too late"); 882 883 fill_window(s); 884 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; 885 886 if (s->lookahead == 0) break; /* flush the current block */ 887 } 888 Assert(s->block_start >= 0L, "block gone"); 889 890 s->strstart += s->lookahead; 891 s->lookahead = 0; 892 893 /* Emit a stored block if pending_buf will be full: */ 894 max_start = s->block_start + max_block_size; 895 if (s->strstart == 0 || (ulg)s->strstart >= max_start) { 896 /* strstart == 0 is possible when wraparound on 16-bit machine */ 897 s->lookahead = (uInt)(s->strstart - max_start); 898 s->strstart = (uInt)max_start; 899 FLUSH_BLOCK(s, 0); 900 } 901 /* Flush if we may have to slide, otherwise block_start may become 902 * negative and the data will be gone: 903 */ 904 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { 905 FLUSH_BLOCK(s, 0); 906 } 907 } 908 FLUSH_BLOCK(s, flush == Z_FINISH); 909 return flush == Z_FINISH ? finish_done : block_done; 910 } 911 912 /* =========================================================================== 913 * Compress as much as possible from the input stream, return the current 914 * block state. 915 * This function does not perform lazy evaluation of matches and inserts 916 * new strings in the dictionary only for unmatched strings or for short 917 * matches. It is used only for the fast compression options. 918 */ 919 static block_state deflate_fast( 920 deflate_state *s, 921 int flush 922 ) 923 { 924 IPos hash_head = NIL; /* head of the hash chain */ 925 int bflush; /* set if current block must be flushed */ 926 927 for (;;) { 928 /* Make sure that we always have enough lookahead, except 929 * at the end of the input file. We need MAX_MATCH bytes 930 * for the next match, plus MIN_MATCH bytes to insert the 931 * string following the next match. 932 */ 933 if (s->lookahead < MIN_LOOKAHEAD) { 934 fill_window(s); 935 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { 936 return need_more; 937 } 938 if (s->lookahead == 0) break; /* flush the current block */ 939 } 940 941 /* Insert the string window[strstart .. strstart+2] in the 942 * dictionary, and set hash_head to the head of the hash chain: 943 */ 944 if (s->lookahead >= MIN_MATCH) { 945 INSERT_STRING(s, s->strstart, hash_head); 946 } 947 948 /* Find the longest match, discarding those <= prev_length. 949 * At this point we have always match_length < MIN_MATCH 950 */ 951 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { 952 /* To simplify the code, we prevent matches with the string 953 * of window index 0 (in particular we have to avoid a match 954 * of the string with itself at the start of the input file). 955 */ 956 if (s->strategy != Z_HUFFMAN_ONLY) { 957 s->match_length = longest_match (s, hash_head); 958 } 959 /* longest_match() sets match_start */ 960 } 961 if (s->match_length >= MIN_MATCH) { 962 check_match(s, s->strstart, s->match_start, s->match_length); 963 964 bflush = zlib_tr_tally(s, s->strstart - s->match_start, 965 s->match_length - MIN_MATCH); 966 967 s->lookahead -= s->match_length; 968 969 /* Insert new strings in the hash table only if the match length 970 * is not too large. This saves time but degrades compression. 971 */ 972 if (s->match_length <= s->max_insert_length && 973 s->lookahead >= MIN_MATCH) { 974 s->match_length--; /* string at strstart already in hash table */ 975 do { 976 s->strstart++; 977 INSERT_STRING(s, s->strstart, hash_head); 978 /* strstart never exceeds WSIZE-MAX_MATCH, so there are 979 * always MIN_MATCH bytes ahead. 980 */ 981 } while (--s->match_length != 0); 982 s->strstart++; 983 } else { 984 s->strstart += s->match_length; 985 s->match_length = 0; 986 s->ins_h = s->window[s->strstart]; 987 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); 988 #if MIN_MATCH != 3 989 Call UPDATE_HASH() MIN_MATCH-3 more times 990 #endif 991 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not 992 * matter since it will be recomputed at next deflate call. 993 */ 994 } 995 } else { 996 /* No match, output a literal byte */ 997 Tracevv((stderr,"%c", s->window[s->strstart])); 998 bflush = zlib_tr_tally (s, 0, s->window[s->strstart]); 999 s->lookahead--; 1000 s->strstart++; 1001 } 1002 if (bflush) FLUSH_BLOCK(s, 0); 1003 } 1004 FLUSH_BLOCK(s, flush == Z_FINISH); 1005 return flush == Z_FINISH ? finish_done : block_done; 1006 } 1007 1008 /* =========================================================================== 1009 * Same as above, but achieves better compression. We use a lazy 1010 * evaluation for matches: a match is finally adopted only if there is 1011 * no better match at the next window position. 1012 */ 1013 static block_state deflate_slow( 1014 deflate_state *s, 1015 int flush 1016 ) 1017 { 1018 IPos hash_head = NIL; /* head of hash chain */ 1019 int bflush; /* set if current block must be flushed */ 1020 1021 /* Process the input block. */ 1022 for (;;) { 1023 /* Make sure that we always have enough lookahead, except 1024 * at the end of the input file. We need MAX_MATCH bytes 1025 * for the next match, plus MIN_MATCH bytes to insert the 1026 * string following the next match. 1027 */ 1028 if (s->lookahead < MIN_LOOKAHEAD) { 1029 fill_window(s); 1030 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { 1031 return need_more; 1032 } 1033 if (s->lookahead == 0) break; /* flush the current block */ 1034 } 1035 1036 /* Insert the string window[strstart .. strstart+2] in the 1037 * dictionary, and set hash_head to the head of the hash chain: 1038 */ 1039 if (s->lookahead >= MIN_MATCH) { 1040 INSERT_STRING(s, s->strstart, hash_head); 1041 } 1042 1043 /* Find the longest match, discarding those <= prev_length. 1044 */ 1045 s->prev_length = s->match_length, s->prev_match = s->match_start; 1046 s->match_length = MIN_MATCH-1; 1047 1048 if (hash_head != NIL && s->prev_length < s->max_lazy_match && 1049 s->strstart - hash_head <= MAX_DIST(s)) { 1050 /* To simplify the code, we prevent matches with the string 1051 * of window index 0 (in particular we have to avoid a match 1052 * of the string with itself at the start of the input file). 1053 */ 1054 if (s->strategy != Z_HUFFMAN_ONLY) { 1055 s->match_length = longest_match (s, hash_head); 1056 } 1057 /* longest_match() sets match_start */ 1058 1059 if (s->match_length <= 5 && (s->strategy == Z_FILTERED || 1060 (s->match_length == MIN_MATCH && 1061 s->strstart - s->match_start > TOO_FAR))) { 1062 1063 /* If prev_match is also MIN_MATCH, match_start is garbage 1064 * but we will ignore the current match anyway. 1065 */ 1066 s->match_length = MIN_MATCH-1; 1067 } 1068 } 1069 /* If there was a match at the previous step and the current 1070 * match is not better, output the previous match: 1071 */ 1072 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { 1073 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; 1074 /* Do not insert strings in hash table beyond this. */ 1075 1076 check_match(s, s->strstart-1, s->prev_match, s->prev_length); 1077 1078 bflush = zlib_tr_tally(s, s->strstart -1 - s->prev_match, 1079 s->prev_length - MIN_MATCH); 1080 1081 /* Insert in hash table all strings up to the end of the match. 1082 * strstart-1 and strstart are already inserted. If there is not 1083 * enough lookahead, the last two strings are not inserted in 1084 * the hash table. 1085 */ 1086 s->lookahead -= s->prev_length-1; 1087 s->prev_length -= 2; 1088 do { 1089 if (++s->strstart <= max_insert) { 1090 INSERT_STRING(s, s->strstart, hash_head); 1091 } 1092 } while (--s->prev_length != 0); 1093 s->match_available = 0; 1094 s->match_length = MIN_MATCH-1; 1095 s->strstart++; 1096 1097 if (bflush) FLUSH_BLOCK(s, 0); 1098 1099 } else if (s->match_available) { 1100 /* If there was no match at the previous position, output a 1101 * single literal. If there was a match but the current match 1102 * is longer, truncate the previous match to a single literal. 1103 */ 1104 Tracevv((stderr,"%c", s->window[s->strstart-1])); 1105 if (zlib_tr_tally (s, 0, s->window[s->strstart-1])) { 1106 FLUSH_BLOCK_ONLY(s, 0); 1107 } 1108 s->strstart++; 1109 s->lookahead--; 1110 if (s->strm->avail_out == 0) return need_more; 1111 } else { 1112 /* There is no previous match to compare with, wait for 1113 * the next step to decide. 1114 */ 1115 s->match_available = 1; 1116 s->strstart++; 1117 s->lookahead--; 1118 } 1119 } 1120 Assert (flush != Z_NO_FLUSH, "no flush?"); 1121 if (s->match_available) { 1122 Tracevv((stderr,"%c", s->window[s->strstart-1])); 1123 zlib_tr_tally (s, 0, s->window[s->strstart-1]); 1124 s->match_available = 0; 1125 } 1126 FLUSH_BLOCK(s, flush == Z_FINISH); 1127 return flush == Z_FINISH ? finish_done : block_done; 1128 } 1129 1130 int zlib_deflate_workspacesize(int windowBits, int memLevel) 1131 { 1132 if (windowBits < 0) /* undocumented feature: suppress zlib header */ 1133 windowBits = -windowBits; 1134 1135 /* Since the return value is typically passed to vmalloc() unchecked... */ 1136 BUG_ON(memLevel < 1 || memLevel > MAX_MEM_LEVEL || windowBits < 9 || 1137 windowBits > 15); 1138 1139 return sizeof(deflate_workspace) 1140 + zlib_deflate_window_memsize(windowBits) 1141 + zlib_deflate_prev_memsize(windowBits) 1142 + zlib_deflate_head_memsize(memLevel) 1143 + zlib_deflate_overlay_memsize(memLevel); 1144 } 1145 1146 int zlib_deflate_dfltcc_enabled(void) 1147 { 1148 return DEFLATE_DFLTCC_ENABLED(); 1149 } 1150