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