]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/zstd/tests/fuzz/stream_decompress.c
Import zstandard 1.3.1
[FreeBSD/FreeBSD.git] / contrib / zstd / tests / fuzz / stream_decompress.c
1 /**
2  * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree. An additional grant
7  * of patent rights can be found in the PATENTS file in the same directory.
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 size_t const kBufSize = ZSTD_BLOCKSIZE_ABSOLUTEMAX;
24
25 static ZSTD_DStream *dstream = NULL;
26 static void* buf = NULL;
27 uint32_t seed;
28
29 static ZSTD_outBuffer makeOutBuffer(void)
30 {
31   ZSTD_outBuffer buffer = { buf, 0, 0 };
32
33   buffer.size = (FUZZ_rand(&seed) % kBufSize) + 1;
34   FUZZ_ASSERT(buffer.size <= kBufSize);
35
36   return buffer;
37 }
38
39 static ZSTD_inBuffer makeInBuffer(const uint8_t **src, size_t *size)
40 {
41   ZSTD_inBuffer buffer = { *src, 0, 0 };
42
43   FUZZ_ASSERT(*size > 0);
44   buffer.size = (FUZZ_rand(&seed) % *size) + 1;
45   FUZZ_ASSERT(buffer.size <= *size);
46   *src += buffer.size;
47   *size -= buffer.size;
48
49   return buffer;
50 }
51
52 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
53 {
54     seed = FUZZ_seed(src, size);
55
56     /* Allocate all buffers and contexts if not already allocated */
57     if (!buf) {
58       buf = malloc(kBufSize);
59       FUZZ_ASSERT(buf);
60     }
61
62     if (!dstream) {
63         dstream = ZSTD_createDStream();
64         FUZZ_ASSERT(dstream);
65         FUZZ_ASSERT(!ZSTD_isError(ZSTD_initDStream(dstream)));
66     } else {
67         FUZZ_ASSERT(!ZSTD_isError(ZSTD_resetDStream(dstream)));
68     }
69
70     while (size > 0) {
71         ZSTD_inBuffer in = makeInBuffer(&src, &size);
72         while (in.pos != in.size) {
73             ZSTD_outBuffer out = makeOutBuffer();
74             size_t const rc = ZSTD_decompressStream(dstream, &out, &in);
75             if (ZSTD_isError(rc)) goto error;
76             if (rc == 0) FUZZ_ASSERT(!ZSTD_isError(ZSTD_resetDStream(dstream)));
77         }
78     }
79
80 error:
81 #ifndef STATEFULL_FUZZING
82     ZSTD_freeDStream(dstream); dstream = NULL;
83 #endif
84     return 0;
85 }