]> wimlib.net Git - wimlib/blob - include/wimlib/decompress_common.h
20790464f1608d6175480b3a9d026523df3cc2bc
[wimlib] / include / wimlib / decompress_common.h
1 /*
2  * decompress_common.h
3  *
4  * Header for decompression code shared by multiple compression formats.
5  *
6  * The following copying information applies to this specific source code file:
7  *
8  * Written in 2012-2016 by Eric Biggers <ebiggers3@gmail.com>
9  *
10  * To the extent possible under law, the author(s) have dedicated all copyright
11  * and related and neighboring rights to this software to the public domain
12  * worldwide via the Creative Commons Zero 1.0 Universal Public Domain
13  * Dedication (the "CC0").
14  *
15  * This software 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 CC0 for more details.
18  *
19  * You should have received a copy of the CC0 along with this software; if not
20  * see <http://creativecommons.org/publicdomain/zero/1.0/>.
21  */
22
23 #ifndef _WIMLIB_DECOMPRESS_COMMON_H
24 #define _WIMLIB_DECOMPRESS_COMMON_H
25
26 #include <string.h>
27
28 #include "wimlib/compiler.h"
29 #include "wimlib/types.h"
30 #include "wimlib/unaligned.h"
31
32 /* Structure that encapsulates a block of in-memory data being interpreted as a
33  * stream of bits, optionally with interwoven literal bytes.  Bits are assumed
34  * to be stored in little endian 16-bit coding units, with the bits ordered high
35  * to low.  */
36 struct input_bitstream {
37
38         /* Bits that have been read from the input buffer.  The bits are
39          * left-justified; the next bit is always bit 31.  */
40         u32 bitbuf;
41
42         /* Number of bits currently held in @bitbuf.  */
43         u32 bitsleft;
44
45         /* Pointer to the next byte to be retrieved from the input buffer.  */
46         const u8 *next;
47
48         /* Pointer past the end of the input buffer.  */
49         const u8 *end;
50 };
51
52 /* Initialize a bitstream to read from the specified input buffer.  */
53 static inline void
54 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
55 {
56         is->bitbuf = 0;
57         is->bitsleft = 0;
58         is->next = buffer;
59         is->end = is->next + size;
60 }
61
62 /* Note: for performance reasons, the following methods don't return error codes
63  * to the caller if the input buffer is overrun.  Instead, they just assume that
64  * all overrun data is zeroes.  This has no effect on well-formed compressed
65  * data.  The only disadvantage is that bad compressed data may go undetected,
66  * but even this is irrelevant if higher level code checksums the uncompressed
67  * data anyway.  */
68
69 /* Ensure the bit buffer variable for the bitstream contains at least @num_bits
70  * bits.  Following this, bitstream_peek_bits() and/or bitstream_remove_bits()
71  * may be called on the bitstream to peek or remove up to @num_bits bits.  */
72 static inline void
73 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
74 {
75         /* This currently works for at most 17 bits.  */
76
77         if (is->bitsleft >= num_bits)
78                 return;
79
80         if (unlikely(is->end - is->next < 2))
81                 goto overflow;
82
83         is->bitbuf |= (u32)get_unaligned_le16(is->next) << (16 - is->bitsleft);
84         is->next += 2;
85         is->bitsleft += 16;
86
87         if (unlikely(num_bits == 17 && is->bitsleft == 16)) {
88                 if (unlikely(is->end - is->next < 2))
89                         goto overflow;
90
91                 is->bitbuf |= (u32)get_unaligned_le16(is->next);
92                 is->next += 2;
93                 is->bitsleft = 32;
94         }
95
96         return;
97
98 overflow:
99         is->bitsleft = 32;
100 }
101
102 /* Return the next @num_bits bits from the bitstream, without removing them.
103  * There must be at least @num_bits remaining in the buffer variable, from a
104  * previous call to bitstream_ensure_bits().  */
105 static inline u32
106 bitstream_peek_bits(const struct input_bitstream *is, const unsigned num_bits)
107 {
108         return (is->bitbuf >> 1) >> (sizeof(is->bitbuf) * 8 - num_bits - 1);
109 }
110
111 /* Remove @num_bits from the bitstream.  There must be at least @num_bits
112  * remaining in the buffer variable, from a previous call to
113  * bitstream_ensure_bits().  */
114 static inline void
115 bitstream_remove_bits(struct input_bitstream *is, unsigned num_bits)
116 {
117         is->bitbuf <<= num_bits;
118         is->bitsleft -= num_bits;
119 }
120
121 /* Remove and return @num_bits bits from the bitstream.  There must be at least
122  * @num_bits remaining in the buffer variable, from a previous call to
123  * bitstream_ensure_bits().  */
124 static inline u32
125 bitstream_pop_bits(struct input_bitstream *is, unsigned num_bits)
126 {
127         u32 bits = bitstream_peek_bits(is, num_bits);
128         bitstream_remove_bits(is, num_bits);
129         return bits;
130 }
131
132 /* Read and return the next @num_bits bits from the bitstream.  */
133 static inline u32
134 bitstream_read_bits(struct input_bitstream *is, unsigned num_bits)
135 {
136         bitstream_ensure_bits(is, num_bits);
137         return bitstream_pop_bits(is, num_bits);
138 }
139
140 /* Read and return the next literal byte embedded in the bitstream.  */
141 static inline u8
142 bitstream_read_byte(struct input_bitstream *is)
143 {
144         if (unlikely(is->end == is->next))
145                 return 0;
146         return *is->next++;
147 }
148
149 /* Read and return the next 16-bit integer embedded in the bitstream.  */
150 static inline u16
151 bitstream_read_u16(struct input_bitstream *is)
152 {
153         u16 v;
154
155         if (unlikely(is->end - is->next < 2))
156                 return 0;
157         v = get_unaligned_le16(is->next);
158         is->next += 2;
159         return v;
160 }
161
162 /* Read and return the next 32-bit integer embedded in the bitstream.  */
163 static inline u32
164 bitstream_read_u32(struct input_bitstream *is)
165 {
166         u32 v;
167
168         if (unlikely(is->end - is->next < 4))
169                 return 0;
170         v = get_unaligned_le32(is->next);
171         is->next += 4;
172         return v;
173 }
174
175 /* Read into @dst_buffer an array of literal bytes embedded in the bitstream.
176  * Return 0 if there were enough bytes remaining in the input, otherwise -1. */
177 static inline int
178 bitstream_read_bytes(struct input_bitstream *is, void *dst_buffer, size_t count)
179 {
180         if (unlikely(is->end - is->next < count))
181                 return -1;
182         memcpy(dst_buffer, is->next, count);
183         is->next += count;
184         return 0;
185 }
186
187 /* Align the input bitstream on a coding-unit boundary.  */
188 static inline void
189 bitstream_align(struct input_bitstream *is)
190 {
191         is->bitsleft = 0;
192         is->bitbuf = 0;
193 }
194
195 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
196  *
197  * Reason: We may fill the entries with SSE instructions without worrying
198  * about dealing with the unaligned case.  */
199 #define DECODE_TABLE_ALIGNMENT 16
200
201 #define DECODE_TABLE_SYMBOL_SHIFT 4
202 #define DECODE_TABLE_LENGTH_MASK DECODE_TABLE_MAX_LENGTH
203
204 #define DECODE_TABLE_MAX_NUM_SYMS ((1 << (16 - DECODE_TABLE_SYMBOL_SHIFT)) - 1)
205 #define DECODE_TABLE_MAX_LENGTH ((1 << DECODE_TABLE_SYMBOL_SHIFT) - 1)
206
207 /*
208  * Reads and returns the next Huffman-encoded symbol from a bitstream.
209  *
210  * If the input data is exhausted, the Huffman symbol is decoded as if the
211  * missing bits are all zeroes.
212  *
213  * XXX: This is mostly duplicated in lzms_decode_huffman_symbol() in
214  * lzms_decompress.c.
215  */
216 static inline unsigned
217 read_huffsym(struct input_bitstream *is, const u16 decode_table[],
218              unsigned table_bits, unsigned max_codeword_len)
219 {
220         unsigned entry;
221         unsigned sym;
222         unsigned len;
223
224         /* If the bitbuffer contains fewer bits than might be required by a
225          * single codeword, then refill it. */
226         bitstream_ensure_bits(is, max_codeword_len);
227
228         /* Index the root table by the next 'table_bits' bits of input. */
229         entry = decode_table[bitstream_peek_bits(is, table_bits)];
230
231         /* Extract the symbol and length from the entry. */
232         sym = entry >> DECODE_TABLE_SYMBOL_SHIFT;
233         len = entry & DECODE_TABLE_LENGTH_MASK;
234
235         /* If the root table is indexed by the full 'max_codeword_len' bits,
236          * then there cannot be any subtables.  This will be known at compile
237          * time.  Otherwise, we must check whether the decoded symbol is really
238          * a subtable pointer.  If so, we must discard the bits with which the
239          * root table was indexed, then index the subtable by the next 'len'
240          * bits of input to get the real entry. */
241         if (max_codeword_len > table_bits &&
242             entry >= (1U << (table_bits + DECODE_TABLE_SYMBOL_SHIFT)))
243         {
244                 /* Subtable required */
245                 bitstream_remove_bits(is, table_bits);
246                 entry = decode_table[sym + bitstream_peek_bits(is, len)];
247                 sym = entry >> DECODE_TABLE_SYMBOL_SHIFT;;
248                 len = entry & DECODE_TABLE_LENGTH_MASK;
249         }
250
251         /* Discard the bits (or the remaining bits, if a subtable was required)
252          * of the codeword. */
253         bitstream_remove_bits(is, len);
254
255         /* Return the decoded symbol. */
256         return sym;
257 }
258
259 /*
260  * The ENOUGH() macro returns the maximum number of decode table entries,
261  * including all subtable entries, that may be required for decoding a given
262  * Huffman code.  This depends on three parameters:
263  *
264  *      num_syms: the maximum number of symbols in the code
265  *      table_bits: the number of bits with which the root table will be indexed
266  *      max_codeword_len: the maximum allowed codeword length
267  *
268  * Given these parameters, the utility program 'enough' from zlib, when run as
269  * './enough num_syms table_bits max_codeword_len', will compute the maximum
270  * number of entries required.  This has already been done for the combinations
271  * we need (or may need) and incorporated into the macro below so that the
272  * mapping can be done at compilation time.  If an unknown combination is used,
273  * then a compilation error will result.  To fix this, use 'enough' to find the
274  * missing value and add it below.
275  */
276 #define ENOUGH(num_syms, table_bits, max_codeword_len) ( \
277         ((num_syms) == 8 && (table_bits) == 7 && (max_codeword_len) == 15) ? 128 : \
278         ((num_syms) == 8 && (table_bits) == 5 && (max_codeword_len) == 7) ? 36 : \
279         ((num_syms) == 8 && (table_bits) == 6 && (max_codeword_len) == 7) ? 66 : \
280         ((num_syms) == 8 && (table_bits) == 7 && (max_codeword_len) == 7) ? 128 : \
281         ((num_syms) == 20 && (table_bits) == 5 && (max_codeword_len) == 15) ? 1062 : \
282         ((num_syms) == 20 && (table_bits) == 6 && (max_codeword_len) == 15) ? 582 : \
283         ((num_syms) == 20 && (table_bits) == 7 && (max_codeword_len) == 15) ? 390 : \
284         ((num_syms) == 54 && (table_bits) == 9 && (max_codeword_len) == 15) ? 618 : \
285         ((num_syms) == 54 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1098 : \
286         ((num_syms) == 249 && (table_bits) == 9 && (max_codeword_len) == 16) ? 878 : \
287         ((num_syms) == 249 && (table_bits) == 10 && (max_codeword_len) == 16) ? 1326 : \
288         ((num_syms) == 249 && (table_bits) == 11 && (max_codeword_len) == 16) ? 2318 : \
289         ((num_syms) == 256 && (table_bits) == 9 && (max_codeword_len) == 15) ? 822 : \
290         ((num_syms) == 256 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1302 : \
291         ((num_syms) == 256 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2310 : \
292         ((num_syms) == 512 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1558 : \
293         ((num_syms) == 512 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2566 : \
294         ((num_syms) == 512 && (table_bits) == 12 && (max_codeword_len) == 15) ? 4606 : \
295         ((num_syms) == 656 && (table_bits) == 10 && (max_codeword_len) == 16) ? 1734 : \
296         ((num_syms) == 656 && (table_bits) == 11 && (max_codeword_len) == 16) ? 2726 : \
297         ((num_syms) == 656 && (table_bits) == 12 && (max_codeword_len) == 16) ? 4758 : \
298         ((num_syms) == 799 && (table_bits) == 9 && (max_codeword_len) == 15) ? 1366 : \
299         ((num_syms) == 799 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1846 : \
300         ((num_syms) == 799 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2854 : \
301         -1)
302
303 /* Wrapper around ENOUGH() that does additional compile-time validation. */
304 #define DECODE_TABLE_LENGTH(num_syms, table_bits, max_codeword_len) (   \
305                                                                         \
306         /* Every possible symbol value must fit into the symbol portion \
307          * of a decode table entry. */                                  \
308         STATIC_ASSERT_ZERO((num_syms) <= DECODE_TABLE_MAX_NUM_SYMS) +   \
309                                                                         \
310         /* There cannot be more symbols than possible codewords. */     \
311         STATIC_ASSERT_ZERO((num_syms) <= 1U << (max_codeword_len)) +    \
312                                                                         \
313         /* It doesn't make sense to use a table_bits more than the      \
314          * maximum codeword length. */                                  \
315         STATIC_ASSERT_ZERO((max_codeword_len) >= (table_bits)) +        \
316                                                                         \
317         /* The maximum length in the root table must fit into the       \
318          * length portion of a decode table entry. */                   \
319         STATIC_ASSERT_ZERO((table_bits) <= DECODE_TABLE_MAX_LENGTH) +   \
320                                                                         \
321         /* The maximum length in a subtable must fit into the length
322          * portion of a decode table entry. */                          \
323         STATIC_ASSERT_ZERO((max_codeword_len) - (table_bits) <=         \
324                                         DECODE_TABLE_MAX_LENGTH) +      \
325                                                                         \
326         /* The needed 'enough' value must have been defined. */         \
327         STATIC_ASSERT_ZERO(ENOUGH((num_syms), (table_bits),             \
328                                   (max_codeword_len)) >= 0) +           \
329                                                                         \
330         /* The maximum subtable index must fit in the field which would \
331          * normally hold a symbol value. */                             \
332         STATIC_ASSERT_ZERO(ENOUGH((num_syms), (table_bits),             \
333                                   (max_codeword_len)) <=                \
334                                         DECODE_TABLE_MAX_NUM_SYMS) +    \
335                                                                         \
336         /* The minimum subtable index must be greater than the greatest \
337          * possible symbol value. */                                    \
338         STATIC_ASSERT_ZERO((1U << table_bits) >= num_syms) +            \
339                                                                         \
340         ENOUGH(num_syms, table_bits, max_codeword_len)                  \
341 )
342
343 /*
344  * Declare the decode table for a Huffman code, given several compile-time
345  * constants that describe that code (see ENOUGH() for details).
346  *
347  * Decode tables must be aligned to a DECODE_TABLE_ALIGNMENT-boundary.  This
348  * implies that if a decode table is nested a dynamically allocated structure,
349  * then the outer structure must be allocated on a DECODE_TABLE_ALIGNMENT-byte
350  * boundary as well.
351  */
352 #define DECODE_TABLE(name, num_syms, table_bits, max_codeword_len) \
353         u16 name[DECODE_TABLE_LENGTH((num_syms), (table_bits), \
354                                      (max_codeword_len))] \
355                 _aligned_attribute(DECODE_TABLE_ALIGNMENT)
356
357 extern int
358 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
359                           unsigned table_bits, const u8 lens[],
360                           unsigned max_codeword_len);
361
362 static inline void
363 copy_word_unaligned(const void *src, void *dst)
364 {
365         store_word_unaligned(load_word_unaligned(src), dst);
366 }
367
368 static inline machine_word_t
369 repeat_u16(u16 b)
370 {
371         machine_word_t v = b;
372
373         STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
374         v |= v << 16;
375         v |= v << ((WORDBITS == 64) ? 32 : 0);
376         return v;
377 }
378
379 static inline machine_word_t
380 repeat_u8(u8 b)
381 {
382         return repeat_u16(((u16)b << 8) | b);
383 }
384
385 /*
386  * Copy an LZ77 match at (dst - offset) to dst.
387  *
388  * The length and offset must be already validated --- that is, (dst - offset)
389  * can't underrun the output buffer, and (dst + length) can't overrun the output
390  * buffer.  Also, the length cannot be 0.
391  *
392  * @winend points to the byte past the end of the output buffer.
393  * This function won't write any data beyond this position.
394  */
395 static inline void
396 lz_copy(u8 *dst, u32 length, u32 offset, const u8 *winend, u32 min_length)
397 {
398         const u8 *src = dst - offset;
399         const u8 * const end = dst + length;
400
401         /*
402          * Try to copy one machine word at a time.  On i386 and x86_64 this is
403          * faster than copying one byte at a time, unless the data is
404          * near-random and all the matches have very short lengths.  Note that
405          * since this requires unaligned memory accesses, it won't necessarily
406          * be faster on every architecture.
407          *
408          * Also note that we might copy more than the length of the match.  For
409          * example, if a word is 8 bytes and the match is of length 5, then
410          * we'll simply copy 8 bytes.  This is okay as long as we don't write
411          * beyond the end of the output buffer, hence the check for (winend -
412          * end >= WORDBYTES - 1).
413          */
414         if (UNALIGNED_ACCESS_IS_FAST && likely(winend - end >= WORDBYTES - 1)) {
415
416                 if (offset >= WORDBYTES) {
417                         /* The source and destination words don't overlap.  */
418
419                         /* To improve branch prediction, one iteration of this
420                          * loop is unrolled.  Most matches are short and will
421                          * fail the first check.  But if that check passes, then
422                          * it becomes increasing likely that the match is long
423                          * and we'll need to continue copying.  */
424
425                         copy_word_unaligned(src, dst);
426                         src += WORDBYTES;
427                         dst += WORDBYTES;
428
429                         if (dst < end) {
430                                 do {
431                                         copy_word_unaligned(src, dst);
432                                         src += WORDBYTES;
433                                         dst += WORDBYTES;
434                                 } while (dst < end);
435                         }
436                         return;
437                 } else if (offset == 1) {
438
439                         /* Offset 1 matches are equivalent to run-length
440                          * encoding of the previous byte.  This case is common
441                          * if the data contains many repeated bytes.  */
442
443                         machine_word_t v = repeat_u8(*(dst - 1));
444                         do {
445                                 store_word_unaligned(v, dst);
446                                 src += WORDBYTES;
447                                 dst += WORDBYTES;
448                         } while (dst < end);
449                         return;
450                 }
451                 /*
452                  * We don't bother with special cases for other 'offset <
453                  * WORDBYTES', which are usually rarer than 'offset == 1'.
454                  * Extra checks will just slow things down.  Actually, it's
455                  * possible to handle all the 'offset < WORDBYTES' cases using
456                  * the same code, but it still becomes more complicated doesn't
457                  * seem any faster overall; it definitely slows down the more
458                  * common 'offset == 1' case.
459                  */
460         }
461
462         /* Fall back to a bytewise copy.  */
463
464         if (min_length >= 2) {
465                 *dst++ = *src++;
466                 length--;
467         }
468         if (min_length >= 3) {
469                 *dst++ = *src++;
470                 length--;
471         }
472         if (min_length >= 4) {
473                 *dst++ = *src++;
474                 length--;
475         }
476         do {
477                 *dst++ = *src++;
478         } while (--length);
479 }
480
481 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */