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