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