1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <stddef.h>
6 #include <stdint.h>
7 #include <stdlib.h>
8
9 #include <brotli/decode.h>
10
11 // Entry point for LibFuzzer.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)12 int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
13 size_t addend = 0;
14 if (size > 0)
15 addend = data[size - 1] & 7;
16 const uint8_t* next_in = data;
17
18 const int kBufferSize = 1024;
19 uint8_t* buffer = (uint8_t*) malloc(kBufferSize);
20 if (!buffer) {
21 // OOM is out-of-scope here.
22 return 0;
23 }
24 /* The biggest "magic number" in brotli is 16MiB - 16, so no need to check
25 the cases with much longer output. */
26 const size_t total_out_limit = (addend == 0) ? (1 << 26) : (1 << 24);
27 size_t total_out = 0;
28
29 BrotliDecoderState* state = BrotliDecoderCreateInstance(0, 0, 0);
30
31 if (addend == 0)
32 addend = size;
33 /* Test both fast (addend == size) and slow (addend <= 7) decoding paths. */
34 for (size_t i = 0; i < size;) {
35 size_t next_i = i + addend;
36 if (next_i > size)
37 next_i = size;
38 size_t avail_in = next_i - i;
39 i = next_i;
40 BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
41 while (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
42 size_t avail_out = kBufferSize;
43 uint8_t* next_out = buffer;
44 result = BrotliDecoderDecompressStream(
45 state, &avail_in, &next_in, &avail_out, &next_out, &total_out);
46 if (total_out > total_out_limit)
47 break;
48 }
49 if (total_out > total_out_limit)
50 break;
51 if (result != BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT)
52 break;
53 }
54
55 BrotliDecoderDestroyInstance(state);
56 free(buffer);
57 return 0;
58 }
59