]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/BrotliCustomDecompressLib/dec/decode.c
ArmPkg: copy/paste fixes in ARM ArmHvcLib/ArmSmcLib
[mirror_edk2.git] / MdeModulePkg / Library / BrotliCustomDecompressLib / dec / decode.c
1 /* Copyright 2013 Google Inc. All Rights Reserved.
2
3 Distributed under MIT license.
4 See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
5 */
6
7 #include "./decode.h"
8
9 #ifdef __ARM_NEON__
10 #include <arm_neon.h>
11 #endif
12
13 //#include <stdlib.h> /* free, malloc */
14 //#include <string.h> /* memcpy, memset */
15 #include <BrotliDecompressLibInternal.h>
16
17 #include "../common/constants.h"
18 #include "../common/dictionary.h"
19 #include "./bit_reader.h"
20 #include "./context.h"
21 #include "./huffman.h"
22 #include "./port.h"
23 #include "./prefix.h"
24 #include "./state.h"
25 #include "./transform.h"
26
27 #if defined(__cplusplus) || defined(c_plusplus)
28 extern "C" {
29 #endif
30
31 #define BROTLI_FAILURE(CODE) (BROTLI_DUMP(), CODE)
32
33 #define BROTLI_LOG_UINT(name) \
34 BROTLI_LOG(("[%s] %s = %lu\n", __func__, #name, (unsigned long)(name)))
35 #define BROTLI_LOG_ARRAY_INDEX(array_name, idx) \
36 BROTLI_LOG(("[%s] %s[%lu] = %lu\n", __func__, #array_name, \
37 (unsigned long)(idx), (unsigned long)array_name[idx]))
38
39 #define HUFFMAN_TABLE_BITS 8U
40 #define HUFFMAN_TABLE_MASK 0xff
41
42 static const uint8_t kCodeLengthCodeOrder[BROTLI_CODE_LENGTH_CODES] = {
43 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15,
44 };
45
46 /* Static prefix code for the complex code length code lengths. */
47 static const uint8_t kCodeLengthPrefixLength[16] = {
48 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4,
49 };
50
51 static const uint8_t kCodeLengthPrefixValue[16] = {
52 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5,
53 };
54
55 BrotliDecoderState* BrotliDecoderCreateInstance(
56 brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
57 BrotliDecoderState* state = 0;
58 if (!alloc_func && !free_func) {
59 state = (BrotliDecoderState*)malloc(sizeof(BrotliDecoderState));
60 } else if (alloc_func && free_func) {
61 state = (BrotliDecoderState*)alloc_func(opaque, sizeof(BrotliDecoderState));
62 }
63 if (state == 0) {
64 BROTLI_DUMP();
65 return 0;
66 }
67 BrotliDecoderStateInitWithCustomAllocators(
68 state, alloc_func, free_func, opaque);
69 state->error_code = BROTLI_DECODER_NO_ERROR;
70 return state;
71 }
72
73 /* Deinitializes and frees BrotliDecoderState instance. */
74 void BrotliDecoderDestroyInstance(BrotliDecoderState* state) {
75 if (!state) {
76 return;
77 } else {
78 brotli_free_func free_func = state->free_func;
79 void* opaque = state->memory_manager_opaque;
80 BrotliDecoderStateCleanup(state);
81 free_func(opaque, state);
82 }
83 }
84
85 /* Saves error code and converts it to BrotliDecoderResult */
86 static BROTLI_NOINLINE BrotliDecoderResult SaveErrorCode(
87 BrotliDecoderState* s, BrotliDecoderErrorCode e) {
88 s->error_code = (int)e;
89 switch (e) {
90 case BROTLI_DECODER_SUCCESS:
91 return BROTLI_DECODER_RESULT_SUCCESS;
92 case BROTLI_DECODER_NEEDS_MORE_INPUT:
93 return BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
94 case BROTLI_DECODER_NEEDS_MORE_OUTPUT:
95 return BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
96 default:
97 return BROTLI_DECODER_RESULT_ERROR;
98 }
99 }
100
101 /* Decodes a number in the range [9..24], by reading 1 - 7 bits.
102 Precondition: bit-reader accumulator has at least 7 bits. */
103 static uint32_t DecodeWindowBits(BrotliBitReader* br) {
104 uint32_t n;
105 BrotliTakeBits(br, 1, &n);
106 if (n == 0) {
107 return 16;
108 }
109 BrotliTakeBits(br, 3, &n);
110 if (n != 0) {
111 return 17 + n;
112 }
113 BrotliTakeBits(br, 3, &n);
114 if (n != 0) {
115 return 8 + n;
116 }
117 return 17;
118 }
119
120 static BROTLI_INLINE void memmove16(uint8_t* dst, uint8_t* src) {
121 #if defined(__ARM_NEON__)
122 vst1q_u8(dst, vld1q_u8(src));
123 #else
124 uint32_t buffer[4];
125 memcpy(buffer, src, 16);
126 memcpy(dst, buffer, 16);
127 #endif
128 }
129
130 /* Decodes a number in the range [0..255], by reading 1 - 11 bits. */
131 static BROTLI_NOINLINE BrotliDecoderErrorCode DecodeVarLenUint8(
132 BrotliDecoderState* s, BrotliBitReader* br, uint32_t* value) {
133 uint32_t bits;
134 switch (s->substate_decode_uint8) {
135 case BROTLI_STATE_DECODE_UINT8_NONE:
136 if (PREDICT_FALSE(!BrotliSafeReadBits(br, 1, &bits))) {
137 return BROTLI_DECODER_NEEDS_MORE_INPUT;
138 }
139 if (bits == 0) {
140 *value = 0;
141 return BROTLI_DECODER_SUCCESS;
142 }
143 /* No break, transit to the next state. */
144
145 case BROTLI_STATE_DECODE_UINT8_SHORT:
146 if (PREDICT_FALSE(!BrotliSafeReadBits(br, 3, &bits))) {
147 s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_SHORT;
148 return BROTLI_DECODER_NEEDS_MORE_INPUT;
149 }
150 if (bits == 0) {
151 *value = 1;
152 s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
153 return BROTLI_DECODER_SUCCESS;
154 }
155 /* Use output value as a temporary storage. It MUST be persisted. */
156 *value = bits;
157 /* No break, transit to the next state. */
158
159 case BROTLI_STATE_DECODE_UINT8_LONG:
160 if (PREDICT_FALSE(!BrotliSafeReadBits(br, *value, &bits))) {
161 s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_LONG;
162 return BROTLI_DECODER_NEEDS_MORE_INPUT;
163 }
164 *value = (1U << *value) + bits;
165 s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
166 return BROTLI_DECODER_SUCCESS;
167
168 default:
169 return
170 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
171 }
172 }
173
174 /* Decodes a metablock length and flags by reading 2 - 31 bits. */
175 static BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength(
176 BrotliDecoderState* s, BrotliBitReader* br) {
177 uint32_t bits;
178 int i;
179 for (;;) {
180 switch (s->substate_metablock_header) {
181 case BROTLI_STATE_METABLOCK_HEADER_NONE:
182 if (!BrotliSafeReadBits(br, 1, &bits)) {
183 return BROTLI_DECODER_NEEDS_MORE_INPUT;
184 }
185 s->is_last_metablock = (uint8_t)bits;
186 s->meta_block_remaining_len = 0;
187 s->is_uncompressed = 0;
188 s->is_metadata = 0;
189 if (!s->is_last_metablock) {
190 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
191 break;
192 }
193 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_EMPTY;
194 /* No break, transit to the next state. */
195
196 case BROTLI_STATE_METABLOCK_HEADER_EMPTY:
197 if (!BrotliSafeReadBits(br, 1, &bits)) {
198 return BROTLI_DECODER_NEEDS_MORE_INPUT;
199 }
200 if (bits) {
201 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
202 return BROTLI_DECODER_SUCCESS;
203 }
204 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
205 /* No break, transit to the next state. */
206
207 case BROTLI_STATE_METABLOCK_HEADER_NIBBLES:
208 if (!BrotliSafeReadBits(br, 2, &bits)) {
209 return BROTLI_DECODER_NEEDS_MORE_INPUT;
210 }
211 s->size_nibbles = (uint8_t)(bits + 4);
212 s->loop_counter = 0;
213 if (bits == 3) {
214 s->is_metadata = 1;
215 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_RESERVED;
216 break;
217 }
218 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_SIZE;
219 /* No break, transit to the next state. */
220
221 case BROTLI_STATE_METABLOCK_HEADER_SIZE:
222 i = s->loop_counter;
223 for (; i < s->size_nibbles; ++i) {
224 if (!BrotliSafeReadBits(br, 4, &bits)) {
225 s->loop_counter = i;
226 return BROTLI_DECODER_NEEDS_MORE_INPUT;
227 }
228 if (i + 1 == s->size_nibbles && s->size_nibbles > 4 && bits == 0) {
229 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE);
230 }
231 s->meta_block_remaining_len |= (int)(bits << (i * 4));
232 }
233 s->substate_metablock_header =
234 BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED;
235 /* No break, transit to the next state. */
236
237 case BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED:
238 if (!s->is_last_metablock) {
239 if (!BrotliSafeReadBits(br, 1, &bits)) {
240 return BROTLI_DECODER_NEEDS_MORE_INPUT;
241 }
242 s->is_uncompressed = (uint8_t)bits;
243 }
244 ++s->meta_block_remaining_len;
245 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
246 return BROTLI_DECODER_SUCCESS;
247
248 case BROTLI_STATE_METABLOCK_HEADER_RESERVED:
249 if (!BrotliSafeReadBits(br, 1, &bits)) {
250 return BROTLI_DECODER_NEEDS_MORE_INPUT;
251 }
252 if (bits != 0) {
253 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_RESERVED);
254 }
255 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_BYTES;
256 /* No break, transit to the next state. */
257
258 case BROTLI_STATE_METABLOCK_HEADER_BYTES:
259 if (!BrotliSafeReadBits(br, 2, &bits)) {
260 return BROTLI_DECODER_NEEDS_MORE_INPUT;
261 }
262 if (bits == 0) {
263 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
264 return BROTLI_DECODER_SUCCESS;
265 }
266 s->size_nibbles = (uint8_t)bits;
267 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_METADATA;
268 /* No break, transit to the next state. */
269
270 case BROTLI_STATE_METABLOCK_HEADER_METADATA:
271 i = s->loop_counter;
272 for (; i < s->size_nibbles; ++i) {
273 if (!BrotliSafeReadBits(br, 8, &bits)) {
274 s->loop_counter = i;
275 return BROTLI_DECODER_NEEDS_MORE_INPUT;
276 }
277 if (i + 1 == s->size_nibbles && s->size_nibbles > 1 && bits == 0) {
278 return BROTLI_FAILURE(
279 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE);
280 }
281 s->meta_block_remaining_len |= (int)(bits << (i * 8));
282 }
283 ++s->meta_block_remaining_len;
284 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
285 return BROTLI_DECODER_SUCCESS;
286
287 default:
288 return
289 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
290 }
291 }
292 }
293
294 /* Decodes the Huffman code.
295 This method doesn't read data from the bit reader, BUT drops the amount of
296 bits that correspond to the decoded symbol.
297 bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits. */
298 static BROTLI_INLINE uint32_t DecodeSymbol(uint32_t bits,
299 const HuffmanCode* table,
300 BrotliBitReader* br) {
301 table += bits & HUFFMAN_TABLE_MASK;
302 if (table->bits > HUFFMAN_TABLE_BITS) {
303 uint32_t nbits = table->bits - HUFFMAN_TABLE_BITS;
304 BrotliDropBits(br, HUFFMAN_TABLE_BITS);
305 table += table->value;
306 table += (bits >> HUFFMAN_TABLE_BITS) & BitMask(nbits);
307 }
308 BrotliDropBits(br, table->bits);
309 return table->value;
310 }
311
312 /* Reads and decodes the next Huffman code from bit-stream.
313 This method peeks 16 bits of input and drops 0 - 15 of them. */
314 static BROTLI_INLINE uint32_t ReadSymbol(const HuffmanCode* table,
315 BrotliBitReader* br) {
316 return DecodeSymbol(BrotliGet16BitsUnmasked(br), table, br);
317 }
318
319 /* Same as DecodeSymbol, but it is known that there is less than 15 bits of
320 input are currently available. */
321 static BROTLI_NOINLINE BROTLI_BOOL SafeDecodeSymbol(
322 const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) {
323 uint32_t val;
324 uint32_t available_bits = BrotliGetAvailableBits(br);
325 if (available_bits == 0) {
326 if (table->bits == 0) {
327 *result = table->value;
328 return BROTLI_TRUE;
329 }
330 return BROTLI_FALSE; /* No valid bits at all. */
331 }
332 val = (uint32_t)BrotliGetBitsUnmasked(br);
333 table += val & HUFFMAN_TABLE_MASK;
334 if (table->bits <= HUFFMAN_TABLE_BITS) {
335 if (table->bits <= available_bits) {
336 BrotliDropBits(br, table->bits);
337 *result = table->value;
338 return BROTLI_TRUE;
339 } else {
340 return BROTLI_FALSE; /* Not enough bits for the first level. */
341 }
342 }
343 if (available_bits <= HUFFMAN_TABLE_BITS) {
344 return BROTLI_FALSE; /* Not enough bits to move to the second level. */
345 }
346
347 /* Speculatively drop HUFFMAN_TABLE_BITS. */
348 val = (val & BitMask(table->bits)) >> HUFFMAN_TABLE_BITS;
349 available_bits -= HUFFMAN_TABLE_BITS;
350 table += table->value + val;
351 if (available_bits < table->bits) {
352 return BROTLI_FALSE; /* Not enough bits for the second level. */
353 }
354
355 BrotliDropBits(br, HUFFMAN_TABLE_BITS + table->bits);
356 *result = table->value;
357 return BROTLI_TRUE;
358 }
359
360 static BROTLI_INLINE BROTLI_BOOL SafeReadSymbol(
361 const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) {
362 uint32_t val;
363 if (PREDICT_TRUE(BrotliSafeGetBits(br, 15, &val))) {
364 *result = DecodeSymbol(val, table, br);
365 return BROTLI_TRUE;
366 }
367 return SafeDecodeSymbol(table, br, result);
368 }
369
370 /* Makes a look-up in first level Huffman table. Peeks 8 bits. */
371 static BROTLI_INLINE void PreloadSymbol(int safe,
372 const HuffmanCode* table,
373 BrotliBitReader* br,
374 uint32_t* bits,
375 uint32_t* value) {
376 if (safe) {
377 return;
378 }
379 table += BrotliGetBits(br, HUFFMAN_TABLE_BITS);
380 *bits = table->bits;
381 *value = table->value;
382 }
383
384 /* Decodes the next Huffman code using data prepared by PreloadSymbol.
385 Reads 0 - 15 bits. Also peeks 8 following bits. */
386 static BROTLI_INLINE uint32_t ReadPreloadedSymbol(const HuffmanCode* table,
387 BrotliBitReader* br,
388 uint32_t* bits,
389 uint32_t* value) {
390 uint32_t result = *value;
391 if (PREDICT_FALSE(*bits > HUFFMAN_TABLE_BITS)) {
392 uint32_t val = BrotliGet16BitsUnmasked(br);
393 const HuffmanCode* ext = table + (val & HUFFMAN_TABLE_MASK) + *value;
394 uint32_t mask = BitMask((*bits - HUFFMAN_TABLE_BITS));
395 BrotliDropBits(br, HUFFMAN_TABLE_BITS);
396 ext += (val >> HUFFMAN_TABLE_BITS) & mask;
397 BrotliDropBits(br, ext->bits);
398 result = ext->value;
399 } else {
400 BrotliDropBits(br, *bits);
401 }
402 PreloadSymbol(0, table, br, bits, value);
403 return result;
404 }
405
406 static BROTLI_INLINE uint32_t Log2Floor(uint32_t x) {
407 uint32_t result = 0;
408 while (x) {
409 x >>= 1;
410 ++result;
411 }
412 return result;
413 }
414
415 /* Reads (s->symbol + 1) symbols.
416 Totally 1..4 symbols are read, 1..10 bits each.
417 The list of symbols MUST NOT contain duplicates.
418 */
419 static BrotliDecoderErrorCode ReadSimpleHuffmanSymbols(
420 uint32_t alphabet_size, BrotliDecoderState* s) {
421 /* max_bits == 1..10; symbol == 0..3; 1..40 bits will be read. */
422 BrotliBitReader* br = &s->br;
423 uint32_t max_bits = Log2Floor(alphabet_size - 1);
424 uint32_t i = s->sub_loop_counter;
425 uint32_t num_symbols = s->symbol;
426 while (i <= num_symbols) {
427 uint32_t v;
428 if (PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))) {
429 s->sub_loop_counter = i;
430 s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ;
431 return BROTLI_DECODER_NEEDS_MORE_INPUT;
432 }
433 if (v >= alphabet_size) {
434 return
435 BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET);
436 }
437 s->symbols_lists_array[i] = (uint16_t)v;
438 BROTLI_LOG_UINT(s->symbols_lists_array[i]);
439 ++i;
440 }
441
442 for (i = 0; i < num_symbols; ++i) {
443 uint32_t k = i + 1;
444 for (; k <= num_symbols; ++k) {
445 if (s->symbols_lists_array[i] == s->symbols_lists_array[k]) {
446 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME);
447 }
448 }
449 }
450
451 return BROTLI_DECODER_SUCCESS;
452 }
453
454 /* Process single decoded symbol code length:
455 A) reset the repeat variable
456 B) remember code length (if it is not 0)
457 C) extend corredponding index-chain
458 D) reduce the huffman space
459 E) update the histogram
460 */
461 static BROTLI_INLINE void ProcessSingleCodeLength(uint32_t code_len,
462 uint32_t* symbol, uint32_t* repeat, uint32_t* space,
463 uint32_t* prev_code_len, uint16_t* symbol_lists,
464 uint16_t* code_length_histo, int* next_symbol) {
465 *repeat = 0;
466 if (code_len != 0) { /* code_len == 1..15 */
467 symbol_lists[next_symbol[code_len]] = (uint16_t)(*symbol);
468 next_symbol[code_len] = (int)(*symbol);
469 *prev_code_len = code_len;
470 *space -= 32768U >> code_len;
471 code_length_histo[code_len]++;
472 BROTLI_LOG(("[ReadHuffmanCode] code_length[%d] = %d\n", *symbol, code_len));
473 }
474 (*symbol)++;
475 }
476
477 /* Process repeated symbol code length.
478 A) Check if it is the extension of previous repeat sequence; if the decoded
479 value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new
480 symbol-skip
481 B) Update repeat variable
482 C) Check if operation is feasible (fits alphapet)
483 D) For each symbol do the same operations as in ProcessSingleCodeLength
484
485 PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or
486 code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH
487 */
488 static BROTLI_INLINE void ProcessRepeatedCodeLength(uint32_t code_len,
489 uint32_t repeat_delta, uint32_t alphabet_size, uint32_t* symbol,
490 uint32_t* repeat, uint32_t* space, uint32_t* prev_code_len,
491 uint32_t* repeat_code_len, uint16_t* symbol_lists,
492 uint16_t* code_length_histo, int* next_symbol) {
493 uint32_t old_repeat;
494 uint32_t extra_bits = 3; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
495 uint32_t new_len = 0; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
496 if (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
497 new_len = *prev_code_len;
498 extra_bits = 2;
499 }
500 if (*repeat_code_len != new_len) {
501 *repeat = 0;
502 *repeat_code_len = new_len;
503 }
504 old_repeat = *repeat;
505 if (*repeat > 0) {
506 *repeat -= 2;
507 *repeat <<= extra_bits;
508 }
509 *repeat += repeat_delta + 3U;
510 repeat_delta = *repeat - old_repeat;
511 if (*symbol + repeat_delta > alphabet_size) {
512 BROTLI_DUMP();
513 *symbol = alphabet_size;
514 *space = 0xFFFFF;
515 return;
516 }
517 BROTLI_LOG(("[ReadHuffmanCode] code_length[%d..%d] = %d\n",
518 *symbol, *symbol + repeat_delta - 1, *repeat_code_len));
519 if (*repeat_code_len != 0) {
520 unsigned last = *symbol + repeat_delta;
521 int next = next_symbol[*repeat_code_len];
522 do {
523 symbol_lists[next] = (uint16_t)*symbol;
524 next = (int)*symbol;
525 } while (++(*symbol) != last);
526 next_symbol[*repeat_code_len] = next;
527 *space -= repeat_delta << (15 - *repeat_code_len);
528 code_length_histo[*repeat_code_len] =
529 (uint16_t)(code_length_histo[*repeat_code_len] + repeat_delta);
530 } else {
531 *symbol += repeat_delta;
532 }
533 }
534
535 /* Reads and decodes symbol codelengths. */
536 static BrotliDecoderErrorCode ReadSymbolCodeLengths(
537 uint32_t alphabet_size, BrotliDecoderState* s) {
538 BrotliBitReader* br = &s->br;
539 uint32_t symbol = s->symbol;
540 uint32_t repeat = s->repeat;
541 uint32_t space = s->space;
542 uint32_t prev_code_len = s->prev_code_len;
543 uint32_t repeat_code_len = s->repeat_code_len;
544 uint16_t* symbol_lists = s->symbol_lists;
545 uint16_t* code_length_histo = s->code_length_histo;
546 int* next_symbol = s->next_symbol;
547 if (!BrotliWarmupBitReader(br)) {
548 return BROTLI_DECODER_NEEDS_MORE_INPUT;
549 }
550 while (symbol < alphabet_size && space > 0) {
551 const HuffmanCode* p = s->table;
552 uint32_t code_len;
553 if (!BrotliCheckInputAmount(br, BROTLI_SHORT_FILL_BIT_WINDOW_READ)) {
554 s->symbol = symbol;
555 s->repeat = repeat;
556 s->prev_code_len = prev_code_len;
557 s->repeat_code_len = repeat_code_len;
558 s->space = space;
559 return BROTLI_DECODER_NEEDS_MORE_INPUT;
560 }
561 BrotliFillBitWindow16(br);
562 p += BrotliGetBitsUnmasked(br) &
563 BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH);
564 BrotliDropBits(br, p->bits); /* Use 1..5 bits */
565 code_len = p->value; /* code_len == 0..17 */
566 if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
567 ProcessSingleCodeLength(code_len, &symbol, &repeat, &space,
568 &prev_code_len, symbol_lists, code_length_histo, next_symbol);
569 } else { /* code_len == 16..17, extra_bits == 2..3 */
570 uint32_t extra_bits =
571 (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) ? 2 : 3;
572 uint32_t repeat_delta =
573 (uint32_t)BrotliGetBitsUnmasked(br) & BitMask(extra_bits);
574 BrotliDropBits(br, extra_bits);
575 ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
576 &symbol, &repeat, &space, &prev_code_len, &repeat_code_len,
577 symbol_lists, code_length_histo, next_symbol);
578 }
579 }
580 s->space = space;
581 return BROTLI_DECODER_SUCCESS;
582 }
583
584 static BrotliDecoderErrorCode SafeReadSymbolCodeLengths(
585 uint32_t alphabet_size, BrotliDecoderState* s) {
586 BrotliBitReader* br = &s->br;
587 while (s->symbol < alphabet_size && s->space > 0) {
588 const HuffmanCode* p = s->table;
589 uint32_t code_len;
590 uint32_t bits = 0;
591 uint32_t available_bits = BrotliGetAvailableBits(br);
592 if (available_bits != 0) {
593 bits = (uint32_t)BrotliGetBitsUnmasked(br);
594 }
595 p += bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH);
596 if (p->bits > available_bits) goto pullMoreInput;
597 code_len = p->value; /* code_len == 0..17 */
598 if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
599 BrotliDropBits(br, p->bits);
600 ProcessSingleCodeLength(code_len, &s->symbol, &s->repeat, &s->space,
601 &s->prev_code_len, s->symbol_lists, s->code_length_histo,
602 s->next_symbol);
603 } else { /* code_len == 16..17, extra_bits == 2..3 */
604 uint32_t extra_bits = code_len - 14U;
605 uint32_t repeat_delta = (bits >> p->bits) & BitMask(extra_bits);
606 if (available_bits < p->bits + extra_bits) goto pullMoreInput;
607 BrotliDropBits(br, p->bits + extra_bits);
608 ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
609 &s->symbol, &s->repeat, &s->space, &s->prev_code_len,
610 &s->repeat_code_len, s->symbol_lists, s->code_length_histo,
611 s->next_symbol);
612 }
613 continue;
614
615 pullMoreInput:
616 if (!BrotliPullByte(br)) {
617 return BROTLI_DECODER_NEEDS_MORE_INPUT;
618 }
619 }
620 return BROTLI_DECODER_SUCCESS;
621 }
622
623 /* Reads and decodes 15..18 codes using static prefix code.
624 Each code is 2..4 bits long. In total 30..72 bits are used. */
625 static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) {
626 BrotliBitReader* br = &s->br;
627 uint32_t num_codes = s->repeat;
628 unsigned space = s->space;
629 uint32_t i = s->sub_loop_counter;
630 for (; i < BROTLI_CODE_LENGTH_CODES; ++i) {
631 const uint8_t code_len_idx = kCodeLengthCodeOrder[i];
632 uint32_t ix;
633 uint32_t v;
634 if (PREDICT_FALSE(!BrotliSafeGetBits(br, 4, &ix))) {
635 uint32_t available_bits = BrotliGetAvailableBits(br);
636 if (available_bits != 0) {
637 ix = BrotliGetBitsUnmasked(br) & 0xF;
638 } else {
639 ix = 0;
640 }
641 if (kCodeLengthPrefixLength[ix] > available_bits) {
642 s->sub_loop_counter = i;
643 s->repeat = num_codes;
644 s->space = space;
645 s->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
646 return BROTLI_DECODER_NEEDS_MORE_INPUT;
647 }
648 }
649 v = kCodeLengthPrefixValue[ix];
650 BrotliDropBits(br, kCodeLengthPrefixLength[ix]);
651 s->code_length_code_lengths[code_len_idx] = (uint8_t)v;
652 BROTLI_LOG_ARRAY_INDEX(s->code_length_code_lengths, code_len_idx);
653 if (v != 0) {
654 space = space - (32U >> v);
655 ++num_codes;
656 ++s->code_length_histo[v];
657 if (space - 1U >= 32U) {
658 /* space is 0 or wrapped around */
659 break;
660 }
661 }
662 }
663 if (!(num_codes == 1 || space == 0)) {
664 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CL_SPACE);
665 }
666 return BROTLI_DECODER_SUCCESS;
667 }
668
669 /* Decodes the Huffman tables.
670 There are 2 scenarios:
671 A) Huffman code contains only few symbols (1..4). Those symbols are read
672 directly; their code lengths are defined by the number of symbols.
673 For this scenario 4 - 45 bits will be read.
674
675 B) 2-phase decoding:
676 B.1) Small Huffman table is decoded; it is specified with code lengths
677 encoded with predefined entropy code. 32 - 74 bits are used.
678 B.2) Decoded table is used to decode code lengths of symbols in resulting
679 Huffman table. In worst case 3520 bits are read.
680 */
681 static BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size,
682 HuffmanCode* table,
683 uint32_t* opt_table_size,
684 BrotliDecoderState* s) {
685 BrotliBitReader* br = &s->br;
686 /* Unnecessary masking, but might be good for safety. */
687 alphabet_size &= 0x3ff;
688 /* State machine */
689 switch (s->substate_huffman) {
690 case BROTLI_STATE_HUFFMAN_NONE:
691 if (!BrotliSafeReadBits(br, 2, &s->sub_loop_counter)) {
692 return BROTLI_DECODER_NEEDS_MORE_INPUT;
693 }
694 BROTLI_LOG_UINT(s->sub_loop_counter);
695 /* The value is used as follows:
696 1 for simple code;
697 0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
698 if (s->sub_loop_counter != 1) {
699 s->space = 32;
700 s->repeat = 0; /* num_codes */
701 memset(&s->code_length_histo[0], 0, sizeof(s->code_length_histo[0]) *
702 (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1));
703 memset(&s->code_length_code_lengths[0], 0,
704 sizeof(s->code_length_code_lengths));
705 s->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
706 goto Complex;
707 }
708 /* No break, transit to the next state. */
709
710 case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE:
711 /* Read symbols, codes & code lengths directly. */
712 if (!BrotliSafeReadBits(br, 2, &s->symbol)) { /* num_symbols */
713 s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
714 return BROTLI_DECODER_NEEDS_MORE_INPUT;
715 }
716 s->sub_loop_counter = 0;
717 /* No break, transit to the next state. */
718 case BROTLI_STATE_HUFFMAN_SIMPLE_READ: {
719 BrotliDecoderErrorCode result =
720 ReadSimpleHuffmanSymbols(alphabet_size, s);
721 if (result != BROTLI_DECODER_SUCCESS) {
722 return result;
723 }
724 /* No break, transit to the next state. */
725 }
726 case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: {
727 uint32_t table_size;
728 if (s->symbol == 3) {
729 uint32_t bits;
730 if (!BrotliSafeReadBits(br, 1, &bits)) {
731 s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
732 return BROTLI_DECODER_NEEDS_MORE_INPUT;
733 }
734 s->symbol += bits;
735 }
736 BROTLI_LOG_UINT(s->symbol);
737 table_size = BrotliBuildSimpleHuffmanTable(
738 table, HUFFMAN_TABLE_BITS, s->symbols_lists_array, s->symbol);
739 if (opt_table_size) {
740 *opt_table_size = table_size;
741 }
742 s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
743 return BROTLI_DECODER_SUCCESS;
744 }
745
746 Complex: /* Decode Huffman-coded code lengths. */
747 case BROTLI_STATE_HUFFMAN_COMPLEX: {
748 uint32_t i;
749 BrotliDecoderErrorCode result = ReadCodeLengthCodeLengths(s);
750 if (result != BROTLI_DECODER_SUCCESS) {
751 return result;
752 }
753 BrotliBuildCodeLengthsHuffmanTable(s->table,
754 s->code_length_code_lengths,
755 s->code_length_histo);
756 memset(&s->code_length_histo[0], 0, sizeof(s->code_length_histo));
757 for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH; ++i) {
758 s->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1);
759 s->symbol_lists[(int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1)] = 0xFFFF;
760 }
761
762 s->symbol = 0;
763 s->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH;
764 s->repeat = 0;
765 s->repeat_code_len = 0;
766 s->space = 32768;
767 s->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
768 /* No break, transit to the next state. */
769 }
770 case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: {
771 uint32_t table_size;
772 BrotliDecoderErrorCode result = ReadSymbolCodeLengths(alphabet_size, s);
773 if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
774 result = SafeReadSymbolCodeLengths(alphabet_size, s);
775 }
776 if (result != BROTLI_DECODER_SUCCESS) {
777 return result;
778 }
779
780 if (s->space != 0) {
781 BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", s->space));
782 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE);
783 }
784 table_size = BrotliBuildHuffmanTable(
785 table, HUFFMAN_TABLE_BITS, s->symbol_lists, s->code_length_histo);
786 if (opt_table_size) {
787 *opt_table_size = table_size;
788 }
789 s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
790 return BROTLI_DECODER_SUCCESS;
791 }
792
793 default:
794 return
795 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
796 }
797 }
798
799 /* Decodes a block length by reading 3..39 bits. */
800 static BROTLI_INLINE uint32_t ReadBlockLength(const HuffmanCode* table,
801 BrotliBitReader* br) {
802 uint32_t code;
803 uint32_t nbits;
804 code = ReadSymbol(table, br);
805 if (code >= BROTLI_NUM_BLOCK_LEN_SYMBOLS) code = BROTLI_NUM_BLOCK_LEN_SYMBOLS - 1;
806 nbits = kBlockLengthPrefixCode[code].nbits; /* nbits == 2..24 */
807 return kBlockLengthPrefixCode[code].offset + BrotliReadBits(br, nbits);
808 }
809
810 /* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
811 reading can't be continued with ReadBlockLength. */
812 static BROTLI_INLINE BROTLI_BOOL SafeReadBlockLength(
813 BrotliDecoderState* s, uint32_t* result, const HuffmanCode* table,
814 BrotliBitReader* br) {
815 uint32_t index;
816 if (s->substate_read_block_length == BROTLI_STATE_READ_BLOCK_LENGTH_NONE) {
817 if (!SafeReadSymbol(table, br, &index)) {
818 return BROTLI_FALSE;
819 }
820 } else {
821 index = s->block_length_index;
822 }
823 {
824 uint32_t bits;
825 uint32_t nbits = kBlockLengthPrefixCode[index].nbits; /* nbits == 2..24 */
826 if (!BrotliSafeReadBits(br, nbits, &bits)) {
827 s->block_length_index = index;
828 s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX;
829 return BROTLI_FALSE;
830 }
831 *result = kBlockLengthPrefixCode[index].offset + bits;
832 s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
833 return BROTLI_TRUE;
834 }
835 }
836
837 /* Transform:
838 1) initialize list L with values 0, 1,... 255
839 2) For each input element X:
840 2.1) let Y = L[X]
841 2.2) remove X-th element from L
842 2.3) prepend Y to L
843 2.4) append Y to output
844
845 In most cases max(Y) <= 7, so most of L remains intact.
846 To reduce the cost of initialization, we reuse L, remember the upper bound
847 of Y values, and reinitialize only first elements in L.
848
849 Most of input values are 0 and 1. To reduce number of branches, we replace
850 inner for loop with do-while.
851 */
852 static BROTLI_NOINLINE void InverseMoveToFrontTransform(
853 uint8_t* v, uint32_t v_len, BrotliDecoderState* state) {
854 /* Reinitialize elements that could have been changed. */
855 uint32_t i = 4;
856 uint32_t upper_bound = state->mtf_upper_bound;
857 uint8_t* mtf = &state->mtf[4]; /* Make mtf[-1] addressable. */
858 /* Load endian-aware constant. */
859 const uint8_t b0123[4] = {0, 1, 2, 3};
860 uint32_t pattern;
861 memcpy(&pattern, &b0123, 4);
862
863 /* Initialize list using 4 consequent values pattern. */
864 *(uint32_t*)mtf = pattern;
865 do {
866 pattern += 0x04040404; /* Advance all 4 values by 4. */
867 *(uint32_t*)(mtf + i) = pattern;
868 i += 4;
869 } while (i <= upper_bound);
870
871 /* Transform the input. */
872 upper_bound = 0;
873 for (i = 0; i < v_len; ++i) {
874 int index = v[i];
875 uint8_t value = mtf[index];
876 upper_bound |= (uint32_t)v[i];
877 v[i] = value;
878 mtf[-1] = value;
879 while (index > 0) {
880 index--;
881 mtf[index + 1] = mtf[index];
882 }
883 }
884 /* Remember amount of elements to be reinitialized. */
885 state->mtf_upper_bound = upper_bound;
886 }
887
888 /* Decodes a series of Huffman table using ReadHuffmanCode function. */
889 static BrotliDecoderErrorCode HuffmanTreeGroupDecode(
890 HuffmanTreeGroup* group, BrotliDecoderState* s) {
891 if (s->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) {
892 s->next = group->codes;
893 s->htree_index = 0;
894 s->substate_tree_group = BROTLI_STATE_TREE_GROUP_LOOP;
895 }
896 while (s->htree_index < group->num_htrees) {
897 uint32_t table_size;
898 BrotliDecoderErrorCode result =
899 ReadHuffmanCode(group->alphabet_size, s->next, &table_size, s);
900 if (result != BROTLI_DECODER_SUCCESS) return result;
901 group->htrees[s->htree_index] = s->next;
902 s->next += table_size;
903 ++s->htree_index;
904 }
905 s->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
906 return BROTLI_DECODER_SUCCESS;
907 }
908
909 /* Decodes a context map.
910 Decoding is done in 4 phases:
911 1) Read auxiliary information (6..16 bits) and allocate memory.
912 In case of trivial context map, decoding is finished at this phase.
913 2) Decode Huffman table using ReadHuffmanCode function.
914 This table will be used for reading context map items.
915 3) Read context map items; "0" values could be run-length encoded.
916 4) Optionally, apply InverseMoveToFront transform to the resulting map.
917 */
918 static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size,
919 uint32_t* num_htrees,
920 uint8_t** context_map_arg,
921 BrotliDecoderState* s) {
922 BrotliBitReader* br = &s->br;
923 BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
924
925 switch ((int)s->substate_context_map) {
926 case BROTLI_STATE_CONTEXT_MAP_NONE:
927 result = DecodeVarLenUint8(s, br, num_htrees);
928 if (result != BROTLI_DECODER_SUCCESS) {
929 return result;
930 }
931 (*num_htrees)++;
932 s->context_index = 0;
933 BROTLI_LOG_UINT(context_map_size);
934 BROTLI_LOG_UINT(*num_htrees);
935 *context_map_arg = (uint8_t*)BROTLI_ALLOC(s, (size_t)context_map_size);
936 if (*context_map_arg == 0) {
937 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP);
938 }
939 if (*num_htrees <= 1) {
940 memset(*context_map_arg, 0, (size_t)context_map_size);
941 return BROTLI_DECODER_SUCCESS;
942 }
943 s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
944 /* No break, continue to next state. */
945 case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: {
946 uint32_t bits;
947 /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe
948 to peek 4 bits ahead. */
949 if (!BrotliSafeGetBits(br, 5, &bits)) {
950 return BROTLI_DECODER_NEEDS_MORE_INPUT;
951 }
952 if ((bits & 1) != 0) { /* Use RLE for zeroes. */
953 s->max_run_length_prefix = (bits >> 1) + 1;
954 BrotliDropBits(br, 5);
955 } else {
956 s->max_run_length_prefix = 0;
957 BrotliDropBits(br, 1);
958 }
959 BROTLI_LOG_UINT(s->max_run_length_prefix);
960 s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN;
961 /* No break, continue to next state. */
962 }
963 case BROTLI_STATE_CONTEXT_MAP_HUFFMAN:
964 result = ReadHuffmanCode(*num_htrees + s->max_run_length_prefix,
965 s->context_map_table, NULL, s);
966 if (result != BROTLI_DECODER_SUCCESS) return result;
967 s->code = 0xFFFF;
968 s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE;
969 /* No break, continue to next state. */
970 case BROTLI_STATE_CONTEXT_MAP_DECODE: {
971 uint32_t context_index = s->context_index;
972 uint32_t max_run_length_prefix = s->max_run_length_prefix;
973 uint8_t* context_map = *context_map_arg;
974 uint32_t code = s->code;
975 if (code != 0xFFFF) {
976 goto rleCode;
977 }
978 while (context_index < context_map_size) {
979 if (!SafeReadSymbol(s->context_map_table, br, &code)) {
980 s->code = 0xFFFF;
981 s->context_index = context_index;
982 return BROTLI_DECODER_NEEDS_MORE_INPUT;
983 }
984 BROTLI_LOG_UINT(code);
985
986 if (code == 0) {
987 context_map[context_index++] = 0;
988 continue;
989 }
990 if (code > max_run_length_prefix) {
991 context_map[context_index++] =
992 (uint8_t)(code - max_run_length_prefix);
993 continue;
994 }
995 rleCode:
996 {
997 uint32_t reps;
998 if (!BrotliSafeReadBits(br, code, &reps)) {
999 s->code = code;
1000 s->context_index = context_index;
1001 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1002 }
1003 reps += 1U << code;
1004 BROTLI_LOG_UINT(reps);
1005 if (context_index + reps > context_map_size) {
1006 return
1007 BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT);
1008 }
1009 do {
1010 context_map[context_index++] = 0;
1011 } while (--reps);
1012 }
1013 }
1014 /* No break, continue to next state. */
1015 }
1016 case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: {
1017 uint32_t bits;
1018 if (!BrotliSafeReadBits(br, 1, &bits)) {
1019 s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
1020 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1021 }
1022 if (bits != 0) {
1023 InverseMoveToFrontTransform(*context_map_arg, context_map_size, s);
1024 }
1025 s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
1026 return BROTLI_DECODER_SUCCESS;
1027 }
1028 default:
1029 return
1030 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
1031 }
1032 }
1033
1034 /* Decodes a command or literal and updates block type ringbuffer.
1035 Reads 3..54 bits. */
1036 static BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength(
1037 int safe, BrotliDecoderState* s, int tree_type) {
1038 uint32_t max_block_type = s->num_block_types[tree_type];
1039 const HuffmanCode* type_tree = &s->block_type_trees[
1040 tree_type * BROTLI_HUFFMAN_MAX_SIZE_258];
1041 const HuffmanCode* len_tree = &s->block_len_trees[
1042 tree_type * BROTLI_HUFFMAN_MAX_SIZE_26];
1043 BrotliBitReader* br = &s->br;
1044 uint32_t* ringbuffer = &s->block_type_rb[tree_type * 2];
1045 uint32_t block_type;
1046
1047 /* Read 0..15 + 3..39 bits */
1048 if (!safe) {
1049 block_type = ReadSymbol(type_tree, br);
1050 s->block_length[tree_type] = ReadBlockLength(len_tree, br);
1051 } else {
1052 BrotliBitReaderState memento;
1053 BrotliBitReaderSaveState(br, &memento);
1054 if (!SafeReadSymbol(type_tree, br, &block_type)) return BROTLI_FALSE;
1055 if (!SafeReadBlockLength(s, &s->block_length[tree_type], len_tree, br)) {
1056 s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
1057 BrotliBitReaderRestoreState(br, &memento);
1058 return BROTLI_FALSE;
1059 }
1060 }
1061
1062 if (block_type == 1) {
1063 block_type = ringbuffer[1] + 1;
1064 } else if (block_type == 0) {
1065 block_type = ringbuffer[0];
1066 } else {
1067 block_type -= 2;
1068 }
1069 if (block_type >= max_block_type) {
1070 block_type -= max_block_type;
1071 }
1072 ringbuffer[0] = ringbuffer[1];
1073 ringbuffer[1] = block_type;
1074 return BROTLI_TRUE;
1075 }
1076
1077 static BROTLI_INLINE void DetectTrivialLiteralBlockTypes(
1078 BrotliDecoderState* s) {
1079 size_t i;
1080 for (i = 0; i < 8; ++i) s->trivial_literal_contexts[i] = 0;
1081 for (i = 0; i < s->num_block_types[0]; i++) {
1082 size_t offset = i << BROTLI_LITERAL_CONTEXT_BITS;
1083 size_t error = 0;
1084 size_t sample = s->context_map[offset];
1085 size_t j;
1086 for (j = 0; j < (1u << BROTLI_LITERAL_CONTEXT_BITS);) {
1087 BROTLI_REPEAT(4, error |= s->context_map[offset + j++] ^ sample;)
1088 }
1089 if (error == 0) {
1090 s->trivial_literal_contexts[i >> 5] |= 1u << (i & 31);
1091 }
1092 }
1093 }
1094
1095 static BROTLI_INLINE void PrepareLiteralDecoding(BrotliDecoderState* s) {
1096 uint8_t context_mode;
1097 size_t trivial;
1098 uint32_t block_type = s->block_type_rb[1];
1099 uint32_t context_offset = block_type << BROTLI_LITERAL_CONTEXT_BITS;
1100 s->context_map_slice = s->context_map + context_offset;
1101 trivial = s->trivial_literal_contexts[block_type >> 5];
1102 s->trivial_literal_context = (trivial >> (block_type & 31)) & 1;
1103 s->literal_htree = s->literal_hgroup.htrees[s->context_map_slice[0]];
1104 context_mode = s->context_modes[block_type];
1105 s->context_lookup1 = &kContextLookup[kContextLookupOffsets[context_mode]];
1106 s->context_lookup2 = &kContextLookup[kContextLookupOffsets[context_mode + 1]];
1107 }
1108
1109 /* Decodes the block type and updates the state for literal context.
1110 Reads 3..54 bits. */
1111 static BROTLI_INLINE BROTLI_BOOL DecodeLiteralBlockSwitchInternal(
1112 int safe, BrotliDecoderState* s) {
1113 if (!DecodeBlockTypeAndLength(safe, s, 0)) {
1114 return BROTLI_FALSE;
1115 }
1116 PrepareLiteralDecoding(s);
1117 return BROTLI_TRUE;
1118 }
1119
1120 static void BROTLI_NOINLINE DecodeLiteralBlockSwitch(BrotliDecoderState* s) {
1121 DecodeLiteralBlockSwitchInternal(0, s);
1122 }
1123
1124 static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeLiteralBlockSwitch(
1125 BrotliDecoderState* s) {
1126 return DecodeLiteralBlockSwitchInternal(1, s);
1127 }
1128
1129 /* Block switch for insert/copy length.
1130 Reads 3..54 bits. */
1131 static BROTLI_INLINE BROTLI_BOOL DecodeCommandBlockSwitchInternal(
1132 int safe, BrotliDecoderState* s) {
1133 if (!DecodeBlockTypeAndLength(safe, s, 1)) {
1134 return BROTLI_FALSE;
1135 }
1136 s->htree_command = s->insert_copy_hgroup.htrees[s->block_type_rb[3]];
1137 return BROTLI_TRUE;
1138 }
1139
1140 static void BROTLI_NOINLINE DecodeCommandBlockSwitch(BrotliDecoderState* s) {
1141 DecodeCommandBlockSwitchInternal(0, s);
1142 }
1143 static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeCommandBlockSwitch(
1144 BrotliDecoderState* s) {
1145 return DecodeCommandBlockSwitchInternal(1, s);
1146 }
1147
1148 /* Block switch for distance codes.
1149 Reads 3..54 bits. */
1150 static BROTLI_INLINE BROTLI_BOOL DecodeDistanceBlockSwitchInternal(
1151 int safe, BrotliDecoderState* s) {
1152 if (!DecodeBlockTypeAndLength(safe, s, 2)) {
1153 return BROTLI_FALSE;
1154 }
1155 s->dist_context_map_slice = s->dist_context_map +
1156 (s->block_type_rb[5] << BROTLI_DISTANCE_CONTEXT_BITS);
1157 s->dist_htree_index = s->dist_context_map_slice[s->distance_context];
1158 return BROTLI_TRUE;
1159 }
1160
1161 static void BROTLI_NOINLINE DecodeDistanceBlockSwitch(BrotliDecoderState* s) {
1162 DecodeDistanceBlockSwitchInternal(0, s);
1163 }
1164
1165 static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeDistanceBlockSwitch(
1166 BrotliDecoderState* s) {
1167 return DecodeDistanceBlockSwitchInternal(1, s);
1168 }
1169
1170 static size_t UnwrittenBytes(const BrotliDecoderState* s, BROTLI_BOOL wrap) {
1171 size_t pos = wrap && s->pos > s->ringbuffer_size ?
1172 (size_t)s->ringbuffer_size : (size_t)(s->pos);
1173 size_t partial_pos_rb = (s->rb_roundtrips * (size_t)s->ringbuffer_size) + pos;
1174 return partial_pos_rb - s->partial_pos_out;
1175 }
1176
1177 static BrotliDecoderErrorCode BROTLI_NOINLINE WriteRingBuffer(
1178 BrotliDecoderState* s, size_t* available_out, uint8_t** next_out,
1179 size_t* total_out) {
1180 uint8_t* start =
1181 s->ringbuffer + (s->partial_pos_out & (size_t)s->ringbuffer_mask);
1182 size_t to_write = UnwrittenBytes(s, BROTLI_TRUE);
1183 size_t num_written = *available_out;
1184 if (num_written > to_write) {
1185 num_written = to_write;
1186 }
1187 if (s->meta_block_remaining_len < 0) {
1188 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1);
1189 }
1190 memcpy(*next_out, start, num_written);
1191 *next_out += num_written;
1192 *available_out -= num_written;
1193 BROTLI_LOG_UINT(to_write);
1194 BROTLI_LOG_UINT(num_written);
1195 s->partial_pos_out += num_written;
1196 if (total_out) *total_out = s->partial_pos_out;
1197 if (num_written < to_write) {
1198 return BROTLI_DECODER_NEEDS_MORE_OUTPUT;
1199 }
1200
1201 if (s->pos >= s->ringbuffer_size) {
1202 s->pos -= s->ringbuffer_size;
1203 s->rb_roundtrips++;
1204 }
1205 return BROTLI_DECODER_SUCCESS;
1206 }
1207
1208 /* Allocates ringbuffer.
1209
1210 s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
1211 this function is called.
1212
1213 Last two bytes of ringbuffer are initialized to 0, so context calculation
1214 could be done uniformly for the first two and all other positions.
1215
1216 Custom dictionary, if any, is copied to the end of ringbuffer.
1217 */
1218 static BROTLI_BOOL BROTLI_NOINLINE BrotliAllocateRingBuffer(
1219 BrotliDecoderState* s) {
1220 /* We need the slack region for the following reasons:
1221 - doing up to two 16-byte copies for fast backward copying
1222 - inserting transformed dictionary word (5 prefix + 24 base + 8 suffix) */
1223 static const int kRingBufferWriteAheadSlack = 42;
1224 s->ringbuffer = (uint8_t*)BROTLI_ALLOC(s, (size_t)(s->ringbuffer_size +
1225 kRingBufferWriteAheadSlack));
1226 if (s->ringbuffer == 0) {
1227 return BROTLI_FALSE;
1228 }
1229
1230 s->ringbuffer_end = s->ringbuffer + s->ringbuffer_size;
1231
1232 s->ringbuffer[s->ringbuffer_size - 2] = 0;
1233 s->ringbuffer[s->ringbuffer_size - 1] = 0;
1234
1235 if (s->custom_dict) {
1236 memcpy(&s->ringbuffer[(-s->custom_dict_size) & s->ringbuffer_mask],
1237 s->custom_dict, (size_t)s->custom_dict_size);
1238 }
1239
1240 return BROTLI_TRUE;
1241 }
1242
1243 static BrotliDecoderErrorCode BROTLI_NOINLINE CopyUncompressedBlockToOutput(
1244 size_t* available_out, uint8_t** next_out, size_t* total_out,
1245 BrotliDecoderState* s) {
1246 /* TODO: avoid allocation for single uncompressed block. */
1247 if (!s->ringbuffer && !BrotliAllocateRingBuffer(s)) {
1248 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1);
1249 }
1250
1251 /* State machine */
1252 for (;;) {
1253 switch (s->substate_uncompressed) {
1254 case BROTLI_STATE_UNCOMPRESSED_NONE: {
1255 int nbytes = (int)BrotliGetRemainingBytes(&s->br);
1256 if (nbytes > s->meta_block_remaining_len) {
1257 nbytes = s->meta_block_remaining_len;
1258 }
1259 if (s->pos + nbytes > s->ringbuffer_size) {
1260 nbytes = s->ringbuffer_size - s->pos;
1261 }
1262 /* Copy remaining bytes from s->br.buf_ to ringbuffer. */
1263 BrotliCopyBytes(&s->ringbuffer[s->pos], &s->br, (size_t)nbytes);
1264 s->pos += nbytes;
1265 s->meta_block_remaining_len -= nbytes;
1266 if (s->pos < s->ringbuffer_size) {
1267 if (s->meta_block_remaining_len == 0) {
1268 return BROTLI_DECODER_SUCCESS;
1269 }
1270 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1271 }
1272 s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_WRITE;
1273 /* No break, continue to next state */
1274 }
1275 case BROTLI_STATE_UNCOMPRESSED_WRITE: {
1276 BrotliDecoderErrorCode result =
1277 WriteRingBuffer(s, available_out, next_out, total_out);
1278 if (result != BROTLI_DECODER_SUCCESS) {
1279 return result;
1280 }
1281 s->max_distance = s->max_backward_distance;
1282 s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE;
1283 break;
1284 }
1285 }
1286 }
1287 BROTLI_DCHECK(0); /* Unreachable */
1288 }
1289
1290 BROTLI_BOOL BrotliDecompressedSize(size_t encoded_size,
1291 const uint8_t* encoded_buffer,
1292 size_t* decoded_size) {
1293 size_t total_size = 0;
1294 BrotliDecoderState s;
1295 BrotliBitReader* br;
1296 BrotliDecoderStateInit(&s);
1297 br = &s.br;
1298 *decoded_size = 0;
1299 br->next_in = encoded_buffer;
1300 br->avail_in = encoded_size;
1301 if (!BrotliWarmupBitReader(br)) return BROTLI_FALSE;
1302 DecodeWindowBits(br);
1303 while (1) {
1304 size_t block_size;
1305 if (DecodeMetaBlockLength(&s, br) != BROTLI_DECODER_SUCCESS) {
1306 return BROTLI_FALSE;
1307 }
1308 block_size = (size_t)s.meta_block_remaining_len;
1309 if (!s.is_metadata) {
1310 if ((block_size + total_size) < total_size) return BROTLI_FALSE;
1311 total_size += block_size;
1312 }
1313 if (s.is_last_metablock) {
1314 *decoded_size = total_size;
1315 return BROTLI_TRUE;
1316 }
1317 if (!s.is_uncompressed && !s.is_metadata) return BROTLI_FALSE;
1318 if (!BrotliJumpToByteBoundary(br)) return BROTLI_FALSE;
1319 BrotliBitReaderUnload(br);
1320 if (br->avail_in < block_size) return BROTLI_FALSE;
1321 br->avail_in -= block_size;
1322 br->next_in += block_size;
1323 if (!BrotliWarmupBitReader(br)) return BROTLI_FALSE;
1324 }
1325 }
1326
1327 /* Calculates the smallest feasible ring buffer.
1328
1329 If we know the data size is small, do not allocate more ringbuffer
1330 size than needed to reduce memory usage.
1331
1332 When this method is called, metablock size and flags MUST be decoded.
1333 */
1334 static void BROTLI_NOINLINE BrotliCalculateRingBufferSize(
1335 BrotliDecoderState* s, BrotliBitReader* br) {
1336 BROTLI_BOOL is_last = TO_BROTLI_BOOL(s->is_last_metablock);
1337 int window_size = 1 << s->window_bits;
1338 s->ringbuffer_size = window_size;
1339
1340 if (s->is_uncompressed) {
1341 int next_block_header =
1342 BrotliPeekByte(br, (size_t)s->meta_block_remaining_len);
1343 if (next_block_header != -1) { /* Peek succeeded */
1344 if ((next_block_header & 3) == 3) { /* ISLAST and ISEMPTY */
1345 is_last = BROTLI_TRUE;
1346 }
1347 }
1348 }
1349
1350 /* We need at least 2 bytes of ring buffer size to get the last two
1351 bytes for context from there */
1352 if (is_last) {
1353 int min_size_x2 = (s->meta_block_remaining_len + s->custom_dict_size) * 2;
1354 while (s->ringbuffer_size >= min_size_x2 && s->ringbuffer_size > 32) {
1355 s->ringbuffer_size >>= 1;
1356 }
1357 }
1358
1359 s->ringbuffer_mask = s->ringbuffer_size - 1;
1360 }
1361
1362 /* Reads 1..256 2-bit context modes. */
1363 static BrotliDecoderErrorCode ReadContextModes(BrotliDecoderState* s) {
1364 BrotliBitReader* br = &s->br;
1365 int i = s->loop_counter;
1366
1367 while (i < (int)s->num_block_types[0]) {
1368 uint32_t bits;
1369 if (!BrotliSafeReadBits(br, 2, &bits)) {
1370 s->loop_counter = i;
1371 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1372 }
1373 s->context_modes[i] = (uint8_t)(bits << 1);
1374 BROTLI_LOG_ARRAY_INDEX(s->context_modes, i);
1375 i++;
1376 }
1377 return BROTLI_DECODER_SUCCESS;
1378 }
1379
1380 static BROTLI_INLINE void TakeDistanceFromRingBuffer(BrotliDecoderState* s) {
1381 if (s->distance_code == 0) {
1382 --s->dist_rb_idx;
1383 s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
1384 } else {
1385 int distance_code = s->distance_code << 1;
1386 /* kDistanceShortCodeIndexOffset has 2-bit values from LSB: */
1387 /* 3, 2, 1, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2 */
1388 const uint32_t kDistanceShortCodeIndexOffset = 0xaaafff1b;
1389 /* kDistanceShortCodeValueOffset has 2-bit values from LSB: */
1390 /*-0, 0,-0, 0,-1, 1,-2, 2,-3, 3,-1, 1,-2, 2,-3, 3 */
1391 const uint32_t kDistanceShortCodeValueOffset = 0xfa5fa500;
1392 int v = (s->dist_rb_idx +
1393 (int)(kDistanceShortCodeIndexOffset >> distance_code)) & 0x3;
1394 s->distance_code = s->dist_rb[v];
1395 v = (int)(kDistanceShortCodeValueOffset >> distance_code) & 0x3;
1396 if ((distance_code & 0x3) != 0) {
1397 s->distance_code += v;
1398 } else {
1399 s->distance_code -= v;
1400 if (s->distance_code <= 0) {
1401 /* A huge distance will cause a BROTLI_FAILURE() soon. */
1402 /* This is a little faster than failing here. */
1403 s->distance_code = 0x0fffffff;
1404 }
1405 }
1406 }
1407 }
1408
1409 static BROTLI_INLINE BROTLI_BOOL SafeReadBits(
1410 BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
1411 if (n_bits != 0) {
1412 return BrotliSafeReadBits(br, n_bits, val);
1413 } else {
1414 *val = 0;
1415 return BROTLI_TRUE;
1416 }
1417 }
1418
1419 /* Precondition: s->distance_code < 0 */
1420 static BROTLI_INLINE BROTLI_BOOL ReadDistanceInternal(
1421 int safe, BrotliDecoderState* s, BrotliBitReader* br) {
1422 int distval;
1423 BrotliBitReaderState memento;
1424 HuffmanCode* distance_tree = s->distance_hgroup.htrees[s->dist_htree_index];
1425 if (!safe) {
1426 s->distance_code = (int)ReadSymbol(distance_tree, br);
1427 } else {
1428 uint32_t code;
1429 BrotliBitReaderSaveState(br, &memento);
1430 if (!SafeReadSymbol(distance_tree, br, &code)) {
1431 return BROTLI_FALSE;
1432 }
1433 s->distance_code = (int)code;
1434 }
1435 /* Convert the distance code to the actual distance by possibly */
1436 /* looking up past distances from the s->ringbuffer. */
1437 if ((s->distance_code & ~0xf) == 0) {
1438 TakeDistanceFromRingBuffer(s);
1439 --s->block_length[2];
1440 return BROTLI_TRUE;
1441 }
1442 distval = s->distance_code - (int)s->num_direct_distance_codes;
1443 if (distval >= 0) {
1444 uint32_t nbits;
1445 int postfix;
1446 int offset;
1447 if (!safe && (s->distance_postfix_bits == 0)) {
1448 nbits = ((uint32_t)distval >> 1) + 1;
1449 offset = ((2 + (distval & 1)) << nbits) - 4;
1450 s->distance_code = (int)s->num_direct_distance_codes + offset +
1451 (int)BrotliReadBits(br, nbits);
1452 } else {
1453 /* This branch also works well when s->distance_postfix_bits == 0 */
1454 uint32_t bits;
1455 postfix = distval & s->distance_postfix_mask;
1456 distval >>= s->distance_postfix_bits;
1457 nbits = ((uint32_t)distval >> 1) + 1;
1458 if (safe) {
1459 if (!SafeReadBits(br, nbits, &bits)) {
1460 s->distance_code = -1; /* Restore precondition. */
1461 BrotliBitReaderRestoreState(br, &memento);
1462 return BROTLI_FALSE;
1463 }
1464 } else {
1465 bits = BrotliReadBits(br, nbits);
1466 }
1467 offset = ((2 + (distval & 1)) << nbits) - 4;
1468 s->distance_code = (int)s->num_direct_distance_codes +
1469 ((offset + (int)bits) << s->distance_postfix_bits) + postfix;
1470 }
1471 }
1472 s->distance_code = s->distance_code - BROTLI_NUM_DISTANCE_SHORT_CODES + 1;
1473 --s->block_length[2];
1474 return BROTLI_TRUE;
1475 }
1476
1477 static BROTLI_INLINE void ReadDistance(
1478 BrotliDecoderState* s, BrotliBitReader* br) {
1479 ReadDistanceInternal(0, s, br);
1480 }
1481
1482 static BROTLI_INLINE BROTLI_BOOL SafeReadDistance(
1483 BrotliDecoderState* s, BrotliBitReader* br) {
1484 return ReadDistanceInternal(1, s, br);
1485 }
1486
1487 static BROTLI_INLINE BROTLI_BOOL ReadCommandInternal(
1488 int safe, BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
1489 uint32_t cmd_code;
1490 uint32_t insert_len_extra = 0;
1491 uint32_t copy_length;
1492 CmdLutElement v;
1493 BrotliBitReaderState memento;
1494 if (!safe) {
1495 cmd_code = ReadSymbol(s->htree_command, br);
1496 } else {
1497 BrotliBitReaderSaveState(br, &memento);
1498 if (!SafeReadSymbol(s->htree_command, br, &cmd_code)) {
1499 return BROTLI_FALSE;
1500 }
1501 }
1502 if (cmd_code >= BROTLI_NUM_COMMAND_SYMBOLS) cmd_code = BROTLI_NUM_COMMAND_SYMBOLS - 1;
1503 v = kCmdLut[cmd_code];
1504 s->distance_code = v.distance_code;
1505 s->distance_context = v.context;
1506 s->dist_htree_index = s->dist_context_map_slice[s->distance_context];
1507 *insert_length = v.insert_len_offset;
1508 if (!safe) {
1509 if (PREDICT_FALSE(v.insert_len_extra_bits != 0)) {
1510 insert_len_extra = BrotliReadBits(br, v.insert_len_extra_bits);
1511 }
1512 copy_length = BrotliReadBits(br, v.copy_len_extra_bits);
1513 } else {
1514 if (!SafeReadBits(br, v.insert_len_extra_bits, &insert_len_extra) ||
1515 !SafeReadBits(br, v.copy_len_extra_bits, &copy_length)) {
1516 BrotliBitReaderRestoreState(br, &memento);
1517 return BROTLI_FALSE;
1518 }
1519 }
1520 s->copy_length = (int)copy_length + v.copy_len_offset;
1521 --s->block_length[1];
1522 *insert_length += (int)insert_len_extra;
1523 return BROTLI_TRUE;
1524 }
1525
1526 static BROTLI_INLINE void ReadCommand(
1527 BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
1528 ReadCommandInternal(0, s, br, insert_length);
1529 }
1530
1531 static BROTLI_INLINE BROTLI_BOOL SafeReadCommand(
1532 BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
1533 return ReadCommandInternal(1, s, br, insert_length);
1534 }
1535
1536 static BROTLI_INLINE BROTLI_BOOL CheckInputAmount(
1537 int safe, BrotliBitReader* const br, size_t num) {
1538 if (safe) {
1539 return BROTLI_TRUE;
1540 }
1541 return BrotliCheckInputAmount(br, num);
1542 }
1543
1544 #define BROTLI_SAFE(METHOD) \
1545 { \
1546 if (safe) { \
1547 if (!Safe##METHOD) { \
1548 result = BROTLI_DECODER_NEEDS_MORE_INPUT; \
1549 goto saveStateAndReturn; \
1550 } \
1551 } else { \
1552 METHOD; \
1553 } \
1554 }
1555
1556 static BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal(
1557 int safe, BrotliDecoderState* s) {
1558 int pos = s->pos;
1559 int i = s->loop_counter;
1560 BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
1561 BrotliBitReader* br = &s->br;
1562
1563 if (!CheckInputAmount(safe, br, 28)) {
1564 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1565 goto saveStateAndReturn;
1566 }
1567 if (!safe) {
1568 BROTLI_UNUSED(BrotliWarmupBitReader(br));
1569 }
1570
1571 /* Jump into state machine. */
1572 if (s->state == BROTLI_STATE_COMMAND_BEGIN) {
1573 goto CommandBegin;
1574 } else if (s->state == BROTLI_STATE_COMMAND_INNER) {
1575 goto CommandInner;
1576 } else if (s->state == BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) {
1577 goto CommandPostDecodeLiterals;
1578 } else if (s->state == BROTLI_STATE_COMMAND_POST_WRAP_COPY) {
1579 goto CommandPostWrapCopy;
1580 } else {
1581 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
1582 }
1583
1584 CommandBegin:
1585 if (safe) {
1586 s->state = BROTLI_STATE_COMMAND_BEGIN;
1587 }
1588 if (!CheckInputAmount(safe, br, 28)) { /* 156 bits + 7 bytes */
1589 s->state = BROTLI_STATE_COMMAND_BEGIN;
1590 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1591 goto saveStateAndReturn;
1592 }
1593 if (PREDICT_FALSE(s->block_length[1] == 0)) {
1594 BROTLI_SAFE(DecodeCommandBlockSwitch(s));
1595 goto CommandBegin;
1596 }
1597 /* Read the insert/copy length in the command */
1598 BROTLI_SAFE(ReadCommand(s, br, &i));
1599 BROTLI_LOG(("[ProcessCommandsInternal] pos = %d insert = %d copy = %d\n",
1600 pos, i, s->copy_length));
1601 if (i == 0) {
1602 goto CommandPostDecodeLiterals;
1603 }
1604 s->meta_block_remaining_len -= i;
1605
1606 CommandInner:
1607 if (safe) {
1608 s->state = BROTLI_STATE_COMMAND_INNER;
1609 }
1610 /* Read the literals in the command */
1611 if (s->trivial_literal_context) {
1612 uint32_t bits;
1613 uint32_t value;
1614 PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
1615 do {
1616 if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */
1617 s->state = BROTLI_STATE_COMMAND_INNER;
1618 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1619 goto saveStateAndReturn;
1620 }
1621 if (PREDICT_FALSE(s->block_length[0] == 0)) {
1622 BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
1623 PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
1624 if (!s->trivial_literal_context) goto CommandInner;
1625 }
1626 if (!safe) {
1627 s->ringbuffer[pos] =
1628 (uint8_t)ReadPreloadedSymbol(s->literal_htree, br, &bits, &value);
1629 } else {
1630 uint32_t literal;
1631 if (!SafeReadSymbol(s->literal_htree, br, &literal)) {
1632 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1633 goto saveStateAndReturn;
1634 }
1635 s->ringbuffer[pos] = (uint8_t)literal;
1636 }
1637 --s->block_length[0];
1638 BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
1639 ++pos;
1640 if (PREDICT_FALSE(pos == s->ringbuffer_size)) {
1641 s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
1642 --i;
1643 goto saveStateAndReturn;
1644 }
1645 } while (--i != 0);
1646 } else {
1647 uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask];
1648 uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask];
1649 do {
1650 const HuffmanCode* hc;
1651 uint8_t context;
1652 if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */
1653 s->state = BROTLI_STATE_COMMAND_INNER;
1654 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1655 goto saveStateAndReturn;
1656 }
1657 if (PREDICT_FALSE(s->block_length[0] == 0)) {
1658 BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
1659 if (s->trivial_literal_context) goto CommandInner;
1660 }
1661 context = s->context_lookup1[p1] | s->context_lookup2[p2];
1662 BROTLI_LOG_UINT(context);
1663 hc = s->literal_hgroup.htrees[s->context_map_slice[context]];
1664 p2 = p1;
1665 if (!safe) {
1666 p1 = (uint8_t)ReadSymbol(hc, br);
1667 } else {
1668 uint32_t literal;
1669 if (!SafeReadSymbol(hc, br, &literal)) {
1670 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1671 goto saveStateAndReturn;
1672 }
1673 p1 = (uint8_t)literal;
1674 }
1675 s->ringbuffer[pos] = p1;
1676 --s->block_length[0];
1677 BROTLI_LOG_UINT(s->context_map_slice[context]);
1678 BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask);
1679 ++pos;
1680 if (PREDICT_FALSE(pos == s->ringbuffer_size)) {
1681 s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
1682 --i;
1683 goto saveStateAndReturn;
1684 }
1685 } while (--i != 0);
1686 }
1687 BROTLI_LOG_UINT(s->meta_block_remaining_len);
1688 if (PREDICT_FALSE(s->meta_block_remaining_len <= 0)) {
1689 s->state = BROTLI_STATE_METABLOCK_DONE;
1690 goto saveStateAndReturn;
1691 }
1692
1693 CommandPostDecodeLiterals:
1694 if (safe) {
1695 s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
1696 }
1697 if (s->distance_code >= 0) {
1698 --s->dist_rb_idx;
1699 s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
1700 goto postReadDistance; /* We already have the implicit distance */
1701 }
1702 /* Read distance code in the command, unless it was implicitly zero. */
1703 if (PREDICT_FALSE(s->block_length[2] == 0)) {
1704 BROTLI_SAFE(DecodeDistanceBlockSwitch(s));
1705 }
1706 BROTLI_SAFE(ReadDistance(s, br));
1707 postReadDistance:
1708 BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n",
1709 pos, s->distance_code));
1710 if (s->max_distance != s->max_backward_distance) {
1711 if (pos < s->max_backward_distance_minus_custom_dict_size) {
1712 s->max_distance = pos + s->custom_dict_size;
1713 } else {
1714 s->max_distance = s->max_backward_distance;
1715 }
1716 }
1717 i = s->copy_length;
1718 /* Apply copy of LZ77 back-reference, or static dictionary reference if
1719 the distance is larger than the max LZ77 distance */
1720 if (s->distance_code > s->max_distance) {
1721 if (i >= kBrotliMinDictionaryWordLength &&
1722 i <= kBrotliMaxDictionaryWordLength) {
1723 int offset = (int)kBrotliDictionaryOffsetsByLength[i];
1724 int word_id = s->distance_code - s->max_distance - 1;
1725 uint32_t shift = kBrotliDictionarySizeBitsByLength[i];
1726 int mask = (int)BitMask(shift);
1727 int word_idx = word_id & mask;
1728 int transform_idx = word_id >> shift;
1729 offset += word_idx * i;
1730 if (transform_idx < kNumTransforms) {
1731 const uint8_t* word = &kBrotliDictionary[offset];
1732 int len = i;
1733 if (transform_idx == 0) {
1734 memcpy(&s->ringbuffer[pos], word, (size_t)len);
1735 } else {
1736 len = TransformDictionaryWord(
1737 &s->ringbuffer[pos], word, len, transform_idx);
1738 }
1739 pos += len;
1740 s->meta_block_remaining_len -= len;
1741 if (pos >= s->ringbuffer_size) {
1742 /*s->partial_pos_rb += (size_t)s->ringbuffer_size;*/
1743 s->state = BROTLI_STATE_COMMAND_POST_WRITE_1;
1744 goto saveStateAndReturn;
1745 }
1746 } else {
1747 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
1748 "len: %d bytes left: %d\n",
1749 pos, s->distance_code, i, s->meta_block_remaining_len));
1750 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
1751 }
1752 } else {
1753 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
1754 "len: %d bytes left: %d\n",
1755 pos, s->distance_code, i, s->meta_block_remaining_len));
1756 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY);
1757 }
1758 } else {
1759 int src_start = (pos - s->distance_code) & s->ringbuffer_mask;
1760 uint8_t* copy_dst = &s->ringbuffer[pos];
1761 uint8_t* copy_src = &s->ringbuffer[src_start];
1762 int dst_end = pos + i;
1763 int src_end = src_start + i;
1764 /* update the recent distances cache */
1765 s->dist_rb[s->dist_rb_idx & 3] = s->distance_code;
1766 ++s->dist_rb_idx;
1767 s->meta_block_remaining_len -= i;
1768 /* There are 32+ bytes of slack in the ringbuffer allocation.
1769 Also, we have 16 short codes, that make these 16 bytes irrelevant
1770 in the ringbuffer. Let's copy over them as a first guess.
1771 */
1772 memmove16(copy_dst, copy_src);
1773 if (src_end > pos && dst_end > src_start) {
1774 /* Regions intersect. */
1775 goto CommandPostWrapCopy;
1776 }
1777 if (dst_end >= s->ringbuffer_size || src_end >= s->ringbuffer_size) {
1778 /* At least one region wraps. */
1779 goto CommandPostWrapCopy;
1780 }
1781 pos += i;
1782 if (i > 16) {
1783 if (i > 32) {
1784 memcpy(copy_dst + 16, copy_src + 16, (size_t)(i - 16));
1785 } else {
1786 /* This branch covers about 45% cases.
1787 Fixed size short copy allows more compiler optimizations. */
1788 memmove16(copy_dst + 16, copy_src + 16);
1789 }
1790 }
1791 }
1792 BROTLI_LOG_UINT(s->meta_block_remaining_len);
1793 if (s->meta_block_remaining_len <= 0) {
1794 /* Next metablock, if any */
1795 s->state = BROTLI_STATE_METABLOCK_DONE;
1796 goto saveStateAndReturn;
1797 } else {
1798 goto CommandBegin;
1799 }
1800 CommandPostWrapCopy:
1801 {
1802 int wrap_guard = s->ringbuffer_size - pos;
1803 while (--i >= 0) {
1804 s->ringbuffer[pos] =
1805 s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
1806 ++pos;
1807 if (PREDICT_FALSE(--wrap_guard == 0)) {
1808 s->state = BROTLI_STATE_COMMAND_POST_WRITE_2;
1809 goto saveStateAndReturn;
1810 }
1811 }
1812 }
1813 if (s->meta_block_remaining_len <= 0) {
1814 /* Next metablock, if any */
1815 s->state = BROTLI_STATE_METABLOCK_DONE;
1816 goto saveStateAndReturn;
1817 } else {
1818 goto CommandBegin;
1819 }
1820
1821 saveStateAndReturn:
1822 s->pos = pos;
1823 s->loop_counter = i;
1824 return result;
1825 }
1826
1827 #undef BROTLI_SAFE
1828
1829 static BROTLI_NOINLINE BrotliDecoderErrorCode ProcessCommands(
1830 BrotliDecoderState* s) {
1831 return ProcessCommandsInternal(0, s);
1832 }
1833
1834 static BROTLI_NOINLINE BrotliDecoderErrorCode SafeProcessCommands(
1835 BrotliDecoderState* s) {
1836 return ProcessCommandsInternal(1, s);
1837 }
1838
1839 BrotliDecoderResult BrotliDecoderDecompress(
1840 size_t encoded_size, const uint8_t* encoded_buffer, size_t* decoded_size,
1841 uint8_t* decoded_buffer) {
1842 BrotliDecoderState s;
1843 BrotliDecoderResult result;
1844 size_t total_out = 0;
1845 size_t available_in = encoded_size;
1846 const uint8_t* next_in = encoded_buffer;
1847 size_t available_out = *decoded_size;
1848 uint8_t* next_out = decoded_buffer;
1849 BrotliDecoderStateInit(&s);
1850 result = BrotliDecoderDecompressStream(
1851 &s, &available_in, &next_in, &available_out, &next_out, &total_out);
1852 *decoded_size = total_out;
1853 BrotliDecoderStateCleanup(&s);
1854 if (result != BROTLI_DECODER_RESULT_SUCCESS) {
1855 result = BROTLI_DECODER_RESULT_ERROR;
1856 }
1857 return result;
1858 }
1859
1860 /* Invariant: input stream is never overconsumed:
1861 * invalid input implies that the whole stream is invalid -> any amount of
1862 input could be read and discarded
1863 * when result is "needs more input", then at leat one more byte is REQUIRED
1864 to complete decoding; all input data MUST be consumed by decoder, so
1865 client could swap the input buffer
1866 * when result is "needs more output" decoder MUST ensure that it doesn't
1867 hold more than 7 bits in bit reader; this saves client from swapping input
1868 buffer ahead of time
1869 * when result is "success" decoder MUST return all unused data back to input
1870 buffer; this is possible because the invariant is hold on enter
1871 */
1872 BrotliDecoderResult BrotliDecoderDecompressStream(
1873 BrotliDecoderState* s, size_t* available_in, const uint8_t** next_in,
1874 size_t* available_out, uint8_t** next_out, size_t* total_out) {
1875 BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
1876 BrotliBitReader* br = &s->br;
1877 if (s->buffer_length == 0) { /* Just connect bit reader to input stream. */
1878 br->avail_in = *available_in;
1879 br->next_in = *next_in;
1880 } else {
1881 /* At least one byte of input is required. More than one byte of input may
1882 be required to complete the transaction -> reading more data must be
1883 done in a loop -> do it in a main loop. */
1884 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1885 br->next_in = &s->buffer.u8[0];
1886 }
1887 /* State machine */
1888 for (;;) {
1889 if (result != BROTLI_DECODER_SUCCESS) { /* Error, needs more input/output */
1890 if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
1891 if (s->ringbuffer != 0) { /* Proactively push output. */
1892 WriteRingBuffer(s, available_out, next_out, total_out);
1893 }
1894 if (s->buffer_length != 0) { /* Used with internal buffer. */
1895 if (br->avail_in == 0) { /* Successfully finished read transaction. */
1896 /* Accamulator contains less than 8 bits, because internal buffer
1897 is expanded byte-by-byte until it is enough to complete read. */
1898 s->buffer_length = 0;
1899 /* Switch to input stream and restart. */
1900 result = BROTLI_DECODER_SUCCESS;
1901 br->avail_in = *available_in;
1902 br->next_in = *next_in;
1903 continue;
1904 } else if (*available_in != 0) {
1905 /* Not enough data in buffer, but can take one more byte from
1906 input stream. */
1907 result = BROTLI_DECODER_SUCCESS;
1908 s->buffer.u8[s->buffer_length] = **next_in;
1909 s->buffer_length++;
1910 br->avail_in = s->buffer_length;
1911 (*next_in)++;
1912 (*available_in)--;
1913 /* Retry with more data in buffer. */
1914 continue;
1915 }
1916 /* Can't finish reading and no more input.*/
1917 break;
1918 } else { /* Input stream doesn't contain enough input. */
1919 /* Copy tail to internal buffer and return. */
1920 *next_in = br->next_in;
1921 *available_in = br->avail_in;
1922 while (*available_in) {
1923 s->buffer.u8[s->buffer_length] = **next_in;
1924 s->buffer_length++;
1925 (*next_in)++;
1926 (*available_in)--;
1927 }
1928 break;
1929 }
1930 /* Unreachable. */
1931 }
1932
1933 /* Fail or needs more output. */
1934
1935 if (s->buffer_length != 0) {
1936 /* Just consumed the buffered input and produced some output. Otherwise
1937 it would result in "needs more input". Reset internal buffer.*/
1938 s->buffer_length = 0;
1939 } else {
1940 /* Using input stream in last iteration. When decoder switches to input
1941 stream it has less than 8 bits in accamulator, so it is safe to
1942 return unused accamulator bits there. */
1943 BrotliBitReaderUnload(br);
1944 *available_in = br->avail_in;
1945 *next_in = br->next_in;
1946 }
1947 break;
1948 }
1949 switch (s->state) {
1950 case BROTLI_STATE_UNINITED:
1951 /* Prepare to the first read. */
1952 if (!BrotliWarmupBitReader(br)) {
1953 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1954 break;
1955 }
1956 /* Decode window size. */
1957 s->window_bits = DecodeWindowBits(br); /* Reads 1..7 bits. */
1958 BROTLI_LOG_UINT(s->window_bits);
1959 if (s->window_bits == 9) {
1960 /* Value 9 is reserved for future use. */
1961 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS);
1962 break;
1963 }
1964 /* Maximum distance, see section 9.1. of the spec. */
1965 s->max_backward_distance = (1 << s->window_bits) - 16;
1966 /* Limit custom dictionary size. */
1967 if (s->custom_dict_size >= s->max_backward_distance) {
1968 s->custom_dict += s->custom_dict_size - s->max_backward_distance;
1969 s->custom_dict_size = s->max_backward_distance;
1970 }
1971 s->max_backward_distance_minus_custom_dict_size =
1972 s->max_backward_distance - s->custom_dict_size;
1973
1974 /* Allocate memory for both block_type_trees and block_len_trees. */
1975 s->block_type_trees = (HuffmanCode*)BROTLI_ALLOC(s,
1976 sizeof(HuffmanCode) * 3 *
1977 (BROTLI_HUFFMAN_MAX_SIZE_258 + BROTLI_HUFFMAN_MAX_SIZE_26));
1978 if (s->block_type_trees == 0) {
1979 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES);
1980 break;
1981 }
1982 s->block_len_trees =
1983 s->block_type_trees + 3 * BROTLI_HUFFMAN_MAX_SIZE_258;
1984
1985 s->state = BROTLI_STATE_METABLOCK_BEGIN;
1986 /* No break, continue to next state */
1987 case BROTLI_STATE_METABLOCK_BEGIN:
1988 BrotliDecoderStateMetablockBegin(s);
1989 BROTLI_LOG_UINT(s->pos);
1990 s->state = BROTLI_STATE_METABLOCK_HEADER;
1991 /* No break, continue to next state */
1992 case BROTLI_STATE_METABLOCK_HEADER:
1993 result = DecodeMetaBlockLength(s, br); /* Reads 2 - 31 bits. */
1994 if (result != BROTLI_DECODER_SUCCESS) {
1995 break;
1996 }
1997 BROTLI_LOG_UINT(s->is_last_metablock);
1998 BROTLI_LOG_UINT(s->meta_block_remaining_len);
1999 BROTLI_LOG_UINT(s->is_metadata);
2000 BROTLI_LOG_UINT(s->is_uncompressed);
2001 if (s->is_metadata || s->is_uncompressed) {
2002 if (!BrotliJumpToByteBoundary(br)) {
2003 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1);
2004 break;
2005 }
2006 }
2007 if (s->is_metadata) {
2008 s->state = BROTLI_STATE_METADATA;
2009 break;
2010 }
2011 if (s->meta_block_remaining_len == 0) {
2012 s->state = BROTLI_STATE_METABLOCK_DONE;
2013 break;
2014 }
2015 if (!s->ringbuffer) {
2016 BrotliCalculateRingBufferSize(s, br);
2017 }
2018 if (s->is_uncompressed) {
2019 s->state = BROTLI_STATE_UNCOMPRESSED;
2020 break;
2021 }
2022 s->loop_counter = 0;
2023 s->state = BROTLI_STATE_HUFFMAN_CODE_0;
2024 break;
2025 case BROTLI_STATE_UNCOMPRESSED: {
2026 int bytes_copied = s->meta_block_remaining_len;
2027 result = CopyUncompressedBlockToOutput(
2028 available_out, next_out, total_out, s);
2029 bytes_copied -= s->meta_block_remaining_len;
2030 if (result != BROTLI_DECODER_SUCCESS) {
2031 break;
2032 }
2033 s->state = BROTLI_STATE_METABLOCK_DONE;
2034 break;
2035 }
2036 case BROTLI_STATE_METADATA:
2037 for (; s->meta_block_remaining_len > 0; --s->meta_block_remaining_len) {
2038 uint32_t bits;
2039 /* Read one byte and ignore it. */
2040 if (!BrotliSafeReadBits(br, 8, &bits)) {
2041 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2042 break;
2043 }
2044 }
2045 if (result == BROTLI_DECODER_SUCCESS) {
2046 s->state = BROTLI_STATE_METABLOCK_DONE;
2047 }
2048 break;
2049 case BROTLI_STATE_HUFFMAN_CODE_0:
2050 if (s->loop_counter >= 3) {
2051 s->state = BROTLI_STATE_METABLOCK_HEADER_2;
2052 break;
2053 }
2054 /* Reads 1..11 bits. */
2055 result = DecodeVarLenUint8(s, br, &s->num_block_types[s->loop_counter]);
2056 if (result != BROTLI_DECODER_SUCCESS) {
2057 break;
2058 }
2059 s->num_block_types[s->loop_counter]++;
2060 BROTLI_LOG_UINT(s->num_block_types[s->loop_counter]);
2061 if (s->num_block_types[s->loop_counter] < 2) {
2062 s->loop_counter++;
2063 break;
2064 }
2065 s->state = BROTLI_STATE_HUFFMAN_CODE_1;
2066 /* No break, continue to next state */
2067 case BROTLI_STATE_HUFFMAN_CODE_1: {
2068 int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_258;
2069 result = ReadHuffmanCode(s->num_block_types[s->loop_counter] + 2,
2070 &s->block_type_trees[tree_offset], NULL, s);
2071 if (result != BROTLI_DECODER_SUCCESS) break;
2072 s->state = BROTLI_STATE_HUFFMAN_CODE_2;
2073 /* No break, continue to next state */
2074 }
2075 case BROTLI_STATE_HUFFMAN_CODE_2: {
2076 int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26;
2077 result = ReadHuffmanCode(BROTLI_NUM_BLOCK_LEN_SYMBOLS,
2078 &s->block_len_trees[tree_offset], NULL, s);
2079 if (result != BROTLI_DECODER_SUCCESS) break;
2080 s->state = BROTLI_STATE_HUFFMAN_CODE_3;
2081 /* No break, continue to next state */
2082 }
2083 case BROTLI_STATE_HUFFMAN_CODE_3: {
2084 int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26;
2085 if (!SafeReadBlockLength(s, &s->block_length[s->loop_counter],
2086 &s->block_len_trees[tree_offset], br)) {
2087 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2088 break;
2089 }
2090 BROTLI_LOG_UINT(s->block_length[s->loop_counter]);
2091 s->loop_counter++;
2092 s->state = BROTLI_STATE_HUFFMAN_CODE_0;
2093 break;
2094 }
2095 case BROTLI_STATE_METABLOCK_HEADER_2: {
2096 uint32_t bits;
2097 if (!BrotliSafeReadBits(br, 6, &bits)) {
2098 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2099 break;
2100 }
2101 s->distance_postfix_bits = bits & BitMask(2);
2102 bits >>= 2;
2103 s->num_direct_distance_codes = BROTLI_NUM_DISTANCE_SHORT_CODES +
2104 (bits << s->distance_postfix_bits);
2105 BROTLI_LOG_UINT(s->num_direct_distance_codes);
2106 BROTLI_LOG_UINT(s->distance_postfix_bits);
2107 s->distance_postfix_mask = (int)BitMask(s->distance_postfix_bits);
2108 s->context_modes =
2109 (uint8_t*)BROTLI_ALLOC(s, (size_t)s->num_block_types[0]);
2110 if (s->context_modes == 0) {
2111 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES);
2112 break;
2113 }
2114 s->loop_counter = 0;
2115 s->state = BROTLI_STATE_CONTEXT_MODES;
2116 /* No break, continue to next state */
2117 }
2118 case BROTLI_STATE_CONTEXT_MODES:
2119 result = ReadContextModes(s);
2120 if (result != BROTLI_DECODER_SUCCESS) {
2121 break;
2122 }
2123 s->state = BROTLI_STATE_CONTEXT_MAP_1;
2124 /* No break, continue to next state */
2125 case BROTLI_STATE_CONTEXT_MAP_1:
2126 result = DecodeContextMap(
2127 s->num_block_types[0] << BROTLI_LITERAL_CONTEXT_BITS,
2128 &s->num_literal_htrees, &s->context_map, s);
2129 if (result != BROTLI_DECODER_SUCCESS) {
2130 break;
2131 }
2132 DetectTrivialLiteralBlockTypes(s);
2133 s->state = BROTLI_STATE_CONTEXT_MAP_2;
2134 /* No break, continue to next state */
2135 case BROTLI_STATE_CONTEXT_MAP_2:
2136 {
2137 uint32_t num_distance_codes =
2138 s->num_direct_distance_codes + (48U << s->distance_postfix_bits);
2139 result = DecodeContextMap(
2140 s->num_block_types[2] << BROTLI_DISTANCE_CONTEXT_BITS,
2141 &s->num_dist_htrees, &s->dist_context_map, s);
2142 if (result != BROTLI_DECODER_SUCCESS) {
2143 break;
2144 }
2145 BrotliDecoderHuffmanTreeGroupInit(
2146 s, &s->literal_hgroup, BROTLI_NUM_LITERAL_SYMBOLS,
2147 s->num_literal_htrees);
2148 BrotliDecoderHuffmanTreeGroupInit(
2149 s, &s->insert_copy_hgroup, BROTLI_NUM_COMMAND_SYMBOLS,
2150 s->num_block_types[1]);
2151 BrotliDecoderHuffmanTreeGroupInit(
2152 s, &s->distance_hgroup, num_distance_codes,
2153 s->num_dist_htrees);
2154 if (s->literal_hgroup.codes == 0 ||
2155 s->insert_copy_hgroup.codes == 0 ||
2156 s->distance_hgroup.codes == 0) {
2157 return SaveErrorCode(s,
2158 BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS));
2159 }
2160 }
2161 s->loop_counter = 0;
2162 s->state = BROTLI_STATE_TREE_GROUP;
2163 /* No break, continue to next state */
2164 case BROTLI_STATE_TREE_GROUP:
2165 {
2166 HuffmanTreeGroup* hgroup = NULL;
2167 switch (s->loop_counter) {
2168 case 0:
2169 hgroup = &s->literal_hgroup;
2170 break;
2171 case 1:
2172 hgroup = &s->insert_copy_hgroup;
2173 break;
2174 case 2:
2175 hgroup = &s->distance_hgroup;
2176 break;
2177 default:
2178 return SaveErrorCode(s, BROTLI_FAILURE(
2179 BROTLI_DECODER_ERROR_UNREACHABLE));
2180 }
2181 result = HuffmanTreeGroupDecode(hgroup, s);
2182 }
2183 if (result != BROTLI_DECODER_SUCCESS) break;
2184 s->loop_counter++;
2185 if (s->loop_counter >= 3) {
2186 PrepareLiteralDecoding(s);
2187 s->dist_context_map_slice = s->dist_context_map;
2188 s->htree_command = s->insert_copy_hgroup.htrees[0];
2189 if (!s->ringbuffer && !BrotliAllocateRingBuffer(s)) {
2190 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
2191 break;
2192 }
2193 s->state = BROTLI_STATE_COMMAND_BEGIN;
2194 }
2195 break;
2196 case BROTLI_STATE_COMMAND_BEGIN:
2197 case BROTLI_STATE_COMMAND_INNER:
2198 case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS:
2199 case BROTLI_STATE_COMMAND_POST_WRAP_COPY:
2200 result = ProcessCommands(s);
2201 if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
2202 result = SafeProcessCommands(s);
2203 }
2204 break;
2205 case BROTLI_STATE_COMMAND_INNER_WRITE:
2206 case BROTLI_STATE_COMMAND_POST_WRITE_1:
2207 case BROTLI_STATE_COMMAND_POST_WRITE_2:
2208 result = WriteRingBuffer(s, available_out, next_out, total_out);
2209 if (result != BROTLI_DECODER_SUCCESS) {
2210 break;
2211 }
2212 s->max_distance = s->max_backward_distance;
2213 if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) {
2214 if (s->ringbuffer != 0) {
2215 memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos);
2216 }
2217 if (s->meta_block_remaining_len == 0) {
2218 /* Next metablock, if any */
2219 s->state = BROTLI_STATE_METABLOCK_DONE;
2220 } else {
2221 s->state = BROTLI_STATE_COMMAND_BEGIN;
2222 }
2223 break;
2224 } else if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_2) {
2225 s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY;
2226 } else { /* BROTLI_STATE_COMMAND_INNER_WRITE */
2227 if (s->loop_counter == 0) {
2228 if (s->meta_block_remaining_len == 0) {
2229 s->state = BROTLI_STATE_METABLOCK_DONE;
2230 } else {
2231 s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2232 }
2233 break;
2234 }
2235 s->state = BROTLI_STATE_COMMAND_INNER;
2236 }
2237 break;
2238 case BROTLI_STATE_METABLOCK_DONE:
2239 if (s->meta_block_remaining_len < 0) {
2240 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2);
2241 break;
2242 }
2243 BrotliDecoderStateCleanupAfterMetablock(s);
2244 if (!s->is_last_metablock) {
2245 s->state = BROTLI_STATE_METABLOCK_BEGIN;
2246 break;
2247 }
2248 if (!BrotliJumpToByteBoundary(br)) {
2249 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2);
2250 break;
2251 }
2252 if (s->buffer_length == 0) {
2253 BrotliBitReaderUnload(br);
2254 *available_in = br->avail_in;
2255 *next_in = br->next_in;
2256 }
2257 s->state = BROTLI_STATE_DONE;
2258 /* No break, continue to next state */
2259 case BROTLI_STATE_DONE:
2260 if (s->ringbuffer != 0) {
2261 result = WriteRingBuffer(s, available_out, next_out, total_out);
2262 if (result != BROTLI_DECODER_SUCCESS) {
2263 break;
2264 }
2265 }
2266 return SaveErrorCode(s, result);
2267 }
2268 }
2269 return SaveErrorCode(s, result);
2270 }
2271
2272 void BrotliDecoderSetCustomDictionary(
2273 BrotliDecoderState* s, size_t size, const uint8_t* dict) {
2274 if (size > (1u << 24)) {
2275 return;
2276 }
2277 s->custom_dict = dict;
2278 s->custom_dict_size = (int)size;
2279 }
2280
2281 BROTLI_BOOL BrotliDecoderHasMoreOutput(const BrotliDecoderState* s) {
2282 return TO_BROTLI_BOOL(
2283 s->ringbuffer != 0 && UnwrittenBytes(s, BROTLI_FALSE) != 0);
2284 }
2285
2286 BROTLI_BOOL BrotliDecoderIsUsed(const BrotliDecoderState* s) {
2287 return TO_BROTLI_BOOL(s->state != BROTLI_STATE_UNINITED ||
2288 BrotliGetAvailableBits(&s->br) != 0);
2289 }
2290
2291 BROTLI_BOOL BrotliDecoderIsFinished(const BrotliDecoderState* s) {
2292 return TO_BROTLI_BOOL(s->state == BROTLI_STATE_DONE);
2293 }
2294
2295 BrotliDecoderErrorCode BrotliDecoderGetErrorCode(const BrotliDecoderState* s) {
2296 return (BrotliDecoderErrorCode)s->error_code;
2297 }
2298
2299 const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c) {
2300 switch (c) {
2301 #define _BROTLI_ERROR_CODE_CASE(PREFIX, NAME, CODE) \
2302 case BROTLI_DECODER ## PREFIX ## NAME: return #NAME;
2303 #define _BROTLI_NOTHING
2304 BROTLI_DECODER_ERROR_CODES_LIST(_BROTLI_ERROR_CODE_CASE, _BROTLI_NOTHING)
2305 #undef _BROTLI_ERROR_CODE_CASE
2306 #undef _BROTLI_NOTHING
2307 default: return "INVALID";
2308 }
2309 }
2310
2311 /* DEPRECATED >>> */
2312 BrotliState* BrotliCreateState(
2313 brotli_alloc_func alloc, brotli_free_func free, void* opaque) {
2314 return (BrotliState*)BrotliDecoderCreateInstance(alloc, free, opaque);
2315 }
2316 void BrotliDestroyState(BrotliState* state) {
2317 BrotliDecoderDestroyInstance((BrotliDecoderState*)state);
2318 }
2319 BrotliResult BrotliDecompressBuffer(
2320 size_t encoded_size, const uint8_t* encoded_buffer, size_t* decoded_size,
2321 uint8_t* decoded_buffer) {
2322 return (BrotliResult)BrotliDecoderDecompress(
2323 encoded_size, encoded_buffer, decoded_size, decoded_buffer);
2324 }
2325 BrotliResult BrotliDecompressStream(
2326 size_t* available_in, const uint8_t** next_in, size_t* available_out,
2327 uint8_t** next_out, size_t* total_out, BrotliState* s) {
2328 return (BrotliResult)BrotliDecoderDecompressStream((BrotliDecoderState*)s,
2329 available_in, next_in, available_out, next_out, total_out);
2330 }
2331 void BrotliSetCustomDictionary(
2332 size_t size, const uint8_t* dict, BrotliState* s) {
2333 BrotliDecoderSetCustomDictionary((BrotliDecoderState*)s, size, dict);
2334 }
2335 BROTLI_BOOL BrotliStateIsStreamStart(const BrotliState* s) {
2336 return !BrotliDecoderIsUsed((const BrotliDecoderState*)s);
2337 }
2338 BROTLI_BOOL BrotliStateIsStreamEnd(const BrotliState* s) {
2339 return BrotliDecoderIsFinished((const BrotliDecoderState*)s);
2340 }
2341 BrotliErrorCode BrotliGetErrorCode(const BrotliState* s) {
2342 return (BrotliErrorCode)BrotliDecoderGetErrorCode(
2343 (const BrotliDecoderState*)s);
2344 }
2345 const char* BrotliErrorString(BrotliErrorCode c) {
2346 return BrotliDecoderErrorString((BrotliDecoderErrorCode)c);
2347 }
2348 /* <<< DEPRECATED */
2349
2350 #if defined(__cplusplus) || defined(c_plusplus)
2351 } /* extern "C" */
2352 #endif