Bitcoin Core 28.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 <test/util/random.h>
12#include <util/check.h>
13#include <util/fs.h>
14#include <util/sock.h>
15#include <util/time.h>
16
17#include <csignal>
18#include <cstdint>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <exception>
23#include <fstream>
24#include <functional>
25#include <iostream>
26#include <map>
27#include <memory>
28#include <string>
29#include <tuple>
30#include <utility>
31#include <vector>
32
33#if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && defined(__AFL_FUZZ_INIT)
34__AFL_FUZZ_INIT();
35#endif
36
37const std::function<void(const std::string&)> G_TEST_LOG_FUN{};
38
46static std::vector<const char*> g_args;
47
48static 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_corpora/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
58const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUMENTS = []() {
59 return g_args;
60};
61
62struct FuzzTarget {
65};
66
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 Apple-Clang-16 ? */ {std::move(target), std::move(opts)})};
76 Assert(ins);
77}
78
79static std::string_view g_fuzz_target;
80static const TypeTestOneInput* g_test_one_input{nullptr};
81
82inline void test_one_input(FuzzBufferType buffer)
83{
84 CheckGlobals check{};
85 (*Assert(g_test_one_input))(buffer);
86}
87
88const std::function<std::string()> G_TEST_GET_FULL_NAME{[]{
89 return std::string{g_fuzz_target};
90}};
91
92#if defined(__clang__) && defined(__linux__)
93extern "C" void __llvm_profile_reset_counters(void) __attribute__((weak));
94extern "C" void __gcov_reset(void) __attribute__((weak));
95
97{
98 if (__llvm_profile_reset_counters) {
99 __llvm_profile_reset_counters();
100 }
101
102 if (__gcov_reset) {
103 __gcov_reset();
104 }
105}
106#else
108#endif
109
110
112{
113 // By default, make the RNG deterministic with a fixed seed. This will affect all
114 // randomness during the fuzz test, except:
115 // - GetStrongRandBytes(), which is used for the creation of private key material.
116 // - Creating a BasicTestingSetup or derived class will switch to a random seed.
118
119 // Terminate immediately if a fuzzing harness ever tries to create a socket.
120 // Individual tests can override this by pointing CreateSock to a mocked alternative.
121 CreateSock = [](int, int, int) -> std::unique_ptr<Sock> { std::terminate(); };
122
123 // Terminate immediately if a fuzzing harness ever tries to perform a DNS lookup.
124 g_dns_lookup = [](const std::string& name, bool allow_lookup) {
125 if (allow_lookup) {
126 std::terminate();
127 }
128 return WrappedGetAddrInfo(name, false);
129 };
130
131 bool should_exit{false};
132 if (std::getenv("PRINT_ALL_FUZZ_TARGETS_AND_ABORT")) {
133 for (const auto& [name, t] : FuzzTargets()) {
134 if (t.opts.hidden) continue;
135 std::cout << name << std::endl;
136 }
137 should_exit = true;
138 }
139 if (const char* out_path = std::getenv("WRITE_ALL_FUZZ_TARGETS_AND_ABORT")) {
140 std::cout << "Writing all fuzz target names to '" << out_path << "'." << std::endl;
141 std::ofstream out_stream{out_path, std::ios::binary};
142 for (const auto& [name, t] : FuzzTargets()) {
143 if (t.opts.hidden) continue;
144 out_stream << name << std::endl;
145 }
146 should_exit = true;
147 }
148 if (should_exit) {
149 std::exit(EXIT_SUCCESS);
150 }
151 if (const auto* env_fuzz{std::getenv("FUZZ")}) {
152 // To allow for easier fuzz executable binary modification,
153 static std::string g_copy{env_fuzz}; // create copy to avoid compiler optimizations, and
154 g_fuzz_target = g_copy.c_str(); // strip string after the first null-char.
155 } else {
156 std::cerr << "Must select fuzz target with the FUZZ env var." << std::endl;
157 std::cerr << "Hint: Set the PRINT_ALL_FUZZ_TARGETS_AND_ABORT=1 env var to see all compiled targets." << std::endl;
158 std::exit(EXIT_FAILURE);
159 }
160 const auto it = FuzzTargets().find(g_fuzz_target);
161 if (it == FuzzTargets().end()) {
162 std::cerr << "No fuzz target compiled for " << g_fuzz_target << "." << std::endl;
163 std::exit(EXIT_FAILURE);
164 }
165 if constexpr (!G_FUZZING) {
166 std::cerr << "Must compile with -DBUILD_FOR_FUZZING=ON to execute a fuzz target." << std::endl;
167 std::exit(EXIT_FAILURE);
168 }
170 g_test_one_input = &it->second.test_one_input;
171 it->second.opts.init();
172
174}
175
176#if defined(PROVIDE_FUZZ_MAIN_FUNCTION)
177static bool read_stdin(std::vector<uint8_t>& data)
178{
179 std::istream::char_type buffer[1024];
180 std::streamsize length;
181 while ((std::cin.read(buffer, 1024), length = std::cin.gcount()) > 0) {
182 data.insert(data.end(), buffer, buffer + length);
183 }
184 return length == 0;
185}
186#endif
187
188#if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && !defined(__AFL_LOOP)
189static bool read_file(fs::path p, std::vector<uint8_t>& data)
190{
191 uint8_t buffer[1024];
192 FILE* f = fsbridge::fopen(p, "rb");
193 if (f == nullptr) return false;
194 do {
195 const size_t length = fread(buffer, sizeof(uint8_t), sizeof(buffer), f);
196 if (ferror(f)) return false;
197 data.insert(data.end(), buffer, buffer + length);
198 } while (!feof(f));
199 fclose(f);
200 return true;
201}
202#endif
203
204#if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && !defined(__AFL_LOOP)
205static fs::path g_input_path;
206void signal_handler(int signal)
207{
208 if (signal == SIGABRT) {
209 std::cerr << "Error processing input " << g_input_path << std::endl;
210 } else {
211 std::cerr << "Unexpected signal " << signal << " received\n";
212 }
213 std::_Exit(EXIT_FAILURE);
214}
215#endif
216
217// This function is used by libFuzzer
218extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
219{
220 test_one_input({data, size});
221 return 0;
222}
223
224// This function is used by libFuzzer
225extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv)
226{
227 SetArgs(*argc, *argv);
228 initialize();
229 return 0;
230}
231
232#if defined(PROVIDE_FUZZ_MAIN_FUNCTION)
233int main(int argc, char** argv)
234{
235 initialize();
236#ifdef __AFL_LOOP
237 // Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
238 // See fuzzing.md for details.
239 const uint8_t* buffer = __AFL_FUZZ_TESTCASE_BUF;
240 while (__AFL_LOOP(100000)) {
241 size_t buffer_len = __AFL_FUZZ_TESTCASE_LEN;
242 test_one_input({buffer, buffer_len});
243 }
244#else
245 std::vector<uint8_t> buffer;
246 if (argc <= 1) {
247 if (!read_stdin(buffer)) {
248 return 0;
249 }
250 test_one_input(buffer);
251 return 0;
252 }
253 std::signal(SIGABRT, signal_handler);
254 const auto start_time{Now<SteadySeconds>()};
255 int tested = 0;
256 for (int i = 1; i < argc; ++i) {
257 fs::path input_path(*(argv + i));
258 if (fs::is_directory(input_path)) {
259 for (fs::directory_iterator it(input_path); it != fs::directory_iterator(); ++it) {
260 if (!fs::is_regular_file(it->path())) continue;
261 g_input_path = it->path();
262 Assert(read_file(it->path(), buffer));
263 test_one_input(buffer);
264 ++tested;
265 buffer.clear();
266 }
267 } else {
268 g_input_path = input_path;
269 Assert(read_file(input_path, buffer));
270 test_one_input(buffer);
271 ++tested;
272 buffer.clear();
273 }
274 }
275 const auto end_time{Now<SteadySeconds>()};
276 std::cout << g_fuzz_target << ": succeeded against " << tested << " files in " << count_seconds(end_time - start_time) << "s." << std::endl;
277#endif
278 return 0;
279}
280#endif
int main(int argc, char **argv)
return EXIT_SUCCESS
constexpr bool G_FUZZING
Definition: check.h:16
#define Assert(val)
Identity function.
Definition: check.h:85
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:111
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:37
static const TypeTestOneInput * g_test_one_input
Definition: fuzz.cpp:80
static void SetArgs(int argc, char **argv)
Definition: fuzz.cpp:48
const std::function< std::vector< const char * >()> G_TEST_COMMAND_LINE_ARGUMENTS
Retrieve the command line arguments.
Definition: fuzz.cpp:58
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
Definition: fuzz.cpp:218
int LLVMFuzzerInitialize(int *argc, char ***argv)
Definition: fuzz.cpp:225
static std::string_view g_fuzz_target
Definition: fuzz.cpp:79
void ResetCoverageCounters()
Definition: fuzz.cpp:107
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::string()> G_TEST_GET_FULL_NAME
Retrieve the unit test name.
Definition: fuzz.cpp:88
void test_one_input(FuzzBufferType buffer)
Definition: fuzz.cpp:82
std::span< const uint8_t > FuzzBufferType
Definition: fuzz.h:25
std::function< void(FuzzBufferType)> TypeTestOneInput
Definition: fuzz.h:27
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:26
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
Definition: netbase.cpp:557
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:98
const char * name
Definition: rest.cpp:49
const TypeTestOneInput test_one_input
Definition: fuzz.cpp:63
const FuzzTargetOptions opts
Definition: fuzz.cpp:64
void SeedRandomStateForTest(SeedRand seedtype)
Seed the global RNG state for testing and log the seed value.
Definition: random.cpp:19
@ ZEROS
Seed with a compile time constant of zeros.
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:56