1 // Copyright 2024 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <string>
6 #include <vector>
7
8 #include "testing/libfuzzer/confirm_fuzztest_init_buildflags.h"
9 #include "testing/libfuzzer/fuzztest_init_helper.h"
10 #include "third_party/fuzztest/src/fuzztest/init_fuzztest.h"
11
12 // We can't depend on //base, hence not using compiler_specific.h - copied
13 // from there
14 #if defined(__clang__)
15 // clang-format off
16 #define UNSAFE_BUFFERS(...) \
17 _Pragma("clang unsafe_buffer_usage begin") \
18 __VA_ARGS__ \
19 _Pragma("clang unsafe_buffer_usage end")
20 // clang-format on
21 #else
22 #define UNSAFE_BUFFERS(...) __VA_ARGS__
23 #endif
24
25 namespace {
26
RealInitFunction(int argc,char ** argv)27 static void RealInitFunction(int argc, char** argv) {
28 static std::vector<std::string> fuzztest_argv_strings;
29 static std::vector<char*> fuzztest_argv_data;
30 static int fuzztest_argc;
31 static char** fuzztest_argv;
32 // Fuzztest might refer to the command line later, by which time Chromium
33 // may have altered it. Keep our own copy so that the data
34 // we pass into fuzztest remains valid, no matter what Chromium code
35 // does to the original.
36 fuzztest_argv_strings.reserve(argc);
37 fuzztest_argv_data.reserve(argc);
38 for (int i = 0; i < argc; i++) {
39 // SAFETY: this function relies upon paired argc and argv
40 // per command-line norms. Spanification of this family
41 // of functions has been attempted, but because the
42 // provider and consumer of the data both work in terms of
43 // old-fashioned argc/argv pairs, it seemed to introduce
44 // more complexity than it eliminated.
45 UNSAFE_BUFFERS(fuzztest_argv_strings.push_back(argv[i]));
46 fuzztest_argv_data.push_back(fuzztest_argv_strings.back().data());
47 }
48 fuzztest_argc = argc;
49 fuzztest_argv = fuzztest_argv_data.data();
50 fuzztest::ParseAbslFlags(fuzztest_argc, fuzztest_argv);
51 #if BUILDFLAG(REGISTER_FUZZTESTS_IN_TEST_SUITES)
52 fuzztest::InitFuzzTest(&fuzztest_argc, &fuzztest_argv);
53 #endif
54 }
55
56 // This code is called from the generic initialization code of any
57 // unit test suite. Such code is used in test suites containing fuzztests
58 // and those without. In those without, we want to avoid depending
59 // on fuzztest's complex dependencies, but on those with fuzztests
60 // we need to call InitFuzzTest. So, use a static initializer to fill
61 // in a function pointer in those cases.
62 class FuzztestInitializer {
63 public:
FuzztestInitializer()64 FuzztestInitializer() {
65 fuzztest_init_helper::initialization_function = RealInitFunction;
66 }
67 };
68
69 FuzztestInitializer static_initializer; // NOLINT
70
71 } // namespace
72