Coverage Report

Created: 2026-09-14 07:37

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