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