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