blob: 664436ed4f92bac972ec8f05f18c394a6752bfa4 [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 Serebryanydc3135d2015-11-12 01:02:01 +0000155 int ExitCode = ExecuteCommand(ToRun.c_str());
Kostya Serebryany016852c2015-02-19 18:45:37 +0000156 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);
Kostya Serebryany856b7af2015-11-03 18:57:25 +0000187 Unit PreciseSizedU(U);
188 assert(PreciseSizedU.size() == PreciseSizedU.capacity());
189 F->ExecuteCallback(PreciseSizedU);
Ivan Krasin95e82d52015-10-01 23:23:06 +0000190 return 0;
191}
192
Kostya Serebryany016852c2015-02-19 18:45:37 +0000193int FuzzerDriver(int argc, char **argv, UserCallback Callback) {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000194 FuzzerRandomLibc Rand(0);
195 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000196 return FuzzerDriver(argc, argv, SUSF);
197}
198
199int FuzzerDriver(int argc, char **argv, UserSuppliedFuzzer &USF) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000200 std::vector<std::string> Args(argv, argv + argc);
201 return FuzzerDriver(Args, USF);
202}
Kostya Serebryany016852c2015-02-19 18:45:37 +0000203
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000204int FuzzerDriver(const std::vector<std::string> &Args, UserCallback Callback) {
205 FuzzerRandomLibc Rand(0);
206 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
207 return FuzzerDriver(Args, SUSF);
208}
209
210int FuzzerDriver(const std::vector<std::string> &Args,
211 UserSuppliedFuzzer &USF) {
212 using namespace fuzzer;
213 assert(!Args.empty());
214 ProgName = new std::string(Args[0]);
215 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000216 if (Flags.help) {
217 PrintHelp();
218 return 0;
219 }
220
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000221 if (Flags.jobs > 0 && Flags.workers == 0) {
222 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
223 if (Flags.workers > 1)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000224 Printf("Running %d workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000225 }
226
Kostya Serebryany016852c2015-02-19 18:45:37 +0000227 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000228 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000229
230 Fuzzer::FuzzingOptions Options;
231 Options.Verbosity = Flags.verbosity;
232 Options.MaxLen = Flags.max_len;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000233 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000234 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000235 Options.DoCrossOver = Flags.cross_over;
236 Options.MutateDepth = Flags.mutate_depth;
237 Options.ExitOnFirst = Flags.exit_on_first;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000238 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000239 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryany5a99ecb2015-05-11 20:51:19 +0000240 Options.UseTraces = Flags.use_traces;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000241 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000242 Options.PreferSmallDuringInitialShuffle =
243 Flags.prefer_small_during_initial_shuffle;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000244 Options.Reload = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000245 Options.OnlyASCII = Flags.only_ascii;
Kostya Serebryany12c78372015-08-12 01:55:37 +0000246 Options.TBMDepth = Flags.tbm_depth;
247 Options.TBMWidth = Flags.tbm_width;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000248 if (Flags.runs >= 0)
249 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000250 if (!Inputs->empty())
251 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000252 if (Flags.sync_command)
253 Options.SyncCommand = Flags.sync_command;
254 Options.SyncTimeout = Flags.sync_timeout;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000255 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000256 if (Flags.artifact_prefix)
257 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000258 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000259 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000260 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000261 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000262 if (Flags.verbosity > 0 && !Dictionary.empty())
263 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000264 Options.SaveArtifacts = !Flags.test_single_input;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000265
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000266 Fuzzer F(USF, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000267
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000268 for (auto &U: Dictionary)
269 USF.GetMD().AddWordToDictionary(U.data(), U.size());
270
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000271 // Timer
272 if (Flags.timeout > 0)
273 SetTimer(Flags.timeout / 2 + 1);
274
Ivan Krasin95e82d52015-10-01 23:23:06 +0000275 if (Flags.test_single_input)
276 return RunOneTest(&F, Flags.test_single_input);
277
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000278 if (Flags.merge) {
279 F.Merge(*Inputs);
280 exit(0);
281 }
282
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000283 unsigned Seed = Flags.seed;
284 // Initialize Seed.
285 if (Seed == 0)
286 Seed = time(0) * 10000 + getpid();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000287 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000288 Printf("Seed: %u\n", Seed);
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000289 USF.GetRand().ResetSeed(Seed);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000290
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000291 F.RereadOutputCorpus();
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000292 for (auto &inp : *Inputs)
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000293 if (inp != Options.OutputCorpus)
294 F.ReadDir(inp, nullptr);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000295
296 if (F.CorpusSize() == 0)
297 F.AddToCorpus(Unit()); // Can't fuzz empty corpus, so add an empty input.
298 F.ShuffleAndMinimize();
299 if (Flags.save_minimized_corpus)
300 F.SaveCorpus();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000301 else if (Flags.drill)
302 F.Drill();
303 else
304 F.Loop();
305
Kostya Serebryany016852c2015-02-19 18:45:37 +0000306 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000307 Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
308 F.secondsSinceProcessStartUp());
309
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000310 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000311}
312
313} // namespace fuzzer