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