blob: 872d2c88e6f2f9e20727bb254781164889b22eaf [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;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000035 unsigned int *UIntFlag;
Kostya Serebryany016852c2015-02-19 18:45:37 +000036};
37
38struct {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000039#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000040#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000041#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
Kostya Serebryany016852c2015-02-19 18:45:37 +000042#include "FuzzerFlags.def"
Kostya Serebryany52a788e2015-03-31 20:13:20 +000043#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000044#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000045#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000046} Flags;
47
Craig Topper26260942015-10-18 05:15:34 +000048static const FlagDescription FlagDescriptions [] {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000049#define FUZZER_FLAG_INT(Name, Default, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000050 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
51#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
52 {#Name, Description, static_cast<int>(Default), \
53 nullptr, nullptr, &Flags.Name},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000054#define FUZZER_FLAG_STRING(Name, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000055 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
Kostya Serebryany016852c2015-02-19 18:45:37 +000056#include "FuzzerFlags.def"
Kostya Serebryany52a788e2015-03-31 20:13:20 +000057#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000058#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000059#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000060};
61
62static const size_t kNumFlags =
63 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
64
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000065static std::vector<std::string> *Inputs;
66static std::string *ProgName;
Kostya Serebryany016852c2015-02-19 18:45:37 +000067
68static void PrintHelp() {
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000069 Printf("Usage: %s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n",
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000070 ProgName->c_str());
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000071 Printf("\nFlags: (strictly in form -flag=value)\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000072 size_t MaxFlagLen = 0;
73 for (size_t F = 0; F < kNumFlags; F++)
74 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
75
76 for (size_t F = 0; F < kNumFlags; F++) {
77 const auto &D = FlagDescriptions[F];
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000078 Printf(" %s", D.Name);
Kostya Serebryany016852c2015-02-19 18:45:37 +000079 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000080 Printf(" ");
81 Printf("\t");
82 Printf("%d\t%s\n", D.Default, D.Description);
Kostya Serebryany016852c2015-02-19 18:45:37 +000083 }
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000084 Printf("\nFlags starting with '--' will be ignored and "
85 "will be passed verbatim to subprocesses.\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000086}
87
88static const char *FlagValue(const char *Param, const char *Name) {
89 size_t Len = strlen(Name);
90 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
91 Param[Len + 1] == '=')
92 return &Param[Len + 2];
93 return nullptr;
94}
95
96static bool ParseOneFlag(const char *Param) {
97 if (Param[0] != '-') return false;
Kostya Serebryany71e0feb2015-05-21 20:39:13 +000098 if (Param[1] == '-') {
99 static bool PrintedWarning = false;
100 if (!PrintedWarning) {
101 PrintedWarning = true;
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000102 Printf("WARNING: libFuzzer ignores flags that start with '--'\n");
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000103 }
104 return true;
105 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000106 for (size_t F = 0; F < kNumFlags; F++) {
107 const char *Name = FlagDescriptions[F].Name;
108 const char *Str = FlagValue(Param, Name);
109 if (Str) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000110 if (FlagDescriptions[F].IntFlag) {
111 int Val = std::stol(Str);
112 *FlagDescriptions[F].IntFlag = Val;
113 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000114 Printf("Flag: %s %d\n", Name, Val);;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000115 return true;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000116 } else if (FlagDescriptions[F].UIntFlag) {
117 unsigned int Val = std::stoul(Str);
118 *FlagDescriptions[F].UIntFlag = Val;
119 if (Flags.verbosity >= 2)
120 Printf("Flag: %s %u\n", Name, Val);
121 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000122 } else if (FlagDescriptions[F].StrFlag) {
123 *FlagDescriptions[F].StrFlag = Str;
124 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000125 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000126 return true;
127 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000128 }
129 }
130 PrintHelp();
131 exit(1);
132}
133
134// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000135static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000136 for (size_t F = 0; F < kNumFlags; F++) {
137 if (FlagDescriptions[F].IntFlag)
138 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000139 if (FlagDescriptions[F].UIntFlag)
140 *FlagDescriptions[F].UIntFlag =
141 static_cast<unsigned int>(FlagDescriptions[F].Default);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000142 if (FlagDescriptions[F].StrFlag)
143 *FlagDescriptions[F].StrFlag = nullptr;
144 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000145 Inputs = new std::vector<std::string>;
146 for (size_t A = 1; A < Args.size(); A++) {
147 if (ParseOneFlag(Args[A].c_str())) continue;
148 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000149 }
150}
151
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000152static std::mutex Mu;
153
154static void PulseThread() {
155 while (true) {
156 std::this_thread::sleep_for(std::chrono::seconds(600));
157 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000158 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000159 }
160}
161
Kostya Serebryany016852c2015-02-19 18:45:37 +0000162static void WorkerThread(const std::string &Cmd, std::atomic<int> *Counter,
163 int NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000164 while (true) {
165 int C = (*Counter)++;
166 if (C >= NumJobs) break;
167 std::string Log = "fuzz-" + std::to_string(C) + ".log";
168 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
169 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000170 Printf("%s", ToRun.c_str());
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000171 int ExitCode = ExecuteCommand(ToRun.c_str());
Kostya Serebryany016852c2015-02-19 18:45:37 +0000172 if (ExitCode != 0)
173 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000174 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000175 Printf("================== Job %d exited with exit code %d ============\n",
176 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000177 fuzzer::CopyFileToErr(Log);
178 }
179}
180
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000181static int RunInMultipleProcesses(const std::vector<std::string> &Args,
182 int NumWorkers, int NumJobs) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000183 std::atomic<int> Counter(0);
184 std::atomic<bool> HasErrors(false);
185 std::string Cmd;
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000186 for (auto &S : Args) {
187 if (FlagValue(S.c_str(), "jobs") || FlagValue(S.c_str(), "workers"))
188 continue;
189 Cmd += S + " ";
Kostya Serebryany016852c2015-02-19 18:45:37 +0000190 }
191 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000192 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000193 Pulse.detach();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000194 for (int i = 0; i < NumWorkers; i++)
195 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
196 for (auto &T : V)
197 T.join();
198 return HasErrors ? 1 : 0;
199}
200
Ivan Krasin95e82d52015-10-01 23:23:06 +0000201int RunOneTest(Fuzzer *F, const char *InputFilePath) {
202 Unit U = FileToVector(InputFilePath);
Kostya Serebryany856b7af2015-11-03 18:57:25 +0000203 Unit PreciseSizedU(U);
204 assert(PreciseSizedU.size() == PreciseSizedU.capacity());
205 F->ExecuteCallback(PreciseSizedU);
Ivan Krasin95e82d52015-10-01 23:23:06 +0000206 return 0;
207}
208
Kostya Serebryany016852c2015-02-19 18:45:37 +0000209int FuzzerDriver(int argc, char **argv, UserCallback Callback) {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000210 FuzzerRandomLibc Rand(0);
211 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000212 return FuzzerDriver(argc, argv, SUSF);
213}
214
215int FuzzerDriver(int argc, char **argv, UserSuppliedFuzzer &USF) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000216 std::vector<std::string> Args(argv, argv + argc);
217 return FuzzerDriver(Args, USF);
218}
Kostya Serebryany016852c2015-02-19 18:45:37 +0000219
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000220int FuzzerDriver(const std::vector<std::string> &Args, UserCallback Callback) {
221 FuzzerRandomLibc Rand(0);
222 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
223 return FuzzerDriver(Args, SUSF);
224}
225
226int FuzzerDriver(const std::vector<std::string> &Args,
227 UserSuppliedFuzzer &USF) {
228 using namespace fuzzer;
229 assert(!Args.empty());
230 ProgName = new std::string(Args[0]);
231 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000232 if (Flags.help) {
233 PrintHelp();
234 return 0;
235 }
236
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000237 if (Flags.jobs > 0 && Flags.workers == 0) {
238 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
239 if (Flags.workers > 1)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000240 Printf("Running %d workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000241 }
242
Kostya Serebryany016852c2015-02-19 18:45:37 +0000243 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000244 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000245
246 Fuzzer::FuzzingOptions Options;
247 Options.Verbosity = Flags.verbosity;
248 Options.MaxLen = Flags.max_len;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000249 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000250 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000251 Options.DoCrossOver = Flags.cross_over;
252 Options.MutateDepth = Flags.mutate_depth;
253 Options.ExitOnFirst = Flags.exit_on_first;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000254 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000255 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryany5a99ecb2015-05-11 20:51:19 +0000256 Options.UseTraces = Flags.use_traces;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000257 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000258 Options.PreferSmallDuringInitialShuffle =
259 Flags.prefer_small_during_initial_shuffle;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000260 Options.Reload = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000261 Options.OnlyASCII = Flags.only_ascii;
Kostya Serebryany12c78372015-08-12 01:55:37 +0000262 Options.TBMDepth = Flags.tbm_depth;
263 Options.TBMWidth = Flags.tbm_width;
Mike Aizatskya9c23872015-11-12 04:38:40 +0000264 Options.OutputCSV = Flags.output_csv;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000265 if (Flags.runs >= 0)
266 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000267 if (!Inputs->empty())
268 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000269 if (Flags.sync_command)
270 Options.SyncCommand = Flags.sync_command;
271 Options.SyncTimeout = Flags.sync_timeout;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000272 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000273 if (Flags.artifact_prefix)
274 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000275 if (Flags.exact_artifact_path)
276 Options.ExactArtifactPath = Flags.exact_artifact_path;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000277 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000278 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000279 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000280 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000281 if (Flags.verbosity > 0 && !Dictionary.empty())
282 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000283 Options.SaveArtifacts = !Flags.test_single_input;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000284
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000285 Fuzzer F(USF, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000286
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000287 for (auto &U: Dictionary)
288 USF.GetMD().AddWordToDictionary(U.data(), U.size());
289
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000290 // Timer
291 if (Flags.timeout > 0)
292 SetTimer(Flags.timeout / 2 + 1);
293
Kostya Serebryanyb5693682015-11-21 03:46:43 +0000294 if (Flags.test_single_input) {
295 RunOneTest(&F, Flags.test_single_input);
296 exit(0);
297 }
Ivan Krasin95e82d52015-10-01 23:23:06 +0000298
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000299 if (Flags.merge) {
300 F.Merge(*Inputs);
301 exit(0);
302 }
303
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000304 unsigned Seed = Flags.seed;
305 // Initialize Seed.
306 if (Seed == 0)
307 Seed = time(0) * 10000 + getpid();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000308 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000309 Printf("Seed: %u\n", Seed);
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000310 USF.GetRand().ResetSeed(Seed);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000311
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000312 F.RereadOutputCorpus();
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000313 for (auto &inp : *Inputs)
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000314 if (inp != Options.OutputCorpus)
315 F.ReadDir(inp, nullptr);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000316
317 if (F.CorpusSize() == 0)
318 F.AddToCorpus(Unit()); // Can't fuzz empty corpus, so add an empty input.
319 F.ShuffleAndMinimize();
320 if (Flags.save_minimized_corpus)
321 F.SaveCorpus();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000322 else if (Flags.drill)
323 F.Drill();
324 else
325 F.Loop();
326
Kostya Serebryany016852c2015-02-19 18:45:37 +0000327 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000328 Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
329 F.secondsSinceProcessStartUp());
330
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000331 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000332}
333
334} // namespace fuzzer