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