blob: eaa308cac723146a5dc1d825f8bafe04ed0b46c1 [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
Kostya Serebryany4282d302016-01-15 00:17:37 +000026// This function should be present in the libFuzzer so that the client
27// binary can test for its existence.
28extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
29
Kostya Serebryany016852c2015-02-19 18:45:37 +000030namespace fuzzer {
31
32// Program arguments.
33struct FlagDescription {
34 const char *Name;
35 const char *Description;
36 int Default;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000037 int *IntFlag;
38 const char **StrFlag;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000039 unsigned int *UIntFlag;
Kostya Serebryany016852c2015-02-19 18:45:37 +000040};
41
42struct {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000043#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000044#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000045#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
Kostya Serebryany016852c2015-02-19 18:45:37 +000046#include "FuzzerFlags.def"
Kostya Serebryany52a788e2015-03-31 20:13:20 +000047#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000048#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000049#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000050} Flags;
51
Craig Topper26260942015-10-18 05:15:34 +000052static const FlagDescription FlagDescriptions [] {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000053#define FUZZER_FLAG_INT(Name, Default, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000054 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
55#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
56 {#Name, Description, static_cast<int>(Default), \
57 nullptr, nullptr, &Flags.Name},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000058#define FUZZER_FLAG_STRING(Name, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000059 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
Kostya Serebryany016852c2015-02-19 18:45:37 +000060#include "FuzzerFlags.def"
Kostya Serebryany52a788e2015-03-31 20:13:20 +000061#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000062#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000063#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000064};
65
66static const size_t kNumFlags =
67 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
68
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000069static std::vector<std::string> *Inputs;
70static std::string *ProgName;
Kostya Serebryany016852c2015-02-19 18:45:37 +000071
72static void PrintHelp() {
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000073 Printf("Usage: %s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n",
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000074 ProgName->c_str());
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000075 Printf("\nFlags: (strictly in form -flag=value)\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000076 size_t MaxFlagLen = 0;
77 for (size_t F = 0; F < kNumFlags; F++)
78 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
79
80 for (size_t F = 0; F < kNumFlags; F++) {
81 const auto &D = FlagDescriptions[F];
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000082 Printf(" %s", D.Name);
Kostya Serebryany016852c2015-02-19 18:45:37 +000083 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000084 Printf(" ");
85 Printf("\t");
86 Printf("%d\t%s\n", D.Default, D.Description);
Kostya Serebryany016852c2015-02-19 18:45:37 +000087 }
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000088 Printf("\nFlags starting with '--' will be ignored and "
89 "will be passed verbatim to subprocesses.\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000090}
91
92static const char *FlagValue(const char *Param, const char *Name) {
93 size_t Len = strlen(Name);
94 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
95 Param[Len + 1] == '=')
96 return &Param[Len + 2];
97 return nullptr;
98}
99
Kostya Serebryany4282d302016-01-15 00:17:37 +0000100// Avoid calling stol as it triggers a bug in clang/glibc build.
101static long MyStol(const char *Str) {
102 long Res = 0;
103 for (size_t i = 0; Str[i]; i++) {
104 char Ch = Str[i];
105 if (Ch < '0' || Ch > '9')
106 return Res;
107 Res = Res * 10 + (Ch - '0');
108 }
109 return Res;
110}
111
Kostya Serebryany016852c2015-02-19 18:45:37 +0000112static bool ParseOneFlag(const char *Param) {
113 if (Param[0] != '-') return false;
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000114 if (Param[1] == '-') {
115 static bool PrintedWarning = false;
116 if (!PrintedWarning) {
117 PrintedWarning = true;
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000118 Printf("WARNING: libFuzzer ignores flags that start with '--'\n");
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000119 }
120 return true;
121 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000122 for (size_t F = 0; F < kNumFlags; F++) {
123 const char *Name = FlagDescriptions[F].Name;
124 const char *Str = FlagValue(Param, Name);
125 if (Str) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000126 if (FlagDescriptions[F].IntFlag) {
Kostya Serebryany4282d302016-01-15 00:17:37 +0000127 int Val = MyStol(Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000128 *FlagDescriptions[F].IntFlag = Val;
129 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000130 Printf("Flag: %s %d\n", Name, Val);;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000131 return true;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000132 } else if (FlagDescriptions[F].UIntFlag) {
133 unsigned int Val = std::stoul(Str);
134 *FlagDescriptions[F].UIntFlag = Val;
135 if (Flags.verbosity >= 2)
136 Printf("Flag: %s %u\n", Name, Val);
137 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000138 } else if (FlagDescriptions[F].StrFlag) {
139 *FlagDescriptions[F].StrFlag = Str;
140 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000141 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000142 return true;
143 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000144 }
145 }
146 PrintHelp();
147 exit(1);
148}
149
150// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000151static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000152 for (size_t F = 0; F < kNumFlags; F++) {
153 if (FlagDescriptions[F].IntFlag)
154 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000155 if (FlagDescriptions[F].UIntFlag)
156 *FlagDescriptions[F].UIntFlag =
157 static_cast<unsigned int>(FlagDescriptions[F].Default);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000158 if (FlagDescriptions[F].StrFlag)
159 *FlagDescriptions[F].StrFlag = nullptr;
160 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000161 Inputs = new std::vector<std::string>;
162 for (size_t A = 1; A < Args.size(); A++) {
163 if (ParseOneFlag(Args[A].c_str())) continue;
164 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000165 }
166}
167
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000168static std::mutex Mu;
169
170static void PulseThread() {
171 while (true) {
172 std::this_thread::sleep_for(std::chrono::seconds(600));
173 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000174 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000175 }
176}
177
Kostya Serebryany016852c2015-02-19 18:45:37 +0000178static void WorkerThread(const std::string &Cmd, std::atomic<int> *Counter,
179 int NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000180 while (true) {
181 int C = (*Counter)++;
182 if (C >= NumJobs) break;
183 std::string Log = "fuzz-" + std::to_string(C) + ".log";
184 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
185 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000186 Printf("%s", ToRun.c_str());
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000187 int ExitCode = ExecuteCommand(ToRun.c_str());
Kostya Serebryany016852c2015-02-19 18:45:37 +0000188 if (ExitCode != 0)
189 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000190 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000191 Printf("================== Job %d exited with exit code %d ============\n",
192 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000193 fuzzer::CopyFileToErr(Log);
194 }
195}
196
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000197static int RunInMultipleProcesses(const std::vector<std::string> &Args,
198 int NumWorkers, int NumJobs) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000199 std::atomic<int> Counter(0);
200 std::atomic<bool> HasErrors(false);
201 std::string Cmd;
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000202 for (auto &S : Args) {
203 if (FlagValue(S.c_str(), "jobs") || FlagValue(S.c_str(), "workers"))
204 continue;
205 Cmd += S + " ";
Kostya Serebryany016852c2015-02-19 18:45:37 +0000206 }
207 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000208 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000209 Pulse.detach();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000210 for (int i = 0; i < NumWorkers; i++)
211 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
212 for (auto &T : V)
213 T.join();
214 return HasErrors ? 1 : 0;
215}
216
Ivan Krasin95e82d52015-10-01 23:23:06 +0000217int RunOneTest(Fuzzer *F, const char *InputFilePath) {
218 Unit U = FileToVector(InputFilePath);
Kostya Serebryany856b7af2015-11-03 18:57:25 +0000219 Unit PreciseSizedU(U);
220 assert(PreciseSizedU.size() == PreciseSizedU.capacity());
221 F->ExecuteCallback(PreciseSizedU);
Ivan Krasin95e82d52015-10-01 23:23:06 +0000222 return 0;
223}
224
Kostya Serebryany016852c2015-02-19 18:45:37 +0000225int FuzzerDriver(int argc, char **argv, UserCallback Callback) {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000226 FuzzerRandomLibc Rand(0);
227 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000228 return FuzzerDriver(argc, argv, SUSF);
229}
230
231int FuzzerDriver(int argc, char **argv, UserSuppliedFuzzer &USF) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000232 std::vector<std::string> Args(argv, argv + argc);
233 return FuzzerDriver(Args, USF);
234}
Kostya Serebryany016852c2015-02-19 18:45:37 +0000235
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000236int FuzzerDriver(const std::vector<std::string> &Args, UserCallback Callback) {
237 FuzzerRandomLibc Rand(0);
238 SimpleUserSuppliedFuzzer SUSF(&Rand, Callback);
239 return FuzzerDriver(Args, SUSF);
240}
241
242int FuzzerDriver(const std::vector<std::string> &Args,
243 UserSuppliedFuzzer &USF) {
244 using namespace fuzzer;
245 assert(!Args.empty());
246 ProgName = new std::string(Args[0]);
247 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000248 if (Flags.help) {
249 PrintHelp();
250 return 0;
251 }
252
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000253 if (Flags.jobs > 0 && Flags.workers == 0) {
254 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
255 if (Flags.workers > 1)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000256 Printf("Running %d workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000257 }
258
Kostya Serebryany016852c2015-02-19 18:45:37 +0000259 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000260 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000261
262 Fuzzer::FuzzingOptions Options;
263 Options.Verbosity = Flags.verbosity;
264 Options.MaxLen = Flags.max_len;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000265 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000266 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000267 Options.DoCrossOver = Flags.cross_over;
268 Options.MutateDepth = Flags.mutate_depth;
269 Options.ExitOnFirst = Flags.exit_on_first;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000270 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000271 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryany5a99ecb2015-05-11 20:51:19 +0000272 Options.UseTraces = Flags.use_traces;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000273 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000274 Options.PreferSmallDuringInitialShuffle =
275 Flags.prefer_small_during_initial_shuffle;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000276 Options.Reload = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000277 Options.OnlyASCII = Flags.only_ascii;
Mike Aizatskya9c23872015-11-12 04:38:40 +0000278 Options.OutputCSV = Flags.output_csv;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000279 if (Flags.runs >= 0)
280 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000281 if (!Inputs->empty())
282 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000283 if (Flags.sync_command)
284 Options.SyncCommand = Flags.sync_command;
285 Options.SyncTimeout = Flags.sync_timeout;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000286 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000287 if (Flags.artifact_prefix)
288 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000289 if (Flags.exact_artifact_path)
290 Options.ExactArtifactPath = Flags.exact_artifact_path;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000291 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000292 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000293 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000294 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000295 if (Flags.verbosity > 0 && !Dictionary.empty())
296 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000297 Options.SaveArtifacts = !Flags.test_single_input;
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000298 Options.PrintNewCovPcs = Flags.print_new_cov_pcs;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000299
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000300 Fuzzer F(USF, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000301
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000302 for (auto &U: Dictionary)
Kostya Serebryany152ac7a2016-01-07 01:49:35 +0000303 USF.GetMD().AddWordToManualDictionary(U);
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000304
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000305 // Timer
306 if (Flags.timeout > 0)
307 SetTimer(Flags.timeout / 2 + 1);
308
Kostya Serebryanyb5693682015-11-21 03:46:43 +0000309 if (Flags.test_single_input) {
310 RunOneTest(&F, Flags.test_single_input);
311 exit(0);
312 }
Ivan Krasin95e82d52015-10-01 23:23:06 +0000313
Kostya Serebryany550e9c82015-12-19 03:42:16 +0000314 if (Flags.save_minimized_corpus) {
315 Printf("The flag -save_minimized_corpus is deprecated; use -merge=1\n");
316 exit(1);
317 }
318
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000319 if (Flags.merge) {
320 F.Merge(*Inputs);
321 exit(0);
322 }
323
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000324 unsigned Seed = Flags.seed;
325 // Initialize Seed.
326 if (Seed == 0)
327 Seed = time(0) * 10000 + getpid();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000328 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000329 Printf("Seed: %u\n", Seed);
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000330 USF.GetRand().ResetSeed(Seed);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000331
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000332 F.RereadOutputCorpus();
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000333 for (auto &inp : *Inputs)
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000334 if (inp != Options.OutputCorpus)
335 F.ReadDir(inp, nullptr);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000336
337 if (F.CorpusSize() == 0)
338 F.AddToCorpus(Unit()); // Can't fuzz empty corpus, so add an empty input.
339 F.ShuffleAndMinimize();
Kostya Serebryany550e9c82015-12-19 03:42:16 +0000340 if (Flags.drill)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000341 F.Drill();
342 else
343 F.Loop();
344
Kostya Serebryany016852c2015-02-19 18:45:37 +0000345 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000346 Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
347 F.secondsSinceProcessStartUp());
348
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000349 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000350}
351
352} // namespace fuzzer