| 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 a valid compressed frame into |
| 13 | * an output buffer that is too small to ensure we always get |
| 14 | * ZSTD_error_dstSize_tooSmall. |
| 15 | */ |
| 16 | |
| 17 | #include <stddef.h> |
| 18 | #include <stdlib.h> |
| 19 | #include <stdio.h> |
| 20 | #include "fuzz_helpers.h" |
| 21 | #include "zstd.h" |
| 22 | #include "zstd_errors.h" |
| 23 | #include "zstd_helpers.h" |
| 24 | #include "fuzz_data_producer.h" |
| 25 | #include "fuzz_third_party_seq_prod.h" |
| 26 | |
| 27 | static ZSTD_CCtx *cctx = NULL; |
| 28 | static ZSTD_DCtx *dctx = NULL; |
| 29 | |
| 30 | int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) |
| 31 | { |
| 32 | FUZZ_SEQ_PROD_SETUP(); |
| 33 | |
| 34 | /* Give a random portion of src data to the producer, to use for |
| 35 | parameter generation. The rest will be used for (de)compression */ |
| 36 | FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size); |
| 37 | size_t rBufSize = FUZZ_dataProducer_uint32Range(producer, 0, size); |
| 38 | size = FUZZ_dataProducer_remainingBytes(producer); |
| 39 | /* Ensure the round-trip buffer is too small. */ |
| 40 | if (rBufSize >= size) { |
| 41 | rBufSize = size > 0 ? size - 1 : 0; |
| 42 | } |
| 43 | size_t const cBufSize = ZSTD_compressBound(size); |
| 44 | |
| 45 | if (!cctx) { |
| 46 | cctx = ZSTD_createCCtx(); |
| 47 | FUZZ_ASSERT(cctx); |
| 48 | } |
| 49 | if (!dctx) { |
| 50 | dctx = ZSTD_createDCtx(); |
| 51 | FUZZ_ASSERT(dctx); |
| 52 | } |
| 53 | |
| 54 | void *cBuf = FUZZ_malloc(cBufSize); |
| 55 | void *rBuf = FUZZ_malloc(rBufSize); |
| 56 | size_t const cSize = ZSTD_compressCCtx(cctx, cBuf, cBufSize, src, size, 1); |
| 57 | FUZZ_ZASSERT(cSize); |
| 58 | size_t const rSize = ZSTD_decompressDCtx(dctx, rBuf, rBufSize, cBuf, cSize); |
| 59 | if (size == 0) { |
| 60 | FUZZ_ASSERT(rSize == 0); |
| 61 | } else { |
| 62 | FUZZ_ASSERT(ZSTD_isError(rSize)); |
| 63 | FUZZ_ASSERT(ZSTD_getErrorCode(rSize) == ZSTD_error_dstSize_tooSmall); |
| 64 | } |
| 65 | free(cBuf); |
| 66 | free(rBuf); |
| 67 | FUZZ_dataProducer_free(producer); |
| 68 | #ifndef STATEFUL_FUZZING |
| 69 | ZSTD_freeCCtx(cctx); cctx = NULL; |
| 70 | ZSTD_freeDCtx(dctx); dctx = NULL; |
| 71 | #endif |
| 72 | FUZZ_SEQ_PROD_TEARDOWN(); |
| 73 | return 0; |
| 74 | } |