1 /*
2 * Copyright (c) 2016-present, Facebook, Inc.
3 * All rights reserved.
4 *
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 */
9
10 /**
11 * This fuzz target performs a zstd round-trip test (compress & decompress),
12 * compares the result with the original, and calls abort() on corruption.
13 */
14
15 #define ZSTD_STATIC_LINKING_ONLY
16
17 #include <stddef.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include "fuzz_helpers.h"
22 #include "zstd_helpers.h"
23
24 static const int kMaxClevel = 19;
25
26 static ZSTD_CCtx *cctx = NULL;
27 static ZSTD_DCtx *dctx = NULL;
28 static uint32_t seed;
29
roundTripTest(void * result,size_t resultCapacity,void * compressed,size_t compressedCapacity,const void * src,size_t srcSize)30 static size_t roundTripTest(void *result, size_t resultCapacity,
31 void *compressed, size_t compressedCapacity,
32 const void *src, size_t srcSize)
33 {
34 size_t cSize;
35 if (FUZZ_rand(&seed) & 1) {
36 FUZZ_setRandomParameters(cctx, srcSize, &seed);
37 cSize = ZSTD_compress2(cctx, compressed, compressedCapacity, src, srcSize);
38 } else {
39 int const cLevel = FUZZ_rand(&seed) % kMaxClevel;
40 cSize = ZSTD_compressCCtx(
41 cctx, compressed, compressedCapacity, src, srcSize, cLevel);
42 }
43 FUZZ_ZASSERT(cSize);
44 return ZSTD_decompressDCtx(dctx, result, resultCapacity, compressed, cSize);
45 }
46
LLVMFuzzerTestOneInput(const uint8_t * src,size_t size)47 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
48 {
49 size_t const rBufSize = size;
50 void* rBuf = malloc(rBufSize);
51 size_t cBufSize = ZSTD_compressBound(size);
52 void* cBuf;
53
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.
58 */
59 cBufSize -= FUZZ_rand32(&seed, 0, 1);
60 cBuf = malloc(cBufSize);
61
62 FUZZ_ASSERT(cBuf && rBuf);
63
64 if (!cctx) {
65 cctx = ZSTD_createCCtx();
66 FUZZ_ASSERT(cctx);
67 }
68 if (!dctx) {
69 dctx = ZSTD_createDCtx();
70 FUZZ_ASSERT(dctx);
71 }
72
73 {
74 size_t const result =
75 roundTripTest(rBuf, rBufSize, cBuf, cBufSize, src, size);
76 FUZZ_ZASSERT(result);
77 FUZZ_ASSERT_MSG(result == size, "Incorrect regenerated size");
78 FUZZ_ASSERT_MSG(!memcmp(src, rBuf, size), "Corruption!");
79 }
80 free(rBuf);
81 free(cBuf);
82 #ifndef STATEFUL_FUZZING
83 ZSTD_freeCCtx(cctx); cctx = NULL;
84 ZSTD_freeDCtx(dctx); dctx = NULL;
85 #endif
86 return 0;
87 }
88