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