Bitcoin Core 29.99.0
P2P Digital Currency
buffered_file.cpp
Go to the documentation of this file.
1// Copyright (c) 2020-2022 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <span.h>
6#include <streams.h>
7#include <test/fuzz/fuzz.h>
9#include <test/fuzz/util.h>
10#include <util/obfuscation.h>
11
12#include <array>
13#include <cstddef>
14#include <cstdint>
15#include <iostream>
16#include <optional>
17#include <vector>
18
19FUZZ_TARGET(buffered_file)
20{
21 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
22 FuzzedFileProvider fuzzed_file_provider{fuzzed_data_provider};
23 std::optional<BufferedFile> opt_buffered_file;
24 const auto key_bytes{ConsumeFixedLengthByteVector<std::byte>(fuzzed_data_provider, Obfuscation::KEY_SIZE)};
25 AutoFile fuzzed_file{
26 fuzzed_file_provider.open(),
27 Obfuscation{std::span{key_bytes}.first<Obfuscation::KEY_SIZE>()},
28 };
29 try {
30 auto n_buf_size = fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(0, 4096);
31 auto n_rewind_in = fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(0, 4096);
32 opt_buffered_file.emplace(fuzzed_file, n_buf_size, n_rewind_in);
33 } catch (const std::ios_base::failure&) {
34 }
35 if (opt_buffered_file && !fuzzed_file.IsNull()) {
36 bool setpos_fail = false;
37 LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100)
38 {
40 fuzzed_data_provider,
41 [&] {
42 std::array<std::byte, 4096> arr{};
43 try {
44 opt_buffered_file->read({arr.data(), fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096)});
45 } catch (const std::ios_base::failure&) {
46 }
47 },
48 [&] {
49 opt_buffered_file->SetLimit(fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(0, 4096));
50 },
51 [&] {
52 if (!opt_buffered_file->SetPos(fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(0, 4096))) {
53 setpos_fail = true;
54 }
55 },
56 [&] {
57 if (setpos_fail) {
58 // Calling FindByte(...) after a failed SetPos(...) call may result in an infinite loop.
59 return;
60 }
61 try {
62 opt_buffered_file->FindByte(std::byte(fuzzed_data_provider.ConsumeIntegral<uint8_t>()));
63 } catch (const std::ios_base::failure&) {
64 }
65 },
66 [&] {
67 ReadFromStream(fuzzed_data_provider, *opt_buffered_file);
68 });
69 }
70 opt_buffered_file->GetPos();
71 }
72}
void ReadFromStream(AddrMan &addr, DataStream &ssPeers)
Only used by tests.
Definition: addrdb.cpp:191
FUZZ_TARGET(buffered_file)
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:371
static constexpr size_t KEY_SIZE
Definition: obfuscation.h:23
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:22
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:35