xref: /netbsd-src/external/bsd/zstd/dist/tests/fuzz/block_decompress.c (revision 3117ece4fc4a4ca4489ba793710b60b0d26bab6c)
1*3117ece4Schristos /**
2*3117ece4Schristos  * Copyright (c) Meta Platforms, Inc. and affiliates.
3*3117ece4Schristos  * All rights reserved.
4*3117ece4Schristos  *
5*3117ece4Schristos  * This source code is licensed under both the BSD-style license (found in the
6*3117ece4Schristos  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7*3117ece4Schristos  * in the COPYING file in the root directory of this source tree).
8*3117ece4Schristos  * You may select, at your option, one of the above-listed licenses.
9*3117ece4Schristos  */
10*3117ece4Schristos 
11*3117ece4Schristos /**
12*3117ece4Schristos  * This fuzz target attempts to decompress the fuzzed data with the simple
13*3117ece4Schristos  * decompression function to ensure the decompressor never crashes.
14*3117ece4Schristos  */
15*3117ece4Schristos 
16*3117ece4Schristos #include "fuzz_data_producer.h"
17*3117ece4Schristos #define ZSTD_STATIC_LINKING_ONLY
18*3117ece4Schristos 
19*3117ece4Schristos #include <stddef.h>
20*3117ece4Schristos #include <stdlib.h>
21*3117ece4Schristos #include <stdio.h>
22*3117ece4Schristos #include "fuzz_helpers.h"
23*3117ece4Schristos #include "zstd.h"
24*3117ece4Schristos 
25*3117ece4Schristos static ZSTD_DCtx *dctx = NULL;
26*3117ece4Schristos static void* rBuf = NULL;
27*3117ece4Schristos static size_t bufSize = 0;
28*3117ece4Schristos 
29*3117ece4Schristos int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
30*3117ece4Schristos {
31*3117ece4Schristos     size_t const neededBufSize = ZSTD_BLOCKSIZE_MAX;
32*3117ece4Schristos     FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size);
33*3117ece4Schristos 
34*3117ece4Schristos     /* Allocate all buffers and contexts if not already allocated */
35*3117ece4Schristos     if (neededBufSize > bufSize) {
36*3117ece4Schristos         free(rBuf);
37*3117ece4Schristos         rBuf = FUZZ_malloc_rand(neededBufSize, producer);
38*3117ece4Schristos         bufSize = neededBufSize;
39*3117ece4Schristos     }
40*3117ece4Schristos     if (!dctx) {
41*3117ece4Schristos         dctx = ZSTD_createDCtx();
42*3117ece4Schristos         FUZZ_ASSERT(dctx);
43*3117ece4Schristos     }
44*3117ece4Schristos     ZSTD_decompressBegin(dctx);
45*3117ece4Schristos     ZSTD_decompressBlock(dctx, rBuf, neededBufSize, src, size);
46*3117ece4Schristos 
47*3117ece4Schristos     FUZZ_dataProducer_free(producer);
48*3117ece4Schristos 
49*3117ece4Schristos #ifndef STATEFUL_FUZZING
50*3117ece4Schristos     ZSTD_freeDCtx(dctx); dctx = NULL;
51*3117ece4Schristos #endif
52*3117ece4Schristos     return 0;
53*3117ece4Schristos }
54