4 * A decompressor for the LZX compression format, as used in WIM files.
8 * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
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
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
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/.
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.
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...
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.
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
50 * TODO: Add support for window sizes up to 2^25 bytes.
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"
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
71 #define LZX_READ_LENS_MAX_OVERRUN 50
73 /* Huffman decoding tables, and arrays that map symbols to codeword lengths. */
76 u16 maincode_decode_table[(1 << LZX_MAINCODE_TABLEBITS) +
77 (LZX_MAINCODE_MAX_NUM_SYMBOLS * 2)]
78 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
79 u8 maincode_lens[LZX_MAINCODE_MAX_NUM_SYMBOLS + LZX_READ_LENS_MAX_OVERRUN];
82 u16 lencode_decode_table[(1 << LZX_LENCODE_TABLEBITS) +
83 (LZX_LENCODE_NUM_SYMBOLS * 2)]
84 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
85 u8 lencode_lens[LZX_LENCODE_NUM_SYMBOLS + LZX_READ_LENS_MAX_OVERRUN];
88 u16 alignedcode_decode_table[(1 << LZX_ALIGNEDCODE_TABLEBITS) +
89 (LZX_ALIGNEDCODE_NUM_SYMBOLS * 2)]
90 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
91 u8 alignedcode_lens[LZX_ALIGNEDCODE_NUM_SYMBOLS];
92 } _aligned_attribute(DECODE_TABLE_ALIGNMENT);
94 /* Least-recently used queue for match offsets. */
95 struct lzx_lru_queue {
96 u32 R[LZX_NUM_RECENT_OFFSETS];
100 lzx_lru_queue_init(struct lzx_lru_queue *queue)
102 for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++)
106 /* The main LZX decompressor structure.
108 * Note: we keep track of most of the decompression state outside this
109 * structure. This structure only exists so that (1) we can store @window_order
110 * and @num_main_syms for multiple calls to lzx_decompress(); and (2) so that we
111 * don't have to allocate the large 'struct lzx_tables' on the stack. */
112 struct lzx_decompressor {
113 unsigned window_order;
114 unsigned num_main_syms;
115 struct lzx_tables tables;
118 /* Read a Huffman-encoded symbol using the precode. */
120 read_huffsym_using_precode(struct input_bitstream *istream,
121 const u16 precode_decode_table[])
123 return read_huffsym(istream, precode_decode_table,
124 LZX_PRECODE_TABLEBITS, LZX_MAX_PRE_CODEWORD_LEN);
127 /* Read a Huffman-encoded symbol using the main code. */
129 read_huffsym_using_maincode(struct input_bitstream *istream,
130 const struct lzx_tables *tables)
132 return read_huffsym(istream, tables->maincode_decode_table,
133 LZX_MAINCODE_TABLEBITS, LZX_MAX_MAIN_CODEWORD_LEN);
136 /* Read a Huffman-encoded symbol using the length code. */
138 read_huffsym_using_lencode(struct input_bitstream *istream,
139 const struct lzx_tables *tables)
141 return read_huffsym(istream, tables->lencode_decode_table,
142 LZX_LENCODE_TABLEBITS, LZX_MAX_LEN_CODEWORD_LEN);
145 /* Read a Huffman-encoded symbol using the aligned offset code. */
147 read_huffsym_using_alignedcode(struct input_bitstream *istream,
148 const struct lzx_tables *tables)
150 return read_huffsym(istream, tables->alignedcode_decode_table,
151 LZX_ALIGNEDCODE_TABLEBITS, LZX_MAX_ALIGNED_CODEWORD_LEN);
155 * Read the precode from the compressed input bitstream, then use it to decode
156 * @num_lens codeword length values.
159 * The input bitstream.
162 * An array that contains the length values from the previous time the
163 * codeword lengths for this Huffman code were read, or all 0's if this is
164 * the first time. This array must have at least (@num_lens +
165 * LZX_READ_LENS_MAX_OVERRUN) entries.
168 * Number of length values to decode.
170 * Returns 0 on success, or -1 if the data was invalid.
173 lzx_read_codeword_lens(struct input_bitstream *istream, u8 *lens, unsigned num_lens)
175 u16 precode_decode_table[(1 << LZX_PRECODE_TABLEBITS) +
176 (LZX_PRECODE_NUM_SYMBOLS * 2)]
177 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
178 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
180 u8 *lens_end = lens + num_lens;
183 /* Read the lengths of the precode codewords. These are given
185 for (int i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++) {
186 precode_lens[i] = bitstream_read_bits(istream,
187 LZX_PRECODE_ELEMENT_SIZE);
190 /* Make the decoding table for the precode. */
191 ret = make_huffman_decode_table(precode_decode_table,
192 LZX_PRECODE_NUM_SYMBOLS,
193 LZX_PRECODE_TABLEBITS,
195 LZX_MAX_PRE_CODEWORD_LEN);
199 /* Decode the codeword lengths. */
204 /* Read the next precode symbol. */
205 presym = read_huffsym_using_precode(istream,
206 precode_decode_table);
208 /* Difference from old length */
209 len = *len_ptr - presym;
214 /* Special RLE values */
220 run_len = 4 + bitstream_read_bits(istream, 4);
222 } else if (presym == 18) {
223 /* Longer run of 0's */
224 run_len = 20 + bitstream_read_bits(istream, 5);
227 /* Run of identical lengths */
228 run_len = 4 + bitstream_read_bits(istream, 1);
229 presym = read_huffsym_using_precode(istream,
230 precode_decode_table);
231 len = *len_ptr - presym;
239 /* Worst case overrun is when presym == 18,
240 * run_len == 20 + 31, and only 1 length was remaining.
241 * So LZX_READ_LENS_MAX_OVERRUN == 50.
243 * Overrun while reading the first half of maincode_lens
244 * can corrupt the previous values in the second half.
245 * This doesn't really matter because the resulting
246 * lengths will still be in range, and data that
247 * generates overruns is invalid anyway. */
249 } while (len_ptr < lens_end);
254 * Read the header of an LZX block and save the block type and size in
255 * *block_type_ret and *block_size_ret, respectively.
257 * If the block is compressed, also update the Huffman decode @tables with the
260 * If the block is uncompressed, also update the match offset @queue with the
263 * Return 0 on success, or -1 if the data was invalid.
266 lzx_read_block_header(struct input_bitstream *istream,
267 unsigned num_main_syms,
268 unsigned window_order,
271 struct lzx_tables *tables,
272 struct lzx_lru_queue *queue)
278 bitstream_ensure_bits(istream, 4);
280 /* The first three bits tell us what kind of block it is, and should be
281 * one of the LZX_BLOCKTYPE_* values. */
282 block_type = bitstream_pop_bits(istream, 3);
284 /* Read the block size. This mirrors the behavior of
285 * lzx_write_compressed_block() in lzx_compress.c; see that for more
287 if (bitstream_pop_bits(istream, 1)) {
288 block_size = LZX_DEFAULT_BLOCK_SIZE;
293 tmp = bitstream_read_bits(istream, 8);
295 tmp = bitstream_read_bits(istream, 8);
299 if (window_order >= 16) {
300 tmp = bitstream_read_bits(istream, 8);
306 switch (block_type) {
308 case LZX_BLOCKTYPE_ALIGNED:
310 /* Read the aligned offset code and prepare its decode table.
313 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
314 tables->alignedcode_lens[i] =
315 bitstream_read_bits(istream,
316 LZX_ALIGNEDCODE_ELEMENT_SIZE);
319 ret = make_huffman_decode_table(tables->alignedcode_decode_table,
320 LZX_ALIGNEDCODE_NUM_SYMBOLS,
321 LZX_ALIGNEDCODE_TABLEBITS,
322 tables->alignedcode_lens,
323 LZX_MAX_ALIGNED_CODEWORD_LEN);
327 /* Fall though, since the rest of the header for aligned offset
328 * blocks is the same as that for verbatim blocks. */
330 case LZX_BLOCKTYPE_VERBATIM:
332 /* Read the main code and prepare its decode table.
334 * Note that the codeword lengths in the main code are encoded
335 * in two parts: one part for literal symbols, and one part for
338 ret = lzx_read_codeword_lens(istream, tables->maincode_lens,
343 ret = lzx_read_codeword_lens(istream,
344 tables->maincode_lens + LZX_NUM_CHARS,
345 num_main_syms - LZX_NUM_CHARS);
349 ret = make_huffman_decode_table(tables->maincode_decode_table,
351 LZX_MAINCODE_TABLEBITS,
352 tables->maincode_lens,
353 LZX_MAX_MAIN_CODEWORD_LEN);
357 /* Read the length code and prepare its decode table. */
359 ret = lzx_read_codeword_lens(istream, tables->lencode_lens,
360 LZX_LENCODE_NUM_SYMBOLS);
364 ret = make_huffman_decode_table(tables->lencode_decode_table,
365 LZX_LENCODE_NUM_SYMBOLS,
366 LZX_LENCODE_TABLEBITS,
367 tables->lencode_lens,
368 LZX_MAX_LEN_CODEWORD_LEN);
374 case LZX_BLOCKTYPE_UNCOMPRESSED:
376 /* Before reading the three LRU match offsets from the
377 * uncompressed block header, the stream must be aligned on a
378 * 16-bit boundary. But, unexpectedly, if the stream is
379 * *already* aligned, the correct thing to do is to throw away
380 * the next 16 bits. */
382 bitstream_ensure_bits(istream, 1);
383 bitstream_align(istream);
384 queue->R[0] = bitstream_read_u32(istream);
385 queue->R[1] = bitstream_read_u32(istream);
386 queue->R[2] = bitstream_read_u32(istream);
388 /* Offsets of 0 are invalid. */
389 if (queue->R[0] == 0 || queue->R[1] == 0 || queue->R[2] == 0)
394 /* Unrecognized block type. */
398 *block_type_ret = block_type;
399 *block_size_ret = block_size;
404 * Decompress an LZX-compressed block of data.
407 * The type of the block (LZX_BLOCKTYPE_VERBATIM or LZX_BLOCKTYPE_ALIGNED).
410 * The size of the block, in bytes.
413 * Pointer to the beginning of the decompression window.
416 * The position in the window at which the block starts.
419 * The Huffman decoding tables for the block.
422 * The least-recently-used queue for match offsets.
425 * The input bitstream, positioned at the start of the block data.
427 * Returns 0 on success, or -1 if the data was invalid.
430 lzx_decompress_block(int block_type, u32 block_size,
431 u8 *window, u32 window_pos,
432 const struct lzx_tables *tables,
433 struct lzx_lru_queue *queue,
434 struct input_bitstream *istream)
436 u8 *window_ptr = &window[window_pos];
437 u8 *window_end = window_ptr + block_size;
440 unsigned offset_slot;
442 unsigned num_extra_bits;
443 unsigned ones_if_aligned = 0U - (block_type == LZX_BLOCKTYPE_ALIGNED);
445 while (window_ptr != window_end) {
447 mainsym = read_huffsym_using_maincode(istream, tables);
448 if (mainsym < LZX_NUM_CHARS) {
450 *window_ptr++ = mainsym;
456 /* Decode the length header and offset slot. */
457 mainsym -= LZX_NUM_CHARS;
458 match_len = mainsym % LZX_NUM_LEN_HEADERS;
459 offset_slot = mainsym / LZX_NUM_LEN_HEADERS;
461 /* If needed, read a length symbol to decode the full length. */
462 if (match_len == LZX_NUM_PRIMARY_LENS)
463 match_len += read_huffsym_using_lencode(istream, tables);
464 match_len += LZX_MIN_MATCH_LEN;
466 if (offset_slot < LZX_NUM_RECENT_OFFSETS) {
469 /* Note: This isn't a real LRU queue, since using the R2
470 * offset doesn't bump the R1 offset down to R2. This
471 * quirk allows all 3 recent offsets to be handled by
472 * the same code. (For R0, the swap is a no-op.) */
473 match_offset = queue->R[offset_slot];
474 queue->R[offset_slot] = queue->R[0];
475 queue->R[0] = match_offset;
477 /* Explicit offset */
479 /* Look up the number of extra bits that need to be read
480 * to decode offsets with this offset slot. */
481 num_extra_bits = lzx_extra_offset_bits[offset_slot];
483 /* Start with the offset slot base value. */
484 match_offset = lzx_offset_slot_base[offset_slot];
486 /* In aligned offset blocks, the low-order 3 bits of
487 * each offset are encoded using the aligned offset
488 * code. Otherwise, all the extra bits are literal. */
490 if ((num_extra_bits & ones_if_aligned) >= LZX_NUM_ALIGNED_OFFSET_BITS) {
492 bitstream_read_bits(istream,
494 LZX_NUM_ALIGNED_OFFSET_BITS)
495 << LZX_NUM_ALIGNED_OFFSET_BITS;
496 match_offset += read_huffsym_using_alignedcode(istream, tables);
498 match_offset += bitstream_read_bits(istream, num_extra_bits);
501 /* Adjust the offset. */
502 match_offset -= LZX_OFFSET_ADJUSTMENT;
504 /* Update the match offset LRU queue. */
505 BUILD_BUG_ON(LZX_NUM_RECENT_OFFSETS != 3);
506 queue->R[2] = queue->R[1];
507 queue->R[1] = queue->R[0];
508 queue->R[0] = match_offset;
511 /* Validate the match, then copy it to the current position. */
513 if (unlikely(match_len > window_end - window_ptr))
516 if (unlikely(match_offset > window_ptr - window))
519 lz_copy(window_ptr, match_len, match_offset, window_end,
522 window_ptr += match_len;
528 lzx_decompress(const void *compressed_data, size_t compressed_size,
529 void *uncompressed_data, size_t uncompressed_size,
532 struct lzx_decompressor *dec = _dec;
533 struct input_bitstream istream;
534 struct lzx_lru_queue queue;
538 bool may_have_e8_byte;
541 init_input_bitstream(&istream, compressed_data, compressed_size);
543 /* Initialize the recent offsets queue. */
544 lzx_lru_queue_init(&queue);
546 /* Codeword lengths begin as all 0's for delta encoding purposes. */
547 memset(dec->tables.maincode_lens, 0, dec->num_main_syms);
548 memset(dec->tables.lencode_lens, 0, LZX_LENCODE_NUM_SYMBOLS);
550 /* Set this to true if there may be 0xe8 bytes in the uncompressed data.
552 may_have_e8_byte = false;
554 /* The compressed data will consist of one or more blocks. The
555 * following loop decompresses one block, and it runs until there all
556 * the compressed data has been decompressed, so there are no more
560 window_pos < uncompressed_size;
561 window_pos += block_size)
563 ret = lzx_read_block_header(&istream, dec->num_main_syms,
564 dec->window_order, &block_type,
565 &block_size, &dec->tables, &queue);
569 if (block_size > uncompressed_size - window_pos)
572 if (block_type != LZX_BLOCKTYPE_UNCOMPRESSED) {
574 /* Compressed block. */
576 ret = lzx_decompress_block(block_type,
586 /* If the first 0xe8 byte was in this block, it must
587 * have been encoded as a literal using mainsym 0xe8. */
588 if (dec->tables.maincode_lens[0xe8] != 0)
589 may_have_e8_byte = true;
592 /* Uncompressed block. */
595 p = bitstream_read_bytes(&istream, block_size);
599 memcpy(&((u8*)uncompressed_data)[window_pos], p, block_size);
601 /* Re-align the bitstream if an odd number of bytes was
604 bitstream_read_byte(&istream);
606 may_have_e8_byte = true;
610 /* Postprocess the data unless it cannot possibly contain 0xe8 bytes */
611 if (may_have_e8_byte)
612 lzx_undo_e8_preprocessing(uncompressed_data, uncompressed_size);
618 lzx_free_decompressor(void *_dec)
620 struct lzx_decompressor *dec = _dec;
626 lzx_create_decompressor(size_t max_block_size, void **dec_ret)
628 struct lzx_decompressor *dec;
629 unsigned window_order;
631 window_order = lzx_get_window_order(max_block_size);
632 if (window_order == 0)
633 return WIMLIB_ERR_INVALID_PARAM;
635 /* The aligned allocation is needed to ensure that the lzx_tables are
636 * aligned properly. */
637 dec = ALIGNED_MALLOC(sizeof(struct lzx_decompressor),
638 DECODE_TABLE_ALIGNMENT);
640 return WIMLIB_ERR_NOMEM;
642 dec->window_order = window_order;
643 dec->num_main_syms = lzx_get_num_main_syms(window_order);
649 const struct decompressor_ops lzx_decompressor_ops = {
650 .create_decompressor = lzx_create_decompressor,
651 .decompress = lzx_decompress,
652 .free_decompressor = lzx_free_decompressor,