]> wimlib.net Git - wimlib/blob - src/lzms_decompress.c
bitops: rename bit scan functions
[wimlib] / src / lzms_decompress.c
1 /*
2  * lzms_decompress.c
3  *
4  * A decompressor for the LZMS compression format.
5  */
6
7 /*
8  * Copyright (C) 2013-2016 Eric Biggers
9  *
10  * This file is free software; you can redistribute it and/or modify it under
11  * the terms of the GNU Lesser General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option) any
13  * later version.
14  *
15  * This file is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this file; 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 is a
35  * 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  * binary range-encoded data, whereas bits read from the backwards bitstream
43  * constitute Huffman-encoded symbols or verbatim bits.  For both bitstreams,
44  * the ordering of the bits within the 16-bit coding units is such that the
45  * first bit is the 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 LZ77 match consists of a length and offset.  It asserts that
54  * the sequence of bytes beginning at the current position and extending for the
55  * length is equal to the same-length sequence of bytes at the offset back in
56  * the data buffer.  This type of match can be visualized as follows, with the
57  * caveat that the sequences may overlap:
58  *
59  *                                offset
60  *                         --------------------
61  *                         |                  |
62  *                         B[1...len]         A[1...len]
63  *
64  * Decoding proceeds as follows:
65  *
66  *                      do {
67  *                              *A++ = *B++;
68  *                      } while (--length);
69  *
70  * On the other hand, a delta match consists of a "span" as well as a length and
71  * offset.  A delta match can be visualized as follows, with the caveat that the
72  * various sequences may overlap:
73  *
74  *                                       offset
75  *                            -----------------------------
76  *                            |                           |
77  *                    span    |                   span    |
78  *                -------------               -------------
79  *                |           |               |           |
80  *                D[1...len]  C[1...len]      B[1...len]  A[1...len]
81  *
82  * Decoding proceeds as follows:
83  *
84  *                      do {
85  *                              *A++ = *B++ + *C++ - *D++;
86  *                      } while (--length);
87  *
88  * A delta match asserts that the bytewise differences of the A and B sequences
89  * are equal to the bytewise differences of the C and D sequences.  The
90  * sequences within each pair are separated by the same number of bytes, the
91  * "span".  The inter-pair distance is the "offset".  In LZMS, spans are
92  * restricted to powers of 2 between 2**0 and 2**7 inclusively.  Offsets are
93  * restricted to multiples of the span.  The stored value for the offset is the
94  * "raw offset", which is the real offset divided by the span.
95  *
96  * Delta matches can cover data containing a series of power-of-2 sized integers
97  * that is linearly increasing or decreasing.  Another way of thinking about it
98  * is that a delta match can match a longer sequence that is interrupted by a
99  * non-matching byte, provided that the non-matching byte is a continuation of a
100  * linearly changing pattern.  Examples of files that may contain data like this
101  * are uncompressed bitmap images, uncompressed digital audio, and Unicode data
102  * tables.  To some extent, this match type is a replacement for delta filters
103  * or multimedia filters that are sometimes used in other compression software
104  * (e.g.  'xz --delta --lzma2').  However, on most types of files, delta matches
105  * do not seem to be very useful.
106  *
107  * Both LZ and delta matches may use overlapping sequences.  Therefore, they
108  * must be decoded as if only one byte is copied at a time.
109  *
110  * For both LZ and delta matches, any match length in [1, 1073809578] can be
111  * represented.  Similarly, any match offset in [1, 1180427428] can be
112  * represented.  For delta matches, this range applies to the raw offset, so the
113  * real offset may be larger.
114  *
115  * For LZ matches, up to 3 repeat offsets are allowed, similar to some other
116  * LZ-based formats such as LZX and LZMA.  They must updated in an LRU fashion,
117  * except for a quirk: inserting anything to the front of the queue must be
118  * delayed by one LZMS item.  The reason for this is presumably that there is
119  * almost no reason to code the same match offset twice in a row, since you
120  * might as well have coded a longer match at that offset.  For this same
121  * reason, it also is a requirement that when an offset in the queue is used,
122  * that offset is removed from the queue immediately (and made pending for
123  * front-insertion after the following decoded item), and everything to the
124  * right is shifted left one queue slot.  This creates a need for an "overflow"
125  * fourth entry in the queue, even though it is only possible to decode
126  * references to the first 3 entries at any given time.  The queue must be
127  * initialized to the offsets {1, 2, 3, 4}.
128  *
129  * Repeat delta matches are handled similarly, but for them the queue contains
130  * (power, raw offset) pairs.  This queue must be initialized to
131  * {(0, 1), (0, 2), (0, 3), (0, 4)}.
132  *
133  * Bits from the binary range decoder must be used to disambiguate item types.
134  * The range decoder must hold two state variables: the range, which must
135  * initially be set to 0xffffffff, and the current code, which must initially be
136  * set to the first 32 bits read from the forwards bitstream.  The range must be
137  * maintained above 0xffff; when it falls below 0xffff, both the range and code
138  * must be left-shifted by 16 bits and the low 16 bits of the code must be
139  * filled in with the next 16 bits from the forwards bitstream.
140  *
141  * To decode each bit, the binary range decoder requires a probability that is
142  * logically a real number between 0 and 1.  Multiplying this probability by the
143  * current range and taking the floor gives the bound between the 0-bit region of
144  * the range and the 1-bit region of the range.  However, in LZMS, probabilities
145  * are restricted to values of n/64 where n is an integer is between 1 and 63
146  * inclusively, so the implementation may use integer operations instead.
147  * Following calculation of the bound, if the current code is in the 0-bit
148  * region, the new range becomes the current code and the decoded bit is 0;
149  * otherwise, the bound must be subtracted from both the range and the code, and
150  * the decoded bit is 1.  More information about range coding can be found at
151  * https://en.wikipedia.org/wiki/Range_encoding.  Furthermore, note that the
152  * LZMA format also uses range coding and has public domain code available for
153  * it.
154  *
155  * The probability used to range-decode each bit must be taken from a table, of
156  * which one instance must exist for each distinct context, or "binary decision
157  * class", in which a range-decoded bit is needed.  At each call of the range
158  * decoder, the appropriate probability must be obtained by indexing the
159  * appropriate probability table with the last 4 (in the context disambiguating
160  * literals from matches), 5 (in the context disambiguating LZ matches from
161  * delta matches), or 6 (in all other contexts) bits recently range-decoded in
162  * that context, ordered such that the most recently decoded bit is the
163  * low-order bit of the index.
164  *
165  * Furthermore, each probability entry itself is variable, as its value must be
166  * maintained as n/64 where n is the number of 0 bits in the most recently
167  * decoded 64 bits with that same entry.  This allows the compressed
168  * representation to adapt to the input and use fewer bits to represent the most
169  * likely data; note that LZMA uses a similar scheme.  Initially, the most
170  * recently 64 decoded bits for each probability entry are assumed to be
171  * 0x0000000055555555 (high order to low order); therefore, all probabilities
172  * are initially 48/64.  During the course of decoding, each probability may be
173  * updated to as low as 0/64 (as a result of reading many consecutive 1 bits
174  * with that entry) or as high as 64/64 (as a result of reading many consecutive
175  * 0 bits with that entry); however, probabilities of 0/64 and 64/64 cannot be
176  * used as-is but rather must be adjusted to 1/64 and 63/64, respectively,
177  * before being used for range decoding.
178  *
179  * Representations of the LZMS items themselves must be read from the backwards
180  * bitstream.  For this, there are 5 different Huffman codes used:
181  *
182  *  - The literal code, used for decoding literal bytes.  Each of the 256
183  *    symbols represents a literal byte.  This code must be rebuilt whenever
184  *    1024 symbols have been decoded with it.
185  *
186  *  - The LZ offset code, used for decoding the offsets of standard LZ77
187  *    matches.  Each symbol represents an offset slot, which corresponds to a
188  *    base value and some number of extra bits which must be read and added to
189  *    the base value to reconstitute the full offset.  The number of symbols in
190  *    this code is the number of offset slots needed to represent all possible
191  *    offsets in the uncompressed block.  This code must be rebuilt whenever
192  *    1024 symbols have been decoded with it.
193  *
194  *  - The length code, used for decoding length symbols.  Each of the 54 symbols
195  *    represents a length slot, which corresponds to a base value and some
196  *    number of extra bits which must be read and added to the base value to
197  *    reconstitute the full length.  This code must be rebuilt whenever 512
198  *    symbols have been decoded with it.
199  *
200  *  - The delta offset code, used for decoding the raw offsets of delta matches.
201  *    Each symbol corresponds to an offset slot, which corresponds to a base
202  *    value and some number of extra bits which must be read and added to the
203  *    base value to reconstitute the full raw offset.  The number of symbols in
204  *    this code is equal to the number of symbols in the LZ offset code.  This
205  *    code must be rebuilt whenever 1024 symbols have been decoded with it.
206  *
207  *  - The delta power code, used for decoding the powers of delta matches.  Each
208  *    of the 8 symbols corresponds to a power.  This code must be rebuilt
209  *    whenever 512 symbols have been decoded with it.
210  *
211  * Initially, each Huffman code must be built assuming that each symbol in that
212  * code has frequency 1.  Following that, each code must be rebuilt each time a
213  * certain number of symbols, as noted above, has been decoded with it.  The
214  * symbol frequencies for a code must be halved after each rebuild of that code;
215  * this makes the codes adapt to the more recent data.
216  *
217  * Like other compression formats such as XPRESS, LZX, and DEFLATE, the LZMS
218  * format requires that all Huffman codes be constructed in canonical form.
219  * This form requires that same-length codewords be lexicographically ordered
220  * the same way as the corresponding symbols and that all shorter codewords
221  * lexicographically precede longer codewords.  Such a code can be constructed
222  * directly from codeword lengths.
223  *
224  * Even with the canonical code restriction, the same frequencies can be used to
225  * construct multiple valid Huffman codes.  Therefore, the decompressor needs to
226  * construct the right one.  Specifically, the LZMS format requires that the
227  * Huffman code be constructed as if the well-known priority queue algorithm is
228  * used and frequency ties are always broken in favor of leaf nodes.
229  *
230  * Codewords in LZMS are guaranteed to not exceed 15 bits.  The format otherwise
231  * places no restrictions on codeword length.  Therefore, the Huffman code
232  * construction algorithm that a correct LZMS decompressor uses need not
233  * implement length-limited code construction.  But if it does (e.g. by virtue
234  * of being shared among multiple compression algorithms), the details of how it
235  * does so are unimportant, provided that the maximum codeword length parameter
236  * is set to at least 15 bits.
237  *
238  * After all LZMS items have been decoded, the data must be postprocessed to
239  * translate absolute address encoded in x86 instructions into their original
240  * relative addresses.
241  *
242  * Details omitted above can be found in the code.  Note that in the absence of
243  * an official specification there is no guarantee that this decompressor
244  * handles all possible cases.
245  */
246
247 #ifdef HAVE_CONFIG_H
248 #  include "config.h"
249 #endif
250
251 #include "wimlib/compress_common.h"
252 #include "wimlib/decompress_common.h"
253 #include "wimlib/decompressor_ops.h"
254 #include "wimlib/error.h"
255 #include "wimlib/lzms_common.h"
256 #include "wimlib/util.h"
257
258 /* The TABLEBITS values can be changed; they only affect decoding speed.  */
259 #define LZMS_LITERAL_TABLEBITS          10
260 #define LZMS_LENGTH_TABLEBITS           9
261 #define LZMS_LZ_OFFSET_TABLEBITS        11
262 #define LZMS_DELTA_OFFSET_TABLEBITS     11
263 #define LZMS_DELTA_POWER_TABLEBITS      7
264
265 struct lzms_range_decoder {
266
267         /* The relevant part of the current range.  Although the logical range
268          * for range decoding is a very large integer, only a small portion
269          * matters at any given time, and it can be normalized (shifted left)
270          * whenever it gets too small.  */
271         u32 range;
272
273         /* The current position in the range encoded by the portion of the input
274          * read so far.  */
275         u32 code;
276
277         /* Pointer to the next little-endian 16-bit integer in the compressed
278          * input data (reading forwards).  */
279         const u8 *next;
280
281         /* Pointer to the end of the compressed input data.  */
282         const u8 *end;
283 };
284
285 typedef u64 bitbuf_t;
286
287 struct lzms_input_bitstream {
288
289         /* Holding variable for bits that have been read from the compressed
290          * data.  The bit ordering is high to low.  */
291         bitbuf_t bitbuf;
292
293         /* Number of bits currently held in @bitbuf.  */
294         unsigned bitsleft;
295
296         /* Pointer to the one past the next little-endian 16-bit integer in the
297          * compressed input data (reading backwards).  */
298         const u8 *next;
299
300         /* Pointer to the beginning of the compressed input data.  */
301         const u8 *begin;
302 };
303
304 #define BITBUF_NBITS    (8 * sizeof(bitbuf_t))
305
306 /* Bookkeeping information for an adaptive Huffman code  */
307 struct lzms_huffman_rebuild_info {
308         unsigned num_syms_until_rebuild;
309         unsigned num_syms;
310         unsigned rebuild_freq;
311         u32 *codewords;
312         u32 *freqs;
313         u16 *decode_table;
314         unsigned table_bits;
315 };
316
317 struct lzms_decompressor {
318
319         /* 'last_target_usages' is in union with everything else because it is
320          * only used for postprocessing.  */
321         union {
322         struct {
323
324         struct lzms_probabilites probs;
325
326         DECODE_TABLE(literal_decode_table, LZMS_NUM_LITERAL_SYMS,
327                      LZMS_LITERAL_TABLEBITS, LZMS_MAX_CODEWORD_LENGTH);
328         u32 literal_freqs[LZMS_NUM_LITERAL_SYMS];
329         struct lzms_huffman_rebuild_info literal_rebuild_info;
330
331         DECODE_TABLE(lz_offset_decode_table, LZMS_MAX_NUM_OFFSET_SYMS,
332                      LZMS_LZ_OFFSET_TABLEBITS, LZMS_MAX_CODEWORD_LENGTH);
333         u32 lz_offset_freqs[LZMS_MAX_NUM_OFFSET_SYMS];
334         struct lzms_huffman_rebuild_info lz_offset_rebuild_info;
335
336         DECODE_TABLE(length_decode_table, LZMS_NUM_LENGTH_SYMS,
337                      LZMS_LENGTH_TABLEBITS, LZMS_MAX_CODEWORD_LENGTH);
338         u32 length_freqs[LZMS_NUM_LENGTH_SYMS];
339         struct lzms_huffman_rebuild_info length_rebuild_info;
340
341         DECODE_TABLE(delta_offset_decode_table, LZMS_MAX_NUM_OFFSET_SYMS,
342                      LZMS_DELTA_OFFSET_TABLEBITS, LZMS_MAX_CODEWORD_LENGTH);
343         u32 delta_offset_freqs[LZMS_MAX_NUM_OFFSET_SYMS];
344         struct lzms_huffman_rebuild_info delta_offset_rebuild_info;
345
346         DECODE_TABLE(delta_power_decode_table, LZMS_NUM_DELTA_POWER_SYMS,
347                      LZMS_DELTA_POWER_TABLEBITS, LZMS_MAX_CODEWORD_LENGTH);
348         u32 delta_power_freqs[LZMS_NUM_DELTA_POWER_SYMS];
349         struct lzms_huffman_rebuild_info delta_power_rebuild_info;
350
351         /* Temporary space for lzms_build_huffman_code() */
352         union {
353                 u32 codewords[LZMS_MAX_NUM_SYMS];
354                 DECODE_TABLE_WORKING_SPACE(working_space, LZMS_MAX_NUM_SYMS,
355                                            LZMS_MAX_CODEWORD_LENGTH);
356         };
357
358         }; // struct
359
360         s32 last_target_usages[65536];
361
362         }; // union
363 };
364
365 /* Initialize the input bitstream @is to read backwards from the compressed data
366  * buffer @in that is @count bytes long.  */
367 static void
368 lzms_input_bitstream_init(struct lzms_input_bitstream *is,
369                           const u8 *in, size_t count)
370 {
371         is->bitbuf = 0;
372         is->bitsleft = 0;
373         is->next = in + count;
374         is->begin = in;
375 }
376
377 /* Ensure that at least @num_bits bits are in the bitbuffer variable.
378  * @num_bits cannot be more than 32.  */
379 static inline void
380 lzms_ensure_bits(struct lzms_input_bitstream *is, unsigned num_bits)
381 {
382         unsigned avail;
383
384         if (is->bitsleft >= num_bits)
385                 return;
386
387         avail = BITBUF_NBITS - is->bitsleft;
388
389         if (UNALIGNED_ACCESS_IS_FAST && CPU_IS_LITTLE_ENDIAN &&
390             WORDBYTES == 8 && likely(is->next - is->begin >= 8))
391         {
392                 is->next -= (avail & ~15) >> 3;
393                 is->bitbuf |= load_u64_unaligned(is->next) << (avail & 15);
394                 is->bitsleft += avail & ~15;
395         } else {
396                 if (likely(is->next != is->begin)) {
397                         is->next -= sizeof(le16);
398                         is->bitbuf |= (bitbuf_t)get_unaligned_le16(is->next)
399                                         << (avail - 16);
400                 }
401                 if (likely(is->next != is->begin)) {
402                         is->next -= sizeof(le16);
403                         is->bitbuf |= (bitbuf_t)get_unaligned_le16(is->next)
404                                         << (avail - 32);
405                 }
406                 is->bitsleft += 32;
407         }
408 }
409
410 /* Get @num_bits bits from the bitbuffer variable.  */
411 static inline bitbuf_t
412 lzms_peek_bits(struct lzms_input_bitstream *is, unsigned num_bits)
413 {
414         return (is->bitbuf >> 1) >> (BITBUF_NBITS - num_bits - 1);
415 }
416
417 /* Remove @num_bits bits from the bitbuffer variable.  */
418 static inline void
419 lzms_remove_bits(struct lzms_input_bitstream *is, unsigned num_bits)
420 {
421         is->bitbuf <<= num_bits;
422         is->bitsleft -= num_bits;
423 }
424
425 /* Remove and return @num_bits bits from the bitbuffer variable.  */
426 static inline bitbuf_t
427 lzms_pop_bits(struct lzms_input_bitstream *is, unsigned num_bits)
428 {
429         bitbuf_t bits = lzms_peek_bits(is, num_bits);
430         lzms_remove_bits(is, num_bits);
431         return bits;
432 }
433
434 /* Read @num_bits bits from the input bitstream.  */
435 static inline bitbuf_t
436 lzms_read_bits(struct lzms_input_bitstream *is, unsigned num_bits)
437 {
438         lzms_ensure_bits(is, num_bits);
439         return lzms_pop_bits(is, num_bits);
440 }
441
442 /* Initialize the range decoder @rd to read forwards from the compressed data
443  * buffer @in that is @count bytes long.  */
444 static void
445 lzms_range_decoder_init(struct lzms_range_decoder *rd,
446                         const u8 *in, size_t count)
447 {
448         rd->range = 0xffffffff;
449         rd->code = ((u32)get_unaligned_le16(in) << 16) |
450                    get_unaligned_le16(in + 2);
451         rd->next = in + 4;
452         rd->end = in + count;
453 }
454
455 /*
456  * Decode a bit using the range coder.  The current state specifies the
457  * probability entry to use.  The state and probability entry will be updated
458  * based on the decoded bit.
459  */
460 static inline int
461 lzms_decode_bit(struct lzms_range_decoder *rd, u32 *state_p, u32 num_states,
462                 struct lzms_probability_entry *probs)
463 {
464         struct lzms_probability_entry *prob_entry;
465         u32 prob;
466         u32 bound;
467
468         /* Load the probability entry corresponding to the current state.  */
469         prob_entry = &probs[*state_p];
470
471         /* Update the state early.  We'll still need to OR the state with 1
472          * later if the decoded bit is a 1.  */
473         *state_p = (*state_p << 1) & (num_states - 1);
474
475         /* Get the probability (out of LZMS_PROBABILITY_DENOMINATOR) that the
476          * next bit is 0.  */
477         prob = lzms_get_probability(prob_entry);
478
479         /* Normalize if needed.  */
480         if (!(rd->range & 0xFFFF0000)) {
481                 rd->range <<= 16;
482                 rd->code <<= 16;
483                 if (likely(rd->next != rd->end)) {
484                         rd->code |= get_unaligned_le16(rd->next);
485                         rd->next += sizeof(le16);
486                 }
487         }
488
489         /* Based on the probability, calculate the bound between the 0-bit
490          * region and the 1-bit region of the range.  */
491         bound = (rd->range >> LZMS_PROBABILITY_BITS) * prob;
492
493         if (rd->code < bound) {
494                 /* Current code is in the 0-bit region of the range.  */
495                 rd->range = bound;
496
497                 /* Update the state and probability entry based on the decoded bit.  */
498                 lzms_update_probability_entry(prob_entry, 0);
499                 return 0;
500         } else {
501                 /* Current code is in the 1-bit region of the range.  */
502                 rd->range -= bound;
503                 rd->code -= bound;
504
505                 /* Update the state and probability entry based on the decoded bit.  */
506                 lzms_update_probability_entry(prob_entry, 1);
507                 *state_p |= 1;
508                 return 1;
509         }
510 }
511
512 static void
513 lzms_build_huffman_code(struct lzms_huffman_rebuild_info *rebuild_info)
514 {
515         make_canonical_huffman_code(rebuild_info->num_syms,
516                                     LZMS_MAX_CODEWORD_LENGTH,
517                                     rebuild_info->freqs,
518                                     (u8 *)rebuild_info->decode_table,
519                                     rebuild_info->codewords);
520
521         make_huffman_decode_table(rebuild_info->decode_table,
522                                   rebuild_info->num_syms,
523                                   rebuild_info->table_bits,
524                                   (u8 *)rebuild_info->decode_table,
525                                   LZMS_MAX_CODEWORD_LENGTH,
526                                   (u16 *)rebuild_info->codewords);
527
528         rebuild_info->num_syms_until_rebuild = rebuild_info->rebuild_freq;
529 }
530
531 static void
532 lzms_init_huffman_code(struct lzms_huffman_rebuild_info *rebuild_info,
533                        unsigned num_syms, unsigned rebuild_freq,
534                        u32 *codewords, u32 *freqs,
535                        u16 *decode_table, unsigned table_bits)
536 {
537         rebuild_info->num_syms = num_syms;
538         rebuild_info->rebuild_freq = rebuild_freq;
539         rebuild_info->codewords = codewords;
540         rebuild_info->freqs = freqs;
541         rebuild_info->decode_table = decode_table;
542         rebuild_info->table_bits = table_bits;
543         lzms_init_symbol_frequencies(freqs, num_syms);
544         lzms_build_huffman_code(rebuild_info);
545 }
546
547 static void
548 lzms_init_huffman_codes(struct lzms_decompressor *d, unsigned num_offset_slots)
549 {
550         lzms_init_huffman_code(&d->literal_rebuild_info,
551                                LZMS_NUM_LITERAL_SYMS,
552                                LZMS_LITERAL_CODE_REBUILD_FREQ,
553                                d->codewords,
554                                d->literal_freqs,
555                                d->literal_decode_table,
556                                LZMS_LITERAL_TABLEBITS);
557
558         lzms_init_huffman_code(&d->lz_offset_rebuild_info,
559                                num_offset_slots,
560                                LZMS_LZ_OFFSET_CODE_REBUILD_FREQ,
561                                d->codewords,
562                                d->lz_offset_freqs,
563                                d->lz_offset_decode_table,
564                                LZMS_LZ_OFFSET_TABLEBITS);
565
566         lzms_init_huffman_code(&d->length_rebuild_info,
567                                LZMS_NUM_LENGTH_SYMS,
568                                LZMS_LENGTH_CODE_REBUILD_FREQ,
569                                d->codewords,
570                                d->length_freqs,
571                                d->length_decode_table,
572                                LZMS_LENGTH_TABLEBITS);
573
574         lzms_init_huffman_code(&d->delta_offset_rebuild_info,
575                                num_offset_slots,
576                                LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ,
577                                d->codewords,
578                                d->delta_offset_freqs,
579                                d->delta_offset_decode_table,
580                                LZMS_DELTA_OFFSET_TABLEBITS);
581
582         lzms_init_huffman_code(&d->delta_power_rebuild_info,
583                                LZMS_NUM_DELTA_POWER_SYMS,
584                                LZMS_DELTA_POWER_CODE_REBUILD_FREQ,
585                                d->codewords,
586                                d->delta_power_freqs,
587                                d->delta_power_decode_table,
588                                LZMS_DELTA_POWER_TABLEBITS);
589 }
590
591 static noinline void
592 lzms_rebuild_huffman_code(struct lzms_huffman_rebuild_info *rebuild_info)
593 {
594         lzms_build_huffman_code(rebuild_info);
595         lzms_dilute_symbol_frequencies(rebuild_info->freqs, rebuild_info->num_syms);
596 }
597
598 /* XXX: mostly copied from read_huffsym() in decompress_common.h because LZMS
599  * needs its own bitstream */
600 static inline unsigned
601 lzms_decode_huffman_symbol(struct lzms_input_bitstream *is, u16 decode_table[],
602                            unsigned table_bits, u32 freqs[],
603                            struct lzms_huffman_rebuild_info *rebuild_info)
604 {
605         unsigned entry;
606         unsigned symbol;
607         unsigned length;
608
609         lzms_ensure_bits(is, LZMS_MAX_CODEWORD_LENGTH);
610
611         entry = decode_table[lzms_peek_bits(is, table_bits)];
612         symbol = entry >> DECODE_TABLE_SYMBOL_SHIFT;
613         length = entry & DECODE_TABLE_LENGTH_MASK;
614
615         if (entry >= (1U << (table_bits + DECODE_TABLE_SYMBOL_SHIFT))) {
616                 lzms_remove_bits(is, table_bits);
617                 entry = decode_table[symbol + lzms_peek_bits(is, length)];
618                 symbol = entry >> DECODE_TABLE_SYMBOL_SHIFT;
619                 length = entry & DECODE_TABLE_LENGTH_MASK;
620         }
621
622         lzms_remove_bits(is, length);
623
624         freqs[symbol]++;
625         if (--rebuild_info->num_syms_until_rebuild == 0)
626                 lzms_rebuild_huffman_code(rebuild_info);
627         return symbol;
628 }
629
630 static inline unsigned
631 lzms_decode_literal(struct lzms_decompressor *d,
632                     struct lzms_input_bitstream *is)
633 {
634         return lzms_decode_huffman_symbol(is,
635                                           d->literal_decode_table,
636                                           LZMS_LITERAL_TABLEBITS,
637                                           d->literal_freqs,
638                                           &d->literal_rebuild_info);
639 }
640
641 static inline u32
642 lzms_decode_lz_offset(struct lzms_decompressor *d,
643                       struct lzms_input_bitstream *is)
644 {
645         unsigned slot = lzms_decode_huffman_symbol(is,
646                                                    d->lz_offset_decode_table,
647                                                    LZMS_LZ_OFFSET_TABLEBITS,
648                                                    d->lz_offset_freqs,
649                                                    &d->lz_offset_rebuild_info);
650         return lzms_offset_slot_base[slot] +
651                lzms_read_bits(is, lzms_extra_offset_bits[slot]);
652 }
653
654 static inline u32
655 lzms_decode_length(struct lzms_decompressor *d,
656                    struct lzms_input_bitstream *is)
657 {
658         unsigned slot = lzms_decode_huffman_symbol(is,
659                                                    d->length_decode_table,
660                                                    LZMS_LENGTH_TABLEBITS,
661                                                    d->length_freqs,
662                                                    &d->length_rebuild_info);
663         u32 length = lzms_length_slot_base[slot];
664         unsigned num_extra_bits = lzms_extra_length_bits[slot];
665         /* Usually most lengths are short and have no extra bits.  */
666         if (num_extra_bits)
667                 length += lzms_read_bits(is, num_extra_bits);
668         return length;
669 }
670
671 static inline u32
672 lzms_decode_delta_offset(struct lzms_decompressor *d,
673                          struct lzms_input_bitstream *is)
674 {
675         unsigned slot = lzms_decode_huffman_symbol(is,
676                                                    d->delta_offset_decode_table,
677                                                    LZMS_DELTA_OFFSET_TABLEBITS,
678                                                    d->delta_offset_freqs,
679                                                    &d->delta_offset_rebuild_info);
680         return lzms_offset_slot_base[slot] +
681                lzms_read_bits(is, lzms_extra_offset_bits[slot]);
682 }
683
684 static inline unsigned
685 lzms_decode_delta_power(struct lzms_decompressor *d,
686                         struct lzms_input_bitstream *is)
687 {
688         return lzms_decode_huffman_symbol(is,
689                                           d->delta_power_decode_table,
690                                           LZMS_DELTA_POWER_TABLEBITS,
691                                           d->delta_power_freqs,
692                                           &d->delta_power_rebuild_info);
693 }
694
695 static int
696 lzms_create_decompressor(size_t max_bufsize, void **d_ret)
697 {
698         struct lzms_decompressor *d;
699
700         if (max_bufsize > LZMS_MAX_BUFFER_SIZE)
701                 return WIMLIB_ERR_INVALID_PARAM;
702
703         d = ALIGNED_MALLOC(sizeof(struct lzms_decompressor),
704                            DECODE_TABLE_ALIGNMENT);
705         if (!d)
706                 return WIMLIB_ERR_NOMEM;
707
708         *d_ret = d;
709         return 0;
710 }
711
712 /*
713  * Decompress @in_nbytes bytes of LZMS-compressed data at @in and write the
714  * uncompressed data, which had original size @out_nbytes, to @out.  Return 0 if
715  * successful or -1 if the compressed data is invalid.
716  */
717 static int
718 lzms_decompress(const void * const restrict in, const size_t in_nbytes,
719                 void * const restrict out, const size_t out_nbytes,
720                 void * const restrict _d)
721 {
722         struct lzms_decompressor *d = _d;
723         u8 *out_next = out;
724         u8 * const out_end = out + out_nbytes;
725         struct lzms_range_decoder rd;
726         struct lzms_input_bitstream is;
727
728         /* LRU queues for match sources  */
729         u32 recent_lz_offsets[LZMS_NUM_LZ_REPS + 1];
730         u64 recent_delta_pairs[LZMS_NUM_DELTA_REPS + 1];
731
732         /* Previous item type: 0 = literal, 1 = LZ match, 2 = delta match.
733          * This is used to handle delayed updates of the LRU queues.  Instead of
734          * actually delaying the updates, we can check when decoding each rep
735          * match whether a delayed update needs to be taken into account, and if
736          * so get the match source from slot 'rep_idx + 1' instead of from slot
737          * 'rep_idx'.  */
738         unsigned prev_item_type = 0;
739
740         /* States and probability entries for item type disambiguation  */
741         u32 main_state = 0;
742         u32 match_state = 0;
743         u32 lz_state = 0;
744         u32 delta_state = 0;
745         u32 lz_rep_states[LZMS_NUM_LZ_REP_DECISIONS] = {};
746         u32 delta_rep_states[LZMS_NUM_DELTA_REP_DECISIONS] = {};
747
748         /*
749          * Requirements on the compressed data:
750          *
751          * 1. LZMS-compressed data is a series of 16-bit integers, so the
752          *    compressed data buffer cannot take up an odd number of bytes.
753          * 2. There must be at least 4 bytes of compressed data, since otherwise
754          *    we cannot even initialize the range decoder.
755          */
756         if ((in_nbytes & 1) || (in_nbytes < 4))
757                 return -1;
758
759         lzms_range_decoder_init(&rd, in, in_nbytes);
760
761         lzms_input_bitstream_init(&is, in, in_nbytes);
762
763         lzms_init_probabilities(&d->probs);
764
765         lzms_init_huffman_codes(d, lzms_get_num_offset_slots(out_nbytes));
766
767         for (int i = 0; i < LZMS_NUM_LZ_REPS + 1; i++)
768                 recent_lz_offsets[i] = i + 1;
769
770         for (int i = 0; i < LZMS_NUM_DELTA_REPS + 1; i++)
771                 recent_delta_pairs[i] = i + 1;
772
773         /* Main decode loop  */
774         while (out_next != out_end) {
775
776                 if (!lzms_decode_bit(&rd, &main_state,
777                                      LZMS_NUM_MAIN_PROBS, d->probs.main))
778                 {
779                         /* Literal  */
780                         *out_next++ = lzms_decode_literal(d, &is);
781                         prev_item_type = 0;
782
783                 } else if (!lzms_decode_bit(&rd, &match_state,
784                                             LZMS_NUM_MATCH_PROBS,
785                                             d->probs.match))
786                 {
787                         /* LZ match  */
788
789                         u32 offset;
790                         u32 length;
791
792                         STATIC_ASSERT(LZMS_NUM_LZ_REPS == 3);
793
794                         if (!lzms_decode_bit(&rd, &lz_state,
795                                              LZMS_NUM_LZ_PROBS, d->probs.lz))
796                         {
797                                 /* Explicit offset  */
798                                 offset = lzms_decode_lz_offset(d, &is);
799
800                                 recent_lz_offsets[3] = recent_lz_offsets[2];
801                                 recent_lz_offsets[2] = recent_lz_offsets[1];
802                                 recent_lz_offsets[1] = recent_lz_offsets[0];
803                         } else {
804                                 /* Repeat offset  */
805
806                                 if (!lzms_decode_bit(&rd, &lz_rep_states[0],
807                                                      LZMS_NUM_LZ_REP_PROBS,
808                                                      d->probs.lz_rep[0]))
809                                 {
810                                         offset = recent_lz_offsets[0 + (prev_item_type & 1)];
811                                         recent_lz_offsets[0 + (prev_item_type & 1)] = recent_lz_offsets[0];
812                                 } else if (!lzms_decode_bit(&rd, &lz_rep_states[1],
813                                                             LZMS_NUM_LZ_REP_PROBS,
814                                                             d->probs.lz_rep[1]))
815                                 {
816                                         offset = recent_lz_offsets[1 + (prev_item_type & 1)];
817                                         recent_lz_offsets[1 + (prev_item_type & 1)] = recent_lz_offsets[1];
818                                         recent_lz_offsets[1] = recent_lz_offsets[0];
819                                 } else {
820                                         offset = recent_lz_offsets[2 + (prev_item_type & 1)];
821                                         recent_lz_offsets[2 + (prev_item_type & 1)] = recent_lz_offsets[2];
822                                         recent_lz_offsets[2] = recent_lz_offsets[1];
823                                         recent_lz_offsets[1] = recent_lz_offsets[0];
824                                 }
825                         }
826                         recent_lz_offsets[0] = offset;
827                         prev_item_type = 1;
828
829                         length = lzms_decode_length(d, &is);
830
831                         if (unlikely(lz_copy(length, offset, out, out_next, out_end,
832                                              LZMS_MIN_MATCH_LENGTH)))
833                                 return -1;
834
835                         out_next += length;
836                 } else {
837                         /* Delta match  */
838
839                         /* (See beginning of file for more information.)  */
840
841                         u32 power;
842                         u32 raw_offset;
843                         u32 span;
844                         u32 offset;
845                         const u8 *matchptr;
846                         u32 length;
847                         u64 pair;
848
849                         STATIC_ASSERT(LZMS_NUM_DELTA_REPS == 3);
850
851                         if (!lzms_decode_bit(&rd, &delta_state,
852                                              LZMS_NUM_DELTA_PROBS,
853                                              d->probs.delta))
854                         {
855                                 /* Explicit offset  */
856                                 power = lzms_decode_delta_power(d, &is);
857                                 raw_offset = lzms_decode_delta_offset(d, &is);
858
859                                 pair = ((u64)power << 32) | raw_offset;
860                                 recent_delta_pairs[3] = recent_delta_pairs[2];
861                                 recent_delta_pairs[2] = recent_delta_pairs[1];
862                                 recent_delta_pairs[1] = recent_delta_pairs[0];
863                         } else {
864                                 if (!lzms_decode_bit(&rd, &delta_rep_states[0],
865                                                      LZMS_NUM_DELTA_REP_PROBS,
866                                                      d->probs.delta_rep[0]))
867                                 {
868                                         pair = recent_delta_pairs[0 + (prev_item_type >> 1)];
869                                         recent_delta_pairs[0 + (prev_item_type >> 1)] = recent_delta_pairs[0];
870                                 } else if (!lzms_decode_bit(&rd, &delta_rep_states[1],
871                                                             LZMS_NUM_DELTA_REP_PROBS,
872                                                             d->probs.delta_rep[1]))
873                                 {
874                                         pair = recent_delta_pairs[1 + (prev_item_type >> 1)];
875                                         recent_delta_pairs[1 + (prev_item_type >> 1)] = recent_delta_pairs[1];
876                                         recent_delta_pairs[1] = recent_delta_pairs[0];
877                                 } else {
878                                         pair = recent_delta_pairs[2 + (prev_item_type >> 1)];
879                                         recent_delta_pairs[2 + (prev_item_type >> 1)] = recent_delta_pairs[2];
880                                         recent_delta_pairs[2] = recent_delta_pairs[1];
881                                         recent_delta_pairs[1] = recent_delta_pairs[0];
882                                 }
883
884                                 power = pair >> 32;
885                                 raw_offset = (u32)pair;
886                         }
887                         recent_delta_pairs[0] = pair;
888                         prev_item_type = 2;
889
890                         length = lzms_decode_length(d, &is);
891
892                         span = (u32)1 << power;
893                         offset = raw_offset << power;
894
895                         /* raw_offset<<power overflows?  */
896                         if (unlikely(offset >> power != raw_offset))
897                                 return -1;
898
899                         /* offset+span overflows?  */
900                         if (unlikely(offset + span < offset))
901                                 return -1;
902
903                         /* buffer underrun?  */
904                         if (unlikely(offset + span > out_next - (u8 *)out))
905                                 return -1;
906
907                         /* buffer overrun?  */
908                         if (unlikely(length > out_end - out_next))
909                                 return -1;
910
911                         matchptr = out_next - offset;
912                         do {
913                                 *out_next = *matchptr + *(out_next - span) -
914                                             *(matchptr - span);
915                                 out_next++;
916                                 matchptr++;
917                         } while (--length);
918                 }
919         }
920
921         lzms_x86_filter(out, out_nbytes, d->last_target_usages, true);
922         return 0;
923 }
924
925 static void
926 lzms_free_decompressor(void *_d)
927 {
928         struct lzms_decompressor *d = _d;
929
930         ALIGNED_FREE(d);
931 }
932
933 const struct decompressor_ops lzms_decompressor_ops = {
934         .create_decompressor  = lzms_create_decompressor,
935         .decompress           = lzms_decompress,
936         .free_decompressor    = lzms_free_decompressor,
937 };