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