Coverage Report

Created: 2026-11-12 07:35

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