2 * Copyright (c) 2016-present, Facebook, Inc.
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree. An additional grant
7 * of patent rights can be found in the PATENTS file in the same directory.
11 * This fuzz target performs a zstd round-trip test (compress & decompress),
12 * compares the result with the original, and calls abort() on corruption.
19 #include "fuzz_helpers.h"
22 static const int kMaxClevel = 19;
24 static ZSTD_CCtx *cctx = NULL;
25 static ZSTD_DCtx *dctx = NULL;
26 static void* cBuf = NULL;
27 static void* rBuf = NULL;
28 static size_t bufSize = 0;
31 static size_t roundTripTest(void *result, size_t resultCapacity,
32 void *compressed, size_t compressedCapacity,
33 const void *src, size_t srcSize)
35 int const cLevel = FUZZ_rand(&seed) % kMaxClevel;
36 size_t const cSize = ZSTD_compressCCtx(cctx, compressed, compressedCapacity,
37 src, srcSize, cLevel);
38 if (ZSTD_isError(cSize)) {
39 fprintf(stderr, "Compression error: %s\n", ZSTD_getErrorName(cSize));
42 return ZSTD_decompressDCtx(dctx, result, resultCapacity, compressed, cSize);
45 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
47 size_t const neededBufSize = ZSTD_compressBound(size);
49 seed = FUZZ_seed(src, size);
51 /* Allocate all buffers and contexts if not already allocated */
52 if (neededBufSize > bufSize) {
55 cBuf = malloc(neededBufSize);
56 rBuf = malloc(neededBufSize);
57 bufSize = neededBufSize;
58 FUZZ_ASSERT(cBuf && rBuf);
61 cctx = ZSTD_createCCtx();
65 dctx = ZSTD_createDCtx();
71 roundTripTest(rBuf, neededBufSize, cBuf, neededBufSize, src, size);
72 FUZZ_ASSERT_MSG(!ZSTD_isError(result), ZSTD_getErrorName(result));
73 FUZZ_ASSERT_MSG(result == size, "Incorrect regenerated size");
74 FUZZ_ASSERT_MSG(!memcmp(src, rBuf, size), "Corruption!");
76 #ifndef STATEFULL_FUZZING
77 ZSTD_freeCCtx(cctx); cctx = NULL;
78 ZSTD_freeDCtx(dctx); dctx = NULL;