]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tests/fuzz/dictionary_decompress.c
Import Zstd 1.4.4
[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 #include "fuzz_data_producer.h"
22
23 static ZSTD_DCtx *dctx = NULL;
24
25 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
26 {
27     /* Give a random portion of src data to the producer, to use for
28     parameter generation. The rest will be used for (de)compression */
29     FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size);
30     size = FUZZ_dataProducer_reserveDataPrefix(producer);
31
32     FUZZ_dict_t dict;
33     ZSTD_DDict* ddict = NULL;
34
35     if (!dctx) {
36         dctx = ZSTD_createDCtx();
37         FUZZ_ASSERT(dctx);
38     }
39     dict = FUZZ_train(src, size, producer);
40     if (FUZZ_dataProducer_uint32Range(producer, 0, 1) == 0) {
41         ddict = ZSTD_createDDict(dict.buff, dict.size);
42         FUZZ_ASSERT(ddict);
43     } else {
44         FUZZ_ZASSERT(ZSTD_DCtx_loadDictionary_advanced(
45                 dctx, dict.buff, dict.size,
46                 (ZSTD_dictLoadMethod_e)FUZZ_dataProducer_uint32Range(producer, 0, 1),
47                 (ZSTD_dictContentType_e)FUZZ_dataProducer_uint32Range(producer, 0, 2)));
48     }
49
50     {
51         size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size);
52         void* rBuf = malloc(bufSize);
53         FUZZ_ASSERT(rBuf);
54         if (ddict) {
55             ZSTD_decompress_usingDDict(dctx, rBuf, bufSize, src, size, ddict);
56         } else {
57             ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size);
58         }
59         free(rBuf);
60     }
61     free(dict.buff);
62     FUZZ_dataProducer_free(producer);
63     ZSTD_freeDDict(ddict);
64 #ifndef STATEFUL_FUZZING
65     ZSTD_freeDCtx(dctx); dctx = NULL;
66 #endif
67     return 0;
68 }