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