]> wimlib.net Git - wimlib/blob - src/lzx-decomp.c
Calculate SHA1 md of NTFS reparse points correctly
[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 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  * 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 = le16_to_cpu(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                 queue->R0 = le32_to_cpu(R[0]);
454                 queue->R1 = le32_to_cpu(R[1]);
455                 queue->R2 = le32_to_cpu(R[2]);
456                 break;
457         default:
458                 LZX_DEBUG("Found invalid block.");
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("lzx_decode_match(): Match of length %d bytes overflows "
617                       "uncompressed block size", match_len);
618                 return -1;
619         }
620
621         if (match_src < window) {
622                 ERROR("lzx_decode_match(): Match of length %d bytes references "
623                       "data before window (match_offset = %d, window_pos = %d)",
624                       match_len, match_offset, window_pos);
625                 return -1;
626         }
627
628 #if 0
629         printf("Match: src %u, dst %u, len %u\n", match_src - window,
630                                                 match_dest - window,
631                                                 match_len);
632         putchar('|');
633         for (i = 0; i < match_len; i++) {
634                 match_dest[i] = match_src[i];
635                 putchar(match_src[i]);
636         }
637         putchar('|');
638         putchar('\n');
639 #else
640         for (i = 0; i < match_len; i++)
641                 match_dest[i] = match_src[i];
642 #endif
643
644         return match_len;
645 }
646
647
648
649 /* Undo the 'E8' preprocessing, where the targets of x86 CALL instructions were
650  * changed from relative offsets to absolute offsets.  This type of
651  * preprocessing can be used on any binary data even if it is not actually
652  * machine code.  It seems to always be used in WIM files, even though there is
653  * no bit to indicate that it actually is used, unlike in the LZX compressed
654  * format as used in other file formats, where a bit is reserved for that
655  * purpose. */
656 static void undo_call_insn_preprocessing(u8 uncompressed_data[],
657                                          uint uncompressed_data_len)
658 {
659         int i = 0;
660         int file_size = LZX_MAGIC_FILESIZE;
661         int32_t abs_offset;
662         int32_t rel_offset;
663
664         /* Not enabled in the last 6 bytes, which means the 5-byte call
665          * instruction cannot start in the last *10* bytes. */
666         while (i < uncompressed_data_len - 10) {
667                 if (uncompressed_data[i] != 0xe8) {
668                         i++;
669                         continue;
670                 }
671                 abs_offset = le32_to_cpu(*(int32_t*)(uncompressed_data + i + 1));
672
673                 if (abs_offset >= -i && abs_offset < file_size) {
674                         if (abs_offset >= 0) {
675                                 /* "good translation" */
676                                 rel_offset = abs_offset - i;
677                         } else {
678                                 /* "compensating translation" */
679                                 rel_offset = abs_offset + file_size;
680                         }
681                         *(int32_t*)(uncompressed_data + i + 1) =
682                                                 cpu_to_le32(rel_offset);
683                 }
684                 i += 5;
685         }
686 }
687
688 /*
689  * Decompresses a compressed block of data from which the header has already
690  * been read.
691  *
692  * @block_type: The type of the block (LZX_BLOCKTYPE_VERBATIM or
693  *              LZX_BLOCKTYPE_ALIGNED)
694  * @block_size: The size of the block, in bytes.
695  * @window:     Pointer to the decompression window.
696  * @window_pos: The current position in the window.  Will be 0 for the first
697  *                      block.
698  * @tables:     The Huffman decoding tables for the block (main, length, and
699  *                      aligned offset, the latter only for LZX_BLOCKTYPE_ALIGNED)
700  * @queue:      The least-recently-used queue for match offsets.
701  * @istream:    The input bitstream for the compressed literals.
702  */
703 static int lzx_decompress_block(int block_type, int block_size, u8 *window,
704                                 int window_pos,
705                                 const struct lzx_tables *tables,
706                                 struct lru_queue *queue,
707                                 struct input_bitstream *istream)
708 {
709         uint bytes_remaining;
710         uint main_element;
711         int match_len;
712         int ret;
713
714         bytes_remaining = block_size;
715         while (bytes_remaining > 0) {
716
717                 ret = read_huffsym_using_maintree(istream, tables,
718                                                   &main_element);
719                 if (ret != 0)
720                         return ret;
721
722                 if (main_element < LZX_NUM_CHARS) {
723                         /* literal: 0 to LZX_NUM_CHARS - 1 */
724                         window[window_pos + block_size - bytes_remaining] =
725                                                         main_element;
726                         bytes_remaining--;
727                 } else {
728                         /* match: LZX_NUM_CHARS to LZX_MAINTREE_NUM_SYMBOLS - 1 */
729                         match_len = lzx_decode_match(main_element,
730                                                 block_type, bytes_remaining, window,
731                                                 block_size + window_pos -
732                                                         bytes_remaining,
733                                                 tables, queue, istream);
734                         if (match_len == -1)
735                                 return 1;
736
737                         bytes_remaining -= match_len;
738                 }
739         }
740         return 0;
741 }
742
743 /*
744  * Decompresses a block of LZX-compressed data using a window size of 32768.
745  *
746  * @compressed_data:    A pointer to the compressed data.
747  * @compressed_len:     The length of the compressed data, in bytes.
748  * @uncompressed_data:  A pointer to the buffer into which to write the
749  *                              uncompressed data.
750  * @uncompressed_len:   The length of the uncompressed data.
751  *
752  * Return non-zero on failure.
753  */
754 int lzx_decompress(const void *compressed_data, uint compressed_len,
755                    void *uncompressed_data, uint uncompressed_len)
756 {
757         struct lzx_tables       tables;
758         struct input_bitstream  istream;
759         struct lru_queue        queue;
760         uint                    bytes_remaining;
761         int ret;
762         int block_size;
763         int block_type;
764
765         LZX_DEBUG("lzx_decompress (compressed_data = %p, compressed_len = %d, "
766                   "uncompressed_data = %p, uncompressed_len = %d).",
767                   compressed_data, compressed_len,
768                   uncompressed_data, uncompressed_len);
769
770         wimlib_assert(uncompressed_len <= 32768);
771
772         memset(tables.maintree_lens, 0, sizeof(tables.maintree_lens));
773         memset(tables.lentree_lens, 0, sizeof(tables.lentree_lens));
774         queue.R0 = 1;
775         queue.R1 = 1;
776         queue.R2 = 1;
777         bytes_remaining = uncompressed_len;
778
779         init_input_bitstream(&istream, compressed_data, compressed_len);
780
781         /* The compressed data will consist of one or more blocks.  The
782          * following loop decompresses one block, and it runs until there all
783          * the compressed data has been decompressed, so there are no more
784          * blocks.  */
785
786         while (bytes_remaining != 0) {
787
788                 LZX_DEBUG("Reading block header.");
789                 ret = lzx_read_block_header(&istream, &block_size, &block_type,
790                                                         &tables, &queue);
791                 if (ret != 0)
792                         return ret;
793
794                 LZX_DEBUG("block_size = %d, bytes_remaining = %d.",
795                           block_size, bytes_remaining);
796
797                 if (block_size > bytes_remaining) {
798                         ERROR("lzx_decompress(): Expected a block size of at "
799                               "most %d bytes (found %d bytes)",
800                               bytes_remaining, block_size);
801                         return 1;
802                 }
803
804                 switch (block_type) {
805                 case LZX_BLOCKTYPE_VERBATIM:
806                 case LZX_BLOCKTYPE_ALIGNED:
807                         if (block_type == LZX_BLOCKTYPE_VERBATIM)
808                                 LZX_DEBUG("LZX_BLOCKTYPE_VERBATIM");
809                         else
810                                 LZX_DEBUG("LZX_BLOCKTYPE_ALIGNED");
811
812                         ret = lzx_decompress_block(block_type,
813                                                    block_size,
814                                                    uncompressed_data,
815                                                    uncompressed_len -
816                                                        bytes_remaining,
817                                                    &tables, &queue, &istream);
818                         if (ret != 0)
819                                 return ret;
820                         break;
821                 case LZX_BLOCKTYPE_UNCOMPRESSED:
822                         LZX_DEBUG("LZX_BLOCKTYPE_UNCOMPRESSED");
823                         ret = bitstream_read_bytes(&istream, block_size,
824                                                    uncompressed_data +
825                                                    uncompressed_len -
826                                                    bytes_remaining);
827                         if (ret != 0)
828                                 return ret;
829                         if (block_size & 1)
830                                 align_input_bitstream(&istream, false);
831                         break;
832                 default:
833                         wimlib_assert(0);
834                         break;
835                 }
836
837                 bytes_remaining -= block_size;
838
839                 if (bytes_remaining != 0)
840                         LZX_DEBUG("%d bytes remaining.", bytes_remaining);
841
842         }
843
844         if (uncompressed_len >= 10)
845                 undo_call_insn_preprocessing(uncompressed_data,
846                                              uncompressed_len);
847
848         return 0;
849 }