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.h"
23
24 static const int kMaxClevel = 19;
25
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;
31 static uint32_t seed;
32
roundTripTest(void * result,size_t resultCapacity,void * compressed,size_t compressedCapacity,const void * src,size_t srcSize)33 static size_t roundTripTest(void *result, size_t resultCapacity,
34 void *compressed, size_t compressedCapacity,
35 const void *src, size_t srcSize)
36 {
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);
40 FUZZ_ZASSERT(ret);
41
42 ret = ZSTD_compressBlock(cctx, compressed, compressedCapacity, src, srcSize);
43 FUZZ_ZASSERT(ret);
44 if (ret == 0) {
45 FUZZ_ASSERT(resultCapacity >= srcSize);
46 memcpy(result, src, srcSize);
47 return srcSize;
48 }
49 ZSTD_decompressBegin(dctx);
50 return ZSTD_decompressBlock(dctx, result, resultCapacity, compressed, ret);
51 }
52
LLVMFuzzerTestOneInput(const uint8_t * src,size_t size)53 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
54 {
55 size_t neededBufSize;
56
57 seed = FUZZ_seed(&src, &size);
58 neededBufSize = size;
59 if (size > ZSTD_BLOCKSIZE_MAX)
60 return 0;
61
62 /* Allocate all buffers and contexts if not already allocated */
63 if (neededBufSize > bufSize || !cBuf || !rBuf) {
64 free(cBuf);
65 free(rBuf);
66 cBuf = malloc(neededBufSize);
67 rBuf = malloc(neededBufSize);
68 bufSize = neededBufSize;
69 FUZZ_ASSERT(cBuf && rBuf);
70 }
71 if (!cctx) {
72 cctx = ZSTD_createCCtx();
73 FUZZ_ASSERT(cctx);
74 }
75 if (!dctx) {
76 dctx = ZSTD_createDCtx();
77 FUZZ_ASSERT(dctx);
78 }
79
80 {
81 size_t const result =
82 roundTripTest(rBuf, neededBufSize, cBuf, neededBufSize, src, size);
83 FUZZ_ZASSERT(result);
84 FUZZ_ASSERT_MSG(result == size, "Incorrect regenerated size");
85 FUZZ_ASSERT_MSG(!memcmp(src, rBuf, size), "Corruption!");
86 }
87 #ifndef STATEFUL_FUZZING
88 ZSTD_freeCCtx(cctx); cctx = NULL;
89 ZSTD_freeDCtx(dctx); dctx = NULL;
90 #endif
91 return 0;
92 }
93