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