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