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 performs a zstd round-trip test (compress & decompress),
12 * compares the result with the original, and calls abort() on corruption.
15 #define ZSTD_STATIC_LINKING_ONLY
21 #include "fuzz_helpers.h"
22 #include "zstd_helpers.h"
24 static const int kMaxClevel = 19;
26 static ZSTD_CCtx *cctx = NULL;
27 static ZSTD_DCtx *dctx = NULL;
28 static void* cBuf = NULL;
29 static void* rBuf = NULL;
30 static size_t bufSize = 0;
33 static size_t roundTripTest(void *result, size_t resultCapacity,
34 void *compressed, size_t compressedCapacity,
35 const void *src, size_t srcSize)
38 if (FUZZ_rand(&seed) & 1) {
39 ZSTD_inBuffer in = {src, srcSize, 0};
40 ZSTD_outBuffer out = {compressed, compressedCapacity, 0};
43 ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
44 FUZZ_setRandomParameters(cctx, srcSize, &seed);
45 err = ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_end);
47 FUZZ_ASSERT(err == 0);
50 int const cLevel = FUZZ_rand(&seed) % kMaxClevel;
51 cSize = ZSTD_compressCCtx(
52 cctx, compressed, compressedCapacity, src, srcSize, cLevel);
55 return ZSTD_decompressDCtx(dctx, result, resultCapacity, compressed, cSize);
58 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
62 seed = FUZZ_seed(&src, &size);
63 neededBufSize = ZSTD_compressBound(size);
65 /* Allocate all buffers and contexts if not already allocated */
66 if (neededBufSize > bufSize) {
69 cBuf = malloc(neededBufSize);
70 rBuf = malloc(neededBufSize);
71 bufSize = neededBufSize;
72 FUZZ_ASSERT(cBuf && rBuf);
75 cctx = ZSTD_createCCtx();
79 dctx = ZSTD_createDCtx();
85 roundTripTest(rBuf, neededBufSize, cBuf, neededBufSize, src, size);
87 FUZZ_ASSERT_MSG(result == size, "Incorrect regenerated size");
88 FUZZ_ASSERT_MSG(!memcmp(src, rBuf, size), "Corruption!");
90 #ifndef STATEFUL_FUZZING
91 ZSTD_freeCCtx(cctx); cctx = NULL;
92 ZSTD_freeDCtx(dctx); dctx = NULL;