]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tests/fuzz/simple_compress.c
Import Zstd 1.4.4
[FreeBSD/FreeBSD.git] / tests / fuzz / simple_compress.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 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 #include "zstd_helpers.h"
22 #include "fuzz_data_producer.h"
23
24 static ZSTD_CCtx *cctx = NULL;
25
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     size_t const maxSize = ZSTD_compressBound(size);
34     size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, maxSize);
35
36     int const cLevel = FUZZ_dataProducer_int32Range(producer, kMinClevel, kMaxClevel);
37
38     if (!cctx) {
39         cctx = ZSTD_createCCtx();
40         FUZZ_ASSERT(cctx);
41     }
42
43     void *rBuf = malloc(bufSize);
44     FUZZ_ASSERT(rBuf);
45     ZSTD_compressCCtx(cctx, rBuf, bufSize, src, size, cLevel);
46     free(rBuf);
47     FUZZ_dataProducer_free(producer);
48 #ifndef STATEFUL_FUZZING
49     ZSTD_freeCCtx(cctx); cctx = NULL;
50 #endif
51     return 0;
52 }