blob: 4b9b57f27ea76c6e4b7607f668e56bf282d0796b [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
45static 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
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000185std::vector<std::string> ReadTokensFile(const char *TokensFilePath) {
186 if (!TokensFilePath) return {};
187 std::string TokensFileContents = FileToString(TokensFilePath);
188 std::istringstream ISS(TokensFileContents);
189 std::vector<std::string> Res = {std::istream_iterator<std::string>{ISS},
190 std::istream_iterator<std::string>{}};
191 Res.push_back(" ");
192 Res.push_back("\t");
193 Res.push_back("\n");
194 return Res;
195}
196
197int ApplyTokens(const Fuzzer &F, const char *InputFilePath) {
198 Unit U = FileToVector(InputFilePath);
199 auto T = F.SubstituteTokens(U);
200 T.push_back(0);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000201 Printf("%s", T.data());
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000202 return 0;
203}
204
Ivan Krasin95e82d52015-10-01 23:23:06 +0000205int RunOneTest(Fuzzer *F, const char *InputFilePath) {
206 Unit U = FileToVector(InputFilePath);
207 F->ExecuteCallback(U);
208 return 0;
209}
210
Kostya Serebryany016852c2015-02-19 18:45:37 +0000211int FuzzerDriver(int argc, char **argv, UserCallback Callback) {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000212 FuzzerRandomLibc Rand(0);
213 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000214 return FuzzerDriver(argc, argv, SUSF);
215}
216
217int FuzzerDriver(int argc, char **argv, UserSuppliedFuzzer &USF) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000218 std::vector<std::string> Args(argv, argv + argc);
219 return FuzzerDriver(Args, USF);
220}
Kostya Serebryany016852c2015-02-19 18:45:37 +0000221
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000222int FuzzerDriver(const std::vector<std::string> &Args, UserCallback Callback) {
223 FuzzerRandomLibc Rand(0);
224 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
225 return FuzzerDriver(Args, SUSF);
226}
227
228int FuzzerDriver(const std::vector<std::string> &Args,
229 UserSuppliedFuzzer &USF) {
230 using namespace fuzzer;
231 assert(!Args.empty());
232 ProgName = new std::string(Args[0]);
233 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000234 if (Flags.help) {
235 PrintHelp();
236 return 0;
237 }
238
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000239 if (Flags.jobs > 0 && Flags.workers == 0) {
240 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
241 if (Flags.workers > 1)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000242 Printf("Running %d workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000243 }
244
Kostya Serebryany016852c2015-02-19 18:45:37 +0000245 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000246 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000247
248 Fuzzer::FuzzingOptions Options;
249 Options.Verbosity = Flags.verbosity;
250 Options.MaxLen = Flags.max_len;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000251 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000252 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000253 Options.DoCrossOver = Flags.cross_over;
254 Options.MutateDepth = Flags.mutate_depth;
255 Options.ExitOnFirst = Flags.exit_on_first;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000256 Options.UseCounters = Flags.use_counters;
Kostya Serebryany5a99ecb2015-05-11 20:51:19 +0000257 Options.UseTraces = Flags.use_traces;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000258 Options.UseFullCoverageSet = Flags.use_full_coverage_set;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000259 Options.PreferSmallDuringInitialShuffle =
260 Flags.prefer_small_during_initial_shuffle;
Kostya Serebryany6ea1b692015-09-02 23:27:39 +0000261 Options.Tokens = ReadTokensFile(Flags.deprecated_tokens);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000262 Options.Reload = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000263 Options.OnlyASCII = Flags.only_ascii;
Kostya Serebryany12c78372015-08-12 01:55:37 +0000264 Options.TBMDepth = Flags.tbm_depth;
265 Options.TBMWidth = Flags.tbm_width;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000266 if (Flags.runs >= 0)
267 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000268 if (!Inputs->empty())
269 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000270 if (Flags.sync_command)
271 Options.SyncCommand = Flags.sync_command;
272 Options.SyncTimeout = Flags.sync_timeout;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000273 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000274 if (Flags.dict)
275 if (!ParseDictionaryFile(FileToString(Flags.dict), &Options.Dictionary))
276 return 1;
277 if (Flags.verbosity > 0 && !Options.Dictionary.empty())
278 Printf("Dictionary: %zd entries\n", Options.Dictionary.size());
279
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000280 Fuzzer F(USF, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000281
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000282 if (Flags.apply_tokens)
283 return ApplyTokens(F, Flags.apply_tokens);
284
Ivan Krasin95e82d52015-10-01 23:23:06 +0000285 if (Flags.test_single_input)
286 return RunOneTest(&F, Flags.test_single_input);
287
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000288 unsigned Seed = Flags.seed;
289 // Initialize Seed.
290 if (Seed == 0)
291 Seed = time(0) * 10000 + getpid();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000292 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000293 Printf("Seed: %u\n", Seed);
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000294 USF.GetRand().ResetSeed(Seed);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000295
296 // Timer
297 if (Flags.timeout > 0)
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000298 SetTimer(Flags.timeout / 2 + 1);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000299
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000300 if (Flags.verbosity >= 2) {
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000301 Printf("Tokens: {");
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000302 for (auto &T : Options.Tokens)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000303 Printf("%s,", T.c_str());
304 Printf("}\n");
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000305 }
306
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000307 F.RereadOutputCorpus();
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000308 for (auto &inp : *Inputs)
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000309 if (inp != Options.OutputCorpus)
310 F.ReadDir(inp, nullptr);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000311
312 if (F.CorpusSize() == 0)
313 F.AddToCorpus(Unit()); // Can't fuzz empty corpus, so add an empty input.
314 F.ShuffleAndMinimize();
315 if (Flags.save_minimized_corpus)
316 F.SaveCorpus();
Kostya Serebryany468ed782015-09-08 17:30:35 +0000317 F.Loop();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000318 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000319 Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
320 F.secondsSinceProcessStartUp());
321
Kostya Serebryany016852c2015-02-19 18:45:37 +0000322 return 0;
323}
324
325} // namespace fuzzer