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 attempts to decompress the fuzzed data with the dictionary
12 * decompression function to ensure the decompressor never crashes. It does not
13 * fuzz the dictionary.
14 */
15
16 #include <stddef.h>
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include "fuzz_helpers.h"
20 #include "zstd_helpers.h"
21
22 static ZSTD_DCtx *dctx = NULL;
23
LLVMFuzzerTestOneInput(const uint8_t * src,size_t size)24 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
25 {
26 uint32_t seed = FUZZ_seed(&src, &size);
27 FUZZ_dict_t dict;
28 ZSTD_DDict* ddict = NULL;
29 int i;
30
31 if (!dctx) {
32 dctx = ZSTD_createDCtx();
33 FUZZ_ASSERT(dctx);
34 }
35 dict = FUZZ_train(src, size, &seed);
36 if (FUZZ_rand32(&seed, 0, 1) == 0) {
37 ddict = ZSTD_createDDict(dict.buff, dict.size);
38 FUZZ_ASSERT(ddict);
39 } else {
40 FUZZ_ZASSERT(ZSTD_DCtx_loadDictionary_advanced(
41 dctx, dict.buff, dict.size,
42 (ZSTD_dictLoadMethod_e)FUZZ_rand32(&seed, 0, 1),
43 (ZSTD_dictContentType_e)FUZZ_rand32(&seed, 0, 2)));
44 }
45 /* Run it 10 times over 10 output sizes. Reuse the context and dict. */
46 for (i = 0; i < 10; ++i) {
47 size_t const bufSize = FUZZ_rand32(&seed, 0, 2 * size);
48 void* rBuf = malloc(bufSize);
49 FUZZ_ASSERT(rBuf);
50 if (ddict) {
51 ZSTD_decompress_usingDDict(dctx, rBuf, bufSize, src, size, ddict);
52 } else {
53 ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size);
54 }
55 free(rBuf);
56 }
57 free(dict.buff);
58 ZSTD_freeDDict(ddict);
59 #ifndef STATEFUL_FUZZING
60 ZSTD_freeDCtx(dctx); dctx = NULL;
61 #endif
62 return 0;
63 }
64