1 /**
2  * Copyright (c) 2016-present, Yann Collet, 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 simple
12  * decompression function to ensure the decompressor never crashes.
13  */
14 
15 #define ZSTD_STATIC_LINKING_ONLY
16 
17 #include <stddef.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include "fuzz_helpers.h"
21 #include "zstd.h"
22 
23 static ZSTD_DCtx *dctx = NULL;
24 static void* rBuf = NULL;
25 static size_t bufSize = 0;
26 
LLVMFuzzerTestOneInput(const uint8_t * src,size_t size)27 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
28 {
29     size_t const neededBufSize = ZSTD_BLOCKSIZE_MAX;
30 
31     FUZZ_seed(&src, &size);
32 
33     /* Allocate all buffers and contexts if not already allocated */
34     if (neededBufSize > bufSize) {
35         free(rBuf);
36         rBuf = malloc(neededBufSize);
37         bufSize = neededBufSize;
38         FUZZ_ASSERT(rBuf);
39     }
40     if (!dctx) {
41         dctx = ZSTD_createDCtx();
42         FUZZ_ASSERT(dctx);
43     }
44     ZSTD_decompressBegin(dctx);
45     ZSTD_decompressBlock(dctx, rBuf, neededBufSize, src, size);
46 
47 #ifndef STATEFUL_FUZZING
48     ZSTD_freeDCtx(dctx); dctx = NULL;
49 #endif
50     return 0;
51 }
52