blob: f2452dc95f2028ce11ad60dbe688915a1dbc5d00 [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
Kostya Serebryany29bb6642016-09-21 22:42:17 +000012#include "FuzzerCorpus.h"
Kostya Serebryany016852c2015-02-19 18:45:37 +000013#include "FuzzerInterface.h"
14#include "FuzzerInternal.h"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000015#include "FuzzerMutate.h"
16#include "FuzzerRandom.h"
Kostya Serebryany016852c2015-02-19 18:45:37 +000017
Mehdi Aminib550cb12016-04-18 09:17:29 +000018#include <algorithm>
Kostya Serebryany016852c2015-02-19 18:45:37 +000019#include <atomic>
Mehdi Aminib550cb12016-04-18 09:17:29 +000020#include <chrono>
21#include <cstring>
Kostya Serebryany016852c2015-02-19 18:45:37 +000022#include <mutex>
Kostya Serebryany52a788e2015-03-31 20:13:20 +000023#include <string>
Mehdi Aminib550cb12016-04-18 09:17:29 +000024#include <thread>
25#include <unistd.h>
Kostya Serebryany016852c2015-02-19 18:45:37 +000026
Kostya Serebryany4282d302016-01-15 00:17:37 +000027// This function should be present in the libFuzzer so that the client
28// binary can test for its existence.
29extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
30
Kostya Serebryany016852c2015-02-19 18:45:37 +000031namespace fuzzer {
32
33// Program arguments.
34struct FlagDescription {
35 const char *Name;
36 const char *Description;
37 int Default;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000038 int *IntFlag;
39 const char **StrFlag;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000040 unsigned int *UIntFlag;
Kostya Serebryany016852c2015-02-19 18:45:37 +000041};
42
43struct {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000044#define FUZZER_DEPRECATED_FLAG(Name)
Kostya Serebryany52a788e2015-03-31 20:13:20 +000045#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000046#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000047#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
Kostya Serebryany016852c2015-02-19 18:45:37 +000048#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000049#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000050#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000051#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000052#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000053} Flags;
54
Craig Topper26260942015-10-18 05:15:34 +000055static const FlagDescription FlagDescriptions [] {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000056#define FUZZER_DEPRECATED_FLAG(Name) \
57 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000058#define FUZZER_FLAG_INT(Name, Default, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000059 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
60#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
61 {#Name, Description, static_cast<int>(Default), \
62 nullptr, nullptr, &Flags.Name},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000063#define FUZZER_FLAG_STRING(Name, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000064 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
Kostya Serebryany016852c2015-02-19 18:45:37 +000065#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000066#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000067#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000068#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000069#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000070};
71
72static const size_t kNumFlags =
73 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
74
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000075static std::vector<std::string> *Inputs;
76static std::string *ProgName;
Kostya Serebryany016852c2015-02-19 18:45:37 +000077
78static void PrintHelp() {
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +000079 Printf("Usage:\n");
80 auto Prog = ProgName->c_str();
81 Printf("\nTo run fuzzing pass 0 or more directories.\n");
82 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
83
84 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
85 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
86
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000087 Printf("\nFlags: (strictly in form -flag=value)\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000088 size_t MaxFlagLen = 0;
89 for (size_t F = 0; F < kNumFlags; F++)
90 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
91
92 for (size_t F = 0; F < kNumFlags; F++) {
93 const auto &D = FlagDescriptions[F];
Kostya Serebryany45299602016-09-10 00:35:30 +000094 if (strstr(D.Description, "internal flag") == D.Description) continue;
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000095 Printf(" %s", D.Name);
Kostya Serebryany016852c2015-02-19 18:45:37 +000096 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000097 Printf(" ");
98 Printf("\t");
99 Printf("%d\t%s\n", D.Default, D.Description);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000100 }
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000101 Printf("\nFlags starting with '--' will be ignored and "
102 "will be passed verbatim to subprocesses.\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000103}
104
105static const char *FlagValue(const char *Param, const char *Name) {
106 size_t Len = strlen(Name);
107 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
108 Param[Len + 1] == '=')
109 return &Param[Len + 2];
110 return nullptr;
111}
112
Kostya Serebryany4282d302016-01-15 00:17:37 +0000113// Avoid calling stol as it triggers a bug in clang/glibc build.
114static long MyStol(const char *Str) {
115 long Res = 0;
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000116 long Sign = 1;
117 if (*Str == '-') {
118 Str++;
119 Sign = -1;
120 }
Kostya Serebryany4282d302016-01-15 00:17:37 +0000121 for (size_t i = 0; Str[i]; i++) {
122 char Ch = Str[i];
123 if (Ch < '0' || Ch > '9')
124 return Res;
125 Res = Res * 10 + (Ch - '0');
126 }
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000127 return Res * Sign;
Kostya Serebryany4282d302016-01-15 00:17:37 +0000128}
129
Kostya Serebryany016852c2015-02-19 18:45:37 +0000130static bool ParseOneFlag(const char *Param) {
131 if (Param[0] != '-') return false;
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000132 if (Param[1] == '-') {
133 static bool PrintedWarning = false;
134 if (!PrintedWarning) {
135 PrintedWarning = true;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000136 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000137 }
Kostya Serebryanyb60397f2016-04-15 21:56:29 +0000138 for (size_t F = 0; F < kNumFlags; F++)
139 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
140 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000141 return true;
142 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000143 for (size_t F = 0; F < kNumFlags; F++) {
144 const char *Name = FlagDescriptions[F].Name;
145 const char *Str = FlagValue(Param, Name);
146 if (Str) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000147 if (FlagDescriptions[F].IntFlag) {
Kostya Serebryany4282d302016-01-15 00:17:37 +0000148 int Val = MyStol(Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000149 *FlagDescriptions[F].IntFlag = Val;
150 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000151 Printf("Flag: %s %d\n", Name, Val);;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000152 return true;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000153 } else if (FlagDescriptions[F].UIntFlag) {
154 unsigned int Val = std::stoul(Str);
155 *FlagDescriptions[F].UIntFlag = Val;
156 if (Flags.verbosity >= 2)
157 Printf("Flag: %s %u\n", Name, Val);
158 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000159 } else if (FlagDescriptions[F].StrFlag) {
160 *FlagDescriptions[F].StrFlag = Str;
161 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000162 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000163 return true;
Kostya Serebryany3d95dd92016-03-01 22:33:14 +0000164 } else { // Deprecated flag.
165 Printf("Flag: %s: deprecated, don't use\n", Name);
166 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000167 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000168 }
169 }
Kostya Serebryanyf8177312016-06-01 16:41:12 +0000170 Printf("\n\nWARNING: unrecognized flag '%s'; "
171 "use -help=1 to list all flags\n\n", Param);
172 return true;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000173}
174
175// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000176static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000177 for (size_t F = 0; F < kNumFlags; F++) {
178 if (FlagDescriptions[F].IntFlag)
179 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000180 if (FlagDescriptions[F].UIntFlag)
181 *FlagDescriptions[F].UIntFlag =
182 static_cast<unsigned int>(FlagDescriptions[F].Default);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000183 if (FlagDescriptions[F].StrFlag)
184 *FlagDescriptions[F].StrFlag = nullptr;
185 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000186 Inputs = new std::vector<std::string>;
187 for (size_t A = 1; A < Args.size(); A++) {
188 if (ParseOneFlag(Args[A].c_str())) continue;
189 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000190 }
191}
192
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000193static std::mutex Mu;
194
195static void PulseThread() {
196 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000197 SleepSeconds(600);
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000198 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000199 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000200 }
201}
202
Kostya Serebryany016852c2015-02-19 18:45:37 +0000203static void WorkerThread(const std::string &Cmd, std::atomic<int> *Counter,
204 int NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000205 while (true) {
206 int C = (*Counter)++;
207 if (C >= NumJobs) break;
208 std::string Log = "fuzz-" + std::to_string(C) + ".log";
209 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
210 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000211 Printf("%s", ToRun.c_str());
Hans Wennborge6319962016-04-11 20:35:17 +0000212 int ExitCode = ExecuteCommand(ToRun);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000213 if (ExitCode != 0)
214 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000215 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000216 Printf("================== Job %d exited with exit code %d ============\n",
217 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000218 fuzzer::CopyFileToErr(Log);
219 }
220}
221
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000222static std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
223 const char *X1, const char *X2) {
224 std::string Cmd;
225 for (auto &S : Args) {
226 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
227 continue;
228 Cmd += S + " ";
229 }
230 return Cmd;
231}
232
233static std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
234 const char *X) {
235 return CloneArgsWithoutX(Args, X, X);
236}
237
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000238static int RunInMultipleProcesses(const std::vector<std::string> &Args,
239 int NumWorkers, int NumJobs) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000240 std::atomic<int> Counter(0);
241 std::atomic<bool> HasErrors(false);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000242 std::string Cmd = CloneArgsWithoutX(Args, "jobs", "workers");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000243 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000244 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000245 Pulse.detach();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000246 for (int i = 0; i < NumWorkers; i++)
247 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
248 for (auto &T : V)
249 T.join();
250 return HasErrors ? 1 : 0;
251}
252
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000253static void RssThread(Fuzzer *F, size_t RssLimitMb) {
254 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000255 SleepSeconds(1);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000256 size_t Peak = GetPeakRSSMb();
257 if (Peak > RssLimitMb)
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000258 F->RssLimitCallback();
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000259 }
260}
261
262static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
263 if (!RssLimitMb) return;
264 std::thread T(RssThread, F, RssLimitMb);
265 T.detach();
266}
267
Kostya Serebryanya016a452016-08-30 14:52:05 +0000268int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
Ivan Krasin95e82d52015-10-01 23:23:06 +0000269 Unit U = FileToVector(InputFilePath);
Kostya Serebryanya016a452016-08-30 14:52:05 +0000270 if (MaxLen && MaxLen < U.size())
271 U.resize(MaxLen);
272 F->RunOne(U.data(), U.size());
Ivan Krasin95e82d52015-10-01 23:23:06 +0000273 return 0;
274}
275
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000276static bool AllInputsAreFiles() {
277 if (Inputs->empty()) return false;
278 for (auto &Path : *Inputs)
279 if (!IsFile(Path))
280 return false;
281 return true;
282}
283
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000284int MinimizeCrashInput(const std::vector<std::string> &Args) {
285 if (Inputs->size() != 1) {
286 Printf("ERROR: -minimize_crash should be given one input file\n");
287 exit(1);
288 }
289 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
290 Printf("ERROR: you need to use -runs=N or "
291 "-max_total_time=N with -minimize_crash=1\n" );
292 exit(1);
293 }
294 std::string InputFilePath = Inputs->at(0);
295 std::string BaseCmd = CloneArgsWithoutX(Args, "minimize_crash");
296 auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
297 assert(InputPos != std::string::npos);
298 BaseCmd.erase(InputPos, InputFilePath.size() + 1);
299 // BaseCmd += " > /dev/null 2>&1 ";
300
301 std::string CurrentFilePath = InputFilePath;
302 while (true) {
303 Unit U = FileToVector(CurrentFilePath);
304 if (U.size() < 2) {
305 Printf("CRASH_MIN: '%s' is small enough\n", CurrentFilePath.c_str());
306 return 0;
307 }
308 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
309 CurrentFilePath.c_str(), U.size());
310
311 auto Cmd = BaseCmd + " " + CurrentFilePath;
312
313 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
314 int ExitCode = ExecuteCommand(Cmd);
315 if (ExitCode == 0) {
316 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
317 exit(1);
318 }
319 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
320 "it further\n",
321 CurrentFilePath.c_str(), U.size());
322
323 std::string ArtifactPath = "minimized-from-" + Hash(U);
324 Cmd += " -minimize_crash_internal_step=1 -exact_artifact_path=" +
325 ArtifactPath;
326 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
327 ExitCode = ExecuteCommand(Cmd);
328 if (ExitCode == 0) {
329 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
330 CurrentFilePath.c_str(), U.size());
331 return 0;
332 }
333 CurrentFilePath = ArtifactPath;
334 Printf("\n\n\n\n\n\n*********************************\n");
335 }
336 return 0;
337}
338
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000339int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000340 assert(Inputs->size() == 1);
341 std::string InputFilePath = Inputs->at(0);
342 Unit U = FileToVector(InputFilePath);
343 assert(U.size() > 2);
344 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000345 Corpus->AddToCorpus(U);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000346 F->SetMaxInputLen(U.size());
347 F->SetMaxMutationLen(U.size() - 1);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000348 F->Loop();
349 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
350 exit(0);
351 return 0;
352}
353
Dan Liewd3c33112016-06-02 05:48:02 +0000354int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000355 using namespace fuzzer;
Dan Liewd3c33112016-06-02 05:48:02 +0000356 assert(argc && argv && "Argument pointers cannot be nullptr");
Dan Liew1873a492016-06-07 23:32:50 +0000357 EF = new ExternalFunctions();
358 if (EF->LLVMFuzzerInitialize)
359 EF->LLVMFuzzerInitialize(argc, argv);
Dan Liewd3c33112016-06-02 05:48:02 +0000360 const std::vector<std::string> Args(*argv, *argv + *argc);
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000361 assert(!Args.empty());
362 ProgName = new std::string(Args[0]);
363 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000364 if (Flags.help) {
365 PrintHelp();
366 return 0;
367 }
368
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000369 if (Flags.minimize_crash)
370 return MinimizeCrashInput(Args);
371
Kostya Serebryany49e40902016-03-18 20:58:29 +0000372 if (Flags.close_fd_mask & 2)
373 DupAndCloseStderr();
374 if (Flags.close_fd_mask & 1)
375 CloseStdout();
376
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000377 if (Flags.jobs > 0 && Flags.workers == 0) {
378 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
379 if (Flags.workers > 1)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000380 Printf("Running %d workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000381 }
382
Kostya Serebryany016852c2015-02-19 18:45:37 +0000383 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000384 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000385
Kostya Serebryany64d24572016-03-12 01:57:04 +0000386 const size_t kMaxSaneLen = 1 << 20;
Kostya Serebryany0c5e3af2016-03-15 01:28:00 +0000387 const size_t kMinDefaultLen = 64;
Mike Aizatskyf0b3e852016-06-23 20:44:48 +0000388 FuzzingOptions Options;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000389 Options.Verbosity = Flags.verbosity;
390 Options.MaxLen = Flags.max_len;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000391 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryany54a63632016-01-29 23:30:07 +0000392 Options.TimeoutExitCode = Flags.timeout_exitcode;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000393 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000394 Options.DoCrossOver = Flags.cross_over;
395 Options.MutateDepth = Flags.mutate_depth;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000396 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000397 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryanyae5b9562016-01-15 06:24:05 +0000398 Options.UseMemcmp = Flags.use_memcmp;
Kostya Serebryanyc135b552016-07-15 23:27:19 +0000399 Options.UseMemmem = Flags.use_memmem;
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000400 Options.UseValueProfile = Flags.use_value_profile;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000401 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000402 Options.PreferSmall = Flags.prefer_small;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000403 Options.Reload = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000404 Options.OnlyASCII = Flags.only_ascii;
Mike Aizatskya9c23872015-11-12 04:38:40 +0000405 Options.OutputCSV = Flags.output_csv;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000406 Options.DetectLeaks = Flags.detect_leaks;
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000407 Options.RssLimitMb = Flags.rss_limit_mb;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000408 if (Flags.runs >= 0)
409 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000410 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000411 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000412 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000413 if (Flags.artifact_prefix)
414 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000415 if (Flags.exact_artifact_path)
416 Options.ExactArtifactPath = Flags.exact_artifact_path;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000417 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000418 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000419 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000420 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000421 if (Flags.verbosity > 0 && !Dictionary.empty())
422 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000423 bool DoPlainRun = AllInputsAreFiles();
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000424 Options.SaveArtifacts =
425 !DoPlainRun || Flags.minimize_crash_internal_step;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000426 Options.PrintNewCovPcs = Flags.print_pcs;
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000427 Options.PrintFinalStats = Flags.print_final_stats;
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000428 Options.PrintCorpusStats = Flags.print_corpus_stats;
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000429 Options.PrintCoverage = Flags.print_coverage;
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000430 Options.PruneCorpus = Flags.prune_corpus;
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000431 if (Flags.exit_on_src_pos)
432 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000433
Kostya Serebryanya3992212016-02-13 03:00:53 +0000434 unsigned Seed = Flags.seed;
435 // Initialize Seed.
436 if (Seed == 0)
437 Seed = (std::chrono::system_clock::now().time_since_epoch().count() << 10) +
438 getpid();
439 if (Flags.verbosity)
Kostya Serebryany64d24572016-03-12 01:57:04 +0000440 Printf("INFO: Seed: %u\n", Seed);
Kostya Serebryanya3992212016-02-13 03:00:53 +0000441
442 Random Rand(Seed);
Mike Aizatskyf0b3e852016-06-23 20:44:48 +0000443 MutationDispatcher MD(Rand, Options);
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000444 InputCorpus Corpus;
445 Fuzzer F(Callback, Corpus, MD, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000446
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000447 for (auto &U: Dictionary)
Kostya Serebryany476f0ce2016-01-16 03:53:32 +0000448 if (U.size() <= Word::GetMaxSize())
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000449 MD.AddWordToManualDictionary(Word(U.data(), U.size()));
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000450
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000451 StartRssThread(&F, Flags.rss_limit_mb);
452
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000453 // Timer
454 if (Flags.timeout > 0)
455 SetTimer(Flags.timeout / 2 + 1);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000456 if (Flags.handle_segv) SetSigSegvHandler();
457 if (Flags.handle_bus) SetSigBusHandler();
458 if (Flags.handle_abrt) SetSigAbrtHandler();
459 if (Flags.handle_ill) SetSigIllHandler();
460 if (Flags.handle_fpe) SetSigFpeHandler();
461 if (Flags.handle_int) SetSigIntHandler();
Kostya Serebryanyf389ae12016-03-24 21:03:58 +0000462 if (Flags.handle_term) SetSigTermHandler();
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000463
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000464 if (Flags.minimize_crash_internal_step)
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000465 return MinimizeCrashInputInternalStep(&F, &Corpus);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000466
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000467 if (DoPlainRun) {
468 Options.SaveArtifacts = false;
Kostya Serebryany9d14e4b2016-02-12 02:32:03 +0000469 int Runs = std::max(1, Flags.runs);
470 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
471 Inputs->size(), Runs);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000472 for (auto &Path : *Inputs) {
473 auto StartTime = system_clock::now();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000474 Printf("Running: %s\n", Path.c_str());
Kostya Serebryany5c3701c2016-03-04 22:35:40 +0000475 for (int Iter = 0; Iter < Runs; Iter++)
Kostya Serebryanya016a452016-08-30 14:52:05 +0000476 RunOneTest(&F, Path.c_str(), Options.MaxLen);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000477 auto StopTime = system_clock::now();
478 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000479 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000480 }
Kostya Serebryanybdb220c2016-08-15 19:44:04 +0000481 Printf("***\n"
482 "*** NOTE: fuzzing was not performed, you have only\n"
483 "*** executed the target code on a fixed set of inputs.\n"
484 "***\n");
Kostya Serebryanybaf7fd02016-05-04 20:44:50 +0000485 F.PrintFinalStats();
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000486 exit(0);
487 }
488
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000489 if (Flags.merge) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000490 if (Options.MaxLen == 0)
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000491 F.SetMaxInputLen(kMaxSaneLen);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000492 F.Merge(*Inputs);
493 exit(0);
494 }
495
Kostya Serebryany64d24572016-03-12 01:57:04 +0000496 size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000497
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000498 UnitVector InitialCorpus;
499 for (auto &Inp : *Inputs) {
500 Printf("Loading corpus dir: %s\n", Inp.c_str());
501 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr, TemporaryMaxLen);
502 }
Kostya Serebryany64d24572016-03-12 01:57:04 +0000503
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000504 if (Options.MaxLen == 0) {
505 size_t MaxLen = 0;
506 for (auto &U : InitialCorpus)
507 MaxLen = std::max(U.size(), MaxLen);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000508 F.SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000509 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000510
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000511 if (InitialCorpus.empty()) {
512 InitialCorpus.push_back(Unit());
Kostya Serebryany09087bb2016-04-18 21:14:11 +0000513 if (Options.Verbosity)
514 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
515 }
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000516 F.ShuffleAndMinimize(&InitialCorpus);
517 F.Loop();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000518
Kostya Serebryany016852c2015-02-19 18:45:37 +0000519 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000520 Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
521 F.secondsSinceProcessStartUp());
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000522 F.PrintFinalStats();
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000523
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000524 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000525}
Dan Liew1873a492016-06-07 23:32:50 +0000526
527// Storage for global ExternalFunctions object.
528ExternalFunctions *EF = nullptr;
529
Kostya Serebryany016852c2015-02-19 18:45:37 +0000530} // namespace fuzzer