Bug Summary

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