git subrepo pull (merge) --force deps/libchdr
[pcsx_rearmed.git] / deps / libchdr / deps / zstd-1.5.5 / tests / fuzz / dictionary_decompress.c
1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
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  * You may select, at your option, one of the above-listed licenses.
9  */
10
11 /**
12  * This fuzz target attempts to decompress the fuzzed data with the dictionary
13  * decompression function to ensure the decompressor never crashes. It does not
14  * fuzz the dictionary.
15  */
16
17 #include <stddef.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include "fuzz_helpers.h"
21 #include "zstd_helpers.h"
22 #include "fuzz_data_producer.h"
23 #include "fuzz_third_party_seq_prod.h"
24
25 static ZSTD_DCtx *dctx = NULL;
26
27 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
28 {
29     FUZZ_SEQ_PROD_SETUP();
30
31     /* Give a random portion of src data to the producer, to use for
32     parameter generation. The rest will be used for (de)compression */
33     FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size);
34     size = FUZZ_dataProducer_reserveDataPrefix(producer);
35
36     FUZZ_dict_t dict;
37     ZSTD_DDict* ddict = NULL;
38
39     if (!dctx) {
40         dctx = ZSTD_createDCtx();
41         FUZZ_ASSERT(dctx);
42     }
43     dict = FUZZ_train(src, size, producer);
44     if (FUZZ_dataProducer_uint32Range(producer, 0, 1) == 0) {
45         ddict = ZSTD_createDDict(dict.buff, dict.size);
46         FUZZ_ASSERT(ddict);
47     } else {
48         if (FUZZ_dataProducer_uint32Range(producer, 0, 1) == 0)
49             FUZZ_ZASSERT(ZSTD_DCtx_loadDictionary_advanced(
50                 dctx, dict.buff, dict.size,
51                 (ZSTD_dictLoadMethod_e)FUZZ_dataProducer_uint32Range(producer, 0, 1),
52                 (ZSTD_dictContentType_e)FUZZ_dataProducer_uint32Range(producer, 0, 2)));
53         else
54             FUZZ_ZASSERT(ZSTD_DCtx_refPrefix_advanced(
55                 dctx, dict.buff, dict.size,
56                 (ZSTD_dictContentType_e)FUZZ_dataProducer_uint32Range(producer, 0, 2)));
57     }
58
59     {
60         size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size);
61         void* rBuf = FUZZ_malloc(bufSize);
62         if (ddict) {
63             ZSTD_decompress_usingDDict(dctx, rBuf, bufSize, src, size, ddict);
64         } else {
65             ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size);
66         }
67         free(rBuf);
68     }
69     free(dict.buff);
70     FUZZ_dataProducer_free(producer);
71     ZSTD_freeDDict(ddict);
72 #ifndef STATEFUL_FUZZING
73     ZSTD_freeDCtx(dctx); dctx = NULL;
74 #endif
75     FUZZ_SEQ_PROD_TEARDOWN();
76     return 0;
77 }