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