]> wimlib.net Git - wimlib/blob - src/lzx_decompress.c
9accd8df2a84cba97a9961c1684722f2864ee99c
[wimlib] / src / lzx_decompress.c
1 /*
2  * lzx_decompress.c
3  *
4  * A decompressor for the LZX compression format, as used in WIM files.
5  */
6
7 /*
8  * Copyright (C) 2012-2016 Eric Biggers
9  *
10  * This file is free software; you can redistribute it and/or modify it under
11  * the terms of the GNU Lesser General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option) any
13  * later version.
14  *
15  * This file is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this file; if not, see http://www.gnu.org/licenses/.
22  */
23
24 /*
25  * LZX is an LZ77 and Huffman-code based compression format that has many
26  * similarities to DEFLATE (the format used by zlib/gzip).  The compression
27  * ratio is as good or better than DEFLATE.  See lzx_compress.c for a format
28  * overview, and see https://en.wikipedia.org/wiki/LZX_(algorithm) for a
29  * historical overview.  Here I make some pragmatic notes.
30  *
31  * The old specification for LZX is the document "Microsoft LZX Data Compression
32  * Format" (1997).  It defines the LZX format as used in cabinet files.  Allowed
33  * window sizes are 2^n where 15 <= n <= 21.  However, this document contains
34  * several errors, so don't read too much into it...
35  *
36  * The new specification for LZX is the document "[MS-PATCH]: LZX DELTA
37  * Compression and Decompression" (2014).  It defines the LZX format as used by
38  * Microsoft's binary patcher.  It corrects several errors in the 1997 document
39  * and extends the format in several ways --- namely, optional reference data,
40  * up to 2^25 byte windows, and longer match lengths.
41  *
42  * WIM files use a more restricted form of LZX.  No LZX DELTA extensions are
43  * present, the window is not "sliding", E8 preprocessing is done
44  * unconditionally with a fixed file size, and the maximum window size is always
45  * 2^15 bytes (equal to the size of each "chunk" in a compressed WIM resource).
46  * This code is primarily intended to implement this form of LZX.  But although
47  * not compatible with WIMGAPI, this code also supports maximum window sizes up
48  * to 2^21 bytes.
49  *
50  * TODO: Add support for window sizes up to 2^25 bytes.
51  */
52
53 #ifdef HAVE_CONFIG_H
54 #  include "config.h"
55 #endif
56
57 #include <string.h>
58
59 #include "wimlib/decompressor_ops.h"
60 #include "wimlib/decompress_common.h"
61 #include "wimlib/error.h"
62 #include "wimlib/lzx_common.h"
63 #include "wimlib/util.h"
64
65 /* These values are chosen for fast decompression.  */
66 #define LZX_MAINCODE_TABLEBITS          11
67 #define LZX_LENCODE_TABLEBITS           10
68 #define LZX_PRECODE_TABLEBITS           6
69 #define LZX_ALIGNEDCODE_TABLEBITS       7
70
71 #define LZX_READ_LENS_MAX_OVERRUN 50
72
73 /* Reusable heap-allocated memory for LZX decompression */
74 struct lzx_decompressor {
75
76         /* Huffman decoding tables, and arrays that map symbols to codeword
77          * lengths  */
78
79         u16 maincode_decode_table[(1 << LZX_MAINCODE_TABLEBITS) +
80                                         (LZX_MAINCODE_MAX_NUM_SYMBOLS * 2)]
81                                         _aligned_attribute(DECODE_TABLE_ALIGNMENT);
82         u8 maincode_lens[LZX_MAINCODE_MAX_NUM_SYMBOLS + LZX_READ_LENS_MAX_OVERRUN];
83
84
85         u16 lencode_decode_table[(1 << LZX_LENCODE_TABLEBITS) +
86                                         (LZX_LENCODE_NUM_SYMBOLS * 2)]
87                                         _aligned_attribute(DECODE_TABLE_ALIGNMENT);
88         u8 lencode_lens[LZX_LENCODE_NUM_SYMBOLS + LZX_READ_LENS_MAX_OVERRUN];
89
90         union {
91                 u16 alignedcode_decode_table[(1 << LZX_ALIGNEDCODE_TABLEBITS) +
92                                                 (LZX_ALIGNEDCODE_NUM_SYMBOLS * 2)]
93                                                 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
94                 u8 alignedcode_lens[LZX_ALIGNEDCODE_NUM_SYMBOLS];
95         };
96
97         union {
98                 u16 precode_decode_table[(1 << LZX_PRECODE_TABLEBITS) +
99                                          (LZX_PRECODE_NUM_SYMBOLS * 2)]
100                                                 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
101                 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
102         };
103
104         unsigned window_order;
105         unsigned num_main_syms;
106 } _aligned_attribute(DECODE_TABLE_ALIGNMENT);
107
108 /* Read a Huffman-encoded symbol using the precode. */
109 static inline unsigned
110 read_presym(const struct lzx_decompressor *d, struct input_bitstream *is)
111 {
112         return read_huffsym(is, d->precode_decode_table,
113                             LZX_PRECODE_TABLEBITS, LZX_MAX_PRE_CODEWORD_LEN);
114 }
115
116 /* Read a Huffman-encoded symbol using the main code. */
117 static inline unsigned
118 read_mainsym(const struct lzx_decompressor *d, struct input_bitstream *is)
119 {
120         return read_huffsym(is, d->maincode_decode_table,
121                             LZX_MAINCODE_TABLEBITS, LZX_MAX_MAIN_CODEWORD_LEN);
122 }
123
124 /* Read a Huffman-encoded symbol using the length code. */
125 static inline unsigned
126 read_lensym(const struct lzx_decompressor *d, struct input_bitstream *is)
127 {
128         return read_huffsym(is, d->lencode_decode_table,
129                             LZX_LENCODE_TABLEBITS, LZX_MAX_LEN_CODEWORD_LEN);
130 }
131
132 /* Read a Huffman-encoded symbol using the aligned offset code. */
133 static inline unsigned
134 read_alignedsym(const struct lzx_decompressor *d, struct input_bitstream *is)
135 {
136         return read_huffsym(is, d->alignedcode_decode_table,
137                             LZX_ALIGNEDCODE_TABLEBITS, LZX_MAX_ALIGNED_CODEWORD_LEN);
138 }
139
140 /*
141  * Read a precode from the compressed input bitstream, then use it to decode
142  * @num_lens codeword length values and write them to @lens.
143  */
144 static int
145 lzx_read_codeword_lens(struct lzx_decompressor *d, struct input_bitstream *is,
146                        u8 *lens, unsigned num_lens)
147 {
148         u8 *len_ptr = lens;
149         u8 *lens_end = lens + num_lens;
150
151         /* Read the lengths of the precode codewords, which are stored
152          * explicitly. */
153         for (int i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++) {
154                 d->precode_lens[i] =
155                         bitstream_read_bits(is, LZX_PRECODE_ELEMENT_SIZE);
156         }
157
158         /* Build the decoding table for the precode. */
159         if (make_huffman_decode_table(d->precode_decode_table,
160                                       LZX_PRECODE_NUM_SYMBOLS,
161                                       LZX_PRECODE_TABLEBITS,
162                                       d->precode_lens,
163                                       LZX_MAX_PRE_CODEWORD_LEN))
164                 return -1;
165
166         /* Decode the codeword lengths. */
167         do {
168                 unsigned presym;
169                 u8 len;
170
171                 /* Read the next precode symbol. */
172                 presym = read_presym(d, is);
173                 if (presym < 17) {
174                         /* Difference from old length */
175                         len = *len_ptr - presym;
176                         if ((s8)len < 0)
177                                 len += 17;
178                         *len_ptr++ = len;
179                 } else {
180                         /* Special RLE values */
181
182                         unsigned run_len;
183
184                         if (presym == 17) {
185                                 /* Run of 0's */
186                                 run_len = 4 + bitstream_read_bits(is, 4);
187                                 len = 0;
188                         } else if (presym == 18) {
189                                 /* Longer run of 0's */
190                                 run_len = 20 + bitstream_read_bits(is, 5);
191                                 len = 0;
192                         } else {
193                                 /* Run of identical lengths */
194                                 run_len = 4 + bitstream_read_bits(is, 1);
195                                 presym = read_presym(d, is);
196                                 if (unlikely(presym > 17))
197                                         return -1;
198                                 len = *len_ptr - presym;
199                                 if ((s8)len < 0)
200                                         len += 17;
201                         }
202
203                         do {
204                                 *len_ptr++ = len;
205                         } while (--run_len);
206                         /*
207                          * The worst case overrun is when presym == 18,
208                          * run_len == 20 + 31, and only 1 length was remaining.
209                          * So LZX_READ_LENS_MAX_OVERRUN == 50.
210                          *
211                          * Overrun while reading the first half of maincode_lens
212                          * can corrupt the previous values in the second half.
213                          * This doesn't really matter because the resulting
214                          * lengths will still be in range, and data that
215                          * generates overruns is invalid anyway.
216                          */
217                 }
218         } while (len_ptr < lens_end);
219
220         return 0;
221 }
222
223 /*
224  * Read the header of an LZX block and save the block type and size in
225  * *block_type_ret and *block_size_ret, respectively.
226  *
227  * If the block is compressed, the nalso initialize the decode tables for the
228  * new Huffman codes.
229  *
230  * If the block is uncompressed, then also update the recent offsets queue.
231  *
232  * Return 0 on success, or -1 if the data was invalid.
233  */
234 static int
235 lzx_read_block_header(struct lzx_decompressor *d, struct input_bitstream *is,
236                       u32 recent_offsets[], int *block_type_ret,
237                       u32 *block_size_ret)
238 {
239         int block_type;
240         u32 block_size;
241
242         bitstream_ensure_bits(is, 4);
243
244         /* Read the block type. */
245         block_type = bitstream_pop_bits(is, 3);
246
247         /* Read the block size. */
248         if (bitstream_pop_bits(is, 1)) {
249                 block_size = LZX_DEFAULT_BLOCK_SIZE;
250         } else {
251                 u32 tmp;
252                 block_size = 0;
253
254                 tmp = bitstream_read_bits(is, 8);
255                 block_size |= tmp;
256                 tmp = bitstream_read_bits(is, 8);
257                 block_size <<= 8;
258                 block_size |= tmp;
259
260                 if (d->window_order >= 16) {
261                         tmp = bitstream_read_bits(is, 8);
262                         block_size <<= 8;
263                         block_size |= tmp;
264                 }
265         }
266
267         switch (block_type) {
268
269         case LZX_BLOCKTYPE_ALIGNED:
270
271                 /* Read the aligned offset code and build its decode table. */
272
273                 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
274                         d->alignedcode_lens[i] =
275                                 bitstream_read_bits(is,
276                                                     LZX_ALIGNEDCODE_ELEMENT_SIZE);
277                 }
278
279                 if (make_huffman_decode_table(d->alignedcode_decode_table,
280                                               LZX_ALIGNEDCODE_NUM_SYMBOLS,
281                                               LZX_ALIGNEDCODE_TABLEBITS,
282                                               d->alignedcode_lens,
283                                               LZX_MAX_ALIGNED_CODEWORD_LEN))
284                         return -1;
285
286                 /* Fall though, since the rest of the header for aligned offset
287                  * blocks is the same as that for verbatim blocks.  */
288
289         case LZX_BLOCKTYPE_VERBATIM:
290
291                 /* Read the main code and build its decode table.  The codeword
292                  * lengths in the main code are encoded in two parts: one part
293                  * for literal symbols, and one part for match symbols. */
294
295                 if (lzx_read_codeword_lens(d, is, d->maincode_lens,
296                                            LZX_NUM_CHARS))
297                         return -1;
298
299                 if (lzx_read_codeword_lens(d, is, d->maincode_lens + LZX_NUM_CHARS,
300                                            d->num_main_syms - LZX_NUM_CHARS))
301                         return -1;
302
303                 if (make_huffman_decode_table(d->maincode_decode_table,
304                                               d->num_main_syms,
305                                               LZX_MAINCODE_TABLEBITS,
306                                               d->maincode_lens,
307                                               LZX_MAX_MAIN_CODEWORD_LEN))
308                         return -1;
309
310                 /* Read the length code and build its decode table. */
311
312                 if (lzx_read_codeword_lens(d, is, d->lencode_lens,
313                                            LZX_LENCODE_NUM_SYMBOLS))
314                         return -1;
315
316                 if (make_huffman_decode_table(d->lencode_decode_table,
317                                               LZX_LENCODE_NUM_SYMBOLS,
318                                               LZX_LENCODE_TABLEBITS,
319                                               d->lencode_lens,
320                                               LZX_MAX_LEN_CODEWORD_LEN))
321                         return -1;
322
323                 break;
324
325         case LZX_BLOCKTYPE_UNCOMPRESSED:
326                 /*
327                  * The header of an uncompressed block contains new values for
328                  * the recent offsets queue, starting on the next 16-bit
329                  * boundary in the bitstream.  Careful: if the stream is
330                  * *already* aligned, the correct thing to do is to throw away
331                  * the next 16 bits (this is probably a mistake in the format).
332                  */
333                 bitstream_ensure_bits(is, 1);
334                 bitstream_align(is);
335                 recent_offsets[0] = bitstream_read_u32(is);
336                 recent_offsets[1] = bitstream_read_u32(is);
337                 recent_offsets[2] = bitstream_read_u32(is);
338
339                 /* Offsets of 0 are invalid. */
340                 if (recent_offsets[0] == 0 || recent_offsets[1] == 0 ||
341                     recent_offsets[2] == 0)
342                         return -1;
343                 break;
344
345         default:
346                 /* Unrecognized block type */
347                 return -1;
348         }
349
350         *block_type_ret = block_type;
351         *block_size_ret = block_size;
352         return 0;
353 }
354
355 /* Decompress a block of LZX-compressed data. */
356 static int
357 lzx_decompress_block(const struct lzx_decompressor *d,
358                      struct input_bitstream *is, int block_type, u32 block_size,
359                      u8 * const out_begin, u8 *out_next, u32 recent_offsets[])
360 {
361         bool is_aligned_block = (block_type == LZX_BLOCKTYPE_ALIGNED);
362         u8 * const block_end = out_next + block_size;
363
364         do {
365                 unsigned mainsym;
366                 unsigned length;
367                 u32 offset;
368                 unsigned offset_slot;
369                 unsigned num_extra_bits;
370
371                 mainsym = read_mainsym(d, is);
372                 if (mainsym < LZX_NUM_CHARS) {
373                         /* Literal */
374                         *out_next++ = mainsym;
375                         continue;
376                 }
377
378                 /* Match */
379
380                 /* Decode the length header and offset slot.  */
381                 mainsym -= LZX_NUM_CHARS;
382                 length = mainsym % LZX_NUM_LEN_HEADERS;
383                 offset_slot = mainsym / LZX_NUM_LEN_HEADERS;
384
385                 /* If needed, read a length symbol to decode the full length. */
386                 if (length == LZX_NUM_PRIMARY_LENS)
387                         length += read_lensym(d, is);
388                 length += LZX_MIN_MATCH_LEN;
389
390                 if (offset_slot < LZX_NUM_RECENT_OFFSETS) {
391                         /* Repeat offset  */
392
393                         /* Note: This isn't a real LRU queue, since using the R2
394                          * offset doesn't bump the R1 offset down to R2.  This
395                          * quirk allows all 3 recent offsets to be handled by
396                          * the same code.  (For R0, the swap is a no-op.)  */
397                         offset = recent_offsets[offset_slot];
398                         recent_offsets[offset_slot] = recent_offsets[0];
399                 } else {
400                         /* Explicit offset  */
401
402                         /* Look up the number of extra bits that need to be read
403                          * to decode offsets with this offset slot.  */
404                         num_extra_bits = lzx_extra_offset_bits[offset_slot];
405
406                         /* Start with the offset slot base value.  */
407                         offset = lzx_offset_slot_base[offset_slot];
408
409                         /* In aligned offset blocks, the low-order 3 bits of
410                          * each offset are encoded using the aligned offset
411                          * code.  Otherwise, all the extra bits are literal.  */
412
413                         if (is_aligned_block && offset_slot >= 8) {
414                                 offset +=
415                                         bitstream_read_bits(is,
416                                                             num_extra_bits -
417                                                                 LZX_NUM_ALIGNED_OFFSET_BITS)
418                                                         << LZX_NUM_ALIGNED_OFFSET_BITS;
419                                 offset += read_alignedsym(d, is);
420                         } else {
421                                 offset += bitstream_read_bits(is, num_extra_bits);
422                         }
423
424                         /* Adjust the offset.  */
425                         offset -= LZX_OFFSET_ADJUSTMENT;
426
427                         /* Update the match offset LRU queue.  */
428                         STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
429                         recent_offsets[2] = recent_offsets[1];
430                         recent_offsets[1] = recent_offsets[0];
431                 }
432                 recent_offsets[0] = offset;
433
434                 /* Validate the match, then copy it to the current position.  */
435
436                 if (unlikely(length > block_end - out_next))
437                         return -1;
438
439                 if (unlikely(offset > out_next - out_begin))
440                         return -1;
441
442                 lz_copy(out_next, length, offset, block_end, LZX_MIN_MATCH_LEN);
443
444                 out_next += length;
445
446         } while (out_next != block_end);
447
448         return 0;
449 }
450
451 static int
452 lzx_decompress(const void *restrict compressed_data, size_t compressed_size,
453                void *restrict uncompressed_data, size_t uncompressed_size,
454                void *restrict _d)
455 {
456         struct lzx_decompressor *d = _d;
457         u8 * const out_begin = uncompressed_data;
458         u8 *out_next = out_begin;
459         u8 * const out_end = out_begin + uncompressed_size;
460         struct input_bitstream is;
461         STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
462         u32 recent_offsets[] = {1, 1, 1};
463         unsigned e8_status = 0;
464
465         init_input_bitstream(&is, compressed_data, compressed_size);
466
467         /* Codeword lengths begin as all 0's for delta encoding purposes. */
468         memset(d->maincode_lens, 0, d->num_main_syms);
469         memset(d->lencode_lens, 0, LZX_LENCODE_NUM_SYMBOLS);
470
471         /* Decompress blocks until we have all the uncompressed data. */
472
473         while (out_next != out_end) {
474                 int block_type;
475                 u32 block_size;
476
477                 if (lzx_read_block_header(d, &is, recent_offsets,
478                                           &block_type, &block_size))
479                         return -1;
480
481                 if (block_size < 1 || block_size > out_end - out_next)
482                         return -1;
483
484                 if (block_type != LZX_BLOCKTYPE_UNCOMPRESSED) {
485
486                         /* Compressed block */
487                         if (lzx_decompress_block(d, &is, block_type, block_size,
488                                                  out_begin, out_next,
489                                                  recent_offsets))
490                                 return -1;
491
492                         /* If the first E8 byte was in this block, then it must
493                          * have been encoded as a literal using mainsym E8. */
494                         e8_status |= d->maincode_lens[0xE8];
495                 } else {
496
497                         /* Uncompressed block */
498                         if (bitstream_read_bytes(&is, out_next, block_size))
499                                 return -1;
500
501                         /* Re-align the bitstream if needed. */
502                         if (block_size & 1)
503                                 bitstream_read_byte(&is);
504
505                         /* There may have been an E8 byte in the block. */
506                         e8_status = 1;
507                 }
508                 out_next += block_size;
509         }
510
511         /* Postprocess the data unless it cannot possibly contain E8 bytes. */
512         if (e8_status)
513                 lzx_postprocess(uncompressed_data, uncompressed_size);
514
515         return 0;
516 }
517
518 static void
519 lzx_free_decompressor(void *_d)
520 {
521         ALIGNED_FREE(_d);
522 }
523
524 static int
525 lzx_create_decompressor(size_t max_block_size, void **d_ret)
526 {
527         unsigned window_order;
528         struct lzx_decompressor *d;
529
530         window_order = lzx_get_window_order(max_block_size);
531         if (window_order == 0)
532                 return WIMLIB_ERR_INVALID_PARAM;
533
534         d = ALIGNED_MALLOC(sizeof(*d), DECODE_TABLE_ALIGNMENT);
535         if (!d)
536                 return WIMLIB_ERR_NOMEM;
537
538         d->window_order = window_order;
539         d->num_main_syms = lzx_get_num_main_syms(window_order);
540
541         *d_ret = d;
542         return 0;
543 }
544
545 const struct decompressor_ops lzx_decompressor_ops = {
546         .create_decompressor = lzx_create_decompressor,
547         .decompress          = lzx_decompress,
548         .free_decompressor   = lzx_free_decompressor,
549 };