Coverage Report

Created: 2018-09-25 14:53

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