• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016-2020, 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  * 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 
24 static ZSTD_DCtx *dctx = NULL;
25 
LLVMFuzzerTestOneInput(const uint8_t * src,size_t size)26 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
27 {
28     /* Give a random portion of src data to the producer, to use for
29     parameter generation. The rest will be used for (de)compression */
30     FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size);
31     size = FUZZ_dataProducer_reserveDataPrefix(producer);
32 
33     FUZZ_dict_t dict;
34     ZSTD_DDict* ddict = NULL;
35 
36     if (!dctx) {
37         dctx = ZSTD_createDCtx();
38         FUZZ_ASSERT(dctx);
39     }
40     dict = FUZZ_train(src, size, producer);
41     if (FUZZ_dataProducer_uint32Range(producer, 0, 1) == 0) {
42         ddict = ZSTD_createDDict(dict.buff, dict.size);
43         FUZZ_ASSERT(ddict);
44     } else {
45         if (FUZZ_dataProducer_uint32Range(producer, 0, 1) == 0)
46             FUZZ_ZASSERT(ZSTD_DCtx_loadDictionary_advanced(
47                 dctx, dict.buff, dict.size,
48                 (ZSTD_dictLoadMethod_e)FUZZ_dataProducer_uint32Range(producer, 0, 1),
49                 (ZSTD_dictContentType_e)FUZZ_dataProducer_uint32Range(producer, 0, 2)));
50         else
51             FUZZ_ZASSERT(ZSTD_DCtx_refPrefix_advanced(
52                 dctx, dict.buff, dict.size,
53                 (ZSTD_dictContentType_e)FUZZ_dataProducer_uint32Range(producer, 0, 2)));
54     }
55 
56     {
57         size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size);
58         void* rBuf = FUZZ_malloc(bufSize);
59         if (ddict) {
60             ZSTD_decompress_usingDDict(dctx, rBuf, bufSize, src, size, ddict);
61         } else {
62             ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size);
63         }
64         free(rBuf);
65     }
66     free(dict.buff);
67     FUZZ_dataProducer_free(producer);
68     ZSTD_freeDDict(ddict);
69 #ifndef STATEFUL_FUZZING
70     ZSTD_freeDCtx(dctx); dctx = NULL;
71 #endif
72     return 0;
73 }
74