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