]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tests/fuzz/dictionary_decompress.c
import zstd 1.4.0
[FreeBSD/FreeBSD.git] / tests / fuzz / dictionary_decompress.c
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 static void* rBuf = NULL;
24 static size_t bufSize = 0;
25
26 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
27 {
28     FUZZ_dict_t dict;
29     size_t neededBufSize;
30
31     uint32_t seed = FUZZ_seed(&src, &size);
32     neededBufSize = MAX(20 * size, (size_t)256 << 10);
33
34     /* Allocate all buffers and contexts if not already allocated */
35     if (neededBufSize > bufSize) {
36         free(rBuf);
37         rBuf = malloc(neededBufSize);
38         bufSize = neededBufSize;
39         FUZZ_ASSERT(rBuf);
40     }
41     if (!dctx) {
42         dctx = ZSTD_createDCtx();
43         FUZZ_ASSERT(dctx);
44     }
45     dict = FUZZ_train(src, size, &seed);
46     if (FUZZ_rand32(&seed, 0, 1) == 0) {
47         ZSTD_decompress_usingDict(dctx,
48                 rBuf, neededBufSize,
49                 src, size,
50                 dict.buff, dict.size);
51     } else {
52         FUZZ_ZASSERT(ZSTD_DCtx_loadDictionary_advanced(
53                 dctx, dict.buff, dict.size,
54                 (ZSTD_dictLoadMethod_e)FUZZ_rand32(&seed, 0, 1),
55                 (ZSTD_dictContentType_e)FUZZ_rand32(&seed, 0, 2)));
56         ZSTD_decompressDCtx(dctx, rBuf, neededBufSize, src, size);
57     }
58
59     free(dict.buff);
60 #ifndef STATEFUL_FUZZING
61     ZSTD_freeDCtx(dctx); dctx = NULL;
62 #endif
63     return 0;
64 }