Coverage Report

Created: 2022-08-24 06:33

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