Coverage Report

Created: 2025-11-16 06:36

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