Coverage Report

Created: 2026-10-28 07:26

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