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