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