Coverage Report

Created: 2024-05-21 06:41

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