Branch data Line data Source code
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>
9 : : #include <test/fuzz/util/check_globals.h>
10 : : #include <test/util/coverage.h>
11 : : #include <test/util/random.h>
12 : : #include <test/util/setup_common.h>
13 : : #include <util/check.h>
14 : : #include <util/fs.h>
15 : : #include <util/sock.h>
16 : : #include <util/time.h>
17 : :
18 : : #include <algorithm>
19 : : #include <csignal>
20 : : #include <cstdint>
21 : : #include <cstdio>
22 : : #include <cstdlib>
23 : : #include <cstring>
24 : : #include <exception>
25 : : #include <fstream>
26 : : #include <functional>
27 : : #include <iostream>
28 : : #include <map>
29 : : #include <memory>
30 : : #include <random>
31 : : #include <string>
32 : : #include <tuple>
33 : : #include <utility>
34 : : #include <vector>
35 : :
36 : : #if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && defined(__AFL_FUZZ_INIT)
37 : : __AFL_FUZZ_INIT();
38 : : #endif
39 : :
40 : : const std::function<void(const std::string&)> G_TEST_LOG_FUN{};
41 : :
42 : : /**
43 : : * A copy of the command line arguments that start with `--`.
44 : : * First `LLVMFuzzerInitialize()` is called, which saves the arguments to `g_args`.
45 : : * Later, depending on the fuzz test, `G_TEST_COMMAND_LINE_ARGUMENTS()` may be
46 : : * called by `BasicTestingSetup` constructor to fetch those arguments and store
47 : : * them in `BasicTestingSetup::m_node::args`.
48 : : */
49 : : static std::vector<const char*> g_args;
50 : :
51 : 0 : static void SetArgs(int argc, char** argv) {
52 [ # # ]: 0 : for (int i = 1; i < argc; ++i) {
53 : : // Only take into account arguments that start with `--`. The others are for the fuzz engine:
54 : : // `fuzz -runs=1 fuzz_corpora/address_deserialize_v2 --checkaddrman=5`
55 [ # # # # : 0 : if (strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == '-') {
# # ]
56 : 0 : g_args.push_back(argv[i]);
57 : : }
58 : : }
59 : 0 : }
60 : :
61 : 901 : const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUMENTS = []() {
62 : 901 : return g_args;
63 : : };
64 : :
65 : 98568 : struct FuzzTarget {
66 : : const TypeTestOneInput test_one_input;
67 : : const FuzzTargetOptions opts;
68 : : };
69 : :
70 : 49727 : auto& FuzzTargets()
71 : : {
72 [ + + + - ]: 49948 : static std::map<std::string_view, FuzzTarget> g_fuzz_targets;
73 : 49727 : return g_fuzz_targets;
74 : : }
75 : :
76 : 49284 : void FuzzFrameworkRegisterTarget(std::string_view name, TypeTestOneInput target, FuzzTargetOptions opts)
77 : : {
78 [ + - ]: 98568 : const auto [it, ins]{FuzzTargets().try_emplace(name, FuzzTarget /* temporary can be dropped after Apple-Clang-16 ? */ {std::move(target), std::move(opts)})};
79 : 49284 : Assert(ins);
80 : 49284 : }
81 : :
82 : : static std::string_view g_fuzz_target;
83 : : static const TypeTestOneInput* g_test_one_input{nullptr};
84 : :
85 : 120379 : static void test_one_input(FuzzBufferType buffer)
86 : : {
87 : 120379 : CheckGlobals check{};
88 [ + - + - ]: 120379 : (*Assert(g_test_one_input))(buffer);
89 : 120379 : }
90 : :
91 : 901 : const std::function<std::string()> G_TEST_GET_FULL_NAME{[]{
92 : 901 : return std::string{g_fuzz_target};
93 : : }};
94 : :
95 : 222 : static void initialize()
96 : : {
97 : : // By default, make the RNG deterministic with a fixed seed. This will affect all
98 : : // randomness during the fuzz test, except:
99 : : // - GetStrongRandBytes(), which is used for the creation of private key material.
100 : : // - Randomness obtained before this call in g_rng_temp_path_init
101 : 222 : SeedRandomStateForTest(SeedRand::ZEROS);
102 : :
103 : : // Set time to the genesis block timestamp for deterministic initialization.
104 : 222 : SetMockTime(1231006505);
105 : :
106 : : // Terminate immediately if a fuzzing harness ever tries to create a socket.
107 : : // Individual tests can override this by pointing CreateSock to a mocked alternative.
108 : 222 : CreateSock = [](int, int, int) -> std::unique_ptr<Sock> { std::terminate(); };
109 : :
110 : : // Terminate immediately if a fuzzing harness ever tries to perform a DNS lookup.
111 : 364771 : g_dns_lookup = [](const std::string& name, bool allow_lookup) {
112 [ - + ]: 364549 : if (allow_lookup) {
113 : 0 : std::terminate();
114 : : }
115 : 364549 : return WrappedGetAddrInfo(name, false);
116 : 222 : };
117 : :
118 : 222 : bool should_exit{false};
119 [ + + ]: 222 : if (std::getenv("PRINT_ALL_FUZZ_TARGETS_AND_ABORT")) {
120 [ + + + + ]: 223 : for (const auto& [name, t] : FuzzTargets()) {
121 [ + + ]: 222 : if (t.opts.hidden) continue;
122 : 221 : std::cout << name << std::endl;
123 : : }
124 : : should_exit = true;
125 : : }
126 [ - + ]: 222 : if (const char* out_path = std::getenv("WRITE_ALL_FUZZ_TARGETS_AND_ABORT")) {
127 : 0 : std::cout << "Writing all fuzz target names to '" << out_path << "'." << std::endl;
128 : 0 : std::ofstream out_stream{out_path, std::ios::binary};
129 [ # # # # : 0 : for (const auto& [name, t] : FuzzTargets()) {
# # ]
130 [ # # ]: 0 : if (t.opts.hidden) continue;
131 [ # # # # ]: 0 : out_stream << name << std::endl;
132 : : }
133 : 0 : should_exit = true;
134 : 0 : }
135 [ + + ]: 222 : if (should_exit) {
136 : 1 : std::exit(EXIT_SUCCESS);
137 : : }
138 [ + - ]: 221 : if (const auto* env_fuzz{std::getenv("FUZZ")}) {
139 : : // To allow for easier fuzz executable binary modification,
140 [ + - + - : 442 : static std::string g_copy{env_fuzz}; // create copy to avoid compiler optimizations, and
+ - ]
141 : 221 : g_fuzz_target = g_copy.c_str(); // strip string after the first null-char.
142 : : } else {
143 : 0 : std::cerr << "Must select fuzz target with the FUZZ env var." << std::endl;
144 : 0 : std::cerr << "Hint: Set the PRINT_ALL_FUZZ_TARGETS_AND_ABORT=1 env var to see all compiled targets." << std::endl;
145 : 0 : std::exit(EXIT_FAILURE);
146 : : }
147 : 221 : const auto it = FuzzTargets().find(g_fuzz_target);
148 [ - + ]: 221 : if (it == FuzzTargets().end()) {
149 : 0 : std::cerr << "No fuzz target compiled for " << g_fuzz_target << "." << std::endl;
150 : 0 : std::exit(EXIT_FAILURE);
151 : : }
152 : 221 : if constexpr (!G_FUZZING_BUILD && !G_ABORT_ON_FAILED_ASSUME) {
153 : : std::cerr << "Must compile with -DBUILD_FOR_FUZZING=ON or in Debug mode to execute a fuzz target." << std::endl;
154 : : std::exit(EXIT_FAILURE);
155 : : }
156 : 221 : if (!EnableFuzzDeterminism()) {
157 : : if (std::getenv("FUZZ_NONDETERMINISM")) {
158 : : std::cerr << "Warning: FUZZ_NONDETERMINISM env var set, results may be inconsistent with fuzz build" << std::endl;
159 : : } else {
160 : : g_enable_dynamic_fuzz_determinism = true;
161 : : assert(EnableFuzzDeterminism());
162 : : }
163 : : }
164 : 221 : Assert(!g_test_one_input);
165 : 221 : g_test_one_input = &it->second.test_one_input;
166 : 221 : it->second.opts.init();
167 : :
168 : 221 : ResetCoverageCounters();
169 : 221 : }
170 : :
171 : : #if defined(PROVIDE_FUZZ_MAIN_FUNCTION)
172 : 0 : static bool read_stdin(std::vector<uint8_t>& data)
173 : : {
174 : 0 : std::istream::char_type buffer[1024];
175 : 0 : std::streamsize length;
176 [ # # ]: 0 : while ((std::cin.read(buffer, 1024), length = std::cin.gcount()) > 0) {
177 : 0 : data.insert(data.end(), buffer, buffer + length);
178 : : }
179 : 0 : return length == 0;
180 : : }
181 : : #endif
182 : :
183 : : #if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && !defined(__AFL_LOOP)
184 : 120379 : static bool read_file(fs::path p, std::vector<uint8_t>& data)
185 : : {
186 : 120379 : uint8_t buffer[1024];
187 : 120379 : FILE* f = fsbridge::fopen(p, "rb");
188 [ + - ]: 120379 : if (f == nullptr) return false;
189 : 2508012 : do {
190 : 2508012 : const size_t length = fread(buffer, sizeof(uint8_t), sizeof(buffer), f);
191 [ + - ]: 2508012 : if (ferror(f)) return false;
192 : 2508012 : data.insert(data.end(), buffer, buffer + length);
193 [ + + ]: 2508012 : } while (!feof(f));
194 : 120379 : fclose(f);
195 : 120379 : return true;
196 : : }
197 : : #endif
198 : :
199 : : #if defined(PROVIDE_FUZZ_MAIN_FUNCTION) && !defined(__AFL_LOOP)
200 : : static fs::path g_input_path;
201 : 0 : void signal_handler(int signal)
202 : : {
203 [ # # ]: 0 : if (signal == SIGABRT) {
204 : 0 : std::cerr << "Error processing input " << g_input_path << std::endl;
205 : : } else {
206 : 0 : std::cerr << "Unexpected signal " << signal << " received\n";
207 : : }
208 : 0 : std::_Exit(EXIT_FAILURE);
209 : : }
210 : : #endif
211 : :
212 : : // This function is used by libFuzzer
213 : 0 : extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
214 : : {
215 : 0 : test_one_input({data, size});
216 : 0 : return 0;
217 : : }
218 : :
219 : : // This function is used by libFuzzer
220 : 0 : extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv)
221 : : {
222 : 0 : SetArgs(*argc, *argv);
223 : 0 : initialize();
224 : 0 : return 0;
225 : : }
226 : :
227 : : #if defined(PROVIDE_FUZZ_MAIN_FUNCTION)
228 : 222 : int main(int argc, char** argv)
229 : : {
230 : 222 : initialize();
231 : : #ifdef __AFL_LOOP
232 : : // Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
233 : : // See fuzzing.md for details.
234 : : const uint8_t* buffer = __AFL_FUZZ_TESTCASE_BUF;
235 : : while (__AFL_LOOP(100000)) {
236 : : size_t buffer_len = __AFL_FUZZ_TESTCASE_LEN;
237 : : test_one_input({buffer, buffer_len});
238 : : }
239 : : #else
240 : 221 : std::vector<uint8_t> buffer;
241 [ - + ]: 221 : if (argc <= 1) {
242 [ # # # # ]: 0 : if (!read_stdin(buffer)) {
243 : : return 0;
244 : : }
245 [ # # ]: 0 : test_one_input(buffer);
246 : : return 0;
247 : : }
248 : 221 : std::signal(SIGABRT, signal_handler);
249 : 221 : const auto start_time{Now<SteadySeconds>()};
250 : 221 : int tested = 0;
251 [ + + ]: 442 : for (int i = 1; i < argc; ++i) {
252 [ + - ]: 221 : fs::path input_path(*(argv + i));
253 [ + - + - ]: 221 : if (fs::is_directory(input_path)) {
254 : 221 : std::vector<fs::path> files;
255 [ + - + - : 120821 : for (fs::directory_iterator it(input_path); it != fs::directory_iterator(); ++it) {
+ + + + ]
256 [ + - - + ]: 120379 : if (!fs::is_regular_file(it->path())) continue;
257 [ + - ]: 120379 : files.emplace_back(it->path());
258 : 0 : }
259 [ + - ]: 442 : std::ranges::shuffle(files, std::mt19937{std::random_device{}()});
260 [ + + ]: 120600 : for (const auto& input_path : files) {
261 [ + - ]: 120379 : g_input_path = input_path;
262 [ + - + - : 120379 : Assert(read_file(input_path, buffer));
+ - ]
263 [ + - ]: 120379 : test_one_input(buffer);
264 : 120379 : ++tested;
265 [ + - ]: 240758 : buffer.clear();
266 : : }
267 : 221 : } else {
268 [ # # ]: 0 : g_input_path = input_path;
269 [ # # # # : 0 : Assert(read_file(input_path, buffer));
# # ]
270 [ # # ]: 0 : test_one_input(buffer);
271 : 0 : ++tested;
272 [ - - ]: 221 : buffer.clear();
273 : : }
274 : 221 : }
275 : 221 : const auto end_time{Now<SteadySeconds>()};
276 [ + - + - : 221 : 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 : 221 : }
280 : : #endif
|