Bug Summary

File:root/firefox-clang/obj-x86_64-pc-linux-gnu/modules/brotli/./../../../modules/brotli/dec/decode.c
Warning:line 2242, column 15
Value stored to 'dict_id' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -O2 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Unified_c_modules_brotli0.c -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/modules/brotli -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/modules/brotli -resource-dir /usr/lib/llvm-23/lib/clang/23 -include /root/firefox-clang/config/gcc_hidden.h -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -I /root/firefox-clang/modules/brotli -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/modules/brotli -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -D BROTLI_BUILD_PORTABLE -internal-isystem /usr/lib/llvm-23/lib/clang/23/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-error=tautological-type-limit-compare -Wno-range-loop-analysis -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-unknown-warning-option -Wno-character-conversion -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fdiagnostics-absolute-paths -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -mllvm -dwarf-linkage-names=Abstract -faddrsig -fdwarf2-cfi-asm -o /tmp/scan-build-2026-09-01-224014-2642839-1 -x c Unified_c_modules_brotli0.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 <brotli/decode.h>
8
9#include "../common/constants.h"
10#include "../common/context.h"
11#include "../common/dictionary.h"
12#include "../common/platform.h"
13#include "../common/shared_dictionary_internal.h"
14#include "../common/transform.h"
15#include "../common/version.h"
16#include "bit_reader.h"
17#include "huffman.h"
18#include "prefix.h"
19#include "state.h"
20#include "static_init.h"
21
22#if defined(BROTLI_TARGET_NEON)
23#include <arm_neon.h>
24#endif
25
26#if defined(__cplusplus) || defined(c_plusplus)
27extern "C" {
28#endif
29
30#define BROTLI_FAILURE(CODE)((void)(0), CODE) (BROTLI_DUMP()(void)(0), CODE)
31
32#define BROTLI_LOG_UINT(name) \
33 BROTLI_LOG(("[%s] %s = %lu\n", __func__, #name, (unsigned long)(name)))
34#define BROTLI_LOG_ARRAY_INDEX(array_name, idx) \
35 BROTLI_LOG(("[%s] %s[%lu] = %lu\n", __func__, #array_name, \
36 (unsigned long)(idx), (unsigned long)array_name[idx]))
37
38#define HUFFMAN_TABLE_BITS8U 8U
39#define HUFFMAN_TABLE_MASK0xFF 0xFF
40
41/* We need the slack region for the following reasons:
42 - doing up to two 16-byte copies for fast backward copying
43 - inserting transformed dictionary word:
44 255 prefix + 32 base + 255 suffix */
45static const brotli_reg_tuint64_t kRingBufferWriteAheadSlack = 542;
46
47static const BROTLI_MODEL("small")__attribute__((model("small")))
48uint8_t kCodeLengthCodeOrder[BROTLI_CODE_LENGTH_CODES(17 + 1)] = {
49 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15,
50};
51
52/* Static prefix code for the complex code length code lengths. */
53static const BROTLI_MODEL("small")__attribute__((model("small")))
54uint8_t kCodeLengthPrefixLength[16] = {
55 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4,
56};
57
58static const BROTLI_MODEL("small")__attribute__((model("small")))
59uint8_t kCodeLengthPrefixValue[16] = {
60 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5,
61};
62
63BROTLI_BOOLint BrotliDecoderSetParameter(
64 BrotliDecoderStateBrotliDecoderStateInternal* state, BrotliDecoderParameter p, uint32_t value) {
65 if (state->state != BROTLI_STATE_UNINITED) return BROTLI_FALSE0;
66 switch (p) {
67 case BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:
68 state->canny_ringbuffer_allocation = !!value ? 0 : 1;
69 return BROTLI_TRUE1;
70
71 case BROTLI_DECODER_PARAM_LARGE_WINDOW:
72 state->large_window = TO_BROTLI_BOOL(!!value)(!!(!!value) ? 1 : 0);
73 return BROTLI_TRUE1;
74
75 default: return BROTLI_FALSE0;
76 }
77}
78
79BrotliDecoderStateBrotliDecoderStateInternal* BrotliDecoderCreateInstance(
80 brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
81 BrotliDecoderStateBrotliDecoderStateInternal* state = 0;
82 if (!BrotliDecoderEnsureStaticInit()) {
83 BROTLI_DUMP()(void)(0);
84 return 0;
85 }
86 if (!alloc_func && !free_func) {
87 state = (BrotliDecoderStateBrotliDecoderStateInternal*)malloc(sizeof(BrotliDecoderStateBrotliDecoderStateInternal));
88 } else if (alloc_func && free_func) {
89 state = (BrotliDecoderStateBrotliDecoderStateInternal*)alloc_func(opaque, sizeof(BrotliDecoderStateBrotliDecoderStateInternal));
90 }
91 if (state == 0) {
92 BROTLI_DUMP()(void)(0);
93 return 0;
94 }
95 if (!BrotliDecoderStateInit(state, alloc_func, free_func, opaque)) {
96 BROTLI_DUMP()(void)(0);
97 if (!alloc_func && !free_func) {
98 free(state);
99 } else if (alloc_func && free_func) {
100 free_func(opaque, state);
101 }
102 return 0;
103 }
104 return state;
105}
106
107/* Deinitializes and frees BrotliDecoderState instance. */
108void BrotliDecoderDestroyInstance(BrotliDecoderStateBrotliDecoderStateInternal* state) {
109 if (!state) {
110 return;
111 } else {
112 brotli_free_func free_func = state->free_func;
113 void* opaque = state->memory_manager_opaque;
114 BrotliDecoderStateCleanup(state);
115 free_func(opaque, state);
116 }
117}
118
119/* Saves error code and converts it to BrotliDecoderResult. */
120static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderResult SaveErrorCode(
121 BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliDecoderErrorCode e, size_t consumed_input) {
122 s->error_code = (int)e;
123 s->used_input += consumed_input;
124 if ((s->buffer_length != 0) && (s->br.next_in == s->br.last_in)) {
125 /* If internal buffer is depleted at last, reset it. */
126 s->buffer_length = 0;
127 }
128 switch (e) {
129 case BROTLI_DECODER_SUCCESS:
130 return BROTLI_DECODER_RESULT_SUCCESS;
131
132 case BROTLI_DECODER_NEEDS_MORE_INPUT:
133 return BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
134
135 case BROTLI_DECODER_NEEDS_MORE_OUTPUT:
136 return BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
137
138 default:
139 return BROTLI_DECODER_RESULT_ERROR;
140 }
141}
142
143/* Decodes WBITS by reading 1 - 7 bits, or 0x11 for "Large Window Brotli".
144 Precondition: bit-reader accumulator has at least 8 bits. */
145static BrotliDecoderErrorCode DecodeWindowBits(BrotliDecoderStateBrotliDecoderStateInternal* s,
146 BrotliBitReader* br) {
147 brotli_reg_tuint64_t n;
148 BROTLI_BOOLint large_window = s->large_window;
149 s->large_window = BROTLI_FALSE0;
150 BrotliTakeBits(br, 1, &n);
151 if (n == 0) {
152 s->window_bits = 16;
153 return BROTLI_DECODER_SUCCESS;
154 }
155 BrotliTakeBits(br, 3, &n);
156 if (n != 0) {
157 s->window_bits = (17u + n) & 63u;
158 return BROTLI_DECODER_SUCCESS;
159 }
160 BrotliTakeBits(br, 3, &n);
161 if (n == 1) {
162 if (large_window) {
163 BrotliTakeBits(br, 1, &n);
164 if (n == 1) {
165 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS)((void)(0), BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS);
166 }
167 s->large_window = BROTLI_TRUE1;
168 return BROTLI_DECODER_SUCCESS;
169 } else {
170 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS)((void)(0), BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS);
171 }
172 }
173 if (n != 0) {
174 s->window_bits = (8u + n) & 63u;
175 return BROTLI_DECODER_SUCCESS;
176 }
177 s->window_bits = 17;
178 return BROTLI_DECODER_SUCCESS;
179}
180
181static BROTLI_INLINEinline __attribute__((__always_inline__)) void memmove16(uint8_t* dst, uint8_t* src) {
182#if defined(BROTLI_TARGET_NEON)
183 vst1q_u8(dst, vld1q_u8(src));
184#else
185 uint32_t buffer[4];
186 memcpy(buffer, src, 16);
187 memcpy(dst, buffer, 16);
188#endif
189}
190
191/* Decodes a number in the range [0..255], by reading 1 - 11 bits. */
192static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderErrorCode DecodeVarLenUint8(
193 BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliBitReader* br, brotli_reg_tuint64_t* value) {
194 brotli_reg_tuint64_t bits;
195 switch (s->substate_decode_uint8) {
196 case BROTLI_STATE_DECODE_UINT8_NONE:
197 if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 1, &bits))(__builtin_expect(!BrotliSafeReadBits(br, 1, &bits), 0))) {
198 return BROTLI_DECODER_NEEDS_MORE_INPUT;
199 }
200 if (bits == 0) {
201 *value = 0;
202 return BROTLI_DECODER_SUCCESS;
203 }
204 /* Fall through. */
205
206 case BROTLI_STATE_DECODE_UINT8_SHORT:
207 if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 3, &bits))(__builtin_expect(!BrotliSafeReadBits(br, 3, &bits), 0))) {
208 s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_SHORT;
209 return BROTLI_DECODER_NEEDS_MORE_INPUT;
210 }
211 if (bits == 0) {
212 *value = 1;
213 s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
214 return BROTLI_DECODER_SUCCESS;
215 }
216 /* Use output value as a temporary storage. It MUST be persisted. */
217 *value = bits;
218 /* Fall through. */
219
220 case BROTLI_STATE_DECODE_UINT8_LONG:
221 if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, *value, &bits))(__builtin_expect(!BrotliSafeReadBits(br, *value, &bits),
0))
) {
222 s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_LONG;
223 return BROTLI_DECODER_NEEDS_MORE_INPUT;
224 }
225 *value = ((brotli_reg_tuint64_t)1U << *value) + bits;
226 s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
227 return BROTLI_DECODER_SUCCESS;
228
229 default:
230 return
231 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE)((void)(0), BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */
232 }
233}
234
235/* Decodes a metablock length and flags by reading 2 - 31 bits. */
236static BrotliDecoderErrorCode BROTLI_NOINLINE__attribute__((__noinline__)) DecodeMetaBlockLength(
237 BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliBitReader* br) {
238 brotli_reg_tuint64_t bits;
239 int i;
240 for (;;) {
241 switch (s->substate_metablock_header) {
242 case BROTLI_STATE_METABLOCK_HEADER_NONE:
243 if (!BrotliSafeReadBits(br, 1, &bits)) {
244 return BROTLI_DECODER_NEEDS_MORE_INPUT;
245 }
246 s->is_last_metablock = bits ? 1 : 0;
247 s->meta_block_remaining_len = 0;
248 s->is_uncompressed = 0;
249 s->is_metadata = 0;
250 if (!s->is_last_metablock) {
251 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
252 break;
253 }
254 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_EMPTY;
255 /* Fall through. */
256
257 case BROTLI_STATE_METABLOCK_HEADER_EMPTY:
258 if (!BrotliSafeReadBits(br, 1, &bits)) {
259 return BROTLI_DECODER_NEEDS_MORE_INPUT;
260 }
261 if (bits) {
262 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
263 return BROTLI_DECODER_SUCCESS;
264 }
265 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
266 /* Fall through. */
267
268 case BROTLI_STATE_METABLOCK_HEADER_NIBBLES:
269 if (!BrotliSafeReadBits(br, 2, &bits)) {
270 return BROTLI_DECODER_NEEDS_MORE_INPUT;
271 }
272 s->size_nibbles = (uint8_t)(bits + 4);
273 s->loop_counter = 0;
274 if (bits == 3) {
275 s->is_metadata = 1;
276 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_RESERVED;
277 break;
278 }
279 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_SIZE;
280 /* Fall through. */
281
282 case BROTLI_STATE_METABLOCK_HEADER_SIZE:
283 i = s->loop_counter;
284 for (; i < (int)s->size_nibbles; ++i) {
285 if (!BrotliSafeReadBits(br, 4, &bits)) {
286 s->loop_counter = i;
287 return BROTLI_DECODER_NEEDS_MORE_INPUT;
288 }
289 if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 4 &&
290 bits == 0) {
291 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE)((void)(0), BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE);
292 }
293 s->meta_block_remaining_len |= (int)(bits << (i * 4));
294 }
295 s->substate_metablock_header =
296 BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED;
297 /* Fall through. */
298
299 case BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED:
300 if (!s->is_last_metablock) {
301 if (!BrotliSafeReadBits(br, 1, &bits)) {
302 return BROTLI_DECODER_NEEDS_MORE_INPUT;
303 }
304 s->is_uncompressed = bits ? 1 : 0;
305 }
306 ++s->meta_block_remaining_len;
307 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
308 return BROTLI_DECODER_SUCCESS;
309
310 case BROTLI_STATE_METABLOCK_HEADER_RESERVED:
311 if (!BrotliSafeReadBits(br, 1, &bits)) {
312 return BROTLI_DECODER_NEEDS_MORE_INPUT;
313 }
314 if (bits != 0) {
315 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_RESERVED)((void)(0), BROTLI_DECODER_ERROR_FORMAT_RESERVED);
316 }
317 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_BYTES;
318 /* Fall through. */
319
320 case BROTLI_STATE_METABLOCK_HEADER_BYTES:
321 if (!BrotliSafeReadBits(br, 2, &bits)) {
322 return BROTLI_DECODER_NEEDS_MORE_INPUT;
323 }
324 if (bits == 0) {
325 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
326 return BROTLI_DECODER_SUCCESS;
327 }
328 s->size_nibbles = (uint8_t)bits;
329 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_METADATA;
330 /* Fall through. */
331
332 case BROTLI_STATE_METABLOCK_HEADER_METADATA:
333 i = s->loop_counter;
334 for (; i < (int)s->size_nibbles; ++i) {
335 if (!BrotliSafeReadBits(br, 8, &bits)) {
336 s->loop_counter = i;
337 return BROTLI_DECODER_NEEDS_MORE_INPUT;
338 }
339 if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 1 &&
340 bits == 0) {
341 return BROTLI_FAILURE(((void)(0), BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE
)
342 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE)((void)(0), BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE
)
;
343 }
344 s->meta_block_remaining_len |= (int)(bits << (i * 8));
345 }
346 ++s->meta_block_remaining_len;
347 s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
348 return BROTLI_DECODER_SUCCESS;
349
350 default:
351 return
352 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE)((void)(0), BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */
353 }
354 }
355}
356
357/* Decodes the Huffman code.
358 This method doesn't read data from the bit reader, BUT drops the amount of
359 bits that correspond to the decoded symbol.
360 bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits. */
361static BROTLI_INLINEinline __attribute__((__always_inline__)) brotli_reg_tuint64_t DecodeSymbol(brotli_reg_tuint64_t bits,
362 const HuffmanCode* table,
363 BrotliBitReader* br) {
364 BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
365 BROTLI_HC_ADJUST_TABLE_INDEX(table, bits & HUFFMAN_TABLE_MASK)table += (bits & 0xFF);
366 if (BROTLI_HC_FAST_LOAD_BITS(table)(table->bits) > HUFFMAN_TABLE_BITS8U) {
367 brotli_reg_tuint64_t nbits = BROTLI_HC_FAST_LOAD_BITS(table)(table->bits) - HUFFMAN_TABLE_BITS8U;
368 BrotliDropBits(br, HUFFMAN_TABLE_BITS8U);
369 BROTLI_HC_ADJUST_TABLE_INDEX(table,table += ((table->value) + ((bits >> 8U) & BitMask
(nbits)))
370 BROTLI_HC_FAST_LOAD_VALUE(table) +table += ((table->value) + ((bits >> 8U) & BitMask
(nbits)))
371 ((bits >> HUFFMAN_TABLE_BITS) & BitMask(nbits)))table += ((table->value) + ((bits >> 8U) & BitMask
(nbits)))
;
372 }
373 BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table)(table->bits));
374 return BROTLI_HC_FAST_LOAD_VALUE(table)(table->value);
375}
376
377/* Reads and decodes the next Huffman code from bit-stream.
378 This method peeks 16 bits of input and drops 0 - 15 of them. */
379static BROTLI_INLINEinline __attribute__((__always_inline__)) brotli_reg_tuint64_t ReadSymbol(const HuffmanCode* table,
380 BrotliBitReader* br) {
381 return DecodeSymbol(BrotliGet16BitsUnmasked(br), table, br);
382}
383
384/* Same as DecodeSymbol, but it is known that there is less than 15 bits of
385 input are currently available. */
386static BROTLI_NOINLINE__attribute__((__noinline__)) BROTLI_BOOLint SafeDecodeSymbol(
387 const HuffmanCode* table, BrotliBitReader* br, brotli_reg_tuint64_t* result) {
388 brotli_reg_tuint64_t val;
389 brotli_reg_tuint64_t available_bits = BrotliGetAvailableBits(br);
390 BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
391 if (available_bits == 0) {
392 if (BROTLI_HC_FAST_LOAD_BITS(table)(table->bits) == 0) {
393 *result = BROTLI_HC_FAST_LOAD_VALUE(table)(table->value);
394 return BROTLI_TRUE1;
395 }
396 return BROTLI_FALSE0; /* No valid bits at all. */
397 }
398 val = BrotliGetBitsUnmasked(br);
399 BROTLI_HC_ADJUST_TABLE_INDEX(table, val & HUFFMAN_TABLE_MASK)table += (val & 0xFF);
400 if (BROTLI_HC_FAST_LOAD_BITS(table)(table->bits) <= HUFFMAN_TABLE_BITS8U) {
401 if (BROTLI_HC_FAST_LOAD_BITS(table)(table->bits) <= available_bits) {
402 BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table)(table->bits));
403 *result = BROTLI_HC_FAST_LOAD_VALUE(table)(table->value);
404 return BROTLI_TRUE1;
405 } else {
406 return BROTLI_FALSE0; /* Not enough bits for the first level. */
407 }
408 }
409 if (available_bits <= HUFFMAN_TABLE_BITS8U) {
410 return BROTLI_FALSE0; /* Not enough bits to move to the second level. */
411 }
412
413 /* Speculatively drop HUFFMAN_TABLE_BITS. */
414 val = (val & BitMask(BROTLI_HC_FAST_LOAD_BITS(table)(table->bits))) >> HUFFMAN_TABLE_BITS8U;
415 available_bits -= HUFFMAN_TABLE_BITS8U;
416 BROTLI_HC_ADJUST_TABLE_INDEX(table, BROTLI_HC_FAST_LOAD_VALUE(table) + val)table += ((table->value) + val);
417 if (available_bits < BROTLI_HC_FAST_LOAD_BITS(table)(table->bits)) {
418 return BROTLI_FALSE0; /* Not enough bits for the second level. */
419 }
420
421 BrotliDropBits(br, HUFFMAN_TABLE_BITS8U + BROTLI_HC_FAST_LOAD_BITS(table)(table->bits));
422 *result = BROTLI_HC_FAST_LOAD_VALUE(table)(table->value);
423 return BROTLI_TRUE1;
424}
425
426static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint SafeReadSymbol(
427 const HuffmanCode* table, BrotliBitReader* br, brotli_reg_tuint64_t* result) {
428 brotli_reg_tuint64_t val;
429 if (BROTLI_PREDICT_TRUE(BrotliSafeGetBits(br, 15, &val))(__builtin_expect(!!(BrotliSafeGetBits(br, 15, &val)), 1)
)
) {
430 *result = DecodeSymbol(val, table, br);
431 return BROTLI_TRUE1;
432 }
433 return SafeDecodeSymbol(table, br, result);
434}
435
436/* Makes a look-up in first level Huffman table. Peeks 8 bits. */
437static BROTLI_INLINEinline __attribute__((__always_inline__)) void PreloadSymbol(int safe,
438 const HuffmanCode* table,
439 BrotliBitReader* br,
440 brotli_reg_tuint64_t* bits,
441 brotli_reg_tuint64_t* value) {
442 if (safe) {
443 return;
444 }
445 BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
446 BROTLI_HC_ADJUST_TABLE_INDEX(table, BrotliGetBits(br, HUFFMAN_TABLE_BITS))table += (BrotliGetBits(br, 8U));
447 *bits = BROTLI_HC_FAST_LOAD_BITS(table)(table->bits);
448 *value = BROTLI_HC_FAST_LOAD_VALUE(table)(table->value);
449}
450
451/* Decodes the next Huffman code using data prepared by PreloadSymbol.
452 Reads 0 - 15 bits. Also peeks 8 following bits. */
453static BROTLI_INLINEinline __attribute__((__always_inline__)) brotli_reg_tuint64_t ReadPreloadedSymbol(const HuffmanCode* table,
454 BrotliBitReader* br,
455 brotli_reg_tuint64_t* bits,
456 brotli_reg_tuint64_t* value) {
457 brotli_reg_tuint64_t result = *value;
458 if (BROTLI_PREDICT_FALSE(*bits > HUFFMAN_TABLE_BITS)(__builtin_expect(*bits > 8U, 0))) {
459 brotli_reg_tuint64_t val = BrotliGet16BitsUnmasked(br);
460 const HuffmanCode* ext = table + (val & HUFFMAN_TABLE_MASK0xFF) + *value;
461 brotli_reg_tuint64_t mask = BitMask((*bits - HUFFMAN_TABLE_BITS8U));
462 BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(ext);
463 BrotliDropBits(br, HUFFMAN_TABLE_BITS8U);
464 BROTLI_HC_ADJUST_TABLE_INDEX(ext, (val >> HUFFMAN_TABLE_BITS) & mask)ext += ((val >> 8U) & mask);
465 BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(ext)(ext->bits));
466 result = BROTLI_HC_FAST_LOAD_VALUE(ext)(ext->value);
467 } else {
468 BrotliDropBits(br, *bits);
469 }
470 PreloadSymbol(0, table, br, bits, value);
471 return result;
472}
473
474/* Reads up to limit symbols from br and copies them into ringbuffer,
475 starting from pos. Caller must ensure that there is enough space
476 for the write. Returns the amount of symbols actually copied. */
477static BROTLI_INLINEinline __attribute__((__always_inline__)) int BrotliCopyPreloadedSymbolsToU8(const HuffmanCode* table,
478 BrotliBitReader* br,
479 brotli_reg_tuint64_t* bits,
480 brotli_reg_tuint64_t* value,
481 uint8_t* ringbuffer,
482 int pos,
483 const int limit) {
484 /* Calculate range where CheckInputAmount is always true.
485 Start with the number of bytes we can read. */
486 int64_t new_lim = br->guard_in - br->next_in;
487 /* Convert to bits, since symbols use variable number of bits. */
488 new_lim *= 8;
489 /* At most 15 bits per symbol, so this is safe. */
490 new_lim /= 15;
491 const int kMaximalOverread = 4;
492 int pos_limit = limit;
493 int copies = 0;
494 if ((new_lim - kMaximalOverread) <= limit) {
495 // Safe cast, since new_lim is already < num_steps
496 pos_limit = (int)(new_lim - kMaximalOverread);
497 }
498 if (pos_limit < 0) {
499 pos_limit = 0;
500 }
501 copies = pos_limit;
502 pos_limit += pos;
503 /* Fast path, caller made sure it is safe to write,
504 we verified that is is safe to read. */
505 for (; pos < pos_limit; pos++) {
506 BROTLI_DCHECK(BrotliCheckInputAmount(br));
507 ringbuffer[pos] = (uint8_t)ReadPreloadedSymbol(table, br, bits, value);
508 BROTLI_LOG_ARRAY_INDEX(ringbuffer, pos);
509 }
510 /* Do the remainder, caller made sure it is safe to write,
511 we need to bverify that it is safe to read. */
512 while (BrotliCheckInputAmount(br) && copies < limit) {
513 ringbuffer[pos] = (uint8_t)ReadPreloadedSymbol(table, br, bits, value);
514 BROTLI_LOG_ARRAY_INDEX(ringbuffer, pos);
515 pos++;
516 copies++;
517 }
518 return copies;
519}
520
521static BROTLI_INLINEinline __attribute__((__always_inline__)) brotli_reg_tuint64_t Log2Floor(brotli_reg_tuint64_t x) {
522 brotli_reg_tuint64_t result = 0;
523 while (x) {
524 x >>= 1;
525 ++result;
526 }
527 return result;
528}
529
530/* Reads (s->symbol + 1) symbols.
531 Totally 1..4 symbols are read, 1..11 bits each.
532 The list of symbols MUST NOT contain duplicates. */
533static BrotliDecoderErrorCode ReadSimpleHuffmanSymbols(
534 brotli_reg_tuint64_t alphabet_size_max, brotli_reg_tuint64_t alphabet_size_limit,
535 BrotliDecoderStateBrotliDecoderStateInternal* s) {
536 /* max_bits == 1..11; symbol == 0..3; 1..44 bits will be read. */
537 BrotliBitReader* br = &s->br;
538 BrotliMetablockHeaderArena* h = &s->arena.header;
539 brotli_reg_tuint64_t max_bits = Log2Floor(alphabet_size_max - 1);
540 brotli_reg_tuint64_t i = h->sub_loop_counter;
541 brotli_reg_tuint64_t num_symbols = h->symbol;
542 while (i <= num_symbols) {
543 brotli_reg_tuint64_t v;
544 if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))(__builtin_expect(!BrotliSafeReadBits(br, max_bits, &v), 0
))
) {
545 h->sub_loop_counter = i;
546 h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ;
547 return BROTLI_DECODER_NEEDS_MORE_INPUT;
548 }
549 if (v >= alphabet_size_limit) {
550 return
551 BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET)((void)(0), BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET
)
;
552 }
553 h->symbols_lists_array[i] = (uint16_t)v;
554 BROTLI_LOG_UINT(h->symbols_lists_array[i]);
555 ++i;
556 }
557
558 for (i = 0; i < num_symbols; ++i) {
559 brotli_reg_tuint64_t k = i + 1;
560 for (; k <= num_symbols; ++k) {
561 if (h->symbols_lists_array[i] == h->symbols_lists_array[k]) {
562 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME)((void)(0), BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME);
563 }
564 }
565 }
566
567 return BROTLI_DECODER_SUCCESS;
568}
569
570/* Process single decoded symbol code length:
571 A) reset the repeat variable
572 B) remember code length (if it is not 0)
573 C) extend corresponding index-chain
574 D) reduce the Huffman space
575 E) update the histogram */
576static BROTLI_INLINEinline __attribute__((__always_inline__)) void ProcessSingleCodeLength(brotli_reg_tuint64_t code_len,
577 brotli_reg_tuint64_t* symbol, brotli_reg_tuint64_t* repeat, brotli_reg_tuint64_t* space,
578 brotli_reg_tuint64_t* prev_code_len, uint16_t* symbol_lists,
579 uint16_t* code_length_histo, int* next_symbol) {
580 *repeat = 0;
581 if (code_len != 0) { /* code_len == 1..15 */
582 symbol_lists[next_symbol[code_len]] = (uint16_t)(*symbol);
583 next_symbol[code_len] = (int)(*symbol);
584 *prev_code_len = code_len;
585 *space -= 32768U >> code_len;
586 code_length_histo[code_len]++;
587 BROTLI_LOG(("[ReadHuffmanCode] code_length[%d] = %d\n",
588 (int)*symbol, (int)code_len));
589 }
590 (*symbol)++;
591}
592
593/* Process repeated symbol code length.
594 A) Check if it is the extension of previous repeat sequence; if the decoded
595 value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new
596 symbol-skip
597 B) Update repeat variable
598 C) Check if operation is feasible (fits alphabet)
599 D) For each symbol do the same operations as in ProcessSingleCodeLength
600
601 PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or
602 code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH */
603static BROTLI_INLINEinline __attribute__((__always_inline__)) void ProcessRepeatedCodeLength(brotli_reg_tuint64_t code_len,
604 brotli_reg_tuint64_t repeat_delta, brotli_reg_tuint64_t alphabet_size, brotli_reg_tuint64_t* symbol,
605 brotli_reg_tuint64_t* repeat, brotli_reg_tuint64_t* space, brotli_reg_tuint64_t* prev_code_len,
606 brotli_reg_tuint64_t* repeat_code_len, uint16_t* symbol_lists,
607 uint16_t* code_length_histo, int* next_symbol) {
608 brotli_reg_tuint64_t old_repeat;
609 brotli_reg_tuint64_t extra_bits = 3; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
610 brotli_reg_tuint64_t new_len = 0; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
611 if (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH16) {
612 new_len = *prev_code_len;
613 extra_bits = 2;
614 }
615 if (*repeat_code_len != new_len) {
616 *repeat = 0;
617 *repeat_code_len = new_len;
618 }
619 old_repeat = *repeat;
620 if (*repeat > 0) {
621 *repeat -= 2;
622 *repeat <<= extra_bits;
623 }
624 *repeat += repeat_delta + 3U;
625 repeat_delta = *repeat - old_repeat;
626 if (*symbol + repeat_delta > alphabet_size) {
627 BROTLI_DUMP()(void)(0);
628 *symbol = alphabet_size;
629 *space = 0xFFFFF;
630 return;
631 }
632 BROTLI_LOG(("[ReadHuffmanCode] code_length[%d..%d] = %d\n",
633 (int)*symbol, (int)(*symbol + repeat_delta - 1), (int)*repeat_code_len));
634 if (*repeat_code_len != 0) {
635 brotli_reg_tuint64_t last = *symbol + repeat_delta;
636 int next = next_symbol[*repeat_code_len];
637 do {
638 symbol_lists[next] = (uint16_t)*symbol;
639 next = (int)*symbol;
640 } while (++(*symbol) != last);
641 next_symbol[*repeat_code_len] = next;
642 *space -= repeat_delta << (15 - *repeat_code_len);
643 code_length_histo[*repeat_code_len] =
644 (uint16_t)(code_length_histo[*repeat_code_len] + repeat_delta);
645 } else {
646 *symbol += repeat_delta;
647 }
648}
649
650/* Reads and decodes symbol codelengths. */
651static BrotliDecoderErrorCode ReadSymbolCodeLengths(
652 brotli_reg_tuint64_t alphabet_size, BrotliDecoderStateBrotliDecoderStateInternal* s) {
653 BrotliBitReader* br = &s->br;
654 BrotliMetablockHeaderArena* h = &s->arena.header;
655 brotli_reg_tuint64_t symbol = h->symbol;
656 brotli_reg_tuint64_t repeat = h->repeat;
657 brotli_reg_tuint64_t space = h->space;
658 brotli_reg_tuint64_t prev_code_len = h->prev_code_len;
659 brotli_reg_tuint64_t repeat_code_len = h->repeat_code_len;
660 uint16_t* symbol_lists = h->symbol_lists;
661 uint16_t* code_length_histo = h->code_length_histo;
662 int* next_symbol = h->next_symbol;
663 if (!BrotliWarmupBitReader(br)) {
664 return BROTLI_DECODER_NEEDS_MORE_INPUT;
665 }
666 while (symbol < alphabet_size && space > 0) {
667 const HuffmanCode* p = h->table;
668 brotli_reg_tuint64_t code_len;
669 BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p);
670 if (!BrotliCheckInputAmount(br)) {
671 h->symbol = symbol;
672 h->repeat = repeat;
673 h->prev_code_len = prev_code_len;
674 h->repeat_code_len = repeat_code_len;
675 h->space = space;
676 return BROTLI_DECODER_NEEDS_MORE_INPUT;
677 }
678 BrotliFillBitWindow16(br);
679 BROTLI_HC_ADJUST_TABLE_INDEX(p, BrotliGetBitsUnmasked(br) &p += (BrotliGetBitsUnmasked(br) & BitMask(5))
680 BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH))p += (BrotliGetBitsUnmasked(br) & BitMask(5));
681 BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p)(p->bits)); /* Use 1..5 bits. */
682 code_len = BROTLI_HC_FAST_LOAD_VALUE(p)(p->value); /* code_len == 0..17 */
683 if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH16) {
684 ProcessSingleCodeLength(code_len, &symbol, &repeat, &space,
685 &prev_code_len, symbol_lists, code_length_histo, next_symbol);
686 } else { /* code_len == 16..17, extra_bits == 2..3 */
687 brotli_reg_tuint64_t extra_bits =
688 (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH16) ? 2 : 3;
689 brotli_reg_tuint64_t repeat_delta =
690 BrotliGetBitsUnmasked(br) & BitMask(extra_bits);
691 BrotliDropBits(br, extra_bits);
692 ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
693 &symbol, &repeat, &space, &prev_code_len, &repeat_code_len,
694 symbol_lists, code_length_histo, next_symbol);
695 }
696 }
697 h->space = space;
698 return BROTLI_DECODER_SUCCESS;
699}
700
701static BrotliDecoderErrorCode SafeReadSymbolCodeLengths(
702 brotli_reg_tuint64_t alphabet_size, BrotliDecoderStateBrotliDecoderStateInternal* s) {
703 BrotliBitReader* br = &s->br;
704 BrotliMetablockHeaderArena* h = &s->arena.header;
705 BROTLI_BOOLint get_byte = BROTLI_FALSE0;
706 while (h->symbol < alphabet_size && h->space > 0) {
707 const HuffmanCode* p = h->table;
708 brotli_reg_tuint64_t code_len;
709 brotli_reg_tuint64_t available_bits;
710 brotli_reg_tuint64_t bits = 0;
711 BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p);
712 if (get_byte && !BrotliPullByte(br)) return BROTLI_DECODER_NEEDS_MORE_INPUT;
713 get_byte = BROTLI_FALSE0;
714 available_bits = BrotliGetAvailableBits(br);
715 if (available_bits != 0) {
716 bits = (uint32_t)BrotliGetBitsUnmasked(br);
717 }
718 BROTLI_HC_ADJUST_TABLE_INDEX(p,p += (bits & BitMask(5))
719 bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH))p += (bits & BitMask(5));
720 if (BROTLI_HC_FAST_LOAD_BITS(p)(p->bits) > available_bits) {
721 get_byte = BROTLI_TRUE1;
722 continue;
723 }
724 code_len = BROTLI_HC_FAST_LOAD_VALUE(p)(p->value); /* code_len == 0..17 */
725 if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH16) {
726 BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p)(p->bits));
727 ProcessSingleCodeLength(code_len, &h->symbol, &h->repeat, &h->space,
728 &h->prev_code_len, h->symbol_lists, h->code_length_histo,
729 h->next_symbol);
730 } else { /* code_len == 16..17, extra_bits == 2..3 */
731 brotli_reg_tuint64_t extra_bits = code_len - 14U;
732 brotli_reg_tuint64_t repeat_delta = (bits >> BROTLI_HC_FAST_LOAD_BITS(p)(p->bits)) &
733 BitMask(extra_bits);
734 if (available_bits < BROTLI_HC_FAST_LOAD_BITS(p)(p->bits) + extra_bits) {
735 get_byte = BROTLI_TRUE1;
736 continue;
737 }
738 BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p)(p->bits) + extra_bits);
739 ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
740 &h->symbol, &h->repeat, &h->space, &h->prev_code_len,
741 &h->repeat_code_len, h->symbol_lists, h->code_length_histo,
742 h->next_symbol);
743 }
744 }
745 return BROTLI_DECODER_SUCCESS;
746}
747
748/* Reads and decodes 15..18 codes using static prefix code.
749 Each code is 2..4 bits long. In total 30..72 bits are used. */
750static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderStateBrotliDecoderStateInternal* s) {
751 BrotliBitReader* br = &s->br;
752 BrotliMetablockHeaderArena* h = &s->arena.header;
753 brotli_reg_tuint64_t num_codes = h->repeat;
754 brotli_reg_tuint64_t space = h->space;
755 brotli_reg_tuint64_t i = h->sub_loop_counter;
756 for (; i < BROTLI_CODE_LENGTH_CODES(17 + 1); ++i) {
757 const uint8_t code_len_idx = kCodeLengthCodeOrder[i];
758 brotli_reg_tuint64_t ix;
759 brotli_reg_tuint64_t v;
760 if (BROTLI_PREDICT_FALSE(!BrotliSafeGetBits(br, 4, &ix))(__builtin_expect(!BrotliSafeGetBits(br, 4, &ix), 0))) {
761 brotli_reg_tuint64_t available_bits = BrotliGetAvailableBits(br);
762 if (available_bits != 0) {
763 ix = BrotliGetBitsUnmasked(br) & 0xF;
764 } else {
765 ix = 0;
766 }
767 if (kCodeLengthPrefixLength[ix] > available_bits) {
768 h->sub_loop_counter = i;
769 h->repeat = num_codes;
770 h->space = space;
771 h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
772 return BROTLI_DECODER_NEEDS_MORE_INPUT;
773 }
774 }
775 v = kCodeLengthPrefixValue[ix];
776 BrotliDropBits(br, kCodeLengthPrefixLength[ix]);
777 h->code_length_code_lengths[code_len_idx] = (uint8_t)v;
778 BROTLI_LOG_ARRAY_INDEX(h->code_length_code_lengths, code_len_idx);
779 if (v != 0) {
780 space = space - (32U >> v);
781 ++num_codes;
782 ++h->code_length_histo[v];
783 if (space - 1U >= 32U) {
784 /* space is 0 or wrapped around. */
785 break;
786 }
787 }
788 }
789 if (!(num_codes == 1 || space == 0)) {
790 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CL_SPACE)((void)(0), BROTLI_DECODER_ERROR_FORMAT_CL_SPACE);
791 }
792 return BROTLI_DECODER_SUCCESS;
793}
794
795/* Decodes the Huffman tables.
796 There are 2 scenarios:
797 A) Huffman code contains only few symbols (1..4). Those symbols are read
798 directly; their code lengths are defined by the number of symbols.
799 For this scenario 4 - 49 bits will be read.
800
801 B) 2-phase decoding:
802 B.1) Small Huffman table is decoded; it is specified with code lengths
803 encoded with predefined entropy code. 32 - 74 bits are used.
804 B.2) Decoded table is used to decode code lengths of symbols in resulting
805 Huffman table. In worst case 3520 bits are read. */
806static BrotliDecoderErrorCode ReadHuffmanCode(brotli_reg_tuint64_t alphabet_size_max,
807 brotli_reg_tuint64_t alphabet_size_limit,
808 HuffmanCode* table,
809 brotli_reg_tuint64_t* opt_table_size,
810 BrotliDecoderStateBrotliDecoderStateInternal* s) {
811 BrotliBitReader* br = &s->br;
812 BrotliMetablockHeaderArena* h = &s->arena.header;
813 /* State machine. */
814 for (;;) {
815 switch (h->substate_huffman) {
816 case BROTLI_STATE_HUFFMAN_NONE:
817 if (!BrotliSafeReadBits(br, 2, &h->sub_loop_counter)) {
818 return BROTLI_DECODER_NEEDS_MORE_INPUT;
819 }
820 BROTLI_LOG_UINT(h->sub_loop_counter);
821 /* The value is used as follows:
822 1 for simple code;
823 0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
824 if (h->sub_loop_counter != 1) {
825 h->space = 32;
826 h->repeat = 0; /* num_codes */
827 memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo[0]) *
828 (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH5 + 1));
829 memset(&h->code_length_code_lengths[0], 0,
830 sizeof(h->code_length_code_lengths));
831 h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
832 continue;
833 }
834 /* Fall through. */
835
836 case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE:
837 /* Read symbols, codes & code lengths directly. */
838 if (!BrotliSafeReadBits(br, 2, &h->symbol)) { /* num_symbols */
839 h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
840 return BROTLI_DECODER_NEEDS_MORE_INPUT;
841 }
842 h->sub_loop_counter = 0;
843 /* Fall through. */
844
845 case BROTLI_STATE_HUFFMAN_SIMPLE_READ: {
846 BrotliDecoderErrorCode result =
847 ReadSimpleHuffmanSymbols(alphabet_size_max, alphabet_size_limit, s);
848 if (result != BROTLI_DECODER_SUCCESS) {
849 return result;
850 }
851 }
852 /* Fall through. */
853
854 case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: {
855 brotli_reg_tuint64_t table_size;
856 if (h->symbol == 3) {
857 brotli_reg_tuint64_t bits;
858 if (!BrotliSafeReadBits(br, 1, &bits)) {
859 h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
860 return BROTLI_DECODER_NEEDS_MORE_INPUT;
861 }
862 h->symbol += bits;
863 }
864 BROTLI_LOG_UINT(h->symbol);
865 table_size = BrotliBuildSimpleHuffmanTable(table, HUFFMAN_TABLE_BITS8U,
866 h->symbols_lists_array,
867 (uint32_t)h->symbol);
868 if (opt_table_size) {
869 *opt_table_size = table_size;
870 }
871 h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
872 return BROTLI_DECODER_SUCCESS;
873 }
874
875 /* Decode Huffman-coded code lengths. */
876 case BROTLI_STATE_HUFFMAN_COMPLEX: {
877 brotli_reg_tuint64_t i;
878 BrotliDecoderErrorCode result = ReadCodeLengthCodeLengths(s);
879 if (result != BROTLI_DECODER_SUCCESS) {
880 return result;
881 }
882 BrotliBuildCodeLengthsHuffmanTable(h->table,
883 h->code_length_code_lengths,
884 h->code_length_histo);
885 memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo));
886 for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH15; ++i) {
887 h->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH15 + 1);
888 h->symbol_lists[h->next_symbol[i]] = 0xFFFF;
889 }
890
891 h->symbol = 0;
892 h->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH8;
893 h->repeat = 0;
894 h->repeat_code_len = 0;
895 h->space = 32768;
896 h->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
897 }
898 /* Fall through. */
899
900 case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: {
901 brotli_reg_tuint64_t table_size;
902 BrotliDecoderErrorCode result = ReadSymbolCodeLengths(
903 alphabet_size_limit, s);
904 if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
905 result = SafeReadSymbolCodeLengths(alphabet_size_limit, s);
906 }
907 if (result != BROTLI_DECODER_SUCCESS) {
908 return result;
909 }
910
911 if (h->space != 0) {
912 BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", (int)h->space));
913 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE)((void)(0), BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE);
914 }
915 table_size = BrotliBuildHuffmanTable(
916 table, HUFFMAN_TABLE_BITS8U, h->symbol_lists, h->code_length_histo);
917 if (opt_table_size) {
918 *opt_table_size = table_size;
919 }
920 h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
921 return BROTLI_DECODER_SUCCESS;
922 }
923
924 default:
925 return
926 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE)((void)(0), BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */
927 }
928 }
929}
930
931/* Decodes a block length by reading 3..39 bits. */
932static BROTLI_INLINEinline __attribute__((__always_inline__)) brotli_reg_tuint64_t ReadBlockLength(const HuffmanCode* table,
933 BrotliBitReader* br) {
934 brotli_reg_tuint64_t code;
935 brotli_reg_tuint64_t nbits;
936 code = ReadSymbol(table, br);
937 nbits = _kBrotliPrefixCodeRanges[code].nbits; /* nbits == 2..24 */
938 return _kBrotliPrefixCodeRanges[code].offset + BrotliReadBits24(br, nbits);
939}
940
941/* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
942 reading can't be continued with ReadBlockLength. */
943static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint SafeReadBlockLength(
944 BrotliDecoderStateBrotliDecoderStateInternal* s, brotli_reg_tuint64_t* result, const HuffmanCode* table,
945 BrotliBitReader* br) {
946 brotli_reg_tuint64_t index;
947 if (s->substate_read_block_length == BROTLI_STATE_READ_BLOCK_LENGTH_NONE) {
948 if (!SafeReadSymbol(table, br, &index)) {
949 return BROTLI_FALSE0;
950 }
951 } else {
952 index = s->block_length_index;
953 }
954 {
955 brotli_reg_tuint64_t bits;
956 brotli_reg_tuint64_t nbits = _kBrotliPrefixCodeRanges[index].nbits;
957 brotli_reg_tuint64_t offset = _kBrotliPrefixCodeRanges[index].offset;
958 if (!BrotliSafeReadBits(br, nbits, &bits)) {
959 s->block_length_index = index;
960 s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX;
961 return BROTLI_FALSE0;
962 }
963 *result = offset + bits;
964 s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
965 return BROTLI_TRUE1;
966 }
967}
968
969/* Transform:
970 1) initialize list L with values 0, 1,... 255
971 2) For each input element X:
972 2.1) let Y = L[X]
973 2.2) remove X-th element from L
974 2.3) prepend Y to L
975 2.4) append Y to output
976
977 In most cases max(Y) <= 7, so most of L remains intact.
978 To reduce the cost of initialization, we reuse L, remember the upper bound
979 of Y values, and reinitialize only first elements in L.
980
981 Most of input values are 0 and 1. To reduce number of branches, we replace
982 inner for loop with do-while. */
983static BROTLI_NOINLINE__attribute__((__noinline__)) void InverseMoveToFrontTransform(
984 uint8_t* v, brotli_reg_tuint64_t v_len, BrotliDecoderStateBrotliDecoderStateInternal* state) {
985 /* Reinitialize elements that could have been changed. */
986 brotli_reg_tuint64_t i = 1;
987 brotli_reg_tuint64_t upper_bound = state->mtf_upper_bound;
988 uint32_t* mtf = &state->mtf[1]; /* Make mtf[-1] addressable. */
989 uint8_t* mtf_u8 = (uint8_t*)mtf;
990 /* Load endian-aware constant. */
991 const uint8_t b0123[4] = {0, 1, 2, 3};
992 uint32_t pattern;
993 memcpy(&pattern, &b0123, 4);
994
995 /* Initialize list using 4 consequent values pattern. */
996 mtf[0] = pattern;
997 do {
998 pattern += 0x04040404; /* Advance all 4 values by 4. */
999 mtf[i] = pattern;
1000 i++;
1001 } while (i <= upper_bound);
1002
1003 /* Transform the input. */
1004 upper_bound = 0;
1005 for (i = 0; i < v_len; ++i) {
1006 int index = v[i];
1007 uint8_t value = mtf_u8[index];
1008 upper_bound |= v[i];
1009 v[i] = value;
1010 mtf_u8[-1] = value;
1011 do {
1012 index--;
1013 mtf_u8[index + 1] = mtf_u8[index];
1014 } while (index >= 0);
1015 }
1016 /* Remember amount of elements to be reinitialized. */
1017 state->mtf_upper_bound = upper_bound >> 2;
1018}
1019
1020/* Decodes a series of Huffman table using ReadHuffmanCode function. */
1021static BrotliDecoderErrorCode HuffmanTreeGroupDecode(
1022 HuffmanTreeGroup* group, BrotliDecoderStateBrotliDecoderStateInternal* s) {
1023 BrotliMetablockHeaderArena* h = &s->arena.header;
1024 if (h->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) {
1025 h->next = group->codes;
1026 h->htree_index = 0;
1027 h->substate_tree_group = BROTLI_STATE_TREE_GROUP_LOOP;
1028 }
1029 while (h->htree_index < group->num_htrees) {
1030 brotli_reg_tuint64_t table_size;
1031 BrotliDecoderErrorCode result = ReadHuffmanCode(group->alphabet_size_max,
1032 group->alphabet_size_limit, h->next, &table_size, s);
1033 if (result != BROTLI_DECODER_SUCCESS) return result;
1034 group->htrees[h->htree_index] = h->next;
1035 h->next += table_size;
1036 ++h->htree_index;
1037 }
1038 h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
1039 return BROTLI_DECODER_SUCCESS;
1040}
1041
1042/* Decodes a context map.
1043 Decoding is done in 4 phases:
1044 1) Read auxiliary information (6..16 bits) and allocate memory.
1045 In case of trivial context map, decoding is finished at this phase.
1046 2) Decode Huffman table using ReadHuffmanCode function.
1047 This table will be used for reading context map items.
1048 3) Read context map items; "0" values could be run-length encoded.
1049 4) Optionally, apply InverseMoveToFront transform to the resulting map. */
1050static BrotliDecoderErrorCode DecodeContextMap(brotli_reg_tuint64_t context_map_size,
1051 brotli_reg_tuint64_t* num_htrees,
1052 uint8_t** context_map_arg,
1053 BrotliDecoderStateBrotliDecoderStateInternal* s) {
1054 BrotliBitReader* br = &s->br;
1055 BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
1056 BrotliMetablockHeaderArena* h = &s->arena.header;
1057
1058 switch ((int)h->substate_context_map) {
1059 case BROTLI_STATE_CONTEXT_MAP_NONE:
1060 result = DecodeVarLenUint8(s, br, num_htrees);
1061 if (result != BROTLI_DECODER_SUCCESS) {
1062 return result;
1063 }
1064 (*num_htrees)++;
1065 h->context_index = 0;
1066 BROTLI_LOG_UINT(context_map_size);
1067 BROTLI_LOG_UINT(*num_htrees);
1068 *context_map_arg =
1069 (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)context_map_size)s->alloc_func(s->memory_manager_opaque, (size_t)context_map_size
)
;
1070 if (*context_map_arg == 0) {
1071 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP)((void)(0), BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP);
1072 }
1073 if (*num_htrees <= 1) {
1074 memset(*context_map_arg, 0, (size_t)context_map_size);
1075 return BROTLI_DECODER_SUCCESS;
1076 }
1077 h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
1078 /* Fall through. */
1079
1080 case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: {
1081 brotli_reg_tuint64_t bits;
1082 /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe
1083 to peek 4 bits ahead. */
1084 if (!BrotliSafeGetBits(br, 5, &bits)) {
1085 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1086 }
1087 if ((bits & 1) != 0) { /* Use RLE for zeros. */
1088 h->max_run_length_prefix = (bits >> 1) + 1;
1089 BrotliDropBits(br, 5);
1090 } else {
1091 h->max_run_length_prefix = 0;
1092 BrotliDropBits(br, 1);
1093 }
1094 BROTLI_LOG_UINT(h->max_run_length_prefix);
1095 h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN;
1096 }
1097 /* Fall through. */
1098
1099 case BROTLI_STATE_CONTEXT_MAP_HUFFMAN: {
1100 brotli_reg_tuint64_t alphabet_size = *num_htrees + h->max_run_length_prefix;
1101 result = ReadHuffmanCode(alphabet_size, alphabet_size,
1102 h->context_map_table, NULL((void*)0), s);
1103 if (result != BROTLI_DECODER_SUCCESS) return result;
1104 h->code = 0xFFFF;
1105 h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE;
1106 }
1107 /* Fall through. */
1108
1109 case BROTLI_STATE_CONTEXT_MAP_DECODE: {
1110 brotli_reg_tuint64_t context_index = h->context_index;
1111 brotli_reg_tuint64_t max_run_length_prefix = h->max_run_length_prefix;
1112 uint8_t* context_map = *context_map_arg;
1113 brotli_reg_tuint64_t code = h->code;
1114 BROTLI_BOOLint skip_preamble = (code != 0xFFFF);
1115 while (context_index < context_map_size || skip_preamble) {
1116 if (!skip_preamble) {
1117 if (!SafeReadSymbol(h->context_map_table, br, &code)) {
1118 h->code = 0xFFFF;
1119 h->context_index = context_index;
1120 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1121 }
1122 BROTLI_LOG_UINT(code);
1123
1124 if (code == 0) {
1125 context_map[context_index++] = 0;
1126 continue;
1127 }
1128 if (code > max_run_length_prefix) {
1129 context_map[context_index++] =
1130 (uint8_t)(code - max_run_length_prefix);
1131 continue;
1132 }
1133 } else {
1134 skip_preamble = BROTLI_FALSE0;
1135 }
1136 /* RLE sub-stage. */
1137 {
1138 brotli_reg_tuint64_t reps;
1139 if (!BrotliSafeReadBits(br, code, &reps)) {
1140 h->code = code;
1141 h->context_index = context_index;
1142 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1143 }
1144 reps += (brotli_reg_tuint64_t)1U << code;
1145 BROTLI_LOG_UINT(reps);
1146 if (context_index + reps > context_map_size) {
1147 return
1148 BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT)((void)(0), BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT);
1149 }
1150 do {
1151 context_map[context_index++] = 0;
1152 } while (--reps);
1153 }
1154 }
1155 }
1156 /* Fall through. */
1157
1158 case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: {
1159 brotli_reg_tuint64_t bits;
1160 if (!BrotliSafeReadBits(br, 1, &bits)) {
1161 h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
1162 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1163 }
1164 if (bits != 0) {
1165 InverseMoveToFrontTransform(*context_map_arg, context_map_size, s);
1166 }
1167 h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
1168 return BROTLI_DECODER_SUCCESS;
1169 }
1170
1171 default:
1172 return
1173 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE)((void)(0), BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */
1174 }
1175}
1176
1177/* Decodes a command or literal and updates block type ring-buffer.
1178 Reads 3..54 bits. */
1179static BROTLI_INLINEinline __attribute__((__always_inline__)) BrotliDecoderErrorCode DecodeBlockTypeAndLength(
1180 int safe, BrotliDecoderStateBrotliDecoderStateInternal* s, int tree_type) {
1181 brotli_reg_tuint64_t max_block_type = s->num_block_types[tree_type];
1182 const HuffmanCode* type_tree = &s->block_type_trees[
1183 tree_type * BROTLI_HUFFMAN_MAX_SIZE_258632];
1184 const HuffmanCode* len_tree = &s->block_len_trees[
1185 tree_type * BROTLI_HUFFMAN_MAX_SIZE_26396];
1186 BrotliBitReader* br = &s->br;
1187 brotli_reg_tuint64_t* ringbuffer = &s->block_type_rb[tree_type * 2];
1188 brotli_reg_tuint64_t block_type;
1189 if (max_block_type <= 1) {
1190 return BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH;
1191 }
1192
1193 /* Read 0..15 + 3..39 bits. */
1194 if (!safe) {
1195 block_type = ReadSymbol(type_tree, br);
1196 s->block_length[tree_type] = ReadBlockLength(len_tree, br);
1197 } else {
1198 BrotliBitReaderState memento;
1199 BrotliBitReaderSaveState(br, &memento);
1200 if (!SafeReadSymbol(type_tree, br, &block_type)) {
1201 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1202 }
1203 if (!SafeReadBlockLength(s, &s->block_length[tree_type], len_tree, br)) {
1204 s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
1205 BrotliBitReaderRestoreState(br, &memento);
1206 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1207 }
1208 }
1209
1210 if (block_type == 1) {
1211 block_type = ringbuffer[1] + 1;
1212 } else if (block_type == 0) {
1213 block_type = ringbuffer[0];
1214 } else {
1215 block_type -= 2;
1216 }
1217 if (block_type >= max_block_type) {
1218 block_type -= max_block_type;
1219 }
1220 ringbuffer[0] = ringbuffer[1];
1221 ringbuffer[1] = block_type;
1222 return BROTLI_DECODER_SUCCESS;
1223}
1224
1225static BROTLI_INLINEinline __attribute__((__always_inline__)) void DetectTrivialLiteralBlockTypes(
1226 BrotliDecoderStateBrotliDecoderStateInternal* s) {
1227 size_t i;
1228 for (i = 0; i < 8; ++i) s->trivial_literal_contexts[i] = 0;
1229 for (i = 0; i < s->num_block_types[0]; i++) {
1230 size_t offset = i << BROTLI_LITERAL_CONTEXT_BITS6;
1231 size_t error = 0;
1232 size_t sample = s->context_map[offset];
1233 size_t j;
1234 for (j = 0; j < (1u << BROTLI_LITERAL_CONTEXT_BITS6);) {
1235 /* NOLINTNEXTLINE(bugprone-macro-repeated-side-effects) */
1236 BROTLI_REPEAT_4({ error |= s->context_map[offset + j++] ^ sample; }){{ error |= s->context_map[offset + j++] ^ sample; }; { error
|= s->context_map[offset + j++] ^ sample; }; { error |= s
->context_map[offset + j++] ^ sample; }; { error |= s->
context_map[offset + j++] ^ sample; };}
1237 }
1238 if (error == 0) {
1239 s->trivial_literal_contexts[i >> 5] |= 1u << (i & 31);
1240 }
1241 }
1242}
1243
1244static BROTLI_INLINEinline __attribute__((__always_inline__)) void PrepareLiteralDecoding(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1245 uint8_t context_mode;
1246 size_t trivial;
1247 brotli_reg_tuint64_t block_type = s->block_type_rb[1];
1248 brotli_reg_tuint64_t context_offset = block_type << BROTLI_LITERAL_CONTEXT_BITS6;
1249 s->context_map_slice = s->context_map + context_offset;
1250 trivial = s->trivial_literal_contexts[block_type >> 5];
1251 s->trivial_literal_context = (trivial >> (block_type & 31)) & 1;
1252 s->literal_htree = s->literal_hgroup.htrees[s->context_map_slice[0]];
1253 context_mode = s->context_modes[block_type] & 3;
1254 s->context_lookup = BROTLI_CONTEXT_LUT(context_mode)(&_kBrotliContextLookupTable[(context_mode) << 9]);
1255}
1256
1257/* Decodes the block type and updates the state for literal context.
1258 Reads 3..54 bits. */
1259static BROTLI_INLINEinline __attribute__((__always_inline__)) BrotliDecoderErrorCode DecodeLiteralBlockSwitchInternal(
1260 int safe, BrotliDecoderStateBrotliDecoderStateInternal* s) {
1261 BrotliDecoderErrorCode result = DecodeBlockTypeAndLength(safe, s, 0);
1262 if (result != BROTLI_DECODER_SUCCESS) {
1263 return result;
1264 }
1265 PrepareLiteralDecoding(s);
1266 return BROTLI_DECODER_SUCCESS;
1267}
1268
1269static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderErrorCode
1270DecodeLiteralBlockSwitch(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1271 return DecodeLiteralBlockSwitchInternal(0, s);
1272}
1273
1274static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderErrorCode SafeDecodeLiteralBlockSwitch(
1275 BrotliDecoderStateBrotliDecoderStateInternal* s) {
1276 return DecodeLiteralBlockSwitchInternal(1, s);
1277}
1278
1279/* Block switch for insert/copy length.
1280 Reads 3..54 bits. */
1281static BROTLI_INLINEinline __attribute__((__always_inline__)) BrotliDecoderErrorCode DecodeCommandBlockSwitchInternal(
1282 int safe, BrotliDecoderStateBrotliDecoderStateInternal* s) {
1283 BrotliDecoderErrorCode result = DecodeBlockTypeAndLength(safe, s, 1);
1284 if (result != BROTLI_DECODER_SUCCESS) {
1285 return result;
1286 }
1287 s->htree_command = s->insert_copy_hgroup.htrees[s->block_type_rb[3]];
1288 return BROTLI_DECODER_SUCCESS;
1289}
1290
1291static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderErrorCode
1292DecodeCommandBlockSwitch(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1293 return DecodeCommandBlockSwitchInternal(0, s);
1294}
1295
1296static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderErrorCode
1297SafeDecodeCommandBlockSwitch(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1298 return DecodeCommandBlockSwitchInternal(1, s);
1299}
1300
1301/* Block switch for distance codes.
1302 Reads 3..54 bits. */
1303static BROTLI_INLINEinline __attribute__((__always_inline__)) BrotliDecoderErrorCode DecodeDistanceBlockSwitchInternal(
1304 int safe, BrotliDecoderStateBrotliDecoderStateInternal* s) {
1305 BrotliDecoderErrorCode result = DecodeBlockTypeAndLength(safe, s, 2);
1306 if (result != BROTLI_DECODER_SUCCESS) {
1307 return result;
1308 }
1309 s->dist_context_map_slice = s->dist_context_map +
1310 (s->block_type_rb[5] << BROTLI_DISTANCE_CONTEXT_BITS2);
1311 s->dist_htree_index = s->dist_context_map_slice[s->distance_context];
1312 return BROTLI_DECODER_SUCCESS;
1313}
1314
1315static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderErrorCode
1316DecodeDistanceBlockSwitch(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1317 return DecodeDistanceBlockSwitchInternal(0, s);
1318}
1319
1320static BROTLI_BOOLint BROTLI_NOINLINE__attribute__((__noinline__)) SafeDecodeDistanceBlockSwitch(
1321 BrotliDecoderStateBrotliDecoderStateInternal* s) {
1322 return DecodeDistanceBlockSwitchInternal(1, s);
1323}
1324
1325static size_t UnwrittenBytes(const BrotliDecoderStateBrotliDecoderStateInternal* s, BROTLI_BOOLint wrap) {
1326 size_t pos = wrap && s->pos > s->ringbuffer_size ?
1327 (size_t)s->ringbuffer_size : (size_t)(s->pos);
1328 size_t partial_pos_rb = (s->rb_roundtrips * (size_t)s->ringbuffer_size) + pos;
1329 return partial_pos_rb - s->partial_pos_out;
1330}
1331
1332/* Dumps output.
1333 Returns BROTLI_DECODER_NEEDS_MORE_OUTPUT only if there is more output to push
1334 and either ring-buffer is as big as window size, or |force| is true. */
1335static BrotliDecoderErrorCode BROTLI_NOINLINE__attribute__((__noinline__)) WriteRingBuffer(
1336 BrotliDecoderStateBrotliDecoderStateInternal* s, size_t* available_out, uint8_t** next_out,
1337 size_t* total_out, BROTLI_BOOLint force) {
1338 uint8_t* start =
1339 s->ringbuffer + (s->partial_pos_out & (size_t)s->ringbuffer_mask);
1340 size_t to_write = UnwrittenBytes(s, BROTLI_TRUE1);
1341 size_t num_written = *available_out;
1342 if (num_written > to_write) {
1343 num_written = to_write;
1344 }
1345 if (s->meta_block_remaining_len < 0) {
1346 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1)((void)(0), BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1);
1347 }
1348 if (next_out && !*next_out) {
1349 *next_out = start;
1350 } else {
1351 if (next_out) {
1352 memcpy(*next_out, start, num_written);
1353 *next_out += num_written;
1354 }
1355 }
1356 *available_out -= num_written;
1357 BROTLI_LOG_UINT(to_write);
1358 BROTLI_LOG_UINT(num_written);
1359 s->partial_pos_out += num_written;
1360 if (total_out) {
1361 *total_out = s->partial_pos_out;
1362 }
1363 if (num_written < to_write) {
1364 if (s->ringbuffer_size == (1 << s->window_bits) || force) {
1365 return BROTLI_DECODER_NEEDS_MORE_OUTPUT;
1366 } else {
1367 return BROTLI_DECODER_SUCCESS;
1368 }
1369 }
1370 /* Wrap ring buffer only if it has reached its maximal size. */
1371 if (s->ringbuffer_size == (1 << s->window_bits) &&
1372 s->pos >= s->ringbuffer_size) {
1373 s->pos -= s->ringbuffer_size;
1374 s->rb_roundtrips++;
1375 s->should_wrap_ringbuffer = (size_t)s->pos != 0 ? 1 : 0;
1376 }
1377 return BROTLI_DECODER_SUCCESS;
1378}
1379
1380static void BROTLI_NOINLINE__attribute__((__noinline__)) WrapRingBuffer(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1381 if (s->should_wrap_ringbuffer) {
1382 memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos);
1383 s->should_wrap_ringbuffer = 0;
1384 }
1385}
1386
1387/* Allocates ring-buffer.
1388
1389 s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
1390 this function is called.
1391
1392 Last two bytes of ring-buffer are initialized to 0, so context calculation
1393 could be done uniformly for the first two and all other positions. */
1394static BROTLI_BOOLint BROTLI_NOINLINE__attribute__((__noinline__)) BrotliEnsureRingBuffer(
1395 BrotliDecoderStateBrotliDecoderStateInternal* s) {
1396 uint8_t* old_ringbuffer = s->ringbuffer;
1397 if (s->ringbuffer_size == s->new_ringbuffer_size) {
1398 return BROTLI_TRUE1;
1399 }
1400
1401 s->ringbuffer = (uint8_t*)BROTLI_DECODER_ALLOC(s,s->alloc_func(s->memory_manager_opaque, (size_t)(s->
new_ringbuffer_size) + kRingBufferWriteAheadSlack)
1402 (size_t)(s->new_ringbuffer_size) + kRingBufferWriteAheadSlack)s->alloc_func(s->memory_manager_opaque, (size_t)(s->
new_ringbuffer_size) + kRingBufferWriteAheadSlack)
;
1403 if (s->ringbuffer == 0) {
1404 /* Restore previous value. */
1405 s->ringbuffer = old_ringbuffer;
1406 return BROTLI_FALSE0;
1407 }
1408 s->ringbuffer[s->new_ringbuffer_size - 2] = 0;
1409 s->ringbuffer[s->new_ringbuffer_size - 1] = 0;
1410
1411 if (!!old_ringbuffer) {
1412 memcpy(s->ringbuffer, old_ringbuffer, (size_t)s->pos);
1413 BROTLI_DECODER_FREE(s, old_ringbuffer){ s->free_func(s->memory_manager_opaque, old_ringbuffer
); old_ringbuffer = ((void*)0); }
;
1414 }
1415
1416 s->ringbuffer_size = s->new_ringbuffer_size;
1417 s->ringbuffer_mask = s->new_ringbuffer_size - 1;
1418 s->ringbuffer_end = s->ringbuffer + s->ringbuffer_size;
1419
1420 return BROTLI_TRUE1;
1421}
1422
1423static BrotliDecoderErrorCode BROTLI_NOINLINE__attribute__((__noinline__))
1424SkipMetadataBlock(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1425 BrotliBitReader* br = &s->br;
1426 int nbytes;
1427
1428 if (s->meta_block_remaining_len == 0) {
1429 return BROTLI_DECODER_SUCCESS;
1430 }
1431
1432 BROTLI_DCHECK((BrotliGetAvailableBits(br) & 7) == 0);
1433
1434 /* Drain accumulator. */
1435 if (BrotliGetAvailableBits(br) >= 8) {
1436 uint8_t buffer[8];
1437 nbytes = (int)(BrotliGetAvailableBits(br)) >> 3;
1438 BROTLI_DCHECK(nbytes <= 8);
1439 if (nbytes > s->meta_block_remaining_len) {
1440 nbytes = s->meta_block_remaining_len;
1441 }
1442 BrotliCopyBytes(buffer, br, (size_t)nbytes);
1443 if (s->metadata_chunk_func) {
1444 s->metadata_chunk_func(s->metadata_callback_opaque, buffer,
1445 (size_t)nbytes);
1446 }
1447 s->meta_block_remaining_len -= nbytes;
1448 if (s->meta_block_remaining_len == 0) {
1449 return BROTLI_DECODER_SUCCESS;
1450 }
1451 }
1452
1453 /* Direct access to metadata is possible. */
1454 nbytes = (int)BrotliGetRemainingBytes(br);
1455 if (nbytes > s->meta_block_remaining_len) {
1456 nbytes = s->meta_block_remaining_len;
1457 }
1458 if (nbytes > 0) {
1459 if (s->metadata_chunk_func) {
1460 s->metadata_chunk_func(s->metadata_callback_opaque, br->next_in,
1461 (size_t)nbytes);
1462 }
1463 BrotliDropBytes(br, (size_t)nbytes);
1464 s->meta_block_remaining_len -= nbytes;
1465 if (s->meta_block_remaining_len == 0) {
1466 return BROTLI_DECODER_SUCCESS;
1467 }
1468 }
1469
1470 BROTLI_DCHECK(BrotliGetRemainingBytes(br) == 0);
1471
1472 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1473}
1474
1475static BrotliDecoderErrorCode BROTLI_NOINLINE__attribute__((__noinline__)) CopyUncompressedBlockToOutput(
1476 size_t* available_out, uint8_t** next_out, size_t* total_out,
1477 BrotliDecoderStateBrotliDecoderStateInternal* s) {
1478 /* TODO(eustas): avoid allocation for single uncompressed block. */
1479 if (!BrotliEnsureRingBuffer(s)) {
1480 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1)((void)(0), BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1);
1481 }
1482
1483 /* State machine */
1484 for (;;) {
1485 switch (s->substate_uncompressed) {
1486 case BROTLI_STATE_UNCOMPRESSED_NONE: {
1487 int nbytes = (int)BrotliGetRemainingBytes(&s->br);
1488 if (nbytes > s->meta_block_remaining_len) {
1489 nbytes = s->meta_block_remaining_len;
1490 }
1491 if (s->pos + nbytes > s->ringbuffer_size) {
1492 nbytes = s->ringbuffer_size - s->pos;
1493 }
1494 /* Copy remaining bytes from s->br.buf_ to ring-buffer. */
1495 BrotliCopyBytes(&s->ringbuffer[s->pos], &s->br, (size_t)nbytes);
1496 s->pos += nbytes;
1497 s->meta_block_remaining_len -= nbytes;
1498 if (s->pos < 1 << s->window_bits) {
1499 if (s->meta_block_remaining_len == 0) {
1500 return BROTLI_DECODER_SUCCESS;
1501 }
1502 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1503 }
1504 s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_WRITE;
1505 }
1506 /* Fall through. */
1507
1508 case BROTLI_STATE_UNCOMPRESSED_WRITE: {
1509 BrotliDecoderErrorCode result;
1510 result = WriteRingBuffer(
1511 s, available_out, next_out, total_out, BROTLI_FALSE0);
1512 if (result != BROTLI_DECODER_SUCCESS) {
1513 return result;
1514 }
1515 if (s->ringbuffer_size == 1 << s->window_bits) {
1516 s->max_distance = s->max_backward_distance;
1517 }
1518 s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE;
1519 break;
1520 }
1521 }
1522 }
1523 BROTLI_DCHECK(0); /* Unreachable */
1524}
1525
1526static BROTLI_BOOLint AttachCompoundDictionary(
1527 BrotliDecoderStateBrotliDecoderStateInternal* state, const uint8_t* data, size_t size) {
1528 BrotliDecoderCompoundDictionary* addon = state->compound_dictionary;
1529 int new_size = (int)size;
1530 if (new_size < 0 || (size_t)new_size != size) return BROTLI_FALSE0;
1531 if (state->state != BROTLI_STATE_UNINITED) return BROTLI_FALSE0;
1532 if (!addon) {
1533 addon = (BrotliDecoderCompoundDictionary*)BROTLI_DECODER_ALLOC(state->alloc_func(state->memory_manager_opaque, sizeof(
BrotliDecoderCompoundDictionary))
1534 state, sizeof(BrotliDecoderCompoundDictionary))state->alloc_func(state->memory_manager_opaque, sizeof(
BrotliDecoderCompoundDictionary))
;
1535 if (!addon) return BROTLI_FALSE0;
1536 addon->num_chunks = 0;
1537 addon->total_size = 0;
1538 addon->br_length = 0;
1539 addon->br_copied = 0;
1540 addon->block_bits = -1;
1541 addon->chunk_offsets[0] = 0;
1542 state->compound_dictionary = addon;
1543 }
1544 if (addon->num_chunks == 15) return BROTLI_FALSE0;
1545 if (!BROTLI_SAFE_ADD(int, addon->total_size, new_size, &new_size)(brotli_safe_add_int((addon->total_size), (new_size), (&
new_size)))
) {
1546 return BROTLI_FALSE0;
1547 }
1548 addon->chunks[addon->num_chunks] = data;
1549 addon->num_chunks++;
1550 addon->total_size = new_size;
1551 addon->chunk_offsets[addon->num_chunks] = new_size;
1552 return BROTLI_TRUE1;
1553}
1554
1555static void EnsureCompoundDictionaryInitialized(BrotliDecoderStateBrotliDecoderStateInternal* state) {
1556 BrotliDecoderCompoundDictionary* addon = state->compound_dictionary;
1557 /* 256 = (1 << 8) slots in block map. */
1558 int block_bits = 8;
1559 int cursor = 0;
1560 int index = 0;
1561 if (addon->block_bits != -1) return;
1562 while (((addon->total_size - 1) >> block_bits) != 0) block_bits++;
1563 block_bits -= 8;
1564 addon->block_bits = block_bits;
1565 while (cursor < addon->total_size) {
1566 while (addon->chunk_offsets[index + 1] < cursor) index++;
1567 addon->block_map[cursor >> block_bits] = (uint8_t)index;
1568 cursor += 1 << block_bits;
1569 }
1570}
1571
1572static BROTLI_BOOLint InitializeCompoundDictionaryCopy(BrotliDecoderStateBrotliDecoderStateInternal* s,
1573 int address, int length) {
1574 BrotliDecoderCompoundDictionary* addon = s->compound_dictionary;
1575 int index;
1576 EnsureCompoundDictionaryInitialized(s);
1577 index = addon->block_map[address >> addon->block_bits];
1578 while (address >= addon->chunk_offsets[index + 1]) index++;
1579 if (addon->total_size < address + length) return BROTLI_FALSE0;
1580 /* Update the recent distances cache. */
1581 s->dist_rb[s->dist_rb_idx & 3] = s->distance_code;
1582 ++s->dist_rb_idx;
1583 s->meta_block_remaining_len -= length;
1584 addon->br_index = index;
1585 addon->br_offset = address - addon->chunk_offsets[index];
1586 addon->br_length = length;
1587 addon->br_copied = 0;
1588 return BROTLI_TRUE1;
1589}
1590
1591static int GetCompoundDictionarySize(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1592 return s->compound_dictionary ? s->compound_dictionary->total_size : 0;
1593}
1594
1595static int CopyFromCompoundDictionary(BrotliDecoderStateBrotliDecoderStateInternal* s, int pos) {
1596 BrotliDecoderCompoundDictionary* addon = s->compound_dictionary;
1597 int orig_pos = pos;
1598 while (addon->br_length != addon->br_copied) {
1599 uint8_t* copy_dst = &s->ringbuffer[pos];
1600 const uint8_t* copy_src =
1601 addon->chunks[addon->br_index] + addon->br_offset;
1602 int space = s->ringbuffer_size - pos;
1603 int rem_chunk_length = (addon->chunk_offsets[addon->br_index + 1] -
1604 addon->chunk_offsets[addon->br_index]) - addon->br_offset;
1605 int length = addon->br_length - addon->br_copied;
1606 if (length > rem_chunk_length) length = rem_chunk_length;
1607 if (length > space) length = space;
1608 memcpy(copy_dst, copy_src, (size_t)length);
1609 pos += length;
1610 addon->br_offset += length;
1611 addon->br_copied += length;
1612 if (length == rem_chunk_length) {
1613 addon->br_index++;
1614 addon->br_offset = 0;
1615 }
1616 if (pos == s->ringbuffer_size) break;
1617 }
1618 return pos - orig_pos;
1619}
1620
1621BROTLI_BOOLint BrotliDecoderAttachDictionary(
1622 BrotliDecoderStateBrotliDecoderStateInternal* state, BrotliSharedDictionaryType type,
1623 size_t data_size, const uint8_t data[BROTLI_ARRAY_PARAM(data_size)]) {
1624 brotli_reg_tuint64_t i;
1625 brotli_reg_tuint64_t num_prefix_before = state->dictionary->num_prefix;
1626 if (state->state != BROTLI_STATE_UNINITED) return BROTLI_FALSE0;
1627 if (!BrotliSharedDictionaryAttach(state->dictionary, type, data_size, data)) {
1628 return BROTLI_FALSE0;
1629 }
1630 for (i = num_prefix_before; i < state->dictionary->num_prefix; i++) {
1631 if (!AttachCompoundDictionary(
1632 state, state->dictionary->prefix[i],
1633 state->dictionary->prefix_size[i])) {
1634 return BROTLI_FALSE0;
1635 }
1636 }
1637 return BROTLI_TRUE1;
1638}
1639
1640/* Calculates the smallest feasible ring buffer.
1641
1642 If we know the data size is small, do not allocate more ring buffer
1643 size than needed to reduce memory usage.
1644
1645 When this method is called, metablock size and flags MUST be decoded. */
1646static void BROTLI_NOINLINE__attribute__((__noinline__)) BrotliCalculateRingBufferSize(
1647 BrotliDecoderStateBrotliDecoderStateInternal* s) {
1648 int window_size = 1 << s->window_bits;
1649 int new_ringbuffer_size = window_size;
1650 /* We need at least 2 bytes of ring buffer size to get the last two
1651 bytes for context from there */
1652 int min_size = s->ringbuffer_size ? s->ringbuffer_size : 1024;
1653 int output_size;
1654
1655 /* If maximum is already reached, no further extension is retired. */
1656 if (s->ringbuffer_size == window_size) {
1657 return;
1658 }
1659
1660 /* Metadata blocks does not touch ring buffer. */
1661 if (s->is_metadata) {
1662 return;
1663 }
1664
1665 if (!s->ringbuffer) {
1666 output_size = 0;
1667 } else {
1668 output_size = s->pos;
1669 }
1670 output_size += s->meta_block_remaining_len;
1671 min_size = min_size < output_size ? output_size : min_size;
1672
1673 if (!!s->canny_ringbuffer_allocation) {
1674 /* Reduce ring buffer size to save memory when server is unscrupulous.
1675 In worst case memory usage might be 1.5x bigger for a short period of
1676 ring buffer reallocation. */
1677 while ((new_ringbuffer_size >> 1) >= min_size) {
1678 new_ringbuffer_size >>= 1;
1679 }
1680 }
1681
1682 s->new_ringbuffer_size = new_ringbuffer_size;
1683}
1684
1685/* Reads 1..256 2-bit context modes. */
1686static BrotliDecoderErrorCode ReadContextModes(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1687 BrotliBitReader* br = &s->br;
1688 int i = s->loop_counter;
1689
1690 while (i < (int)s->num_block_types[0]) {
1691 brotli_reg_tuint64_t bits;
1692 if (!BrotliSafeReadBits(br, 2, &bits)) {
1693 s->loop_counter = i;
1694 return BROTLI_DECODER_NEEDS_MORE_INPUT;
1695 }
1696 s->context_modes[i] = (uint8_t)bits;
1697 BROTLI_LOG_ARRAY_INDEX(s->context_modes, i);
1698 i++;
1699 }
1700 return BROTLI_DECODER_SUCCESS;
1701}
1702
1703static BROTLI_INLINEinline __attribute__((__always_inline__)) void TakeDistanceFromRingBuffer(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1704 int offset = s->distance_code - 3;
1705 if (s->distance_code <= 3) {
1706 /* Compensate double distance-ring-buffer roll for dictionary items. */
1707 s->distance_context = 1 >> s->distance_code;
1708 s->distance_code = s->dist_rb[(s->dist_rb_idx - offset) & 3];
1709 s->dist_rb_idx -= s->distance_context;
1710 } else {
1711 int index_delta = 3;
1712 int delta;
1713 int base = s->distance_code - 10;
1714 if (s->distance_code < 10) {
1715 base = s->distance_code - 4;
1716 } else {
1717 index_delta = 2;
1718 }
1719 /* Unpack one of six 4-bit values. */
1720 delta = ((0x605142 >> (4 * base)) & 0xF) - 3;
1721 s->distance_code = s->dist_rb[(s->dist_rb_idx + index_delta) & 0x3] + delta;
1722 if (s->distance_code <= 0) {
1723 /* A huge distance will cause a BROTLI_FAILURE() soon.
1724 This is a little faster than failing here. */
1725 s->distance_code = 0x7FFFFFFF;
1726 }
1727 }
1728}
1729
1730static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint SafeReadBits(
1731 BrotliBitReader* const br, brotli_reg_tuint64_t n_bits, brotli_reg_tuint64_t* val) {
1732 if (n_bits != 0) {
1733 return BrotliSafeReadBits(br, n_bits, val);
1734 } else {
1735 *val = 0;
1736 return BROTLI_TRUE1;
1737 }
1738}
1739
1740static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint SafeReadBits32(
1741 BrotliBitReader* const br, brotli_reg_tuint64_t n_bits, brotli_reg_tuint64_t* val) {
1742 if (n_bits != 0) {
1743 return BrotliSafeReadBits32(br, n_bits, val);
1744 } else {
1745 *val = 0;
1746 return BROTLI_TRUE1;
1747 }
1748}
1749
1750/*
1751 RFC 7932 Section 4 with "..." shortenings and "[]" emendations.
1752
1753 Each distance ... is represented with a pair <distance code, extra bits>...
1754 The distance code is encoded using a prefix code... The number of extra bits
1755 can be 0..24... Two additional parameters: NPOSTFIX (0..3), and ...
1756 NDIRECT (0..120) ... are encoded in the meta-block header...
1757
1758 The first 16 distance symbols ... reference past distances... ring buffer ...
1759 Next NDIRECT distance symbols ... represent distances from 1 to NDIRECT...
1760 [For] distance symbols 16 + NDIRECT and greater ... the number of extra bits
1761 ... is given by the following formula:
1762
1763 [ xcode = dcode - NDIRECT - 16 ]
1764 ndistbits = 1 + [ xcode ] >> (NPOSTFIX + 1)
1765
1766 ...
1767*/
1768
1769/*
1770 RFC 7932 Section 9.2 with "..." shortenings and "[]" emendations.
1771
1772 ... to get the actual value of the parameter NDIRECT, left-shift this
1773 four-bit number by NPOSTFIX bits ...
1774*/
1775
1776/* Remaining formulas from RFC 7932 Section 4 could be rewritten as following:
1777
1778 alphabet_size = 16 + NDIRECT + (max_distbits << (NPOSTFIX + 1))
1779
1780 half = ((xcode >> NPOSTFIX) & 1) << ndistbits
1781 postfix = xcode & ((1 << NPOSTFIX) - 1)
1782 range_start = 2 * (1 << ndistbits - 1 - 1)
1783
1784 distance = (range_start + half + extra) << NPOSTFIX + postfix + NDIRECT + 1
1785
1786 NB: ndistbits >= 1 -> range_start >= 0
1787 NB: range_start has factor 2, as the range is covered by 2 "halves"
1788 NB: extra -1 offset in range_start formula covers the absence of
1789 ndistbits = 0 case
1790 NB: when NPOSTFIX = 0, NDIRECT is not greater than 15
1791
1792 In other words, xcode has the following binary structure - XXXHPPP:
1793 - XXX represent the number of extra distance bits
1794 - H selects upper / lower range of distances
1795 - PPP represent "postfix"
1796
1797 "Regular" distance encoding has NPOSTFIX = 0; omitting the postfix part
1798 simplifies distance calculation.
1799
1800 Using NPOSTFIX > 0 allows cheaper encoding of regular structures, e.g. where
1801 most of distances have the same reminder of division by 2/4/8. For example,
1802 the table of int32_t values that come from different sources; if it is likely
1803 that 3 highest bytes of values from the same source are the same, then
1804 copy distance often looks like 4x + y.
1805
1806 Distance calculation could be rewritten to:
1807
1808 ndistbits = NDISTBITS(NDIRECT, NPOSTFIX)[dcode]
1809 distance = OFFSET(NDIRECT, NPOSTFIX)[dcode] + extra << NPOSTFIX
1810
1811 NDISTBITS and OFFSET could be pre-calculated, as NDIRECT and NPOSTFIX could
1812 change only once per meta-block.
1813*/
1814
1815/* Calculates distance lookup table.
1816 NB: it is possible to have all 64 tables precalculated. */
1817static void CalculateDistanceLut(BrotliDecoderStateBrotliDecoderStateInternal* s) {
1818 BrotliMetablockBodyArena* b = &s->arena.body;
1819 brotli_reg_tuint64_t npostfix = s->distance_postfix_bits;
1820 brotli_reg_tuint64_t ndirect = s->num_direct_distance_codes;
1821 brotli_reg_tuint64_t alphabet_size_limit = s->distance_hgroup.alphabet_size_limit;
1822 brotli_reg_tuint64_t postfix = (brotli_reg_tuint64_t)1u << npostfix;
1823 brotli_reg_tuint64_t j;
1824 brotli_reg_tuint64_t bits = 1;
1825 brotli_reg_tuint64_t half = 0;
1826
1827 /* Skip short codes. */
1828 brotli_reg_tuint64_t i = BROTLI_NUM_DISTANCE_SHORT_CODES16;
1829
1830 /* Fill direct codes. */
1831 for (j = 0; j < ndirect; ++j) {
1832 b->dist_extra_bits[i] = 0;
1833 b->dist_offset[i] = j + 1;
1834 ++i;
1835 }
1836
1837 /* Fill regular distance codes. */
1838 while (i < alphabet_size_limit) {
1839 brotli_reg_tuint64_t base = ndirect + ((((2 + half) << bits) - 4) << npostfix) + 1;
1840 /* Always fill the complete group. */
1841 for (j = 0; j < postfix; ++j) {
1842 b->dist_extra_bits[i] = (uint8_t)bits;
1843 b->dist_offset[i] = base + j;
1844 ++i;
1845 }
1846 bits = bits + half;
1847 half = half ^ 1;
1848 }
1849}
1850
1851/* Precondition: s->distance_code < 0. */
1852static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint ReadDistanceInternal(
1853 int safe, BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliBitReader* br) {
1854 BrotliMetablockBodyArena* b = &s->arena.body;
1855 brotli_reg_tuint64_t code;
1856 brotli_reg_tuint64_t bits;
1857 BrotliBitReaderState memento;
1858 HuffmanCode* distance_tree = s->distance_hgroup.htrees[s->dist_htree_index];
1859 if (!safe) {
1860 code = ReadSymbol(distance_tree, br);
1861 } else {
1862 BrotliBitReaderSaveState(br, &memento);
1863 if (!SafeReadSymbol(distance_tree, br, &code)) {
1864 return BROTLI_FALSE0;
1865 }
1866 }
1867 --s->block_length[2];
1868 /* Convert the distance code to the actual distance by possibly
1869 looking up past distances from the s->dist_rb. */
1870 s->distance_context = 0;
1871 if ((code & ~0xFu) == 0) {
1872 s->distance_code = (int)code;
1873 TakeDistanceFromRingBuffer(s);
1874 return BROTLI_TRUE1;
1875 }
1876 if (!safe) {
1877 bits = BrotliReadBits32(br, b->dist_extra_bits[code]);
1878 } else {
1879 if (!SafeReadBits32(br, b->dist_extra_bits[code], &bits)) {
1880 ++s->block_length[2];
1881 BrotliBitReaderRestoreState(br, &memento);
1882 return BROTLI_FALSE0;
1883 }
1884 }
1885 s->distance_code =
1886 (int)(b->dist_offset[code] + (bits << s->distance_postfix_bits));
1887 return BROTLI_TRUE1;
1888}
1889
1890static BROTLI_INLINEinline __attribute__((__always_inline__)) void ReadDistance(
1891 BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliBitReader* br) {
1892 ReadDistanceInternal(0, s, br);
1893}
1894
1895static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint SafeReadDistance(
1896 BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliBitReader* br) {
1897 return ReadDistanceInternal(1, s, br);
1898}
1899
1900static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint ReadCommandInternal(
1901 int safe, BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliBitReader* br, int* insert_length) {
1902 brotli_reg_tuint64_t cmd_code;
1903 brotli_reg_tuint64_t insert_len_extra = 0;
1904 brotli_reg_tuint64_t copy_length;
1905 CmdLutElement v;
1906 BrotliBitReaderState memento;
1907 if (!safe) {
1908 cmd_code = ReadSymbol(s->htree_command, br);
1909 } else {
1910 BrotliBitReaderSaveState(br, &memento);
1911 if (!SafeReadSymbol(s->htree_command, br, &cmd_code)) {
1912 return BROTLI_FALSE0;
1913 }
1914 }
1915 v = kCmdLut[cmd_code];
1916 s->distance_code = v.distance_code;
1917 s->distance_context = v.context;
1918 s->dist_htree_index = s->dist_context_map_slice[s->distance_context];
1919 *insert_length = v.insert_len_offset;
1920 if (!safe) {
1921 if (BROTLI_PREDICT_FALSE(v.insert_len_extra_bits != 0)(__builtin_expect(v.insert_len_extra_bits != 0, 0))) {
1922 insert_len_extra = BrotliReadBits24(br, v.insert_len_extra_bits);
1923 }
1924 copy_length = BrotliReadBits24(br, v.copy_len_extra_bits);
1925 } else {
1926 if (!SafeReadBits(br, v.insert_len_extra_bits, &insert_len_extra) ||
1927 !SafeReadBits(br, v.copy_len_extra_bits, &copy_length)) {
1928 BrotliBitReaderRestoreState(br, &memento);
1929 return BROTLI_FALSE0;
1930 }
1931 }
1932 s->copy_length = (int)copy_length + v.copy_len_offset;
1933 --s->block_length[1];
1934 *insert_length += (int)insert_len_extra;
1935 return BROTLI_TRUE1;
1936}
1937
1938static BROTLI_INLINEinline __attribute__((__always_inline__)) void ReadCommand(
1939 BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliBitReader* br, int* insert_length) {
1940 ReadCommandInternal(0, s, br, insert_length);
1941}
1942
1943static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint SafeReadCommand(
1944 BrotliDecoderStateBrotliDecoderStateInternal* s, BrotliBitReader* br, int* insert_length) {
1945 return ReadCommandInternal(1, s, br, insert_length);
1946}
1947
1948static BROTLI_INLINEinline __attribute__((__always_inline__)) BROTLI_BOOLint CheckInputAmount(
1949 int safe, BrotliBitReader* const br) {
1950 if (safe) {
1951 return BROTLI_TRUE1;
1952 }
1953 return BrotliCheckInputAmount(br);
1954}
1955
1956/* NB: METHOD should return BROTLI_FALSE only in case there is not enough input;
1957 in case of "unsafe" execution, when input is guaranteed to be sufficient,
1958 result is ignored. */
1959#define BROTLI_SAFE(METHOD) \
1960 { \
1961 if (safe) { \
1962 if (!Safe##METHOD) { \
1963 result = BROTLI_DECODER_NEEDS_MORE_INPUT; \
1964 goto saveStateAndReturn; \
1965 } \
1966 } else { \
1967 METHOD; \
1968 } \
1969 }
1970
1971/* NB: METHOD should return BROTLI_DECODER_SUCCESS, BROTLI_DECODER_ERROR_*, or
1972 BROTLI_DECODER_NEEDS_MORE_INPUT; the later two break the processing. */
1973#define BROTLI_SAFE_WITH_STATUS(METHOD){ BrotliDecoderErrorCode status; if (safe) { status = SafeMETHOD
; } else { status = METHOD; } if (status != BROTLI_DECODER_SUCCESS
) { result = status; goto saveStateAndReturn; } }
\
1974 { \
1975 BrotliDecoderErrorCode status; \
1976 if (safe) { \
1977 status = Safe##METHOD; \
1978 } else { \
1979 status = METHOD; \
1980 } \
1981 if (status != BROTLI_DECODER_SUCCESS) { \
1982 result = status; \
1983 goto saveStateAndReturn; \
1984 } \
1985 }
1986
1987static BROTLI_INLINEinline __attribute__((__always_inline__)) BrotliDecoderErrorCode ProcessCommandsInternal(
1988 int safe, BrotliDecoderStateBrotliDecoderStateInternal* s) {
1989 int pos = s->pos;
1990 int i = s->loop_counter;
1991 BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
1992 BrotliBitReader* br = &s->br;
1993 int compound_dictionary_size = GetCompoundDictionarySize(s);
1994
1995 if (!CheckInputAmount(safe, br)) {
1996 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1997 goto saveStateAndReturn;
1998 }
1999 if (!safe) {
2000 BROTLI_UNUSED(BrotliWarmupBitReader(br))(void)(BrotliWarmupBitReader(br));
2001 }
2002
2003 /* Jump into state machine. */
2004 if (s->state == BROTLI_STATE_COMMAND_BEGIN) {
2005 goto CommandBegin;
2006 } else if (s->state == BROTLI_STATE_COMMAND_INNER) {
2007 goto CommandInner;
2008 } else if (s->state == BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) {
2009 goto CommandPostDecodeLiterals;
2010 } else if (s->state == BROTLI_STATE_COMMAND_POST_WRAP_COPY) {
2011 goto CommandPostWrapCopy;
2012 } else {
2013 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE)((void)(0), BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */
2014 }
2015
2016CommandBegin:
2017 if (safe) {
2018 s->state = BROTLI_STATE_COMMAND_BEGIN;
2019 }
2020 if (!CheckInputAmount(safe, br)) {
2021 s->state = BROTLI_STATE_COMMAND_BEGIN;
2022 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2023 goto saveStateAndReturn;
2024 }
2025 if (BROTLI_PREDICT_FALSE(s->block_length[1] == 0)(__builtin_expect(s->block_length[1] == 0, 0))) {
2026 BROTLI_SAFE_WITH_STATUS(DecodeCommandBlockSwitch(s)){ BrotliDecoderErrorCode status; if (safe) { status = SafeDecodeCommandBlockSwitch
(s); } else { status = DecodeCommandBlockSwitch(s); } if (status
!= BROTLI_DECODER_SUCCESS) { result = status; goto saveStateAndReturn
; } }
;
2027 goto CommandBegin;
2028 }
2029 /* Read the insert/copy length in the command. */
2030 BROTLI_SAFE(ReadCommand(s, br, &i));
2031 BROTLI_LOG(("[ProcessCommandsInternal] pos = %d insert = %d copy = %d\n",
2032 pos, i, s->copy_length));
2033 if (i == 0) {
2034 goto CommandPostDecodeLiterals;
2035 }
2036 s->meta_block_remaining_len -= i;
2037
2038CommandInner:
2039 if (safe) {
2040 s->state = BROTLI_STATE_COMMAND_INNER;
2041 }
2042 /* Read the literals in the command. */
2043 if (s->trivial_literal_context) {
2044 brotli_reg_tuint64_t bits;
2045 brotli_reg_tuint64_t value;
2046 PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
2047 if (!safe) {
2048 // This is a hottest part of the decode, so we copy the loop below
2049 // and optimize it by calculating the number of steps where all checks
2050 // evaluate to false (ringbuffer size/block size/input size).
2051 // Since all checks are loop invariant, we just need to find
2052 // minimal number of iterations for a simple loop, and run
2053 // the full version for the remainder.
2054 int num_steps = i - 1;
2055 if (num_steps > 0 && ((brotli_reg_tuint64_t)(num_steps) > s->block_length[0])) {
2056 // Safe cast, since block_length < steps
2057 num_steps = (int)s->block_length[0];
2058 }
2059 if (s->ringbuffer_size >= pos &&
2060 (s->ringbuffer_size - pos) <= num_steps) {
2061 num_steps = s->ringbuffer_size - pos - 1;
2062 }
2063 if (num_steps < 0) {
2064 num_steps = 0;
2065 }
2066 num_steps = BrotliCopyPreloadedSymbolsToU8(s->literal_htree, br, &bits,
2067 &value, s->ringbuffer, pos,
2068 num_steps);
2069 pos += num_steps;
2070 s->block_length[0] -= (brotli_reg_tuint64_t)num_steps;
2071 i -= num_steps;
2072 do {
2073 if (!CheckInputAmount(safe, br)) {
2074 s->state = BROTLI_STATE_COMMAND_INNER;
2075 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2076 goto saveStateAndReturn;
2077 }
2078 if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)(__builtin_expect(s->block_length[0] == 0, 0))) {
2079 goto NextLiteralBlock;
2080 }
2081 BrotliCopyPreloadedSymbolsToU8(s->literal_htree, br, &bits, &value,
2082 s->ringbuffer, pos, 1);
2083 --s->block_length[0];
2084 BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
2085 ++pos;
2086 if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)(__builtin_expect(pos == s->ringbuffer_size, 0))) {
2087 s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
2088 --i;
2089 goto saveStateAndReturn;
2090 }
2091 } while (--i != 0);
2092 } else { /* safe */
2093 do {
2094 if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)(__builtin_expect(s->block_length[0] == 0, 0))) {
2095 goto NextLiteralBlock;
2096 }
2097 brotli_reg_tuint64_t literal;
2098 if (!SafeReadSymbol(s->literal_htree, br, &literal)) {
2099 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2100 goto saveStateAndReturn;
2101 }
2102 s->ringbuffer[pos] = (uint8_t)literal;
2103 --s->block_length[0];
2104 BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
2105 ++pos;
2106 if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)(__builtin_expect(pos == s->ringbuffer_size, 0))) {
2107 s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
2108 --i;
2109 goto saveStateAndReturn;
2110 }
2111 } while (--i != 0);
2112 }
2113 } else {
2114 uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask];
2115 uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask];
2116 do {
2117 const HuffmanCode* hc;
2118 uint8_t context;
2119 if (!CheckInputAmount(safe, br)) {
2120 s->state = BROTLI_STATE_COMMAND_INNER;
2121 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2122 goto saveStateAndReturn;
2123 }
2124 if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)(__builtin_expect(s->block_length[0] == 0, 0))) {
2125 goto NextLiteralBlock;
2126 }
2127 context = BROTLI_CONTEXT(p1, p2, s->context_lookup)((s->context_lookup)[p1] | ((s->context_lookup) + 256)[
p2])
;
2128 BROTLI_LOG_UINT(context);
2129 hc = s->literal_hgroup.htrees[s->context_map_slice[context]];
2130 p2 = p1;
2131 if (!safe) {
2132 p1 = (uint8_t)ReadSymbol(hc, br);
2133 } else {
2134 brotli_reg_tuint64_t literal;
2135 if (!SafeReadSymbol(hc, br, &literal)) {
2136 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2137 goto saveStateAndReturn;
2138 }
2139 p1 = (uint8_t)literal;
2140 }
2141 s->ringbuffer[pos] = p1;
2142 --s->block_length[0];
2143 BROTLI_LOG_UINT(s->context_map_slice[context]);
2144 BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask);
2145 ++pos;
2146 if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)(__builtin_expect(pos == s->ringbuffer_size, 0))) {
2147 s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
2148 --i;
2149 goto saveStateAndReturn;
2150 }
2151 } while (--i != 0);
2152 }
2153 BROTLI_LOG_UINT(s->meta_block_remaining_len);
2154 if (BROTLI_PREDICT_FALSE(s->meta_block_remaining_len <= 0)(__builtin_expect(s->meta_block_remaining_len <= 0, 0))) {
2155 s->state = BROTLI_STATE_METABLOCK_DONE;
2156 goto saveStateAndReturn;
2157 }
2158
2159CommandPostDecodeLiterals:
2160 if (safe) {
2161 s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2162 }
2163 if (s->distance_code >= 0) {
2164 /* Implicit distance case. */
2165 s->distance_context = s->distance_code ? 0 : 1;
2166 --s->dist_rb_idx;
2167 s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
2168 } else {
2169 /* Read distance code in the command, unless it was implicitly zero. */
2170 if (BROTLI_PREDICT_FALSE(s->block_length[2] == 0)(__builtin_expect(s->block_length[2] == 0, 0))) {
2171 BROTLI_SAFE_WITH_STATUS(DecodeDistanceBlockSwitch(s)){ BrotliDecoderErrorCode status; if (safe) { status = SafeDecodeDistanceBlockSwitch
(s); } else { status = DecodeDistanceBlockSwitch(s); } if (status
!= BROTLI_DECODER_SUCCESS) { result = status; goto saveStateAndReturn
; } }
;
2172 }
2173 BROTLI_SAFE(ReadDistance(s, br));
2174 }
2175 BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n",
2176 pos, s->distance_code));
2177 if (s->max_distance != s->max_backward_distance) {
2178 s->max_distance =
2179 (pos < s->max_backward_distance) ? pos : s->max_backward_distance;
2180 }
2181 i = s->copy_length;
2182 /* Apply copy of LZ77 back-reference, or static dictionary reference if
2183 the distance is larger than the max LZ77 distance */
2184 if (s->distance_code > s->max_distance) {
2185 /* The maximum allowed distance is BROTLI_MAX_ALLOWED_DISTANCE = 0x7FFFFFFC.
2186 With this choice, no signed overflow can occur after decoding
2187 a special distance code (e.g., after adding 3 to the last distance). */
2188 if (s->distance_code > BROTLI_MAX_ALLOWED_DISTANCE0x7FFFFFFC) {
2189 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
2190 "len: %d bytes left: %d\n",
2191 pos, s->distance_code, i, s->meta_block_remaining_len));
2192 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DISTANCE)((void)(0), BROTLI_DECODER_ERROR_FORMAT_DISTANCE);
2193 }
2194 if (s->distance_code - s->max_distance - 1 < compound_dictionary_size) {
2195 int address = compound_dictionary_size -
2196 (s->distance_code - s->max_distance);
2197 if (!InitializeCompoundDictionaryCopy(s, address, i)) {
2198 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY)((void)(0), BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY);
2199 }
2200 pos += CopyFromCompoundDictionary(s, pos);
2201 if (pos >= s->ringbuffer_size) {
2202 s->state = BROTLI_STATE_COMMAND_POST_WRITE_1;
2203 goto saveStateAndReturn;
2204 }
2205 } else if (i >= SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH4 &&
2206 i <= SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH31) {
2207 uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask];
2208 uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask];
2209 uint8_t dict_id = s->dictionary->context_based ?
2210 s->dictionary->context_map[BROTLI_CONTEXT(p1, p2, s->context_lookup)((s->context_lookup)[p1] | ((s->context_lookup) + 256)[
p2])
]
2211 : 0;
2212 const BrotliDictionary* words = s->dictionary->words[dict_id];
2213 const BrotliTransforms* transforms = s->dictionary->transforms[dict_id];
2214 int offset = (int)words->offsets_by_length[i];
2215 brotli_reg_tuint64_t shift = words->size_bits_by_length[i];
2216 int address =
2217 s->distance_code - s->max_distance - 1 - compound_dictionary_size;
2218 int mask = (int)BitMask(shift);
2219 int word_idx = address & mask;
2220 int transform_idx = address >> shift;
2221 /* Compensate double distance-ring-buffer roll. */
2222 s->dist_rb_idx += s->distance_context;
2223 offset += word_idx * i;
2224 /* If the distance is out of bound, select a next static dictionary if
2225 there exist multiple. */
2226 if ((transform_idx >= (int)transforms->num_transforms ||
2227 words->size_bits_by_length[i] == 0) &&
2228 s->dictionary->num_dictionaries > 1) {
2229 uint8_t dict_id2;
2230 int dist_remaining = address -
2231 (int)(((1u << shift) & ~1u)) * (int)transforms->num_transforms;
2232 for (dict_id2 = 0; dict_id2 < s->dictionary->num_dictionaries;
2233 dict_id2++) {
2234 const BrotliDictionary* words2 = s->dictionary->words[dict_id2];
2235 if (dict_id2 != dict_id && words2->size_bits_by_length[i] != 0) {
2236 const BrotliTransforms* transforms2 =
2237 s->dictionary->transforms[dict_id2];
2238 brotli_reg_tuint64_t shift2 = words2->size_bits_by_length[i];
2239 int num = (int)((1u << shift2) & ~1u) *
2240 (int)transforms2->num_transforms;
2241 if (dist_remaining < num) {
2242 dict_id = dict_id2;
Value stored to 'dict_id' is never read
2243 words = words2;
2244 transforms = transforms2;
2245 address = dist_remaining;
2246 shift = shift2;
2247 mask = (int)BitMask(shift);
2248 word_idx = address & mask;
2249 transform_idx = address >> shift;
2250 offset = (int)words->offsets_by_length[i] + word_idx * i;
2251 break;
2252 }
2253 dist_remaining -= num;
2254 }
2255 }
2256 }
2257 if (BROTLI_PREDICT_FALSE(words->size_bits_by_length[i] == 0)(__builtin_expect(words->size_bits_by_length[i] == 0, 0))) {
2258 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
2259 "len: %d bytes left: %d\n",
2260 pos, s->distance_code, i, s->meta_block_remaining_len));
2261 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY)((void)(0), BROTLI_DECODER_ERROR_FORMAT_DICTIONARY);
2262 }
2263 if (BROTLI_PREDICT_FALSE(!words->data)(__builtin_expect(!words->data, 0))) {
2264 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET)((void)(0), BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET);
2265 }
2266 if (transform_idx < (int)transforms->num_transforms) {
2267 const uint8_t* word = &words->data[offset];
2268 int len = i;
2269 if (transform_idx == transforms->cutOffTransforms[0]) {
2270 memcpy(&s->ringbuffer[pos], word, (size_t)len);
2271 BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s]\n",
2272 len, word));
2273 } else {
2274 len = BrotliTransformDictionaryWord(&s->ringbuffer[pos], word, len,
2275 transforms, transform_idx);
2276 BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s],"
2277 " transform_idx = %d, transformed: [%.*s]\n",
2278 i, word, transform_idx, len, &s->ringbuffer[pos]));
2279 if (len == 0 && s->distance_code <= 120) {
2280 BROTLI_LOG(("Invalid length-0 dictionary word after transform\n"));
2281 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM)((void)(0), BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
2282 }
2283 }
2284 pos += len;
2285 s->meta_block_remaining_len -= len;
2286 if (pos >= s->ringbuffer_size) {
2287 s->state = BROTLI_STATE_COMMAND_POST_WRITE_1;
2288 goto saveStateAndReturn;
2289 }
2290 } else {
2291 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
2292 "len: %d bytes left: %d\n",
2293 pos, s->distance_code, i, s->meta_block_remaining_len));
2294 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM)((void)(0), BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
2295 }
2296 } else {
2297 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
2298 "len: %d bytes left: %d\n",
2299 pos, s->distance_code, i, s->meta_block_remaining_len));
2300 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY)((void)(0), BROTLI_DECODER_ERROR_FORMAT_DICTIONARY);
2301 }
2302 } else {
2303 int src_start = (pos - s->distance_code) & s->ringbuffer_mask;
2304 uint8_t* copy_dst = &s->ringbuffer[pos];
2305 uint8_t* copy_src = &s->ringbuffer[src_start];
2306 int dst_end = pos + i;
2307 int src_end = src_start + i;
2308 /* Update the recent distances cache. */
2309 s->dist_rb[s->dist_rb_idx & 3] = s->distance_code;
2310 ++s->dist_rb_idx;
2311 s->meta_block_remaining_len -= i;
2312 /* There are 32+ bytes of slack in the ring-buffer allocation.
2313 Also, we have 16 short codes, that make these 16 bytes irrelevant
2314 in the ring-buffer. Let's copy over them as a first guess. */
2315 memmove16(copy_dst, copy_src);
2316 if (src_end > pos && dst_end > src_start) {
2317 /* Regions intersect. */
2318 goto CommandPostWrapCopy;
2319 }
2320 if (dst_end >= s->ringbuffer_size || src_end >= s->ringbuffer_size) {
2321 /* At least one region wraps. */
2322 goto CommandPostWrapCopy;
2323 }
2324 pos += i;
2325 if (i > 16) {
2326 if (i > 32) {
2327 memcpy(copy_dst + 16, copy_src + 16, (size_t)(i - 16));
2328 } else {
2329 /* This branch covers about 45% cases.
2330 Fixed size short copy allows more compiler optimizations. */
2331 memmove16(copy_dst + 16, copy_src + 16);
2332 }
2333 }
2334 }
2335 BROTLI_LOG_UINT(s->meta_block_remaining_len);
2336 if (s->meta_block_remaining_len <= 0) {
2337 /* Next metablock, if any. */
2338 s->state = BROTLI_STATE_METABLOCK_DONE;
2339 goto saveStateAndReturn;
2340 } else {
2341 goto CommandBegin;
2342 }
2343CommandPostWrapCopy:
2344 {
2345 int wrap_guard = s->ringbuffer_size - pos;
2346 while (--i >= 0) {
2347 s->ringbuffer[pos] =
2348 s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
2349 ++pos;
2350 if (BROTLI_PREDICT_FALSE(--wrap_guard == 0)(__builtin_expect(--wrap_guard == 0, 0))) {
2351 s->state = BROTLI_STATE_COMMAND_POST_WRITE_2;
2352 goto saveStateAndReturn;
2353 }
2354 }
2355 }
2356 if (s->meta_block_remaining_len <= 0) {
2357 /* Next metablock, if any. */
2358 s->state = BROTLI_STATE_METABLOCK_DONE;
2359 goto saveStateAndReturn;
2360 } else {
2361 goto CommandBegin;
2362 }
2363
2364NextLiteralBlock:
2365 BROTLI_SAFE_WITH_STATUS(DecodeLiteralBlockSwitch(s)){ BrotliDecoderErrorCode status; if (safe) { status = SafeDecodeLiteralBlockSwitch
(s); } else { status = DecodeLiteralBlockSwitch(s); } if (status
!= BROTLI_DECODER_SUCCESS) { result = status; goto saveStateAndReturn
; } }
;
2366 goto CommandInner;
2367
2368saveStateAndReturn:
2369 s->pos = pos;
2370 s->loop_counter = i;
2371 return result;
2372}
2373
2374#undef BROTLI_SAFE
2375
2376static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderErrorCode ProcessCommands(
2377 BrotliDecoderStateBrotliDecoderStateInternal* s) {
2378 return ProcessCommandsInternal(0, s);
2379}
2380
2381static BROTLI_NOINLINE__attribute__((__noinline__)) BrotliDecoderErrorCode SafeProcessCommands(
2382 BrotliDecoderStateBrotliDecoderStateInternal* s) {
2383 return ProcessCommandsInternal(1, s);
2384}
2385
2386BrotliDecoderResult BrotliDecoderDecompress(
2387 size_t encoded_size,
2388 const uint8_t encoded_buffer[BROTLI_ARRAY_PARAM(encoded_size)],
2389 size_t* decoded_size,
2390 uint8_t decoded_buffer[BROTLI_ARRAY_PARAM(*decoded_size)]) {
2391 BrotliDecoderStateBrotliDecoderStateInternal s;
2392 BrotliDecoderResult result;
2393 size_t total_out = 0;
2394 size_t available_in = encoded_size;
2395 const uint8_t* next_in = encoded_buffer;
2396 size_t available_out = *decoded_size;
2397 uint8_t* next_out = decoded_buffer;
2398 if (!BrotliDecoderStateInit(&s, 0, 0, 0)) {
2399 return BROTLI_DECODER_RESULT_ERROR;
2400 }
2401 result = BrotliDecoderDecompressStream(
2402 &s, &available_in, &next_in, &available_out, &next_out, &total_out);
2403 *decoded_size = total_out;
2404 BrotliDecoderStateCleanup(&s);
2405 if (result != BROTLI_DECODER_RESULT_SUCCESS) {
2406 result = BROTLI_DECODER_RESULT_ERROR;
2407 }
2408 return result;
2409}
2410
2411/* Invariant: input stream is never overconsumed:
2412 - invalid input implies that the whole stream is invalid -> any amount of
2413 input could be read and discarded
2414 - when result is "needs more input", then at least one more byte is REQUIRED
2415 to complete decoding; all input data MUST be consumed by decoder, so
2416 client could swap the input buffer
2417 - when result is "needs more output" decoder MUST ensure that it doesn't
2418 hold more than 7 bits in bit reader; this saves client from swapping input
2419 buffer ahead of time
2420 - when result is "success" decoder MUST return all unused data back to input
2421 buffer; this is possible because the invariant is held on enter */
2422BrotliDecoderResult BrotliDecoderDecompressStream(
2423 BrotliDecoderStateBrotliDecoderStateInternal* s, size_t* available_in, const uint8_t** next_in,
2424 size_t* available_out, uint8_t** next_out, size_t* total_out) {
2425 BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
2426 BrotliBitReader* br = &s->br;
2427 size_t input_size = *available_in;
2428#define BROTLI_SAVE_ERROR_CODE(code) \
2429 SaveErrorCode(s, (code), input_size - *available_in)
2430 /* Ensure that |total_out| is set, even if no data will ever be pushed out. */
2431 if (total_out) {
2432 *total_out = s->partial_pos_out;
2433 }
2434 /* Do not try to process further in a case of unrecoverable error. */
2435 if ((int)s->error_code < 0) {
2436 return BROTLI_DECODER_RESULT_ERROR;
2437 }
2438 if (*available_out && (!next_out || !*next_out)) {
2439 return BROTLI_SAVE_ERROR_CODE(
2440 BROTLI_FAILURE(BROTLI_DECODER_ERROR_INVALID_ARGUMENTS)((void)(0), BROTLI_DECODER_ERROR_INVALID_ARGUMENTS));
2441 }
2442 if (!*available_out) next_out = 0;
2443 if (s->buffer_length == 0) { /* Just connect bit reader to input stream. */
2444 BrotliBitReaderSetInput(br, *next_in, *available_in);
2445 } else {
2446 /* At least one byte of input is required. More than one byte of input may
2447 be required to complete the transaction -> reading more data must be
2448 done in a loop -> do it in a main loop. */
2449 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2450 BrotliBitReaderSetInput(br, &s->buffer.u8[0], s->buffer_length);
2451 }
2452 /* State machine */
2453 for (;;) {
2454 if (result != BROTLI_DECODER_SUCCESS) {
2455 /* Error, needs more input/output. */
2456 if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
2457 if (s->ringbuffer != 0) { /* Pro-actively push output. */
2458 BrotliDecoderErrorCode intermediate_result = WriteRingBuffer(s,
2459 available_out, next_out, total_out, BROTLI_TRUE1);
2460 /* WriteRingBuffer checks s->meta_block_remaining_len validity. */
2461 if ((int)intermediate_result < 0) {
2462 result = intermediate_result;
2463 break;
2464 }
2465 }
2466 if (s->buffer_length != 0) { /* Used with internal buffer. */
2467 if (br->next_in == br->last_in) {
2468 /* Successfully finished read transaction.
2469 Accumulator contains less than 8 bits, because internal buffer
2470 is expanded byte-by-byte until it is enough to complete read. */
2471 s->buffer_length = 0;
2472 /* Switch to input stream and restart. */
2473 result = BROTLI_DECODER_SUCCESS;
2474 BrotliBitReaderSetInput(br, *next_in, *available_in);
2475 continue;
2476 } else if (*available_in != 0) {
2477 /* Not enough data in buffer, but can take one more byte from
2478 input stream. */
2479 result = BROTLI_DECODER_SUCCESS;
2480 BROTLI_DCHECK(s->buffer_length < 8);
2481 s->buffer.u8[s->buffer_length] = **next_in;
2482 s->buffer_length++;
2483 BrotliBitReaderSetInput(br, &s->buffer.u8[0], s->buffer_length);
2484 (*next_in)++;
2485 (*available_in)--;
2486 /* Retry with more data in buffer. */
2487 continue;
2488 }
2489 /* Can't finish reading and no more input. */
2490 break;
2491 } else { /* Input stream doesn't contain enough input. */
2492 /* Copy tail to internal buffer and return. */
2493 *next_in = br->next_in;
2494 *available_in = BrotliBitReaderGetAvailIn(br);
2495 while (*available_in) {
2496 s->buffer.u8[s->buffer_length] = **next_in;
2497 s->buffer_length++;
2498 (*next_in)++;
2499 (*available_in)--;
2500 }
2501 break;
2502 }
2503 /* Unreachable. */
2504 }
2505
2506 /* Fail or needs more output. */
2507
2508 if (s->buffer_length != 0) {
2509 /* Just consumed the buffered input and produced some output. Otherwise
2510 it would result in "needs more input". Reset internal buffer. */
2511 s->buffer_length = 0;
2512 } else {
2513 /* Using input stream in last iteration. When decoder switches to input
2514 stream it has less than 8 bits in accumulator, so it is safe to
2515 return unused accumulator bits there. */
2516 BrotliBitReaderUnload(br);
2517 *available_in = BrotliBitReaderGetAvailIn(br);
2518 *next_in = br->next_in;
2519 }
2520 break;
2521 }
2522 switch (s->state) {
2523 case BROTLI_STATE_UNINITED:
2524 /* Prepare to the first read. */
2525 if (!BrotliWarmupBitReader(br)) {
2526 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2527 break;
2528 }
2529 /* Decode window size. */
2530 result = DecodeWindowBits(s, br); /* Reads 1..8 bits. */
2531 if (result != BROTLI_DECODER_SUCCESS) {
2532 break;
2533 }
2534 if (s->large_window) {
2535 s->state = BROTLI_STATE_LARGE_WINDOW_BITS;
2536 break;
2537 }
2538 s->state = BROTLI_STATE_INITIALIZE;
2539 break;
2540
2541 case BROTLI_STATE_LARGE_WINDOW_BITS: {
2542 brotli_reg_tuint64_t bits;
2543 if (!BrotliSafeReadBits(br, 6, &bits)) {
2544 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2545 break;
2546 }
2547 s->window_bits = bits & 63u;
2548 if (s->window_bits < BROTLI_LARGE_MIN_WBITS10 ||
2549 s->window_bits > BROTLI_LARGE_MAX_WBITS30) {
2550 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS)((void)(0), BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS);
2551 break;
2552 }
2553 s->state = BROTLI_STATE_INITIALIZE;
2554 }
2555 /* Fall through. */
2556
2557 case BROTLI_STATE_INITIALIZE:
2558 BROTLI_LOG_UINT(s->window_bits);
2559 /* Maximum distance, see section 9.1. of the spec. */
2560 s->max_backward_distance = (1 << s->window_bits) - BROTLI_WINDOW_GAP16;
2561
2562 /* Allocate memory for both block_type_trees and block_len_trees. */
2563 s->block_type_trees = (HuffmanCode*)BROTLI_DECODER_ALLOC(s,s->alloc_func(s->memory_manager_opaque, sizeof(HuffmanCode
) * 3 * (632 + 396))
2564 sizeof(HuffmanCode) * 3 *s->alloc_func(s->memory_manager_opaque, sizeof(HuffmanCode
) * 3 * (632 + 396))
2565 (BROTLI_HUFFMAN_MAX_SIZE_258 + BROTLI_HUFFMAN_MAX_SIZE_26))s->alloc_func(s->memory_manager_opaque, sizeof(HuffmanCode
) * 3 * (632 + 396))
;
2566 if (s->block_type_trees == 0) {
2567 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES)((void)(0), BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES);
2568 break;
2569 }
2570 s->block_len_trees =
2571 s->block_type_trees + 3 * BROTLI_HUFFMAN_MAX_SIZE_258632;
2572
2573 s->state = BROTLI_STATE_METABLOCK_BEGIN;
2574 /* Fall through. */
2575
2576 case BROTLI_STATE_METABLOCK_BEGIN:
2577 BrotliDecoderStateMetablockBegin(s);
2578 BROTLI_LOG_UINT(s->pos);
2579 s->state = BROTLI_STATE_METABLOCK_HEADER;
2580 /* Fall through. */
2581
2582 case BROTLI_STATE_METABLOCK_HEADER:
2583 result = DecodeMetaBlockLength(s, br); /* Reads 2 - 31 bits. */
2584 if (result != BROTLI_DECODER_SUCCESS) {
2585 break;
2586 }
2587 BROTLI_DCHECK(s->meta_block_remaining_len <=
2588 (int)BROTLI_BLOCK_SIZE_CAP);
2589 BROTLI_LOG_UINT(s->is_last_metablock);
2590 BROTLI_LOG_UINT(s->meta_block_remaining_len);
2591 BROTLI_LOG_UINT(s->is_metadata);
2592 BROTLI_LOG_UINT(s->is_uncompressed);
2593 if (s->is_metadata || s->is_uncompressed) {
2594 if (!BrotliJumpToByteBoundary(br)) {
2595 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1)((void)(0), BROTLI_DECODER_ERROR_FORMAT_PADDING_1);
2596 break;
2597 }
2598 }
2599 if (s->is_metadata) {
2600 s->state = BROTLI_STATE_METADATA;
2601 if (s->metadata_start_func) {
2602 s->metadata_start_func(s->metadata_callback_opaque,
2603 (size_t)s->meta_block_remaining_len);
2604 }
2605 break;
2606 }
2607 if (s->meta_block_remaining_len == 0) {
2608 s->state = BROTLI_STATE_METABLOCK_DONE;
2609 break;
2610 }
2611 BrotliCalculateRingBufferSize(s);
2612 if (s->is_uncompressed) {
2613 s->state = BROTLI_STATE_UNCOMPRESSED;
2614 break;
2615 }
2616 s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER;
2617 /* Fall through. */
2618
2619 case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER: {
2620 BrotliMetablockHeaderArena* h = &s->arena.header;
2621 s->loop_counter = 0;
2622 /* Initialize compressed metablock header arena. */
2623 h->sub_loop_counter = 0;
2624 /* Make small negative indexes addressable. */
2625 h->symbol_lists =
2626 &h->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH15 + 1];
2627 h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
2628 h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
2629 h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
2630 s->state = BROTLI_STATE_HUFFMAN_CODE_0;
2631 }
2632 /* Fall through. */
2633
2634 case BROTLI_STATE_HUFFMAN_CODE_0:
2635 if (s->loop_counter >= 3) {
2636 s->state = BROTLI_STATE_METABLOCK_HEADER_2;
2637 break;
2638 }
2639 /* Reads 1..11 bits. */
2640 result = DecodeVarLenUint8(s, br, &s->num_block_types[s->loop_counter]);
2641 if (result != BROTLI_DECODER_SUCCESS) {
2642 break;
2643 }
2644 s->num_block_types[s->loop_counter]++;
2645 BROTLI_LOG_UINT(s->num_block_types[s->loop_counter]);
2646 if (s->num_block_types[s->loop_counter] < 2) {
2647 s->loop_counter++;
2648 break;
2649 }
2650 s->state = BROTLI_STATE_HUFFMAN_CODE_1;
2651 /* Fall through. */
2652
2653 case BROTLI_STATE_HUFFMAN_CODE_1: {
2654 brotli_reg_tuint64_t alphabet_size = s->num_block_types[s->loop_counter] + 2;
2655 int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_258632;
2656 result = ReadHuffmanCode(alphabet_size, alphabet_size,
2657 &s->block_type_trees[tree_offset], NULL((void*)0), s);
2658 if (result != BROTLI_DECODER_SUCCESS) break;
2659 s->state = BROTLI_STATE_HUFFMAN_CODE_2;
2660 }
2661 /* Fall through. */
2662
2663 case BROTLI_STATE_HUFFMAN_CODE_2: {
2664 brotli_reg_tuint64_t alphabet_size = BROTLI_NUM_BLOCK_LEN_SYMBOLS26;
2665 int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26396;
2666 result = ReadHuffmanCode(alphabet_size, alphabet_size,
2667 &s->block_len_trees[tree_offset], NULL((void*)0), s);
2668 if (result != BROTLI_DECODER_SUCCESS) break;
2669 s->state = BROTLI_STATE_HUFFMAN_CODE_3;
2670 }
2671 /* Fall through. */
2672
2673 case BROTLI_STATE_HUFFMAN_CODE_3: {
2674 int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26396;
2675 if (!SafeReadBlockLength(s, &s->block_length[s->loop_counter],
2676 &s->block_len_trees[tree_offset], br)) {
2677 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2678 break;
2679 }
2680 BROTLI_LOG_UINT(s->block_length[s->loop_counter]);
2681 s->loop_counter++;
2682 s->state = BROTLI_STATE_HUFFMAN_CODE_0;
2683 break;
2684 }
2685
2686 case BROTLI_STATE_UNCOMPRESSED: {
2687 result = CopyUncompressedBlockToOutput(
2688 available_out, next_out, total_out, s);
2689 if (result != BROTLI_DECODER_SUCCESS) {
2690 break;
2691 }
2692 s->state = BROTLI_STATE_METABLOCK_DONE;
2693 break;
2694 }
2695
2696 case BROTLI_STATE_METADATA:
2697 result = SkipMetadataBlock(s);
2698 if (result != BROTLI_DECODER_SUCCESS) {
2699 break;
2700 }
2701 s->state = BROTLI_STATE_METABLOCK_DONE;
2702 break;
2703
2704 case BROTLI_STATE_METABLOCK_HEADER_2: {
2705 brotli_reg_tuint64_t bits;
2706 if (!BrotliSafeReadBits(br, 6, &bits)) {
2707 result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2708 break;
2709 }
2710 s->distance_postfix_bits = bits & BitMask(2);
2711 bits >>= 2;
2712 s->num_direct_distance_codes = bits << s->distance_postfix_bits;
2713 BROTLI_LOG_UINT(s->num_direct_distance_codes);
2714 BROTLI_LOG_UINT(s->distance_postfix_bits);
2715 s->context_modes =
2716 (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)s->num_block_types[0])s->alloc_func(s->memory_manager_opaque, (size_t)s->num_block_types
[0])
;
2717 if (s->context_modes == 0) {
2718 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES)((void)(0), BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES);
2719 break;
2720 }
2721 s->loop_counter = 0;
2722 s->state = BROTLI_STATE_CONTEXT_MODES;
2723 }
2724 /* Fall through. */
2725
2726 case BROTLI_STATE_CONTEXT_MODES:
2727 result = ReadContextModes(s);
2728 if (result != BROTLI_DECODER_SUCCESS) {
2729 break;
2730 }
2731 s->state = BROTLI_STATE_CONTEXT_MAP_1;
2732 /* Fall through. */
2733
2734 case BROTLI_STATE_CONTEXT_MAP_1:
2735 result = DecodeContextMap(
2736 s->num_block_types[0] << BROTLI_LITERAL_CONTEXT_BITS6,
2737 &s->num_literal_htrees, &s->context_map, s);
2738 if (result != BROTLI_DECODER_SUCCESS) {
2739 break;
2740 }
2741 DetectTrivialLiteralBlockTypes(s);
2742 s->state = BROTLI_STATE_CONTEXT_MAP_2;
2743 /* Fall through. */
2744
2745 case BROTLI_STATE_CONTEXT_MAP_2: {
2746 brotli_reg_tuint64_t npostfix = s->distance_postfix_bits;
2747 brotli_reg_tuint64_t ndirect = s->num_direct_distance_codes;
2748 brotli_reg_tuint64_t distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE(( 16 + (ndirect) + ((24U) << ((npostfix) + 1)))
2749 npostfix, ndirect, BROTLI_MAX_DISTANCE_BITS)( 16 + (ndirect) + ((24U) << ((npostfix) + 1)));
2750 brotli_reg_tuint64_t distance_alphabet_size_limit = distance_alphabet_size_max;
2751 BROTLI_BOOLint allocation_success = BROTLI_TRUE1;
2752 if (s->large_window) {
2753 BrotliDistanceCodeLimit limit = BrotliCalculateDistanceCodeLimit(
2754 BROTLI_MAX_ALLOWED_DISTANCE0x7FFFFFFC, (uint32_t)npostfix,
2755 (uint32_t)ndirect);
2756 distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE(( 16 + (ndirect) + ((62U) << ((npostfix) + 1)))
2757 npostfix, ndirect, BROTLI_LARGE_MAX_DISTANCE_BITS)( 16 + (ndirect) + ((62U) << ((npostfix) + 1)));
2758 distance_alphabet_size_limit = limit.max_alphabet_size;
2759 }
2760 result = DecodeContextMap(
2761 s->num_block_types[2] << BROTLI_DISTANCE_CONTEXT_BITS2,
2762 &s->num_dist_htrees, &s->dist_context_map, s);
2763 if (result != BROTLI_DECODER_SUCCESS) {
2764 break;
2765 }
2766 allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
2767 s, &s->literal_hgroup, BROTLI_NUM_LITERAL_SYMBOLS256,
2768 BROTLI_NUM_LITERAL_SYMBOLS256, s->num_literal_htrees);
2769 allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
2770 s, &s->insert_copy_hgroup, BROTLI_NUM_COMMAND_SYMBOLS704,
2771 BROTLI_NUM_COMMAND_SYMBOLS704, s->num_block_types[1]);
2772 allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
2773 s, &s->distance_hgroup, distance_alphabet_size_max,
2774 distance_alphabet_size_limit, s->num_dist_htrees);
2775 if (!allocation_success) {
2776 return BROTLI_SAVE_ERROR_CODE(
2777 BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS)((void)(0), BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS));
2778 }
2779 s->loop_counter = 0;
2780 s->state = BROTLI_STATE_TREE_GROUP;
2781 }
2782 /* Fall through. */
2783
2784 case BROTLI_STATE_TREE_GROUP: {
2785 HuffmanTreeGroup* hgroup = NULL((void*)0);
2786 switch (s->loop_counter) {
2787 case 0: hgroup = &s->literal_hgroup; break;
2788 case 1: hgroup = &s->insert_copy_hgroup; break;
2789 case 2: hgroup = &s->distance_hgroup; break;
2790 default: return BROTLI_SAVE_ERROR_CODE(BROTLI_FAILURE(((void)(0), BROTLI_DECODER_ERROR_UNREACHABLE)
2791 BROTLI_DECODER_ERROR_UNREACHABLE)((void)(0), BROTLI_DECODER_ERROR_UNREACHABLE)); /* COV_NF_LINE */
2792 }
2793 result = HuffmanTreeGroupDecode(hgroup, s);
2794 if (result != BROTLI_DECODER_SUCCESS) break;
2795 s->loop_counter++;
2796 if (s->loop_counter < 3) {
2797 break;
2798 }
2799 s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY;
2800 }
2801 /* Fall through. */
2802
2803 case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY:
2804 PrepareLiteralDecoding(s);
2805 s->dist_context_map_slice = s->dist_context_map;
2806 s->htree_command = s->insert_copy_hgroup.htrees[0];
2807 if (!BrotliEnsureRingBuffer(s)) {
2808 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2)((void)(0), BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
2809 break;
2810 }
2811 CalculateDistanceLut(s);
2812 s->state = BROTLI_STATE_COMMAND_BEGIN;
2813 /* Fall through. */
2814
2815 case BROTLI_STATE_COMMAND_BEGIN:
2816 /* Fall through. */
2817 case BROTLI_STATE_COMMAND_INNER:
2818 /* Fall through. */
2819 case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS:
2820 /* Fall through. */
2821 case BROTLI_STATE_COMMAND_POST_WRAP_COPY:
2822 result = ProcessCommands(s);
2823 if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
2824 result = SafeProcessCommands(s);
2825 }
2826 break;
2827
2828 case BROTLI_STATE_COMMAND_INNER_WRITE:
2829 /* Fall through. */
2830 case BROTLI_STATE_COMMAND_POST_WRITE_1:
2831 /* Fall through. */
2832 case BROTLI_STATE_COMMAND_POST_WRITE_2:
2833 result = WriteRingBuffer(
2834 s, available_out, next_out, total_out, BROTLI_FALSE0);
2835 if (result != BROTLI_DECODER_SUCCESS) {
2836 break;
2837 }
2838 WrapRingBuffer(s);
2839 if (s->ringbuffer_size == 1 << s->window_bits) {
2840 s->max_distance = s->max_backward_distance;
2841 }
2842 if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) {
2843 BrotliDecoderCompoundDictionary* addon = s->compound_dictionary;
2844 if (addon && (addon->br_length != addon->br_copied)) {
2845 s->pos += CopyFromCompoundDictionary(s, s->pos);
2846 if (s->pos >= s->ringbuffer_size) continue;
2847 }
2848 if (s->meta_block_remaining_len == 0) {
2849 /* Next metablock, if any. */
2850 s->state = BROTLI_STATE_METABLOCK_DONE;
2851 } else {
2852 s->state = BROTLI_STATE_COMMAND_BEGIN;
2853 }
2854 break;
2855 } else if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_2) {
2856 s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY;
2857 } else { /* BROTLI_STATE_COMMAND_INNER_WRITE */
2858 if (s->loop_counter == 0) {
2859 if (s->meta_block_remaining_len == 0) {
2860 s->state = BROTLI_STATE_METABLOCK_DONE;
2861 } else {
2862 s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2863 }
2864 break;
2865 }
2866 s->state = BROTLI_STATE_COMMAND_INNER;
2867 }
2868 break;
2869
2870 case BROTLI_STATE_METABLOCK_DONE:
2871 if (s->meta_block_remaining_len < 0) {
2872 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2)((void)(0), BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2);
2873 break;
2874 }
2875 BrotliDecoderStateCleanupAfterMetablock(s);
2876 if (!s->is_last_metablock) {
2877 s->state = BROTLI_STATE_METABLOCK_BEGIN;
2878 break;
2879 }
2880 if (!BrotliJumpToByteBoundary(br)) {
2881 result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2)((void)(0), BROTLI_DECODER_ERROR_FORMAT_PADDING_2);
2882 break;
2883 }
2884 if (s->buffer_length == 0) {
2885 BrotliBitReaderUnload(br);
2886 *available_in = BrotliBitReaderGetAvailIn(br);
2887 *next_in = br->next_in;
2888 }
2889 s->state = BROTLI_STATE_DONE;
2890 /* Fall through. */
2891
2892 case BROTLI_STATE_DONE:
2893 if (s->ringbuffer != 0) {
2894 result = WriteRingBuffer(
2895 s, available_out, next_out, total_out, BROTLI_TRUE1);
2896 if (result != BROTLI_DECODER_SUCCESS) {
2897 break;
2898 }
2899 }
2900 return BROTLI_SAVE_ERROR_CODE(result);
2901 }
2902 }
2903 return BROTLI_SAVE_ERROR_CODE(result);
2904#undef BROTLI_SAVE_ERROR_CODE
2905}
2906
2907BROTLI_BOOLint BrotliDecoderHasMoreOutput(const BrotliDecoderStateBrotliDecoderStateInternal* s) {
2908 /* After unrecoverable error remaining output is considered nonsensical. */
2909 if ((int)s->error_code < 0) {
2910 return BROTLI_FALSE0;
2911 }
2912 return TO_BROTLI_BOOL((!!(s->ringbuffer != 0 && UnwrittenBytes(s, 0) != 0
) ? 1 : 0)
2913 s->ringbuffer != 0 && UnwrittenBytes(s, BROTLI_FALSE) != 0)(!!(s->ringbuffer != 0 && UnwrittenBytes(s, 0) != 0
) ? 1 : 0)
;
2914}
2915
2916const uint8_t* BrotliDecoderTakeOutput(BrotliDecoderStateBrotliDecoderStateInternal* s, size_t* size) {
2917 uint8_t* result = 0;
2918 size_t available_out = *size ? *size : 1u << 24;
2919 size_t requested_out = available_out;
2920 BrotliDecoderErrorCode status;
2921 if ((s->ringbuffer == 0) || ((int)s->error_code < 0)) {
2922 *size = 0;
2923 return 0;
2924 }
2925 WrapRingBuffer(s);
2926 status = WriteRingBuffer(s, &available_out, &result, 0, BROTLI_TRUE1);
2927 /* Either WriteRingBuffer returns those "success" codes... */
2928 if (status == BROTLI_DECODER_SUCCESS ||
2929 status == BROTLI_DECODER_NEEDS_MORE_OUTPUT) {
2930 *size = requested_out - available_out;
2931 } else {
2932 /* ... or stream is broken. Normally this should be caught by
2933 BrotliDecoderDecompressStream, this is just a safeguard. */
2934 if ((int)status < 0) SaveErrorCode(s, status, 0);
2935 *size = 0;
2936 result = 0;
2937 }
2938 return result;
2939}
2940
2941BROTLI_BOOLint BrotliDecoderIsUsed(const BrotliDecoderStateBrotliDecoderStateInternal* s) {
2942 return TO_BROTLI_BOOL(s->state != BROTLI_STATE_UNINITED ||(!!(s->state != BROTLI_STATE_UNINITED || BrotliGetAvailableBits
(&s->br) != 0) ? 1 : 0)
2943 BrotliGetAvailableBits(&s->br) != 0)(!!(s->state != BROTLI_STATE_UNINITED || BrotliGetAvailableBits
(&s->br) != 0) ? 1 : 0)
;
2944}
2945
2946BROTLI_BOOLint BrotliDecoderIsFinished(const BrotliDecoderStateBrotliDecoderStateInternal* s) {
2947 return TO_BROTLI_BOOL(s->state == BROTLI_STATE_DONE)(!!(s->state == BROTLI_STATE_DONE) ? 1 : 0) &&
2948 !BrotliDecoderHasMoreOutput(s);
2949}
2950
2951BrotliDecoderErrorCode BrotliDecoderGetErrorCode(const BrotliDecoderStateBrotliDecoderStateInternal* s) {
2952 return (BrotliDecoderErrorCode)s->error_code;
2953}
2954
2955const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c) {
2956 switch (c) {
2957#define BROTLI_ERROR_CODE_CASE_(PREFIX, NAME, CODE) \
2958 case BROTLI_DECODER ## PREFIX ## NAME: return #PREFIX #NAME;
2959#define BROTLI_NOTHING_
2960 BROTLI_DECODER_ERROR_CODES_LIST(BROTLI_ERROR_CODE_CASE_, BROTLI_NOTHING_)BROTLI_ERROR_CODE_CASE_(_, NO_ERROR, 0) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_, SUCCESS, 1) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_(_, NEEDS_MORE_INPUT
, 2) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_(_, NEEDS_MORE_OUTPUT
, 3) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_(_ERROR_FORMAT_, EXUBERANT_NIBBLE
, -1) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_(_ERROR_FORMAT_,
RESERVED, -2) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_(_ERROR_FORMAT_
, EXUBERANT_META_NIBBLE, -3) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, SIMPLE_HUFFMAN_ALPHABET, -4) BROTLI_NOTHING_
BROTLI_ERROR_CODE_CASE_(_ERROR_FORMAT_, SIMPLE_HUFFMAN_SAME,
-5) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_(_ERROR_FORMAT_, CL_SPACE
, -6) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_(_ERROR_FORMAT_,
HUFFMAN_SPACE, -7) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_(_ERROR_FORMAT_
, CONTEXT_MAP_REPEAT, -8) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, BLOCK_LENGTH_1, -9) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, BLOCK_LENGTH_2, -10) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, TRANSFORM, -11) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, DICTIONARY, -12) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, WINDOW_BITS, -13) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, PADDING_1, -14) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, PADDING_2, -15) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, DISTANCE, -16) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_FORMAT_, BLOCK_SWITCH, -17) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_, COMPOUND_DICTIONARY, -18) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_, DICTIONARY_NOT_SET, -19) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_, INVALID_ARGUMENTS, -20) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_ALLOC_, CONTEXT_MODES, -21) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_ALLOC_, TREE_GROUPS, -22) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_ALLOC_, CONTEXT_MAP, -25) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_ALLOC_, RING_BUFFER_1, -26) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_ALLOC_, RING_BUFFER_2, -27) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_ALLOC_, BLOCK_TYPE_TREES, -30) BROTLI_NOTHING_ BROTLI_ERROR_CODE_CASE_
(_ERROR_, UNREACHABLE, -31)
2961#undef BROTLI_ERROR_CODE_CASE_
2962#undef BROTLI_NOTHING_
2963 default: return "INVALID";
2964 }
2965}
2966
2967uint32_t BrotliDecoderVersion(void) {
2968 return BROTLI_VERSION((1 << 24) | (2 << 12) | 0);
2969}
2970
2971void BrotliDecoderSetMetadataCallbacks(
2972 BrotliDecoderStateBrotliDecoderStateInternal* state,
2973 brotli_decoder_metadata_start_func start_func,
2974 brotli_decoder_metadata_chunk_func chunk_func, void* opaque) {
2975 state->metadata_start_func = start_func;
2976 state->metadata_chunk_func = chunk_func;
2977 state->metadata_callback_opaque = opaque;
2978}
2979
2980/* Escalate internal functions visibility; for testing purposes only. */
2981#if defined(BROTLI_TEST)
2982BROTLI_BOOLint BrotliSafeReadSymbolForTest(
2983 const HuffmanCode*, BrotliBitReader*, brotli_reg_tuint64_t*);
2984BROTLI_BOOLint BrotliSafeReadSymbolForTest(
2985 const HuffmanCode* table, BrotliBitReader* br, brotli_reg_tuint64_t* result) {
2986 return SafeReadSymbol(table, br, result);
2987}
2988void BrotliInverseMoveToFrontTransformForTest(
2989 uint8_t*, brotli_reg_tuint64_t, BrotliDecoderStateBrotliDecoderStateInternal*);
2990void BrotliInverseMoveToFrontTransformForTest(
2991 uint8_t* v, brotli_reg_tuint64_t l, BrotliDecoderStateBrotliDecoderStateInternal* s) {
2992 InverseMoveToFrontTransform(v, l, s);
2993}
2994#endif
2995
2996#if defined(__cplusplus) || defined(c_plusplus)
2997} /* extern "C" */
2998#endif