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