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