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;
30 static size_t roundTripTest(void *result, size_t resultCapacity,
31 void *compressed, size_t compressedCapacity,
32 const void *src, size_t srcSize)
35 if (FUZZ_rand(&seed) & 1) {
36 FUZZ_setRandomParameters(cctx, srcSize, &seed);
37 cSize = ZSTD_compress2(cctx, compressed, compressedCapacity, src, srcSize);
39 int const cLevel = FUZZ_rand(&seed) % kMaxClevel;
40 cSize = ZSTD_compressCCtx(
41 cctx, compressed, compressedCapacity, src, srcSize, cLevel);
44 return ZSTD_decompressDCtx(dctx, result, resultCapacity, compressed, cSize);
47 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
49 size_t const rBufSize = size;
50 void* rBuf = malloc(rBufSize);
51 size_t cBufSize = ZSTD_compressBound(size);
54 seed = FUZZ_seed(&src, &size);
55 /* Half of the time fuzz with a 1 byte smaller output size.
56 * This will still succeed because we don't use a dictionary, so the dictID
57 * field is empty, giving us 4 bytes of overhead.
59 cBufSize -= FUZZ_rand32(&seed, 0, 1);
60 cBuf = malloc(cBufSize);
62 FUZZ_ASSERT(cBuf && rBuf);
65 cctx = ZSTD_createCCtx();
69 dctx = ZSTD_createDCtx();
75 roundTripTest(rBuf, rBufSize, cBuf, cBufSize, src, size);
77 FUZZ_ASSERT_MSG(result == size, "Incorrect regenerated size");
78 FUZZ_ASSERT_MSG(!memcmp(src, rBuf, size), "Corruption!");
82 #ifndef STATEFUL_FUZZING
83 ZSTD_freeCCtx(cctx); cctx = NULL;
84 ZSTD_freeDCtx(dctx); dctx = NULL;