Coverage Report

Created: 2026-04-29 07:00

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