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 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_MAX;
24
25 static ZSTD_DStream *dstream = NULL;
26 static void* buf = NULL;
27 uint32_t seed;
28
makeOutBuffer(void)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
makeInBuffer(const uint8_t ** src,size_t * size)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
LLVMFuzzerTestOneInput(const uint8_t * src,size_t size)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 } else {
66 FUZZ_ZASSERT(ZSTD_DCtx_reset(dstream, ZSTD_reset_session_only));
67 }
68
69 while (size > 0) {
70 ZSTD_inBuffer in = makeInBuffer(&src, &size);
71 while (in.pos != in.size) {
72 ZSTD_outBuffer out = makeOutBuffer();
73 size_t const rc = ZSTD_decompressStream(dstream, &out, &in);
74 if (ZSTD_isError(rc)) goto error;
75 }
76 }
77
78 error:
79 #ifndef STATEFUL_FUZZING
80 ZSTD_freeDStream(dstream); dstream = NULL;
81 #endif
82 return 0;
83 }
84