4 * A decompressor for the LZMS compression format.
8 * Copyright (C) 2013 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your option)
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with wimlib; if not, see http://www.gnu.org/licenses/.
27 * This is a decompressor for the LZMS compression format used by Microsoft.
28 * This format is not documented, but it is one of the formats supported by the
29 * compression API available in Windows 8, and as of Windows 8 it is one of the
30 * formats that can be used in WIM files.
32 * This decompressor only implements "raw" decompression, which decompresses a
33 * single LZMS-compressed block. This behavior is the same as that of
34 * Decompress() in the Windows 8 compression API when using a compression handle
35 * created with CreateDecompressor() with the Algorithm parameter specified as
36 * COMPRESS_ALGORITHM_LZMS | COMPRESS_RAW. Presumably, non-raw LZMS data
37 * is a container format from which the locations and sizes (both compressed and
38 * uncompressed) of the constituent blocks can be determined.
40 * A LZMS-compressed block must be read in 16-bit little endian units from both
41 * directions. One logical bitstream starts at the front of the block and
42 * proceeds forwards. Another logical bitstream starts at the end of the block
43 * and proceeds backwards. Bits read from the forwards bitstream constitute
44 * range-encoded data, whereas bits read from the backwards bitstream constitute
45 * Huffman-encoded symbols or verbatim bits. For both bitstreams, the ordering
46 * of the bits within the 16-bit coding units is such that the first bit is the
47 * high-order bit and the last bit is the low-order bit.
49 * From these two logical bitstreams, an LZMS decompressor can reconstitute the
50 * series of items that make up the LZMS data representation. Each such item
51 * may be a literal byte or a match. Matches may be either traditional LZ77
52 * matches or "delta" matches, either of which can have its offset encoded
53 * explicitly or encoded via a reference to a recently used (repeat) offset.
55 * A traditional LZ match consists of a length and offset; it asserts that the
56 * sequence of bytes beginning at the current position and extending for the
57 * length is exactly equal to the equal-length sequence of bytes at the offset
58 * back in the window. On the other hand, a delta match consists of a length,
59 * raw offset, and power. It asserts that the sequence of bytes beginning at
60 * the current position and extending for the length is equal to the bytewise
61 * sum of the two equal-length sequences of bytes (2**power) and (raw_offset *
62 * 2**power) bytes before the current position, minus bytewise the sequence of
63 * bytes beginning at (2**power + raw_offset * 2**power) bytes before the
64 * current position. Although not generally as useful as traditional LZ
65 * matches, delta matches can be helpful on some types of data. Both LZ and
66 * delta matches may overlap with the current position; in fact, the minimum
67 * offset is 1, regardless of match length.
69 * For LZ matches, up to 3 repeat offsets are allowed, similar to some other
70 * LZ-based formats such as LZX and LZMA. They must updated in a LRU fashion,
71 * except for a quirk: updates to the queue must be delayed by one LZMS item,
72 * except for the removal of a repeat match. As a result, 4 entries are
73 * actually needed in the queue, even though it is only possible to decode
74 * references to the first 3 at any given time. The queue must be initialized
75 * to the offsets {1, 2, 3, 4}.
77 * Repeat delta matches are handled similarly, but for them there are two queues
78 * updated in lock-step: one for powers and one for raw offsets. The power
79 * queue must be initialized to {0, 0, 0, 0}, and the raw offset queue must be
80 * initialized to {1, 2, 3, 4}.
82 * Bits from the range decoder must be used to disambiguate item types. The
83 * range decoder must hold two state variables: the range, which must initially
84 * be set to 0xffffffff, and the current code, which must initially be set to
85 * the first 32 bits read from the forwards bitstream. The range must be
86 * maintained above 0xffff; when it falls below 0xffff, both the range and code
87 * must be left-shifted by 16 bits and the low 16 bits of the code must be
88 * filled in with the next 16 bits from the forwards bitstream.
90 * To decode each bit, the range decoder requires a probability that is
91 * logically a real number between 0 and 1. Multiplying this probability by the
92 * current range and taking the floor gives the bound between the 0-bit region
93 * of the range and the 1-bit region of the range. However, in LZMS,
94 * probabilities are restricted to values of n/64 where n is an integer is
95 * between 1 and 63 inclusively, so the implementation may use integer
96 * operations instead. Following calculation of the bound, if the current code
97 * is in the 0-bit region, the new range becomes the current code and the
98 * decoded bit is 0; otherwise, the bound must be subtracted from both the range
99 * and the code, and the decoded bit is 1. More information about range coding
100 * can be found at https://en.wikipedia.org/wiki/Range_encoding. Furthermore,
101 * note that the LZMA format also uses range coding and has public domain code
104 * The probability used to range-decode each bit must be taken from a table, of
105 * which one instance must exist for each distinct context in which a
106 * range-decoded bit is needed. At each call of the range decoder, the
107 * appropriate probability must be obtained by indexing the appropriate
108 * probability table with the last 4 (in the context disambiguating literals
109 * from matches), 5 (in the context disambiguating LZ matches from delta
110 * matches), or 6 (in all other contexts) bits recently range-decoded in that
111 * context, ordered such that the most recently decoded bit is the low-order bit
114 * Furthermore, each probability entry itself is variable, as its value must be
115 * maintained as n/64 where n is the number of 0 bits in the most recently
116 * decoded 64 bits with that same entry. This allows the compressed
117 * representation to adapt to the input and use fewer bits to represent the most
118 * likely data; note that LZMA uses a similar scheme. Initially, the most
119 * recently 64 decoded bits for each probability entry are assumed to be
120 * 0x0000000055555555 (high order to low order); therefore, all probabilities
121 * are initially 48/64. During the course of decoding, each probability may be
122 * updated to as low as 0/64 (as a result of reading many consecutive 1 bits
123 * with that entry) or as high as 64/64 (as a result of reading many consecutive
124 * 0 bits with that entry); however, probabilities of 0/64 and 64/64 cannot be
125 * used as-is but rather must be adjusted to 1/64 and 63/64, respectively,
126 * before being used for range decoding.
128 * Representations of the LZMS items themselves must be read from the backwards
129 * bitstream. For this, there are 5 different Huffman codes used:
131 * - The literal code, used for decoding literal bytes. Each of the 256
132 * symbols represents a literal byte. This code must be rebuilt whenever
133 * 1024 symbols have been decoded with it.
135 * - The LZ offset code, used for decoding the offsets of standard LZ77
136 * matches. Each symbol represents a position slot, which corresponds to a
137 * base value and some number of extra bits which must be read and added to
138 * the base value to reconstitute the full offset. The number of symbols in
139 * this code is the number of position slots needed to represent all possible
140 * offsets in the uncompressed block. This code must be rebuilt whenever
141 * 1024 symbols have been decoded with it.
143 * - The length code, used for decoding length symbols. Each of the 54 symbols
144 * represents a length slot, which corresponds to a base value and some
145 * number of extra bits which must be read and added to the base value to
146 * reconstitute the full length. This code must be rebuilt whenever 512
147 * symbols have been decoded with it.
149 * - The delta offset code, used for decoding the offsets of delta matches.
150 * Each symbol corresponds to a position slot, which corresponds to a base
151 * value and some number of extra bits which must be read and added to the
152 * base value to reconstitute the full offset. The number of symbols in this
153 * code is equal to the number of symbols in the LZ offset code. This code
154 * must be rebuilt whenever 1024 symbols have been decoded with it.
156 * - The delta power code, used for decoding the powers of delta matches. Each
157 * of the 8 symbols corresponds to a power. This code must be rebuilt
158 * whenever 512 symbols have been decoded with it.
160 * All the LZMS Huffman codes must be built adaptively based on symbol
161 * frequencies. Initially, each code must be built assuming that all symbols
162 * have equal frequency. Following that, each code must be rebuilt whenever a
163 * certain number of symbols has been decoded with it.
165 * In general, multiple valid Huffman codes can be constructed from a set of
166 * symbol frequencies. Like other compression formats such as XPRESS, LZX, and
167 * DEFLATE, the LZMS format solves this ambiguity by requiring that all Huffman
168 * codes be constructed in canonical form. This form requires that same-length
169 * codewords be lexicographically ordered the same way as the corresponding
170 * symbols and that all shorter codewords lexicographically precede longer
173 * Codewords in all the LZMS Huffman codes are limited to 15 bits. If the
174 * canonical code for a given set of symbol frequencies has any codewords longer
175 * than 15 bits, then all frequencies must be divided by 2, rounding up, and the
176 * code construction must be attempted again.
178 * A LZMS-compressed block seemingly cannot have a compressed size greater than
179 * or equal to the uncompressed size. In such cases the block must be stored
182 * After all LZMS items have been decoded, the data must be postprocessed to
183 * translate absolute address encoded in x86 instructions into their original
184 * relative addresses.
186 * Details omitted above can be found in the code. Note that in the absence of
187 * an official specification there is no guarantee that this decompressor
188 * handles all possible cases.
196 #include "wimlib/compress_common.h"
197 #include "wimlib/decompressor_ops.h"
198 #include "wimlib/decompress_common.h"
199 #include "wimlib/error.h"
200 #include "wimlib/lzms.h"
201 #include "wimlib/util.h"
206 #define LZMS_DECODE_TABLE_BITS 10
208 /* Structure used for range decoding, reading bits forwards. This is the first
209 * logical bitstream mentioned above. */
210 struct lzms_range_decoder_raw {
211 /* The relevant part of the current range. Although the logical range
212 * for range decoding is a very large integer, only a small portion
213 * matters at any given time, and it can be normalized (shifted left)
214 * whenever it gets too small. */
217 /* The current position in the range encoded by the portion of the input
221 /* Pointer to the next little-endian 16-bit integer in the compressed
222 * input data (reading forwards). */
225 /* Number of 16-bit integers remaining in the compressed input data
226 * (reading forwards). */
227 size_t num_le16_remaining;
230 /* Structure used for reading raw bits backwards. This is the second logical
231 * bitstream mentioned above. */
232 struct lzms_input_bitstream {
233 /* Holding variable for bits that have been read from the compressed
234 * data. The bits are ordered from high-order to low-order. */
235 /* XXX: Without special-case code to handle reading more than 17 bits
236 * at a time, this needs to be 64 bits rather than 32 bits. */
239 /* Number of bits in @bitbuf that are are used. */
240 unsigned num_filled_bits;
242 /* Pointer to the one past the next little-endian 16-bit integer in the
243 * compressed input data (reading backwards). */
246 /* Number of 16-bit integers remaining in the compressed input data
247 * (reading backwards). */
248 size_t num_le16_remaining;
251 /* Probability entry for use by the range decoder when in a specific state. */
252 struct lzms_probability_entry {
254 /* Number of zeroes in the most recent LZMS_PROBABILITY_MAX bits that
255 * have been decoded using this probability entry. This is a cached
256 * value because it can be computed as LZMS_PROBABILITY_MAX minus the
257 * Hamming weight of the low-order LZMS_PROBABILITY_MAX bits of
259 u32 num_recent_zero_bits;
261 /* The most recent LZMS_PROBABILITY_MAX bits that have been decoded
262 * using this probability entry. The size of this variable, in bits,
263 * must be at least LZMS_PROBABILITY_MAX. */
267 /* Structure used for range decoding. This wraps around `struct
268 * lzms_range_decoder_raw' to use and maintain probability entries. */
269 struct lzms_range_decoder {
270 /* Pointer to the raw range decoder, which has no persistent knowledge
271 * of probabilities. Multiple lzms_range_decoder's share the same
272 * lzms_range_decoder_raw. */
273 struct lzms_range_decoder_raw *rd;
275 /* Bits recently decoded by this range decoder. This are used as in
276 * index into @prob_entries. */
279 /* Bitmask for @state to prevent its value from exceeding the number of
280 * probability entries. */
283 /* Probability entries being used for this range decoder. */
284 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
287 /* Structure used for Huffman decoding, optionally using the decoded symbols as
288 * slots into a base table to determine how many extra bits need to be read to
289 * reconstitute the full value. */
290 struct lzms_huffman_decoder {
292 /* Bitstream to read Huffman-encoded symbols and verbatim bits from.
293 * Multiple lzms_huffman_decoder's share the same lzms_input_bitstream.
295 struct lzms_input_bitstream *is;
297 /* Pointer to the slot base table to use. It is indexed by the decoded
298 * Huffman symbol that specifies the slot. The entry specifies the base
299 * value to use, and the position of its high bit is the number of
300 * additional bits that must be read to reconstitute the full value.
302 * This member need not be set if only raw Huffman symbols are being
303 * read using this decoder. */
304 const u32 *slot_base_tab;
306 /* Number of symbols that have been read using this code far. Reset to
307 * 0 whenever the code is rebuilt. */
310 /* When @num_syms_read reaches this number, the Huffman code must be
314 /* Number of symbols in the represented Huffman code. */
317 /* Running totals of symbol frequencies. These are diluted slightly
318 * whenever the code is rebuilt. */
319 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
321 /* The length, in bits, of each symbol in the Huffman code. */
322 u8 lens[LZMS_MAX_NUM_SYMS];
324 /* The codeword of each symbol in the Huffman code. */
325 u16 codewords[LZMS_MAX_NUM_SYMS];
327 /* A table for quickly decoding symbols encoded using the Huffman code.
329 u16 decode_table[(1U << LZMS_DECODE_TABLE_BITS) + 2 * LZMS_MAX_NUM_SYMS]
330 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
333 /* State of the LZMS decompressor. */
334 struct lzms_decompressor {
336 /* Pointer to the beginning of the uncompressed data buffer. */
339 /* Pointer to the next position in the uncompressed data buffer. */
342 /* Pointer to one past the end of the uncompressed data buffer. */
345 /* Range decoder, which reads bits from the beginning of the compressed
346 * block, going forwards. */
347 struct lzms_range_decoder_raw rd;
349 /* Input bitstream, which reads from the end of the compressed block,
350 * going backwards. */
351 struct lzms_input_bitstream is;
353 /* Range decoders. */
354 struct lzms_range_decoder main_range_decoder;
355 struct lzms_range_decoder match_range_decoder;
356 struct lzms_range_decoder lz_match_range_decoder;
357 struct lzms_range_decoder lz_repeat_match_range_decoders[LZMS_NUM_RECENT_OFFSETS - 1];
358 struct lzms_range_decoder delta_match_range_decoder;
359 struct lzms_range_decoder delta_repeat_match_range_decoders[LZMS_NUM_RECENT_OFFSETS - 1];
361 /* Huffman decoders. */
362 struct lzms_huffman_decoder literal_decoder;
363 struct lzms_huffman_decoder lz_offset_decoder;
364 struct lzms_huffman_decoder length_decoder;
365 struct lzms_huffman_decoder delta_power_decoder;
366 struct lzms_huffman_decoder delta_offset_decoder;
368 /* LRU (least-recently-used) queue of LZ match offsets. */
369 u64 recent_lz_offsets[LZMS_NUM_RECENT_OFFSETS + 1];
371 /* LRU (least-recently-used) queue of delta match powers. */
372 u32 recent_delta_powers[LZMS_NUM_RECENT_OFFSETS + 1];
374 /* LRU (least-recently-used) queue of delta match offsets. */
375 u32 recent_delta_offsets[LZMS_NUM_RECENT_OFFSETS + 1];
377 /* These variables are used to delay updates to the LRU queues by one
380 u32 prev_delta_power;
381 u32 prev_delta_offset;
382 u32 upcoming_lz_offset;
383 u32 upcoming_delta_power;
384 u32 upcoming_delta_offset;
386 /* Used for postprocessing */
387 s32 last_target_usages[65536];
390 /* A table that maps position slots to their base values. These are constants
391 * computed at runtime by lzms_compute_slot_bases(). */
392 static u32 lzms_position_slot_base[LZMS_MAX_NUM_OFFSET_SYMS + 1];
394 /* A table that maps length slots to their base values. These are constants
395 * computed at runtime by lzms_compute_slot_bases(). */
396 static u32 lzms_length_slot_base[LZMS_NUM_LEN_SYMS + 1];
399 lzms_decode_delta_rle_slot_bases(u32 slot_bases[],
400 const u8 delta_run_lens[], size_t num_run_lens)
405 for (size_t i = 0; i < num_run_lens; i++) {
406 u8 run_len = delta_run_lens[i];
409 slot_bases[slot++] = base;
415 /* Initialize the global position and length slot tables. */
417 lzms_compute_slot_bases(void)
419 /* If an explicit formula that maps LZMS position and length slots to
420 * slot bases exists, then it could be used here. But until one is
421 * found, the following code fills in the slots using the observation
422 * that the increase from one slot base to the next is an increasing
423 * power of 2. Therefore, run-length encoding of the delta of adjacent
424 * entries can be used. */
425 static const u8 position_slot_delta_run_lens[] = {
426 9, 0, 9, 7, 10, 15, 15, 20,
427 20, 30, 33, 40, 42, 45, 60, 73,
431 static const u8 length_slot_delta_run_lens[] = {
432 27, 4, 6, 4, 5, 2, 1, 1,
433 1, 1, 1, 0, 0, 0, 0, 0,
437 lzms_decode_delta_rle_slot_bases(lzms_position_slot_base,
438 position_slot_delta_run_lens,
439 ARRAY_LEN(position_slot_delta_run_lens));
441 lzms_position_slot_base[LZMS_MAX_NUM_OFFSET_SYMS] = 0x7fffffff;
443 lzms_decode_delta_rle_slot_bases(lzms_length_slot_base,
444 length_slot_delta_run_lens,
445 ARRAY_LEN(length_slot_delta_run_lens));
447 lzms_length_slot_base[LZMS_NUM_LEN_SYMS] = 0x400108ab;
450 /* Initialize the global position length slot tables if not done so already. */
452 lzms_init_slot_bases(void)
454 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
455 static bool already_computed = false;
457 if (unlikely(!already_computed)) {
458 pthread_mutex_lock(&mutex);
459 if (!already_computed) {
460 lzms_compute_slot_bases();
461 already_computed = true;
463 pthread_mutex_unlock(&mutex);
467 /* Return the position slot for the specified offset. */
469 lzms_get_position_slot_raw(u32 offset)
471 u32 position_slot = 0;
472 while (lzms_position_slot_base[position_slot + 1] <= offset)
474 return position_slot;
477 /* Initialize the input bitstream @is to read forwards from the specified
478 * compressed data buffer @in that is @in_limit 16-bit integers long. */
480 lzms_input_bitstream_init(struct lzms_input_bitstream *is,
481 const le16 *in, size_t in_limit)
484 is->num_filled_bits = 0;
485 is->in = in + in_limit;
486 is->num_le16_remaining = in_limit;
489 /* Ensures that @num_bits bits are buffered in the input bitstream. */
491 lzms_input_bitstream_ensure_bits(struct lzms_input_bitstream *is,
494 while (is->num_filled_bits < num_bits) {
497 LZMS_ASSERT(is->num_filled_bits + 16 <= sizeof(is->bitbuf) * 8);
499 if (unlikely(is->num_le16_remaining == 0))
502 next = le16_to_cpu(*--is->in);
503 is->num_le16_remaining--;
505 is->bitbuf |= next << (sizeof(is->bitbuf) * 8 - is->num_filled_bits - 16);
506 is->num_filled_bits += 16;
512 /* Returns the next @num_bits bits that are buffered in the input bitstream. */
514 lzms_input_bitstream_peek_bits(struct lzms_input_bitstream *is,
517 LZMS_ASSERT(is->num_filled_bits >= num_bits);
518 return is->bitbuf >> (sizeof(is->bitbuf) * 8 - num_bits);
521 /* Removes the next @num_bits bits that are buffered in the input bitstream. */
523 lzms_input_bitstream_remove_bits(struct lzms_input_bitstream *is,
526 LZMS_ASSERT(is->num_filled_bits >= num_bits);
527 is->bitbuf <<= num_bits;
528 is->num_filled_bits -= num_bits;
531 /* Removes and returns the next @num_bits bits that are buffered in the input
534 lzms_input_bitstream_pop_bits(struct lzms_input_bitstream *is,
537 u32 bits = lzms_input_bitstream_peek_bits(is, num_bits);
538 lzms_input_bitstream_remove_bits(is, num_bits);
542 /* Reads the next @num_bits from the input bitstream. */
544 lzms_input_bitstream_read_bits(struct lzms_input_bitstream *is,
547 if (unlikely(lzms_input_bitstream_ensure_bits(is, num_bits)))
549 return lzms_input_bitstream_pop_bits(is, num_bits);
552 /* Initialize the range decoder @rd to read forwards from the specified
553 * compressed data buffer @in that is @in_limit 16-bit integers long. */
555 lzms_range_decoder_raw_init(struct lzms_range_decoder_raw *rd,
556 const le16 *in, size_t in_limit)
558 rd->range = 0xffffffff;
559 rd->code = ((u32)le16_to_cpu(in[0]) << 16) |
560 ((u32)le16_to_cpu(in[1]) << 0);
562 rd->num_le16_remaining = in_limit - 2;
565 /* Ensures the current range of the range decoder has at least 16 bits of
568 lzms_range_decoder_raw_normalize(struct lzms_range_decoder_raw *rd)
570 if (rd->range <= 0xffff) {
572 if (unlikely(rd->num_le16_remaining == 0))
574 rd->code = (rd->code << 16) | le16_to_cpu(*rd->in++);
575 rd->num_le16_remaining--;
580 /* Decode and return the next bit from the range decoder (raw version).
582 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0.
585 lzms_range_decoder_raw_decode_bit(struct lzms_range_decoder_raw *rd, u32 prob)
589 /* Ensure the range has at least 16 bits of precision. */
590 lzms_range_decoder_raw_normalize(rd);
592 /* Based on the probability, calculate the bound between the 0-bit
593 * region and the 1-bit region of the range. */
594 bound = (rd->range >> LZMS_PROBABILITY_BITS) * prob;
596 if (rd->code < bound) {
597 /* Current code is in the 0-bit region of the range. */
601 /* Current code is in the 1-bit region of the range. */
608 /* Decode and return the next bit from the range decoder. This wraps around
609 * lzms_range_decoder_raw_decode_bit() to handle using and updating the
610 * appropriate probability table. */
612 lzms_range_decode_bit(struct lzms_range_decoder *dec)
614 struct lzms_probability_entry *prob_entry;
618 /* Load the probability entry corresponding to the current state. */
619 prob_entry = &dec->prob_entries[dec->state];
621 /* Treat the number of zero bits in the most recently decoded
622 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
623 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
624 * don't allow 0% or 100% probabilities. */
625 prob = prob_entry->num_recent_zero_bits;
626 if (prob == LZMS_PROBABILITY_MAX)
627 prob = LZMS_PROBABILITY_MAX - 1;
631 /* Decode the next bit. */
632 bit = lzms_range_decoder_raw_decode_bit(dec->rd, prob);
634 /* Update the state based on the newly decoded bit. */
635 dec->state = (((dec->state << 1) | bit) & dec->mask);
637 /* Update the recent bits, including the cached count of 0's. */
638 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
640 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
641 /* Replacing 1 bit with 0 bit; increment the zero count.
643 prob_entry->num_recent_zero_bits++;
646 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
647 /* Replacing 0 bit with 1 bit; decrement the zero count.
649 prob_entry->num_recent_zero_bits--;
652 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
654 /* Return the decoded bit. */
659 /* Build the decoding table for a new adaptive Huffman code using the alphabet
660 * used in the specified Huffman decoder, with the symbol frequencies
663 lzms_rebuild_adaptive_huffman_code(struct lzms_huffman_decoder *dec)
667 /* XXX: This implementation makes use of code already implemented for
668 * the XPRESS and LZX compression formats. However, since for the
669 * adaptive codes used in LZMS we don't actually need the explicit codes
670 * themselves, only the decode tables, it may be possible to optimize
671 * this by somehow directly building or updating the Huffman decode
672 * table. This may be a worthwhile optimization because the adaptive
673 * codes change many times throughout a decompression run. */
674 LZMS_DEBUG("Rebuilding adaptive Huffman code (num_syms=%u)",
676 make_canonical_huffman_code(dec->num_syms, LZMS_MAX_CODEWORD_LEN,
677 dec->sym_freqs, dec->lens, dec->codewords);
678 ret = make_huffman_decode_table(dec->decode_table, dec->num_syms,
679 LZMS_DECODE_TABLE_BITS, dec->lens,
680 LZMS_MAX_CODEWORD_LEN);
681 LZMS_ASSERT(ret == 0);
684 /* Decode and return the next Huffman-encoded symbol from the LZMS-compressed
685 * block using the specified Huffman decoder. */
687 lzms_decode_huffman_symbol(struct lzms_huffman_decoder *dec)
689 const u8 *lens = dec->lens;
690 const u16 *decode_table = dec->decode_table;
691 struct lzms_input_bitstream *is = dec->is;
693 /* The Huffman codes used in LZMS are adaptive and must be rebuilt
694 * whenever a certain number of symbols have been read. Each such
695 * rebuild uses the current symbol frequencies, but the format also
696 * requires that the symbol frequencies be halved after each code
697 * rebuild. This diminishes the effect of old symbols on the current
698 * Huffman codes, thereby causing the Huffman codes to be more locally
700 if (dec->num_syms_read == dec->rebuild_freq) {
701 lzms_rebuild_adaptive_huffman_code(dec);
702 for (unsigned i = 0; i < dec->num_syms; i++) {
703 dec->sym_freqs[i] >>= 1;
704 dec->sym_freqs[i] += 1;
706 dec->num_syms_read = 0;
709 /* In the following Huffman decoding implementation, the first
710 * LZMS_DECODE_TABLE_BITS of the input are used as an offset into a
711 * decode table. The entry will either provide the decoded symbol
712 * directly, or else a "real" Huffman binary tree will be searched to
713 * decode the symbol. */
715 lzms_input_bitstream_ensure_bits(is, LZMS_MAX_CODEWORD_LEN);
717 u16 key_bits = lzms_input_bitstream_peek_bits(is, LZMS_DECODE_TABLE_BITS);
718 u16 sym = decode_table[key_bits];
720 if (sym < dec->num_syms) {
721 /* Fast case: The decode table directly provided the symbol. */
722 lzms_input_bitstream_remove_bits(is, lens[sym]);
724 /* Slow case: The symbol took too many bits to include directly
725 * in the decode table, so search for it in a binary tree at the
726 * end of the decode table. */
727 lzms_input_bitstream_remove_bits(is, LZMS_DECODE_TABLE_BITS);
729 key_bits = sym + lzms_input_bitstream_pop_bits(is, 1);
730 } while ((sym = decode_table[key_bits]) >= dec->num_syms);
733 /* Tally and return the decoded symbol. */
734 ++dec->sym_freqs[sym];
735 ++dec->num_syms_read;
739 /* Decode a number from the LZMS bitstream, encoded as a Huffman-encoded symbol
740 * specifying a "slot" (whose corresponding value is looked up in a static
741 * table) plus the number specified by a number of extra bits depending on the
744 lzms_decode_value(struct lzms_huffman_decoder *dec)
747 unsigned num_extra_bits;
750 /* Read the slot (position slot, length slot, etc.), which is encoded as
751 * a Huffman symbol. */
752 slot = lzms_decode_huffman_symbol(dec);
754 LZMS_ASSERT(dec->slot_base_tab != NULL);
756 /* Get the number of extra bits needed to represent the range of values
757 * that share the slot. */
758 num_extra_bits = bsr32(dec->slot_base_tab[slot + 1] -
759 dec->slot_base_tab[slot]);
761 /* Read the number of extra bits and add them to the slot to form the
762 * final decoded value. */
763 extra_bits = lzms_input_bitstream_read_bits(dec->is, num_extra_bits);
764 return dec->slot_base_tab[slot] + extra_bits;
767 /* Copy a literal to the output buffer. */
769 lzms_copy_literal(struct lzms_decompressor *ctx, u8 literal)
771 *ctx->out_next++ = literal;
775 /* Validate an LZ match and copy it to the output buffer. */
777 lzms_copy_lz_match(struct lzms_decompressor *ctx, u32 length, u32 offset)
782 if (length > ctx->out_end - ctx->out_next) {
783 LZMS_DEBUG("Match overrun!");
786 if (offset > ctx->out_next - ctx->out_begin) {
787 LZMS_DEBUG("Match underrun!");
791 out_next = ctx->out_next;
792 matchptr = out_next - offset;
794 *out_next++ = *matchptr++;
796 ctx->out_next = out_next;
800 /* Validate a delta match and copy it to the output buffer. */
802 lzms_copy_delta_match(struct lzms_decompressor *ctx, u32 length,
803 u32 power, u32 raw_offset)
805 u32 offset1 = 1U << power;
806 u32 offset2 = raw_offset << power;
807 u32 offset = offset1 + offset2;
813 if (length > ctx->out_end - ctx->out_next) {
814 LZMS_DEBUG("Match overrun!");
817 if (offset > ctx->out_next - ctx->out_begin) {
818 LZMS_DEBUG("Match underrun!");
822 out_next = ctx->out_next;
823 matchptr1 = out_next - offset1;
824 matchptr2 = out_next - offset2;
825 matchptr = out_next - offset;
828 *out_next++ = *matchptr1++ + *matchptr2++ - *matchptr++;
830 ctx->out_next = out_next;
834 /* Decode a (length, offset) pair from the input. */
836 lzms_decode_lz_match(struct lzms_decompressor *ctx)
841 /* Decode the match offset. The next range-encoded bit indicates
842 * whether it's a repeat offset or an explicit offset. */
844 bit = lzms_range_decode_bit(&ctx->lz_match_range_decoder);
846 /* Explicit offset. */
847 offset = lzms_decode_value(&ctx->lz_offset_decoder);
852 for (i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
853 if (!lzms_range_decode_bit(&ctx->lz_repeat_match_range_decoders[i]))
856 offset = ctx->recent_lz_offsets[i];
858 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
859 ctx->recent_lz_offsets[i] = ctx->recent_lz_offsets[i + 1];
862 /* Decode match length, which is always given explicitly (there is no
863 * LRU queue for repeat lengths). */
864 length = lzms_decode_value(&ctx->length_decoder);
866 ctx->upcoming_lz_offset = offset;
868 LZMS_DEBUG("Decoded %s LZ match: length=%u, offset=%u",
869 (bit ? "repeat" : "explicit"), length, offset);
871 /* Validate the match and copy it to the output. */
872 return lzms_copy_lz_match(ctx, length, offset);
875 /* Decodes a "delta" match from the input. */
877 lzms_decode_delta_match(struct lzms_decompressor *ctx)
880 u32 length, power, raw_offset;
882 /* Decode the match power and raw offset. The next range-encoded bit
883 * indicates whether these data are a repeat, or given explicitly. */
885 bit = lzms_range_decode_bit(&ctx->delta_match_range_decoder);
887 power = lzms_decode_huffman_symbol(&ctx->delta_power_decoder);
888 raw_offset = lzms_decode_value(&ctx->delta_offset_decoder);
892 for (i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
893 if (!lzms_range_decode_bit(&ctx->delta_repeat_match_range_decoders[i]))
896 power = ctx->recent_delta_powers[i];
897 raw_offset = ctx->recent_delta_offsets[i];
899 for (; i < LZMS_NUM_RECENT_OFFSETS; i++) {
900 ctx->recent_delta_powers[i] = ctx->recent_delta_powers[i + 1];
901 ctx->recent_delta_offsets[i] = ctx->recent_delta_offsets[i + 1];
905 length = lzms_decode_value(&ctx->length_decoder);
907 ctx->upcoming_delta_power = power;
908 ctx->upcoming_delta_offset = raw_offset;
910 LZMS_DEBUG("Decoded %s delta match: length=%u, power=%u, raw_offset=%u",
911 (bit ? "repeat" : "explicit"), length, power, raw_offset);
913 /* Validate the match and copy it to the output. */
914 return lzms_copy_delta_match(ctx, length, power, raw_offset);
918 lzms_decode_match(struct lzms_decompressor *ctx)
920 if (!lzms_range_decode_bit(&ctx->match_range_decoder))
921 return lzms_decode_lz_match(ctx);
923 return lzms_decode_delta_match(ctx);
926 /* Decode a literal byte encoded using the literal Huffman code. */
928 lzms_decode_literal(struct lzms_decompressor *ctx)
930 u8 literal = lzms_decode_huffman_symbol(&ctx->literal_decoder);
931 LZMS_DEBUG("Decoded literal: 0x%02x", literal);
932 return lzms_copy_literal(ctx, literal);
935 /* Decode the next LZMS match or literal. */
937 lzms_decode_item(struct lzms_decompressor *ctx)
941 ctx->upcoming_delta_offset = 0;
942 ctx->upcoming_lz_offset = 0;
943 ctx->upcoming_delta_power = 0;
945 if (lzms_range_decode_bit(&ctx->main_range_decoder))
946 ret = lzms_decode_match(ctx);
948 ret = lzms_decode_literal(ctx);
953 /* Update LRU queues */
954 if (ctx->prev_lz_offset != 0) {
955 for (int i = LZMS_NUM_RECENT_OFFSETS - 1; i >= 0; i--)
956 ctx->recent_lz_offsets[i + 1] = ctx->recent_lz_offsets[i];
957 ctx->recent_lz_offsets[0] = ctx->prev_lz_offset;
960 if (ctx->prev_delta_offset != 0) {
961 for (int i = LZMS_NUM_RECENT_OFFSETS - 1; i >= 0; i--) {
962 ctx->recent_delta_powers[i + 1] = ctx->recent_delta_powers[i];
963 ctx->recent_delta_offsets[i + 1] = ctx->recent_delta_offsets[i];
965 ctx->recent_delta_powers[0] = ctx->prev_delta_power;
966 ctx->recent_delta_offsets[0] = ctx->prev_delta_offset;
969 ctx->prev_lz_offset = ctx->upcoming_lz_offset;
970 ctx->prev_delta_offset = ctx->upcoming_delta_offset;
971 ctx->prev_delta_power = ctx->upcoming_delta_power;
976 lzms_init_range_decoder(struct lzms_range_decoder *dec,
977 struct lzms_range_decoder_raw *rd, u32 num_states)
981 dec->mask = num_states - 1;
982 for (u32 i = 0; i < num_states; i++) {
983 dec->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
984 dec->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
989 lzms_init_huffman_decoder(struct lzms_huffman_decoder *dec,
990 struct lzms_input_bitstream *is,
991 const u32 *slot_base_tab, unsigned num_syms,
992 unsigned rebuild_freq)
995 dec->slot_base_tab = slot_base_tab;
996 dec->num_syms = num_syms;
997 dec->num_syms_read = rebuild_freq;
998 dec->rebuild_freq = rebuild_freq;
999 for (unsigned i = 0; i < num_syms; i++)
1000 dec->sym_freqs[i] = 1;
1003 /* Prepare to decode items from an LZMS-compressed block. */
1005 lzms_init_decompressor(struct lzms_decompressor *ctx,
1006 const void *cdata, unsigned clen,
1007 void *ubuf, unsigned ulen)
1009 unsigned num_position_slots;
1011 LZMS_DEBUG("Initializing decompressor (clen=%u, ulen=%u)", clen, ulen);
1013 /* Initialize output pointers. */
1014 ctx->out_begin = ubuf;
1015 ctx->out_next = ubuf;
1016 ctx->out_end = (u8*)ubuf + ulen;
1018 /* Initialize the raw range decoder (reading forwards). */
1019 lzms_range_decoder_raw_init(&ctx->rd, cdata, clen / 2);
1021 /* Initialize the input bitstream for Huffman symbols (reading
1023 lzms_input_bitstream_init(&ctx->is, cdata, clen / 2);
1025 /* Initialize position and length slot bases if not done already. */
1026 lzms_init_slot_bases();
1028 /* Calculate the number of position slots needed for this compressed
1030 num_position_slots = lzms_get_position_slot_raw(ulen - 1) + 1;
1032 LZMS_DEBUG("Using %u position slots", num_position_slots);
1034 /* Initialize Huffman decoders for each alphabet used in the compressed
1035 * representation. */
1036 lzms_init_huffman_decoder(&ctx->literal_decoder, &ctx->is,
1037 NULL, LZMS_NUM_LITERAL_SYMS,
1038 LZMS_LITERAL_CODE_REBUILD_FREQ);
1040 lzms_init_huffman_decoder(&ctx->lz_offset_decoder, &ctx->is,
1041 lzms_position_slot_base, num_position_slots,
1042 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
1044 lzms_init_huffman_decoder(&ctx->length_decoder, &ctx->is,
1045 lzms_length_slot_base, LZMS_NUM_LEN_SYMS,
1046 LZMS_LENGTH_CODE_REBUILD_FREQ);
1048 lzms_init_huffman_decoder(&ctx->delta_offset_decoder, &ctx->is,
1049 lzms_position_slot_base, num_position_slots,
1050 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
1052 lzms_init_huffman_decoder(&ctx->delta_power_decoder, &ctx->is,
1053 NULL, LZMS_NUM_DELTA_POWER_SYMS,
1054 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
1057 /* Initialize range decoders, all of which wrap around the same
1058 * lzms_range_decoder_raw. */
1059 lzms_init_range_decoder(&ctx->main_range_decoder,
1060 &ctx->rd, LZMS_NUM_MAIN_STATES);
1062 lzms_init_range_decoder(&ctx->match_range_decoder,
1063 &ctx->rd, LZMS_NUM_MATCH_STATES);
1065 lzms_init_range_decoder(&ctx->lz_match_range_decoder,
1066 &ctx->rd, LZMS_NUM_LZ_MATCH_STATES);
1068 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_decoders); i++)
1069 lzms_init_range_decoder(&ctx->lz_repeat_match_range_decoders[i],
1070 &ctx->rd, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
1072 lzms_init_range_decoder(&ctx->delta_match_range_decoder,
1073 &ctx->rd, LZMS_NUM_DELTA_MATCH_STATES);
1075 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_decoders); i++)
1076 lzms_init_range_decoder(&ctx->delta_repeat_match_range_decoders[i],
1077 &ctx->rd, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1079 /* Initialize the LRU queue for recent match offsets. */
1080 for (size_t i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++)
1081 ctx->recent_lz_offsets[i] = i + 1;
1083 for (size_t i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++) {
1084 ctx->recent_delta_powers[i] = 0;
1085 ctx->recent_delta_offsets[i] = i + 1;
1087 ctx->prev_lz_offset = 0;
1088 ctx->prev_delta_offset = 0;
1089 ctx->prev_delta_power = 0;
1090 ctx->upcoming_lz_offset = 0;
1091 ctx->upcoming_delta_offset = 0;
1092 ctx->upcoming_delta_power = 0;
1094 LZMS_DEBUG("Decompressor successfully initialized");
1097 /* Decode the series of literals and matches from the LZMS-compressed data.
1098 * Returns 0 on success; nonzero if the compressed data is invalid. */
1100 lzms_decode_items(const u8 *cdata, size_t clen, u8 *ubuf, size_t ulen,
1101 struct lzms_decompressor *ctx)
1103 /* Initialize the LZMS decompressor. */
1104 lzms_init_decompressor(ctx, cdata, clen, ubuf, ulen);
1106 /* Decode the sequence of items. */
1107 while (ctx->out_next != ctx->out_end) {
1108 LZMS_DEBUG("Position %u", ctx->out_next - ctx->out_begin);
1109 if (lzms_decode_item(ctx))
1116 lzms_try_x86_translation(u8 *ubuf, s32 i, s32 num_op_bytes,
1117 s32 *closest_target_usage_p, s32 last_target_usages[],
1118 s32 max_trans_offset)
1122 if (i - *closest_target_usage_p <= max_trans_offset) {
1123 LZMS_DEBUG("Performed x86 translation at position %d "
1124 "(opcode 0x%02x)", i, ubuf[i]);
1125 le32 *p32 = (le32*)&ubuf[i + num_op_bytes];
1126 u32 n = le32_to_cpu(*p32);
1127 *p32 = cpu_to_le32(n - i);
1130 pos = i + le16_to_cpu(*(const le16*)&ubuf[i + num_op_bytes]);
1132 i += num_op_bytes + sizeof(le32) - 1;
1134 if (i - last_target_usages[pos] <= LZMS_X86_MAX_GOOD_TARGET_OFFSET)
1135 *closest_target_usage_p = i;
1137 last_target_usages[pos] = i;
1143 lzms_process_x86_translation(u8 *ubuf, s32 i, s32 *closest_target_usage_p,
1144 s32 last_target_usages[])
1146 /* Switch on first byte of the opcode, assuming it is really an x86
1150 if (ubuf[i + 1] == 0x8b) {
1151 if (ubuf[i + 2] == 0x5 || ubuf[i + 2] == 0xd) {
1152 /* Load relative (x86_64) */
1153 return lzms_try_x86_translation(ubuf, i, 3,
1154 closest_target_usage_p,
1156 LZMS_X86_MAX_TRANSLATION_OFFSET);
1158 } else if (ubuf[i + 1] == 0x8d) {
1159 if ((ubuf[i + 2] & 0x7) == 0x5) {
1160 /* Load effective address relative (x86_64) */
1161 return lzms_try_x86_translation(ubuf, i, 3,
1162 closest_target_usage_p,
1164 LZMS_X86_MAX_TRANSLATION_OFFSET);
1170 if (ubuf[i + 1] == 0x8d) {
1171 if ((ubuf[i + 2] & 0x7) == 0x5) {
1172 /* Load effective address relative (x86_64) */
1173 return lzms_try_x86_translation(ubuf, i, 3,
1174 closest_target_usage_p,
1176 LZMS_X86_MAX_TRANSLATION_OFFSET);
1183 return lzms_try_x86_translation(ubuf, i, 1, closest_target_usage_p,
1185 LZMS_X86_MAX_TRANSLATION_OFFSET / 2);
1192 if (ubuf[i + 1] == 0x83 && ubuf[i + 2] == 0x05) {
1193 /* Lock add relative */
1194 return lzms_try_x86_translation(ubuf, i, 3,
1195 closest_target_usage_p,
1197 LZMS_X86_MAX_TRANSLATION_OFFSET);
1202 if (ubuf[i + 1] == 0x15) {
1204 return lzms_try_x86_translation(ubuf, i, 2,
1205 closest_target_usage_p,
1207 LZMS_X86_MAX_TRANSLATION_OFFSET);
1214 /* Postprocess the uncompressed data by undoing the translation of relative
1215 * addresses embedded in x86 instructions into absolute addresses.
1217 * There does not appear to be any way to check to see if this postprocessing
1218 * actually needs to be done (or to plug in alternate filters, like in LZMA),
1219 * and the corresponding preprocessing seems to be done unconditionally. */
1221 lzms_postprocess_data(u8 *ubuf, s32 ulen, s32 *last_target_usages)
1223 /* Offset (from beginning of buffer) of the most recent reference to a
1224 * seemingly valid target address. */
1225 s32 closest_target_usage = -LZMS_X86_MAX_TRANSLATION_OFFSET - 1;
1227 /* Initialize the last_target_usages array. Each entry will contain the
1228 * offset (from beginning of buffer) of the most recently used target
1229 * address beginning with two bytes equal to the array index. */
1230 for (s32 i = 0; i < 65536; i++)
1231 last_target_usages[i] = -LZMS_X86_MAX_GOOD_TARGET_OFFSET - 1;
1233 /* Check each byte in the buffer for an x86 opcode for which a
1234 * translation may be possible. No translations are done on any
1235 * instructions starting in the last 11 bytes of the buffer. */
1236 for (s32 i = 0; i < ulen - 11; )
1237 i = lzms_process_x86_translation(ubuf, i, &closest_target_usage,
1238 last_target_usages);
1242 lzms_decompress(const void *compressed_data, size_t compressed_size,
1243 void *uncompressed_data, size_t uncompressed_size, void *_ctx)
1245 struct lzms_decompressor *ctx = _ctx;
1247 /* The range decoder requires that a minimum of 4 bytes of compressed
1248 * data be initially available. */
1249 if (compressed_size < 4) {
1250 LZMS_DEBUG("Compressed size too small (got %zu, expected >= 4)",
1255 /* A LZMS-compressed data block should be evenly divisible into 16-bit
1257 if (compressed_size % 2 != 0) {
1258 LZMS_DEBUG("Compressed size not divisible by 2 (got %zu)",
1263 /* Handle the trivial case where nothing needs to be decompressed.
1264 * (Necessary because a window of size 0 does not have a valid position
1266 if (uncompressed_size == 0)
1269 /* The x86 post-processor requires that the uncompressed length fit into
1270 * a signed 32-bit integer. Also, the position slot table cannot be
1271 * searched for a position of INT32_MAX or greater. */
1272 if (uncompressed_size >= INT32_MAX) {
1273 LZMS_DEBUG("Uncompressed length too large "
1274 "(got %u, expected < INT32_MAX)", ulen);
1278 /* Decode the literals and matches. */
1279 if (lzms_decode_items(compressed_data, compressed_size,
1280 uncompressed_data, uncompressed_size, ctx))
1283 /* Postprocess the data. */
1284 lzms_postprocess_data(uncompressed_data, uncompressed_size,
1285 ctx->last_target_usages);
1287 LZMS_DEBUG("Decompression successful.");
1292 lzms_free_decompressor(void *_ctx)
1294 struct lzms_decompressor *ctx = _ctx;
1300 lzms_create_decompressor(size_t max_block_size,
1301 const struct wimlib_decompressor_params_header *params,
1304 struct lzms_decompressor *ctx;
1306 ctx = MALLOC(sizeof(struct lzms_decompressor));
1308 return WIMLIB_ERR_NOMEM;
1314 const struct decompressor_ops lzms_decompressor_ops = {
1315 .create_decompressor = lzms_create_decompressor,
1316 .decompress = lzms_decompress,
1317 .free_decompressor = lzms_free_decompressor,