1 /* 2 * Copyright (c) Meta Platforms, Inc. and affiliates. 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 * You may select, at your option, one of the above-listed licenses. 9 */ 10 11 /** 12 * This fuzz target attempts to decompress the fuzzed data with the simple 13 * decompression function to ensure the decompressor never crashes. 14 */ 15 16 #include <stddef.h> 17 #include <stdlib.h> 18 #include <stdio.h> 19 20 #define ZSTD_STATIC_LINKING_ONLY 21 22 #include "fuzz_helpers.h" 23 #include "zstd.h" 24 #include "fuzz_data_producer.h" 25 26 static ZSTD_DCtx *dctx = NULL; 27 28 int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) 29 { 30 /* Give a random portion of src data to the producer, to use for 31 parameter generation. The rest will be used for (de)compression */ 32 FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size); 33 size = FUZZ_dataProducer_reserveDataPrefix(producer); 34 35 if (!dctx) { 36 dctx = ZSTD_createDCtx(); 37 FUZZ_ASSERT(dctx); 38 } 39 40 { 41 size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size); 42 void *rBuf = FUZZ_malloc(bufSize); 43 size_t const dSize = ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size); 44 if (!ZSTD_isError(dSize)) { 45 /* If decompression was successful, the content size from the frame header(s) should be valid. */ 46 unsigned long long const expectedSize = ZSTD_findDecompressedSize(src, size); 47 FUZZ_ASSERT(expectedSize != ZSTD_CONTENTSIZE_ERROR); 48 FUZZ_ASSERT(expectedSize == ZSTD_CONTENTSIZE_UNKNOWN || expectedSize == dSize); 49 } 50 free(rBuf); 51 } 52 53 FUZZ_dataProducer_free(producer); 54 55 #ifndef STATEFUL_FUZZING 56 ZSTD_freeDCtx(dctx); dctx = NULL; 57 #endif 58 return 0; 59 } 60