]> wimlib.net Git - wimlib/blob - include/wimlib/decompress_common.h
Remove support for --enable-more-assertions configure option
[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 author dedicates this file to the public domain.
7  * You can do whatever you want with this file.
8  */
9
10 #ifndef _WIMLIB_DECOMPRESS_COMMON_H
11 #define _WIMLIB_DECOMPRESS_COMMON_H
12
13 #include "wimlib/assert.h"
14 #include "wimlib/compiler.h"
15 #include "wimlib/endianness.h"
16 #include "wimlib/types.h"
17 #include "wimlib/unaligned.h"
18
19 /* Structure that encapsulates a block of in-memory data being interpreted as a
20  * stream of bits, optionally with interwoven literal bytes.  Bits are assumed
21  * to be stored in little endian 16-bit coding units, with the bits ordered high
22  * to low.  */
23 struct input_bitstream {
24
25         /* Bits that have been read from the input buffer.  The bits are
26          * left-justified; the next bit is always bit 31.  */
27         u32 bitbuf;
28
29         /* Number of bits currently held in @bitbuf.  */
30         u32 bitsleft;
31
32         /* Pointer to the next byte to be retrieved from the input buffer.  */
33         const u8 *next;
34
35         /* Pointer past the end of the input buffer.  */
36         const u8 *end;
37 };
38
39 /* Initialize a bitstream to read from the specified input buffer.  */
40 static inline void
41 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
42 {
43         is->bitbuf = 0;
44         is->bitsleft = 0;
45         is->next = buffer;
46         is->end = is->next + size;
47 }
48
49 /* Note: for performance reasons, the following methods don't return error codes
50  * to the caller if the input buffer is overrun.  Instead, they just assume that
51  * all overrun data is zeroes.  This has no effect on well-formed compressed
52  * data.  The only disadvantage is that bad compressed data may go undetected,
53  * but even this is irrelevant if higher level code checksums the uncompressed
54  * data anyway.  */
55
56 /* Ensure the bit buffer variable for the bitstream contains at least @num_bits
57  * bits.  Following this, bitstream_peek_bits() and/or bitstream_remove_bits()
58  * may be called on the bitstream to peek or remove up to @num_bits bits.  */
59 static inline void
60 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
61 {
62         /* This currently works for at most 17 bits.  */
63
64         if (is->bitsleft >= num_bits)
65                 return;
66
67         if (unlikely(is->end - is->next < 2))
68                 goto overflow;
69
70         is->bitbuf |= (u32)get_unaligned_u16_le(is->next) << (16 - is->bitsleft);
71         is->next += 2;
72         is->bitsleft += 16;
73
74         if (unlikely(num_bits == 17 && is->bitsleft == 16)) {
75                 if (unlikely(is->end - is->next < 2))
76                         goto overflow;
77
78                 is->bitbuf |= (u32)get_unaligned_u16_le(is->next);
79                 is->next += 2;
80                 is->bitsleft = 32;
81         }
82
83         return;
84
85 overflow:
86         is->bitsleft = 32;
87 }
88
89 /* Return the next @num_bits bits from the bitstream, without removing them.
90  * There must be at least @num_bits remaining in the buffer variable, from a
91  * previous call to bitstream_ensure_bits().  */
92 static inline u32
93 bitstream_peek_bits(const struct input_bitstream *is, const unsigned num_bits)
94 {
95         if (unlikely(num_bits == 0))
96                 return 0;
97         return is->bitbuf >> (32 - num_bits);
98 }
99
100 /* Remove @num_bits from the bitstream.  There must be at least @num_bits
101  * remaining in the buffer variable, from a previous call to
102  * bitstream_ensure_bits().  */
103 static inline void
104 bitstream_remove_bits(struct input_bitstream *is, unsigned num_bits)
105 {
106         is->bitbuf <<= num_bits;
107         is->bitsleft -= num_bits;
108 }
109
110 /* Remove and return @num_bits bits from the bitstream.  There must be at least
111  * @num_bits remaining in the buffer variable, from a previous call to
112  * bitstream_ensure_bits().  */
113 static inline u32
114 bitstream_pop_bits(struct input_bitstream *is, unsigned num_bits)
115 {
116         u32 bits = bitstream_peek_bits(is, num_bits);
117         bitstream_remove_bits(is, num_bits);
118         return bits;
119 }
120
121 /* Read and return the next @num_bits bits from the bitstream.  */
122 static inline u32
123 bitstream_read_bits(struct input_bitstream *is, unsigned num_bits)
124 {
125         bitstream_ensure_bits(is, num_bits);
126         return bitstream_pop_bits(is, num_bits);
127 }
128
129 /* Read and return the next literal byte embedded in the bitstream.  */
130 static inline u8
131 bitstream_read_byte(struct input_bitstream *is)
132 {
133         if (unlikely(is->end == is->next))
134                 return 0;
135         return *is->next++;
136 }
137
138 /* Read and return the next 16-bit integer embedded in the bitstream.  */
139 static inline u16
140 bitstream_read_u16(struct input_bitstream *is)
141 {
142         u16 v;
143
144         if (unlikely(is->end - is->next < 2))
145                 return 0;
146         v = get_unaligned_u16_le(is->next);
147         is->next += 2;
148         return v;
149 }
150
151 /* Read and return the next 32-bit integer embedded in the bitstream.  */
152 static inline u32
153 bitstream_read_u32(struct input_bitstream *is)
154 {
155         u32 v;
156
157         if (unlikely(is->end - is->next < 4))
158                 return 0;
159         v = get_unaligned_u32_le(is->next);
160         is->next += 4;
161         return v;
162 }
163
164 /* Read an array of literal bytes embedded in the bitstream.  Return a pointer
165  * to the resulting array, or NULL if the read overflows the input buffer.  */
166 static inline const u8 *
167 bitstream_read_bytes(struct input_bitstream *is, size_t count)
168 {
169         const u8 *p;
170
171         if (unlikely(is->end - is->next < count))
172                 return NULL;
173         p = is->next;
174         is->next += count;
175         return p;
176 }
177
178 /* Align the input bitstream on a coding-unit boundary.  */
179 static inline void
180 bitstream_align(struct input_bitstream *is)
181 {
182         is->bitsleft = 0;
183         is->bitbuf = 0;
184 }
185
186 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
187  *
188  * Reason: We may fill the entries with SSE instructions without worrying
189  * about dealing with the unaligned case.  */
190 #define DECODE_TABLE_ALIGNMENT 16
191
192 /* Maximum supported symbol count for make_huffman_decode_table().
193  *
194  * Reason: In direct mapping entries, we store the symbol in 11 bits.  */
195 #define DECODE_TABLE_MAX_SYMBOLS 2048
196
197 /* Maximum supported table bits for make_huffman_decode_table().
198  *
199  * Reason: In internal binary tree nodes, offsets are encoded in 14 bits.
200  * But the real limit is 13, because we allocate entries past the end of
201  * the direct lookup part of the table for binary tree nodes.  (Note: if
202  * needed this limit could be removed by encoding the offsets relative to
203  * &decode_table[1 << table_bits].)  */
204 #define DECODE_TABLE_MAX_TABLE_BITS 13
205
206 /* Maximum supported codeword length for make_huffman_decode_table().
207  *
208  * Reason: In direct mapping entries, we encode the codeword length in 5
209  * bits, and the top 2 bits can't both be set because that has special
210  * meaning.  */
211 #define DECODE_TABLE_MAX_CODEWORD_LEN 23
212
213 /* Reads and returns the next Huffman-encoded symbol from a bitstream.  If the
214  * input data is exhausted, the Huffman symbol is decoded as if the missing bits
215  * are all zeroes.
216  *
217  * XXX: This is mostly duplicated in lzms_huffman_decode_symbol() in
218  * lzms-decompress.c.  */
219 static inline u16
220 read_huffsym(struct input_bitstream *istream, const u16 decode_table[],
221              unsigned table_bits, unsigned max_codeword_len)
222 {
223         unsigned entry;
224         unsigned key_bits;
225
226         bitstream_ensure_bits(istream, max_codeword_len);
227
228         /* Index the decode table by the next table_bits bits of the input.  */
229         key_bits = bitstream_peek_bits(istream, table_bits);
230         entry = decode_table[key_bits];
231         if (likely(entry < 0xC000)) {
232                 /* Fast case: The decode table directly provided the
233                  * symbol and codeword length.  The low 11 bits are the
234                  * symbol, and the high 5 bits are the codeword length.  */
235                 bitstream_remove_bits(istream, entry >> 11);
236                 return entry & 0x7FF;
237         } else {
238                 /* Slow case: The codeword for the symbol is longer than
239                  * table_bits, so the symbol does not have an entry
240                  * directly in the first (1 << table_bits) entries of the
241                  * decode table.  Traverse the appropriate binary tree
242                  * bit-by-bit to decode the symbol.  */
243                 bitstream_remove_bits(istream, table_bits);
244                 do {
245                         key_bits = (entry & 0x3FFF) + bitstream_pop_bits(istream, 1);
246                 } while ((entry = decode_table[key_bits]) >= 0xC000);
247                 return entry;
248         }
249 }
250
251 extern int
252 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
253                           unsigned num_bits, const u8 lens[],
254                           unsigned max_codeword_len);
255
256
257 /*
258  * Copy an LZ77 match at (dst - offset) to dst.
259  *
260  * The length and offset must be already validated --- that is, (dst - offset)
261  * can't underrun the output buffer, and (dst + length) can't overrun the output
262  * buffer.  Also, the length cannot be 0.
263  *
264  * @winend points to the byte past the end of the output buffer.
265  * This function won't write any data beyond this position.
266  */
267 static inline void
268 lz_copy(u8 *dst, u32 length, u32 offset, const u8 *winend, u32 min_length)
269 {
270         const u8 *src = dst - offset;
271         const u8 * const end = dst + length;
272
273         /*
274          * Try to copy one machine word at a time.  On i386 and x86_64 this is
275          * faster than copying one byte at a time, unless the data is
276          * near-random and all the matches have very short lengths.  Note that
277          * since this requires unaligned memory accesses, it won't necessarily
278          * be faster on every architecture.
279          *
280          * Also note that we might copy more than the length of the match.  For
281          * example, if a word is 8 bytes and the match is of length 5, then
282          * we'll simply copy 8 bytes.  This is okay as long as we don't write
283          * beyond the end of the output buffer, hence the check for (winend -
284          * end >= WORDSIZE - 1).
285          */
286         if (UNALIGNED_ACCESS_IS_VERY_FAST &&
287             likely(winend - end >= WORDSIZE - 1))
288         {
289
290                 if (offset >= WORDSIZE) {
291                         /* The source and destination words don't overlap.  */
292
293                         /* To improve branch prediction, one iteration of this
294                          * loop is unrolled.  Most matches are short and will
295                          * fail the first check.  But if that check passes, then
296                          * it becomes increasing likely that the match is long
297                          * and we'll need to continue copying.  */
298
299                         copy_word_unaligned(src, dst);
300                         src += WORDSIZE;
301                         dst += WORDSIZE;
302
303                         if (dst < end) {
304                                 do {
305                                         copy_word_unaligned(src, dst);
306                                         src += WORDSIZE;
307                                         dst += WORDSIZE;
308                                 } while (dst < end);
309                         }
310                         return;
311                 } else if (offset == 1) {
312
313                         /* Offset 1 matches are equivalent to run-length
314                          * encoding of the previous byte.  This case is common
315                          * if the data contains many repeated bytes.  */
316
317                         machine_word_t v = repeat_byte(*(dst - 1));
318                         do {
319                                 store_word_unaligned(v, dst);
320                                 src += WORDSIZE;
321                                 dst += WORDSIZE;
322                         } while (dst < end);
323                         return;
324                 }
325                 /*
326                  * We don't bother with special cases for other 'offset <
327                  * WORDSIZE', which are usually rarer than 'offset == 1'.  Extra
328                  * checks will just slow things down.  Actually, it's possible
329                  * to handle all the 'offset < WORDSIZE' cases using the same
330                  * code, but it still becomes more complicated doesn't seem any
331                  * faster overall; it definitely slows down the more common
332                  * 'offset == 1' case.
333                  */
334         }
335
336         /* Fall back to a bytewise copy.  */
337
338         if (min_length >= 2) {
339                 *dst++ = *src++;
340                 length--;
341         }
342         if (min_length >= 3) {
343                 *dst++ = *src++;
344                 length--;
345         }
346         if (min_length >= 4) {
347                 *dst++ = *src++;
348                 length--;
349         }
350         do {
351                 *dst++ = *src++;
352         } while (--length);
353 }
354
355 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */