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"
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)
37 int const cLevel = FUZZ_rand(&seed) % kMaxClevel;
38 ZSTD_parameters const params = ZSTD_getParams(cLevel, srcSize, 0);
39 size_t ret = ZSTD_compressBegin_advanced(cctx, NULL, 0, params, srcSize);
42 ret = ZSTD_compressBlock(cctx, compressed, compressedCapacity, src, srcSize);
45 FUZZ_ASSERT(resultCapacity >= srcSize);
46 memcpy(result, src, srcSize);
49 ZSTD_decompressBegin(dctx);
50 return ZSTD_decompressBlock(dctx, result, resultCapacity, compressed, ret);
53 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
57 seed = FUZZ_seed(&src, &size);
59 if (size > ZSTD_BLOCKSIZE_MAX)
62 /* Allocate all buffers and contexts if not already allocated */
63 if (neededBufSize > bufSize || !cBuf || !rBuf) {
66 cBuf = malloc(neededBufSize);
67 rBuf = malloc(neededBufSize);
68 bufSize = neededBufSize;
69 FUZZ_ASSERT(cBuf && rBuf);
72 cctx = ZSTD_createCCtx();
76 dctx = ZSTD_createDCtx();
82 roundTripTest(rBuf, neededBufSize, cBuf, neededBufSize, src, size);
84 FUZZ_ASSERT_MSG(result == size, "Incorrect regenerated size");
85 FUZZ_ASSERT_MSG(!memcmp(src, rBuf, size), "Corruption!");
87 #ifndef STATEFUL_FUZZING
88 ZSTD_freeCCtx(cctx); cctx = NULL;
89 ZSTD_freeDCtx(dctx); dctx = NULL;