[libFuzzer] add two more variants of FuzzerDriver for convenience
[oota-llvm.git] / lib / Fuzzer / FuzzerDriver.cpp
1 //===- 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>
16 #include <chrono>
17 #include <unistd.h>
18 #include <thread>
19 #include <atomic>
20 #include <mutex>
21 #include <string>
22 #include <sstream>
23 #include <algorithm>
24 #include <iterator>
25
26 namespace fuzzer {
27
28 // Program arguments.
29 struct FlagDescription {
30   const char *Name;
31   const char *Description;
32   int   Default;
33   int   *IntFlag;
34   const char **StrFlag;
35 };
36
37 struct {
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
43 } Flags;
44
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
53 };
54
55 static const size_t kNumFlags =
56     sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
57
58 static std::vector<std::string> *Inputs;
59 static std::string *ProgName;
60
61 static void PrintHelp() {
62   Printf("Usage: %s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n",
63          ProgName->c_str());
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);
68
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++)
73       Printf(" ");
74     Printf("\t");
75     Printf("%d\t%s\n", D.Default, D.Description);
76   }
77   Printf("\nFlags starting with '--' will be ignored and "
78             "will be passed verbatim to subprocesses.\n");
79 }
80
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];
86   return nullptr;
87 }
88
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");
96     }
97     return true;
98   }
99   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)  {
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);;
108         return true;
109       } else if (FlagDescriptions[F].StrFlag) {
110         *FlagDescriptions[F].StrFlag = Str;
111         if (Flags.verbosity >= 2)
112           Printf("Flag: %s %s\n", Name, Str);
113         return true;
114       }
115     }
116   }
117   PrintHelp();
118   exit(1);
119 }
120
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;
128   }
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]);
133   }
134 }
135
136 static std::mutex Mu;
137
138 static void PulseThread() {
139   while (true) {
140     std::this_thread::sleep_for(std::chrono::seconds(600));
141     std::lock_guard<std::mutex> Lock(Mu);
142     Printf("pulse...\n");
143   }
144 }
145
146 static void WorkerThread(const std::string &Cmd, std::atomic<int> *Counter,
147                         int NumJobs, std::atomic<bool> *HasErrors) {
148   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)
154       Printf("%s", ToRun.c_str());
155     int ExitCode = system(ToRun.c_str());
156     if (ExitCode != 0)
157       *HasErrors = true;
158     std::lock_guard<std::mutex> Lock(Mu);
159     Printf("================== Job %d exited with exit code %d ============\n",
160            C, ExitCode);
161     fuzzer::CopyFileToErr(Log);
162   }
163 }
164
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);
169   std::string Cmd;
170   for (auto &S : Args) {
171     if (FlagValue(S.c_str(), "jobs") || FlagValue(S.c_str(), "workers"))
172       continue;
173     Cmd += S + " ";
174   }
175   std::vector<std::thread> V;
176   std::thread Pulse(PulseThread);
177   Pulse.detach();
178   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
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>{}};
191   Res.push_back(" ");
192   Res.push_back("\t");
193   Res.push_back("\n");
194   return Res;
195 }
196
197 int ApplyTokens(const Fuzzer &F, const char *InputFilePath) {
198   Unit U = FileToVector(InputFilePath);
199   auto T = F.SubstituteTokens(U);
200   T.push_back(0);
201   Printf("%s", T.data());
202   return 0;
203 }
204
205 int FuzzerDriver(int argc, char **argv, UserCallback Callback) {
206   FuzzerRandomLibc Rand(0);
207   SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
208   return FuzzerDriver(argc, argv, SUSF);
209 }
210
211 int FuzzerDriver(int argc, char **argv, UserSuppliedFuzzer &USF) {
212   std::vector<std::string> Args(argv, argv + argc);
213   return FuzzerDriver(Args, USF);
214 }
215
216 int FuzzerDriver(const std::vector<std::string> &Args, UserCallback Callback) {
217   FuzzerRandomLibc Rand(0);
218   SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
219   return FuzzerDriver(Args, SUSF);
220 }
221
222 int FuzzerDriver(const std::vector<std::string> &Args,
223                  UserSuppliedFuzzer &USF) {
224   using namespace fuzzer;
225   assert(!Args.empty());
226   ProgName = new std::string(Args[0]);
227   ParseFlags(Args);
228   if (Flags.help) {
229     PrintHelp();
230     return 0;
231   }
232
233   if (Flags.jobs > 0 && Flags.workers == 0) {
234     Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
235     if (Flags.workers > 1)
236       Printf("Running %d workers\n", Flags.workers);
237   }
238
239   if (Flags.workers > 0 && Flags.jobs > 0)
240     return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
241
242   Fuzzer::FuzzingOptions Options;
243   Options.Verbosity = Flags.verbosity;
244   Options.MaxLen = Flags.max_len;
245   Options.UnitTimeoutSec = Flags.timeout;
246   Options.DoCrossOver = Flags.cross_over;
247   Options.MutateDepth = Flags.mutate_depth;
248   Options.ExitOnFirst = Flags.exit_on_first;
249   Options.UseCounters = Flags.use_counters;
250   Options.UseTraces = Flags.use_traces;
251   Options.UseFullCoverageSet = Flags.use_full_coverage_set;
252   Options.PreferSmallDuringInitialShuffle =
253       Flags.prefer_small_during_initial_shuffle;
254   Options.Tokens = ReadTokensFile(Flags.deprecated_tokens);
255   Options.Reload = Flags.reload;
256   Options.OnlyASCII = Flags.only_ascii;
257   Options.TBMDepth = Flags.tbm_depth;
258   Options.TBMWidth = Flags.tbm_width;
259   if (Flags.runs >= 0)
260     Options.MaxNumberOfRuns = Flags.runs;
261   if (!Inputs->empty())
262     Options.OutputCorpus = (*Inputs)[0];
263   if (Flags.sync_command)
264     Options.SyncCommand = Flags.sync_command;
265   Options.SyncTimeout = Flags.sync_timeout;
266   Options.ReportSlowUnits = Flags.report_slow_units;
267   if (Flags.dict)
268     if (!ParseDictionaryFile(FileToString(Flags.dict), &Options.Dictionary))
269       return 1;
270   if (Flags.verbosity > 0 && !Options.Dictionary.empty())
271     Printf("Dictionary: %zd entries\n", Options.Dictionary.size());
272
273   Fuzzer F(USF, Options);
274
275   if (Flags.apply_tokens)
276     return ApplyTokens(F, Flags.apply_tokens);
277
278   unsigned Seed = Flags.seed;
279   // Initialize Seed.
280   if (Seed == 0)
281     Seed = time(0) * 10000 + getpid();
282   if (Flags.verbosity)
283     Printf("Seed: %u\n", Seed);
284   USF.GetRand().ResetSeed(Seed);
285
286   // Timer
287   if (Flags.timeout > 0)
288     SetTimer(Flags.timeout / 2 + 1);
289
290   if (Flags.verbosity >= 2) {
291     Printf("Tokens: {");
292     for (auto &T : Options.Tokens)
293       Printf("%s,", T.c_str());
294     Printf("}\n");
295   }
296
297   F.RereadOutputCorpus();
298   for (auto &inp : *Inputs)
299     if (inp != Options.OutputCorpus)
300       F.ReadDir(inp, nullptr);
301
302   if (F.CorpusSize() == 0)
303     F.AddToCorpus(Unit());  // Can't fuzz empty corpus, so add an empty input.
304   F.ShuffleAndMinimize();
305   if (Flags.save_minimized_corpus)
306     F.SaveCorpus();
307   F.Loop();
308   if (Flags.verbosity)
309     Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
310            F.secondsSinceProcessStartUp());
311
312   return 0;
313 }
314
315 }  // namespace fuzzer