2 * Copyright (c) Meta Platforms, Inc. and affiliates.
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).
8 * You may select, at your option, one of the above-listed licenses.
12 * This fuzz target attempts to decompress the fuzzed data with the simple
13 * decompression function to ensure the decompressor never crashes.
16 #define ZSTD_STATIC_LINKING_ONLY
21 #include "fuzz_helpers.h"
23 #include "fuzz_data_producer.h"
25 static ZSTD_DStream *dstream = NULL;
28 static ZSTD_outBuffer makeOutBuffer(FUZZ_dataProducer_t *producer, void* buf, size_t bufSize)
30 ZSTD_outBuffer buffer = { buf, 0, 0 };
32 if (FUZZ_dataProducer_empty(producer)) {
33 buffer.size = bufSize;
35 buffer.size = (FUZZ_dataProducer_uint32Range(producer, 0, bufSize));
37 FUZZ_ASSERT(buffer.size <= bufSize);
39 if (buffer.size == 0) {
46 static ZSTD_inBuffer makeInBuffer(const uint8_t **src, size_t *size,
47 FUZZ_dataProducer_t *producer)
49 ZSTD_inBuffer buffer = { *src, 0, 0 };
51 FUZZ_ASSERT(*size > 0);
52 if (FUZZ_dataProducer_empty(producer)) {
55 buffer.size = (FUZZ_dataProducer_uint32Range(producer, 0, *size));
57 FUZZ_ASSERT(buffer.size <= *size);
61 if (buffer.size == 0) {
68 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
70 /* Give a random portion of src data to the producer, to use for
71 parameter generation. The rest will be used for (de)compression */
72 FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size);
77 size = FUZZ_dataProducer_reserveDataPrefix(producer);
78 bufSize = MAX(10 * size, ZSTD_BLOCKSIZE_MAX);
80 /* Allocate all buffers and contexts if not already allocated */
81 buf = FUZZ_malloc(bufSize);
84 dstream = ZSTD_createDStream();
87 FUZZ_ZASSERT(ZSTD_DCtx_reset(dstream, ZSTD_reset_session_only));
90 stableOutBuffer = FUZZ_dataProducer_uint32Range(producer, 0, 10) == 5;
91 if (stableOutBuffer) {
92 FUZZ_ZASSERT(ZSTD_DCtx_setParameter(dstream, ZSTD_d_stableOutBuffer, 1));
97 out = makeOutBuffer(producer, buf, bufSize);
101 ZSTD_inBuffer in = makeInBuffer(&src, &size, producer);
103 size_t const rc = ZSTD_decompressStream(dstream, &out, &in);
104 if (ZSTD_isError(rc)) goto error;
105 if (out.pos == out.size) {
106 if (stableOutBuffer) goto error;
107 out = makeOutBuffer(producer, buf, bufSize);
109 } while (in.pos != in.size);
113 #ifndef STATEFUL_FUZZING
114 ZSTD_freeDStream(dstream); dstream = NULL;
116 FUZZ_dataProducer_free(producer);