2 * Copyright (c) 2016-present, Facebook, Inc.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
11 * This fuzz target attempts to decompress the fuzzed data with the simple
12 * decompression function to ensure the decompressor never crashes.
15 #define ZSTD_STATIC_LINKING_ONLY
20 #include "fuzz_helpers.h"
22 #include "fuzz_data_producer.h"
24 static size_t const kBufSize = ZSTD_BLOCKSIZE_MAX;
26 static ZSTD_DStream *dstream = NULL;
27 static void* buf = NULL;
30 static ZSTD_outBuffer makeOutBuffer(FUZZ_dataProducer_t *producer)
32 ZSTD_outBuffer buffer = { buf, 0, 0 };
34 buffer.size = (FUZZ_dataProducer_uint32Range(producer, 1, kBufSize));
35 FUZZ_ASSERT(buffer.size <= kBufSize);
40 static ZSTD_inBuffer makeInBuffer(const uint8_t **src, size_t *size,
41 FUZZ_dataProducer_t *producer)
43 ZSTD_inBuffer buffer = { *src, 0, 0 };
45 FUZZ_ASSERT(*size > 0);
46 buffer.size = (FUZZ_dataProducer_uint32Range(producer, 1, *size));
47 FUZZ_ASSERT(buffer.size <= *size);
54 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
56 /* Give a random portion of src data to the producer, to use for
57 parameter generation. The rest will be used for (de)compression */
58 FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size);
59 size = FUZZ_dataProducer_reserveDataPrefix(producer);
61 /* Allocate all buffers and contexts if not already allocated */
63 buf = malloc(kBufSize);
68 dstream = ZSTD_createDStream();
71 FUZZ_ZASSERT(ZSTD_DCtx_reset(dstream, ZSTD_reset_session_only));
75 ZSTD_inBuffer in = makeInBuffer(&src, &size, producer);
76 while (in.pos != in.size) {
77 ZSTD_outBuffer out = makeOutBuffer(producer);
78 size_t const rc = ZSTD_decompressStream(dstream, &out, &in);
79 if (ZSTD_isError(rc)) goto error;
84 #ifndef STATEFUL_FUZZING
85 ZSTD_freeDStream(dstream); dstream = NULL;
87 FUZZ_dataProducer_free(producer);