]> wimlib.net Git - wimlib/blob - src/lzms-decompress.c
lzms-decompress.c: Update comments about Huffman codes
[wimlib] / src / lzms-decompress.c
1 /*
2  * lzms-decompress.c
3  */
4
5 /*
6  * Copyright (C) 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 /*
25  * This is a decompressor for the LZMS compression format used by Microsoft.
26  * This format is not documented, but it is one of the formats supported by the
27  * compression API available in Windows 8, and as of Windows 8 it is one of the
28  * formats that can be used in WIM files.
29  *
30  * This decompressor only implements "raw" decompression, which decompresses a
31  * single LZMS-compressed block.  This behavior is the same as that of
32  * Decompress() in the Windows 8 compression API when using a compression handle
33  * created with CreateDecompressor() with the Algorithm parameter specified as
34  * COMPRESS_ALGORITHM_LZMS | COMPRESS_RAW.  Presumably, non-raw LZMS data
35  * is a container format from which the locations and sizes (both compressed and
36  * uncompressed) of the constituent blocks can be determined.
37  *
38  * An LZMS-compressed block must be read in 16-bit little endian units from both
39  * directions.  One logical bitstream starts at the front of the block and
40  * proceeds forwards.  Another logical bitstream starts at the end of the block
41  * and proceeds backwards.  Bits read from the forwards bitstream constitute
42  * range-encoded data, whereas bits read from the backwards bitstream constitute
43  * Huffman-encoded symbols or verbatim bits.  For both bitstreams, the ordering
44  * of the bits within the 16-bit coding units is such that the first bit is the
45  * high-order bit and the last bit is the low-order bit.
46  *
47  * From these two logical bitstreams, an LZMS decompressor can reconstitute the
48  * series of items that make up the LZMS data representation.  Each such item
49  * may be a literal byte or a match.  Matches may be either traditional LZ77
50  * matches or "delta" matches, either of which can have its offset encoded
51  * explicitly or encoded via a reference to a recently used (repeat) offset.
52  *
53  * A traditional LZ match consists of a length and offset; it asserts that the
54  * sequence of bytes beginning at the current position and extending for the
55  * length is exactly equal to the equal-length sequence of bytes at the offset
56  * back in the window.  On the other hand, a delta match consists of a length,
57  * raw offset, and power.  It asserts that the sequence of bytes beginning at
58  * the current position and extending for the length is equal to the bytewise
59  * sum of the two equal-length sequences of bytes (2**power) and (raw_offset *
60  * 2**power) bytes before the current position, minus bytewise the sequence of
61  * bytes beginning at (2**power + raw_offset * 2**power) bytes before the
62  * current position.  Although not generally as useful as traditional LZ
63  * matches, delta matches can be helpful on some types of data.  Both LZ and
64  * delta matches may overlap with the current position; in fact, the minimum
65  * offset is 1, regardless of match length.
66  *
67  * For LZ matches, up to 3 repeat offsets are allowed, similar to some other
68  * LZ-based formats such as LZX and LZMA.  They must updated in an LRU fashion,
69  * except for a quirk: updates to the queue must be delayed by one LZMS item,
70  * except for the removal of a repeat match.  As a result, 4 entries are
71  * actually needed in the queue, even though it is only possible to decode
72  * references to the first 3 at any given time.  The queue must be initialized
73  * to the offsets {1, 2, 3, 4}.
74  *
75  * Repeat delta matches are handled similarly, but for them there are two queues
76  * updated in lock-step: one for powers and one for raw offsets.  The power
77  * queue must be initialized to {0, 0, 0, 0}, and the raw offset queue must be
78  * initialized to {1, 2, 3, 4}.
79  *
80  * Bits from the range decoder must be used to disambiguate item types.  The
81  * range decoder must hold two state variables: the range, which must initially
82  * be set to 0xffffffff, and the current code, which must initially be set to
83  * the first 32 bits read from the forwards bitstream.  The range must be
84  * maintained above 0xffff; when it falls below 0xffff, both the range and code
85  * must be left-shifted by 16 bits and the low 16 bits of the code must be
86  * filled in with the next 16 bits from the forwards bitstream.
87  *
88  * To decode each bit, the range decoder requires a probability that is
89  * logically a real number between 0 and 1.  Multiplying this probability by the
90  * current range and taking the floor gives the bound between the 0-bit region
91  * of the range and the 1-bit region of the range.  However, in LZMS,
92  * probabilities are restricted to values of n/64 where n is an integer is
93  * between 1 and 63 inclusively, so the implementation may use integer
94  * operations instead.  Following calculation of the bound, if the current code
95  * is in the 0-bit region, the new range becomes the current code and the
96  * decoded bit is 0; otherwise, the bound must be subtracted from both the range
97  * and the code, and the decoded bit is 1.  More information about range coding
98  * can be found at https://en.wikipedia.org/wiki/Range_encoding.  Furthermore,
99  * note that the LZMA format also uses range coding and has public domain code
100  * available for it.
101  *
102  * The probability used to range-decode each bit must be taken from a table, of
103  * which one instance must exist for each distinct context in which a
104  * range-decoded bit is needed.  At each call of the range decoder, the
105  * appropriate probability must be obtained by indexing the appropriate
106  * probability table with the last 4 (in the context disambiguating literals
107  * from matches), 5 (in the context disambiguating LZ matches from delta
108  * matches), or 6 (in all other contexts) bits recently range-decoded in that
109  * context, ordered such that the most recently decoded bit is the low-order bit
110  * of the index.
111  *
112  * Furthermore, each probability entry itself is variable, as its value must be
113  * maintained as n/64 where n is the number of 0 bits in the most recently
114  * decoded 64 bits with that same entry.  This allows the compressed
115  * representation to adapt to the input and use fewer bits to represent the most
116  * likely data; note that LZMA uses a similar scheme.  Initially, the most
117  * recently 64 decoded bits for each probability entry are assumed to be
118  * 0x0000000055555555 (high order to low order); therefore, all probabilities
119  * are initially 48/64.  During the course of decoding, each probability may be
120  * updated to as low as 0/64 (as a result of reading many consecutive 1 bits
121  * with that entry) or as high as 64/64 (as a result of reading many consecutive
122  * 0 bits with that entry); however, probabilities of 0/64 and 64/64 cannot be
123  * used as-is but rather must be adjusted to 1/64 and 63/64, respectively,
124  * before being used for range decoding.
125  *
126  * Representations of the LZMS items themselves must be read from the backwards
127  * bitstream.  For this, there are 5 different Huffman codes used:
128  *
129  *  - The literal code, used for decoding literal bytes.  Each of the 256
130  *    symbols represents a literal byte.  This code must be rebuilt whenever
131  *    1024 symbols have been decoded with it.
132  *
133  *  - The LZ offset code, used for decoding the offsets of standard LZ77
134  *    matches.  Each symbol represents a position slot, which corresponds to a
135  *    base value and some number of extra bits which must be read and added to
136  *    the base value to reconstitute the full offset.  The number of symbols in
137  *    this code is the number of position slots needed to represent all possible
138  *    offsets in the uncompressed block.  This code must be rebuilt whenever
139  *    1024 symbols have been decoded with it.
140  *
141  *  - The length code, used for decoding length symbols.  Each of the 54 symbols
142  *    represents a length slot, which corresponds to a base value and some
143  *    number of extra bits which must be read and added to the base value to
144  *    reconstitute the full length.  This code must be rebuilt whenever 512
145  *    symbols have been decoded with it.
146  *
147  *  - The delta offset code, used for decoding the offsets of delta matches.
148  *    Each symbol corresponds to a position slot, which corresponds to a base
149  *    value and some number of extra bits which must be read and added to the
150  *    base value to reconstitute the full offset.  The number of symbols in this
151  *    code is equal to the number of symbols in the LZ offset code.  This code
152  *    must be rebuilt whenever 1024 symbols have been decoded with it.
153  *
154  *  - The delta power code, used for decoding the powers of delta matches.  Each
155  *    of the 8 symbols corresponds to a power.  This code must be rebuilt
156  *    whenever 512 symbols have been decoded with it.
157  *
158  * All the LZMS Huffman codes must be built adaptively based on symbol
159  * frequencies.  Initially, each code must be built assuming that all symbols
160  * have equal frequency.  Following that, each code must be rebuilt whenever a
161  * certain number of symbols has been decoded with it.
162  *
163  * Like other compression formats such as XPRESS, LZX, and DEFLATE, the LZMS
164  * format requires that all Huffman codes be constructed in canonical form.
165  * This form requires that same-length codewords be lexicographically ordered
166  * the same way as the corresponding symbols and that all shorter codewords
167  * lexicographically precede longer codewords.  Such a code can be constructed
168  * directly from codeword lengths, although in LZMS this is not actually
169  * necessary because the codes are built using adaptive symbol frequencies.
170  *
171  * Even with the canonical code restriction, the same frequencies can be used to
172  * construct multiple valid Huffman codes.  Therefore, the decompressor needs to
173  * construct the right one.  Specifically, the LZMS format requires that the
174  * Huffman code be constructed as if the well-known priority queue algorithm is
175  * used and frequency ties are always broken in favor of leaf nodes.  See
176  * make_canonical_huffman_code() in compress_common.c for more information.
177  *
178  * Codewords in LZMS are guaranteed to not exceed 15 bits.  The format otherwise
179  * places no restrictions on codeword length.  Therefore, the Huffman code
180  * construction algorithm that a correct LZMS decompressor uses need not
181  * implement length-limited code construction.  But if it does (e.g. by virtue
182  * of being shared among multiple compression algorithms), the details of how it
183  * does so are unimportant, provided that the maximum codeword length parameter
184  * is set to at least 15 bits.
185  *
186  * An LZMS-compressed block seemingly cannot have a compressed size greater than
187  * or equal to the uncompressed size.  In such cases the block must be stored
188  * uncompressed.
189  *
190  * After all LZMS items have been decoded, the data must be postprocessed to
191  * translate absolute address encoded in x86 instructions into their original
192  * relative addresses.
193  *
194  * Details omitted above can be found in the code.  Note that in the absence of
195  * an official specification there is no guarantee that this decompressor
196  * handles all possible cases.
197  */
198
199 #ifdef HAVE_CONFIG_H
200 #  include "config.h"
201 #endif
202
203 #include "wimlib.h"
204 #include "wimlib/compress_common.h"
205 #include "wimlib/decompressor_ops.h"
206 #include "wimlib/decompress_common.h"
207 #include "wimlib/lzms.h"
208 #include "wimlib/util.h"
209
210 #include <limits.h>
211
212 #define LZMS_DECODE_TABLE_BITS  10
213
214 /* Structure used for range decoding, reading bits forwards.  This is the first
215  * logical bitstream mentioned above.  */
216 struct lzms_range_decoder_raw {
217         /* The relevant part of the current range.  Although the logical range
218          * for range decoding is a very large integer, only a small portion
219          * matters at any given time, and it can be normalized (shifted left)
220          * whenever it gets too small.  */
221         u32 range;
222
223         /* The current position in the range encoded by the portion of the input
224          * read so far.  */
225         u32 code;
226
227         /* Pointer to the next little-endian 16-bit integer in the compressed
228          * input data (reading forwards).  */
229         const le16 *in;
230
231         /* Number of 16-bit integers remaining in the compressed input data
232          * (reading forwards).  */
233         size_t num_le16_remaining;
234 };
235
236 /* Structure used for reading raw bits backwards.  This is the second logical
237  * bitstream mentioned above.  */
238 struct lzms_input_bitstream {
239         /* Holding variable for bits that have been read from the compressed
240          * data.  The bits are ordered from high-order to low-order.  */
241         /* XXX:  Without special-case code to handle reading more than 17 bits
242          * at a time, this needs to be 64 bits rather than 32 bits.  */
243         u64 bitbuf;
244
245         /* Number of bits in @bitbuf that are used.  */
246         unsigned num_filled_bits;
247
248         /* Pointer to the one past the next little-endian 16-bit integer in the
249          * compressed input data (reading backwards).  */
250         const le16 *in;
251
252         /* Number of 16-bit integers remaining in the compressed input data
253          * (reading backwards).  */
254         size_t num_le16_remaining;
255 };
256
257 /* Structure used for range decoding.  This wraps around `struct
258  * lzms_range_decoder_raw' to use and maintain probability entries.  */
259 struct lzms_range_decoder {
260         /* Pointer to the raw range decoder, which has no persistent knowledge
261          * of probabilities.  Multiple lzms_range_decoder's share the same
262          * lzms_range_decoder_raw.  */
263         struct lzms_range_decoder_raw *rd;
264
265         /* Bits recently decoded by this range decoder.  This are used as in
266          * index into @prob_entries.  */
267         u32 state;
268
269         /* Bitmask for @state to prevent its value from exceeding the number of
270          * probability entries.  */
271         u32 mask;
272
273         /* Probability entries being used for this range decoder.  */
274         struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
275 };
276
277 /* Structure used for Huffman decoding, optionally using the decoded symbols as
278  * slots into a base table to determine how many extra bits need to be read to
279  * reconstitute the full value.  */
280 struct lzms_huffman_decoder {
281
282         /* Bitstream to read Huffman-encoded symbols and verbatim bits from.
283          * Multiple lzms_huffman_decoder's share the same lzms_input_bitstream.
284          */
285         struct lzms_input_bitstream *is;
286
287         /* Pointer to the slot base table to use.  It is indexed by the decoded
288          * Huffman symbol that specifies the slot.  The entry specifies the base
289          * value to use, and the position of its high bit is the number of
290          * additional bits that must be read to reconstitute the full value.
291          *
292          * This member need not be set if only raw Huffman symbols are being
293          * read using this decoder.  */
294         const u32 *slot_base_tab;
295
296         const u8 *extra_bits_tab;
297
298         /* Number of symbols that have been read using this code far.  Reset to
299          * 0 whenever the code is rebuilt.  */
300         u32 num_syms_read;
301
302         /* When @num_syms_read reaches this number, the Huffman code must be
303          * rebuilt.  */
304         u32 rebuild_freq;
305
306         /* Number of symbols in the represented Huffman code.  */
307         unsigned num_syms;
308
309         /* Running totals of symbol frequencies.  These are diluted slightly
310          * whenever the code is rebuilt.  */
311         u32 sym_freqs[LZMS_MAX_NUM_SYMS];
312
313         /* The length, in bits, of each symbol in the Huffman code.  */
314         u8 lens[LZMS_MAX_NUM_SYMS];
315
316         /* The codeword of each symbol in the Huffman code.  */
317         u32 codewords[LZMS_MAX_NUM_SYMS];
318
319         /* A table for quickly decoding symbols encoded using the Huffman code.
320          */
321         u16 decode_table[(1U << LZMS_DECODE_TABLE_BITS) + 2 * LZMS_MAX_NUM_SYMS]
322                                 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
323 };
324
325 /* State of the LZMS decompressor.  */
326 struct lzms_decompressor {
327
328         /* Pointer to the beginning of the uncompressed data buffer.  */
329         u8 *out_begin;
330
331         /* Pointer to the next position in the uncompressed data buffer.  */
332         u8 *out_next;
333
334         /* Pointer to one past the end of the uncompressed data buffer.  */
335         u8 *out_end;
336
337         /* Range decoder, which reads bits from the beginning of the compressed
338          * block, going forwards.  */
339         struct lzms_range_decoder_raw rd;
340
341         /* Input bitstream, which reads from the end of the compressed block,
342          * going backwards.  */
343         struct lzms_input_bitstream is;
344
345         /* Range decoders.  */
346         struct lzms_range_decoder main_range_decoder;
347         struct lzms_range_decoder match_range_decoder;
348         struct lzms_range_decoder lz_match_range_decoder;
349         struct lzms_range_decoder lz_repeat_match_range_decoders[LZMS_NUM_RECENT_OFFSETS - 1];
350         struct lzms_range_decoder delta_match_range_decoder;
351         struct lzms_range_decoder delta_repeat_match_range_decoders[LZMS_NUM_RECENT_OFFSETS - 1];
352
353         /* Huffman decoders.  */
354         struct lzms_huffman_decoder literal_decoder;
355         struct lzms_huffman_decoder lz_offset_decoder;
356         struct lzms_huffman_decoder length_decoder;
357         struct lzms_huffman_decoder delta_power_decoder;
358         struct lzms_huffman_decoder delta_offset_decoder;
359
360         /* LRU (least-recently-used) queues for match information.  */
361         struct lzms_lru_queues lru;
362
363         /* Used for postprocessing.  */
364         s32 last_target_usages[65536];
365 };
366
367 /* Initialize the input bitstream @is to read forwards from the specified
368  * compressed data buffer @in that is @in_limit 16-bit integers long.  */
369 static void
370 lzms_input_bitstream_init(struct lzms_input_bitstream *is,
371                           const le16 *in, size_t in_limit)
372 {
373         is->bitbuf = 0;
374         is->num_filled_bits = 0;
375         is->in = in + in_limit;
376         is->num_le16_remaining = in_limit;
377 }
378
379 /* Ensures that @num_bits bits are buffered in the input bitstream.  */
380 static int
381 lzms_input_bitstream_ensure_bits(struct lzms_input_bitstream *is,
382                                  unsigned num_bits)
383 {
384         while (is->num_filled_bits < num_bits) {
385                 u64 next;
386
387                 LZMS_ASSERT(is->num_filled_bits + 16 <= sizeof(is->bitbuf) * 8);
388
389                 if (unlikely(is->num_le16_remaining == 0))
390                         return -1;
391
392                 next = le16_to_cpu(*--is->in);
393                 is->num_le16_remaining--;
394
395                 is->bitbuf |= next << (sizeof(is->bitbuf) * 8 - is->num_filled_bits - 16);
396                 is->num_filled_bits += 16;
397         }
398         return 0;
399
400 }
401
402 /* Returns the next @num_bits bits that are buffered in the input bitstream.  */
403 static u32
404 lzms_input_bitstream_peek_bits(struct lzms_input_bitstream *is,
405                                unsigned num_bits)
406 {
407         LZMS_ASSERT(is->num_filled_bits >= num_bits);
408         return is->bitbuf >> (sizeof(is->bitbuf) * 8 - num_bits);
409 }
410
411 /* Removes the next @num_bits bits that are buffered in the input bitstream.  */
412 static void
413 lzms_input_bitstream_remove_bits(struct lzms_input_bitstream *is,
414                                  unsigned num_bits)
415 {
416         LZMS_ASSERT(is->num_filled_bits >= num_bits);
417         is->bitbuf <<= num_bits;
418         is->num_filled_bits -= num_bits;
419 }
420
421 /* Removes and returns the next @num_bits bits that are buffered in the input
422  * bitstream.  */
423 static u32
424 lzms_input_bitstream_pop_bits(struct lzms_input_bitstream *is,
425                               unsigned num_bits)
426 {
427         u32 bits = lzms_input_bitstream_peek_bits(is, num_bits);
428         lzms_input_bitstream_remove_bits(is, num_bits);
429         return bits;
430 }
431
432 /* Reads the next @num_bits from the input bitstream.  */
433 static u32
434 lzms_input_bitstream_read_bits(struct lzms_input_bitstream *is,
435                                unsigned num_bits)
436 {
437         if (unlikely(lzms_input_bitstream_ensure_bits(is, num_bits)))
438                 return 0;
439         return lzms_input_bitstream_pop_bits(is, num_bits);
440 }
441
442 /* Initialize the range decoder @rd to read forwards from the specified
443  * compressed data buffer @in that is @in_limit 16-bit integers long.  */
444 static void
445 lzms_range_decoder_raw_init(struct lzms_range_decoder_raw *rd,
446                             const le16 *in, size_t in_limit)
447 {
448         rd->range = 0xffffffff;
449         rd->code = ((u32)le16_to_cpu(in[0]) << 16) |
450                    ((u32)le16_to_cpu(in[1]) <<  0);
451         rd->in = in + 2;
452         rd->num_le16_remaining = in_limit - 2;
453 }
454
455 /* Ensures the current range of the range decoder has at least 16 bits of
456  * precision.  */
457 static int
458 lzms_range_decoder_raw_normalize(struct lzms_range_decoder_raw *rd)
459 {
460         if (rd->range <= 0xffff) {
461                 rd->range <<= 16;
462                 if (unlikely(rd->num_le16_remaining == 0))
463                         return -1;
464                 rd->code = (rd->code << 16) | le16_to_cpu(*rd->in++);
465                 rd->num_le16_remaining--;
466         }
467         return 0;
468 }
469
470 /* Decode and return the next bit from the range decoder (raw version).
471  *
472  * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0.
473  */
474 static int
475 lzms_range_decoder_raw_decode_bit(struct lzms_range_decoder_raw *rd, u32 prob)
476 {
477         u32 bound;
478
479         /* Ensure the range has at least 16 bits of precision.  */
480         lzms_range_decoder_raw_normalize(rd);
481
482         /* Based on the probability, calculate the bound between the 0-bit
483          * region and the 1-bit region of the range.  */
484         bound = (rd->range >> LZMS_PROBABILITY_BITS) * prob;
485
486         if (rd->code < bound) {
487                 /* Current code is in the 0-bit region of the range.  */
488                 rd->range = bound;
489                 return 0;
490         } else {
491                 /* Current code is in the 1-bit region of the range.  */
492                 rd->range -= bound;
493                 rd->code -= bound;
494                 return 1;
495         }
496 }
497
498 /* Decode and return the next bit from the range decoder.  This wraps around
499  * lzms_range_decoder_raw_decode_bit() to handle using and updating the
500  * appropriate probability table.  */
501 static int
502 lzms_range_decode_bit(struct lzms_range_decoder *dec)
503 {
504         struct lzms_probability_entry *prob_entry;
505         u32 prob;
506         int bit;
507
508         /* Load the probability entry corresponding to the current state.  */
509         prob_entry = &dec->prob_entries[dec->state];
510
511         /* Treat the number of zero bits in the most recently decoded
512          * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
513          * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0.  However,
514          * don't allow 0% or 100% probabilities.  */
515         prob = prob_entry->num_recent_zero_bits;
516         if (prob == LZMS_PROBABILITY_MAX)
517                 prob = LZMS_PROBABILITY_MAX - 1;
518         else if (prob == 0)
519                 prob = 1;
520
521         /* Decode the next bit.  */
522         bit = lzms_range_decoder_raw_decode_bit(dec->rd, prob);
523
524         /* Update the state based on the newly decoded bit.  */
525         dec->state = (((dec->state << 1) | bit) & dec->mask);
526
527         /* Update the recent bits, including the cached count of 0's.  */
528         BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
529         if (bit == 0) {
530                 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
531                         /* Replacing 1 bit with 0 bit; increment the zero count.
532                          */
533                         prob_entry->num_recent_zero_bits++;
534                 }
535         } else {
536                 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
537                         /* Replacing 0 bit with 1 bit; decrement the zero count.
538                          */
539                         prob_entry->num_recent_zero_bits--;
540                 }
541         }
542         prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
543
544         /* Return the decoded bit.  */
545         return bit;
546 }
547
548
549 /* Build the decoding table for a new adaptive Huffman code using the alphabet
550  * used in the specified Huffman decoder, with the symbol frequencies
551  * dec->sym_freqs.  */
552 static void
553 lzms_rebuild_adaptive_huffman_code(struct lzms_huffman_decoder *dec)
554 {
555
556         /* XXX:  This implementation makes use of code already implemented for
557          * the XPRESS and LZX compression formats.  However, since for the
558          * adaptive codes used in LZMS we don't actually need the explicit codes
559          * themselves, only the decode tables, it may be possible to optimize
560          * this by somehow directly building or updating the Huffman decode
561          * table.  This may be a worthwhile optimization because the adaptive
562          * codes change many times throughout a decompression run.  */
563         LZMS_DEBUG("Rebuilding adaptive Huffman code (num_syms=%u)",
564                    dec->num_syms);
565         make_canonical_huffman_code(dec->num_syms, LZMS_MAX_CODEWORD_LEN,
566                                     dec->sym_freqs, dec->lens, dec->codewords);
567 #if defined(ENABLE_LZMS_DEBUG)
568         int ret =
569 #endif
570         make_huffman_decode_table(dec->decode_table, dec->num_syms,
571                                   LZMS_DECODE_TABLE_BITS, dec->lens,
572                                   LZMS_MAX_CODEWORD_LEN);
573         LZMS_ASSERT(ret == 0);
574 }
575
576 /* Decode and return the next Huffman-encoded symbol from the LZMS-compressed
577  * block using the specified Huffman decoder.  */
578 static u32
579 lzms_huffman_decode_symbol(struct lzms_huffman_decoder *dec)
580 {
581         const u16 *decode_table = dec->decode_table;
582         struct lzms_input_bitstream *is = dec->is;
583         u16 entry;
584         u16 key_bits;
585         u16 sym;
586
587         /* The Huffman codes used in LZMS are adaptive and must be rebuilt
588          * whenever a certain number of symbols have been read.  Each such
589          * rebuild uses the current symbol frequencies, but the format also
590          * requires that the symbol frequencies be halved after each code
591          * rebuild.  This diminishes the effect of old symbols on the current
592          * Huffman codes, thereby causing the Huffman codes to be more locally
593          * adaptable.  */
594         if (dec->num_syms_read == dec->rebuild_freq) {
595                 lzms_rebuild_adaptive_huffman_code(dec);
596                 for (unsigned i = 0; i < dec->num_syms; i++) {
597                         dec->sym_freqs[i] >>= 1;
598                         dec->sym_freqs[i] += 1;
599                 }
600                 dec->num_syms_read = 0;
601         }
602
603         /* XXX: Copied from read_huffsym() (decompress_common.h), since this
604          * uses a different input bitstream type.  Should unify the
605          * implementations.  */
606         lzms_input_bitstream_ensure_bits(is, LZMS_MAX_CODEWORD_LEN);
607
608         /* Index the decode table by the next table_bits bits of the input.  */
609         key_bits = lzms_input_bitstream_peek_bits(is, LZMS_DECODE_TABLE_BITS);
610         entry = decode_table[key_bits];
611         if (likely(entry < 0xC000)) {
612                 /* Fast case: The decode table directly provided the symbol and
613                  * codeword length.  The low 11 bits are the symbol, and the
614                  * high 5 bits are the codeword length.  */
615                 lzms_input_bitstream_remove_bits(is, entry >> 11);
616                 sym = entry & 0x7FF;
617         } else {
618                 /* Slow case: The codeword for the symbol is longer than
619                  * table_bits, so the symbol does not have an entry directly in
620                  * the first (1 << table_bits) entries of the decode table.
621                  * Traverse the appropriate binary tree bit-by-bit in order to
622                  * decode the symbol.  */
623                 lzms_input_bitstream_remove_bits(is, LZMS_DECODE_TABLE_BITS);
624                 do {
625                         key_bits = (entry & 0x3FFF) + lzms_input_bitstream_pop_bits(is, 1);
626                 } while ((entry = decode_table[key_bits]) >= 0xC000);
627                 sym = entry;
628         }
629
630         /* Tally and return the decoded symbol.  */
631         ++dec->sym_freqs[sym];
632         ++dec->num_syms_read;
633         return sym;
634 }
635
636 /* Decode a number from the LZMS bitstream, encoded as a Huffman-encoded symbol
637  * specifying a "slot" (whose corresponding value is looked up in a static
638  * table) plus the number specified by a number of extra bits depending on the
639  * slot.  */
640 static u32
641 lzms_decode_value(struct lzms_huffman_decoder *dec)
642 {
643         unsigned slot;
644         unsigned num_extra_bits;
645         u32 extra_bits;
646
647         LZMS_ASSERT(dec->slot_base_tab != NULL);
648         LZMS_ASSERT(dec->extra_bits_tab != NULL);
649
650         /* Read the slot (position slot, length slot, etc.), which is encoded as
651          * a Huffman symbol.  */
652         slot = lzms_huffman_decode_symbol(dec);
653
654         /* Get the number of extra bits needed to represent the range of values
655          * that share the slot.  */
656         num_extra_bits = dec->extra_bits_tab[slot];
657
658         /* Read the number of extra bits and add them to the slot base to form
659          * the final decoded value.  */
660         extra_bits = lzms_input_bitstream_read_bits(dec->is, num_extra_bits);
661         return dec->slot_base_tab[slot] + extra_bits;
662 }
663
664 /* Copy a literal to the output buffer.  */
665 static int
666 lzms_copy_literal(struct lzms_decompressor *ctx, u8 literal)
667 {
668         *ctx->out_next++ = literal;
669         return 0;
670 }
671
672 /* Validate an LZ match and copy it to the output buffer.  */
673 static int
674 lzms_copy_lz_match(struct lzms_decompressor *ctx, u32 length, u32 offset)
675 {
676         u8 *out_next;
677
678         if (length > ctx->out_end - ctx->out_next) {
679                 LZMS_DEBUG("Match overrun!");
680                 return -1;
681         }
682         if (offset > ctx->out_next - ctx->out_begin) {
683                 LZMS_DEBUG("Match underrun!");
684                 return -1;
685         }
686
687         out_next = ctx->out_next;
688
689         lz_copy(out_next, length, offset, ctx->out_end);
690         ctx->out_next = out_next + length;
691
692         return 0;
693 }
694
695 /* Validate a delta match and copy it to the output buffer.  */
696 static int
697 lzms_copy_delta_match(struct lzms_decompressor *ctx, u32 length,
698                       u32 power, u32 raw_offset)
699 {
700         u32 offset1 = 1U << power;
701         u32 offset2 = raw_offset << power;
702         u32 offset = offset1 + offset2;
703         u8 *out_next;
704         u8 *matchptr1;
705         u8 *matchptr2;
706         u8 *matchptr;
707
708         if (length > ctx->out_end - ctx->out_next) {
709                 LZMS_DEBUG("Match overrun!");
710                 return -1;
711         }
712         if (offset > ctx->out_next - ctx->out_begin) {
713                 LZMS_DEBUG("Match underrun!");
714                 return -1;
715         }
716
717         out_next = ctx->out_next;
718         matchptr1 = out_next - offset1;
719         matchptr2 = out_next - offset2;
720         matchptr = out_next - offset;
721
722         while (length--)
723                 *out_next++ = *matchptr1++ + *matchptr2++ - *matchptr++;
724
725         ctx->out_next = out_next;
726         return 0;
727 }
728
729 /* Decode a (length, offset) pair from the input.  */
730 static int
731 lzms_decode_lz_match(struct lzms_decompressor *ctx)
732 {
733         int bit;
734         u32 length, offset;
735
736         /* Decode the match offset.  The next range-encoded bit indicates
737          * whether it's a repeat offset or an explicit offset.  */
738
739         bit = lzms_range_decode_bit(&ctx->lz_match_range_decoder);
740         if (bit == 0) {
741                 /* Explicit offset.  */
742                 offset = lzms_decode_value(&ctx->lz_offset_decoder);
743         } else {
744                 /* Repeat offset.  */
745                 int i;
746
747                 for (i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
748                         if (!lzms_range_decode_bit(&ctx->lz_repeat_match_range_decoders[i]))
749                                 break;
750
751                 offset = ctx->lru.lz.recent_offsets[i];
752
753                 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
754                         ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
755         }
756
757         /* Decode match length, which is always given explicitly (there is no
758          * LRU queue for repeat lengths).  */
759         length = lzms_decode_value(&ctx->length_decoder);
760
761         ctx->lru.lz.upcoming_offset = offset;
762
763         LZMS_DEBUG("Decoded %s LZ match: length=%u, offset=%u",
764                    (bit ? "repeat" : "explicit"), length, offset);
765
766         /* Validate the match and copy it to the output.  */
767         return lzms_copy_lz_match(ctx, length, offset);
768 }
769
770 /* Decodes a "delta" match from the input.  */
771 static int
772 lzms_decode_delta_match(struct lzms_decompressor *ctx)
773 {
774         int bit;
775         u32 length, power, raw_offset;
776
777         /* Decode the match power and raw offset.  The next range-encoded bit
778          * indicates whether these data are a repeat, or given explicitly.  */
779
780         bit = lzms_range_decode_bit(&ctx->delta_match_range_decoder);
781         if (bit == 0) {
782                 power = lzms_huffman_decode_symbol(&ctx->delta_power_decoder);
783                 raw_offset = lzms_decode_value(&ctx->delta_offset_decoder);
784         } else {
785                 int i;
786
787                 for (i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
788                         if (!lzms_range_decode_bit(&ctx->delta_repeat_match_range_decoders[i]))
789                                 break;
790
791                 power = ctx->lru.delta.recent_powers[i];
792                 raw_offset = ctx->lru.delta.recent_offsets[i];
793
794                 for (; i < LZMS_NUM_RECENT_OFFSETS; i++) {
795                         ctx->lru.delta.recent_powers[i] = ctx->lru.delta.recent_powers[i + 1];
796                         ctx->lru.delta.recent_offsets[i] = ctx->lru.delta.recent_offsets[i + 1];
797                 }
798         }
799
800         length = lzms_decode_value(&ctx->length_decoder);
801
802         ctx->lru.delta.upcoming_power = power;
803         ctx->lru.delta.upcoming_offset = raw_offset;
804
805         LZMS_DEBUG("Decoded %s delta match: length=%u, power=%u, raw_offset=%u",
806                    (bit ? "repeat" : "explicit"), length, power, raw_offset);
807
808         /* Validate the match and copy it to the output.  */
809         return lzms_copy_delta_match(ctx, length, power, raw_offset);
810 }
811
812 /* Decode an LZ or delta match.  */
813 static int
814 lzms_decode_match(struct lzms_decompressor *ctx)
815 {
816         if (!lzms_range_decode_bit(&ctx->match_range_decoder))
817                 return lzms_decode_lz_match(ctx);
818         else
819                 return lzms_decode_delta_match(ctx);
820 }
821
822 /* Decode a literal byte encoded using the literal Huffman code.  */
823 static int
824 lzms_decode_literal(struct lzms_decompressor *ctx)
825 {
826         u8 literal = lzms_huffman_decode_symbol(&ctx->literal_decoder);
827         LZMS_DEBUG("Decoded literal: 0x%02x", literal);
828         return lzms_copy_literal(ctx, literal);
829 }
830
831 /* Decode the next LZMS match or literal.  */
832 static int
833 lzms_decode_item(struct lzms_decompressor *ctx)
834 {
835         int ret;
836
837         ctx->lru.lz.upcoming_offset = 0;
838         ctx->lru.delta.upcoming_power = 0;
839         ctx->lru.delta.upcoming_offset = 0;
840
841         if (lzms_range_decode_bit(&ctx->main_range_decoder))
842                 ret = lzms_decode_match(ctx);
843         else
844                 ret = lzms_decode_literal(ctx);
845
846         if (ret)
847                 return ret;
848
849         lzms_update_lru_queues(&ctx->lru);
850         return 0;
851 }
852
853 static void
854 lzms_init_range_decoder(struct lzms_range_decoder *dec,
855                         struct lzms_range_decoder_raw *rd, u32 num_states)
856 {
857         dec->rd = rd;
858         dec->state = 0;
859         dec->mask = num_states - 1;
860         for (u32 i = 0; i < num_states; i++) {
861                 dec->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
862                 dec->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
863         }
864 }
865
866 static void
867 lzms_init_huffman_decoder(struct lzms_huffman_decoder *dec,
868                           struct lzms_input_bitstream *is,
869                           const u32 *slot_base_tab,
870                           const u8 *extra_bits_tab,
871                           unsigned num_syms,
872                           unsigned rebuild_freq)
873 {
874         dec->is = is;
875         dec->slot_base_tab = slot_base_tab;
876         dec->extra_bits_tab = extra_bits_tab;
877         dec->num_syms = num_syms;
878         dec->num_syms_read = rebuild_freq;
879         dec->rebuild_freq = rebuild_freq;
880         for (unsigned i = 0; i < num_syms; i++)
881                 dec->sym_freqs[i] = 1;
882 }
883
884 /* Prepare to decode items from an LZMS-compressed block.  */
885 static void
886 lzms_init_decompressor(struct lzms_decompressor *ctx,
887                        const void *cdata, unsigned clen,
888                        void *ubuf, unsigned ulen)
889 {
890         unsigned num_position_slots;
891
892         LZMS_DEBUG("Initializing decompressor (clen=%u, ulen=%u)", clen, ulen);
893
894         /* Initialize output pointers.  */
895         ctx->out_begin = ubuf;
896         ctx->out_next = ubuf;
897         ctx->out_end = (u8*)ubuf + ulen;
898
899         /* Initialize the raw range decoder (reading forwards).  */
900         lzms_range_decoder_raw_init(&ctx->rd, cdata, clen / 2);
901
902         /* Initialize the input bitstream for Huffman symbols (reading
903          * backwards)  */
904         lzms_input_bitstream_init(&ctx->is, cdata, clen / 2);
905
906         /* Calculate the number of position slots needed for this compressed
907          * block.  */
908         num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
909
910         LZMS_DEBUG("Using %u position slots", num_position_slots);
911
912         /* Initialize Huffman decoders for each alphabet used in the compressed
913          * representation.  */
914         lzms_init_huffman_decoder(&ctx->literal_decoder, &ctx->is,
915                                   NULL, NULL, LZMS_NUM_LITERAL_SYMS,
916                                   LZMS_LITERAL_CODE_REBUILD_FREQ);
917
918         lzms_init_huffman_decoder(&ctx->lz_offset_decoder, &ctx->is,
919                                   lzms_position_slot_base,
920                                   lzms_extra_position_bits,
921                                   num_position_slots,
922                                   LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
923
924         lzms_init_huffman_decoder(&ctx->length_decoder, &ctx->is,
925                                   lzms_length_slot_base,
926                                   lzms_extra_length_bits,
927                                   LZMS_NUM_LEN_SYMS,
928                                   LZMS_LENGTH_CODE_REBUILD_FREQ);
929
930         lzms_init_huffman_decoder(&ctx->delta_offset_decoder, &ctx->is,
931                                   lzms_position_slot_base,
932                                   lzms_extra_position_bits,
933                                   num_position_slots,
934                                   LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
935
936         lzms_init_huffman_decoder(&ctx->delta_power_decoder, &ctx->is,
937                                   NULL, NULL, LZMS_NUM_DELTA_POWER_SYMS,
938                                   LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
939
940
941         /* Initialize range decoders, all of which wrap around the same
942          * lzms_range_decoder_raw.  */
943         lzms_init_range_decoder(&ctx->main_range_decoder,
944                                 &ctx->rd, LZMS_NUM_MAIN_STATES);
945
946         lzms_init_range_decoder(&ctx->match_range_decoder,
947                                 &ctx->rd, LZMS_NUM_MATCH_STATES);
948
949         lzms_init_range_decoder(&ctx->lz_match_range_decoder,
950                                 &ctx->rd, LZMS_NUM_LZ_MATCH_STATES);
951
952         for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_decoders); i++)
953                 lzms_init_range_decoder(&ctx->lz_repeat_match_range_decoders[i],
954                                         &ctx->rd, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
955
956         lzms_init_range_decoder(&ctx->delta_match_range_decoder,
957                                 &ctx->rd, LZMS_NUM_DELTA_MATCH_STATES);
958
959         for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_decoders); i++)
960                 lzms_init_range_decoder(&ctx->delta_repeat_match_range_decoders[i],
961                                         &ctx->rd, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
962
963         /* Initialize LRU match information.  */
964         lzms_init_lru_queues(&ctx->lru);
965
966         LZMS_DEBUG("Decompressor successfully initialized");
967 }
968
969 /* Decode the series of literals and matches from the LZMS-compressed data.
970  * Returns 0 on success; nonzero if the compressed data is invalid.  */
971 static int
972 lzms_decode_items(const u8 *cdata, size_t clen, u8 *ubuf, size_t ulen,
973                   struct lzms_decompressor *ctx)
974 {
975         /* Initialize the LZMS decompressor.  */
976         lzms_init_decompressor(ctx, cdata, clen, ubuf, ulen);
977
978         /* Decode the sequence of items.  */
979         while (ctx->out_next != ctx->out_end) {
980                 LZMS_DEBUG("Position %u", ctx->out_next - ctx->out_begin);
981                 if (lzms_decode_item(ctx))
982                         return -1;
983         }
984         return 0;
985 }
986
987 static int
988 lzms_decompress(const void *compressed_data, size_t compressed_size,
989                 void *uncompressed_data, size_t uncompressed_size, void *_ctx)
990 {
991         struct lzms_decompressor *ctx = _ctx;
992
993         /* The range decoder requires that a minimum of 4 bytes of compressed
994          * data be initially available.  */
995         if (compressed_size < 4) {
996                 LZMS_DEBUG("Compressed size too small (got %zu, expected >= 4)",
997                            compressed_size);
998                 return -1;
999         }
1000
1001         /* An LZMS-compressed data block should be evenly divisible into 16-bit
1002          * integers.  */
1003         if (compressed_size % 2 != 0) {
1004                 LZMS_DEBUG("Compressed size not divisible by 2 (got %zu)",
1005                            compressed_size);
1006                 return -1;
1007         }
1008
1009         /* Handle the trivial case where nothing needs to be decompressed.
1010          * (Necessary because a window of size 0 does not have a valid position
1011          * slot.)  */
1012         if (uncompressed_size == 0)
1013                 return 0;
1014
1015         /* The x86 post-processor requires that the uncompressed length fit into
1016          * a signed 32-bit integer.  Also, the position slot table cannot be
1017          * searched for a position of INT32_MAX or greater.  */
1018         if (uncompressed_size >= INT32_MAX) {
1019                 LZMS_DEBUG("Uncompressed length too large "
1020                            "(got %zu, expected < INT32_MAX)",
1021                            uncompressed_size);
1022                 return -1;
1023         }
1024
1025         /* Decode the literals and matches.  */
1026         if (lzms_decode_items(compressed_data, compressed_size,
1027                               uncompressed_data, uncompressed_size, ctx))
1028                 return -1;
1029
1030         /* Postprocess the data.  */
1031         lzms_x86_filter(uncompressed_data, uncompressed_size,
1032                         ctx->last_target_usages, true);
1033
1034         LZMS_DEBUG("Decompression successful.");
1035         return 0;
1036 }
1037
1038 static void
1039 lzms_free_decompressor(void *_ctx)
1040 {
1041         struct lzms_decompressor *ctx = _ctx;
1042
1043         ALIGNED_FREE(ctx);
1044 }
1045
1046 static int
1047 lzms_create_decompressor(size_t max_block_size,
1048                          const struct wimlib_decompressor_params_header *params,
1049                          void **ctx_ret)
1050 {
1051         struct lzms_decompressor *ctx;
1052
1053         ctx = ALIGNED_MALLOC(sizeof(struct lzms_decompressor),
1054                              DECODE_TABLE_ALIGNMENT);
1055         if (ctx == NULL)
1056                 return WIMLIB_ERR_NOMEM;
1057
1058         /* Initialize position and length slot data if not done already.  */
1059         lzms_init_slots();
1060
1061         *ctx_ret = ctx;
1062         return 0;
1063 }
1064
1065 const struct decompressor_ops lzms_decompressor_ops = {
1066         .create_decompressor  = lzms_create_decompressor,
1067         .decompress           = lzms_decompress,
1068         .free_decompressor    = lzms_free_decompressor,
1069 };