Coverage Report

Created: 2026-07-15 07:31

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