blob: 821d34cccc2bf906f000118609a8786625093920 [file] [log] [blame]
Kostya Serebryany016852c2015-02-19 18:45:37 +00001//===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// FuzzerDriver and flag parsing.
10//===----------------------------------------------------------------------===//
11
12#include "FuzzerInterface.h"
13#include "FuzzerInternal.h"
14
15#include <cstring>
Kostya Serebryany83fd4862015-05-11 21:31:51 +000016#include <chrono>
Kostya Serebryany016852c2015-02-19 18:45:37 +000017#include <unistd.h>
Kostya Serebryany016852c2015-02-19 18:45:37 +000018#include <thread>
19#include <atomic>
20#include <mutex>
Kostya Serebryany52a788e2015-03-31 20:13:20 +000021#include <string>
22#include <sstream>
23#include <algorithm>
24#include <iterator>
Kostya Serebryany016852c2015-02-19 18:45:37 +000025
26namespace fuzzer {
27
28// Program arguments.
29struct FlagDescription {
30 const char *Name;
31 const char *Description;
32 int Default;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000033 int *IntFlag;
34 const char **StrFlag;
Kostya Serebryany016852c2015-02-19 18:45:37 +000035};
36
37struct {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000038#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
39#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
Kostya Serebryany016852c2015-02-19 18:45:37 +000040#include "FuzzerFlags.def"
Kostya Serebryany52a788e2015-03-31 20:13:20 +000041#undef FUZZER_FLAG_INT
42#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000043} Flags;
44
Craig Topper26260942015-10-18 05:15:34 +000045static const FlagDescription FlagDescriptions [] {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000046#define FUZZER_FLAG_INT(Name, Default, Description) \
47 { #Name, Description, Default, &Flags.Name, nullptr},
48#define FUZZER_FLAG_STRING(Name, Description) \
49 { #Name, Description, 0, nullptr, &Flags.Name },
Kostya Serebryany016852c2015-02-19 18:45:37 +000050#include "FuzzerFlags.def"
Kostya Serebryany52a788e2015-03-31 20:13:20 +000051#undef FUZZER_FLAG_INT
52#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000053};
54
55static const size_t kNumFlags =
56 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
57
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000058static std::vector<std::string> *Inputs;
59static std::string *ProgName;
Kostya Serebryany016852c2015-02-19 18:45:37 +000060
61static void PrintHelp() {
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000062 Printf("Usage: %s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n",
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000063 ProgName->c_str());
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000064 Printf("\nFlags: (strictly in form -flag=value)\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000065 size_t MaxFlagLen = 0;
66 for (size_t F = 0; F < kNumFlags; F++)
67 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
68
69 for (size_t F = 0; F < kNumFlags; F++) {
70 const auto &D = FlagDescriptions[F];
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000071 Printf(" %s", D.Name);
Kostya Serebryany016852c2015-02-19 18:45:37 +000072 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000073 Printf(" ");
74 Printf("\t");
75 Printf("%d\t%s\n", D.Default, D.Description);
Kostya Serebryany016852c2015-02-19 18:45:37 +000076 }
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000077 Printf("\nFlags starting with '--' will be ignored and "
78 "will be passed verbatim to subprocesses.\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000079}
80
81static const char *FlagValue(const char *Param, const char *Name) {
82 size_t Len = strlen(Name);
83 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
84 Param[Len + 1] == '=')
85 return &Param[Len + 2];
86 return nullptr;
87}
88
89static bool ParseOneFlag(const char *Param) {
90 if (Param[0] != '-') return false;
Kostya Serebryany71e0feb2015-05-21 20:39:13 +000091 if (Param[1] == '-') {
92 static bool PrintedWarning = false;
93 if (!PrintedWarning) {
94 PrintedWarning = true;
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000095 Printf("WARNING: libFuzzer ignores flags that start with '--'\n");
Kostya Serebryany71e0feb2015-05-21 20:39:13 +000096 }
97 return true;
98 }
Kostya Serebryany016852c2015-02-19 18:45:37 +000099 for (size_t F = 0; F < kNumFlags; F++) {
100 const char *Name = FlagDescriptions[F].Name;
101 const char *Str = FlagValue(Param, Name);
102 if (Str) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000103 if (FlagDescriptions[F].IntFlag) {
104 int Val = std::stol(Str);
105 *FlagDescriptions[F].IntFlag = Val;
106 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000107 Printf("Flag: %s %d\n", Name, Val);;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000108 return true;
109 } else if (FlagDescriptions[F].StrFlag) {
110 *FlagDescriptions[F].StrFlag = Str;
111 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000112 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000113 return true;
114 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000115 }
116 }
117 PrintHelp();
118 exit(1);
119}
120
121// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000122static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000123 for (size_t F = 0; F < kNumFlags; F++) {
124 if (FlagDescriptions[F].IntFlag)
125 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
126 if (FlagDescriptions[F].StrFlag)
127 *FlagDescriptions[F].StrFlag = nullptr;
128 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000129 Inputs = new std::vector<std::string>;
130 for (size_t A = 1; A < Args.size(); A++) {
131 if (ParseOneFlag(Args[A].c_str())) continue;
132 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000133 }
134}
135
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000136static std::mutex Mu;
137
138static void PulseThread() {
139 while (true) {
140 std::this_thread::sleep_for(std::chrono::seconds(600));
141 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000142 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000143 }
144}
145
Kostya Serebryany016852c2015-02-19 18:45:37 +0000146static void WorkerThread(const std::string &Cmd, std::atomic<int> *Counter,
147 int NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000148 while (true) {
149 int C = (*Counter)++;
150 if (C >= NumJobs) break;
151 std::string Log = "fuzz-" + std::to_string(C) + ".log";
152 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
153 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000154 Printf("%s", ToRun.c_str());
Kostya Serebryany016852c2015-02-19 18:45:37 +0000155 int ExitCode = system(ToRun.c_str());
156 if (ExitCode != 0)
157 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000158 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000159 Printf("================== Job %d exited with exit code %d ============\n",
160 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000161 fuzzer::CopyFileToErr(Log);
162 }
163}
164
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000165static int RunInMultipleProcesses(const std::vector<std::string> &Args,
166 int NumWorkers, int NumJobs) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000167 std::atomic<int> Counter(0);
168 std::atomic<bool> HasErrors(false);
169 std::string Cmd;
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000170 for (auto &S : Args) {
171 if (FlagValue(S.c_str(), "jobs") || FlagValue(S.c_str(), "workers"))
172 continue;
173 Cmd += S + " ";
Kostya Serebryany016852c2015-02-19 18:45:37 +0000174 }
175 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000176 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000177 Pulse.detach();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000178 for (int i = 0; i < NumWorkers; i++)
179 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
180 for (auto &T : V)
181 T.join();
182 return HasErrors ? 1 : 0;
183}
184
Ivan Krasin95e82d52015-10-01 23:23:06 +0000185int RunOneTest(Fuzzer *F, const char *InputFilePath) {
186 Unit U = FileToVector(InputFilePath);
187 F->ExecuteCallback(U);
188 return 0;
189}
190
Kostya Serebryany016852c2015-02-19 18:45:37 +0000191int FuzzerDriver(int argc, char **argv, UserCallback Callback) {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000192 FuzzerRandomLibc Rand(0);
193 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000194 return FuzzerDriver(argc, argv, SUSF);
195}
196
197int FuzzerDriver(int argc, char **argv, UserSuppliedFuzzer &USF) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000198 std::vector<std::string> Args(argv, argv + argc);
199 return FuzzerDriver(Args, USF);
200}
Kostya Serebryany016852c2015-02-19 18:45:37 +0000201
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000202int FuzzerDriver(const std::vector<std::string> &Args, UserCallback Callback) {
203 FuzzerRandomLibc Rand(0);
204 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
205 return FuzzerDriver(Args, SUSF);
206}
207
208int FuzzerDriver(const std::vector<std::string> &Args,
209 UserSuppliedFuzzer &USF) {
210 using namespace fuzzer;
211 assert(!Args.empty());
212 ProgName = new std::string(Args[0]);
213 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000214 if (Flags.help) {
215 PrintHelp();
216 return 0;
217 }
218
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000219 if (Flags.jobs > 0 && Flags.workers == 0) {
220 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
221 if (Flags.workers > 1)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000222 Printf("Running %d workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000223 }
224
Kostya Serebryany016852c2015-02-19 18:45:37 +0000225 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000226 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000227
228 Fuzzer::FuzzingOptions Options;
229 Options.Verbosity = Flags.verbosity;
230 Options.MaxLen = Flags.max_len;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000231 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000232 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000233 Options.DoCrossOver = Flags.cross_over;
234 Options.MutateDepth = Flags.mutate_depth;
235 Options.ExitOnFirst = Flags.exit_on_first;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000236 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000237 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryany5a99ecb2015-05-11 20:51:19 +0000238 Options.UseTraces = Flags.use_traces;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000239 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000240 Options.PreferSmallDuringInitialShuffle =
241 Flags.prefer_small_during_initial_shuffle;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000242 Options.Reload = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000243 Options.OnlyASCII = Flags.only_ascii;
Kostya Serebryany12c78372015-08-12 01:55:37 +0000244 Options.TBMDepth = Flags.tbm_depth;
245 Options.TBMWidth = Flags.tbm_width;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000246 if (Flags.runs >= 0)
247 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000248 if (!Inputs->empty())
249 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000250 if (Flags.sync_command)
251 Options.SyncCommand = Flags.sync_command;
252 Options.SyncTimeout = Flags.sync_timeout;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000253 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000254 if (Flags.artifact_prefix)
255 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000256 if (Flags.dict)
257 if (!ParseDictionaryFile(FileToString(Flags.dict), &Options.Dictionary))
258 return 1;
259 if (Flags.verbosity > 0 && !Options.Dictionary.empty())
260 Printf("Dictionary: %zd entries\n", Options.Dictionary.size());
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000261 Options.SaveArtifacts = !Flags.test_single_input;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000262
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000263 Fuzzer F(USF, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000264
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000265 // Timer
266 if (Flags.timeout > 0)
267 SetTimer(Flags.timeout / 2 + 1);
268
Ivan Krasin95e82d52015-10-01 23:23:06 +0000269 if (Flags.test_single_input)
270 return RunOneTest(&F, Flags.test_single_input);
271
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000272 if (Flags.merge) {
273 F.Merge(*Inputs);
274 exit(0);
275 }
276
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000277 unsigned Seed = Flags.seed;
278 // Initialize Seed.
279 if (Seed == 0)
280 Seed = time(0) * 10000 + getpid();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000281 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000282 Printf("Seed: %u\n", Seed);
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000283 USF.GetRand().ResetSeed(Seed);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000284
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000285 F.RereadOutputCorpus();
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000286 for (auto &inp : *Inputs)
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000287 if (inp != Options.OutputCorpus)
288 F.ReadDir(inp, nullptr);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000289
290 if (F.CorpusSize() == 0)
291 F.AddToCorpus(Unit()); // Can't fuzz empty corpus, so add an empty input.
292 F.ShuffleAndMinimize();
293 if (Flags.save_minimized_corpus)
294 F.SaveCorpus();
Kostya Serebryany468ed782015-09-08 17:30:35 +0000295 F.Loop();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000296 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000297 Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
298 F.secondsSinceProcessStartUp());
299
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000300 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000301}
302
303} // namespace fuzzer