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 comprss the fuzzed data with the simple
12  * compression function with an output buffer that may be too small to
13  * ensure that the compressor never crashes.
14  */
15 
16 #include <stddef.h>
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include "fuzz_helpers.h"
20 #include "zstd.h"
21 
22 static ZSTD_CCtx *cctx = NULL;
23 
LLVMFuzzerTestOneInput(const uint8_t * src,size_t size)24 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
25 {
26     uint32_t seed = FUZZ_seed(&src, &size);
27     size_t const maxSize = ZSTD_compressBound(size);
28     int i;
29     if (!cctx) {
30         cctx = ZSTD_createCCtx();
31         FUZZ_ASSERT(cctx);
32     }
33     /* Run it 10 times over 10 output sizes. Reuse the context. */
34     for (i = 0; i < 10; ++i) {
35         int const level = (int)FUZZ_rand32(&seed, 0, 19 + 3) - 3; /* [-3, 19] */
36         size_t const bufSize = FUZZ_rand32(&seed, 0, maxSize);
37         void* rBuf = malloc(bufSize);
38         FUZZ_ASSERT(rBuf);
39         ZSTD_compressCCtx(cctx, rBuf, bufSize, src, size, level);
40         free(rBuf);
41     }
42 
43 #ifndef STATEFUL_FUZZING
44     ZSTD_freeCCtx(cctx); cctx = NULL;
45 #endif
46     return 0;
47 }
48