4 * A very fast decompressor for LZX, as used in WIM files.
8 * Copyright (C) 2012, 2013, 2014 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your option)
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with wimlib; if not, see http://www.gnu.org/licenses/.
27 * LZX is an LZ77 and Huffman-code based compression format that has many
28 * similarities to DEFLATE (the format used by zlib/gzip). The compression
29 * ratio is as good or better than DEFLATE. See lzx-compress.c for a format
30 * overview, and see https://en.wikipedia.org/wiki/LZX_(algorithm) for a
31 * historical overview. Here I make some pragmatic notes.
33 * The old specification for LZX is the document "Microsoft LZX Data Compression
34 * Format" (1997). It defines the LZX format as used in cabinet files. Allowed
35 * window sizes are 2^n where 15 <= n <= 21. However, this document contains
36 * several errors, so don't read too much into it...
38 * The new specification for LZX is the document "[MS-PATCH]: LZX DELTA
39 * Compression and Decompression" (2014). It defines the LZX format as used by
40 * Microsoft's binary patcher. It corrects several errors in the 1997 document
41 * and extends the format in several ways --- namely, optional reference data,
42 * up to 2^25 byte windows, and longer match lengths.
44 * WIM files use a more restricted form of LZX. No LZX DELTA extensions are
45 * present, the window is not "sliding", E8 preprocessing is done
46 * unconditionally with a fixed file size, and the maximum window size is always
47 * 2^15 bytes (equal to the size of each "chunk" in a compressed WIM resource).
48 * This code is primarily intended to implement this form of LZX. But although
49 * not compatible with WIMGAPI, this code also supports maximum window sizes up
52 * 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.h"
63 #include "wimlib/util.h"
67 /* These values are chosen for fast decompression. */
68 #define LZX_MAINCODE_TABLEBITS 11
69 #define LZX_LENCODE_TABLEBITS 10
70 #define LZX_PRECODE_TABLEBITS 6
71 #define LZX_ALIGNEDCODE_TABLEBITS 7
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];
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];
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 /* The main LZX decompressor structure.
96 * Note: we keep track of most of the decompression state outside this
97 * structure. This structure only exists so that (1) we can store @window_order
98 * and @num_main_syms for multiple calls to lzx_decompress(); and (2) so that we
99 * don't have to allocate the large 'struct lzx_tables' on the stack. */
100 struct lzx_decompressor {
101 unsigned window_order;
102 unsigned num_main_syms;
103 struct lzx_tables tables;
106 /* Read a Huffman-encoded symbol using the precode. */
108 read_huffsym_using_precode(struct input_bitstream *istream,
109 const u16 precode_decode_table[])
111 return read_huffsym(istream, precode_decode_table,
112 LZX_PRECODE_TABLEBITS, LZX_MAX_PRE_CODEWORD_LEN);
115 /* Read a Huffman-encoded symbol using the main code. */
117 read_huffsym_using_maincode(struct input_bitstream *istream,
118 const struct lzx_tables *tables)
120 return read_huffsym(istream, tables->maincode_decode_table,
121 LZX_MAINCODE_TABLEBITS, LZX_MAX_MAIN_CODEWORD_LEN);
124 /* Read a Huffman-encoded symbol using the length code. */
126 read_huffsym_using_lencode(struct input_bitstream *istream,
127 const struct lzx_tables *tables)
129 return read_huffsym(istream, tables->lencode_decode_table,
130 LZX_LENCODE_TABLEBITS, LZX_MAX_LEN_CODEWORD_LEN);
133 /* Read a Huffman-encoded symbol using the aligned offset code. */
135 read_huffsym_using_alignedcode(struct input_bitstream *istream,
136 const struct lzx_tables *tables)
138 return read_huffsym(istream, tables->alignedcode_decode_table,
139 LZX_ALIGNEDCODE_TABLEBITS, LZX_MAX_ALIGNED_CODEWORD_LEN);
143 * Read the precode from the compressed input bitstream, then use it to decode
144 * @num_lens codeword length values.
147 * The input bitstream.
150 * An array that contains the length values from the previous time the
151 * codeword lengths for this Huffman code were read, or all 0's if this is
155 * Number of length values to decode.
157 * Returns 0 on success, or -1 if the data was invalid.
160 lzx_read_codeword_lens(struct input_bitstream *istream, u8 lens[], unsigned num_lens)
162 /* Declare the decoding table and length table for the precode. */
163 u16 precode_decode_table[(1 << LZX_PRECODE_TABLEBITS) +
164 (LZX_PRECODE_NUM_SYMBOLS * 2)]
165 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
166 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
169 /* Read the lengths of the precode codewords. These are given
171 for (int i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++) {
172 precode_lens[i] = bitstream_read_bits(istream,
173 LZX_PRECODE_ELEMENT_SIZE);
176 /* Make the decoding table for the precode. */
177 ret = make_huffman_decode_table(precode_decode_table,
178 LZX_PRECODE_NUM_SYMBOLS,
179 LZX_PRECODE_TABLEBITS,
181 LZX_MAX_PRE_CODEWORD_LEN);
185 /* Pointer past the last length value that needs to be filled in. */
186 u8 *lens_end = lens + num_lens;
194 /* Decode a symbol from the input.
196 * If the symbol is between 0 and 16, it is the difference from
197 * the old length, modulo 17.
199 * If the symbol is between 17 and 19, it is a special symbol
200 * that indicates that some number of the next lengths are all
201 * 0, or that some number of the next lengths are all equal to
202 * the next symbol. */
204 presym = read_huffsym_using_precode(istream,
205 precode_decode_table);
208 case 17: /* Run of 0's */
209 run_len = 4 + bitstream_read_bits(istream, 4);
212 if (++lens == lens_end)
217 case 18: /* Longer run of 0's */
218 run_len = 20 + bitstream_read_bits(istream, 5);
221 if (++lens == lens_end)
226 case 19: /* Run of identical lengths */
227 run_len = 4 + bitstream_read_bits(istream, 1);
228 presym = read_huffsym_using_precode(istream,
229 precode_decode_table);
230 value = (signed char)*lens - (signed char)presym;
235 if (++lens == lens_end)
240 default: /* Difference from old length */
241 value = (signed char)*lens - (signed char)presym;
245 if (++lens == lens_end)
253 * Read the header of an LZX block and save the block type and size in
254 * *block_type_ret and *block_size_ret, respectively.
256 * If the block is compressed, also update the Huffman decode @tables with the
259 * If the block is uncompressed, also update the match offset @queue with the
262 * Return 0 on success, or -1 if the data was invalid.
265 lzx_read_block_header(struct input_bitstream *istream,
266 unsigned num_main_syms,
267 unsigned window_order,
270 struct lzx_tables *tables,
271 struct lzx_lru_queue *queue)
277 bitstream_ensure_bits(istream, 4);
279 /* The first three bits tell us what kind of block it is, and should be
280 * one of the LZX_BLOCKTYPE_* values. */
281 block_type = bitstream_pop_bits(istream, 3);
283 /* Read the block size. This mirrors the behavior of
284 * lzx_write_compressed_block() in lzx-compress.c; see that for more
286 if (bitstream_pop_bits(istream, 1)) {
287 block_size = LZX_DEFAULT_BLOCK_SIZE;
292 tmp = bitstream_read_bits(istream, 8);
294 tmp = bitstream_read_bits(istream, 8);
298 if (window_order >= 16) {
299 tmp = bitstream_read_bits(istream, 8);
305 switch (block_type) {
307 case LZX_BLOCKTYPE_ALIGNED:
309 /* Read the aligned offset code and prepare its decode table.
312 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
313 tables->alignedcode_lens[i] =
314 bitstream_read_bits(istream,
315 LZX_ALIGNEDCODE_ELEMENT_SIZE);
318 ret = make_huffman_decode_table(tables->alignedcode_decode_table,
319 LZX_ALIGNEDCODE_NUM_SYMBOLS,
320 LZX_ALIGNEDCODE_TABLEBITS,
321 tables->alignedcode_lens,
322 LZX_MAX_ALIGNED_CODEWORD_LEN);
326 /* Fall though, since the rest of the header for aligned offset
327 * blocks is the same as that for verbatim blocks. */
329 case LZX_BLOCKTYPE_VERBATIM:
331 /* Read the main code and prepare its decode table.
333 * Note that the codeword lengths in the main code are encoded
334 * in two parts: one part for literal symbols, and one part for
337 ret = lzx_read_codeword_lens(istream, tables->maincode_lens,
342 ret = lzx_read_codeword_lens(istream,
343 tables->maincode_lens + LZX_NUM_CHARS,
344 num_main_syms - LZX_NUM_CHARS);
348 ret = make_huffman_decode_table(tables->maincode_decode_table,
350 LZX_MAINCODE_TABLEBITS,
351 tables->maincode_lens,
352 LZX_MAX_MAIN_CODEWORD_LEN);
356 /* Read the length code and prepare its decode table. */
358 ret = lzx_read_codeword_lens(istream, tables->lencode_lens,
359 LZX_LENCODE_NUM_SYMBOLS);
363 ret = make_huffman_decode_table(tables->lencode_decode_table,
364 LZX_LENCODE_NUM_SYMBOLS,
365 LZX_LENCODE_TABLEBITS,
366 tables->lencode_lens,
367 LZX_MAX_LEN_CODEWORD_LEN);
373 case LZX_BLOCKTYPE_UNCOMPRESSED:
375 /* Before reading the three LRU match offsets from the
376 * uncompressed block header, the stream must be aligned on a
377 * 16-bit boundary. But, unexpectedly, if the stream is
378 * *already* aligned, the correct thing to do is to throw away
379 * the next 16 bits. */
381 bitstream_ensure_bits(istream, 1);
382 bitstream_align(istream);
383 queue->R[0] = bitstream_read_u32(istream);
384 queue->R[1] = bitstream_read_u32(istream);
385 queue->R[2] = bitstream_read_u32(istream);
387 /* Offsets of 0 are invalid. */
388 if (queue->R[0] == 0 || queue->R[1] == 0 || queue->R[2] == 0)
393 /* Unrecognized block type. */
397 *block_type_ret = block_type;
398 *block_size_ret = block_size;
403 * Decompress an LZX-compressed block of data.
406 * The type of the block (LZX_BLOCKTYPE_VERBATIM or LZX_BLOCKTYPE_ALIGNED).
409 * The size of the block, in bytes.
412 * Pointer to the beginning of the decompression window.
415 * The position in the window at which the block starts.
418 * The Huffman decoding tables for the block.
421 * The least-recently-used queue for match offsets.
424 * The input bitstream, positioned at the start of the block data.
426 * Returns 0 on success, or -1 if the data was invalid.
429 lzx_decompress_block(int block_type, u32 block_size,
430 u8 *window, u32 window_pos,
431 const struct lzx_tables *tables,
432 struct lzx_lru_queue *queue,
433 struct input_bitstream *istream)
435 u8 *window_ptr = &window[window_pos];
436 u8 *window_end = window_ptr + block_size;
439 unsigned position_slot;
441 unsigned num_extra_bits;
443 while (window_ptr != window_end) {
445 mainsym = read_huffsym_using_maincode(istream, tables);
446 if (mainsym < LZX_NUM_CHARS) {
448 *window_ptr++ = mainsym;
454 /* Decode the length header and position slot. */
455 mainsym -= LZX_NUM_CHARS;
456 match_len = mainsym & 0x7;
457 position_slot = mainsym >> 3;
459 /* If needed, read a length symbol to decode the full length. */
460 if (match_len == 0x7)
461 match_len += read_huffsym_using_lencode(istream, tables);
462 match_len += LZX_MIN_MATCH_LEN;
464 if (position_slot <= 2) {
467 /* Note: This isn't a real LRU queue, since using the R2
468 * offset doesn't bump the R1 offset down to R2. This
469 * quirk allows all 3 recent offsets to be handled by
470 * the same code. (For R0, the swap is a no-op.) */
471 match_offset = queue->R[position_slot];
472 queue->R[position_slot] = queue->R[0];
473 queue->R[0] = match_offset;
475 /* Explicit offset */
477 /* Look up the number of extra bits that need to be read
478 * to decode offsets with this position slot. */
479 num_extra_bits = lzx_get_num_extra_bits(position_slot);
481 /* Start with the position slot base value. */
482 match_offset = lzx_position_base[position_slot];
484 /* In aligned offset blocks, the low-order 3 bits of
485 * each offset are encoded using the aligned offset
486 * code. Otherwise, all the extra bits are literal. */
487 if (block_type == LZX_BLOCKTYPE_ALIGNED && num_extra_bits >= 3) {
488 match_offset += bitstream_read_bits(istream, num_extra_bits - 3) << 3;
489 match_offset += read_huffsym_using_alignedcode(istream, tables);
491 match_offset += bitstream_read_bits(istream, num_extra_bits);
494 /* Adjust the offset. */
495 match_offset -= LZX_OFFSET_OFFSET;
497 /* Update the match offset LRU queue. */
498 queue->R[2] = queue->R[1];
499 queue->R[1] = queue->R[0];
500 queue->R[0] = match_offset;
503 /* Validate the match, then copy it to the current position. */
505 if (unlikely(match_len > window_end - window_ptr))
508 if (unlikely(match_offset > window_ptr - window))
511 lz_copy(window_ptr, match_len, match_offset, window_end);
513 window_ptr += match_len;
519 lzx_decompress(const void *compressed_data, size_t compressed_size,
520 void *uncompressed_data, size_t uncompressed_size,
523 struct lzx_decompressor *dec = _dec;
524 struct input_bitstream istream;
525 struct lzx_lru_queue queue;
529 bool may_have_e8_byte;
532 init_input_bitstream(&istream, compressed_data, compressed_size);
534 /* Initialize the recent offsets queue. */
535 lzx_lru_queue_init(&queue);
537 /* Codeword lengths begin as all 0's for delta encoding purposes. */
538 memset(dec->tables.maincode_lens, 0, sizeof(dec->tables.maincode_lens));
539 memset(dec->tables.lencode_lens, 0, sizeof(dec->tables.lencode_lens));
541 /* Set this to true if there may be 0xe8 bytes in the uncompressed data.
543 may_have_e8_byte = false;
545 /* The compressed data will consist of one or more blocks. The
546 * following loop decompresses one block, and it runs until there all
547 * the compressed data has been decompressed, so there are no more
551 window_pos < uncompressed_size;
552 window_pos += block_size)
554 ret = lzx_read_block_header(&istream, dec->num_main_syms,
555 dec->window_order, &block_type,
556 &block_size, &dec->tables, &queue);
560 if (block_size > uncompressed_size - window_pos)
563 if (block_type != LZX_BLOCKTYPE_UNCOMPRESSED) {
565 /* Compressed block. */
567 ret = lzx_decompress_block(block_type,
577 /* If the first 0xe8 byte was in this block, it must
578 * have been encoded as a literal using mainsym 0xe8. */
579 if (dec->tables.maincode_lens[0xe8] != 0)
580 may_have_e8_byte = true;
583 /* Uncompressed block. */
586 p = bitstream_read_bytes(&istream, block_size);
590 memcpy(&((u8*)uncompressed_data)[window_pos], p, block_size);
592 /* Re-align the bitstream if an odd number of bytes was
595 bitstream_read_byte(&istream);
597 may_have_e8_byte = true;
601 /* Postprocess the data unless it cannot possibly contain 0xe8 bytes */
602 if (may_have_e8_byte)
603 lzx_undo_e8_preprocessing(uncompressed_data, uncompressed_size);
609 lzx_free_decompressor(void *_dec)
611 struct lzx_decompressor *dec = _dec;
617 lzx_create_decompressor(size_t max_block_size, void **dec_ret)
619 struct lzx_decompressor *dec;
620 unsigned window_order;
622 window_order = lzx_get_window_order(max_block_size);
623 if (window_order == 0)
624 return WIMLIB_ERR_INVALID_PARAM;
626 /* The aligned allocation is needed to ensure that the lzx_tables are
627 * aligned properly. */
628 dec = ALIGNED_MALLOC(sizeof(struct lzx_decompressor),
629 DECODE_TABLE_ALIGNMENT);
631 return WIMLIB_ERR_NOMEM;
633 dec->window_order = window_order;
634 dec->num_main_syms = lzx_get_num_main_syms(window_order);
640 const struct decompressor_ops lzx_decompressor_ops = {
641 .create_decompressor = lzx_create_decompressor,
642 .decompress = lzx_decompress,
643 .free_decompressor = lzx_free_decompressor,