Coverage Report

Created: 2026-04-01 07:49

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
368
#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
392k
#define HUFFMAN_TABLE_BITS 8U
39
80.7k
#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
631
    brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
81
631
  BrotliDecoderState* state = 0;
82
631
  if (!BrotliDecoderEnsureStaticInit()) {
83
0
    BROTLI_DUMP();
84
0
    return 0;
85
0
  }
86
631
  if (!alloc_func && !free_func) {
87
631
    state = (BrotliDecoderState*)malloc(sizeof(BrotliDecoderState));
88
631
  } else if (alloc_func && free_func) {
89
0
    state = (BrotliDecoderState*)alloc_func(opaque, sizeof(BrotliDecoderState));
90
0
  }
91
631
  if (state == 0) {
92
0
    BROTLI_DUMP();
93
0
    return 0;
94
0
  }
95
631
  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
631
  return state;
105
631
}
106
107
/* Deinitializes and frees BrotliDecoderState instance. */
108
631
void BrotliDecoderDestroyInstance(BrotliDecoderState* state) {
109
631
  if (!state) {
110
0
    return;
111
631
  } else {
112
631
    brotli_free_func free_func = state->free_func;
113
631
    void* opaque = state->memory_manager_opaque;
114
631
    BrotliDecoderStateCleanup(state);
115
631
    free_func(opaque, state);
116
631
  }
117
631
}
118
119
/* Saves error code and converts it to BrotliDecoderResult. */
120
static BROTLI_NOINLINE BrotliDecoderResult SaveErrorCode(
121
631
    BrotliDecoderState* s, BrotliDecoderErrorCode e, size_t consumed_input) {
122
631
  s->error_code = (int)e;
123
631
  s->used_input += consumed_input;
124
631
  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
631
  switch (e) {
129
47
    case BROTLI_DECODER_SUCCESS:
130
47
      return BROTLI_DECODER_RESULT_SUCCESS;
131
132
216
    case BROTLI_DECODER_NEEDS_MORE_INPUT:
133
216
      return BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
134
135
0
    case BROTLI_DECODER_NEEDS_MORE_OUTPUT:
136
0
      return BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
137
138
368
    default:
139
368
      return BROTLI_DECODER_RESULT_ERROR;
140
631
  }
141
631
}
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
629
                                               BrotliBitReader* br) {
147
629
  brotli_reg_t n;
148
629
  BROTLI_BOOL large_window = s->large_window;
149
629
  s->large_window = BROTLI_FALSE;
150
629
  BrotliTakeBits(br, 1, &n);
151
629
  if (n == 0) {
152
403
    s->window_bits = 16;
153
403
    return BROTLI_DECODER_SUCCESS;
154
403
  }
155
226
  BrotliTakeBits(br, 3, &n);
156
226
  if (n != 0) {
157
88
    s->window_bits = (17u + n) & 63u;
158
88
    return BROTLI_DECODER_SUCCESS;
159
88
  }
160
138
  BrotliTakeBits(br, 3, &n);
161
138
  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
136
  if (n != 0) {
174
21
    s->window_bits = (8u + n) & 63u;
175
21
    return BROTLI_DECODER_SUCCESS;
176
21
  }
177
115
  s->window_bits = 17;
178
115
  return BROTLI_DECODER_SUCCESS;
179
136
}
180
181
119k
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
119k
  uint32_t buffer[4];
186
119k
  memcpy(buffer, src, 16);
187
119k
  memcpy(dst, buffer, 16);
188
119k
#endif
189
119k
}
190
191
/* Decodes a number in the range [0..255], by reading 1 - 11 bits. */
192
static BROTLI_NOINLINE BrotliDecoderErrorCode DecodeVarLenUint8(
193
2.54k
    BrotliDecoderState* s, BrotliBitReader* br, brotli_reg_t* value) {
194
2.54k
  brotli_reg_t bits;
195
2.54k
  switch (s->substate_decode_uint8) {
196
2.54k
    case BROTLI_STATE_DECODE_UINT8_NONE:
197
2.54k
      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 1, &bits))) {
198
0
        return BROTLI_DECODER_NEEDS_MORE_INPUT;
199
0
      }
200
2.54k
      if (bits == 0) {
201
2.26k
        *value = 0;
202
2.26k
        return BROTLI_DECODER_SUCCESS;
203
2.26k
      }
204
    /* Fall through. */
205
206
288
    case BROTLI_STATE_DECODE_UINT8_SHORT:
207
288
      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 3, &bits))) {
208
0
        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_SHORT;
209
0
        return BROTLI_DECODER_NEEDS_MORE_INPUT;
210
0
      }
211
288
      if (bits == 0) {
212
33
        *value = 1;
213
33
        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
214
33
        return BROTLI_DECODER_SUCCESS;
215
33
      }
216
      /* Use output value as a temporary storage. It MUST be persisted. */
217
255
      *value = bits;
218
    /* Fall through. */
219
220
255
    case BROTLI_STATE_DECODE_UINT8_LONG:
221
255
      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, *value, &bits))) {
222
0
        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_LONG;
223
0
        return BROTLI_DECODER_NEEDS_MORE_INPUT;
224
0
      }
225
255
      *value = ((brotli_reg_t)1U << *value) + bits;
226
255
      s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
227
255
      return BROTLI_DECODER_SUCCESS;
228
229
0
    default:
230
0
      return
231
0
          BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);  /* COV_NF_LINE */
232
2.54k
  }
233
2.54k
}
234
235
/* Decodes a metablock length and flags by reading 2 - 31 bits. */
236
static BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength(
237
706
    BrotliDecoderState* s, BrotliBitReader* br) {
238
706
  brotli_reg_t bits;
239
706
  int i;
240
1.29k
  for (;;) {
241
1.29k
    switch (s->substate_metablock_header) {
242
706
      case BROTLI_STATE_METABLOCK_HEADER_NONE:
243
706
        if (!BrotliSafeReadBits(br, 1, &bits)) {
244
1
          return BROTLI_DECODER_NEEDS_MORE_INPUT;
245
1
        }
246
705
        s->is_last_metablock = bits ? 1 : 0;
247
705
        s->meta_block_remaining_len = 0;
248
705
        s->is_uncompressed = 0;
249
705
        s->is_metadata = 0;
250
705
        if (!s->is_last_metablock) {
251
526
          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
252
526
          break;
253
526
        }
254
179
        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_EMPTY;
255
      /* Fall through. */
256
257
179
      case BROTLI_STATE_METABLOCK_HEADER_EMPTY:
258
179
        if (!BrotliSafeReadBits(br, 1, &bits)) {
259
1
          return BROTLI_DECODER_NEEDS_MORE_INPUT;
260
1
        }
261
178
        if (bits) {
262
36
          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
263
36
          return BROTLI_DECODER_SUCCESS;
264
36
        }
265
142
        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
266
      /* Fall through. */
267
268
668
      case BROTLI_STATE_METABLOCK_HEADER_NIBBLES:
269
668
        if (!BrotliSafeReadBits(br, 2, &bits)) {
270
1
          return BROTLI_DECODER_NEEDS_MORE_INPUT;
271
1
        }
272
667
        s->size_nibbles = (uint8_t)(bits + 4);
273
667
        s->loop_counter = 0;
274
667
        if (bits == 3) {
275
67
          s->is_metadata = 1;
276
67
          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_RESERVED;
277
67
          break;
278
67
        }
279
600
        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_SIZE;
280
      /* Fall through. */
281
282
600
      case BROTLI_STATE_METABLOCK_HEADER_SIZE:
283
600
        i = s->loop_counter;
284
3.13k
        for (; i < (int)s->size_nibbles; ++i) {
285
2.54k
          if (!BrotliSafeReadBits(br, 4, &bits)) {
286
3
            s->loop_counter = i;
287
3
            return BROTLI_DECODER_NEEDS_MORE_INPUT;
288
3
          }
289
2.54k
          if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 4 &&
290
95
              bits == 0) {
291
2
            return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE);
292
2
          }
293
2.53k
          s->meta_block_remaining_len |= (int)(bits << (i * 4));
294
2.53k
        }
295
595
        s->substate_metablock_header =
296
595
            BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED;
297
      /* Fall through. */
298
299
595
      case BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED:
300
595
        if (!s->is_last_metablock) {
301
475
          if (!BrotliSafeReadBits(br, 1, &bits)) {
302
0
            return BROTLI_DECODER_NEEDS_MORE_INPUT;
303
0
          }
304
475
          s->is_uncompressed = bits ? 1 : 0;
305
475
        }
306
595
        ++s->meta_block_remaining_len;
307
595
        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
308
595
        return BROTLI_DECODER_SUCCESS;
309
310
67
      case BROTLI_STATE_METABLOCK_HEADER_RESERVED:
311
67
        if (!BrotliSafeReadBits(br, 1, &bits)) {
312
1
          return BROTLI_DECODER_NEEDS_MORE_INPUT;
313
1
        }
314
66
        if (bits != 0) {
315
3
          return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_RESERVED);
316
3
        }
317
63
        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_BYTES;
318
      /* Fall through. */
319
320
63
      case BROTLI_STATE_METABLOCK_HEADER_BYTES:
321
63
        if (!BrotliSafeReadBits(br, 2, &bits)) {
322
1
          return BROTLI_DECODER_NEEDS_MORE_INPUT;
323
1
        }
324
62
        if (bits == 0) {
325
25
          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
326
25
          return BROTLI_DECODER_SUCCESS;
327
25
        }
328
37
        s->size_nibbles = (uint8_t)bits;
329
37
        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_METADATA;
330
      /* Fall through. */
331
332
37
      case BROTLI_STATE_METABLOCK_HEADER_METADATA:
333
37
        i = s->loop_counter;
334
102
        for (; i < (int)s->size_nibbles; ++i) {
335
68
          if (!BrotliSafeReadBits(br, 8, &bits)) {
336
1
            s->loop_counter = i;
337
1
            return BROTLI_DECODER_NEEDS_MORE_INPUT;
338
1
          }
339
67
          if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 1 &&
340
19
              bits == 0) {
341
2
            return BROTLI_FAILURE(
342
2
                BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE);
343
2
          }
344
65
          s->meta_block_remaining_len |= (int)(bits << (i * 8));
345
65
        }
346
34
        ++s->meta_block_remaining_len;
347
34
        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
348
34
        return BROTLI_DECODER_SUCCESS;
349
350
0
      default:
351
0
        return
352
0
            BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);  /* COV_NF_LINE */
353
1.29k
    }
354
1.29k
  }
355
706
}
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
227k
                                               BrotliBitReader* br) {
364
227k
  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
365
227k
  BROTLI_HC_ADJUST_TABLE_INDEX(table, bits & HUFFMAN_TABLE_MASK);
366
227k
  if (BROTLI_HC_FAST_LOAD_BITS(table) > HUFFMAN_TABLE_BITS) {
367
592
    brotli_reg_t nbits = BROTLI_HC_FAST_LOAD_BITS(table) - HUFFMAN_TABLE_BITS;
368
592
    BrotliDropBits(br, HUFFMAN_TABLE_BITS);
369
592
    BROTLI_HC_ADJUST_TABLE_INDEX(table,
370
592
        BROTLI_HC_FAST_LOAD_VALUE(table) +
371
592
        ((bits >> HUFFMAN_TABLE_BITS) & BitMask(nbits)));
372
592
  }
373
227k
  BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table));
374
227k
  return BROTLI_HC_FAST_LOAD_VALUE(table);
375
227k
}
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
154k
                                             BrotliBitReader* br) {
381
154k
  return DecodeSymbol(BrotliGet16BitsUnmasked(br), table, br);
382
154k
}
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
507
    const HuffmanCode* table, BrotliBitReader* br, brotli_reg_t* result) {
388
507
  brotli_reg_t val;
389
507
  brotli_reg_t available_bits = BrotliGetAvailableBits(br);
390
507
  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
391
507
  if (available_bits == 0) {
392
32
    if (BROTLI_HC_FAST_LOAD_BITS(table) == 0) {
393
2
      *result = BROTLI_HC_FAST_LOAD_VALUE(table);
394
2
      return BROTLI_TRUE;
395
2
    }
396
30
    return BROTLI_FALSE;  /* No valid bits at all. */
397
32
  }
398
475
  val = BrotliGetBitsUnmasked(br);
399
475
  BROTLI_HC_ADJUST_TABLE_INDEX(table, val & HUFFMAN_TABLE_MASK);
400
475
  if (BROTLI_HC_FAST_LOAD_BITS(table) <= HUFFMAN_TABLE_BITS) {
401
451
    if (BROTLI_HC_FAST_LOAD_BITS(table) <= available_bits) {
402
369
      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table));
403
369
      *result = BROTLI_HC_FAST_LOAD_VALUE(table);
404
369
      return BROTLI_TRUE;
405
369
    } else {
406
82
      return BROTLI_FALSE;  /* Not enough bits for the first level. */
407
82
    }
408
451
  }
409
24
  if (available_bits <= HUFFMAN_TABLE_BITS) {
410
14
    return BROTLI_FALSE;  /* Not enough bits to move to the second level. */
411
14
  }
412
413
  /* Speculatively drop HUFFMAN_TABLE_BITS. */
414
10
  val = (val & BitMask(BROTLI_HC_FAST_LOAD_BITS(table))) >> HUFFMAN_TABLE_BITS;
415
10
  available_bits -= HUFFMAN_TABLE_BITS;
416
10
  BROTLI_HC_ADJUST_TABLE_INDEX(table, BROTLI_HC_FAST_LOAD_VALUE(table) + val);
417
10
  if (available_bits < BROTLI_HC_FAST_LOAD_BITS(table)) {
418
3
    return BROTLI_FALSE;  /* Not enough bits for the second level. */
419
3
  }
420
421
7
  BrotliDropBits(br, HUFFMAN_TABLE_BITS + BROTLI_HC_FAST_LOAD_BITS(table));
422
7
  *result = BROTLI_HC_FAST_LOAD_VALUE(table);
423
7
  return BROTLI_TRUE;
424
10
}
425
426
static BROTLI_INLINE BROTLI_BOOL SafeReadSymbol(
427
73.3k
    const HuffmanCode* table, BrotliBitReader* br, brotli_reg_t* result) {
428
73.3k
  brotli_reg_t val;
429
73.3k
  if (BROTLI_PREDICT_TRUE(BrotliSafeGetBits(br, 15, &val))) {
430
72.8k
    *result = DecodeSymbol(val, table, br);
431
72.8k
    return BROTLI_TRUE;
432
72.8k
  }
433
507
  return SafeDecodeSymbol(table, br, result);
434
73.3k
}
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
764k
                                        brotli_reg_t* value) {
442
764k
  if (safe) {
443
1.33k
    return;
444
1.33k
  }
445
763k
  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
446
763k
  BROTLI_HC_ADJUST_TABLE_INDEX(table, BrotliGetBits(br, HUFFMAN_TABLE_BITS));
447
763k
  *bits = BROTLI_HC_FAST_LOAD_BITS(table);
448
763k
  *value = BROTLI_HC_FAST_LOAD_VALUE(table);
449
763k
}
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
645k
                                                  brotli_reg_t* value) {
457
645k
  brotli_reg_t result = *value;
458
645k
  if (BROTLI_PREDICT_FALSE(*bits > HUFFMAN_TABLE_BITS)) {
459
80.7k
    brotli_reg_t val = BrotliGet16BitsUnmasked(br);
460
80.7k
    const HuffmanCode* ext = table + (val & HUFFMAN_TABLE_MASK) + *value;
461
80.7k
    brotli_reg_t mask = BitMask((*bits - HUFFMAN_TABLE_BITS));
462
80.7k
    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(ext);
463
80.7k
    BrotliDropBits(br, HUFFMAN_TABLE_BITS);
464
80.7k
    BROTLI_HC_ADJUST_TABLE_INDEX(ext, (val >> HUFFMAN_TABLE_BITS) & mask);
465
80.7k
    BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(ext));
466
80.7k
    result = BROTLI_HC_FAST_LOAD_VALUE(ext);
467
564k
  } else {
468
564k
    BrotliDropBits(br, *bits);
469
564k
  }
470
645k
  PreloadSymbol(0, table, br, bits, value);
471
645k
  return result;
472
645k
}
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
222k
                                                        const int limit) {
484
  /* Calculate range where CheckInputAmount is always true.
485
     Start with the number of bytes we can read. */
486
222k
  int64_t new_lim = br->guard_in - br->next_in;
487
  /* Convert to bits, since symbols use variable number of bits. */
488
222k
  new_lim *= 8;
489
  /* At most 15 bits per symbol, so this is safe. */
490
222k
  new_lim /= 15;
491
222k
  const int kMaximalOverread = 4;
492
222k
  int pos_limit = limit;
493
222k
  int copies = 0;
494
222k
  if ((new_lim - kMaximalOverread) <= limit) {
495
    // Safe cast, since new_lim is already < num_steps
496
1.17k
    pos_limit = (int)(new_lim - kMaximalOverread);
497
1.17k
  }
498
222k
  if (pos_limit < 0) {
499
558
    pos_limit = 0;
500
558
  }
501
222k
  copies = pos_limit;
502
222k
  pos_limit += pos;
503
  /* Fast path, caller made sure it is safe to write,
504
     we verified that is is safe to read. */
505
832k
  for (; pos < pos_limit; pos++) {
506
610k
    BROTLI_DCHECK(BrotliCheckInputAmount(br));
507
610k
    ringbuffer[pos] = (uint8_t)ReadPreloadedSymbol(table, br, bits, value);
508
610k
    BROTLI_LOG_ARRAY_INDEX(ringbuffer, pos);
509
610k
  }
510
  /* Do the remainder, caller made sure it is safe to write,
511
     we need to bverify that it is safe to read. */
512
257k
  while (BrotliCheckInputAmount(br) && copies < limit) {
513
34.8k
    ringbuffer[pos] = (uint8_t)ReadPreloadedSymbol(table, br, bits, value);
514
34.8k
    BROTLI_LOG_ARRAY_INDEX(ringbuffer, pos);
515
34.8k
    pos++;
516
34.8k
    copies++;
517
34.8k
  }
518
222k
  return copies;
519
222k
}
520
521
735
static BROTLI_INLINE brotli_reg_t Log2Floor(brotli_reg_t x) {
522
735
  brotli_reg_t result = 0;
523
6.02k
  while (x) {
524
5.28k
    x >>= 1;
525
5.28k
    ++result;
526
5.28k
  }
527
735
  return result;
528
735
}
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
735
    BrotliDecoderState* s) {
536
  /* max_bits == 1..11; symbol == 0..3; 1..44 bits will be read. */
537
735
  BrotliBitReader* br = &s->br;
538
735
  BrotliMetablockHeaderArena* h = &s->arena.header;
539
735
  brotli_reg_t max_bits = Log2Floor(alphabet_size_max - 1);
540
735
  brotli_reg_t i = h->sub_loop_counter;
541
735
  brotli_reg_t num_symbols = h->symbol;
542
2.36k
  while (i <= num_symbols) {
543
1.63k
    brotli_reg_t v;
544
1.63k
    if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))) {
545
2
      h->sub_loop_counter = i;
546
2
      h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ;
547
2
      return BROTLI_DECODER_NEEDS_MORE_INPUT;
548
2
    }
549
1.63k
    if (v >= alphabet_size_limit) {
550
9
      return
551
9
          BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET);
552
9
    }
553
1.62k
    h->symbols_lists_array[i] = (uint16_t)v;
554
1.62k
    BROTLI_LOG_UINT(h->symbols_lists_array[i]);
555
1.62k
    ++i;
556
1.62k
  }
557
558
1.61k
  for (i = 0; i < num_symbols; ++i) {
559
892
    brotli_reg_t k = i + 1;
560
2.25k
    for (; k <= num_symbols; ++k) {
561
1.36k
      if (h->symbols_lists_array[i] == h->symbols_lists_array[k]) {
562
4
        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME);
563
4
      }
564
1.36k
    }
565
892
  }
566
567
720
  return BROTLI_DECODER_SUCCESS;
568
724
}
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
61.1k
    uint16_t* code_length_histo, int* next_symbol) {
580
61.1k
  *repeat = 0;
581
61.1k
  if (code_len != 0) {  /* code_len == 1..15 */
582
59.2k
    symbol_lists[next_symbol[code_len]] = (uint16_t)(*symbol);
583
59.2k
    next_symbol[code_len] = (int)(*symbol);
584
59.2k
    *prev_code_len = code_len;
585
59.2k
    *space -= 32768U >> code_len;
586
59.2k
    code_length_histo[code_len]++;
587
59.2k
    BROTLI_LOG(("[ReadHuffmanCode] code_length[%d] = %d\n",
588
59.2k
        (int)*symbol, (int)code_len));
589
59.2k
  }
590
61.1k
  (*symbol)++;
591
61.1k
}
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
3.71k
    uint16_t* code_length_histo, int* next_symbol) {
608
3.71k
  brotli_reg_t old_repeat;
609
3.71k
  brotli_reg_t extra_bits = 3;  /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
610
3.71k
  brotli_reg_t new_len = 0;  /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
611
3.71k
  if (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
612
2.92k
    new_len = *prev_code_len;
613
2.92k
    extra_bits = 2;
614
2.92k
  }
615
3.71k
  if (*repeat_code_len != new_len) {
616
1.90k
    *repeat = 0;
617
1.90k
    *repeat_code_len = new_len;
618
1.90k
  }
619
3.71k
  old_repeat = *repeat;
620
3.71k
  if (*repeat > 0) {
621
318
    *repeat -= 2;
622
318
    *repeat <<= extra_bits;
623
318
  }
624
3.71k
  *repeat += repeat_delta + 3U;
625
3.71k
  repeat_delta = *repeat - old_repeat;
626
3.71k
  if (*symbol + repeat_delta > alphabet_size) {
627
31
    BROTLI_DUMP();
628
31
    *symbol = alphabet_size;
629
31
    *space = 0xFFFFF;
630
31
    return;
631
31
  }
632
3.68k
  BROTLI_LOG(("[ReadHuffmanCode] code_length[%d..%d] = %d\n",
633
3.68k
      (int)*symbol, (int)(*symbol + repeat_delta - 1), (int)*repeat_code_len));
634
3.68k
  if (*repeat_code_len != 0) {
635
2.90k
    brotli_reg_t last = *symbol + repeat_delta;
636
2.90k
    int next = next_symbol[*repeat_code_len];
637
14.7k
    do {
638
14.7k
      symbol_lists[next] = (uint16_t)*symbol;
639
14.7k
      next = (int)*symbol;
640
14.7k
    } while (++(*symbol) != last);
641
2.90k
    next_symbol[*repeat_code_len] = next;
642
2.90k
    *space -= repeat_delta << (15 - *repeat_code_len);
643
2.90k
    code_length_histo[*repeat_code_len] =
644
2.90k
        (uint16_t)(code_length_histo[*repeat_code_len] + repeat_delta);
645
2.90k
  } else {
646
778
    *symbol += repeat_delta;
647
778
  }
648
3.68k
}
649
650
/* Reads and decodes symbol codelengths. */
651
static BrotliDecoderErrorCode ReadSymbolCodeLengths(
652
687
    brotli_reg_t alphabet_size, BrotliDecoderState* s) {
653
687
  BrotliBitReader* br = &s->br;
654
687
  BrotliMetablockHeaderArena* h = &s->arena.header;
655
687
  brotli_reg_t symbol = h->symbol;
656
687
  brotli_reg_t repeat = h->repeat;
657
687
  brotli_reg_t space = h->space;
658
687
  brotli_reg_t prev_code_len = h->prev_code_len;
659
687
  brotli_reg_t repeat_code_len = h->repeat_code_len;
660
687
  uint16_t* symbol_lists = h->symbol_lists;
661
687
  uint16_t* code_length_histo = h->code_length_histo;
662
687
  int* next_symbol = h->next_symbol;
663
687
  if (!BrotliWarmupBitReader(br)) {
664
0
    return BROTLI_DECODER_NEEDS_MORE_INPUT;
665
0
  }
666
62.4k
  while (symbol < alphabet_size && space > 0) {
667
61.8k
    const HuffmanCode* p = h->table;
668
61.8k
    brotli_reg_t code_len;
669
61.8k
    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p);
670
61.8k
    if (!BrotliCheckInputAmount(br)) {
671
79
      h->symbol = symbol;
672
79
      h->repeat = repeat;
673
79
      h->prev_code_len = prev_code_len;
674
79
      h->repeat_code_len = repeat_code_len;
675
79
      h->space = space;
676
79
      return BROTLI_DECODER_NEEDS_MORE_INPUT;
677
79
    }
678
61.7k
    BrotliFillBitWindow16(br);
679
61.7k
    BROTLI_HC_ADJUST_TABLE_INDEX(p, BrotliGetBitsUnmasked(br) &
680
61.7k
        BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH));
681
61.7k
    BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p));  /* Use 1..5 bits. */
682
61.7k
    code_len = BROTLI_HC_FAST_LOAD_VALUE(p);  /* code_len == 0..17 */
683
61.7k
    if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
684
58.2k
      ProcessSingleCodeLength(code_len, &symbol, &repeat, &space,
685
58.2k
          &prev_code_len, symbol_lists, code_length_histo, next_symbol);
686
58.2k
    } else {  /* code_len == 16..17, extra_bits == 2..3 */
687
3.47k
      brotli_reg_t extra_bits =
688
3.47k
          (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) ? 2 : 3;
689
3.47k
      brotli_reg_t repeat_delta =
690
3.47k
          BrotliGetBitsUnmasked(br) & BitMask(extra_bits);
691
3.47k
      BrotliDropBits(br, extra_bits);
692
3.47k
      ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
693
3.47k
          &symbol, &repeat, &space, &prev_code_len, &repeat_code_len,
694
3.47k
          symbol_lists, code_length_histo, next_symbol);
695
3.47k
    }
696
61.7k
  }
697
608
  h->space = space;
698
608
  return BROTLI_DECODER_SUCCESS;
699
687
}
700
701
static BrotliDecoderErrorCode SafeReadSymbolCodeLengths(
702
79
    brotli_reg_t alphabet_size, BrotliDecoderState* s) {
703
79
  BrotliBitReader* br = &s->br;
704
79
  BrotliMetablockHeaderArena* h = &s->arena.header;
705
79
  BROTLI_BOOL get_byte = BROTLI_FALSE;
706
3.69k
  while (h->symbol < alphabet_size && h->space > 0) {
707
3.64k
    const HuffmanCode* p = h->table;
708
3.64k
    brotli_reg_t code_len;
709
3.64k
    brotli_reg_t available_bits;
710
3.64k
    brotli_reg_t bits = 0;
711
3.64k
    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p);
712
3.64k
    if (get_byte && !BrotliPullByte(br)) return BROTLI_DECODER_NEEDS_MORE_INPUT;
713
3.62k
    get_byte = BROTLI_FALSE;
714
3.62k
    available_bits = BrotliGetAvailableBits(br);
715
3.62k
    if (available_bits != 0) {
716
3.39k
      bits = (uint32_t)BrotliGetBitsUnmasked(br);
717
3.39k
    }
718
3.62k
    BROTLI_HC_ADJUST_TABLE_INDEX(p,
719
3.62k
        bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH));
720
3.62k
    if (BROTLI_HC_FAST_LOAD_BITS(p) > available_bits) {
721
473
      get_byte = BROTLI_TRUE;
722
473
      continue;
723
473
    }
724
3.14k
    code_len = BROTLI_HC_FAST_LOAD_VALUE(p);  /* code_len == 0..17 */
725
3.14k
    if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
726
2.81k
      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p));
727
2.81k
      ProcessSingleCodeLength(code_len, &h->symbol, &h->repeat, &h->space,
728
2.81k
          &h->prev_code_len, h->symbol_lists, h->code_length_histo,
729
2.81k
          h->next_symbol);
730
2.81k
    } else {  /* code_len == 16..17, extra_bits == 2..3 */
731
330
      brotli_reg_t extra_bits = code_len - 14U;
732
330
      brotli_reg_t repeat_delta = (bits >> BROTLI_HC_FAST_LOAD_BITS(p)) &
733
330
          BitMask(extra_bits);
734
330
      if (available_bits < BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits) {
735
83
        get_byte = BROTLI_TRUE;
736
83
        continue;
737
83
      }
738
247
      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits);
739
247
      ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
740
247
          &h->symbol, &h->repeat, &h->space, &h->prev_code_len,
741
247
          &h->repeat_code_len, h->symbol_lists, h->code_length_histo,
742
247
          h->next_symbol);
743
247
    }
744
3.14k
  }
745
59
  return BROTLI_DECODER_SUCCESS;
746
79
}
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
794
static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) {
751
794
  BrotliBitReader* br = &s->br;
752
794
  BrotliMetablockHeaderArena* h = &s->arena.header;
753
794
  brotli_reg_t num_codes = h->repeat;
754
794
  brotli_reg_t space = h->space;
755
794
  brotli_reg_t i = h->sub_loop_counter;
756
9.70k
  for (; i < BROTLI_CODE_LENGTH_CODES; ++i) {
757
9.50k
    const uint8_t code_len_idx = kCodeLengthCodeOrder[i];
758
9.50k
    brotli_reg_t ix;
759
9.50k
    brotli_reg_t v;
760
9.50k
    if (BROTLI_PREDICT_FALSE(!BrotliSafeGetBits(br, 4, &ix))) {
761
17
      brotli_reg_t available_bits = BrotliGetAvailableBits(br);
762
17
      if (available_bits != 0) {
763
13
        ix = BrotliGetBitsUnmasked(br) & 0xF;
764
13
      } else {
765
4
        ix = 0;
766
4
      }
767
17
      if (kCodeLengthPrefixLength[ix] > available_bits) {
768
9
        h->sub_loop_counter = i;
769
9
        h->repeat = num_codes;
770
9
        h->space = space;
771
9
        h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
772
9
        return BROTLI_DECODER_NEEDS_MORE_INPUT;
773
9
      }
774
17
    }
775
9.49k
    v = kCodeLengthPrefixValue[ix];
776
9.49k
    BrotliDropBits(br, kCodeLengthPrefixLength[ix]);
777
9.49k
    h->code_length_code_lengths[code_len_idx] = (uint8_t)v;
778
9.49k
    BROTLI_LOG_ARRAY_INDEX(h->code_length_code_lengths, code_len_idx);
779
9.49k
    if (v != 0) {
780
4.05k
      space = space - (32U >> v);
781
4.05k
      ++num_codes;
782
4.05k
      ++h->code_length_histo[v];
783
4.05k
      if (space - 1U >= 32U) {
784
        /* space is 0 or wrapped around. */
785
587
        break;
786
587
      }
787
4.05k
    }
788
9.49k
  }
789
785
  if (!(num_codes == 1 || space == 0)) {
790
98
    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CL_SPACE);
791
98
  }
792
687
  return BROTLI_DECODER_SUCCESS;
793
785
}
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
1.53k
                                              BrotliDecoderState* s) {
811
1.53k
  BrotliBitReader* br = &s->br;
812
1.53k
  BrotliMetablockHeaderArena* h = &s->arena.header;
813
  /* State machine. */
814
2.32k
  for (;;) {
815
2.32k
    switch (h->substate_huffman) {
816
1.53k
      case BROTLI_STATE_HUFFMAN_NONE:
817
1.53k
        if (!BrotliSafeReadBits(br, 2, &h->sub_loop_counter)) {
818
4
          return BROTLI_DECODER_NEEDS_MORE_INPUT;
819
4
        }
820
1.52k
        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
1.52k
        if (h->sub_loop_counter != 1) {
825
794
          h->space = 32;
826
794
          h->repeat = 0;  /* num_codes */
827
794
          memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo[0]) *
828
794
              (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1));
829
794
          memset(&h->code_length_code_lengths[0], 0,
830
794
              sizeof(h->code_length_code_lengths));
831
794
          h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
832
794
          continue;
833
794
        }
834
      /* Fall through. */
835
836
735
      case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE:
837
        /* Read symbols, codes & code lengths directly. */
838
735
        if (!BrotliSafeReadBits(br, 2, &h->symbol)) {  /* num_symbols */
839
0
          h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
840
0
          return BROTLI_DECODER_NEEDS_MORE_INPUT;
841
0
        }
842
735
        h->sub_loop_counter = 0;
843
      /* Fall through. */
844
845
735
      case BROTLI_STATE_HUFFMAN_SIMPLE_READ: {
846
735
        BrotliDecoderErrorCode result =
847
735
            ReadSimpleHuffmanSymbols(alphabet_size_max, alphabet_size_limit, s);
848
735
        if (result != BROTLI_DECODER_SUCCESS) {
849
15
          return result;
850
15
        }
851
735
      }
852
      /* Fall through. */
853
854
720
      case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: {
855
720
        brotli_reg_t table_size;
856
720
        if (h->symbol == 3) {
857
130
          brotli_reg_t bits;
858
130
          if (!BrotliSafeReadBits(br, 1, &bits)) {
859
0
            h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
860
0
            return BROTLI_DECODER_NEEDS_MORE_INPUT;
861
0
          }
862
130
          h->symbol += bits;
863
130
        }
864
720
        BROTLI_LOG_UINT(h->symbol);
865
720
        table_size = BrotliBuildSimpleHuffmanTable(table, HUFFMAN_TABLE_BITS,
866
720
                                                   h->symbols_lists_array,
867
720
                                                   (uint32_t)h->symbol);
868
720
        if (opt_table_size) {
869
460
          *opt_table_size = table_size;
870
460
        }
871
720
        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
872
720
        return BROTLI_DECODER_SUCCESS;
873
720
      }
874
875
      /* Decode Huffman-coded code lengths. */
876
794
      case BROTLI_STATE_HUFFMAN_COMPLEX: {
877
794
        brotli_reg_t i;
878
794
        BrotliDecoderErrorCode result = ReadCodeLengthCodeLengths(s);
879
794
        if (result != BROTLI_DECODER_SUCCESS) {
880
107
          return result;
881
107
        }
882
687
        BrotliBuildCodeLengthsHuffmanTable(h->table,
883
687
                                           h->code_length_code_lengths,
884
687
                                           h->code_length_histo);
885
687
        memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo));
886
11.6k
        for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH; ++i) {
887
10.9k
          h->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1);
888
10.9k
          h->symbol_lists[h->next_symbol[i]] = 0xFFFF;
889
10.9k
        }
890
891
687
        h->symbol = 0;
892
687
        h->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH;
893
687
        h->repeat = 0;
894
687
        h->repeat_code_len = 0;
895
687
        h->space = 32768;
896
687
        h->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
897
687
      }
898
      /* Fall through. */
899
900
687
      case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: {
901
687
        brotli_reg_t table_size;
902
687
        BrotliDecoderErrorCode result = ReadSymbolCodeLengths(
903
687
            alphabet_size_limit, s);
904
687
        if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
905
79
          result = SafeReadSymbolCodeLengths(alphabet_size_limit, s);
906
79
        }
907
687
        if (result != BROTLI_DECODER_SUCCESS) {
908
20
          return result;
909
20
        }
910
911
667
        if (h->space != 0) {
912
102
          BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", (int)h->space));
913
102
          return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE);
914
102
        }
915
565
        table_size = BrotliBuildHuffmanTable(
916
565
            table, HUFFMAN_TABLE_BITS, h->symbol_lists, h->code_length_histo);
917
565
        if (opt_table_size) {
918
525
          *opt_table_size = table_size;
919
525
        }
920
565
        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
921
565
        return BROTLI_DECODER_SUCCESS;
922
667
      }
923
924
0
      default:
925
0
        return
926
0
            BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);  /* COV_NF_LINE */
927
2.32k
    }
928
2.32k
  }
929
1.53k
}
930
931
/* Decodes a block length by reading 3..39 bits. */
932
static BROTLI_INLINE brotli_reg_t ReadBlockLength(const HuffmanCode* table,
933
14.3k
                                                  BrotliBitReader* br) {
934
14.3k
  brotli_reg_t code;
935
14.3k
  brotli_reg_t nbits;
936
14.3k
  code = ReadSymbol(table, br);
937
14.3k
  nbits = _kBrotliPrefixCodeRanges[code].nbits;  /* nbits == 2..24 */
938
14.3k
  return _kBrotliPrefixCodeRanges[code].offset + BrotliReadBits24(br, nbits);
939
14.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
611
    BrotliBitReader* br) {
946
611
  brotli_reg_t index;
947
611
  if (s->substate_read_block_length == BROTLI_STATE_READ_BLOCK_LENGTH_NONE) {
948
611
    if (!SafeReadSymbol(table, br, &index)) {
949
0
      return BROTLI_FALSE;
950
0
    }
951
611
  } else {
952
0
    index = s->block_length_index;
953
0
  }
954
611
  {
955
611
    brotli_reg_t bits;
956
611
    brotli_reg_t nbits = _kBrotliPrefixCodeRanges[index].nbits;
957
611
    brotli_reg_t offset = _kBrotliPrefixCodeRanges[index].offset;
958
611
    if (!BrotliSafeReadBits(br, nbits, &bits)) {
959
5
      s->block_length_index = index;
960
5
      s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX;
961
5
      return BROTLI_FALSE;
962
5
    }
963
606
    *result = offset + bits;
964
606
    s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
965
606
    return BROTLI_TRUE;
966
611
  }
967
611
}
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
21
    uint8_t* v, brotli_reg_t v_len, BrotliDecoderState* state) {
985
  /* Reinitialize elements that could have been changed. */
986
21
  brotli_reg_t i = 1;
987
21
  brotli_reg_t upper_bound = state->mtf_upper_bound;
988
21
  uint32_t* mtf = &state->mtf[1];  /* Make mtf[-1] addressable. */
989
21
  uint8_t* mtf_u8 = (uint8_t*)mtf;
990
  /* Load endian-aware constant. */
991
21
  const uint8_t b0123[4] = {0, 1, 2, 3};
992
21
  uint32_t pattern;
993
21
  memcpy(&pattern, &b0123, 4);
994
995
  /* Initialize list using 4 consequent values pattern. */
996
21
  mtf[0] = pattern;
997
1.26k
  do {
998
1.26k
    pattern += 0x04040404;  /* Advance all 4 values by 4. */
999
1.26k
    mtf[i] = pattern;
1000
1.26k
    i++;
1001
1.26k
  } while (i <= upper_bound);
1002
1003
  /* Transform the input. */
1004
21
  upper_bound = 0;
1005
25.5k
  for (i = 0; i < v_len; ++i) {
1006
25.5k
    int index = v[i];
1007
25.5k
    uint8_t value = mtf_u8[index];
1008
25.5k
    upper_bound |= v[i];
1009
25.5k
    v[i] = value;
1010
25.5k
    mtf_u8[-1] = value;
1011
46.9k
    do {
1012
46.9k
      index--;
1013
46.9k
      mtf_u8[index + 1] = mtf_u8[index];
1014
46.9k
    } while (index >= 0);
1015
25.5k
  }
1016
  /* Remember amount of elements to be reinitialized. */
1017
21
  state->mtf_upper_bound = upper_bound >> 2;
1018
21
}
1019
1020
/* Decodes a series of Huffman table using ReadHuffmanCode function. */
1021
static BrotliDecoderErrorCode HuffmanTreeGroupDecode(
1022
1.11k
    HuffmanTreeGroup* group, BrotliDecoderState* s) {
1023
1.11k
  BrotliMetablockHeaderArena* h = &s->arena.header;
1024
1.11k
  if (h->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) {
1025
1.11k
    h->next = group->codes;
1026
1.11k
    h->htree_index = 0;
1027
1.11k
    h->substate_tree_group = BROTLI_STATE_TREE_GROUP_LOOP;
1028
1.11k
  }
1029
2.09k
  while (h->htree_index < group->num_htrees) {
1030
1.11k
    brotli_reg_t table_size;
1031
1.11k
    BrotliDecoderErrorCode result = ReadHuffmanCode(group->alphabet_size_max,
1032
1.11k
        group->alphabet_size_limit, h->next, &table_size, s);
1033
1.11k
    if (result != BROTLI_DECODER_SUCCESS) return result;
1034
985
    group->htrees[h->htree_index] = h->next;
1035
985
    h->next += table_size;
1036
985
    ++h->htree_index;
1037
985
  }
1038
980
  h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
1039
980
  return BROTLI_DECODER_SUCCESS;
1040
1.11k
}
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
951
                                               BrotliDecoderState* s) {
1054
951
  BrotliBitReader* br = &s->br;
1055
951
  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
1056
951
  BrotliMetablockHeaderArena* h = &s->arena.header;
1057
1058
951
  switch ((int)h->substate_context_map) {
1059
951
    case BROTLI_STATE_CONTEXT_MAP_NONE:
1060
951
      result = DecodeVarLenUint8(s, br, num_htrees);
1061
951
      if (result != BROTLI_DECODER_SUCCESS) {
1062
0
        return result;
1063
0
      }
1064
951
      (*num_htrees)++;
1065
951
      h->context_index = 0;
1066
951
      BROTLI_LOG_UINT(context_map_size);
1067
951
      BROTLI_LOG_UINT(*num_htrees);
1068
951
      *context_map_arg =
1069
951
          (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)context_map_size);
1070
951
      if (*context_map_arg == 0) {
1071
0
        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP);
1072
0
      }
1073
951
      if (*num_htrees <= 1) {
1074
841
        memset(*context_map_arg, 0, (size_t)context_map_size);
1075
841
        return BROTLI_DECODER_SUCCESS;
1076
841
      }
1077
110
      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
1078
    /* Fall through. */
1079
1080
110
    case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: {
1081
110
      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
110
      if (!BrotliSafeGetBits(br, 5, &bits)) {
1085
1
        return BROTLI_DECODER_NEEDS_MORE_INPUT;
1086
1
      }
1087
109
      if ((bits & 1) != 0) { /* Use RLE for zeros. */
1088
51
        h->max_run_length_prefix = (bits >> 1) + 1;
1089
51
        BrotliDropBits(br, 5);
1090
58
      } else {
1091
58
        h->max_run_length_prefix = 0;
1092
58
        BrotliDropBits(br, 1);
1093
58
      }
1094
109
      BROTLI_LOG_UINT(h->max_run_length_prefix);
1095
109
      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN;
1096
109
    }
1097
    /* Fall through. */
1098
1099
109
    case BROTLI_STATE_CONTEXT_MAP_HUFFMAN: {
1100
109
      brotli_reg_t alphabet_size = *num_htrees + h->max_run_length_prefix;
1101
109
      result = ReadHuffmanCode(alphabet_size, alphabet_size,
1102
109
                               h->context_map_table, NULL, s);
1103
109
      if (result != BROTLI_DECODER_SUCCESS) return result;
1104
66
      h->code = 0xFFFF;
1105
66
      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE;
1106
66
    }
1107
    /* Fall through. */
1108
1109
66
    case BROTLI_STATE_CONTEXT_MAP_DECODE: {
1110
66
      brotli_reg_t context_index = h->context_index;
1111
66
      brotli_reg_t max_run_length_prefix = h->max_run_length_prefix;
1112
66
      uint8_t* context_map = *context_map_arg;
1113
66
      brotli_reg_t code = h->code;
1114
66
      BROTLI_BOOL skip_preamble = (code != 0xFFFF);
1115
64.1k
      while (context_index < context_map_size || skip_preamble) {
1116
64.1k
        if (!skip_preamble) {
1117
64.1k
          if (!SafeReadSymbol(h->context_map_table, br, &code)) {
1118
3
            h->code = 0xFFFF;
1119
3
            h->context_index = context_index;
1120
3
            return BROTLI_DECODER_NEEDS_MORE_INPUT;
1121
3
          }
1122
64.1k
          BROTLI_LOG_UINT(code);
1123
1124
64.1k
          if (code == 0) {
1125
37.1k
            context_map[context_index++] = 0;
1126
37.1k
            continue;
1127
37.1k
          }
1128
26.9k
          if (code > max_run_length_prefix) {
1129
26.6k
            context_map[context_index++] =
1130
26.6k
                (uint8_t)(code - max_run_length_prefix);
1131
26.6k
            continue;
1132
26.6k
          }
1133
26.9k
        } else {
1134
0
          skip_preamble = BROTLI_FALSE;
1135
0
        }
1136
        /* RLE sub-stage. */
1137
324
        {
1138
324
          brotli_reg_t reps;
1139
324
          if (!BrotliSafeReadBits(br, code, &reps)) {
1140
1
            h->code = code;
1141
1
            h->context_index = context_index;
1142
1
            return BROTLI_DECODER_NEEDS_MORE_INPUT;
1143
1
          }
1144
323
          reps += (brotli_reg_t)1U << code;
1145
323
          BROTLI_LOG_UINT(reps);
1146
323
          if (context_index + reps > context_map_size) {
1147
11
            return
1148
11
                BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT);
1149
11
          }
1150
11.8k
          do {
1151
11.8k
            context_map[context_index++] = 0;
1152
11.8k
          } while (--reps);
1153
312
        }
1154
312
      }
1155
66
    }
1156
    /* Fall through. */
1157
1158
51
    case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: {
1159
51
      brotli_reg_t bits;
1160
51
      if (!BrotliSafeReadBits(br, 1, &bits)) {
1161
0
        h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
1162
0
        return BROTLI_DECODER_NEEDS_MORE_INPUT;
1163
0
      }
1164
51
      if (bits != 0) {
1165
21
        InverseMoveToFrontTransform(*context_map_arg, context_map_size, s);
1166
21
      }
1167
51
      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
1168
51
      return BROTLI_DECODER_SUCCESS;
1169
51
    }
1170
1171
0
    default:
1172
0
      return
1173
0
          BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);  /* COV_NF_LINE */
1174
951
  }
1175
951
}
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
14.9k
    int safe, BrotliDecoderState* s, int tree_type) {
1181
14.9k
  brotli_reg_t max_block_type = s->num_block_types[tree_type];
1182
14.9k
  const HuffmanCode* type_tree = &s->block_type_trees[
1183
14.9k
      tree_type * BROTLI_HUFFMAN_MAX_SIZE_258];
1184
14.9k
  const HuffmanCode* len_tree = &s->block_len_trees[
1185
14.9k
      tree_type * BROTLI_HUFFMAN_MAX_SIZE_26];
1186
14.9k
  BrotliBitReader* br = &s->br;
1187
14.9k
  brotli_reg_t* ringbuffer = &s->block_type_rb[tree_type * 2];
1188
14.9k
  brotli_reg_t block_type;
1189
14.9k
  if (max_block_type <= 1) {
1190
0
    return BROTLI_FALSE;
1191
0
  }
1192
1193
  /* Read 0..15 + 3..39 bits. */
1194
14.9k
  if (!safe) {
1195
14.3k
    block_type = ReadSymbol(type_tree, br);
1196
14.3k
    s->block_length[tree_type] = ReadBlockLength(len_tree, br);
1197
14.3k
  } else {
1198
509
    BrotliBitReaderState memento;
1199
509
    BrotliBitReaderSaveState(br, &memento);
1200
509
    if (!SafeReadSymbol(type_tree, br, &block_type)) return BROTLI_FALSE;
1201
505
    if (!SafeReadBlockLength(s, &s->block_length[tree_type], len_tree, br)) {
1202
5
      s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
1203
5
      BrotliBitReaderRestoreState(br, &memento);
1204
5
      return BROTLI_FALSE;
1205
5
    }
1206
505
  }
1207
1208
14.8k
  if (block_type == 1) {
1209
0
    block_type = ringbuffer[1] + 1;
1210
14.8k
  } else if (block_type == 0) {
1211
0
    block_type = ringbuffer[0];
1212
14.8k
  } else {
1213
14.8k
    block_type -= 2;
1214
14.8k
  }
1215
14.8k
  if (block_type >= max_block_type) {
1216
0
    block_type -= max_block_type;
1217
0
  }
1218
14.8k
  ringbuffer[0] = ringbuffer[1];
1219
14.8k
  ringbuffer[1] = block_type;
1220
14.8k
  return BROTLI_TRUE;
1221
14.9k
}
1222
1223
static BROTLI_INLINE void DetectTrivialLiteralBlockTypes(
1224
460
    BrotliDecoderState* s) {
1225
460
  size_t i;
1226
4.14k
  for (i = 0; i < 8; ++i) s->trivial_literal_contexts[i] = 0;
1227
5.35k
  for (i = 0; i < s->num_block_types[0]; i++) {
1228
4.89k
    size_t offset = i << BROTLI_LITERAL_CONTEXT_BITS;
1229
4.89k
    size_t error = 0;
1230
4.89k
    size_t sample = s->context_map[offset];
1231
4.89k
    size_t j;
1232
83.2k
    for (j = 0; j < (1u << BROTLI_LITERAL_CONTEXT_BITS);) {
1233
      /* NOLINTNEXTLINE(bugprone-macro-repeated-side-effects) */
1234
78.3k
      BROTLI_REPEAT_4({ error |= s->context_map[offset + j++] ^ sample; })
1235
78.3k
    }
1236
4.89k
    if (error == 0) {
1237
3.99k
      s->trivial_literal_contexts[i >> 5] |= 1u << (i & 31);
1238
3.99k
    }
1239
4.89k
  }
1240
460
}
1241
1242
15.1k
static BROTLI_INLINE void PrepareLiteralDecoding(BrotliDecoderState* s) {
1243
15.1k
  uint8_t context_mode;
1244
15.1k
  size_t trivial;
1245
15.1k
  brotli_reg_t block_type = s->block_type_rb[1];
1246
15.1k
  brotli_reg_t context_offset = block_type << BROTLI_LITERAL_CONTEXT_BITS;
1247
15.1k
  s->context_map_slice = s->context_map + context_offset;
1248
15.1k
  trivial = s->trivial_literal_contexts[block_type >> 5];
1249
15.1k
  s->trivial_literal_context = (trivial >> (block_type & 31)) & 1;
1250
15.1k
  s->literal_htree = s->literal_hgroup.htrees[s->context_map_slice[0]];
1251
15.1k
  context_mode = s->context_modes[block_type] & 3;
1252
15.1k
  s->context_lookup = BROTLI_CONTEXT_LUT(context_mode);
1253
15.1k
}
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
14.9k
    int safe, BrotliDecoderState* s) {
1259
14.9k
  if (!DecodeBlockTypeAndLength(safe, s, 0)) {
1260
9
    return BROTLI_FALSE;
1261
9
  }
1262
14.8k
  PrepareLiteralDecoding(s);
1263
14.8k
  return BROTLI_TRUE;
1264
14.9k
}
1265
1266
14.3k
static void BROTLI_NOINLINE DecodeLiteralBlockSwitch(BrotliDecoderState* s) {
1267
14.3k
  DecodeLiteralBlockSwitchInternal(0, s);
1268
14.3k
}
1269
1270
static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeLiteralBlockSwitch(
1271
509
    BrotliDecoderState* s) {
1272
509
  return DecodeLiteralBlockSwitchInternal(1, s);
1273
509
}
1274
1275
/* Block switch for insert/copy length.
1276
   Reads 3..54 bits. */
1277
static BROTLI_INLINE BROTLI_BOOL DecodeCommandBlockSwitchInternal(
1278
0
    int safe, BrotliDecoderState* s) {
1279
0
  if (!DecodeBlockTypeAndLength(safe, s, 1)) {
1280
0
    return BROTLI_FALSE;
1281
0
  }
1282
0
  s->htree_command = s->insert_copy_hgroup.htrees[s->block_type_rb[3]];
1283
0
  return BROTLI_TRUE;
1284
0
}
1285
1286
0
static void BROTLI_NOINLINE DecodeCommandBlockSwitch(BrotliDecoderState* s) {
1287
0
  DecodeCommandBlockSwitchInternal(0, s);
1288
0
}
1289
1290
static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeCommandBlockSwitch(
1291
0
    BrotliDecoderState* s) {
1292
0
  return DecodeCommandBlockSwitchInternal(1, s);
1293
0
}
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
199
static size_t UnwrittenBytes(const BrotliDecoderState* s, BROTLI_BOOL wrap) {
1318
199
  size_t pos = wrap && s->pos > s->ringbuffer_size ?
1319
199
      (size_t)s->ringbuffer_size : (size_t)(s->pos);
1320
199
  size_t partial_pos_rb = (s->rb_roundtrips * (size_t)s->ringbuffer_size) + pos;
1321
199
  return partial_pos_rb - s->partial_pos_out;
1322
199
}
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
199
    size_t* total_out, BROTLI_BOOL force) {
1330
199
  uint8_t* start =
1331
199
      s->ringbuffer + (s->partial_pos_out & (size_t)s->ringbuffer_mask);
1332
199
  size_t to_write = UnwrittenBytes(s, BROTLI_TRUE);
1333
199
  size_t num_written = *available_out;
1334
199
  if (num_written > to_write) {
1335
199
    num_written = to_write;
1336
199
  }
1337
199
  if (s->meta_block_remaining_len < 0) {
1338
23
    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1);
1339
23
  }
1340
176
  if (next_out && !*next_out) {
1341
0
    *next_out = start;
1342
176
  } else {
1343
176
    if (next_out) {
1344
176
      memcpy(*next_out, start, num_written);
1345
176
      *next_out += num_written;
1346
176
    }
1347
176
  }
1348
176
  *available_out -= num_written;
1349
176
  BROTLI_LOG_UINT(to_write);
1350
176
  BROTLI_LOG_UINT(num_written);
1351
176
  s->partial_pos_out += num_written;
1352
176
  if (total_out) {
1353
0
    *total_out = s->partial_pos_out;
1354
0
  }
1355
176
  if (num_written < to_write) {
1356
0
    if (s->ringbuffer_size == (1 << s->window_bits) || force) {
1357
0
      return BROTLI_DECODER_NEEDS_MORE_OUTPUT;
1358
0
    } else {
1359
0
      return BROTLI_DECODER_SUCCESS;
1360
0
    }
1361
0
  }
1362
  /* Wrap ring buffer only if it has reached its maximal size. */
1363
176
  if (s->ringbuffer_size == (1 << s->window_bits) &&
1364
16
      s->pos >= s->ringbuffer_size) {
1365
6
    s->pos -= s->ringbuffer_size;
1366
6
    s->rb_roundtrips++;
1367
6
    s->should_wrap_ringbuffer = (size_t)s->pos != 0 ? 1 : 0;
1368
6
  }
1369
176
  return BROTLI_DECODER_SUCCESS;
1370
176
}
1371
1372
0
static void BROTLI_NOINLINE WrapRingBuffer(BrotliDecoderState* s) {
1373
0
  if (s->should_wrap_ringbuffer) {
1374
0
    memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos);
1375
0
    s->should_wrap_ringbuffer = 0;
1376
0
  }
1377
0
}
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
323
    BrotliDecoderState* s) {
1388
323
  uint8_t* old_ringbuffer = s->ringbuffer;
1389
323
  if (s->ringbuffer_size == s->new_ringbuffer_size) {
1390
2
    return BROTLI_TRUE;
1391
2
  }
1392
1393
321
  s->ringbuffer = (uint8_t*)BROTLI_DECODER_ALLOC(s,
1394
321
      (size_t)(s->new_ringbuffer_size) + kRingBufferWriteAheadSlack);
1395
321
  if (s->ringbuffer == 0) {
1396
    /* Restore previous value. */
1397
0
    s->ringbuffer = old_ringbuffer;
1398
0
    return BROTLI_FALSE;
1399
0
  }
1400
321
  s->ringbuffer[s->new_ringbuffer_size - 2] = 0;
1401
321
  s->ringbuffer[s->new_ringbuffer_size - 1] = 0;
1402
1403
321
  if (!!old_ringbuffer) {
1404
5
    memcpy(s->ringbuffer, old_ringbuffer, (size_t)s->pos);
1405
5
    BROTLI_DECODER_FREE(s, old_ringbuffer);
1406
5
  }
1407
1408
321
  s->ringbuffer_size = s->new_ringbuffer_size;
1409
321
  s->ringbuffer_mask = s->new_ringbuffer_size - 1;
1410
321
  s->ringbuffer_end = s->ringbuffer + s->ringbuffer_size;
1411
1412
321
  return BROTLI_TRUE;
1413
321
}
1414
1415
static BrotliDecoderErrorCode BROTLI_NOINLINE
1416
55
SkipMetadataBlock(BrotliDecoderState* s) {
1417
55
  BrotliBitReader* br = &s->br;
1418
55
  int nbytes;
1419
1420
55
  if (s->meta_block_remaining_len == 0) {
1421
24
    return BROTLI_DECODER_SUCCESS;
1422
24
  }
1423
1424
31
  BROTLI_DCHECK((BrotliGetAvailableBits(br) & 7) == 0);
1425
1426
  /* Drain accumulator. */
1427
31
  if (BrotliGetAvailableBits(br) >= 8) {
1428
6
    uint8_t buffer[8];
1429
6
    nbytes = (int)(BrotliGetAvailableBits(br)) >> 3;
1430
6
    BROTLI_DCHECK(nbytes <= 8);
1431
6
    if (nbytes > s->meta_block_remaining_len) {
1432
0
      nbytes = s->meta_block_remaining_len;
1433
0
    }
1434
6
    BrotliCopyBytes(buffer, br, (size_t)nbytes);
1435
6
    if (s->metadata_chunk_func) {
1436
0
      s->metadata_chunk_func(s->metadata_callback_opaque, buffer,
1437
0
                             (size_t)nbytes);
1438
0
    }
1439
6
    s->meta_block_remaining_len -= nbytes;
1440
6
    if (s->meta_block_remaining_len == 0) {
1441
0
      return BROTLI_DECODER_SUCCESS;
1442
0
    }
1443
6
  }
1444
1445
  /* Direct access to metadata is possible. */
1446
31
  nbytes = (int)BrotliGetRemainingBytes(br);
1447
31
  if (nbytes > s->meta_block_remaining_len) {
1448
15
    nbytes = s->meta_block_remaining_len;
1449
15
  }
1450
31
  if (nbytes > 0) {
1451
30
    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
30
    BrotliDropBytes(br, (size_t)nbytes);
1456
30
    s->meta_block_remaining_len -= nbytes;
1457
30
    if (s->meta_block_remaining_len == 0) {
1458
16
      return BROTLI_DECODER_SUCCESS;
1459
16
    }
1460
30
  }
1461
1462
15
  BROTLI_DCHECK(BrotliGetRemainingBytes(br) == 0);
1463
1464
15
  return BROTLI_DECODER_NEEDS_MORE_INPUT;
1465
31
}
1466
1467
static BrotliDecoderErrorCode BROTLI_NOINLINE CopyUncompressedBlockToOutput(
1468
    size_t* available_out, uint8_t** next_out, size_t* total_out,
1469
24
    BrotliDecoderState* s) {
1470
  /* TODO(eustas): avoid allocation for single uncompressed block. */
1471
24
  if (!BrotliEnsureRingBuffer(s)) {
1472
0
    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1);
1473
0
  }
1474
1475
  /* State machine */
1476
30
  for (;;) {
1477
30
    switch (s->substate_uncompressed) {
1478
30
      case BROTLI_STATE_UNCOMPRESSED_NONE: {
1479
30
        int nbytes = (int)BrotliGetRemainingBytes(&s->br);
1480
30
        if (nbytes > s->meta_block_remaining_len) {
1481
10
          nbytes = s->meta_block_remaining_len;
1482
10
        }
1483
30
        if (s->pos + nbytes > s->ringbuffer_size) {
1484
6
          nbytes = s->ringbuffer_size - s->pos;
1485
6
        }
1486
        /* Copy remaining bytes from s->br.buf_ to ring-buffer. */
1487
30
        BrotliCopyBytes(&s->ringbuffer[s->pos], &s->br, (size_t)nbytes);
1488
30
        s->pos += nbytes;
1489
30
        s->meta_block_remaining_len -= nbytes;
1490
30
        if (s->pos < 1 << s->window_bits) {
1491
24
          if (s->meta_block_remaining_len == 0) {
1492
10
            return BROTLI_DECODER_SUCCESS;
1493
10
          }
1494
14
          return BROTLI_DECODER_NEEDS_MORE_INPUT;
1495
24
        }
1496
6
        s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_WRITE;
1497
6
      }
1498
      /* Fall through. */
1499
1500
6
      case BROTLI_STATE_UNCOMPRESSED_WRITE: {
1501
6
        BrotliDecoderErrorCode result;
1502
6
        result = WriteRingBuffer(
1503
6
            s, available_out, next_out, total_out, BROTLI_FALSE);
1504
6
        if (result != BROTLI_DECODER_SUCCESS) {
1505
0
          return result;
1506
0
        }
1507
6
        if (s->ringbuffer_size == 1 << s->window_bits) {
1508
6
          s->max_distance = s->max_backward_distance;
1509
6
        }
1510
6
        s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE;
1511
6
        break;
1512
6
      }
1513
30
    }
1514
30
  }
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
483
static int GetCompoundDictionarySize(BrotliDecoderState* s) {
1579
483
  return s->compound_dictionary ? s->compound_dictionary->total_size : 0;
1580
483
}
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
590
    BrotliDecoderState* s) {
1635
590
  int window_size = 1 << s->window_bits;
1636
590
  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
590
  int min_size = s->ringbuffer_size ? s->ringbuffer_size : 1024;
1640
590
  int output_size;
1641
1642
  /* If maximum is already reached, no further extension is retired. */
1643
590
  if (s->ringbuffer_size == window_size) {
1644
0
    return;
1645
0
  }
1646
1647
  /* Metadata blocks does not touch ring buffer. */
1648
590
  if (s->is_metadata) {
1649
0
    return;
1650
0
  }
1651
1652
590
  if (!s->ringbuffer) {
1653
559
    output_size = 0;
1654
559
  } else {
1655
31
    output_size = s->pos;
1656
31
  }
1657
590
  output_size += s->meta_block_remaining_len;
1658
590
  min_size = min_size < output_size ? output_size : min_size;
1659
1660
590
  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
2.56k
    while ((new_ringbuffer_size >> 1) >= min_size) {
1665
1.97k
      new_ringbuffer_size >>= 1;
1666
1.97k
    }
1667
590
  }
1668
1669
590
  s->new_ringbuffer_size = new_ringbuffer_size;
1670
590
}
1671
1672
/* Reads 1..256 2-bit context modes. */
1673
494
static BrotliDecoderErrorCode ReadContextModes(BrotliDecoderState* s) {
1674
494
  BrotliBitReader* br = &s->br;
1675
494
  int i = s->loop_counter;
1676
1677
5.72k
  while (i < (int)s->num_block_types[0]) {
1678
5.23k
    brotli_reg_t bits;
1679
5.23k
    if (!BrotliSafeReadBits(br, 2, &bits)) {
1680
3
      s->loop_counter = i;
1681
3
      return BROTLI_DECODER_NEEDS_MORE_INPUT;
1682
3
    }
1683
5.23k
    s->context_modes[i] = (uint8_t)bits;
1684
5.23k
    BROTLI_LOG_ARRAY_INDEX(s->context_modes, i);
1685
5.23k
    i++;
1686
5.23k
  }
1687
491
  return BROTLI_DECODER_SUCCESS;
1688
494
}
1689
1690
1.47k
static BROTLI_INLINE void TakeDistanceFromRingBuffer(BrotliDecoderState* s) {
1691
1.47k
  int offset = s->distance_code - 3;
1692
1.47k
  if (s->distance_code <= 3) {
1693
    /* Compensate double distance-ring-buffer roll for dictionary items. */
1694
418
    s->distance_context = 1 >> s->distance_code;
1695
418
    s->distance_code = s->dist_rb[(s->dist_rb_idx - offset) & 3];
1696
418
    s->dist_rb_idx -= s->distance_context;
1697
1.05k
  } else {
1698
1.05k
    int index_delta = 3;
1699
1.05k
    int delta;
1700
1.05k
    int base = s->distance_code - 10;
1701
1.05k
    if (s->distance_code < 10) {
1702
917
      base = s->distance_code - 4;
1703
917
    } else {
1704
142
      index_delta = 2;
1705
142
    }
1706
    /* Unpack one of six 4-bit values. */
1707
1.05k
    delta = ((0x605142 >> (4 * base)) & 0xF) - 3;
1708
1.05k
    s->distance_code = s->dist_rb[(s->dist_rb_idx + index_delta) & 0x3] + delta;
1709
1.05k
    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
4
      s->distance_code = 0x7FFFFFFF;
1713
4
    }
1714
1.05k
  }
1715
1.47k
}
1716
1717
static BROTLI_INLINE BROTLI_BOOL SafeReadBits(
1718
1.76k
    BrotliBitReader* const br, brotli_reg_t n_bits, brotli_reg_t* val) {
1719
1.76k
  if (n_bits != 0) {
1720
559
    return BrotliSafeReadBits(br, n_bits, val);
1721
1.20k
  } else {
1722
1.20k
    *val = 0;
1723
1.20k
    return BROTLI_TRUE;
1724
1.20k
  }
1725
1.76k
}
1726
1727
static BROTLI_INLINE BROTLI_BOOL SafeReadBits32(
1728
146
    BrotliBitReader* const br, brotli_reg_t n_bits, brotli_reg_t* val) {
1729
146
  if (n_bits != 0) {
1730
146
    return BrotliSafeReadBits32(br, n_bits, val);
1731
146
  } else {
1732
0
    *val = 0;
1733
0
    return BROTLI_TRUE;
1734
0
  }
1735
146
}
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
299
static void CalculateDistanceLut(BrotliDecoderState* s) {
1805
299
  BrotliMetablockBodyArena* b = &s->arena.body;
1806
299
  brotli_reg_t npostfix = s->distance_postfix_bits;
1807
299
  brotli_reg_t ndirect = s->num_direct_distance_codes;
1808
299
  brotli_reg_t alphabet_size_limit = s->distance_hgroup.alphabet_size_limit;
1809
299
  brotli_reg_t postfix = (brotli_reg_t)1u << npostfix;
1810
299
  brotli_reg_t j;
1811
299
  brotli_reg_t bits = 1;
1812
299
  brotli_reg_t half = 0;
1813
1814
  /* Skip short codes. */
1815
299
  brotli_reg_t i = BROTLI_NUM_DISTANCE_SHORT_CODES;
1816
1817
  /* Fill direct codes. */
1818
9.14k
  for (j = 0; j < ndirect; ++j) {
1819
8.84k
    b->dist_extra_bits[i] = 0;
1820
8.84k
    b->dist_offset[i] = j + 1;
1821
8.84k
    ++i;
1822
8.84k
  }
1823
1824
  /* Fill regular distance codes. */
1825
14.6k
  while (i < alphabet_size_limit) {
1826
14.3k
    brotli_reg_t base = ndirect + ((((2 + half) << bits) - 4) << npostfix) + 1;
1827
    /* Always fill the complete group. */
1828
76.9k
    for (j = 0; j < postfix; ++j) {
1829
62.6k
      b->dist_extra_bits[i] = (uint8_t)bits;
1830
62.6k
      b->dist_offset[i] = base + j;
1831
62.6k
      ++i;
1832
62.6k
    }
1833
14.3k
    bits = bits + half;
1834
14.3k
    half = half ^ 1;
1835
14.3k
  }
1836
299
}
1837
1838
/* Precondition: s->distance_code < 0. */
1839
static BROTLI_INLINE BROTLI_BOOL ReadDistanceInternal(
1840
4.91k
    int safe, BrotliDecoderState* s, BrotliBitReader* br) {
1841
4.91k
  BrotliMetablockBodyArena* b = &s->arena.body;
1842
4.91k
  brotli_reg_t code;
1843
4.91k
  brotli_reg_t bits;
1844
4.91k
  BrotliBitReaderState memento;
1845
4.91k
  HuffmanCode* distance_tree = s->distance_hgroup.htrees[s->dist_htree_index];
1846
4.91k
  if (!safe) {
1847
4.67k
    code = ReadSymbol(distance_tree, br);
1848
4.67k
  } else {
1849
238
    BrotliBitReaderSaveState(br, &memento);
1850
238
    if (!SafeReadSymbol(distance_tree, br, &code)) {
1851
3
      return BROTLI_FALSE;
1852
3
    }
1853
238
  }
1854
4.90k
  --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
4.90k
  s->distance_context = 0;
1858
4.90k
  if ((code & ~0xFu) == 0) {
1859
1.47k
    s->distance_code = (int)code;
1860
1.47k
    TakeDistanceFromRingBuffer(s);
1861
1.47k
    return BROTLI_TRUE;
1862
1.47k
  }
1863
3.43k
  if (!safe) {
1864
3.28k
    bits = BrotliReadBits32(br, b->dist_extra_bits[code]);
1865
3.28k
  } else {
1866
146
    if (!SafeReadBits32(br, b->dist_extra_bits[code], &bits)) {
1867
3
      ++s->block_length[2];
1868
3
      BrotliBitReaderRestoreState(br, &memento);
1869
3
      return BROTLI_FALSE;
1870
3
    }
1871
146
  }
1872
3.42k
  s->distance_code =
1873
3.42k
      (int)(b->dist_offset[code] + (bits << s->distance_postfix_bits));
1874
3.42k
  return BROTLI_TRUE;
1875
3.43k
}
1876
1877
static BROTLI_INLINE void ReadDistance(
1878
4.67k
    BrotliDecoderState* s, BrotliBitReader* br) {
1879
4.67k
  ReadDistanceInternal(0, s, br);
1880
4.67k
}
1881
1882
static BROTLI_INLINE BROTLI_BOOL SafeReadDistance(
1883
238
    BrotliDecoderState* s, BrotliBitReader* br) {
1884
238
  return ReadDistanceInternal(1, s, br);
1885
238
}
1886
1887
static BROTLI_INLINE BROTLI_BOOL ReadCommandInternal(
1888
122k
    int safe, BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
1889
122k
  brotli_reg_t cmd_code;
1890
122k
  brotli_reg_t insert_len_extra = 0;
1891
122k
  brotli_reg_t copy_length;
1892
122k
  CmdLutElement v;
1893
122k
  BrotliBitReaderState memento;
1894
122k
  if (!safe) {
1895
121k
    cmd_code = ReadSymbol(s->htree_command, br);
1896
121k
  } else {
1897
888
    BrotliBitReaderSaveState(br, &memento);
1898
888
    if (!SafeReadSymbol(s->htree_command, br, &cmd_code)) {
1899
7
      return BROTLI_FALSE;
1900
7
    }
1901
888
  }
1902
122k
  v = kCmdLut[cmd_code];
1903
122k
  s->distance_code = v.distance_code;
1904
122k
  s->distance_context = v.context;
1905
122k
  s->dist_htree_index = s->dist_context_map_slice[s->distance_context];
1906
122k
  *insert_length = v.insert_len_offset;
1907
122k
  if (!safe) {
1908
121k
    if (BROTLI_PREDICT_FALSE(v.insert_len_extra_bits != 0)) {
1909
48.6k
      insert_len_extra = BrotliReadBits24(br, v.insert_len_extra_bits);
1910
48.6k
    }
1911
121k
    copy_length = BrotliReadBits24(br, v.copy_len_extra_bits);
1912
121k
  } else {
1913
881
    if (!SafeReadBits(br, v.insert_len_extra_bits, &insert_len_extra) ||
1914
879
        !SafeReadBits(br, v.copy_len_extra_bits, &copy_length)) {
1915
5
      BrotliBitReaderRestoreState(br, &memento);
1916
5
      return BROTLI_FALSE;
1917
5
    }
1918
881
  }
1919
122k
  s->copy_length = (int)copy_length + v.copy_len_offset;
1920
122k
  --s->block_length[1];
1921
122k
  *insert_length += (int)insert_len_extra;
1922
122k
  return BROTLI_TRUE;
1923
122k
}
1924
1925
static BROTLI_INLINE void ReadCommand(
1926
121k
    BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
1927
121k
  ReadCommandInternal(0, s, br, insert_length);
1928
121k
}
1929
1930
static BROTLI_INLINE BROTLI_BOOL SafeReadCommand(
1931
888
    BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
1932
888
  return ReadCommandInternal(1, s, br, insert_length);
1933
888
}
1934
1935
static BROTLI_INLINE BROTLI_BOOL CheckInputAmount(
1936
241k
    int safe, BrotliBitReader* const br) {
1937
241k
  if (safe) {
1938
1.07k
    return BROTLI_TRUE;
1939
1.07k
  }
1940
240k
  return BrotliCheckInputAmount(br);
1941
241k
}
1942
1943
#define BROTLI_SAFE(METHOD)                       \
1944
141k
  {                                               \
1945
141k
    if (safe) {                                   \
1946
1.63k
      if (!Safe##METHOD) {                        \
1947
27
        result = BROTLI_DECODER_NEEDS_MORE_INPUT; \
1948
27
        goto saveStateAndReturn;                  \
1949
27
      }                                           \
1950
140k
    } else {                                      \
1951
140k
      METHOD;                                     \
1952
140k
    }                                             \
1953
141k
  }
1954
1955
static BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal(
1956
483
    int safe, BrotliDecoderState* s) {
1957
483
  int pos = s->pos;
1958
483
  int i = s->loop_counter;
1959
483
  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
1960
483
  BrotliBitReader* br = &s->br;
1961
483
  int compound_dictionary_size = GetCompoundDictionarySize(s);
1962
1963
483
  if (!CheckInputAmount(safe, br)) {
1964
4
    result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1965
4
    goto saveStateAndReturn;
1966
4
  }
1967
479
  if (!safe) {
1968
295
    BROTLI_UNUSED(BrotliWarmupBitReader(br));
1969
295
  }
1970
1971
  /* Jump into state machine. */
1972
479
  if (s->state == BROTLI_STATE_COMMAND_BEGIN) {
1973
320
    goto CommandBegin;
1974
320
  } else if (s->state == BROTLI_STATE_COMMAND_INNER) {
1975
159
    goto CommandInner;
1976
159
  } else if (s->state == BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) {
1977
0
    goto CommandPostDecodeLiterals;
1978
0
  } else if (s->state == BROTLI_STATE_COMMAND_POST_WRAP_COPY) {
1979
0
    goto CommandPostWrapCopy;
1980
0
  } else {
1981
0
    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);  /* COV_NF_LINE */
1982
0
  }
1983
1984
122k
CommandBegin:
1985
122k
  if (safe) {
1986
888
    s->state = BROTLI_STATE_COMMAND_BEGIN;
1987
888
  }
1988
122k
  if (!CheckInputAmount(safe, br)) {
1989
21
    s->state = BROTLI_STATE_COMMAND_BEGIN;
1990
21
    result = BROTLI_DECODER_NEEDS_MORE_INPUT;
1991
21
    goto saveStateAndReturn;
1992
21
  }
1993
122k
  if (BROTLI_PREDICT_FALSE(s->block_length[1] == 0)) {
1994
0
    BROTLI_SAFE(DecodeCommandBlockSwitch(s));
1995
0
    goto CommandBegin;
1996
0
  }
1997
  /* Read the insert/copy length in the command. */
1998
122k
  BROTLI_SAFE(ReadCommand(s, br, &i));
1999
122k
  BROTLI_LOG(("[ProcessCommandsInternal] pos = %d insert = %d copy = %d\n",
2000
122k
              pos, i, s->copy_length));
2001
122k
  if (i == 0) {
2002
17.4k
    goto CommandPostDecodeLiterals;
2003
17.4k
  }
2004
104k
  s->meta_block_remaining_len -= i;
2005
2006
119k
CommandInner:
2007
119k
  if (safe) {
2008
1.33k
    s->state = BROTLI_STATE_COMMAND_INNER;
2009
1.33k
  }
2010
  /* Read the literals in the command. */
2011
119k
  if (s->trivial_literal_context) {
2012
119k
    brotli_reg_t bits;
2013
119k
    brotli_reg_t value;
2014
119k
    PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
2015
119k
    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
118k
      int num_steps = i - 1;
2023
118k
      if (num_steps > 0 && ((brotli_reg_t)(num_steps) > s->block_length[0])) {
2024
        // Safe cast, since block_length < steps
2025
12.6k
        num_steps = (int)s->block_length[0];
2026
12.6k
      }
2027
118k
      if (s->ringbuffer_size >= pos &&
2028
118k
          (s->ringbuffer_size - pos) <= num_steps) {
2029
16
        num_steps = s->ringbuffer_size - pos - 1;
2030
16
      }
2031
118k
      if (num_steps < 0) {
2032
0
        num_steps = 0;
2033
0
      }
2034
118k
      num_steps = BrotliCopyPreloadedSymbolsToU8(s->literal_htree, br, &bits,
2035
118k
                                                 &value, s->ringbuffer, pos,
2036
118k
                                                 num_steps);
2037
118k
      pos += num_steps;
2038
118k
      s->block_length[0] -= (brotli_reg_t)num_steps;
2039
118k
      i -= num_steps;
2040
118k
      do {
2041
118k
        if (!CheckInputAmount(safe, br)) {
2042
159
          s->state = BROTLI_STATE_COMMAND_INNER;
2043
159
          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2044
159
          goto saveStateAndReturn;
2045
159
        }
2046
118k
        if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) {
2047
14.3k
          goto NextLiteralBlock;
2048
14.3k
        }
2049
103k
        BrotliCopyPreloadedSymbolsToU8(s->literal_htree, br, &bits, &value,
2050
103k
                                       s->ringbuffer, pos, 1);
2051
103k
        --s->block_length[0];
2052
103k
        BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
2053
103k
        ++pos;
2054
103k
        if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) {
2055
12
          s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
2056
12
          --i;
2057
12
          goto saveStateAndReturn;
2058
12
        }
2059
103k
      } while (--i != 0);
2060
118k
    } else { /* safe */
2061
7.51k
      do {
2062
7.51k
        if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) {
2063
509
          goto NextLiteralBlock;
2064
509
        }
2065
7.00k
        brotli_reg_t literal;
2066
7.00k
        if (!SafeReadSymbol(s->literal_htree, br, &literal)) {
2067
112
          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2068
112
          goto saveStateAndReturn;
2069
112
        }
2070
6.89k
        s->ringbuffer[pos] = (uint8_t)literal;
2071
6.89k
        --s->block_length[0];
2072
6.89k
        BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
2073
6.89k
        ++pos;
2074
6.89k
        if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) {
2075
1
          s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
2076
1
          --i;
2077
1
          goto saveStateAndReturn;
2078
1
        }
2079
6.89k
      } while (--i != 0);
2080
1.33k
    }
2081
119k
  } else {
2082
0
    uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask];
2083
0
    uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask];
2084
0
    do {
2085
0
      const HuffmanCode* hc;
2086
0
      uint8_t context;
2087
0
      if (!CheckInputAmount(safe, br)) {
2088
0
        s->state = BROTLI_STATE_COMMAND_INNER;
2089
0
        result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2090
0
        goto saveStateAndReturn;
2091
0
      }
2092
0
      if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) {
2093
0
        goto NextLiteralBlock;
2094
0
      }
2095
0
      context = BROTLI_CONTEXT(p1, p2, s->context_lookup);
2096
0
      BROTLI_LOG_UINT(context);
2097
0
      hc = s->literal_hgroup.htrees[s->context_map_slice[context]];
2098
0
      p2 = p1;
2099
0
      if (!safe) {
2100
0
        p1 = (uint8_t)ReadSymbol(hc, br);
2101
0
      } else {
2102
0
        brotli_reg_t literal;
2103
0
        if (!SafeReadSymbol(hc, br, &literal)) {
2104
0
          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2105
0
          goto saveStateAndReturn;
2106
0
        }
2107
0
        p1 = (uint8_t)literal;
2108
0
      }
2109
0
      s->ringbuffer[pos] = p1;
2110
0
      --s->block_length[0];
2111
0
      BROTLI_LOG_UINT(s->context_map_slice[context]);
2112
0
      BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask);
2113
0
      ++pos;
2114
0
      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
0
    } while (--i != 0);
2120
0
  }
2121
104k
  BROTLI_LOG_UINT(s->meta_block_remaining_len);
2122
104k
  if (BROTLI_PREDICT_FALSE(s->meta_block_remaining_len <= 0)) {
2123
44
    s->state = BROTLI_STATE_METABLOCK_DONE;
2124
44
    goto saveStateAndReturn;
2125
44
  }
2126
2127
121k
CommandPostDecodeLiterals:
2128
121k
  if (safe) {
2129
904
    s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2130
904
  }
2131
121k
  if (s->distance_code >= 0) {
2132
    /* Implicit distance case. */
2133
117k
    s->distance_context = s->distance_code ? 0 : 1;
2134
117k
    --s->dist_rb_idx;
2135
117k
    s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
2136
117k
  } else {
2137
    /* Read distance code in the command, unless it was implicitly zero. */
2138
4.91k
    if (BROTLI_PREDICT_FALSE(s->block_length[2] == 0)) {
2139
0
      BROTLI_SAFE(DecodeDistanceBlockSwitch(s));
2140
0
    }
2141
4.91k
    BROTLI_SAFE(ReadDistance(s, br));
2142
4.90k
  }
2143
121k
  BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n",
2144
121k
              pos, s->distance_code));
2145
121k
  if (s->max_distance != s->max_backward_distance) {
2146
121k
    s->max_distance =
2147
121k
        (pos < s->max_backward_distance) ? pos : s->max_backward_distance;
2148
121k
  }
2149
121k
  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
121k
  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
2.23k
    if (s->distance_code > BROTLI_MAX_ALLOWED_DISTANCE) {
2157
4
      BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
2158
4
          "len: %d bytes left: %d\n",
2159
4
          pos, s->distance_code, i, s->meta_block_remaining_len));
2160
4
      return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DISTANCE);
2161
4
    }
2162
2.22k
    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
2.22k
    } else if (i >= SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH &&
2174
2.22k
               i <= SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH) {
2175
2.21k
      uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask];
2176
2.21k
      uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask];
2177
2.21k
      uint8_t dict_id = s->dictionary->context_based ?
2178
0
          s->dictionary->context_map[BROTLI_CONTEXT(p1, p2, s->context_lookup)]
2179
2.21k
          : 0;
2180
2.21k
      const BrotliDictionary* words = s->dictionary->words[dict_id];
2181
2.21k
      const BrotliTransforms* transforms = s->dictionary->transforms[dict_id];
2182
2.21k
      int offset = (int)words->offsets_by_length[i];
2183
2.21k
      brotli_reg_t shift = words->size_bits_by_length[i];
2184
2.21k
      int address =
2185
2.21k
          s->distance_code - s->max_distance - 1 - compound_dictionary_size;
2186
2.21k
      int mask = (int)BitMask(shift);
2187
2.21k
      int word_idx = address & mask;
2188
2.21k
      int transform_idx = address >> shift;
2189
      /* Compensate double distance-ring-buffer roll. */
2190
2.21k
      s->dist_rb_idx += s->distance_context;
2191
2.21k
      offset += word_idx * i;
2192
      /* If the distance is out of bound, select a next static dictionary if
2193
         there exist multiple. */
2194
2.21k
      if ((transform_idx >= (int)transforms->num_transforms ||
2195
2.19k
          words->size_bits_by_length[i] == 0) &&
2196
19
          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
2.21k
      if (BROTLI_PREDICT_FALSE(words->size_bits_by_length[i] == 0)) {
2226
2
        BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
2227
2
            "len: %d bytes left: %d\n",
2228
2
            pos, s->distance_code, i, s->meta_block_remaining_len));
2229
2
        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY);
2230
2
      }
2231
2.21k
      if (BROTLI_PREDICT_FALSE(!words->data)) {
2232
0
        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET);
2233
0
      }
2234
2.21k
      if (transform_idx < (int)transforms->num_transforms) {
2235
2.19k
        const uint8_t* word = &words->data[offset];
2236
2.19k
        int len = i;
2237
2.19k
        if (transform_idx == transforms->cutOffTransforms[0]) {
2238
685
          memcpy(&s->ringbuffer[pos], word, (size_t)len);
2239
685
          BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s]\n",
2240
685
                      len, word));
2241
1.50k
        } else {
2242
1.50k
          len = BrotliTransformDictionaryWord(&s->ringbuffer[pos], word, len,
2243
1.50k
              transforms, transform_idx);
2244
1.50k
          BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s],"
2245
1.50k
                      " transform_idx = %d, transformed: [%.*s]\n",
2246
1.50k
                      i, word, transform_idx, len, &s->ringbuffer[pos]));
2247
1.50k
          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
1.50k
        }
2252
2.19k
        pos += len;
2253
2.19k
        s->meta_block_remaining_len -= len;
2254
2.19k
        if (pos >= s->ringbuffer_size) {
2255
0
          s->state = BROTLI_STATE_COMMAND_POST_WRITE_1;
2256
0
          goto saveStateAndReturn;
2257
0
        }
2258
2.19k
      } else {
2259
17
        BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
2260
17
            "len: %d bytes left: %d\n",
2261
17
            pos, s->distance_code, i, s->meta_block_remaining_len));
2262
17
        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
2263
17
      }
2264
2.21k
    } else {
2265
15
      BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
2266
15
          "len: %d bytes left: %d\n",
2267
15
          pos, s->distance_code, i, s->meta_block_remaining_len));
2268
15
      return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY);
2269
15
    }
2270
119k
  } else {
2271
119k
    int src_start = (pos - s->distance_code) & s->ringbuffer_mask;
2272
119k
    uint8_t* copy_dst = &s->ringbuffer[pos];
2273
119k
    uint8_t* copy_src = &s->ringbuffer[src_start];
2274
119k
    int dst_end = pos + i;
2275
119k
    int src_end = src_start + i;
2276
    /* Update the recent distances cache. */
2277
119k
    s->dist_rb[s->dist_rb_idx & 3] = s->distance_code;
2278
119k
    ++s->dist_rb_idx;
2279
119k
    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
119k
    memmove16(copy_dst, copy_src);
2284
119k
    if (src_end > pos && dst_end > src_start) {
2285
      /* Regions intersect. */
2286
82.7k
      goto CommandPostWrapCopy;
2287
82.7k
    }
2288
36.9k
    if (dst_end >= s->ringbuffer_size || src_end >= s->ringbuffer_size) {
2289
      /* At least one region wraps. */
2290
1
      goto CommandPostWrapCopy;
2291
1
    }
2292
36.9k
    pos += i;
2293
36.9k
    if (i > 16) {
2294
190
      if (i > 32) {
2295
184
        memcpy(copy_dst + 16, copy_src + 16, (size_t)(i - 16));
2296
184
      } else {
2297
        /* This branch covers about 45% cases.
2298
           Fixed size short copy allows more compiler optimizations. */
2299
6
        memmove16(copy_dst + 16, copy_src + 16);
2300
6
      }
2301
190
    }
2302
36.9k
  }
2303
39.1k
  BROTLI_LOG_UINT(s->meta_block_remaining_len);
2304
39.1k
  if (s->meta_block_remaining_len <= 0) {
2305
    /* Next metablock, if any. */
2306
22
    s->state = BROTLI_STATE_METABLOCK_DONE;
2307
22
    goto saveStateAndReturn;
2308
39.1k
  } else {
2309
39.1k
    goto CommandBegin;
2310
39.1k
  }
2311
82.7k
CommandPostWrapCopy:
2312
82.7k
  {
2313
82.7k
    int wrap_guard = s->ringbuffer_size - pos;
2314
717k
    while (--i >= 0) {
2315
635k
      s->ringbuffer[pos] =
2316
635k
          s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
2317
635k
      ++pos;
2318
635k
      if (BROTLI_PREDICT_FALSE(--wrap_guard == 0)) {
2319
4
        s->state = BROTLI_STATE_COMMAND_POST_WRITE_2;
2320
4
        goto saveStateAndReturn;
2321
4
      }
2322
635k
    }
2323
82.7k
  }
2324
82.7k
  if (s->meta_block_remaining_len <= 0) {
2325
    /* Next metablock, if any. */
2326
39
    s->state = BROTLI_STATE_METABLOCK_DONE;
2327
39
    goto saveStateAndReturn;
2328
82.7k
  } else {
2329
82.7k
    goto CommandBegin;
2330
82.7k
  }
2331
2332
14.9k
NextLiteralBlock:
2333
14.9k
  BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
2334
14.8k
  goto CommandInner;
2335
2336
445
saveStateAndReturn:
2337
445
  s->pos = pos;
2338
445
  s->loop_counter = i;
2339
445
  return result;
2340
14.9k
}
2341
2342
#undef BROTLI_SAFE
2343
2344
static BROTLI_NOINLINE BrotliDecoderErrorCode ProcessCommands(
2345
299
    BrotliDecoderState* s) {
2346
299
  return ProcessCommandsInternal(0, s);
2347
299
}
2348
2349
static BROTLI_NOINLINE BrotliDecoderErrorCode SafeProcessCommands(
2350
184
    BrotliDecoderState* s) {
2351
184
  return ProcessCommandsInternal(1, s);
2352
184
}
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
631
    size_t* available_out, uint8_t** next_out, size_t* total_out) {
2393
631
  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
2394
631
  BrotliBitReader* br = &s->br;
2395
631
  size_t input_size = *available_in;
2396
631
#define BROTLI_SAVE_ERROR_CODE(code) \
2397
631
    SaveErrorCode(s, (code), input_size - *available_in)
2398
  /* Ensure that |total_out| is set, even if no data will ever be pushed out. */
2399
631
  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
631
  if ((int)s->error_code < 0) {
2404
0
    return BROTLI_DECODER_RESULT_ERROR;
2405
0
  }
2406
631
  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
631
  if (!*available_out) next_out = 0;
2411
631
  if (s->buffer_length == 0) {  /* Just connect bit reader to input stream. */
2412
631
    BrotliBitReaderSetInput(br, *next_in, *available_in);
2413
631
  } 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
4.90k
  for (;;) {
2422
4.90k
    if (result != BROTLI_DECODER_SUCCESS) {
2423
      /* Error, needs more input/output. */
2424
584
      if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
2425
222
        if (s->ringbuffer != 0) {  /* Pro-actively push output. */
2426
162
          BrotliDecoderErrorCode intermediate_result = WriteRingBuffer(s,
2427
162
              available_out, next_out, total_out, BROTLI_TRUE);
2428
          /* WriteRingBuffer checks s->meta_block_remaining_len validity. */
2429
162
          if ((int)intermediate_result < 0) {
2430
6
            result = intermediate_result;
2431
6
            break;
2432
6
          }
2433
162
        }
2434
216
        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
216
        } else {  /* Input stream doesn't contain enough input. */
2460
          /* Copy tail to internal buffer and return. */
2461
216
          *next_in = br->next_in;
2462
216
          *available_in = BrotliBitReaderGetAvailIn(br);
2463
216
          while (*available_in) {
2464
0
            s->buffer.u8[s->buffer_length] = **next_in;
2465
0
            s->buffer_length++;
2466
0
            (*next_in)++;
2467
0
            (*available_in)--;
2468
0
          }
2469
216
          break;
2470
216
        }
2471
        /* Unreachable. */
2472
216
      }
2473
2474
      /* Fail or needs more output. */
2475
2476
362
      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
362
      } 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
362
        BrotliBitReaderUnload(br);
2485
362
        *available_in = BrotliBitReaderGetAvailIn(br);
2486
362
        *next_in = br->next_in;
2487
362
      }
2488
362
      break;
2489
584
    }
2490
4.32k
    switch (s->state) {
2491
631
      case BROTLI_STATE_UNINITED:
2492
        /* Prepare to the first read. */
2493
631
        if (!BrotliWarmupBitReader(br)) {
2494
2
          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2495
2
          break;
2496
2
        }
2497
        /* Decode window size. */
2498
629
        result = DecodeWindowBits(s, br);  /* Reads 1..8 bits. */
2499
629
        if (result != BROTLI_DECODER_SUCCESS) {
2500
2
          break;
2501
2
        }
2502
627
        if (s->large_window) {
2503
0
          s->state = BROTLI_STATE_LARGE_WINDOW_BITS;
2504
0
          break;
2505
0
        }
2506
627
        s->state = BROTLI_STATE_INITIALIZE;
2507
627
        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
627
      case BROTLI_STATE_INITIALIZE:
2526
627
        BROTLI_LOG_UINT(s->window_bits);
2527
        /* Maximum distance, see section 9.1. of the spec. */
2528
627
        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
627
        s->block_type_trees = (HuffmanCode*)BROTLI_DECODER_ALLOC(s,
2532
627
            sizeof(HuffmanCode) * 3 *
2533
627
                (BROTLI_HUFFMAN_MAX_SIZE_258 + BROTLI_HUFFMAN_MAX_SIZE_26));
2534
627
        if (s->block_type_trees == 0) {
2535
0
          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES);
2536
0
          break;
2537
0
        }
2538
627
        s->block_len_trees =
2539
627
            s->block_type_trees + 3 * BROTLI_HUFFMAN_MAX_SIZE_258;
2540
2541
627
        s->state = BROTLI_STATE_METABLOCK_BEGIN;
2542
      /* Fall through. */
2543
2544
706
      case BROTLI_STATE_METABLOCK_BEGIN:
2545
706
        BrotliDecoderStateMetablockBegin(s);
2546
706
        BROTLI_LOG_UINT(s->pos);
2547
706
        s->state = BROTLI_STATE_METABLOCK_HEADER;
2548
      /* Fall through. */
2549
2550
706
      case BROTLI_STATE_METABLOCK_HEADER:
2551
706
        result = DecodeMetaBlockLength(s, br);  /* Reads 2 - 31 bits. */
2552
706
        if (result != BROTLI_DECODER_SUCCESS) {
2553
16
          break;
2554
16
        }
2555
690
        BROTLI_LOG_UINT(s->is_last_metablock);
2556
690
        BROTLI_LOG_UINT(s->meta_block_remaining_len);
2557
690
        BROTLI_LOG_UINT(s->is_metadata);
2558
690
        BROTLI_LOG_UINT(s->is_uncompressed);
2559
690
        if (s->is_metadata || s->is_uncompressed) {
2560
88
          if (!BrotliJumpToByteBoundary(br)) {
2561
9
            result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1);
2562
9
            break;
2563
9
          }
2564
88
        }
2565
681
        if (s->is_metadata) {
2566
55
          s->state = BROTLI_STATE_METADATA;
2567
55
          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
55
          break;
2572
55
        }
2573
626
        if (s->meta_block_remaining_len == 0) {
2574
36
          s->state = BROTLI_STATE_METABLOCK_DONE;
2575
36
          break;
2576
36
        }
2577
590
        BrotliCalculateRingBufferSize(s);
2578
590
        if (s->is_uncompressed) {
2579
24
          s->state = BROTLI_STATE_UNCOMPRESSED;
2580
24
          break;
2581
24
        }
2582
566
        s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER;
2583
      /* Fall through. */
2584
2585
566
      case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER: {
2586
566
        BrotliMetablockHeaderArena* h = &s->arena.header;
2587
566
        s->loop_counter = 0;
2588
        /* Initialize compressed metablock header arena. */
2589
566
        h->sub_loop_counter = 0;
2590
        /* Make small negative indexes addressable. */
2591
566
        h->symbol_lists =
2592
566
            &h->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1];
2593
566
        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
2594
566
        h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
2595
566
        h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
2596
566
        s->state = BROTLI_STATE_HUFFMAN_CODE_0;
2597
566
      }
2598
      /* Fall through. */
2599
2600
2.09k
      case BROTLI_STATE_HUFFMAN_CODE_0:
2601
2.09k
        if (s->loop_counter >= 3) {
2602
494
          s->state = BROTLI_STATE_METABLOCK_HEADER_2;
2603
494
          break;
2604
494
        }
2605
        /* Reads 1..11 bits. */
2606
1.59k
        result = DecodeVarLenUint8(s, br, &s->num_block_types[s->loop_counter]);
2607
1.59k
        if (result != BROTLI_DECODER_SUCCESS) {
2608
0
          break;
2609
0
        }
2610
1.59k
        s->num_block_types[s->loop_counter]++;
2611
1.59k
        BROTLI_LOG_UINT(s->num_block_types[s->loop_counter]);
2612
1.59k
        if (s->num_block_types[s->loop_counter] < 2) {
2613
1.42k
          s->loop_counter++;
2614
1.42k
          break;
2615
1.42k
        }
2616
178
        s->state = BROTLI_STATE_HUFFMAN_CODE_1;
2617
      /* Fall through. */
2618
2619
178
      case BROTLI_STATE_HUFFMAN_CODE_1: {
2620
178
        brotli_reg_t alphabet_size = s->num_block_types[s->loop_counter] + 2;
2621
178
        int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_258;
2622
178
        result = ReadHuffmanCode(alphabet_size, alphabet_size,
2623
178
            &s->block_type_trees[tree_offset], NULL, s);
2624
178
        if (result != BROTLI_DECODER_SUCCESS) break;
2625
128
        s->state = BROTLI_STATE_HUFFMAN_CODE_2;
2626
128
      }
2627
      /* Fall through. */
2628
2629
128
      case BROTLI_STATE_HUFFMAN_CODE_2: {
2630
128
        brotli_reg_t alphabet_size = BROTLI_NUM_BLOCK_LEN_SYMBOLS;
2631
128
        int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26;
2632
128
        result = ReadHuffmanCode(alphabet_size, alphabet_size,
2633
128
            &s->block_len_trees[tree_offset], NULL, s);
2634
128
        if (result != BROTLI_DECODER_SUCCESS) break;
2635
106
        s->state = BROTLI_STATE_HUFFMAN_CODE_3;
2636
106
      }
2637
      /* Fall through. */
2638
2639
106
      case BROTLI_STATE_HUFFMAN_CODE_3: {
2640
106
        int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26;
2641
106
        if (!SafeReadBlockLength(s, &s->block_length[s->loop_counter],
2642
106
            &s->block_len_trees[tree_offset], br)) {
2643
0
          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2644
0
          break;
2645
0
        }
2646
106
        BROTLI_LOG_UINT(s->block_length[s->loop_counter]);
2647
106
        s->loop_counter++;
2648
106
        s->state = BROTLI_STATE_HUFFMAN_CODE_0;
2649
106
        break;
2650
106
      }
2651
2652
24
      case BROTLI_STATE_UNCOMPRESSED: {
2653
24
        result = CopyUncompressedBlockToOutput(
2654
24
            available_out, next_out, total_out, s);
2655
24
        if (result != BROTLI_DECODER_SUCCESS) {
2656
14
          break;
2657
14
        }
2658
10
        s->state = BROTLI_STATE_METABLOCK_DONE;
2659
10
        break;
2660
24
      }
2661
2662
55
      case BROTLI_STATE_METADATA:
2663
55
        result = SkipMetadataBlock(s);
2664
55
        if (result != BROTLI_DECODER_SUCCESS) {
2665
15
          break;
2666
15
        }
2667
40
        s->state = BROTLI_STATE_METABLOCK_DONE;
2668
40
        break;
2669
2670
494
      case BROTLI_STATE_METABLOCK_HEADER_2: {
2671
494
        brotli_reg_t bits;
2672
494
        if (!BrotliSafeReadBits(br, 6, &bits)) {
2673
0
          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
2674
0
          break;
2675
0
        }
2676
494
        s->distance_postfix_bits = bits & BitMask(2);
2677
494
        bits >>= 2;
2678
494
        s->num_direct_distance_codes = bits << s->distance_postfix_bits;
2679
494
        BROTLI_LOG_UINT(s->num_direct_distance_codes);
2680
494
        BROTLI_LOG_UINT(s->distance_postfix_bits);
2681
494
        s->context_modes =
2682
494
            (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)s->num_block_types[0]);
2683
494
        if (s->context_modes == 0) {
2684
0
          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES);
2685
0
          break;
2686
0
        }
2687
494
        s->loop_counter = 0;
2688
494
        s->state = BROTLI_STATE_CONTEXT_MODES;
2689
494
      }
2690
      /* Fall through. */
2691
2692
494
      case BROTLI_STATE_CONTEXT_MODES:
2693
494
        result = ReadContextModes(s);
2694
494
        if (result != BROTLI_DECODER_SUCCESS) {
2695
3
          break;
2696
3
        }
2697
491
        s->state = BROTLI_STATE_CONTEXT_MAP_1;
2698
      /* Fall through. */
2699
2700
491
      case BROTLI_STATE_CONTEXT_MAP_1:
2701
491
        result = DecodeContextMap(
2702
491
            s->num_block_types[0] << BROTLI_LITERAL_CONTEXT_BITS,
2703
491
            &s->num_literal_htrees, &s->context_map, s);
2704
491
        if (result != BROTLI_DECODER_SUCCESS) {
2705
31
          break;
2706
31
        }
2707
460
        DetectTrivialLiteralBlockTypes(s);
2708
460
        s->state = BROTLI_STATE_CONTEXT_MAP_2;
2709
      /* Fall through. */
2710
2711
460
      case BROTLI_STATE_CONTEXT_MAP_2: {
2712
460
        brotli_reg_t npostfix = s->distance_postfix_bits;
2713
460
        brotli_reg_t ndirect = s->num_direct_distance_codes;
2714
460
        brotli_reg_t distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE(
2715
460
            npostfix, ndirect, BROTLI_MAX_DISTANCE_BITS);
2716
460
        brotli_reg_t distance_alphabet_size_limit = distance_alphabet_size_max;
2717
460
        BROTLI_BOOL allocation_success = BROTLI_TRUE;
2718
460
        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
460
        result = DecodeContextMap(
2727
460
            s->num_block_types[2] << BROTLI_DISTANCE_CONTEXT_BITS,
2728
460
            &s->num_dist_htrees, &s->dist_context_map, s);
2729
460
        if (result != BROTLI_DECODER_SUCCESS) {
2730
28
          break;
2731
28
        }
2732
432
        allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
2733
432
            s, &s->literal_hgroup, BROTLI_NUM_LITERAL_SYMBOLS,
2734
432
            BROTLI_NUM_LITERAL_SYMBOLS, s->num_literal_htrees);
2735
432
        allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
2736
432
            s, &s->insert_copy_hgroup, BROTLI_NUM_COMMAND_SYMBOLS,
2737
432
            BROTLI_NUM_COMMAND_SYMBOLS, s->num_block_types[1]);
2738
432
        allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
2739
432
            s, &s->distance_hgroup, distance_alphabet_size_max,
2740
432
            distance_alphabet_size_limit, s->num_dist_htrees);
2741
432
        if (!allocation_success) {
2742
0
          return BROTLI_SAVE_ERROR_CODE(
2743
0
              BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS));
2744
0
        }
2745
432
        s->loop_counter = 0;
2746
432
        s->state = BROTLI_STATE_TREE_GROUP;
2747
432
      }
2748
      /* Fall through. */
2749
2750
1.11k
      case BROTLI_STATE_TREE_GROUP: {
2751
1.11k
        HuffmanTreeGroup* hgroup = NULL;
2752
1.11k
        switch (s->loop_counter) {
2753
432
          case 0: hgroup = &s->literal_hgroup; break;
2754
365
          case 1: hgroup = &s->insert_copy_hgroup; break;
2755
316
          case 2: hgroup = &s->distance_hgroup; break;
2756
0
          default: return BROTLI_SAVE_ERROR_CODE(BROTLI_FAILURE(
2757
1.11k
              BROTLI_DECODER_ERROR_UNREACHABLE));  /* COV_NF_LINE */
2758
1.11k
        }
2759
1.11k
        result = HuffmanTreeGroupDecode(hgroup, s);
2760
1.11k
        if (result != BROTLI_DECODER_SUCCESS) break;
2761
980
        s->loop_counter++;
2762
980
        if (s->loop_counter < 3) {
2763
681
          break;
2764
681
        }
2765
299
        s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY;
2766
299
      }
2767
      /* Fall through. */
2768
2769
299
      case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY:
2770
299
        PrepareLiteralDecoding(s);
2771
299
        s->dist_context_map_slice = s->dist_context_map;
2772
299
        s->htree_command = s->insert_copy_hgroup.htrees[0];
2773
299
        if (!BrotliEnsureRingBuffer(s)) {
2774
0
          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
2775
0
          break;
2776
0
        }
2777
299
        CalculateDistanceLut(s);
2778
299
        s->state = BROTLI_STATE_COMMAND_BEGIN;
2779
      /* Fall through. */
2780
2781
299
      case BROTLI_STATE_COMMAND_BEGIN:
2782
      /* Fall through. */
2783
299
      case BROTLI_STATE_COMMAND_INNER:
2784
      /* Fall through. */
2785
299
      case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS:
2786
      /* Fall through. */
2787
299
      case BROTLI_STATE_COMMAND_POST_WRAP_COPY:
2788
299
        result = ProcessCommands(s);
2789
299
        if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
2790
184
          result = SafeProcessCommands(s);
2791
184
        }
2792
299
        break;
2793
2794
13
      case BROTLI_STATE_COMMAND_INNER_WRITE:
2795
      /* Fall through. */
2796
13
      case BROTLI_STATE_COMMAND_POST_WRITE_1:
2797
      /* Fall through. */
2798
17
      case BROTLI_STATE_COMMAND_POST_WRITE_2:
2799
17
        result = WriteRingBuffer(
2800
17
            s, available_out, next_out, total_out, BROTLI_FALSE);
2801
17
        if (result != BROTLI_DECODER_SUCCESS) {
2802
17
          break;
2803
17
        }
2804
0
        WrapRingBuffer(s);
2805
0
        if (s->ringbuffer_size == 1 << s->window_bits) {
2806
0
          s->max_distance = s->max_backward_distance;
2807
0
        }
2808
0
        if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) {
2809
0
          BrotliDecoderCompoundDictionary* addon = s->compound_dictionary;
2810
0
          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
0
          if (s->meta_block_remaining_len == 0) {
2815
            /* Next metablock, if any. */
2816
0
            s->state = BROTLI_STATE_METABLOCK_DONE;
2817
0
          } else {
2818
0
            s->state = BROTLI_STATE_COMMAND_BEGIN;
2819
0
          }
2820
0
          break;
2821
0
        } else if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_2) {
2822
0
          s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY;
2823
0
        } else {  /* BROTLI_STATE_COMMAND_INNER_WRITE */
2824
0
          if (s->loop_counter == 0) {
2825
0
            if (s->meta_block_remaining_len == 0) {
2826
0
              s->state = BROTLI_STATE_METABLOCK_DONE;
2827
0
            } else {
2828
0
              s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
2829
0
            }
2830
0
            break;
2831
0
          }
2832
0
          s->state = BROTLI_STATE_COMMAND_INNER;
2833
0
        }
2834
0
        break;
2835
2836
191
      case BROTLI_STATE_METABLOCK_DONE:
2837
191
        if (s->meta_block_remaining_len < 0) {
2838
61
          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2);
2839
61
          break;
2840
61
        }
2841
130
        BrotliDecoderStateCleanupAfterMetablock(s);
2842
130
        if (!s->is_last_metablock) {
2843
79
          s->state = BROTLI_STATE_METABLOCK_BEGIN;
2844
79
          break;
2845
79
        }
2846
51
        if (!BrotliJumpToByteBoundary(br)) {
2847
4
          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2);
2848
4
          break;
2849
4
        }
2850
47
        if (s->buffer_length == 0) {
2851
47
          BrotliBitReaderUnload(br);
2852
47
          *available_in = BrotliBitReaderGetAvailIn(br);
2853
47
          *next_in = br->next_in;
2854
47
        }
2855
47
        s->state = BROTLI_STATE_DONE;
2856
      /* Fall through. */
2857
2858
47
      case BROTLI_STATE_DONE:
2859
47
        if (s->ringbuffer != 0) {
2860
14
          result = WriteRingBuffer(
2861
14
              s, available_out, next_out, total_out, BROTLI_TRUE);
2862
14
          if (result != BROTLI_DECODER_SUCCESS) {
2863
0
            break;
2864
0
          }
2865
14
        }
2866
47
        return BROTLI_SAVE_ERROR_CODE(result);
2867
4.32k
    }
2868
4.32k
  }
2869
584
  return BROTLI_SAVE_ERROR_CODE(result);
2870
631
#undef BROTLI_SAVE_ERROR_CODE
2871
631
}
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
368
BrotliDecoderErrorCode BrotliDecoderGetErrorCode(const BrotliDecoderState* s) {
2918
368
  return (BrotliDecoderErrorCode)s->error_code;
2919
368
}
2920
2921
368
const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c) {
2922
368
  switch (c) {
2923
0
#define BROTLI_ERROR_CODE_CASE_(PREFIX, NAME, CODE) \
2924
368
    case BROTLI_DECODER ## PREFIX ## NAME: return #PREFIX #NAME;
2925
0
#define BROTLI_NOTHING_
2926
368
    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
368
  }
2931
368
}
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