]> wimlib.net Git - wimlib/blob - src/lzx-decompress.c
Faster Huffman symbol decoding
[wimlib] / src / lzx-decompress.c
1 /*
2  * lzx-decompress.c
3  *
4  * LZX decompression routines, originally based on code taken from cabextract
5  * v0.5, which was, itself, a modified version of the lzx decompression code
6  * from unlzx.
7  */
8
9 /*
10  * Copyright (C) 2012, 2013, 2014 Eric Biggers
11  *
12  * This file is part of wimlib, a library for working with WIM files.
13  *
14  * wimlib is free software; you can redistribute it and/or modify it under the
15  * terms of the GNU General Public License as published by the Free
16  * Software Foundation; either version 3 of the License, or (at your option)
17  * any later version.
18  *
19  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21  * A PARTICULAR PURPOSE. See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with wimlib; if not, see http://www.gnu.org/licenses/.
26  */
27
28 /*
29  * LZX is an LZ77 and Huffman-code based compression format that has many
30  * similarities to the DEFLATE format used in zlib.  The compression ratio is as
31  * good or better than DEFLATE.
32  *
33  * Some notes on the LZX compression format as used in Windows Imaging (WIM)
34  * files:
35  *
36  * A compressed WIM resource consists of a table of chunk offsets followed by
37  * the compressed chunks themselves.  All compressed chunks except possibly the
38  * last decompress to a fixed number of bytes, by default 32768.  This is quite
39  * similar to the cabinet (.cab) file format, but they are not the same.
40  * According to the cabinet format documentation, the LZX block size is
41  * independent from the CFDATA blocks, and an LZX block may span several CFDATA
42  * blocks.  However, in WIMs, LZX blocks do not appear to ever span multiple WIM
43  * chunks.  Note that this means any WIM chunk may be decompressed or compressed
44  * independently from any other chunk, which allows random access.
45  *
46  * An LZX compressed WIM chunk contains one or more LZX blocks of the aligned,
47  * verbatim, or uncompressed block types.  For aligned and verbatim blocks, the
48  * size of the block in uncompressed bytes is specified by a bit following the 3
49  * bits that specify the block type, possibly followed by an additional 16 bits.
50  * '1' means to use the default block size (equal to 32768, the default size of
51  * a WIM chunk), while '0' means that the block size is provided by the next 16
52  * bits.
53  *
54  * The cabinet format, as documented, allows for the possibility that a
55  * compressed CFDATA chunk is up to 6144 bytes larger than the data it
56  * uncompresses to.  However, in the WIM format it appears that every chunk that
57  * would be 32768 bytes or more when compressed is actually stored fully
58  * uncompressed.
59  *
60  * The 'e8' preprocessing step that changes x86 call instructions to use
61  * absolute offsets instead of relative offsets relies on a filesize parameter.
62  * There is no such parameter for this in the WIM files (even though the size of
63  * the file resource could be used for this purpose), and instead a magic file
64  * size of 12000000 is used.  The 'e8' preprocessing is always done, and there
65  * is no bit to indicate whether it is done or not.
66  */
67
68 /*
69  * Some more notes about errors in Microsoft's LZX documentation:
70  *
71  * Microsoft's LZX document and their implementation of the com.ms.util.cab Java
72  * package do not concur.
73  *
74  * In the LZX document, there is a table showing the correlation between window
75  * size and the number of position slots. It states that the 1MB window = 40
76  * slots and the 2MB window = 42 slots. In the implementation, 1MB = 42 slots,
77  * 2MB = 50 slots. The actual calculation is 'find the first slot whose position
78  * base is equal to or more than the required window size'. This would explain
79  * why other tables in the document refer to 50 slots rather than 42.
80  *
81  * The constant NUM_PRIMARY_LENS used in the decompression pseudocode is not
82  * defined in the specification.
83  *
84  * The LZX document states that aligned offset blocks have their aligned offset
85  * Huffman tree AFTER the main and length trees. The implementation suggests
86  * that the aligned offset tree is BEFORE the main and length trees.
87  *
88  * The LZX document decoding algorithm states that, in an aligned offset block,
89  * if an extra_bits value is 1, 2 or 3, then that number of bits should be read
90  * and the result added to the match offset. This is correct for 1 and 2, but
91  * not 3, where just a Huffman symbol (using the aligned tree) should be read.
92  *
93  * Regarding the E8 preprocessing, the LZX document states 'No translation may
94  * be performed on the last 6 bytes of the input block'. This is correct.
95  * However, the pseudocode provided checks for the *E8 leader* up to the last 6
96  * bytes. If the leader appears between -10 and -7 bytes from the end, this
97  * would cause the next four bytes to be modified, at least one of which would
98  * be in the last 6 bytes, which is not allowed according to the spec.
99  *
100  * The specification states that the Huffman trees must always contain at least
101  * one element. However, many CAB files contain blocks where the length tree is
102  * completely empty (because there are no matches), and this is expected to
103  * succeed.
104  */
105
106 #ifdef HAVE_CONFIG_H
107 #  include "config.h"
108 #endif
109
110 #include "wimlib.h"
111 #include "wimlib/decompressor_ops.h"
112 #include "wimlib/decompress_common.h"
113 #include "wimlib/lzx.h"
114 #include "wimlib/util.h"
115
116 #include <string.h>
117
118 #ifdef __SSE2__
119 #  include <emmintrin.h>
120 #endif
121
122 /* Huffman decoding tables and maps from symbols to code lengths. */
123 struct lzx_tables {
124
125         u16 maintree_decode_table[(1 << LZX_MAINCODE_TABLEBITS) +
126                                         (LZX_MAINCODE_MAX_NUM_SYMBOLS * 2)]
127                                         _aligned_attribute(DECODE_TABLE_ALIGNMENT);
128         u8 maintree_lens[LZX_MAINCODE_MAX_NUM_SYMBOLS];
129
130
131         u16 lentree_decode_table[(1 << LZX_LENCODE_TABLEBITS) +
132                                         (LZX_LENCODE_NUM_SYMBOLS * 2)]
133                                         _aligned_attribute(DECODE_TABLE_ALIGNMENT);
134         u8 lentree_lens[LZX_LENCODE_NUM_SYMBOLS];
135
136
137         u16 alignedtree_decode_table[(1 << LZX_ALIGNEDCODE_TABLEBITS) +
138                                         (LZX_ALIGNEDCODE_NUM_SYMBOLS * 2)]
139                                         _aligned_attribute(DECODE_TABLE_ALIGNMENT);
140         u8 alignedtree_lens[LZX_ALIGNEDCODE_NUM_SYMBOLS];
141 } _aligned_attribute(DECODE_TABLE_ALIGNMENT);
142
143 struct lzx_decompressor {
144         u32 max_window_size;
145         unsigned num_main_syms;
146         struct lzx_tables tables;
147 };
148
149 /*
150  * Reads a Huffman-encoded symbol using the pre-tree.
151  */
152 static inline u16
153 read_huffsym_using_pretree(struct input_bitstream *istream,
154                            const u16 pretree_decode_table[])
155 {
156         return read_huffsym(istream, pretree_decode_table,
157                             LZX_PRECODE_NUM_SYMBOLS, LZX_PRECODE_TABLEBITS,
158                             LZX_MAX_PRE_CODEWORD_LEN);
159 }
160
161 /* Reads a Huffman-encoded symbol using the main tree. */
162 static inline u16
163 read_huffsym_using_maintree(struct input_bitstream *istream,
164                             const struct lzx_tables *tables,
165                             unsigned num_main_syms)
166 {
167         return read_huffsym(istream, tables->maintree_decode_table,
168                             num_main_syms,
169                             LZX_MAINCODE_TABLEBITS, LZX_MAX_MAIN_CODEWORD_LEN);
170 }
171
172 /* Reads a Huffman-encoded symbol using the length tree. */
173 static inline u16
174 read_huffsym_using_lentree(struct input_bitstream *istream,
175                            const struct lzx_tables *tables)
176 {
177         return read_huffsym(istream, tables->lentree_decode_table,
178                             LZX_LENCODE_NUM_SYMBOLS,
179                             LZX_LENCODE_TABLEBITS, LZX_MAX_LEN_CODEWORD_LEN);
180 }
181
182 /* Reads a Huffman-encoded symbol using the aligned offset tree. */
183 static inline u16
184 read_huffsym_using_alignedtree(struct input_bitstream *istream,
185                                const struct lzx_tables *tables)
186 {
187         return read_huffsym(istream, tables->alignedtree_decode_table,
188                             LZX_ALIGNEDCODE_NUM_SYMBOLS,
189                             LZX_ALIGNEDCODE_TABLEBITS,
190                             LZX_MAX_ALIGNED_CODEWORD_LEN);
191 }
192
193 /*
194  * Reads the pretree from the input, then uses the pretree to decode @num_lens
195  * code length values from the input.
196  *
197  * @istream:    The bit stream for the input.  It is positioned on the beginning
198  *                      of the pretree for the code length values.
199  * @lens:       An array that contains the length values from the previous time
200  *                      the code lengths for this Huffman tree were read, or all
201  *                      0's if this is the first time.
202  * @num_lens:   Number of length values to decode and return.
203  *
204  */
205 static int
206 lzx_read_code_lens(struct input_bitstream *istream, u8 lens[],
207                    unsigned num_lens)
208 {
209         /* Declare the decoding table and length table for the pretree. */
210         u16 pretree_decode_table[(1 << LZX_PRECODE_TABLEBITS) +
211                                         (LZX_PRECODE_NUM_SYMBOLS * 2)]
212                                         _aligned_attribute(DECODE_TABLE_ALIGNMENT);
213         u8 pretree_lens[LZX_PRECODE_NUM_SYMBOLS];
214         unsigned i;
215         int ret;
216
217         /* Read the code lengths of the pretree codes.  There are 20 lengths of
218          * 4 bits each. */
219         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++) {
220                 pretree_lens[i] = bitstream_read_bits(istream,
221                                                       LZX_PRECODE_ELEMENT_SIZE);
222         }
223
224         /* Make the decoding table for the pretree. */
225         ret = make_huffman_decode_table(pretree_decode_table,
226                                         LZX_PRECODE_NUM_SYMBOLS,
227                                         LZX_PRECODE_TABLEBITS,
228                                         pretree_lens,
229                                         LZX_MAX_PRE_CODEWORD_LEN);
230         if (ret)
231                 return ret;
232
233         /* Pointer past the last length value that needs to be filled in. */
234         u8 *lens_end = lens + num_lens;
235
236         while (1) {
237
238                 /* Decode a symbol from the input.  If the symbol is between 0
239                  * and 16, it is the difference from the old length.  If it is
240                  * between 17 and 19, it is a special code that indicates that
241                  * some number of the next lengths are all 0, or some number of
242                  * the next lengths are all equal to the next symbol in the
243                  * input. */
244                 unsigned tree_code;
245                 u32 num_zeroes;
246                 unsigned code;
247                 u32 num_same;
248                 signed char value;
249
250                 tree_code = read_huffsym_using_pretree(istream,
251                                                        pretree_decode_table);
252                 switch (tree_code) {
253                 case 17: /* Run of 0's */
254                         num_zeroes = bitstream_read_bits(istream, 4);
255                         num_zeroes += 4;
256                         while (num_zeroes--) {
257                                 *lens = 0;
258                                 if (++lens == lens_end)
259                                         return 0;
260                         }
261                         break;
262                 case 18: /* Longer run of 0's */
263                         num_zeroes = bitstream_read_bits(istream, 5);
264                         num_zeroes += 20;
265                         while (num_zeroes--) {
266                                 *lens = 0;
267                                 if (++lens == lens_end)
268                                         return 0;
269                         }
270                         break;
271                 case 19: /* Run of identical lengths */
272                         num_same = bitstream_read_bits(istream, 1);
273                         num_same += 4;
274                         code = read_huffsym_using_pretree(istream,
275                                                           pretree_decode_table);
276                         value = (signed char)*lens - (signed char)code;
277                         if (value < 0)
278                                 value += 17;
279                         while (num_same--) {
280                                 *lens = value;
281                                 if (++lens == lens_end)
282                                         return 0;
283                         }
284                         break;
285                 default: /* Difference from old length. */
286                         value = (signed char)*lens - (signed char)tree_code;
287                         if (value < 0)
288                                 value += 17;
289                         *lens = value;
290                         if (++lens == lens_end)
291                                 return 0;
292                         break;
293                 }
294         }
295 }
296
297 /*
298  * Reads the header for an LZX-compressed block.
299  *
300  * @istream:            The input bitstream.
301  * @block_size_ret:     A pointer to an int into which the size of the block,
302  *                              in bytes, will be returned.
303  * @block_type_ret:     A pointer to an int into which the type of the block
304  *                              (LZX_BLOCKTYPE_*) will be returned.
305  * @tables:             A pointer to an lzx_tables structure in which the
306  *                              main tree, the length tree, and possibly the
307  *                              aligned offset tree will be constructed.
308  * @queue:      A pointer to the least-recently-used queue into which
309  *                      R0, R1, and R2 will be written (only for uncompressed
310  *                      blocks, which contain this information in the header)
311  */
312 static int
313 lzx_read_block_header(struct input_bitstream *istream,
314                       unsigned num_main_syms,
315                       unsigned max_window_size,
316                       unsigned *block_size_ret,
317                       unsigned *block_type_ret,
318                       struct lzx_tables *tables,
319                       struct lzx_lru_queue *queue)
320 {
321         int ret;
322         unsigned block_type;
323         unsigned block_size;
324
325         bitstream_ensure_bits(istream, 4);
326
327         /* The first three bits tell us what kind of block it is, and are one
328          * of the LZX_BLOCKTYPE_* values.  */
329         block_type = bitstream_pop_bits(istream, 3);
330
331         /* Read the block size.  This mirrors the behavior
332          * lzx_write_compressed_block() in lzx-compress.c; see that for more
333          * details.  */
334         if (bitstream_pop_bits(istream, 1)) {
335                 block_size = LZX_DEFAULT_BLOCK_SIZE;
336         } else {
337                 u32 tmp;
338                 block_size = 0;
339
340                 tmp = bitstream_read_bits(istream, 8);
341                 block_size |= tmp;
342                 tmp = bitstream_read_bits(istream, 8);
343                 block_size <<= 8;
344                 block_size |= tmp;
345
346                 if (max_window_size >= 65536) {
347                         tmp = bitstream_read_bits(istream, 8);
348                         block_size <<= 8;
349                         block_size |= tmp;
350                 }
351         }
352
353         switch (block_type) {
354         case LZX_BLOCKTYPE_ALIGNED:
355                 /* Read the path lengths for the elements of the aligned tree,
356                  * then build it. */
357
358                 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
359                         tables->alignedtree_lens[i] =
360                                 bitstream_read_bits(istream,
361                                                     LZX_ALIGNEDCODE_ELEMENT_SIZE);
362                 }
363
364                 LZX_DEBUG("Building the aligned tree.");
365                 ret = make_huffman_decode_table(tables->alignedtree_decode_table,
366                                                 LZX_ALIGNEDCODE_NUM_SYMBOLS,
367                                                 LZX_ALIGNEDCODE_TABLEBITS,
368                                                 tables->alignedtree_lens,
369                                                 LZX_MAX_ALIGNED_CODEWORD_LEN);
370                 if (ret) {
371                         LZX_DEBUG("Failed to make the decode table for the "
372                                   "aligned offset tree");
373                         return ret;
374                 }
375
376                 /* Fall though, since the rest of the header for aligned offset
377                  * blocks is the same as that for verbatim blocks */
378
379         case LZX_BLOCKTYPE_VERBATIM:
380                 if (block_type == LZX_BLOCKTYPE_VERBATIM)
381                         LZX_DEBUG("Found verbatim block.");
382
383                 LZX_DEBUG("Reading path lengths for main tree.");
384                 /* Read the path lengths for the first 256 elements of the main
385                  * tree. */
386                 ret = lzx_read_code_lens(istream, tables->maintree_lens,
387                                          LZX_NUM_CHARS);
388                 if (ret) {
389                         LZX_DEBUG("Failed to read the code lengths for the "
390                                   "first 256 elements of the main tree");
391                         return ret;
392                 }
393
394                 /* Read the path lengths for the remaining elements of the main
395                  * tree. */
396                 LZX_DEBUG("Reading path lengths for remaining elements of "
397                           "main tree (%d elements).",
398                           num_main_syms - LZX_NUM_CHARS);
399                 ret = lzx_read_code_lens(istream,
400                                          tables->maintree_lens + LZX_NUM_CHARS,
401                                          num_main_syms - LZX_NUM_CHARS);
402                 if (ret) {
403                         LZX_DEBUG("Failed to read the path lengths for the "
404                                   "remaining elements of the main tree");
405                         return ret;
406                 }
407
408                 LZX_DEBUG("Building the Huffman decoding "
409                           "table for the main tree.");
410
411                 ret = make_huffman_decode_table(tables->maintree_decode_table,
412                                                 num_main_syms,
413                                                 LZX_MAINCODE_TABLEBITS,
414                                                 tables->maintree_lens,
415                                                 LZX_MAX_MAIN_CODEWORD_LEN);
416                 if (ret) {
417                         LZX_DEBUG("Failed to make the decode "
418                                   "table for the main tree");
419                         return ret;
420                 }
421
422                 LZX_DEBUG("Reading path lengths for the length tree.");
423                 ret = lzx_read_code_lens(istream, tables->lentree_lens,
424                                          LZX_LENCODE_NUM_SYMBOLS);
425                 if (ret) {
426                         LZX_DEBUG("Failed to read the path "
427                                   "lengths for the length tree");
428                         return ret;
429                 }
430
431                 LZX_DEBUG("Building the length tree.");
432                 ret = make_huffman_decode_table(tables->lentree_decode_table,
433                                                 LZX_LENCODE_NUM_SYMBOLS,
434                                                 LZX_LENCODE_TABLEBITS,
435                                                 tables->lentree_lens,
436                                                 LZX_MAX_LEN_CODEWORD_LEN);
437                 if (ret) {
438                         LZX_DEBUG("Failed to build the length Huffman tree");
439                         return ret;
440                 }
441                 /* The bitstream of compressed literals and matches for this
442                  * block directly follows and will be read in
443                  * lzx_decompress_block(). */
444                 break;
445         case LZX_BLOCKTYPE_UNCOMPRESSED:
446                 LZX_DEBUG("Found uncompressed block.");
447                 /* Before reading the three LRU match offsets from the
448                  * uncompressed block header, the stream needs to be aligned on
449                  * a 16-bit boundary.  But, unexpectedly, if the stream is
450                  * *already* aligned, the correct thing to do is to throw away
451                  * the next 16 bits. */
452                 if (istream->bitsleft == 0) {
453                         if (istream->data_bytes_left < 14) {
454                                 LZX_DEBUG("Insufficient length in "
455                                           "uncompressed block");
456                                 return -1;
457                         }
458                         istream->data += 2;
459                         istream->data_bytes_left -= 2;
460                 } else {
461                         if (istream->data_bytes_left < 12) {
462                                 LZX_DEBUG("Insufficient length in "
463                                           "uncompressed block");
464                                 return -1;
465                         }
466                         istream->bitsleft = 0;
467                         istream->bitbuf = 0;
468                 }
469                 queue->R[0] = le32_to_cpu(*(le32*)(istream->data + 0));
470                 queue->R[1] = le32_to_cpu(*(le32*)(istream->data + 4));
471                 queue->R[2] = le32_to_cpu(*(le32*)(istream->data + 8));
472                 istream->data += 12;
473                 istream->data_bytes_left -= 12;
474                 /* The uncompressed data of this block directly follows and will
475                  * be read in lzx_decompress(). */
476                 break;
477         default:
478                 LZX_DEBUG("Found invalid block");
479                 return -1;
480         }
481         *block_type_ret = block_type;
482         *block_size_ret = block_size;
483         return 0;
484 }
485
486 /*
487  * Decodes a compressed match from a block of LZX-compressed data.  A match
488  * refers to some match_offset to a point earlier in the window as well as some
489  * match_len, for which the data is to be copied to the current position in the
490  * window.
491  *
492  * @main_element:       The start of the match data, as decoded using the main
493  *                      tree.
494  *
495  * @block_type:         The type of the block (LZX_BLOCKTYPE_ALIGNED or
496  *                      LZX_BLOCKTYPE_VERBATIM)
497  *
498  * @bytes_remaining:    The amount of uncompressed data remaining to be
499  *                      uncompressed in this block.  It is an error if the match
500  *                      is longer than this number.
501  *
502  * @window:             A pointer to the window into which the uncompressed
503  *                      data is being written.
504  *
505  * @window_pos:         The current byte offset in the window.
506  *
507  * @tables:             The Huffman decoding tables for this LZX block (main
508  *                      code, length code, and for LZX_BLOCKTYPE_ALIGNED blocks,
509  *                      also the aligned offset code).
510  *
511  * @queue:              The least-recently used queue for match offsets.
512  *
513  * @istream:            The input bitstream.
514  *
515  * Returns the length of the match, or a negative number on error.  The possible
516  * error cases are:
517  *      - Match would exceed the amount of data remaining to be uncompressed.
518  *      - Match refers to data before the window.
519  *      - The input bitstream ended unexpectedly.
520  */
521 static int
522 lzx_decode_match(unsigned main_element, int block_type,
523                  unsigned bytes_remaining, u8 *window,
524                  unsigned window_pos,
525                  const struct lzx_tables *tables,
526                  struct lzx_lru_queue *queue,
527                  struct input_bitstream *istream)
528 {
529         unsigned length_header;
530         unsigned position_slot;
531         unsigned match_len;
532         unsigned match_offset;
533         unsigned num_extra_bits;
534         u32 verbatim_bits;
535         u32 aligned_bits;
536         unsigned i;
537         u8 *match_dest;
538         u8 *match_src;
539
540         /* The main element is offset by 256 because values under 256 indicate a
541          * literal value. */
542         main_element -= LZX_NUM_CHARS;
543
544         /* The length header consists of the lower 3 bits of the main element.
545          * The position slot is the rest of it. */
546         length_header = main_element & LZX_NUM_PRIMARY_LENS;
547         position_slot = main_element >> 3;
548
549         /* If the length_header is less than LZX_NUM_PRIMARY_LENS (= 7), it
550          * gives the match length as the offset from LZX_MIN_MATCH_LEN.
551          * Otherwise, the length is given by an additional symbol encoded using
552          * the length tree, offset by 9 (LZX_MIN_MATCH_LEN +
553          * LZX_NUM_PRIMARY_LENS) */
554         match_len = LZX_MIN_MATCH_LEN + length_header;
555         if (length_header == LZX_NUM_PRIMARY_LENS)
556                 match_len += read_huffsym_using_lentree(istream, tables);
557
558         /* If the position_slot is 0, 1, or 2, the match offset is retrieved
559          * from the LRU queue.  Otherwise, the match offset is not in the LRU
560          * queue. */
561         switch (position_slot) {
562         case 0:
563                 match_offset = queue->R[0];
564                 break;
565         case 1:
566                 match_offset = queue->R[1];
567                 swap(queue->R[0], queue->R[1]);
568                 break;
569         case 2:
570                 /* The queue doesn't work quite the same as a real LRU queue,
571                  * since using the R2 offset doesn't bump the R1 offset down to
572                  * R2. */
573                 match_offset = queue->R[2];
574                 swap(queue->R[0], queue->R[2]);
575                 break;
576         default:
577                 /* Otherwise, the offset was not encoded as one the offsets in
578                  * the queue.  Depending on the position slot, there is a
579                  * certain number of extra bits that need to be read to fully
580                  * decode the match offset. */
581
582                 /* Look up the number of extra bits that need to be read. */
583                 num_extra_bits = lzx_get_num_extra_bits(position_slot);
584
585                 /* For aligned blocks, if there are at least 3 extra bits, the
586                  * actual number of extra bits is 3 less, and they encode a
587                  * number of 8-byte words that are added to the offset; there
588                  * is then an additional symbol read using the aligned tree that
589                  * specifies the actual byte alignment. */
590                 if (block_type == LZX_BLOCKTYPE_ALIGNED && num_extra_bits >= 3) {
591
592                         /* There is an error in the LZX "specification" at this
593                          * point; it indicates that a Huffman symbol is to be
594                          * read only if num_extra_bits is greater than 3, but
595                          * actually it is if num_extra_bits is greater than or
596                          * equal to 3.  (Note that in the case with
597                          * num_extra_bits == 3, the assignment to verbatim_bits
598                          * will just set it to 0. ) */
599                         verbatim_bits = bitstream_read_bits(istream,
600                                                             num_extra_bits - 3);
601                         verbatim_bits <<= 3;
602                         aligned_bits = read_huffsym_using_alignedtree(istream,
603                                                                       tables);
604                 } else {
605                         /* For non-aligned blocks, or for aligned blocks with
606                          * less than 3 extra bits, the extra bits are added
607                          * directly to the match offset, and the correction for
608                          * the alignment is taken to be 0. */
609                         verbatim_bits = bitstream_read_bits(istream, num_extra_bits);
610                         aligned_bits = 0;
611                 }
612
613                 /* Calculate the match offset. */
614                 match_offset = lzx_position_base[position_slot] +
615                                verbatim_bits + aligned_bits - LZX_OFFSET_OFFSET;
616
617                 /* Update the LRU queue. */
618                 queue->R[2] = queue->R[1];
619                 queue->R[1] = queue->R[0];
620                 queue->R[0] = match_offset;
621                 break;
622         }
623
624         /* Verify that the match is in the bounds of the part of the window
625          * currently in use, then copy the source of the match to the current
626          * position. */
627
628         if (unlikely(match_len > bytes_remaining)) {
629                 LZX_DEBUG("Match of length %u bytes overflows "
630                           "uncompressed block size", match_len);
631                 return -1;
632         }
633
634         if (unlikely(match_offset > window_pos)) {
635                 LZX_DEBUG("Match of length %u bytes references "
636                           "data before window (match_offset = %u, "
637                           "window_pos = %u)",
638                           match_len, match_offset, window_pos);
639                 return -1;
640         }
641
642         match_dest = window + window_pos;
643         match_src = match_dest - match_offset;
644
645 #if 0
646         printf("Match: src %u, dst %u, len %u\n", match_src - window,
647                                                 match_dest - window,
648                                                 match_len);
649         putchar('|');
650         for (i = 0; i < match_len; i++) {
651                 match_dest[i] = match_src[i];
652                 putchar(match_src[i]);
653         }
654         putchar('|');
655         putchar('\n');
656 #else
657         for (i = 0; i < match_len; i++)
658                 match_dest[i] = match_src[i];
659 #endif
660
661         return match_len;
662 }
663
664 static void
665 undo_call_insn_translation(u32 *call_insn_target, s32 input_pos)
666 {
667         s32 abs_offset;
668         s32 rel_offset;
669
670         abs_offset = le32_to_cpu(*call_insn_target);
671         if (abs_offset >= 0) {
672                 if (abs_offset < LZX_WIM_MAGIC_FILESIZE) {
673                         /* "good translation" */
674                         rel_offset = abs_offset - input_pos;
675
676                         *call_insn_target = cpu_to_le32(rel_offset);
677                 }
678         } else {
679                 if (abs_offset >= -input_pos) {
680                         /* "compensating translation" */
681                         rel_offset = abs_offset + LZX_WIM_MAGIC_FILESIZE;
682
683                         *call_insn_target = cpu_to_le32(rel_offset);
684                 }
685         }
686 }
687
688 /* Undo the 'E8' preprocessing, where the targets of x86 CALL instructions were
689  * changed from relative offsets to absolute offsets.
690  *
691  * Note that this call instruction preprocessing can and will be used on any
692  * data even if it is not actually x86 machine code.  In fact, this type of
693  * preprocessing appears to always be used in LZX-compressed resources in WIM
694  * files; there is no bit to indicate whether it is used or not, unlike in the
695  * LZX compressed format as used in cabinet files, where a bit is reserved for
696  * that purpose.
697  *
698  * Call instruction preprocessing is disabled in the last 6 bytes of the
699  * uncompressed data, which really means the 5-byte call instruction cannot
700  * start in the last 10 bytes of the uncompressed data.  This is one of the
701  * errors in the LZX documentation.
702  *
703  * Call instruction preprocessing does not appear to be disabled after the
704  * 32768th chunk of a WIM stream, which is apparently is yet another difference
705  * from the LZX compression used in cabinet files.
706  *
707  * Call instruction processing is supposed to take the file size as a parameter,
708  * as it is used in calculating the translated jump targets.  But in WIM files,
709  * this file size is always the same (LZX_WIM_MAGIC_FILESIZE == 12000000).*/
710 static void
711 undo_call_insn_preprocessing(u8 *uncompressed_data, size_t uncompressed_size)
712 {
713 #ifdef __SSE2__
714
715         /* SSE2 vectorized implementation for x86_64.  This speeds up LZX
716          * decompression by about 5-8% overall.  (Usually --- the performance
717          * actually regresses slightly in the degenerate case that the data
718          * consists entirely of 0xe8 bytes.)  */
719         __m128i *p128 = (__m128i *)uncompressed_data;
720         u32 valid_mask = 0xFFFFFFFF;
721
722         if (uncompressed_size >= 32 &&
723             ((uintptr_t)uncompressed_data % 16 == 0))
724         {
725                 __m128i * const end128 = p128 + uncompressed_size / 16 - 1;
726
727                 /* Create a vector of all 0xe8 bytes  */
728                 const __m128i e8_bytes = _mm_set1_epi8(0xe8);
729
730                 /* Iterate through the 16-byte vectors in the input.  */
731                 do {
732                         /* Compare the current 16-byte vector with the vector of
733                          * all 0xe8 bytes.  This produces 0xff where the byte is
734                          * 0xe8 and 0x00 where it is not.  */
735                         __m128i cmpresult = _mm_cmpeq_epi8(*p128, e8_bytes);
736
737                         /* Map the comparison results into a single 16-bit
738                          * number.  It will contain a 1 bit when the
739                          * corresponding byte in the current 16-byte vector is
740                          * an e8 byte.  Note: the low-order bit corresponds to
741                          * the first (lowest address) byte.  */
742                         u32 e8_mask = _mm_movemask_epi8(cmpresult);
743
744                         if (!e8_mask) {
745                                 /* If e8_mask is 0, then none of these 16 bytes
746                                  * have value 0xe8.  No e8 translation is
747                                  * needed, and there is no restriction that
748                                  * carries over to the next 16 bytes.  */
749                                 valid_mask = 0xFFFFFFFF;
750                         } else {
751                                 /* At least one byte has value 0xe8.
752                                  *
753                                  * The AND with valid_mask accounts for the fact
754                                  * that we can't start an e8 translation that
755                                  * overlaps the previous one.  */
756                                 while ((e8_mask &= valid_mask)) {
757
758                                         /* Count the number of trailing zeroes
759                                          * in e8_mask.  This will produce the
760                                          * index of the byte, within the 16, at
761                                          * which the next e8 translation should
762                                          * be done.  */
763                                         u32 bit = __builtin_ctz(e8_mask);
764
765                                         /* Do the e8 translation.  */
766                                         u8 *p8 = (u8 *)p128 + bit;
767                                         undo_call_insn_translation((s32 *)(p8 + 1),
768                                                                    p8 - uncompressed_data);
769
770                                         /* Don't start an e8 translation in the
771                                          * next 4 bytes.  */
772                                         valid_mask &= ~((u32)0x1F << bit);
773                                 }
774                                 /* Moving on to the next vector.  Shift and set
775                                  * valid_mask accordingly.  */
776                                 valid_mask >>= 16;
777                                 valid_mask |= 0xFFFF0000;
778                         }
779                 } while (++p128 < end128);
780         }
781
782         u8 *p8 = (u8 *)p128;
783         while (!(valid_mask & 1)) {
784                 p8++;
785                 valid_mask >>= 1;
786         }
787 #else /* __SSE2__  */
788         u8 *p8 = uncompressed_data;
789 #endif /* !__SSE2__  */
790
791         if (uncompressed_size > 10) {
792                 /* Finish any bytes that weren't processed by the vectorized
793                  * implementation.  */
794                 u8 *p8_end = uncompressed_data + uncompressed_size - 10;
795                 do {
796                         if (*p8 == 0xe8) {
797                                 undo_call_insn_translation((s32 *)(p8 + 1),
798                                                            p8 - uncompressed_data);
799                                 p8 += 5;
800                         } else {
801                                 p8++;
802                         }
803                 } while (p8 < p8_end);
804         }
805 }
806
807 /*
808  * Decompresses an LZX-compressed block of data from which the header has already
809  * been read.
810  *
811  * @block_type: The type of the block (LZX_BLOCKTYPE_VERBATIM or
812  *              LZX_BLOCKTYPE_ALIGNED)
813  * @block_size: The size of the block, in bytes.
814  * @num_main_syms:      Number of symbols in the main alphabet.
815  * @window:     Pointer to the decompression window.
816  * @window_pos: The current position in the window.  Will be 0 for the first
817  *                      block.
818  * @tables:     The Huffman decoding tables for the block (main, length, and
819  *                      aligned offset, the latter only for LZX_BLOCKTYPE_ALIGNED)
820  * @queue:      The least-recently-used queue for match offsets.
821  * @istream:    The input bitstream for the compressed literals.
822  */
823 static int
824 lzx_decompress_block(int block_type, unsigned block_size,
825                      unsigned num_main_syms,
826                      u8 *window,
827                      unsigned window_pos,
828                      const struct lzx_tables *tables,
829                      struct lzx_lru_queue *queue,
830                      struct input_bitstream *istream)
831 {
832         unsigned main_element;
833         unsigned end;
834         int match_len;
835
836         end = window_pos + block_size;
837         while (window_pos < end) {
838                 main_element = read_huffsym_using_maintree(istream, tables,
839                                                            num_main_syms);
840                 if (main_element < LZX_NUM_CHARS) {
841                         /* literal: 0 to LZX_NUM_CHARS - 1 */
842                         window[window_pos++] = main_element;
843                 } else {
844                         /* match: LZX_NUM_CHARS to num_main_syms - 1 */
845                         match_len = lzx_decode_match(main_element,
846                                                      block_type,
847                                                      end - window_pos,
848                                                      window,
849                                                      window_pos,
850                                                      tables,
851                                                      queue,
852                                                      istream);
853                         if (unlikely(match_len < 0))
854                                 return match_len;
855                         window_pos += match_len;
856                 }
857         }
858         return 0;
859 }
860
861 static int
862 lzx_decompress(const void *compressed_data, size_t compressed_size,
863                void *uncompressed_data, size_t uncompressed_size,
864                void *_ctx)
865 {
866         struct lzx_decompressor *ctx = _ctx;
867         struct input_bitstream istream;
868         struct lzx_lru_queue queue;
869         unsigned window_pos;
870         unsigned block_size;
871         unsigned block_type;
872         int ret;
873         bool e8_preprocessing_done;
874
875         LZX_DEBUG("compressed_data = %p, compressed_size = %zu, "
876                   "uncompressed_data = %p, uncompressed_size = %zu, "
877                   "max_window_size=%u).",
878                   compressed_data, compressed_size,
879                   uncompressed_data, uncompressed_size,
880                   ctx->max_window_size);
881
882         if (uncompressed_size > ctx->max_window_size) {
883                 LZX_DEBUG("Uncompressed size of %zu exceeds "
884                           "window size of %u!",
885                           uncompressed_size, ctx->max_window_size);
886                 return -1;
887         }
888
889         memset(ctx->tables.maintree_lens, 0, sizeof(ctx->tables.maintree_lens));
890         memset(ctx->tables.lentree_lens, 0, sizeof(ctx->tables.lentree_lens));
891         lzx_lru_queue_init(&queue);
892         init_input_bitstream(&istream, compressed_data, compressed_size);
893
894         e8_preprocessing_done = false; /* Set to true if there may be 0xe8 bytes
895                                           in the uncompressed data. */
896
897         /* The compressed data will consist of one or more blocks.  The
898          * following loop decompresses one block, and it runs until there all
899          * the compressed data has been decompressed, so there are no more
900          * blocks.  */
901
902         for (window_pos = 0;
903              window_pos < uncompressed_size;
904              window_pos += block_size)
905         {
906                 LZX_DEBUG("Reading block header.");
907                 ret = lzx_read_block_header(&istream, ctx->num_main_syms,
908                                             ctx->max_window_size, &block_size,
909                                             &block_type, &ctx->tables, &queue);
910                 if (ret)
911                         return ret;
912
913                 LZX_DEBUG("block_size = %u, window_pos = %u",
914                           block_size, window_pos);
915
916                 if (block_size > uncompressed_size - window_pos) {
917                         LZX_DEBUG("Expected a block size of at "
918                                   "most %zu bytes (found %u bytes)",
919                                   uncompressed_size - window_pos, block_size);
920                         return -1;
921                 }
922
923                 switch (block_type) {
924                 case LZX_BLOCKTYPE_VERBATIM:
925                 case LZX_BLOCKTYPE_ALIGNED:
926                         if (block_type == LZX_BLOCKTYPE_VERBATIM)
927                                 LZX_DEBUG("LZX_BLOCKTYPE_VERBATIM");
928                         else
929                                 LZX_DEBUG("LZX_BLOCKTYPE_ALIGNED");
930                         ret = lzx_decompress_block(block_type,
931                                                    block_size,
932                                                    ctx->num_main_syms,
933                                                    uncompressed_data,
934                                                    window_pos,
935                                                    &ctx->tables,
936                                                    &queue,
937                                                    &istream);
938                         if (ret)
939                                 return ret;
940
941                         if (ctx->tables.maintree_lens[0xe8] != 0)
942                                 e8_preprocessing_done = true;
943                         break;
944                 case LZX_BLOCKTYPE_UNCOMPRESSED:
945                         LZX_DEBUG("LZX_BLOCKTYPE_UNCOMPRESSED");
946                         if (istream.data_bytes_left < block_size) {
947                                 LZX_DEBUG("Unexpected end of input when "
948                                           "reading %u bytes from LZX bitstream "
949                                           "(only have %u bytes left)",
950                                           block_size, istream.data_bytes_left);
951                                 return -1;
952                         }
953                         memcpy(&((u8*)uncompressed_data)[window_pos], istream.data,
954                                block_size);
955                         istream.data += block_size;
956                         istream.data_bytes_left -= block_size;
957                         /* Re-align bitstream if an odd number of bytes were
958                          * read.  */
959                         if (istream.data_bytes_left && (block_size & 1)) {
960                                 istream.data_bytes_left--;
961                                 istream.data++;
962                         }
963                         e8_preprocessing_done = true;
964                         break;
965                 }
966         }
967         if (e8_preprocessing_done)
968                 undo_call_insn_preprocessing(uncompressed_data, uncompressed_size);
969         return 0;
970 }
971
972 static void
973 lzx_free_decompressor(void *_ctx)
974 {
975         struct lzx_decompressor *ctx = _ctx;
976
977         FREE(ctx);
978 }
979
980 static int
981 lzx_create_decompressor(size_t max_window_size,
982                         const struct wimlib_decompressor_params_header *params,
983                         void **ctx_ret)
984 {
985         struct lzx_decompressor *ctx;
986
987         if (!lzx_window_size_valid(max_window_size))
988                 return WIMLIB_ERR_INVALID_PARAM;
989
990         ctx = MALLOC(sizeof(struct lzx_decompressor));
991         if (ctx == NULL)
992                 return WIMLIB_ERR_NOMEM;
993
994         ctx->max_window_size = max_window_size;
995         ctx->num_main_syms = lzx_get_num_main_syms(max_window_size);
996
997         *ctx_ret = ctx;
998         return 0;
999 }
1000
1001 const struct decompressor_ops lzx_decompressor_ops = {
1002         .create_decompressor = lzx_create_decompressor,
1003         .decompress          = lzx_decompress,
1004         .free_decompressor   = lzx_free_decompressor,
1005 };