1 /////////////////////////////////////////////////////////////////////////////// 2 // 3 /// \file lz_encoder.c 4 /// \brief LZ in window 5 /// 6 // Authors: Igor Pavlov 7 // Lasse Collin 8 // 9 // This file has been put into the public domain. 10 // You can do whatever you want with this file. 11 // 12 /////////////////////////////////////////////////////////////////////////////// 13 14 #include "lz_encoder.h" 15 #include "lz_encoder_hash.h" 16 17 // See lz_encoder_hash.h. This is a bit hackish but avoids making 18 // endianness a conditional in makefiles. 19 #if defined(WORDS_BIGENDIAN) && !defined(HAVE_SMALL) 20 # include "lz_encoder_hash_table.h" 21 #endif 22 23 #include "memcmplen.h" 24 25 26 typedef struct { 27 /// LZ-based encoder e.g. LZMA 28 lzma_lz_encoder lz; 29 30 /// History buffer and match finder 31 lzma_mf mf; 32 33 /// Next coder in the chain 34 lzma_next_coder next; 35 } lzma_coder; 36 37 38 /// \brief Moves the data in the input window to free space for new data 39 /// 40 /// mf->buffer is a sliding input window, which keeps mf->keep_size_before 41 /// bytes of input history available all the time. Now and then we need to 42 /// "slide" the buffer to make space for the new data to the end of the 43 /// buffer. At the same time, data older than keep_size_before is dropped. 44 /// 45 static void 46 move_window(lzma_mf *mf) 47 { 48 // Align the move to a multiple of 16 bytes. Some LZ-based encoders 49 // like LZMA use the lowest bits of mf->read_pos to know the 50 // alignment of the uncompressed data. We also get better speed 51 // for memmove() with aligned buffers. 52 assert(mf->read_pos > mf->keep_size_before); 53 const uint32_t move_offset 54 = (mf->read_pos - mf->keep_size_before) & ~UINT32_C(15); 55 56 assert(mf->write_pos > move_offset); 57 const size_t move_size = mf->write_pos - move_offset; 58 59 assert(move_offset + move_size <= mf->size); 60 61 memmove(mf->buffer, mf->buffer + move_offset, move_size); 62 63 mf->offset += move_offset; 64 mf->read_pos -= move_offset; 65 mf->read_limit -= move_offset; 66 mf->write_pos -= move_offset; 67 68 return; 69 } 70 71 72 /// \brief Tries to fill the input window (mf->buffer) 73 /// 74 /// If we are the last encoder in the chain, our input data is in in[]. 75 /// Otherwise we call the next filter in the chain to process in[] and 76 /// write its output to mf->buffer. 77 /// 78 /// This function must not be called once it has returned LZMA_STREAM_END. 79 /// 80 static lzma_ret 81 fill_window(lzma_coder *coder, const lzma_allocator *allocator, 82 const uint8_t *in, size_t *in_pos, size_t in_size, 83 lzma_action action) 84 { 85 assert(coder->mf.read_pos <= coder->mf.write_pos); 86 87 // Move the sliding window if needed. 88 if (coder->mf.read_pos >= coder->mf.size - coder->mf.keep_size_after) 89 move_window(&coder->mf); 90 91 // Maybe this is ugly, but lzma_mf uses uint32_t for most things 92 // (which I find cleanest), but we need size_t here when filling 93 // the history window. 94 size_t write_pos = coder->mf.write_pos; 95 lzma_ret ret; 96 if (coder->next.code == NULL) { 97 // Not using a filter, simply memcpy() as much as possible. 98 lzma_bufcpy(in, in_pos, in_size, coder->mf.buffer, 99 &write_pos, coder->mf.size); 100 101 ret = action != LZMA_RUN && *in_pos == in_size 102 ? LZMA_STREAM_END : LZMA_OK; 103 104 } else { 105 ret = coder->next.code(coder->next.coder, allocator, 106 in, in_pos, in_size, 107 coder->mf.buffer, &write_pos, 108 coder->mf.size, action); 109 } 110 111 coder->mf.write_pos = write_pos; 112 113 // Silence Valgrind. lzma_memcmplen() can read extra bytes 114 // and Valgrind will give warnings if those bytes are uninitialized 115 // because Valgrind cannot see that the values of the uninitialized 116 // bytes are eventually ignored. 117 memzero(coder->mf.buffer + write_pos, LZMA_MEMCMPLEN_EXTRA); 118 119 // If end of stream has been reached or flushing completed, we allow 120 // the encoder to process all the input (that is, read_pos is allowed 121 // to reach write_pos). Otherwise we keep keep_size_after bytes 122 // available as prebuffer. 123 if (ret == LZMA_STREAM_END) { 124 assert(*in_pos == in_size); 125 ret = LZMA_OK; 126 coder->mf.action = action; 127 coder->mf.read_limit = coder->mf.write_pos; 128 129 } else if (coder->mf.write_pos > coder->mf.keep_size_after) { 130 // This needs to be done conditionally, because if we got 131 // only little new input, there may be too little input 132 // to do any encoding yet. 133 coder->mf.read_limit = coder->mf.write_pos 134 - coder->mf.keep_size_after; 135 } 136 137 // Restart the match finder after finished LZMA_SYNC_FLUSH. 138 if (coder->mf.pending > 0 139 && coder->mf.read_pos < coder->mf.read_limit) { 140 // Match finder may update coder->pending and expects it to 141 // start from zero, so use a temporary variable. 142 const uint32_t pending = coder->mf.pending; 143 coder->mf.pending = 0; 144 145 // Rewind read_pos so that the match finder can hash 146 // the pending bytes. 147 assert(coder->mf.read_pos >= pending); 148 coder->mf.read_pos -= pending; 149 150 // Call the skip function directly instead of using 151 // mf_skip(), since we don't want to touch mf->read_ahead. 152 coder->mf.skip(&coder->mf, pending); 153 } 154 155 return ret; 156 } 157 158 159 static lzma_ret 160 lz_encode(void *coder_ptr, const lzma_allocator *allocator, 161 const uint8_t *restrict in, size_t *restrict in_pos, 162 size_t in_size, 163 uint8_t *restrict out, size_t *restrict out_pos, 164 size_t out_size, lzma_action action) 165 { 166 lzma_coder *coder = coder_ptr; 167 168 while (*out_pos < out_size 169 && (*in_pos < in_size || action != LZMA_RUN)) { 170 // Read more data to coder->mf.buffer if needed. 171 if (coder->mf.action == LZMA_RUN && coder->mf.read_pos 172 >= coder->mf.read_limit) 173 return_if_error(fill_window(coder, allocator, 174 in, in_pos, in_size, action)); 175 176 // Encode 177 const lzma_ret ret = coder->lz.code(coder->lz.coder, 178 &coder->mf, out, out_pos, out_size); 179 if (ret != LZMA_OK) { 180 // Setting this to LZMA_RUN for cases when we are 181 // flushing. It doesn't matter when finishing or if 182 // an error occurred. 183 coder->mf.action = LZMA_RUN; 184 return ret; 185 } 186 } 187 188 return LZMA_OK; 189 } 190 191 192 static bool 193 lz_encoder_prepare(lzma_mf *mf, const lzma_allocator *allocator, 194 const lzma_lz_options *lz_options) 195 { 196 // For now, the dictionary size is limited to 1.5 GiB. This may grow 197 // in the future if needed, but it needs a little more work than just 198 // changing this check. 199 if (!IS_ENC_DICT_SIZE_VALID(lz_options->dict_size) 200 || lz_options->nice_len > lz_options->match_len_max) 201 return true; 202 203 mf->keep_size_before = lz_options->before_size + lz_options->dict_size; 204 205 mf->keep_size_after = lz_options->after_size 206 + lz_options->match_len_max; 207 208 // To avoid constant memmove()s, allocate some extra space. Since 209 // memmove()s become more expensive when the size of the buffer 210 // increases, we reserve more space when a large dictionary is 211 // used to make the memmove() calls rarer. 212 // 213 // This works with dictionaries up to about 3 GiB. If bigger 214 // dictionary is wanted, some extra work is needed: 215 // - Several variables in lzma_mf have to be changed from uint32_t 216 // to size_t. 217 // - Memory usage calculation needs something too, e.g. use uint64_t 218 // for mf->size. 219 uint32_t reserve = lz_options->dict_size / 2; 220 if (reserve > (UINT32_C(1) << 30)) 221 reserve /= 2; 222 223 reserve += (lz_options->before_size + lz_options->match_len_max 224 + lz_options->after_size) / 2 + (UINT32_C(1) << 19); 225 226 const uint32_t old_size = mf->size; 227 mf->size = mf->keep_size_before + reserve + mf->keep_size_after; 228 229 // Deallocate the old history buffer if it exists but has different 230 // size than what is needed now. 231 if (mf->buffer != NULL && old_size != mf->size) { 232 lzma_free(mf->buffer, allocator); 233 mf->buffer = NULL; 234 } 235 236 // Match finder options 237 mf->match_len_max = lz_options->match_len_max; 238 mf->nice_len = lz_options->nice_len; 239 240 // cyclic_size has to stay smaller than 2 Gi. Note that this doesn't 241 // mean limiting dictionary size to less than 2 GiB. With a match 242 // finder that uses multibyte resolution (hashes start at e.g. every 243 // fourth byte), cyclic_size would stay below 2 Gi even when 244 // dictionary size is greater than 2 GiB. 245 // 246 // It would be possible to allow cyclic_size >= 2 Gi, but then we 247 // would need to be careful to use 64-bit types in various places 248 // (size_t could do since we would need bigger than 32-bit address 249 // space anyway). It would also require either zeroing a multigigabyte 250 // buffer at initialization (waste of time and RAM) or allow 251 // normalization in lz_encoder_mf.c to access uninitialized 252 // memory to keep the code simpler. The current way is simple and 253 // still allows pretty big dictionaries, so I don't expect these 254 // limits to change. 255 mf->cyclic_size = lz_options->dict_size + 1; 256 257 // Validate the match finder ID and setup the function pointers. 258 switch (lz_options->match_finder) { 259 #ifdef HAVE_MF_HC3 260 case LZMA_MF_HC3: 261 mf->find = &lzma_mf_hc3_find; 262 mf->skip = &lzma_mf_hc3_skip; 263 break; 264 #endif 265 #ifdef HAVE_MF_HC4 266 case LZMA_MF_HC4: 267 mf->find = &lzma_mf_hc4_find; 268 mf->skip = &lzma_mf_hc4_skip; 269 break; 270 #endif 271 #ifdef HAVE_MF_BT2 272 case LZMA_MF_BT2: 273 mf->find = &lzma_mf_bt2_find; 274 mf->skip = &lzma_mf_bt2_skip; 275 break; 276 #endif 277 #ifdef HAVE_MF_BT3 278 case LZMA_MF_BT3: 279 mf->find = &lzma_mf_bt3_find; 280 mf->skip = &lzma_mf_bt3_skip; 281 break; 282 #endif 283 #ifdef HAVE_MF_BT4 284 case LZMA_MF_BT4: 285 mf->find = &lzma_mf_bt4_find; 286 mf->skip = &lzma_mf_bt4_skip; 287 break; 288 #endif 289 290 default: 291 return true; 292 } 293 294 // Calculate the sizes of mf->hash and mf->son. 295 // 296 // NOTE: Since 5.3.5beta the LZMA encoder ensures that nice_len 297 // is big enough for the selected match finder. This makes it 298 // easier for applications as nice_len = 2 will always be accepted 299 // even though the effective value can be slightly bigger. 300 const uint32_t hash_bytes 301 = mf_get_hash_bytes(lz_options->match_finder); 302 assert(hash_bytes <= mf->nice_len); 303 304 const bool is_bt = (lz_options->match_finder & 0x10) != 0; 305 uint32_t hs; 306 307 if (hash_bytes == 2) { 308 hs = 0xFFFF; 309 } else { 310 // Round dictionary size up to the next 2^n - 1 so it can 311 // be used as a hash mask. 312 hs = lz_options->dict_size - 1; 313 hs |= hs >> 1; 314 hs |= hs >> 2; 315 hs |= hs >> 4; 316 hs |= hs >> 8; 317 hs >>= 1; 318 hs |= 0xFFFF; 319 320 if (hs > (UINT32_C(1) << 24)) { 321 if (hash_bytes == 3) 322 hs = (UINT32_C(1) << 24) - 1; 323 else 324 hs >>= 1; 325 } 326 } 327 328 mf->hash_mask = hs; 329 330 ++hs; 331 if (hash_bytes > 2) 332 hs += HASH_2_SIZE; 333 if (hash_bytes > 3) 334 hs += HASH_3_SIZE; 335 /* 336 No match finder uses this at the moment. 337 if (mf->hash_bytes > 4) 338 hs += HASH_4_SIZE; 339 */ 340 341 const uint32_t old_hash_count = mf->hash_count; 342 const uint32_t old_sons_count = mf->sons_count; 343 mf->hash_count = hs; 344 mf->sons_count = mf->cyclic_size; 345 if (is_bt) 346 mf->sons_count *= 2; 347 348 // Deallocate the old hash array if it exists and has different size 349 // than what is needed now. 350 if (old_hash_count != mf->hash_count 351 || old_sons_count != mf->sons_count) { 352 lzma_free(mf->hash, allocator); 353 mf->hash = NULL; 354 355 lzma_free(mf->son, allocator); 356 mf->son = NULL; 357 } 358 359 // Maximum number of match finder cycles 360 mf->depth = lz_options->depth; 361 if (mf->depth == 0) { 362 if (is_bt) 363 mf->depth = 16 + mf->nice_len / 2; 364 else 365 mf->depth = 4 + mf->nice_len / 4; 366 } 367 368 return false; 369 } 370 371 372 static bool 373 lz_encoder_init(lzma_mf *mf, const lzma_allocator *allocator, 374 const lzma_lz_options *lz_options) 375 { 376 // Allocate the history buffer. 377 if (mf->buffer == NULL) { 378 // lzma_memcmplen() is used for the dictionary buffer 379 // so we need to allocate a few extra bytes to prevent 380 // it from reading past the end of the buffer. 381 mf->buffer = lzma_alloc(mf->size + LZMA_MEMCMPLEN_EXTRA, 382 allocator); 383 if (mf->buffer == NULL) 384 return true; 385 386 // Keep Valgrind happy with lzma_memcmplen() and initialize 387 // the extra bytes whose value may get read but which will 388 // effectively get ignored. 389 memzero(mf->buffer + mf->size, LZMA_MEMCMPLEN_EXTRA); 390 } 391 392 // Use cyclic_size as initial mf->offset. This allows 393 // avoiding a few branches in the match finders. The downside is 394 // that match finder needs to be normalized more often, which may 395 // hurt performance with huge dictionaries. 396 mf->offset = mf->cyclic_size; 397 mf->read_pos = 0; 398 mf->read_ahead = 0; 399 mf->read_limit = 0; 400 mf->write_pos = 0; 401 mf->pending = 0; 402 403 #if UINT32_MAX >= SIZE_MAX / 4 404 // Check for integer overflow. (Huge dictionaries are not 405 // possible on 32-bit CPU.) 406 if (mf->hash_count > SIZE_MAX / sizeof(uint32_t) 407 || mf->sons_count > SIZE_MAX / sizeof(uint32_t)) 408 return true; 409 #endif 410 411 // Allocate and initialize the hash table. Since EMPTY_HASH_VALUE 412 // is zero, we can use lzma_alloc_zero() or memzero() for mf->hash. 413 // 414 // We don't need to initialize mf->son, but not doing that may 415 // make Valgrind complain in normalization (see normalize() in 416 // lz_encoder_mf.c). Skipping the initialization is *very* good 417 // when big dictionary is used but only small amount of data gets 418 // actually compressed: most of the mf->son won't get actually 419 // allocated by the kernel, so we avoid wasting RAM and improve 420 // initialization speed a lot. 421 if (mf->hash == NULL) { 422 mf->hash = lzma_alloc_zero(mf->hash_count * sizeof(uint32_t), 423 allocator); 424 mf->son = lzma_alloc(mf->sons_count * sizeof(uint32_t), 425 allocator); 426 427 if (mf->hash == NULL || mf->son == NULL) { 428 lzma_free(mf->hash, allocator); 429 mf->hash = NULL; 430 431 lzma_free(mf->son, allocator); 432 mf->son = NULL; 433 434 return true; 435 } 436 } else { 437 /* 438 for (uint32_t i = 0; i < mf->hash_count; ++i) 439 mf->hash[i] = EMPTY_HASH_VALUE; 440 */ 441 memzero(mf->hash, mf->hash_count * sizeof(uint32_t)); 442 } 443 444 mf->cyclic_pos = 0; 445 446 // Handle preset dictionary. 447 if (lz_options->preset_dict != NULL 448 && lz_options->preset_dict_size > 0) { 449 // If the preset dictionary is bigger than the actual 450 // dictionary, use only the tail. 451 mf->write_pos = my_min(lz_options->preset_dict_size, mf->size); 452 memcpy(mf->buffer, lz_options->preset_dict 453 + lz_options->preset_dict_size - mf->write_pos, 454 mf->write_pos); 455 mf->action = LZMA_SYNC_FLUSH; 456 mf->skip(mf, mf->write_pos); 457 } 458 459 mf->action = LZMA_RUN; 460 461 return false; 462 } 463 464 465 extern uint64_t 466 lzma_lz_encoder_memusage(const lzma_lz_options *lz_options) 467 { 468 // Old buffers must not exist when calling lz_encoder_prepare(). 469 lzma_mf mf = { 470 .buffer = NULL, 471 .hash = NULL, 472 .son = NULL, 473 .hash_count = 0, 474 .sons_count = 0, 475 }; 476 477 // Setup the size information into mf. 478 if (lz_encoder_prepare(&mf, NULL, lz_options)) 479 return UINT64_MAX; 480 481 // Calculate the memory usage. 482 return ((uint64_t)(mf.hash_count) + mf.sons_count) * sizeof(uint32_t) 483 + mf.size + sizeof(lzma_coder); 484 } 485 486 487 static void 488 lz_encoder_end(void *coder_ptr, const lzma_allocator *allocator) 489 { 490 lzma_coder *coder = coder_ptr; 491 492 lzma_next_end(&coder->next, allocator); 493 494 lzma_free(coder->mf.son, allocator); 495 lzma_free(coder->mf.hash, allocator); 496 lzma_free(coder->mf.buffer, allocator); 497 498 if (coder->lz.end != NULL) 499 coder->lz.end(coder->lz.coder, allocator); 500 else 501 lzma_free(coder->lz.coder, allocator); 502 503 lzma_free(coder, allocator); 504 return; 505 } 506 507 508 static lzma_ret 509 lz_encoder_update(void *coder_ptr, const lzma_allocator *allocator, 510 const lzma_filter *filters_null lzma_attribute((__unused__)), 511 const lzma_filter *reversed_filters) 512 { 513 lzma_coder *coder = coder_ptr; 514 515 if (coder->lz.options_update == NULL) 516 return LZMA_PROG_ERROR; 517 518 return_if_error(coder->lz.options_update( 519 coder->lz.coder, reversed_filters)); 520 521 return lzma_next_filter_update( 522 &coder->next, allocator, reversed_filters + 1); 523 } 524 525 526 static lzma_ret 527 lz_encoder_set_out_limit(void *coder_ptr, uint64_t *uncomp_size, 528 uint64_t out_limit) 529 { 530 lzma_coder *coder = coder_ptr; 531 532 // This is supported only if there are no other filters chained. 533 if (coder->next.code == NULL && coder->lz.set_out_limit != NULL) 534 return coder->lz.set_out_limit( 535 coder->lz.coder, uncomp_size, out_limit); 536 537 return LZMA_OPTIONS_ERROR; 538 } 539 540 541 extern lzma_ret 542 lzma_lz_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator, 543 const lzma_filter_info *filters, 544 lzma_ret (*lz_init)(lzma_lz_encoder *lz, 545 const lzma_allocator *allocator, 546 lzma_vli id, const void *options, 547 lzma_lz_options *lz_options)) 548 { 549 #if defined(HAVE_SMALL) && !defined(HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR) 550 // We need that the CRC32 table has been initialized. 551 lzma_crc32_init(); 552 #endif 553 554 // Allocate and initialize the base data structure. 555 lzma_coder *coder = next->coder; 556 if (coder == NULL) { 557 coder = lzma_alloc(sizeof(lzma_coder), allocator); 558 if (coder == NULL) 559 return LZMA_MEM_ERROR; 560 561 next->coder = coder; 562 next->code = &lz_encode; 563 next->end = &lz_encoder_end; 564 next->update = &lz_encoder_update; 565 next->set_out_limit = &lz_encoder_set_out_limit; 566 567 coder->lz.coder = NULL; 568 coder->lz.code = NULL; 569 coder->lz.end = NULL; 570 571 // mf.size is initialized to silence Valgrind 572 // when used on optimized binaries (GCC may reorder 573 // code in a way that Valgrind gets unhappy). 574 coder->mf.buffer = NULL; 575 coder->mf.size = 0; 576 coder->mf.hash = NULL; 577 coder->mf.son = NULL; 578 coder->mf.hash_count = 0; 579 coder->mf.sons_count = 0; 580 581 coder->next = LZMA_NEXT_CODER_INIT; 582 } 583 584 // Initialize the LZ-based encoder. 585 lzma_lz_options lz_options; 586 return_if_error(lz_init(&coder->lz, allocator, 587 filters[0].id, filters[0].options, &lz_options)); 588 589 // Setup the size information into coder->mf and deallocate 590 // old buffers if they have wrong size. 591 if (lz_encoder_prepare(&coder->mf, allocator, &lz_options)) 592 return LZMA_OPTIONS_ERROR; 593 594 // Allocate new buffers if needed, and do the rest of 595 // the initialization. 596 if (lz_encoder_init(&coder->mf, allocator, &lz_options)) 597 return LZMA_MEM_ERROR; 598 599 // Initialize the next filter in the chain, if any. 600 return lzma_next_filter_init(&coder->next, allocator, filters + 1); 601 } 602 603 604 extern LZMA_API(lzma_bool) 605 lzma_mf_is_supported(lzma_match_finder mf) 606 { 607 switch (mf) { 608 #ifdef HAVE_MF_HC3 609 case LZMA_MF_HC3: 610 return true; 611 #endif 612 #ifdef HAVE_MF_HC4 613 case LZMA_MF_HC4: 614 return true; 615 #endif 616 #ifdef HAVE_MF_BT2 617 case LZMA_MF_BT2: 618 return true; 619 #endif 620 #ifdef HAVE_MF_BT3 621 case LZMA_MF_BT3: 622 return true; 623 #endif 624 #ifdef HAVE_MF_BT4 625 case LZMA_MF_BT4: 626 return true; 627 #endif 628 default: 629 return false; 630 } 631 } 632