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