/ src / test / fuzz / autofile.cpp
autofile.cpp
 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/FuzzedDataProvider.h>
 8  #include <test/fuzz/fuzz.h>
 9  #include <test/fuzz/util.h>
10  
11  #include <array>
12  #include <cstddef>
13  #include <cstdio>
14  #include <iostream>
15  #include <vector>
16  
17  FUZZ_TARGET(autofile)
18  {
19      FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
20      FuzzedFileProvider fuzzed_file_provider{fuzzed_data_provider};
21      AutoFile auto_file{
22          fuzzed_file_provider.open(),
23          ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider),
24      };
25      LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100)
26      {
27          CallOneOf(
28              fuzzed_data_provider,
29              [&] {
30                  std::array<std::byte, 4096> arr{};
31                  try {
32                      auto_file.read({arr.data(), fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096)});
33                  } catch (const std::ios_base::failure&) {
34                  }
35              },
36              [&] {
37                  const std::array<std::byte, 4096> arr{};
38                  try {
39                      auto_file.write({arr.data(), fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096)});
40                  } catch (const std::ios_base::failure&) {
41                  }
42              },
43              [&] {
44                  try {
45                      auto_file.ignore(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096));
46                  } catch (const std::ios_base::failure&) {
47                  }
48              },
49              [&] {
50                  auto_file.fclose();
51              },
52              [&] {
53                  ReadFromStream(fuzzed_data_provider, auto_file);
54              },
55              [&] {
56                  WriteToStream(fuzzed_data_provider, auto_file);
57              });
58      }
59      (void)auto_file.Get();
60      (void)auto_file.IsNull();
61      if (fuzzed_data_provider.ConsumeBool()) {
62          FILE* f = auto_file.release();
63          if (f != nullptr) {
64              fclose(f);
65          }
66      }
67  }