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