Bitcoin Core  27.99.0
P2P Digital Currency
fuzz.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-present 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 <test/fuzz/fuzz.h>
6 
7 #include <netaddress.h>
8 #include <netbase.h>
10 #include <util/check.h>
11 #include <util/fs.h>
12 #include <util/sock.h>
13 #include <util/time.h>
14 
15 #include <csignal>
16 #include <cstdint>
17 #include <cstdio>
18 #include <cstdlib>
19 #include <cstring>
20 #include <exception>
21 #include <fstream>
22 #include <functional>
23 #include <iostream>
24 #include <map>
25 #include <memory>
26 #include <string>
27 #include <tuple>
28 #include <utility>
29 #include <vector>
30 
31 #if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && defined(__AFL_FUZZ_INIT)
32 __AFL_FUZZ_INIT();
33 #endif
34 
35 const std::function<void(const std::string&)> G_TEST_LOG_FUN{};
36 
37 const std::function<std::string()> G_TEST_GET_FULL_NAME{};
38 
46 static std::vector<const char*> g_args;
47 
48 static void SetArgs(int argc, char** argv) {
49  for (int i = 1; i < argc; ++i) {
50  // Only take into account arguments that start with `--`. The others are for the fuzz engine:
51  // `fuzz -runs=1 fuzz_seed_corpus/address_deserialize_v2 --checkaddrman=5`
52  if (strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == '-') {
53  g_args.push_back(argv[i]);
54  }
55  }
56 }
57 
58 const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUMENTS = []() {
59  return g_args;
60 };
61 
62 struct FuzzTarget {
65 };
66 
67 auto& FuzzTargets()
68 {
69  static std::map<std::string_view, FuzzTarget> g_fuzz_targets;
70  return g_fuzz_targets;
71 }
72 
74 {
75  const auto it_ins{FuzzTargets().try_emplace(name, FuzzTarget /* temporary can be dropped after clang-16 */ {std::move(target), std::move(opts)})};
76  Assert(it_ins.second);
77 }
78 
79 static std::string_view g_fuzz_target;
80 static const TypeTestOneInput* g_test_one_input{nullptr};
81 
82 void initialize()
83 {
84  // Terminate immediately if a fuzzing harness ever tries to create a TCP socket.
85  CreateSock = [](const sa_family_t&) -> std::unique_ptr<Sock> { std::terminate(); };
86 
87  // Terminate immediately if a fuzzing harness ever tries to perform a DNS lookup.
88  g_dns_lookup = [](const std::string& name, bool allow_lookup) {
89  if (allow_lookup) {
90  std::terminate();
91  }
92  return WrappedGetAddrInfo(name, false);
93  };
94 
95  bool should_exit{false};
96  if (std::getenv("PRINT_ALL_FUZZ_TARGETS_AND_ABORT")) {
97  for (const auto& [name, t] : FuzzTargets()) {
98  if (t.opts.hidden) continue;
99  std::cout << name << std::endl;
100  }
101  should_exit = true;
102  }
103  if (const char* out_path = std::getenv("WRITE_ALL_FUZZ_TARGETS_AND_ABORT")) {
104  std::cout << "Writing all fuzz target names to '" << out_path << "'." << std::endl;
105  std::ofstream out_stream{out_path, std::ios::binary};
106  for (const auto& [name, t] : FuzzTargets()) {
107  if (t.opts.hidden) continue;
108  out_stream << name << std::endl;
109  }
110  should_exit = true;
111  }
112  if (should_exit) {
113  std::exit(EXIT_SUCCESS);
114  }
115  if (const auto* env_fuzz{std::getenv("FUZZ")}) {
116  // To allow for easier fuzz executable binary modification,
117  static std::string g_copy{env_fuzz}; // create copy to avoid compiler optimizations, and
118  g_fuzz_target = g_copy.c_str(); // strip string after the first null-char.
119  } else {
120  std::cerr << "Must select fuzz target with the FUZZ env var." << std::endl;
121  std::cerr << "Hint: Set the PRINT_ALL_FUZZ_TARGETS_AND_ABORT=1 env var to see all compiled targets." << std::endl;
122  std::exit(EXIT_FAILURE);
123  }
124  const auto it = FuzzTargets().find(g_fuzz_target);
125  if (it == FuzzTargets().end()) {
126  std::cerr << "No fuzz target compiled for " << g_fuzz_target << "." << std::endl;
127  std::exit(EXIT_FAILURE);
128  }
130  g_test_one_input = &it->second.test_one_input;
131  it->second.opts.init();
132 }
133 
134 #if defined(PROVIDE_FUZZ_MAIN_FUNCTION)
135 static bool read_stdin(std::vector<uint8_t>& data)
136 {
137  std::istream::char_type buffer[1024];
138  std::streamsize length;
139  while ((std::cin.read(buffer, 1024), length = std::cin.gcount()) > 0) {
140  data.insert(data.end(), buffer, buffer + length);
141  }
142  return length == 0;
143 }
144 #endif
145 
146 #if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && !defined(__AFL_LOOP)
147 static bool read_file(fs::path p, std::vector<uint8_t>& data)
148 {
149  uint8_t buffer[1024];
150  FILE* f = fsbridge::fopen(p, "rb");
151  if (f == nullptr) return false;
152  do {
153  const size_t length = fread(buffer, sizeof(uint8_t), sizeof(buffer), f);
154  if (ferror(f)) return false;
155  data.insert(data.end(), buffer, buffer + length);
156  } while (!feof(f));
157  fclose(f);
158  return true;
159 }
160 #endif
161 
162 #if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && !defined(__AFL_LOOP)
163 static fs::path g_input_path;
164 void signal_handler(int signal)
165 {
166  if (signal == SIGABRT) {
167  std::cerr << "Error processing input " << g_input_path << std::endl;
168  } else {
169  std::cerr << "Unexpected signal " << signal << " received\n";
170  }
171  std::_Exit(EXIT_FAILURE);
172 }
173 #endif
174 
175 // This function is used by libFuzzer
176 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
177 {
178  static const auto& test_one_input = *Assert(g_test_one_input);
179  test_one_input({data, size});
180  return 0;
181 }
182 
183 // This function is used by libFuzzer
184 extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv)
185 {
186  SetArgs(*argc, *argv);
187  initialize();
188  return 0;
189 }
190 
191 #if defined(PROVIDE_FUZZ_MAIN_FUNCTION)
192 int main(int argc, char** argv)
193 {
194  initialize();
195  static const auto& test_one_input = *Assert(g_test_one_input);
196 #ifdef __AFL_LOOP
197  // Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
198  // See fuzzing.md for details.
199  const uint8_t* buffer = __AFL_FUZZ_TESTCASE_BUF;
200  while (__AFL_LOOP(100000)) {
201  size_t buffer_len = __AFL_FUZZ_TESTCASE_LEN;
202  test_one_input({buffer, buffer_len});
203  }
204 #else
205  std::vector<uint8_t> buffer;
206  if (argc <= 1) {
207  if (!read_stdin(buffer)) {
208  return 0;
209  }
210  test_one_input(buffer);
211  return 0;
212  }
213  std::signal(SIGABRT, signal_handler);
214  const auto start_time{Now<SteadySeconds>()};
215  int tested = 0;
216  for (int i = 1; i < argc; ++i) {
217  fs::path input_path(*(argv + i));
218  if (fs::is_directory(input_path)) {
219  for (fs::directory_iterator it(input_path); it != fs::directory_iterator(); ++it) {
220  if (!fs::is_regular_file(it->path())) continue;
221  g_input_path = it->path();
222  Assert(read_file(it->path(), buffer));
223  test_one_input(buffer);
224  ++tested;
225  buffer.clear();
226  }
227  } else {
228  g_input_path = input_path;
229  Assert(read_file(input_path, buffer));
230  test_one_input(buffer);
231  ++tested;
232  buffer.clear();
233  }
234  }
235  const auto end_time{Now<SteadySeconds>()};
236  std::cout << g_fuzz_target << ": succeeded against " << tested << " files in " << count_seconds(end_time - start_time) << "s." << std::endl;
237 #endif
238  return 0;
239 }
240 #endif
int main(int argc, char **argv)
return EXIT_SUCCESS
#define Assert(val)
Identity function.
Definition: check.h:77
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
path(std::filesystem::path path)
Definition: fs.h:38
void initialize()
Definition: fuzz.cpp:82
auto & FuzzTargets()
Definition: fuzz.cpp:67
void FuzzFrameworkRegisterTarget(std::string_view name, TypeTestOneInput target, FuzzTargetOptions opts)
Definition: fuzz.cpp:73
const std::function< void(const std::string &)> G_TEST_LOG_FUN
This is connected to the logger.
Definition: fuzz.cpp:35
static const TypeTestOneInput * g_test_one_input
Definition: fuzz.cpp:80
static void SetArgs(int argc, char **argv)
Definition: fuzz.cpp:48
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
Definition: fuzz.cpp:176
int LLVMFuzzerInitialize(int *argc, char ***argv)
Definition: fuzz.cpp:184
static std::string_view g_fuzz_target
Definition: fuzz.cpp:79
static std::vector< const char * > g_args
A copy of the command line arguments that start with --.
Definition: fuzz.cpp:46
const std::function< std::vector< const char * >)> G_TEST_COMMAND_LINE_ARGUMENTS
Retrieve the command line arguments.
Definition: fuzz.cpp:58
const std::function< std::string()> G_TEST_GET_FULL_NAME
Retrieve the unit test name.
Definition: fuzz.cpp:37
std::function< void(FuzzBufferType)> TypeTestOneInput
Definition: fuzz.h:28
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:26
std::vector< CNetAddr > WrappedGetAddrInfo(const std::string &name, bool allow_lookup)
Wrapper for getaddrinfo(3).
Definition: netbase.cpp:43
DNSLookupFn g_dns_lookup
Definition: netbase.cpp:85
std::function< std::unique_ptr< Sock >const sa_family_t &)> CreateSock
Socket factory.
Definition: netbase.cpp:541
const char * name
Definition: rest.cpp:48
const TypeTestOneInput test_one_input
Definition: fuzz.cpp:63
const FuzzTargetOptions opts
Definition: fuzz.cpp:64
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:54