Coverage Report

Created: 2026-08-11 07:29

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