blob: ab1fdf76ebf47a658b1caae9350e6fc522669a8c [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"
Zachary Turner24a148b2016-11-30 19:06:14 +000015#include "FuzzerIO.h"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000016#include "FuzzerMutate.h"
17#include "FuzzerRandom.h"
Kostya Serebryany016852c2015-02-19 18:45:37 +000018
Mehdi Aminib550cb12016-04-18 09:17:29 +000019#include <algorithm>
Kostya Serebryany016852c2015-02-19 18:45:37 +000020#include <atomic>
Mehdi Aminib550cb12016-04-18 09:17:29 +000021#include <chrono>
22#include <cstring>
Kostya Serebryany016852c2015-02-19 18:45:37 +000023#include <mutex>
Kostya Serebryany52a788e2015-03-31 20:13:20 +000024#include <string>
Mehdi Aminib550cb12016-04-18 09:17:29 +000025#include <thread>
26#include <unistd.h>
Kostya Serebryany016852c2015-02-19 18:45:37 +000027
Kostya Serebryany4282d302016-01-15 00:17:37 +000028// This function should be present in the libFuzzer so that the client
29// binary can test for its existence.
30extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
31
Kostya Serebryany016852c2015-02-19 18:45:37 +000032namespace fuzzer {
33
34// Program arguments.
35struct FlagDescription {
36 const char *Name;
37 const char *Description;
38 int Default;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000039 int *IntFlag;
40 const char **StrFlag;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000041 unsigned int *UIntFlag;
Kostya Serebryany016852c2015-02-19 18:45:37 +000042};
43
44struct {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000045#define FUZZER_DEPRECATED_FLAG(Name)
Kostya Serebryany52a788e2015-03-31 20:13:20 +000046#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000047#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000048#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
Kostya Serebryany016852c2015-02-19 18:45:37 +000049#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000050#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000051#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000052#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000053#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000054} Flags;
55
Craig Topper26260942015-10-18 05:15:34 +000056static const FlagDescription FlagDescriptions [] {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000057#define FUZZER_DEPRECATED_FLAG(Name) \
58 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000059#define FUZZER_FLAG_INT(Name, Default, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000060 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
61#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
62 {#Name, Description, static_cast<int>(Default), \
63 nullptr, nullptr, &Flags.Name},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000064#define FUZZER_FLAG_STRING(Name, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000065 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
Kostya Serebryany016852c2015-02-19 18:45:37 +000066#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000067#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000068#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000069#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000070#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000071};
72
73static const size_t kNumFlags =
74 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
75
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000076static std::vector<std::string> *Inputs;
77static std::string *ProgName;
Kostya Serebryany016852c2015-02-19 18:45:37 +000078
79static void PrintHelp() {
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +000080 Printf("Usage:\n");
81 auto Prog = ProgName->c_str();
82 Printf("\nTo run fuzzing pass 0 or more directories.\n");
83 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
84
85 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
86 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
87
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000088 Printf("\nFlags: (strictly in form -flag=value)\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000089 size_t MaxFlagLen = 0;
90 for (size_t F = 0; F < kNumFlags; F++)
91 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
92
93 for (size_t F = 0; F < kNumFlags; F++) {
94 const auto &D = FlagDescriptions[F];
Kostya Serebryany45299602016-09-10 00:35:30 +000095 if (strstr(D.Description, "internal flag") == D.Description) continue;
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000096 Printf(" %s", D.Name);
Kostya Serebryany016852c2015-02-19 18:45:37 +000097 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000098 Printf(" ");
99 Printf("\t");
100 Printf("%d\t%s\n", D.Default, D.Description);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000101 }
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000102 Printf("\nFlags starting with '--' will be ignored and "
103 "will be passed verbatim to subprocesses.\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000104}
105
106static const char *FlagValue(const char *Param, const char *Name) {
107 size_t Len = strlen(Name);
108 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
109 Param[Len + 1] == '=')
110 return &Param[Len + 2];
111 return nullptr;
112}
113
Kostya Serebryany4282d302016-01-15 00:17:37 +0000114// Avoid calling stol as it triggers a bug in clang/glibc build.
115static long MyStol(const char *Str) {
116 long Res = 0;
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000117 long Sign = 1;
118 if (*Str == '-') {
119 Str++;
120 Sign = -1;
121 }
Kostya Serebryany4282d302016-01-15 00:17:37 +0000122 for (size_t i = 0; Str[i]; i++) {
123 char Ch = Str[i];
124 if (Ch < '0' || Ch > '9')
125 return Res;
126 Res = Res * 10 + (Ch - '0');
127 }
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000128 return Res * Sign;
Kostya Serebryany4282d302016-01-15 00:17:37 +0000129}
130
Kostya Serebryany016852c2015-02-19 18:45:37 +0000131static bool ParseOneFlag(const char *Param) {
132 if (Param[0] != '-') return false;
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000133 if (Param[1] == '-') {
134 static bool PrintedWarning = false;
135 if (!PrintedWarning) {
136 PrintedWarning = true;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000137 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000138 }
Kostya Serebryanyb60397f2016-04-15 21:56:29 +0000139 for (size_t F = 0; F < kNumFlags; F++)
140 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
141 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000142 return true;
143 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000144 for (size_t F = 0; F < kNumFlags; F++) {
145 const char *Name = FlagDescriptions[F].Name;
146 const char *Str = FlagValue(Param, Name);
147 if (Str) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000148 if (FlagDescriptions[F].IntFlag) {
Kostya Serebryany4282d302016-01-15 00:17:37 +0000149 int Val = MyStol(Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000150 *FlagDescriptions[F].IntFlag = Val;
151 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000152 Printf("Flag: %s %d\n", Name, Val);;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000153 return true;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000154 } else if (FlagDescriptions[F].UIntFlag) {
155 unsigned int Val = std::stoul(Str);
156 *FlagDescriptions[F].UIntFlag = Val;
157 if (Flags.verbosity >= 2)
158 Printf("Flag: %s %u\n", Name, Val);
159 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000160 } else if (FlagDescriptions[F].StrFlag) {
161 *FlagDescriptions[F].StrFlag = Str;
162 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000163 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000164 return true;
Kostya Serebryany3d95dd92016-03-01 22:33:14 +0000165 } else { // Deprecated flag.
166 Printf("Flag: %s: deprecated, don't use\n", Name);
167 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000168 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000169 }
170 }
Kostya Serebryanyf8177312016-06-01 16:41:12 +0000171 Printf("\n\nWARNING: unrecognized flag '%s'; "
172 "use -help=1 to list all flags\n\n", Param);
173 return true;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000174}
175
176// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000177static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000178 for (size_t F = 0; F < kNumFlags; F++) {
179 if (FlagDescriptions[F].IntFlag)
180 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000181 if (FlagDescriptions[F].UIntFlag)
182 *FlagDescriptions[F].UIntFlag =
183 static_cast<unsigned int>(FlagDescriptions[F].Default);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000184 if (FlagDescriptions[F].StrFlag)
185 *FlagDescriptions[F].StrFlag = nullptr;
186 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000187 Inputs = new std::vector<std::string>;
188 for (size_t A = 1; A < Args.size(); A++) {
189 if (ParseOneFlag(Args[A].c_str())) continue;
190 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000191 }
192}
193
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000194static std::mutex Mu;
195
196static void PulseThread() {
197 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000198 SleepSeconds(600);
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000199 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000200 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000201 }
202}
203
Kostya Serebryany016852c2015-02-19 18:45:37 +0000204static void WorkerThread(const std::string &Cmd, std::atomic<int> *Counter,
205 int NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000206 while (true) {
207 int C = (*Counter)++;
208 if (C >= NumJobs) break;
209 std::string Log = "fuzz-" + std::to_string(C) + ".log";
210 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
211 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000212 Printf("%s", ToRun.c_str());
Hans Wennborge6319962016-04-11 20:35:17 +0000213 int ExitCode = ExecuteCommand(ToRun);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000214 if (ExitCode != 0)
215 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000216 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000217 Printf("================== Job %d exited with exit code %d ============\n",
218 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000219 fuzzer::CopyFileToErr(Log);
220 }
221}
222
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000223static std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
224 const char *X1, const char *X2) {
225 std::string Cmd;
226 for (auto &S : Args) {
227 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
228 continue;
229 Cmd += S + " ";
230 }
231 return Cmd;
232}
233
234static std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
235 const char *X) {
236 return CloneArgsWithoutX(Args, X, X);
237}
238
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000239static int RunInMultipleProcesses(const std::vector<std::string> &Args,
240 int NumWorkers, int NumJobs) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000241 std::atomic<int> Counter(0);
242 std::atomic<bool> HasErrors(false);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000243 std::string Cmd = CloneArgsWithoutX(Args, "jobs", "workers");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000244 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000245 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000246 Pulse.detach();
Kostya Serebryany016852c2015-02-19 18:45:37 +0000247 for (int i = 0; i < NumWorkers; i++)
248 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
249 for (auto &T : V)
250 T.join();
251 return HasErrors ? 1 : 0;
252}
253
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000254static void RssThread(Fuzzer *F, size_t RssLimitMb) {
255 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000256 SleepSeconds(1);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000257 size_t Peak = GetPeakRSSMb();
258 if (Peak > RssLimitMb)
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000259 F->RssLimitCallback();
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000260 }
261}
262
263static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
264 if (!RssLimitMb) return;
265 std::thread T(RssThread, F, RssLimitMb);
266 T.detach();
267}
268
Kostya Serebryanya016a452016-08-30 14:52:05 +0000269int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
Ivan Krasin95e82d52015-10-01 23:23:06 +0000270 Unit U = FileToVector(InputFilePath);
Kostya Serebryanya016a452016-08-30 14:52:05 +0000271 if (MaxLen && MaxLen < U.size())
272 U.resize(MaxLen);
273 F->RunOne(U.data(), U.size());
Kostya Serebryanybb59ef72016-10-18 18:38:08 +0000274 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
Ivan Krasin95e82d52015-10-01 23:23:06 +0000275 return 0;
276}
277
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000278static bool AllInputsAreFiles() {
279 if (Inputs->empty()) return false;
280 for (auto &Path : *Inputs)
281 if (!IsFile(Path))
282 return false;
283 return true;
284}
285
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000286int MinimizeCrashInput(const std::vector<std::string> &Args) {
287 if (Inputs->size() != 1) {
288 Printf("ERROR: -minimize_crash should be given one input file\n");
289 exit(1);
290 }
291 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
292 Printf("ERROR: you need to use -runs=N or "
293 "-max_total_time=N with -minimize_crash=1\n" );
294 exit(1);
295 }
296 std::string InputFilePath = Inputs->at(0);
297 std::string BaseCmd = CloneArgsWithoutX(Args, "minimize_crash");
298 auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
299 assert(InputPos != std::string::npos);
300 BaseCmd.erase(InputPos, InputFilePath.size() + 1);
301 // BaseCmd += " > /dev/null 2>&1 ";
302
303 std::string CurrentFilePath = InputFilePath;
304 while (true) {
305 Unit U = FileToVector(CurrentFilePath);
306 if (U.size() < 2) {
307 Printf("CRASH_MIN: '%s' is small enough\n", CurrentFilePath.c_str());
308 return 0;
309 }
310 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
311 CurrentFilePath.c_str(), U.size());
312
313 auto Cmd = BaseCmd + " " + CurrentFilePath;
314
315 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
316 int ExitCode = ExecuteCommand(Cmd);
317 if (ExitCode == 0) {
318 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
319 exit(1);
320 }
321 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
322 "it further\n",
323 CurrentFilePath.c_str(), U.size());
324
325 std::string ArtifactPath = "minimized-from-" + Hash(U);
326 Cmd += " -minimize_crash_internal_step=1 -exact_artifact_path=" +
327 ArtifactPath;
328 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
329 ExitCode = ExecuteCommand(Cmd);
330 if (ExitCode == 0) {
331 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
332 CurrentFilePath.c_str(), U.size());
333 return 0;
334 }
335 CurrentFilePath = ArtifactPath;
336 Printf("\n\n\n\n\n\n*********************************\n");
337 }
338 return 0;
339}
340
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000341int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000342 assert(Inputs->size() == 1);
343 std::string InputFilePath = Inputs->at(0);
344 Unit U = FileToVector(InputFilePath);
345 assert(U.size() > 2);
346 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000347 Corpus->AddToCorpus(U, 0);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000348 F->SetMaxInputLen(U.size());
349 F->SetMaxMutationLen(U.size() - 1);
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000350 F->MinimizeCrashLoop(U);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000351 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
352 exit(0);
353 return 0;
354}
355
Dan Liewd3c33112016-06-02 05:48:02 +0000356int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000357 using namespace fuzzer;
Dan Liewd3c33112016-06-02 05:48:02 +0000358 assert(argc && argv && "Argument pointers cannot be nullptr");
Dan Liew1873a492016-06-07 23:32:50 +0000359 EF = new ExternalFunctions();
360 if (EF->LLVMFuzzerInitialize)
361 EF->LLVMFuzzerInitialize(argc, argv);
Dan Liewd3c33112016-06-02 05:48:02 +0000362 const std::vector<std::string> Args(*argv, *argv + *argc);
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000363 assert(!Args.empty());
364 ProgName = new std::string(Args[0]);
365 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000366 if (Flags.help) {
367 PrintHelp();
368 return 0;
369 }
370
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000371 if (Flags.minimize_crash)
372 return MinimizeCrashInput(Args);
373
Kostya Serebryany49e40902016-03-18 20:58:29 +0000374 if (Flags.close_fd_mask & 2)
375 DupAndCloseStderr();
376 if (Flags.close_fd_mask & 1)
377 CloseStdout();
378
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000379 if (Flags.jobs > 0 && Flags.workers == 0) {
380 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
381 if (Flags.workers > 1)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000382 Printf("Running %d workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000383 }
384
Kostya Serebryany016852c2015-02-19 18:45:37 +0000385 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000386 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000387
Kostya Serebryany64d24572016-03-12 01:57:04 +0000388 const size_t kMaxSaneLen = 1 << 20;
Kostya Serebryany0c5e3af2016-03-15 01:28:00 +0000389 const size_t kMinDefaultLen = 64;
Mike Aizatskyf0b3e852016-06-23 20:44:48 +0000390 FuzzingOptions Options;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000391 Options.Verbosity = Flags.verbosity;
392 Options.MaxLen = Flags.max_len;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000393 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryany8a569172016-11-03 19:31:18 +0000394 Options.ErrorExitCode = Flags.error_exitcode;
Kostya Serebryany54a63632016-01-29 23:30:07 +0000395 Options.TimeoutExitCode = Flags.timeout_exitcode;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000396 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000397 Options.DoCrossOver = Flags.cross_over;
398 Options.MutateDepth = Flags.mutate_depth;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000399 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000400 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryanyae5b9562016-01-15 06:24:05 +0000401 Options.UseMemcmp = Flags.use_memcmp;
Kostya Serebryanyc135b552016-07-15 23:27:19 +0000402 Options.UseMemmem = Flags.use_memmem;
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000403 Options.UseCmp = Flags.use_cmp;
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000404 Options.UseValueProfile = Flags.use_value_profile;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000405 Options.Shrink = Flags.shrink;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000406 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000407 Options.PreferSmall = Flags.prefer_small;
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000408 Options.ReloadIntervalSec = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000409 Options.OnlyASCII = Flags.only_ascii;
Mike Aizatskya9c23872015-11-12 04:38:40 +0000410 Options.OutputCSV = Flags.output_csv;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000411 Options.DetectLeaks = Flags.detect_leaks;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000412 Options.TraceMalloc = Flags.trace_malloc;
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000413 Options.RssLimitMb = Flags.rss_limit_mb;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000414 if (Flags.runs >= 0)
415 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000416 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000417 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000418 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000419 if (Flags.artifact_prefix)
420 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000421 if (Flags.exact_artifact_path)
422 Options.ExactArtifactPath = Flags.exact_artifact_path;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000423 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000424 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000425 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000426 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000427 if (Flags.verbosity > 0 && !Dictionary.empty())
428 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000429 bool DoPlainRun = AllInputsAreFiles();
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000430 Options.SaveArtifacts =
431 !DoPlainRun || Flags.minimize_crash_internal_step;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000432 Options.PrintNewCovPcs = Flags.print_pcs;
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000433 Options.PrintFinalStats = Flags.print_final_stats;
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000434 Options.PrintCorpusStats = Flags.print_corpus_stats;
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000435 Options.PrintCoverage = Flags.print_coverage;
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000436 if (Flags.exit_on_src_pos)
437 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000438 if (Flags.exit_on_item)
439 Options.ExitOnItem = Flags.exit_on_item;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000440
Kostya Serebryanya3992212016-02-13 03:00:53 +0000441 unsigned Seed = Flags.seed;
442 // Initialize Seed.
443 if (Seed == 0)
444 Seed = (std::chrono::system_clock::now().time_since_epoch().count() << 10) +
445 getpid();
446 if (Flags.verbosity)
Kostya Serebryany64d24572016-03-12 01:57:04 +0000447 Printf("INFO: Seed: %u\n", Seed);
Kostya Serebryanya3992212016-02-13 03:00:53 +0000448
449 Random Rand(Seed);
Kostya Serebryany6c778112016-11-14 19:21:38 +0000450 auto *MD = new MutationDispatcher(Rand, Options);
451 auto *Corpus = new InputCorpus(Options.OutputCorpus);
452 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000453
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000454 for (auto &U: Dictionary)
Kostya Serebryany476f0ce2016-01-16 03:53:32 +0000455 if (U.size() <= Word::GetMaxSize())
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000456 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000457
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000458 StartRssThread(F, Flags.rss_limit_mb);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000459
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000460 // Timer
461 if (Flags.timeout > 0)
462 SetTimer(Flags.timeout / 2 + 1);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000463 if (Flags.handle_segv) SetSigSegvHandler();
464 if (Flags.handle_bus) SetSigBusHandler();
465 if (Flags.handle_abrt) SetSigAbrtHandler();
466 if (Flags.handle_ill) SetSigIllHandler();
467 if (Flags.handle_fpe) SetSigFpeHandler();
468 if (Flags.handle_int) SetSigIntHandler();
Kostya Serebryanyf389ae12016-03-24 21:03:58 +0000469 if (Flags.handle_term) SetSigTermHandler();
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000470
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000471 if (Flags.minimize_crash_internal_step)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000472 return MinimizeCrashInputInternalStep(F, Corpus);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000473
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000474 if (DoPlainRun) {
475 Options.SaveArtifacts = false;
Kostya Serebryany9d14e4b2016-02-12 02:32:03 +0000476 int Runs = std::max(1, Flags.runs);
477 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
478 Inputs->size(), Runs);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000479 for (auto &Path : *Inputs) {
480 auto StartTime = system_clock::now();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000481 Printf("Running: %s\n", Path.c_str());
Kostya Serebryany5c3701c2016-03-04 22:35:40 +0000482 for (int Iter = 0; Iter < Runs; Iter++)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000483 RunOneTest(F, Path.c_str(), Options.MaxLen);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000484 auto StopTime = system_clock::now();
485 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000486 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000487 }
Kostya Serebryanybdb220c2016-08-15 19:44:04 +0000488 Printf("***\n"
489 "*** NOTE: fuzzing was not performed, you have only\n"
490 "*** executed the target code on a fixed set of inputs.\n"
491 "***\n");
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000492 F->PrintFinalStats();
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000493 exit(0);
494 }
495
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000496 if (Flags.merge) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000497 if (Options.MaxLen == 0)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000498 F->SetMaxInputLen(kMaxSaneLen);
499 F->Merge(*Inputs);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000500 exit(0);
501 }
502
Kostya Serebryany64d24572016-03-12 01:57:04 +0000503 size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000504
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000505 UnitVector InitialCorpus;
506 for (auto &Inp : *Inputs) {
507 Printf("Loading corpus dir: %s\n", Inp.c_str());
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000508 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
509 TemporaryMaxLen, /*ExitOnError=*/false);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000510 }
Kostya Serebryany64d24572016-03-12 01:57:04 +0000511
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000512 if (Options.MaxLen == 0) {
513 size_t MaxLen = 0;
514 for (auto &U : InitialCorpus)
515 MaxLen = std::max(U.size(), MaxLen);
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000516 F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000517 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000518
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000519 if (InitialCorpus.empty()) {
Kostya Serebryany53c894d2016-11-12 02:27:21 +0000520 InitialCorpus.push_back(Unit({'\n'})); // Valid ASCII input.
Kostya Serebryany09087bb2016-04-18 21:14:11 +0000521 if (Options.Verbosity)
522 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
523 }
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000524 F->ShuffleAndMinimize(&InitialCorpus);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000525 InitialCorpus.clear(); // Don't need this memory any more.
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000526 F->Loop();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000527
Kostya Serebryany016852c2015-02-19 18:45:37 +0000528 if (Flags.verbosity)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000529 Printf("Done %d runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
530 F->secondsSinceProcessStartUp());
531 F->PrintFinalStats();
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000532
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000533 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000534}
Dan Liew1873a492016-06-07 23:32:50 +0000535
536// Storage for global ExternalFunctions object.
537ExternalFunctions *EF = nullptr;
538
Kostya Serebryany016852c2015-02-19 18:45:37 +0000539} // namespace fuzzer