4 * Header for decompression code shared by multiple compression formats.
6 * Copyright 2022 Eric Biggers
8 * Permission is hereby granted, free of charge, to any person
9 * obtaining a copy of this software and associated documentation
10 * files (the "Software"), to deal in the Software without
11 * restriction, including without limitation the rights to use,
12 * copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the
14 * Software is furnished to do so, subject to the following
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
22 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
24 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
25 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27 * OTHER DEALINGS IN THE SOFTWARE.
30 #ifndef _WIMLIB_DECOMPRESS_COMMON_H
31 #define _WIMLIB_DECOMPRESS_COMMON_H
35 #include "wimlib/compiler.h"
36 #include "wimlib/types.h"
37 #include "wimlib/unaligned.h"
39 /******************************************************************************/
40 /* Input bitstream for XPRESS and LZX */
41 /*----------------------------------------------------------------------------*/
43 /* Structure that encapsulates a block of in-memory data being interpreted as a
44 * stream of bits, optionally with interwoven literal bytes. Bits are assumed
45 * to be stored in little endian 16-bit coding units, with the bits ordered high
47 struct input_bitstream {
49 /* Bits that have been read from the input buffer. The bits are
50 * left-justified; the next bit is always bit 31. */
53 /* Number of bits currently held in @bitbuf. */
56 /* Pointer to the next byte to be retrieved from the input buffer. */
59 /* Pointer past the end of the input buffer. */
63 /* Initialize a bitstream to read from the specified input buffer. */
64 static forceinline void
65 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
70 is->end = is->next + size;
73 /* Note: for performance reasons, the following methods don't return error codes
74 * to the caller if the input buffer is overrun. Instead, they just assume that
75 * all overrun data is zeroes. This has no effect on well-formed compressed
76 * data. The only disadvantage is that bad compressed data may go undetected,
77 * but even this is irrelevant if higher level code checksums the uncompressed
80 /* Ensure the bit buffer variable for the bitstream contains at least @num_bits
81 * bits. Following this, bitstream_peek_bits() and/or bitstream_remove_bits()
82 * may be called on the bitstream to peek or remove up to @num_bits bits. */
83 static forceinline void
84 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
86 /* This currently works for at most 17 bits. */
88 if (is->bitsleft >= num_bits)
91 if (unlikely(is->end - is->next < 2))
94 is->bitbuf |= (u32)get_unaligned_le16(is->next) << (16 - is->bitsleft);
98 if (unlikely(num_bits == 17 && is->bitsleft == 16)) {
99 if (unlikely(is->end - is->next < 2))
102 is->bitbuf |= (u32)get_unaligned_le16(is->next);
113 /* Return the next @num_bits bits from the bitstream, without removing them.
114 * There must be at least @num_bits remaining in the buffer variable, from a
115 * previous call to bitstream_ensure_bits(). */
116 static forceinline u32
117 bitstream_peek_bits(const struct input_bitstream *is, const unsigned num_bits)
119 return (is->bitbuf >> 1) >> (sizeof(is->bitbuf) * 8 - num_bits - 1);
122 /* Remove @num_bits from the bitstream. There must be at least @num_bits
123 * remaining in the buffer variable, from a previous call to
124 * bitstream_ensure_bits(). */
125 static forceinline void
126 bitstream_remove_bits(struct input_bitstream *is, unsigned num_bits)
128 is->bitbuf <<= num_bits;
129 is->bitsleft -= num_bits;
132 /* Remove and return @num_bits bits from the bitstream. There must be at least
133 * @num_bits remaining in the buffer variable, from a previous call to
134 * bitstream_ensure_bits(). */
135 static forceinline u32
136 bitstream_pop_bits(struct input_bitstream *is, unsigned num_bits)
138 u32 bits = bitstream_peek_bits(is, num_bits);
139 bitstream_remove_bits(is, num_bits);
143 /* Read and return the next @num_bits bits from the bitstream. */
144 static forceinline u32
145 bitstream_read_bits(struct input_bitstream *is, unsigned num_bits)
147 bitstream_ensure_bits(is, num_bits);
148 return bitstream_pop_bits(is, num_bits);
151 /* Read and return the next literal byte embedded in the bitstream. */
152 static forceinline u8
153 bitstream_read_byte(struct input_bitstream *is)
155 if (unlikely(is->end == is->next))
160 /* Read and return the next 16-bit integer embedded in the bitstream. */
161 static forceinline u16
162 bitstream_read_u16(struct input_bitstream *is)
166 if (unlikely(is->end - is->next < 2))
168 v = get_unaligned_le16(is->next);
173 /* Read and return the next 32-bit integer embedded in the bitstream. */
174 static forceinline u32
175 bitstream_read_u32(struct input_bitstream *is)
179 if (unlikely(is->end - is->next < 4))
181 v = get_unaligned_le32(is->next);
186 /* Read into @dst_buffer an array of literal bytes embedded in the bitstream.
187 * Return 0 if there were enough bytes remaining in the input, otherwise -1. */
188 static forceinline int
189 bitstream_read_bytes(struct input_bitstream *is, void *dst_buffer, size_t count)
191 if (unlikely(is->end - is->next < count))
193 memcpy(dst_buffer, is->next, count);
198 /* Align the input bitstream on a coding-unit boundary. */
199 static forceinline void
200 bitstream_align(struct input_bitstream *is)
206 /******************************************************************************/
207 /* Huffman decoding */
208 /*----------------------------------------------------------------------------*/
211 * Required alignment for the Huffman decode tables. We require this alignment
212 * so that we can fill the entries with vector or word instructions and not have
213 * to deal with misaligned buffers.
215 #define DECODE_TABLE_ALIGNMENT 16
218 * Each decode table entry is 16 bits divided into two fields: 'symbol' (high 12
219 * bits) and 'length' (low 4 bits). The precise meaning of these fields depends
220 * on the type of entry:
222 * Root table entries which are *not* subtable pointers:
223 * symbol: symbol to decode
224 * length: codeword length in bits
226 * Root table entries which are subtable pointers:
227 * symbol: index of start of subtable
228 * length: number of bits with which the subtable is indexed
231 * symbol: symbol to decode
232 * length: codeword length in bits, minus the number of bits with which the
233 * root table is indexed
235 #define DECODE_TABLE_SYMBOL_SHIFT 4
236 #define DECODE_TABLE_MAX_SYMBOL ((1 << (16 - DECODE_TABLE_SYMBOL_SHIFT)) - 1)
237 #define DECODE_TABLE_MAX_LENGTH ((1 << DECODE_TABLE_SYMBOL_SHIFT) - 1)
238 #define DECODE_TABLE_LENGTH_MASK DECODE_TABLE_MAX_LENGTH
239 #define MAKE_DECODE_TABLE_ENTRY(symbol, length) \
240 (((symbol) << DECODE_TABLE_SYMBOL_SHIFT) | (length))
243 * Read and return the next Huffman-encoded symbol from the given bitstream
244 * using the given decode table.
246 * If the input data is exhausted, then the Huffman symbol will be decoded as if
247 * the missing bits were all zeroes.
249 * XXX: This is mostly duplicated in lzms_decode_huffman_symbol() in
250 * lzms_decompress.c; keep them in sync!
252 static forceinline unsigned
253 read_huffsym(struct input_bitstream *is, const u16 decode_table[],
254 unsigned table_bits, unsigned max_codeword_len)
260 /* Preload the bitbuffer with 'max_codeword_len' bits so that we're
261 * guaranteed to be able to fully decode a codeword. */
262 bitstream_ensure_bits(is, max_codeword_len);
264 /* Index the root table by the next 'table_bits' bits of input. */
265 entry = decode_table[bitstream_peek_bits(is, table_bits)];
267 /* Extract the "symbol" and "length" from the entry. */
268 symbol = entry >> DECODE_TABLE_SYMBOL_SHIFT;
269 length = entry & DECODE_TABLE_LENGTH_MASK;
271 /* If the root table is indexed by the full 'max_codeword_len' bits,
272 * then there cannot be any subtables, and this will be known at compile
273 * time. Otherwise, we must check whether the decoded symbol is really
274 * a subtable pointer. If so, we must discard the bits with which the
275 * root table was indexed, then index the subtable by the next 'length'
276 * bits of input to get the real entry. */
277 if (max_codeword_len > table_bits &&
278 entry >= (1U << (table_bits + DECODE_TABLE_SYMBOL_SHIFT)))
280 /* Subtable required */
281 bitstream_remove_bits(is, table_bits);
282 entry = decode_table[symbol + bitstream_peek_bits(is, length)];
283 symbol = entry >> DECODE_TABLE_SYMBOL_SHIFT;
284 length = entry & DECODE_TABLE_LENGTH_MASK;
287 /* Discard the bits (or the remaining bits, if a subtable was required)
288 * of the codeword. */
289 bitstream_remove_bits(is, length);
291 /* Return the decoded symbol. */
296 * The DECODE_TABLE_ENOUGH() macro evaluates to the maximum number of decode
297 * table entries, including all subtable entries, that may be required for
298 * decoding a given Huffman code. This depends on three parameters:
300 * num_syms: the maximum number of symbols in the code
301 * table_bits: the number of bits with which the root table will be indexed
302 * max_codeword_len: the maximum allowed codeword length in the code
304 * Given these parameters, the utility program 'enough' from zlib, when passed
305 * the three arguments 'num_syms', 'table_bits', and 'max_codeword_len', will
306 * compute the maximum number of entries required. This has already been done
307 * for the combinations we need and incorporated into the macro below so that
308 * the mapping can be done at compilation time. If an unknown combination is
309 * used, then a compilation error will result. To fix this, use 'enough' to
310 * find the missing value and add it below. If that still doesn't fix the
311 * compilation error, then most likely a constraint would be violated by the
312 * requested parameters, so they cannot be used, at least without other changes
313 * to the decode table --- see DECODE_TABLE_SIZE().
315 #define DECODE_TABLE_ENOUGH(num_syms, table_bits, max_codeword_len) ( \
316 ((num_syms) == 8 && (table_bits) == 7 && (max_codeword_len) == 15) ? 128 : \
317 ((num_syms) == 8 && (table_bits) == 5 && (max_codeword_len) == 7) ? 36 : \
318 ((num_syms) == 8 && (table_bits) == 6 && (max_codeword_len) == 7) ? 66 : \
319 ((num_syms) == 8 && (table_bits) == 7 && (max_codeword_len) == 7) ? 128 : \
320 ((num_syms) == 20 && (table_bits) == 5 && (max_codeword_len) == 15) ? 1062 : \
321 ((num_syms) == 20 && (table_bits) == 6 && (max_codeword_len) == 15) ? 582 : \
322 ((num_syms) == 20 && (table_bits) == 7 && (max_codeword_len) == 15) ? 390 : \
323 ((num_syms) == 54 && (table_bits) == 9 && (max_codeword_len) == 15) ? 618 : \
324 ((num_syms) == 54 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1098 : \
325 ((num_syms) == 249 && (table_bits) == 9 && (max_codeword_len) == 16) ? 878 : \
326 ((num_syms) == 249 && (table_bits) == 10 && (max_codeword_len) == 16) ? 1326 : \
327 ((num_syms) == 249 && (table_bits) == 11 && (max_codeword_len) == 16) ? 2318 : \
328 ((num_syms) == 256 && (table_bits) == 9 && (max_codeword_len) == 15) ? 822 : \
329 ((num_syms) == 256 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1302 : \
330 ((num_syms) == 256 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2310 : \
331 ((num_syms) == 512 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1558 : \
332 ((num_syms) == 512 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2566 : \
333 ((num_syms) == 512 && (table_bits) == 12 && (max_codeword_len) == 15) ? 4606 : \
334 ((num_syms) == 656 && (table_bits) == 10 && (max_codeword_len) == 16) ? 1734 : \
335 ((num_syms) == 656 && (table_bits) == 11 && (max_codeword_len) == 16) ? 2726 : \
336 ((num_syms) == 656 && (table_bits) == 12 && (max_codeword_len) == 16) ? 4758 : \
337 ((num_syms) == 799 && (table_bits) == 9 && (max_codeword_len) == 15) ? 1366 : \
338 ((num_syms) == 799 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1846 : \
339 ((num_syms) == 799 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2854 : \
342 /* Wrapper around DECODE_TABLE_ENOUGH() that does additional compile-time
344 #define DECODE_TABLE_SIZE(num_syms, table_bits, max_codeword_len) ( \
346 /* All values must be positive. */ \
347 STATIC_ASSERT_ZERO((num_syms) > 0) + \
348 STATIC_ASSERT_ZERO((table_bits) > 0) + \
349 STATIC_ASSERT_ZERO((max_codeword_len) > 0) + \
351 /* There cannot be more symbols than possible codewords. */ \
352 STATIC_ASSERT_ZERO((num_syms) <= 1U << (max_codeword_len)) + \
354 /* There is no reason for the root table to be indexed with
355 * more bits than the maximum codeword length. */ \
356 STATIC_ASSERT_ZERO((table_bits) <= (max_codeword_len)) + \
358 /* The maximum symbol value must fit in the 'symbol' field. */ \
359 STATIC_ASSERT_ZERO((num_syms) - 1 <= DECODE_TABLE_MAX_SYMBOL) + \
361 /* The maximum codeword length in the root table must fit in
362 * the 'length' field. */ \
363 STATIC_ASSERT_ZERO((table_bits) <= DECODE_TABLE_MAX_LENGTH) + \
365 /* The maximum codeword length in a subtable must fit in the
366 * 'length' field. */ \
367 STATIC_ASSERT_ZERO((max_codeword_len) - (table_bits) <= \
368 DECODE_TABLE_MAX_LENGTH) + \
370 /* The minimum subtable index must be greater than the maximum
371 * symbol value. If this were not the case, then there would
372 * be no way to tell whether a given root table entry is a
373 * "subtable pointer" or not. (An alternate solution would be
374 * to reserve a flag bit specifically for this purpose.) */ \
375 STATIC_ASSERT_ZERO((1U << table_bits) > (num_syms) - 1) + \
377 /* The needed 'enough' value must have been defined. */ \
378 STATIC_ASSERT_ZERO(DECODE_TABLE_ENOUGH( \
379 (num_syms), (table_bits), \
380 (max_codeword_len)) > 0) + \
382 /* The maximum subtable index must fit in the 'symbol' field. */\
383 STATIC_ASSERT_ZERO(DECODE_TABLE_ENOUGH( \
384 (num_syms), (table_bits), \
385 (max_codeword_len)) - 1 <= \
386 DECODE_TABLE_MAX_SYMBOL) + \
388 /* Finally, make the macro evaluate to the needed maximum
389 * number of decode table entries. */ \
390 DECODE_TABLE_ENOUGH((num_syms), (table_bits), \
391 (max_codeword_len)) \
395 * Declare the decode table for a Huffman code, given several compile-time
396 * constants that describe the code. See DECODE_TABLE_ENOUGH() for details.
398 * Decode tables must be aligned to a DECODE_TABLE_ALIGNMENT-byte boundary.
399 * This implies that if a decode table is nested inside a dynamically allocated
400 * structure, then the outer structure must be allocated on a
401 * DECODE_TABLE_ALIGNMENT-byte aligned boundary as well.
403 #define DECODE_TABLE(name, num_syms, table_bits, max_codeword_len) \
404 u16 name[DECODE_TABLE_SIZE((num_syms), (table_bits), \
405 (max_codeword_len))] \
406 _aligned_attribute(DECODE_TABLE_ALIGNMENT)
409 * Declare the temporary "working_space" array needed for building the decode
410 * table for a Huffman code.
412 #define DECODE_TABLE_WORKING_SPACE(name, num_syms, max_codeword_len) \
413 u16 name[2 * ((max_codeword_len) + 1) + (num_syms)];
416 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
417 unsigned table_bits, const u8 lens[],
418 unsigned max_codeword_len, u16 working_space[]);
420 /******************************************************************************/
421 /* LZ match copying */
422 /*----------------------------------------------------------------------------*/
424 static forceinline void
425 copy_word_unaligned(const void *src, void *dst)
427 store_word_unaligned(load_word_unaligned(src), dst);
430 static forceinline machine_word_t
433 machine_word_t v = b;
435 STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
437 v |= v << ((WORDBITS == 64) ? 32 : 0);
441 static forceinline machine_word_t
444 return repeat_u16(((u16)b << 8) | b);
448 * Copy an LZ77 match of 'length' bytes from the match source at 'out_next -
449 * offset' to the match destination at 'out_next'. The source and destination
452 * This handles validating the length and offset. It is validated that the
453 * beginning of the match source is '>= out_begin' and that end of the match
454 * destination is '<= out_end'. The return value is 0 if the match was valid
455 * (and was copied), otherwise -1.
457 * 'min_length' is a hint which specifies the minimum possible match length.
458 * This should be a compile-time constant.
460 static forceinline int
461 lz_copy(u32 length, u32 offset, u8 *out_begin, u8 *out_next, u8 *out_end,
467 /* Validate the offset. */
468 if (unlikely(offset > out_next - out_begin))
472 * Fast path: copy a match which is no longer than a few words, is not
473 * overlapped such that copying a word at a time would produce incorrect
474 * results, and is not too close to the end of the buffer. Note that
475 * this might copy more than the length of the match, but that's okay in
478 src = out_next - offset;
479 if (UNALIGNED_ACCESS_IS_FAST && length <= 3 * WORDBYTES &&
480 offset >= WORDBYTES && out_end - out_next >= 3 * WORDBYTES)
482 copy_word_unaligned(src + WORDBYTES*0, out_next + WORDBYTES*0);
483 copy_word_unaligned(src + WORDBYTES*1, out_next + WORDBYTES*1);
484 copy_word_unaligned(src + WORDBYTES*2, out_next + WORDBYTES*2);
488 /* Validate the length. This isn't needed in the fast path above, due
489 * to the additional conditions tested, but we do need it here. */
490 if (unlikely(length > out_end - out_next))
492 end = out_next + length;
495 * Try to copy one word at a time. On i386 and x86_64 this is faster
496 * than copying one byte at a time, unless the data is near-random and
497 * all the matches have very short lengths. Note that since this
498 * requires unaligned memory accesses, it won't necessarily be faster on
499 * every architecture.
501 * Also note that we might copy more than the length of the match. For
502 * example, if a word is 8 bytes and the match is of length 5, then
503 * we'll simply copy 8 bytes. This is okay as long as we don't write
504 * beyond the end of the output buffer, hence the check for (out_end -
505 * end >= WORDBYTES - 1).
507 if (UNALIGNED_ACCESS_IS_FAST && likely(out_end - end >= WORDBYTES - 1))
509 if (offset >= WORDBYTES) {
510 /* The source and destination words don't overlap. */
512 copy_word_unaligned(src, out_next);
514 out_next += WORDBYTES;
515 } while (out_next < end);
517 } else if (offset == 1) {
518 /* Offset 1 matches are equivalent to run-length
519 * encoding of the previous byte. This case is common
520 * if the data contains many repeated bytes. */
521 machine_word_t v = repeat_byte(*(out_next - 1));
523 store_word_unaligned(v, out_next);
525 out_next += WORDBYTES;
526 } while (out_next < end);
530 * We don't bother with special cases for other 'offset <
531 * WORDBYTES', which are usually rarer than 'offset == 1'.
532 * Extra checks will just slow things down. Actually, it's
533 * possible to handle all the 'offset < WORDBYTES' cases using
534 * the same code, but it still becomes more complicated doesn't
535 * seem any faster overall; it definitely slows down the more
536 * common 'offset == 1' case.
540 /* Fall back to a bytewise copy. */
542 *out_next++ = *src++;
544 *out_next++ = *src++;
546 *out_next++ = *src++;
548 *out_next++ = *src++;
549 } while (out_next != end);
553 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */