1 // Copyright 2015 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 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
7 #pragma allow_unsafe_buffers
8 #endif
9
10 // A simple unit-test style driver for libfuzzer tests.
11 // Usage: <fuzzer_test> <file>...
12
13 #include <stddef.h>
14 #include <stdint.h>
15
16 #include <fstream>
17 #include <iostream>
18 #include <iterator>
19 #include <vector>
20
21 // Libfuzzer API.
22 extern "C" {
23 // User function.
24 int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
25 // Initialization function.
26 __attribute__((weak)) int LLVMFuzzerInitialize(int *argc, char ***argv);
27 // Mutation function provided by libFuzzer.
28 size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize);
29 }
30
readFile(std::string path)31 std::vector<uint8_t> readFile(std::string path) {
32 std::ifstream in(path);
33 return std::vector<uint8_t>((std::istreambuf_iterator<char>(in)),
34 std::istreambuf_iterator<char>());
35 }
36
LLVMFuzzerMutate(uint8_t * Data,size_t Size,size_t MaxSize)37 size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
38 return 0;
39 }
40
main(int argc,char ** argv)41 int main(int argc, char **argv) {
42 if (argc == 1) {
43 std::cerr
44 << "Usage: " << argv[0]
45 << " <file>...\n"
46 "\n"
47 "Alternatively, try building this target with "
48 "use_libfuzzer=true for a better test driver. For details see:\n"
49 "\n"
50 "https://chromium.googlesource.com/chromium/src/+/main/"
51 "testing/libfuzzer/getting_started.md"
52 << std::endl;
53 exit(1);
54 }
55
56 if (LLVMFuzzerInitialize)
57 LLVMFuzzerInitialize(&argc, &argv);
58
59 for (int i = 1; i < argc; ++i) {
60 std::cout << argv[i] << std::endl;
61 auto v = readFile(argv[i]);
62 LLVMFuzzerTestOneInput(v.data(), v.size());
63 }
64 }
65