]> wimlib.net Git - wimlib/blob - src/lzx-decomp.c
Comments; NTFS hardlinks
[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("LZX input stream overrun");
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                 /* Read the path lengths for the elements of the aligned tree,
351                  * then build it. */
352
353                 for (i = 0; i < LZX_ALIGNEDTREE_NUM_SYMBOLS; i++) {
354                         ret = bitstream_read_bits(istream, 
355                                                   LZX_ALIGNEDTREE_ELEMENT_SIZE, 
356                                                   &len);
357                         if (ret != 0)
358                                 return ret;
359                         tables->alignedtree_lens[i] = len;
360                 }
361                 
362                 LZX_DEBUG("Building the aligned tree.");
363                 ret = make_huffman_decode_table(tables->alignedtree_decode_table,
364                                                 LZX_ALIGNEDTREE_NUM_SYMBOLS, 
365                                                 LZX_ALIGNEDTREE_TABLEBITS,
366                                                 tables->alignedtree_lens,
367                                                 8);
368                 if (ret != 0) {
369                         ERROR("lzx_decompress(): Failed to make the decode "
370                               "table for the aligned offset tree");
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.");
380
381                 LZX_DEBUG("Reading path lengths for main tree.");
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("lzx_decompress(): Failed to read the code "
388                               "lengths for the first 256 elements of the "
389                               "main tree");
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).",
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("lzx_decompress(): Failed to read the path "
403                               "lengths for the remaining elements of the main "
404                               "tree");
405                         return ret;
406                 }
407
408                 LZX_DEBUG("Building the Huffman decoding "
409                           "table for the main tree.");
410
411                 ret = make_huffman_decode_table(tables->maintree_decode_table,
412                                                 LZX_MAINTREE_NUM_SYMBOLS,
413                                                 LZX_MAINTREE_TABLEBITS,
414                                                 tables->maintree_lens, 
415                                                 LZX_MAX_CODEWORD_LEN);
416                 if (ret != 0) {
417                         ERROR("lzx_decompress(): Failed to make the decode "
418                               "table for the main tree");
419                         return ret;
420                 }
421
422                 LZX_DEBUG("Reading path lengths for the length tree.");
423                 ret = lzx_read_code_lens(istream, tables->lentree_lens, 
424                                          LZX_LENTREE_NUM_SYMBOLS);
425                 if (ret != 0) {
426                         ERROR("lzx_decompress(): Failed to read the path "
427                               "lengths for the length tree");
428                         return ret;
429                 }
430
431                 LZX_DEBUG("Building the length tree.");
432                 ret = make_huffman_decode_table(tables->lentree_decode_table,
433                                                 LZX_LENTREE_NUM_SYMBOLS, 
434                                                 LZX_LENTREE_TABLEBITS,
435                                                 tables->lentree_lens, 
436                                                 LZX_MAX_CODEWORD_LEN);
437                 if (ret != 0) {
438                         ERROR("lzx_decompress(): Failed to build the length "
439                               "Huffman tree");
440                         return ret;
441                 }
442
443                 break;
444
445         case LZX_BLOCKTYPE_UNCOMPRESSED:
446                 LZX_DEBUG("Found uncompressed block.");
447                 ret = align_input_bitstream(istream, true);
448                 if (ret != 0)
449                         return ret;
450                 ret = bitstream_read_bytes(istream, sizeof(R), R);
451                 if (ret != 0)
452                         return ret;
453                 array_to_le32(R, ARRAY_LEN(3));
454                 queue->R0 = R[0];
455                 queue->R1 = R[1];
456                 queue->R2 = R[2];
457                 break;
458         default:
459                 LZX_DEBUG("Found invalid block.");
460                 return 1;
461         }
462         *block_type_ret = block_type;
463         *block_size_ret = block_size;
464         return 0;
465 }
466
467 /* 
468  * Decodes a compressed literal match value.  It refers to some match_offset to
469  * a point earlier in the window, and some match_len, for which the data is to
470  * be copied to the current position in the window.
471  *
472  * @main_element:       The start of the match data, as decoded using the main
473  *                              tree.
474  * @block_type: The type of the block (LZX_BLOCKTYPE_ALIGNED or
475  *                      LZX_BLOCKTYPE_VERBATIM)
476  * @bytes_remaining:    The amount of uncompressed data remaining to be
477  *                              uncompressed.  It is an error if the match
478  *                              is longer than @bytes_remaining.
479  * @window:     A pointer to the window into which the uncompressed
480  *                      data is being written.
481  * @window_pos: The current position in the window.
482  * @tables:     Contains the Huffman tables for the block (main,
483  *                      length, and also aligned offset only for
484  *                      LZX_BLOCKTYPE_ALIGNED)
485  * @queue:      The least-recently used queue for match offsets.
486  * @istream:    The input bitstream.
487  *
488  * Returns the length of the match, or -1 on error (match would exceed
489  * the amount of data needing to be uncompressed, or match refers to data before
490  * the window, or the input bitstream ended unexpectedly).
491  */
492 static int lzx_decode_match(int main_element, int block_type, 
493                             int bytes_remaining, u8 *window, int window_pos, 
494                             const struct lzx_tables *tables, 
495                             struct lru_queue *queue, 
496                             struct input_bitstream *istream)
497 {
498         uint length_header;
499         uint position_slot;
500         uint match_len;
501         uint match_offset;
502         uint additional_len;
503         uint num_extra_bits;
504         uint verbatim_bits;
505         uint aligned_bits;
506         int ret;
507         int i;
508         u8 *match_dest;
509         u8 *match_src;
510
511         /* The main element is offset by 256 because values under 256 indicate a
512          * literal value. */
513         main_element -= LZX_NUM_CHARS;
514
515         /* The length header consists of the lower 3 bits of the main element.
516          * The position slot is the rest of it. */
517         length_header = main_element & LZX_NUM_PRIMARY_LENS;
518         position_slot = main_element >> 3;
519
520         /* If the length_header is less than LZX_NUM_PRIMARY_LENS (= 7), it
521          * gives the match length as the offset from LZX_MIN_MATCH.  Otherwise,
522          * the length is given by an additional symbol encoded using the length
523          * tree, offset by 9 (LZX_MIN_MATCH + LZX_NUM_PRIMARY_LENS) */
524         match_len = LZX_MIN_MATCH + length_header;
525         if (length_header == LZX_NUM_PRIMARY_LENS) {
526                 ret = read_huffsym_using_lentree(istream, tables, 
527                                                 &additional_len);
528                 if (ret != 0)
529                         return -1;
530                 match_len += additional_len;
531         }
532
533
534         /* If the position_slot is 0, 1, or 2, the match offset is retrieved
535          * from the LRU queue.  Otherwise, the match offset is not in the LRU
536          * queue. */
537         switch (position_slot) {
538         case 0:
539                 match_offset = queue->R0;
540                 break;
541         case 1:
542                 match_offset = queue->R1;
543                 swap(queue->R0, queue->R1);
544                 break;
545         case 2:
546                 /* The queue doesn't work quite the same as a real LRU queue,
547                  * since using the R2 offset doesn't bump the R1 offset down to
548                  * R2. */
549                 match_offset = queue->R2;
550                 swap(queue->R0, queue->R2);
551                 break;
552         default:
553                 /* Otherwise, the offset was not encoded as one the offsets in
554                  * the queue.  Depending on the position slot, there is a
555                  * certain number of extra bits that need to be read to fully
556                  * decode the match offset. */
557
558                 /* Look up the number of extra bits that need to be read. */
559                 num_extra_bits = lzx_extra_bits[position_slot];
560
561                 /* For aligned blocks, if there are at least 3 extra bits, the
562                  * actual number of extra bits is 3 less, and they encode a
563                  * number of 8-byte words that are added to the offset; there
564                  * is then an additional symbol read using the aligned tree that
565                  * specifies the actual byte alignment. */
566                 if (block_type == LZX_BLOCKTYPE_ALIGNED && num_extra_bits >= 3) {
567
568                         /* There is an error in the LZX "specification" at this
569                          * point; it indicates that a Huffman symbol is to be
570                          * read only if num_extra_bits is greater than 3, but
571                          * actually it is if num_extra_bits is greater than or
572                          * equal to 3.  (Note that in the case with
573                          * num_extra_bits == 3, the assignment to verbatim_bits
574                          * will just set it to 0. ) */
575                         ret = bitstream_read_bits(istream, num_extra_bits - 3, 
576                                                                 &verbatim_bits);
577                         if (ret != 0)
578                                 return -1;
579
580                         verbatim_bits <<= 3;
581
582                         ret = read_huffsym_using_alignedtree(istream, tables, 
583                                                              &aligned_bits);
584                         if (ret != 0)
585                                 return -1;
586                 } else {
587                         /* For non-aligned blocks, or for aligned blocks with
588                          * less than 3 extra bits, the extra bits are added
589                          * directly to the match offset, and the correction for
590                          * the alignment is taken to be 0. */
591                         ret = bitstream_read_bits(istream, num_extra_bits, 
592                                                   &verbatim_bits);
593                         if (ret != 0)
594                                 return -1;
595
596                         aligned_bits = 0;
597                 }
598
599                 /* Calculate the match offset. */
600                 match_offset = lzx_position_base[position_slot] + verbatim_bits + 
601                                                         aligned_bits - 2;
602
603                 /* Update the LRU queue. */
604                 queue->R2 = queue->R1;
605                 queue->R1 = queue->R0;
606                 queue->R0 = match_offset;
607                 break;
608         }
609
610         /* Verify that the match is in the bounds of the part of the window
611          * currently in use, then copy the source of the match to the current
612          * position. */
613         match_dest = window + window_pos;
614         match_src = match_dest - match_offset;
615
616         if (match_len > bytes_remaining) {
617                 ERROR("lzx_decode_match(): Match of length %d bytes overflows "
618                       "uncompressed block size", match_len);
619                 return -1;
620         }
621
622         if (match_src < window) {
623                 ERROR("lzx_decode_match(): Match of length %d bytes references "
624                       "data before window (match_offset = %d, window_pos = %d)",
625                       match_len, 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).",
755                   compressed_data, compressed_len,
756                   uncompressed_data, 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.");
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.",
783                           block_size, bytes_remaining);
784
785                 if (block_size > bytes_remaining) {
786                         ERROR("lzx_decompress(): Expected a block size of at "
787                               "most %d bytes (found %d bytes)",
788                               bytes_remaining, block_size);
789                         return 1;
790                 }
791
792                 switch (block_type) {
793                 case LZX_BLOCKTYPE_VERBATIM:
794                 case LZX_BLOCKTYPE_ALIGNED:
795                         if (block_type == LZX_BLOCKTYPE_VERBATIM)
796                                 LZX_DEBUG("LZX_BLOCKTYPE_VERBATIM");
797                         else
798                                 LZX_DEBUG("LZX_BLOCKTYPE_ALIGNED");
799
800                         ret = lzx_decompress_block(block_type, 
801                                                    block_size,
802                                                    uncompressed_data,
803                                                    uncompressed_len -
804                                                        bytes_remaining, 
805                                                    &tables, &queue, &istream);
806                         if (ret != 0)
807                                 return ret;
808                         break;
809                 case LZX_BLOCKTYPE_UNCOMPRESSED:
810                         LZX_DEBUG("LZX_BLOCKTYPE_UNCOMPRESSED");
811                         ret = bitstream_read_bytes(&istream, block_size, 
812                                                    uncompressed_data + 
813                                                    uncompressed_len - 
814                                                    bytes_remaining);
815                         if (ret != 0)
816                                 return ret;
817                         if (block_size & 1)
818                                 align_input_bitstream(&istream, false);
819                         break;
820                 default:
821                         wimlib_assert(0);
822                         break;
823                 }
824
825                 bytes_remaining -= block_size;
826
827                 if (bytes_remaining != 0)
828                         LZX_DEBUG("%d bytes remaining.", bytes_remaining);
829
830         }
831
832         if (uncompressed_len >= 10)
833                 undo_call_insn_preprocessing(uncompressed_data,
834                                              uncompressed_len);
835
836         return 0;
837 }