]> wimlib.net Git - wimlib/blob - src/lzx-decompress.c
print_lookup_table_entry(): add FILE* parameter
[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 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 a 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.  However, in WIM files only up to 32768 bytes of
32  * data can ever compressed be in the same LZX block, so a .tar.gz file could
33  * potentially be smaller than a WIM file that uses LZX compression because it
34  * can use a larger LZ77 window size.
35  *
36  * Some notes on the LZX compression format as used in Windows Imaging (WIM)
37  * files:
38  *
39  * A compressed WIM resource consists of a table of chunk offsets followed by
40  * the compressed chunks themselves.  All compressed chunks except possibly the
41  * last decompress to WIM_CHUNK_SIZE (= 32768) bytes.  This is quite similar to
42  * the cabinet (.cab) file format, but they are not the same.  According to the
43  * cabinet format documentation, the LZX block size is independent from the
44  * CFDATA blocks, and a LZX block may span several CFDATA blocks.  However, in
45  * WIMs, LZX blocks do not appear to ever span multiple WIM chunks.  Note that
46  * this means any WIM chunk may be decompressed or compressed independently from
47  * any other chunk, which is convenient.
48  *
49  * A LZX compressed WIM chunk contains one or more LZX blocks of the aligned,
50  * verbatim, or uncompressed block types.  For aligned and verbatim blocks, the
51  * size of the block in uncompressed bytes is specified by a bit following the 3
52  * bits that specify the block type, possibly followed by an additional 16 bits.
53  * '1' means to use the default block size (equal to 32768, the size of a WIM
54  * chunk--- and this seems to only be valid for the first LZX block in a WIM
55  * chunk), while '0' means that the block size is provided by the next 16 bits.
56  *
57  * The cabinet format, as documented, allows for the possibility that a
58  * compressed CFDATA chunk is up to 6144 bytes larger than the data it
59  * uncompresses to.  However, in the WIM format it appears that every chunk that
60  * would be 32768 bytes or more when compressed is actually stored fully
61  * uncompressed.
62  *
63  * The 'e8' preprocessing step that changes x86 call instructions to use
64  * absolute offsets instead of relative offsets relies on a filesize parameter.
65  * There is no such parameter for this in the WIM files (even though the size of
66  * the file resource could be used for this purpose), and instead a magic file
67  * size of 12000000 is used.  The 'e8' preprocessing is always done, and there
68  * is no bit to indicate whether it is done or not.
69  */
70
71 /*
72  * Some more notes about errors in Microsoft's LZX documentation:
73  *
74  * Microsoft's LZX document and their implementation of the com.ms.util.cab Java
75  * package do not concur.
76  *
77  * In the LZX document, there is a table showing the correlation between window
78  * size and the number of position slots. It states that the 1MB window = 40
79  * slots and the 2MB window = 42 slots. In the implementation, 1MB = 42 slots,
80  * 2MB = 50 slots. The actual calculation is 'find the first slot whose position
81  * base is equal to or more than the required window size'. This would explain
82  * why other tables in the document refer to 50 slots rather than 42.
83  *
84  * The constant NUM_PRIMARY_LENS used in the decompression pseudocode is not
85  * defined in the specification.
86  *
87  * The LZX document states that aligned offset blocks have their aligned offset
88  * huffman tree AFTER the main and length trees. The implementation suggests
89  * that the aligned offset tree is BEFORE the main and length trees.
90  *
91  * The LZX document decoding algorithm states that, in an aligned offset block,
92  * if an extra_bits value is 1, 2 or 3, then that number of bits should be read
93  * and the result added to the match offset. This is correct for 1 and 2, but
94  * not 3, where just a huffman symbol (using the aligned tree) should be read.
95  *
96  * Regarding the E8 preprocessing, the LZX document states 'No translation may
97  * be performed on the last 6 bytes of the input block'. This is correct.
98  * However, the pseudocode provided checks for the *E8 leader* up to the last 6
99  * bytes. If the leader appears between -10 and -7 bytes from the end, this
100  * would cause the next four bytes to be modified, at least one of which would
101  * be in the last 6 bytes, which is not allowed according to the spec.
102  *
103  * The specification states that the huffman trees must always contain at least
104  * one element. However, many CAB files contain blocks where the length tree is
105  * completely empty (because there are no matches), and this is expected to
106  * succeed.
107  */
108
109 #include "util.h"
110 #include "lzx.h"
111 #include "decompress.h"
112 #include <string.h>
113
114 /* Huffman decoding tables and maps from symbols to code lengths. */
115 struct lzx_tables {
116
117         u16 maintree_decode_table[(1 << LZX_MAINTREE_TABLEBITS) +
118                                         (LZX_MAINTREE_NUM_SYMBOLS * 2)];
119         u8 maintree_lens[LZX_MAINTREE_NUM_SYMBOLS];
120
121
122         u16 lentree_decode_table[(1 << LZX_LENTREE_TABLEBITS) +
123                                         (LZX_LENTREE_NUM_SYMBOLS * 2)];
124         u8 lentree_lens[LZX_LENTREE_NUM_SYMBOLS];
125
126
127         u16 alignedtree_decode_table[(1 << LZX_ALIGNEDTREE_TABLEBITS) +
128                                         (LZX_ALIGNEDTREE_NUM_SYMBOLS * 2)];
129         u8 alignedtree_lens[LZX_ALIGNEDTREE_NUM_SYMBOLS];
130 };
131
132
133 /*
134  * Reads a Huffman-encoded symbol using the pre-tree.
135  */
136 static inline int read_huffsym_using_pretree(struct input_bitstream *istream,
137                                              const u16 pretree_decode_table[],
138                                              const u8 pretree_lens[], unsigned *n)
139 {
140         return read_huffsym(istream, pretree_decode_table, pretree_lens,
141                             LZX_PRETREE_NUM_SYMBOLS, LZX_PRETREE_TABLEBITS, n,
142                             LZX_MAX_CODEWORD_LEN);
143 }
144
145 /* Reads a Huffman-encoded symbol using the main tree. */
146 static inline int read_huffsym_using_maintree(struct input_bitstream *istream,
147                                               const struct lzx_tables *tables,
148                                               unsigned *n)
149 {
150         return read_huffsym(istream, tables->maintree_decode_table,
151                             tables->maintree_lens, LZX_MAINTREE_NUM_SYMBOLS,
152                             LZX_MAINTREE_TABLEBITS, n, LZX_MAX_CODEWORD_LEN);
153 }
154
155 /* Reads a Huffman-encoded symbol using the length tree. */
156 static inline int read_huffsym_using_lentree(struct input_bitstream *istream,
157                                              const struct lzx_tables *tables,
158                                              unsigned *n)
159 {
160         return read_huffsym(istream, tables->lentree_decode_table,
161                             tables->lentree_lens, LZX_LENTREE_NUM_SYMBOLS,
162                             LZX_LENTREE_TABLEBITS, n, LZX_MAX_CODEWORD_LEN);
163 }
164
165 /* Reads a Huffman-encoded symbol using the aligned offset tree. */
166 static inline int read_huffsym_using_alignedtree(struct input_bitstream *istream,
167                                                  const struct lzx_tables *tables,
168                                                  unsigned *n)
169 {
170         return read_huffsym(istream, tables->alignedtree_decode_table,
171                             tables->alignedtree_lens,
172                             LZX_ALIGNEDTREE_NUM_SYMBOLS,
173                             LZX_ALIGNEDTREE_TABLEBITS, n, 8);
174 }
175
176 /*
177  * Reads the pretree from the input, then uses the pretree to decode @num_lens
178  * code length values from the input.
179  *
180  * @istream:    The bit stream for the input.  It is positioned on the beginning
181  *                      of the pretree for the code length values.
182  * @lens:       An array that contains the length values from the previous time
183  *                      the code lengths for this Huffman tree were read, or all
184  *                      0's if this is the first time.
185  * @num_lens:   Number of length values to decode and return.
186  *
187  */
188 static int lzx_read_code_lens(struct input_bitstream *istream, u8 lens[],
189                               unsigned num_lens)
190 {
191         /* Declare the decoding table and length table for the pretree. */
192         u16 pretree_decode_table[(1 << LZX_PRETREE_TABLEBITS) +
193                                         (LZX_PRETREE_NUM_SYMBOLS * 2)];
194         u8 pretree_lens[LZX_PRETREE_NUM_SYMBOLS];
195         unsigned i;
196         unsigned len;
197         int ret;
198
199         /* Read the code lengths of the pretree codes.  There are 20 lengths of
200          * 4 bits each. */
201         for (i = 0; i < LZX_PRETREE_NUM_SYMBOLS; i++) {
202                 ret = bitstream_read_bits(istream, LZX_PRETREE_ELEMENT_SIZE,
203                                           &len);
204                 if (ret != 0)
205                         return ret;
206                 pretree_lens[i] = len;
207         }
208
209         /* Make the decoding table for the pretree. */
210         ret = make_huffman_decode_table(pretree_decode_table,
211                                         LZX_PRETREE_NUM_SYMBOLS,
212                                         LZX_PRETREE_TABLEBITS,
213                                         pretree_lens,
214                                         LZX_MAX_CODEWORD_LEN);
215         if (ret != 0)
216                 return ret;
217
218         /* Pointer past the last length value that needs to be filled in. */
219         u8 *lens_end = lens + num_lens;
220
221         while (1) {
222
223                 /* Decode a symbol from the input.  If the symbol is between 0
224                  * and 16, it is the difference from the old length.  If it is
225                  * between 17 and 19, it is a special code that indicates that
226                  * some number of the next lengths are all 0, or some number of
227                  * the next lengths are all equal to the next symbol in the
228                  * input. */
229                 unsigned tree_code;
230                 unsigned num_zeroes;
231                 unsigned code;
232                 unsigned num_same;
233                 char value;
234
235                 ret = read_huffsym_using_pretree(istream, pretree_decode_table,
236                                                  pretree_lens, &tree_code);
237                 if (ret != 0)
238                         return ret;
239                 switch (tree_code) {
240                 case 17: /* Run of 0's */
241                         ret = bitstream_read_bits(istream, 4, &num_zeroes);
242                         if (ret != 0)
243                                 return ret;
244                         num_zeroes += 4;
245                         while (num_zeroes--) {
246                                 *lens = 0;
247                                 if (++lens == lens_end)
248                                         return 0;
249                         }
250                         break;
251                 case 18: /* Longer run of 0's */
252                         ret = bitstream_read_bits(istream, 5, &num_zeroes);
253                         if (ret != 0)
254                                 return ret;
255                         num_zeroes += 20;
256                         while (num_zeroes--) {
257                                 *lens = 0;
258                                 if (++lens == lens_end)
259                                         return 0;
260                         }
261                         break;
262                 case 19: /* Run of identical lengths */
263                         ret = bitstream_read_bits(istream, 1, &num_same);
264                         if (ret != 0)
265                                 return ret;
266                         num_same += 4;
267                         ret = read_huffsym_using_pretree(istream,
268                                                          pretree_decode_table,
269                                                          pretree_lens,
270                                                          &code);
271                         if (ret != 0)
272                                 return ret;
273                         value = (char)*lens - (char)code;
274                         if (value < 0)
275                                 value += 17;
276                         while (num_same--) {
277                                 *lens = value;
278                                 if (++lens == lens_end)
279                                         return 0;
280                         }
281                         break;
282                 default: /* Difference from old length. */
283                         value = (char)*lens - (char)tree_code;
284                         if (value < 0)
285                                 value += 17;
286                         *lens = value;
287                         if (++lens == lens_end)
288                                 return 0;
289                         break;
290                 }
291         }
292 }
293
294 /*
295  * Reads the header for an LZX-compressed block.
296  *
297  * @istream:            The input bitstream.
298  * @block_size_ret:     A pointer to an int into which the size of the block,
299  *                              in bytes, will be returned.
300  * @block_type_ret:     A pointer to an int into which the type of the block
301  *                              (LZX_BLOCKTYPE_*) will be returned.
302  * @tables:             A pointer to a lzx_tables structure in which the
303  *                              main tree, the length tree, and possibly the
304  *                              aligned offset tree will be constructed.
305  * @queue:      A pointer to the least-recently-used queue into which
306  *                      R0, R1, and R2 will be written (only for uncompressed
307  *                      blocks, which contain this information in the header)
308  */
309 static int lzx_read_block_header(struct input_bitstream *istream,
310                                  unsigned *block_size_ret,
311                                  unsigned *block_type_ret,
312                                  struct lzx_tables *tables,
313                                  struct lru_queue *queue)
314 {
315         int ret;
316         unsigned block_type;
317         unsigned block_size;
318         unsigned s;
319         unsigned i;
320         unsigned len;
321
322         ret = bitstream_ensure_bits(istream, 4);
323         if (ret != 0) {
324                 ERROR("LZX input stream overrun");
325                 return ret;
326         }
327
328         /* The first three bits tell us what kind of block it is, and are one
329          * of the LZX_BLOCKTYPE_* values.  */
330         block_type = bitstream_read_bits_nocheck(istream, 3);
331
332         /* The next bit indicates whether the block size is the default (32768),
333          * indicated by a 1 bit, or whether the block size is given by the next
334          * 16 bits, indicated by a 0 bit. */
335         s = bitstream_read_bits_nocheck(istream, 1);
336
337         if (s) {
338                 block_size = 32768;
339         } else {
340                 ret = bitstream_read_bits(istream, 16, &block_size);
341                 if (ret != 0)
342                         return ret;
343                 block_size = le16_to_cpu(block_size);
344         }
345
346         switch (block_type) {
347         case LZX_BLOCKTYPE_ALIGNED:
348                 /* Read the path lengths for the elements of the aligned tree,
349                  * then build it. */
350
351                 for (i = 0; i < LZX_ALIGNEDTREE_NUM_SYMBOLS; i++) {
352                         ret = bitstream_read_bits(istream,
353                                                   LZX_ALIGNEDTREE_ELEMENT_SIZE,
354                                                   &len);
355                         if (ret != 0)
356                                 return ret;
357                         tables->alignedtree_lens[i] = len;
358                 }
359
360                 LZX_DEBUG("Building the aligned tree.");
361                 ret = make_huffman_decode_table(tables->alignedtree_decode_table,
362                                                 LZX_ALIGNEDTREE_NUM_SYMBOLS,
363                                                 LZX_ALIGNEDTREE_TABLEBITS,
364                                                 tables->alignedtree_lens,
365                                                 8);
366                 if (ret != 0) {
367                         ERROR("lzx_decompress(): Failed to make the decode "
368                               "table for the aligned offset tree");
369                         return ret;
370                 }
371
372                 /* Fall though, since the rest of the header for aligned offset
373                  * blocks is the same as that for verbatim blocks */
374
375         case LZX_BLOCKTYPE_VERBATIM:
376                 if (block_type == LZX_BLOCKTYPE_VERBATIM)
377                         LZX_DEBUG("Found verbatim block.");
378
379                 LZX_DEBUG("Reading path lengths for main tree.");
380                 /* Read the path lengths for the first 256 elements of the main
381                  * tree. */
382                 ret = lzx_read_code_lens(istream, tables->maintree_lens,
383                                          LZX_NUM_CHARS);
384                 if (ret != 0) {
385                         ERROR("lzx_decompress(): Failed to read the code "
386                               "lengths for the first 256 elements of the "
387                               "main tree");
388                         return ret;
389                 }
390
391                 /* Read the path lengths for the remaining elements of the main
392                  * tree. */
393                 LZX_DEBUG("Reading path lengths for remaining elements of "
394                           "main tree (%d elements).",
395                           LZX_MAINTREE_NUM_SYMBOLS - LZX_NUM_CHARS);
396                 ret = lzx_read_code_lens(istream,
397                                          tables->maintree_lens + LZX_NUM_CHARS,
398                                          LZX_MAINTREE_NUM_SYMBOLS - LZX_NUM_CHARS);
399                 if (ret != 0) {
400                         ERROR("lzx_decompress(): Failed to read the path "
401                               "lengths for the remaining elements of the main "
402                               "tree");
403                         return ret;
404                 }
405
406                 LZX_DEBUG("Building the Huffman decoding "
407                           "table for the main tree.");
408
409                 ret = make_huffman_decode_table(tables->maintree_decode_table,
410                                                 LZX_MAINTREE_NUM_SYMBOLS,
411                                                 LZX_MAINTREE_TABLEBITS,
412                                                 tables->maintree_lens,
413                                                 LZX_MAX_CODEWORD_LEN);
414                 if (ret != 0) {
415                         ERROR("lzx_decompress(): Failed to make the decode "
416                               "table for the main tree");
417                         return ret;
418                 }
419
420                 LZX_DEBUG("Reading path lengths for the length tree.");
421                 ret = lzx_read_code_lens(istream, tables->lentree_lens,
422                                          LZX_LENTREE_NUM_SYMBOLS);
423                 if (ret != 0) {
424                         ERROR("lzx_decompress(): Failed to read the path "
425                               "lengths for the length tree");
426                         return ret;
427                 }
428
429                 LZX_DEBUG("Building the length tree.");
430                 ret = make_huffman_decode_table(tables->lentree_decode_table,
431                                                 LZX_LENTREE_NUM_SYMBOLS,
432                                                 LZX_LENTREE_TABLEBITS,
433                                                 tables->lentree_lens,
434                                                 LZX_MAX_CODEWORD_LEN);
435                 if (ret != 0) {
436                         ERROR("lzx_decompress(): Failed to build the length "
437                               "Huffman tree");
438                         return ret;
439                 }
440                 /* The bitstream of compressed literals and matches for this
441                  * block directly follows and will be read in
442                  * lzx_decompress_block(). */
443                 break;
444         case LZX_BLOCKTYPE_UNCOMPRESSED:
445                 LZX_DEBUG("Found uncompressed block.");
446                 /* Before reading the three LRU match offsets from the
447                  * uncompressed block header, the stream needs to be aligned on
448                  * a 16-bit boundary.  But, unexpectedly, if the stream is
449                  * *already* aligned, the correct thing to do is to throw away
450                  * the next 16 bits. */
451                 if (istream->bitsleft == 0) {
452                         if (istream->data_bytes_left < 14)
453                                 return -1;
454                         istream->data += 2;
455                         istream->data_bytes_left -= 2;
456                 } else {
457                         if (istream->data_bytes_left < 12)
458                                 return -1;
459                         istream->bitsleft = 0;
460                         istream->bitbuf = 0;
461                 }
462                 queue->R0 = le32_to_cpu(*(u32*)(istream->data + 0));
463                 queue->R1 = le32_to_cpu(*(u32*)(istream->data + 4));
464                 queue->R2 = le32_to_cpu(*(u32*)(istream->data + 8));
465                 istream->data += 12;
466                 istream->data_bytes_left -= 12;
467                 /* The uncompressed data of this block directly follows and will
468                  * be read in lzx_decompress(). */
469                 break;
470         default:
471                 ERROR("lzx_decompress(): Found invalid block");
472                 return -1;
473         }
474         *block_type_ret = block_type;
475         *block_size_ret = block_size;
476         return 0;
477 }
478
479 /*
480  * Decodes a compressed match from a block of LZX-compressed data.  A match
481  * refers to some match_offset to a point earlier in the window as well as some
482  * match_len, for which the data is to be copied to the current position in the
483  * window.
484  *
485  * @main_element:       The start of the match data, as decoded using the main
486  *                      tree.
487  *
488  * @block_type:         The type of the block (LZX_BLOCKTYPE_ALIGNED or
489  *                      LZX_BLOCKTYPE_VERBATIM)
490  *
491  * @bytes_remaining:    The amount of uncompressed data remaining to be
492  *                      uncompressed in this block.  It is an error if the match
493  *                      is longer than this number.
494  *
495  * @window:             A pointer to the window into which the uncompressed
496  *                      data is being written.
497  *
498  * @window_pos:         The current byte offset in the window.
499  *
500  * @tables:             The Huffman decoding tables for this LZX block (main
501  *                      code, length code, and for LZX_BLOCKTYPE_ALIGNED blocks,
502  *                      also the aligned offset code).
503  *
504  * @queue:              The least-recently used queue for match offsets.
505  *
506  * @istream:            The input bitstream.
507  *
508  * Returns the length of the match, or a negative number on error.  The possible
509  * error cases are:
510  *      - Match would exceed the amount of data remaining to be uncompressed.
511  *      - Match refers to data before the window.
512  *      - The input bitstream ended unexpectedly.
513  */
514 static int lzx_decode_match(unsigned main_element, int block_type,
515                             unsigned bytes_remaining, u8 *window,
516                             unsigned window_pos,
517                             const struct lzx_tables *tables,
518                             struct lru_queue *queue,
519                             struct input_bitstream *istream)
520 {
521         unsigned length_header;
522         unsigned position_slot;
523         unsigned match_len;
524         unsigned match_offset;
525         unsigned additional_len;
526         unsigned num_extra_bits;
527         unsigned verbatim_bits;
528         unsigned aligned_bits;
529         unsigned i;
530         int ret;
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.  Otherwise,
545          * the length is given by an additional symbol encoded using the length
546          * tree, offset by 9 (LZX_MIN_MATCH + LZX_NUM_PRIMARY_LENS) */
547         match_len = LZX_MIN_MATCH + length_header;
548         if (length_header == LZX_NUM_PRIMARY_LENS) {
549                 ret = read_huffsym_using_lentree(istream, tables,
550                                                  &additional_len);
551                 if (ret != 0)
552                         return ret;
553                 match_len += additional_len;
554         }
555
556
557         /* If the position_slot is 0, 1, or 2, the match offset is retrieved
558          * from the LRU queue.  Otherwise, the match offset is not in the LRU
559          * queue. */
560         switch (position_slot) {
561         case 0:
562                 match_offset = queue->R0;
563                 break;
564         case 1:
565                 match_offset = queue->R1;
566                 swap(queue->R0, queue->R1);
567                 break;
568         case 2:
569                 /* The queue doesn't work quite the same as a real LRU queue,
570                  * since using the R2 offset doesn't bump the R1 offset down to
571                  * R2. */
572                 match_offset = queue->R2;
573                 swap(queue->R0, queue->R2);
574                 break;
575         default:
576                 /* Otherwise, the offset was not encoded as one the offsets in
577                  * the queue.  Depending on the position slot, there is a
578                  * certain number of extra bits that need to be read to fully
579                  * decode the match offset. */
580
581                 /* Look up the number of extra bits that need to be read. */
582                 num_extra_bits = lzx_get_num_extra_bits(position_slot);
583
584                 /* For aligned blocks, if there are at least 3 extra bits, the
585                  * actual number of extra bits is 3 less, and they encode a
586                  * number of 8-byte words that are added to the offset; there
587                  * is then an additional symbol read using the aligned tree that
588                  * specifies the actual byte alignment. */
589                 if (block_type == LZX_BLOCKTYPE_ALIGNED && num_extra_bits >= 3) {
590
591                         /* There is an error in the LZX "specification" at this
592                          * point; it indicates that a Huffman symbol is to be
593                          * read only if num_extra_bits is greater than 3, but
594                          * actually it is if num_extra_bits is greater than or
595                          * equal to 3.  (Note that in the case with
596                          * num_extra_bits == 3, the assignment to verbatim_bits
597                          * will just set it to 0. ) */
598                         ret = bitstream_read_bits(istream, num_extra_bits - 3,
599                                                   &verbatim_bits);
600                         if (ret != 0)
601                                 return ret;
602
603                         verbatim_bits <<= 3;
604
605                         ret = read_huffsym_using_alignedtree(istream, tables,
606                                                              &aligned_bits);
607                         if (ret != 0)
608                                 return ret;
609                 } else {
610                         /* For non-aligned blocks, or for aligned blocks with
611                          * less than 3 extra bits, the extra bits are added
612                          * directly to the match offset, and the correction for
613                          * the alignment is taken to be 0. */
614                         ret = bitstream_read_bits(istream, num_extra_bits,
615                                                   &verbatim_bits);
616                         if (ret != 0)
617                                 return ret;
618
619                         aligned_bits = 0;
620                 }
621
622                 /* Calculate the match offset. */
623                 match_offset = lzx_position_base[position_slot] +
624                                verbatim_bits + aligned_bits - 2;
625
626                 /* Update the LRU queue. */
627                 queue->R2 = queue->R1;
628                 queue->R1 = queue->R0;
629                 queue->R0 = match_offset;
630                 break;
631         }
632
633         /* Verify that the match is in the bounds of the part of the window
634          * currently in use, then copy the source of the match to the current
635          * position. */
636         match_dest = window + window_pos;
637         match_src = match_dest - match_offset;
638
639         if (match_len > bytes_remaining) {
640                 ERROR("lzx_decode_match(): Match of length %u bytes overflows "
641                       "uncompressed block size", match_len);
642                 return -1;
643         }
644
645         if (match_src < window) {
646                 ERROR("lzx_decode_match(): Match of length %u bytes references "
647                       "data before window (match_offset = %u, window_pos = %u)",
648                       match_len, match_offset, window_pos);
649                 return -1;
650         }
651
652 #if 0
653         printf("Match: src %u, dst %u, len %u\n", match_src - window,
654                                                 match_dest - window,
655                                                 match_len);
656         putchar('|');
657         for (i = 0; i < match_len; i++) {
658                 match_dest[i] = match_src[i];
659                 putchar(match_src[i]);
660         }
661         putchar('|');
662         putchar('\n');
663 #else
664         for (i = 0; i < match_len; i++)
665                 match_dest[i] = match_src[i];
666 #endif
667
668         return match_len;
669 }
670
671 static void undo_call_insn_translation(u32 *call_insn_target, int input_pos,
672                                        int32_t file_size)
673 {
674         int32_t abs_offset;
675         int32_t rel_offset;
676
677         abs_offset = le32_to_cpu(*call_insn_target);
678         if (abs_offset >= -input_pos && abs_offset < file_size) {
679                 if (abs_offset >= 0) {
680                         /* "good translation" */
681                         rel_offset = abs_offset - input_pos;
682                 } else {
683                         /* "compensating translation" */
684                         rel_offset = abs_offset + file_size;
685                 }
686                 *call_insn_target = cpu_to_le32(rel_offset);
687         }
688 }
689
690 /* Undo the 'E8' preprocessing, where the targets of x86 CALL instructions were
691  * changed from relative offsets to absolute offsets.
692  *
693  * Note that this call instruction preprocessing can and will be used on any
694  * data even if it is not actually x86 machine code.  In fact, this type of
695  * preprocessing appears to always be used in LZX-compressed resources in WIM
696  * files; there is no bit to indicate whether it is used or not, unlike in the
697  * LZX compressed format as used in cabinet files, where a bit is reserved for
698  * that purpose.
699  *
700  * Call instruction preprocessing is disabled in the last 6 bytes of the
701  * uncompressed data, which really means the 5-byte call instruction cannot
702  * start in the last 10 bytes of the uncompressed data.  This is one of the
703  * errors in the LZX documentation.
704  *
705  * Call instruction preprocessing does not appear to be disabled after the
706  * 32768th chunk of a WIM stream, which is apparently is yet another difference
707  * from the LZX compression used in cabinet files.
708  *
709  * Call instruction processing is supposed to take the file size as a parameter,
710  * as it is used in calculating the translated jump targets.  But in WIM files,
711  * this file size is always the same (LZX_WIM_MAGIC_FILESIZE == 12000000).*/
712 static void undo_call_insn_preprocessing(u8 uncompressed_data[],
713                                          int uncompressed_data_len)
714 {
715         for (int i = 0; i < uncompressed_data_len - 10; i++) {
716                 if (uncompressed_data[i] == 0xe8) {
717                         undo_call_insn_translation((u32*)&uncompressed_data[i + 1],
718                                                    i,
719                                                    LZX_WIM_MAGIC_FILESIZE);
720                         i += 4;
721                 }
722         }
723 }
724
725 /*
726  * Decompresses a LZX-compressed block of data from which the header has already
727  * been read.
728  *
729  * @block_type: The type of the block (LZX_BLOCKTYPE_VERBATIM or
730  *              LZX_BLOCKTYPE_ALIGNED)
731  * @block_size: The size of the block, in bytes.
732  * @window:     Pointer to the decompression window.
733  * @window_pos: The current position in the window.  Will be 0 for the first
734  *                      block.
735  * @tables:     The Huffman decoding tables for the block (main, length, and
736  *                      aligned offset, the latter only for LZX_BLOCKTYPE_ALIGNED)
737  * @queue:      The least-recently-used queue for match offsets.
738  * @istream:    The input bitstream for the compressed literals.
739  */
740 static int lzx_decompress_block(int block_type, unsigned block_size,
741                                 u8 *window,
742                                 unsigned window_pos,
743                                 const struct lzx_tables *tables,
744                                 struct lru_queue *queue,
745                                 struct input_bitstream *istream)
746 {
747         unsigned main_element;
748         unsigned end;
749         int ret;
750         int match_len;
751
752         end = window_pos + block_size;
753         while (window_pos < end) {
754                 ret = read_huffsym_using_maintree(istream, tables,
755                                                   &main_element);
756                 if (ret != 0)
757                         return ret;
758
759                 if (main_element < LZX_NUM_CHARS) {
760                         /* literal: 0 to LZX_NUM_CHARS - 1 */
761                         window[window_pos++] = main_element;
762                 } else {
763                         /* match: LZX_NUM_CHARS to LZX_MAINTREE_NUM_SYMBOLS - 1 */
764                         match_len = lzx_decode_match(main_element,
765                                                      block_type,
766                                                      end - window_pos,
767                                                      window,
768                                                      window_pos,
769                                                      tables,
770                                                      queue,
771                                                      istream);
772                         if (match_len < 0)
773                                 return match_len;
774                         window_pos += match_len;
775                 }
776         }
777         return 0;
778 }
779
780 /*
781  * Decompresses a block of LZX-compressed data as used in the WIM file format.
782  *
783  * Note that this will NOT work unmodified for LZX as used in the cabinet
784  * format, which is not the same as in the WIM format!
785  *
786  * @compressed_data:    A pointer to the compressed data.
787  *
788  * @compressed_len:     The length of the compressed data, in bytes.
789  *
790  * @uncompressed_data:  A pointer to the buffer into which to write the
791  *                      uncompressed data.
792  *
793  * @uncompressed_len:   The length of the uncompressed data.  It must be
794  *                      32768 bytes or less.
795  *
796  * Return 0 on success; non-zero on failure.
797  */
798 int lzx_decompress(const void *compressed_data, unsigned compressed_len,
799                    void *uncompressed_data, unsigned uncompressed_len)
800 {
801         struct lzx_tables tables;
802         struct input_bitstream istream;
803         struct lru_queue queue;
804         unsigned window_pos;
805         unsigned block_size;
806         unsigned block_type;
807         int ret;
808         bool e8_preprocessing_done;
809
810         LZX_DEBUG("lzx_decompress (compressed_data = %p, compressed_len = %d, "
811                   "uncompressed_data = %p, uncompressed_len = %d).",
812                   compressed_data, compressed_len,
813                   uncompressed_data, uncompressed_len);
814
815         wimlib_assert(uncompressed_len <= 32768);
816
817         memset(tables.maintree_lens, 0, sizeof(tables.maintree_lens));
818         memset(tables.lentree_lens, 0, sizeof(tables.lentree_lens));
819         queue.R0 = 1;
820         queue.R1 = 1;
821         queue.R2 = 1;
822         init_input_bitstream(&istream, compressed_data, compressed_len);
823
824         e8_preprocessing_done = false; /* Set to true if there may be 0xe8 bytes
825                                           in the uncompressed data. */
826
827         /* The compressed data will consist of one or more blocks.  The
828          * following loop decompresses one block, and it runs until there all
829          * the compressed data has been decompressed, so there are no more
830          * blocks.  */
831
832         for (window_pos = 0;
833              window_pos < uncompressed_len;
834              window_pos += block_size)
835         {
836                 LZX_DEBUG("Reading block header.");
837                 ret = lzx_read_block_header(&istream, &block_size,
838                                             &block_type, &tables, &queue);
839                 if (ret != 0)
840                         return ret;
841
842                 LZX_DEBUG("block_size = %u, window_pos = %u",
843                           block_size, window_pos);
844
845                 if (block_size > uncompressed_len - window_pos) {
846                         ERROR("lzx_decompress(): Expected a block size of at "
847                               "most %u bytes (found %u bytes)",
848                               uncompressed_len - window_pos, block_size);
849                         return -1;
850                 }
851
852                 switch (block_type) {
853                 case LZX_BLOCKTYPE_VERBATIM:
854                 case LZX_BLOCKTYPE_ALIGNED:
855                         if (block_type == LZX_BLOCKTYPE_VERBATIM)
856                                 LZX_DEBUG("LZX_BLOCKTYPE_VERBATIM");
857                         else
858                                 LZX_DEBUG("LZX_BLOCKTYPE_ALIGNED");
859                         ret = lzx_decompress_block(block_type,
860                                                    block_size,
861                                                    uncompressed_data,
862                                                    window_pos,
863                                                    &tables,
864                                                    &queue,
865                                                    &istream);
866                         if (ret != 0)
867                                 return ret;
868                         if (tables.maintree_lens[0xe8] != 0)
869                                 e8_preprocessing_done = true;
870                         break;
871                 case LZX_BLOCKTYPE_UNCOMPRESSED:
872                         LZX_DEBUG("LZX_BLOCKTYPE_UNCOMPRESSED");
873                         if (istream.data_bytes_left < block_size) {
874                                 ERROR("Unexpected end of input when "
875                                       "reading %u bytes from LZX bitstream "
876                                       "(only have %u bytes left)",
877                                       block_size, istream.data_bytes_left);
878                                 return -1;
879                         }
880                         memcpy(&((u8*)uncompressed_data)[window_pos], istream.data,
881                                block_size);
882                         istream.data += block_size;
883                         istream.data_bytes_left -= block_size;
884                         /* Re-align bitstream if an odd number of bytes were
885                          * read.  */
886                         if (istream.data_bytes_left && (block_size & 1)) {
887                                 istream.data_bytes_left--;
888                                 istream.data++;
889                         }
890                         e8_preprocessing_done = true;
891                         break;
892                 }
893         }
894         if (e8_preprocessing_done)
895                 undo_call_insn_preprocessing(uncompressed_data, uncompressed_len);
896         return 0;
897 }