Bitcoin Core 28.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>
8#include <test/fuzz/fuzz.h>
9#include <test/fuzz/util.h>
10
11#include <array>
12#include <cstddef>
13#include <cstdint>
14#include <iostream>
15#include <optional>
16#include <vector>
17
18FUZZ_TARGET(buffered_file)
19{
20 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
21 FuzzedFileProvider fuzzed_file_provider{fuzzed_data_provider};
22 std::optional<BufferedFile> opt_buffered_file;
23 AutoFile fuzzed_file{
24 fuzzed_file_provider.open(),
25 ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider),
26 };
27 try {
28 auto n_buf_size = fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(0, 4096);
29 auto n_rewind_in = fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(0, 4096);
30 opt_buffered_file.emplace(fuzzed_file, n_buf_size, n_rewind_in);
31 } catch (const std::ios_base::failure&) {
32 }
33 if (opt_buffered_file && !fuzzed_file.IsNull()) {
34 bool setpos_fail = false;
35 LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100)
36 {
38 fuzzed_data_provider,
39 [&] {
40 std::array<std::byte, 4096> arr{};
41 try {
42 opt_buffered_file->read({arr.data(), fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096)});
43 } catch (const std::ios_base::failure&) {
44 }
45 },
46 [&] {
47 opt_buffered_file->SetLimit(fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(0, 4096));
48 },
49 [&] {
50 if (!opt_buffered_file->SetPos(fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(0, 4096))) {
51 setpos_fail = true;
52 }
53 },
54 [&] {
55 if (setpos_fail) {
56 // Calling FindByte(...) after a failed SetPos(...) call may result in an infinite loop.
57 return;
58 }
59 try {
60 opt_buffered_file->FindByte(std::byte(fuzzed_data_provider.ConsumeIntegral<uint8_t>()));
61 } catch (const std::ios_base::failure&) {
62 }
63 },
64 [&] {
65 ReadFromStream(fuzzed_data_provider, *opt_buffered_file);
66 });
67 }
68 opt_buffered_file->GetPos();
69 }
70}
void ReadFromStream(AddrMan &addr, DataStream &ssPeers)
Only used by tests.
Definition: addrdb.cpp:186
FUZZ_TARGET(buffered_file)
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:392
#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