1 //===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // FuzzerDriver and flag parsing.
10 //===----------------------------------------------------------------------===//
12 #include "FuzzerInterface.h"
13 #include "FuzzerInternal.h"
29 struct FlagDescription {
31 const char *Description;
38 #define FUZZER_FLAG_INT(Name, Default, Description) int Name;
39 #define FUZZER_FLAG_STRING(Name, Description) const char *Name;
40 #include "FuzzerFlags.def"
41 #undef FUZZER_FLAG_INT
42 #undef FUZZER_FLAG_STRING
45 static FlagDescription FlagDescriptions [] {
46 #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 },
50 #include "FuzzerFlags.def"
51 #undef FUZZER_FLAG_INT
52 #undef FUZZER_FLAG_STRING
55 static const size_t kNumFlags =
56 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
58 static std::vector<std::string> *Inputs;
59 static std::string *ProgName;
61 static void PrintHelp() {
62 Printf("Usage: %s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n",
64 Printf("\nFlags: (strictly in form -flag=value)\n");
65 size_t MaxFlagLen = 0;
66 for (size_t F = 0; F < kNumFlags; F++)
67 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
69 for (size_t F = 0; F < kNumFlags; F++) {
70 const auto &D = FlagDescriptions[F];
71 Printf(" %s", D.Name);
72 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
75 Printf("%d\t%s\n", D.Default, D.Description);
77 Printf("\nFlags starting with '--' will be ignored and "
78 "will be passed verbatim to subprocesses.\n");
81 static 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];
89 static bool ParseOneFlag(const char *Param) {
90 if (Param[0] != '-') return false;
91 if (Param[1] == '-') {
92 static bool PrintedWarning = false;
93 if (!PrintedWarning) {
94 PrintedWarning = true;
95 Printf("WARNING: libFuzzer ignores flags that start with '--'\n");
99 for (size_t F = 0; F < kNumFlags; F++) {
100 const char *Name = FlagDescriptions[F].Name;
101 const char *Str = FlagValue(Param, Name);
103 if (FlagDescriptions[F].IntFlag) {
104 int Val = std::stol(Str);
105 *FlagDescriptions[F].IntFlag = Val;
106 if (Flags.verbosity >= 2)
107 Printf("Flag: %s %d\n", Name, Val);;
109 } else if (FlagDescriptions[F].StrFlag) {
110 *FlagDescriptions[F].StrFlag = Str;
111 if (Flags.verbosity >= 2)
112 Printf("Flag: %s %s\n", Name, Str);
121 // We don't use any library to minimize dependencies.
122 static void ParseFlags(const std::vector<std::string> &Args) {
123 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;
129 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]);
136 static std::mutex Mu;
138 static void PulseThread() {
140 std::this_thread::sleep_for(std::chrono::seconds(600));
141 std::lock_guard<std::mutex> Lock(Mu);
142 Printf("pulse...\n");
146 static void WorkerThread(const std::string &Cmd, std::atomic<int> *Counter,
147 int NumJobs, std::atomic<bool> *HasErrors) {
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";
154 Printf("%s", ToRun.c_str());
155 int ExitCode = system(ToRun.c_str());
158 std::lock_guard<std::mutex> Lock(Mu);
159 Printf("================== Job %d exited with exit code %d ============\n",
161 fuzzer::CopyFileToErr(Log);
165 static int RunInMultipleProcesses(const std::vector<std::string> &Args,
166 int NumWorkers, int NumJobs) {
167 std::atomic<int> Counter(0);
168 std::atomic<bool> HasErrors(false);
170 for (auto &S : Args) {
171 if (FlagValue(S.c_str(), "jobs") || FlagValue(S.c_str(), "workers"))
175 std::vector<std::thread> V;
176 std::thread Pulse(PulseThread);
178 for (int i = 0; i < NumWorkers; i++)
179 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
182 return HasErrors ? 1 : 0;
185 std::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>{}};
197 int ApplyTokens(const Fuzzer &F, const char *InputFilePath) {
198 Unit U = FileToVector(InputFilePath);
199 auto T = F.SubstituteTokens(U);
201 Printf("%s", T.data());
205 int RunOneTest(Fuzzer *F, const char *InputFilePath) {
206 Unit U = FileToVector(InputFilePath);
207 F->ExecuteCallback(U);
211 int FuzzerDriver(int argc, char **argv, UserCallback Callback) {
212 FuzzerRandomLibc Rand(0);
213 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
214 return FuzzerDriver(argc, argv, SUSF);
217 int FuzzerDriver(int argc, char **argv, UserSuppliedFuzzer &USF) {
218 std::vector<std::string> Args(argv, argv + argc);
219 return FuzzerDriver(Args, USF);
222 int FuzzerDriver(const std::vector<std::string> &Args, UserCallback Callback) {
223 FuzzerRandomLibc Rand(0);
224 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
225 return FuzzerDriver(Args, SUSF);
228 int 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]);
239 if (Flags.jobs > 0 && Flags.workers == 0) {
240 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
241 if (Flags.workers > 1)
242 Printf("Running %d workers\n", Flags.workers);
245 if (Flags.workers > 0 && Flags.jobs > 0)
246 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
248 Fuzzer::FuzzingOptions Options;
249 Options.Verbosity = Flags.verbosity;
250 Options.MaxLen = Flags.max_len;
251 Options.UnitTimeoutSec = Flags.timeout;
252 Options.MaxTotalTimeSec = Flags.max_total_time;
253 Options.DoCrossOver = Flags.cross_over;
254 Options.MutateDepth = Flags.mutate_depth;
255 Options.ExitOnFirst = Flags.exit_on_first;
256 Options.UseCounters = Flags.use_counters;
257 Options.UseTraces = Flags.use_traces;
258 Options.PreferSmallDuringInitialShuffle =
259 Flags.prefer_small_during_initial_shuffle;
260 Options.Tokens = ReadTokensFile(Flags.deprecated_tokens);
261 Options.Reload = Flags.reload;
262 Options.OnlyASCII = Flags.only_ascii;
263 Options.TBMDepth = Flags.tbm_depth;
264 Options.TBMWidth = Flags.tbm_width;
266 Options.MaxNumberOfRuns = Flags.runs;
267 if (!Inputs->empty())
268 Options.OutputCorpus = (*Inputs)[0];
269 if (Flags.sync_command)
270 Options.SyncCommand = Flags.sync_command;
271 Options.SyncTimeout = Flags.sync_timeout;
272 Options.ReportSlowUnits = Flags.report_slow_units;
273 if (Flags.artifact_prefix)
274 Options.ArtifactPrefix = Flags.artifact_prefix;
276 if (!ParseDictionaryFile(FileToString(Flags.dict), &Options.Dictionary))
278 if (Flags.verbosity > 0 && !Options.Dictionary.empty())
279 Printf("Dictionary: %zd entries\n", Options.Dictionary.size());
281 Fuzzer F(USF, Options);
283 if (Flags.apply_tokens)
284 return ApplyTokens(F, Flags.apply_tokens);
286 if (Flags.test_single_input)
287 return RunOneTest(&F, Flags.test_single_input);
289 unsigned Seed = Flags.seed;
292 Seed = time(0) * 10000 + getpid();
294 Printf("Seed: %u\n", Seed);
295 USF.GetRand().ResetSeed(Seed);
298 if (Flags.timeout > 0)
299 SetTimer(Flags.timeout / 2 + 1);
301 if (Flags.verbosity >= 2) {
303 for (auto &T : Options.Tokens)
304 Printf("%s,", T.c_str());
308 F.RereadOutputCorpus();
309 for (auto &inp : *Inputs)
310 if (inp != Options.OutputCorpus)
311 F.ReadDir(inp, nullptr);
313 if (F.CorpusSize() == 0)
314 F.AddToCorpus(Unit()); // Can't fuzz empty corpus, so add an empty input.
315 F.ShuffleAndMinimize();
316 if (Flags.save_minimized_corpus)
320 Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
321 F.secondsSinceProcessStartUp());
323 exit(0); // Don't let F destroy itself.
326 } // namespace fuzzer