blob: fb86cbc1efa36778c5a964514673709d282922f7 [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"
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>
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 Serebryany3d95dd92016-03-01 22:33:14 +000043#define FUZZER_DEPRECATED_FLAG(Name)
Kostya Serebryany52a788e2015-03-31 20:13:20 +000044#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000045#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000046#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
Kostya Serebryany016852c2015-02-19 18:45:37 +000047#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000048#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000049#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000050#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000051#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000052} Flags;
53
Craig Topper26260942015-10-18 05:15:34 +000054static const FlagDescription FlagDescriptions [] {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000055#define FUZZER_DEPRECATED_FLAG(Name) \
56 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000057#define FUZZER_FLAG_INT(Name, Default, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000058 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
59#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
60 {#Name, Description, static_cast<int>(Default), \
61 nullptr, nullptr, &Flags.Name},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000062#define FUZZER_FLAG_STRING(Name, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000063 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
Kostya Serebryany016852c2015-02-19 18:45:37 +000064#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000065#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000066#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000067#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000068#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000069};
70
71static const size_t kNumFlags =
72 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
73
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000074static std::vector<std::string> *Inputs;
75static std::string *ProgName;
Kostya Serebryany016852c2015-02-19 18:45:37 +000076
77static void PrintHelp() {
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +000078 Printf("Usage:\n");
79 auto Prog = ProgName->c_str();
80 Printf("\nTo run fuzzing pass 0 or more directories.\n");
81 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
82
83 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
84 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
85
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000086 Printf("\nFlags: (strictly in form -flag=value)\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000087 size_t MaxFlagLen = 0;
88 for (size_t F = 0; F < kNumFlags; F++)
89 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
90
91 for (size_t F = 0; F < kNumFlags; F++) {
92 const auto &D = FlagDescriptions[F];
Kostya Serebryany45299602016-09-10 00:35:30 +000093 if (strstr(D.Description, "internal flag") == D.Description) continue;
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000094 Printf(" %s", D.Name);
Kostya Serebryany016852c2015-02-19 18:45:37 +000095 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000096 Printf(" ");
97 Printf("\t");
98 Printf("%d\t%s\n", D.Default, D.Description);
Kostya Serebryany016852c2015-02-19 18:45:37 +000099 }
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000100 Printf("\nFlags starting with '--' will be ignored and "
101 "will be passed verbatim to subprocesses.\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000102}
103
104static const char *FlagValue(const char *Param, const char *Name) {
105 size_t Len = strlen(Name);
106 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
107 Param[Len + 1] == '=')
108 return &Param[Len + 2];
109 return nullptr;
110}
111
Kostya Serebryany4282d302016-01-15 00:17:37 +0000112// Avoid calling stol as it triggers a bug in clang/glibc build.
113static long MyStol(const char *Str) {
114 long Res = 0;
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000115 long Sign = 1;
116 if (*Str == '-') {
117 Str++;
118 Sign = -1;
119 }
Kostya Serebryany4282d302016-01-15 00:17:37 +0000120 for (size_t i = 0; Str[i]; i++) {
121 char Ch = Str[i];
122 if (Ch < '0' || Ch > '9')
123 return Res;
124 Res = Res * 10 + (Ch - '0');
125 }
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000126 return Res * Sign;
Kostya Serebryany4282d302016-01-15 00:17:37 +0000127}
128
Kostya Serebryany016852c2015-02-19 18:45:37 +0000129static bool ParseOneFlag(const char *Param) {
130 if (Param[0] != '-') return false;
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000131 if (Param[1] == '-') {
132 static bool PrintedWarning = false;
133 if (!PrintedWarning) {
134 PrintedWarning = true;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000135 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000136 }
Kostya Serebryanyb60397f2016-04-15 21:56:29 +0000137 for (size_t F = 0; F < kNumFlags; F++)
138 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
139 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000140 return true;
141 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000142 for (size_t F = 0; F < kNumFlags; F++) {
143 const char *Name = FlagDescriptions[F].Name;
144 const char *Str = FlagValue(Param, Name);
145 if (Str) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000146 if (FlagDescriptions[F].IntFlag) {
Kostya Serebryany4282d302016-01-15 00:17:37 +0000147 int Val = MyStol(Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000148 *FlagDescriptions[F].IntFlag = Val;
149 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000150 Printf("Flag: %s %d\n", Name, Val);;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000151 return true;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000152 } else if (FlagDescriptions[F].UIntFlag) {
153 unsigned int Val = std::stoul(Str);
154 *FlagDescriptions[F].UIntFlag = Val;
155 if (Flags.verbosity >= 2)
156 Printf("Flag: %s %u\n", Name, Val);
157 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000158 } else if (FlagDescriptions[F].StrFlag) {
159 *FlagDescriptions[F].StrFlag = Str;
160 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000161 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000162 return true;
Kostya Serebryany3d95dd92016-03-01 22:33:14 +0000163 } else { // Deprecated flag.
164 Printf("Flag: %s: deprecated, don't use\n", Name);
165 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000166 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000167 }
168 }
Kostya Serebryanyf8177312016-06-01 16:41:12 +0000169 Printf("\n\nWARNING: unrecognized flag '%s'; "
170 "use -help=1 to list all flags\n\n", Param);
171 return true;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000172}
173
174// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000175static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000176 for (size_t F = 0; F < kNumFlags; F++) {
177 if (FlagDescriptions[F].IntFlag)
178 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000179 if (FlagDescriptions[F].UIntFlag)
180 *FlagDescriptions[F].UIntFlag =
181 static_cast<unsigned int>(FlagDescriptions[F].Default);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000182 if (FlagDescriptions[F].StrFlag)
183 *FlagDescriptions[F].StrFlag = nullptr;
184 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000185 Inputs = new std::vector<std::string>;
186 for (size_t A = 1; A < Args.size(); A++) {
187 if (ParseOneFlag(Args[A].c_str())) continue;
188 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000189 }
190}
191
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000192static std::mutex Mu;
193
194static void PulseThread() {
195 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000196 SleepSeconds(600);
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000197 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000198 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000199 }
200}
201
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000202static void WorkerThread(const std::string &Cmd, std::atomic<unsigned> *Counter,
203 unsigned NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000204 while (true) {
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000205 unsigned C = (*Counter)++;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000206 if (C >= NumJobs) break;
207 std::string Log = "fuzz-" + std::to_string(C) + ".log";
208 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
209 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000210 Printf("%s", ToRun.c_str());
Hans Wennborge6319962016-04-11 20:35:17 +0000211 int ExitCode = ExecuteCommand(ToRun);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000212 if (ExitCode != 0)
213 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000214 std::lock_guard<std::mutex> Lock(Mu);
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000215 Printf("================== Job %u exited with exit code %d ============\n",
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000216 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000217 fuzzer::CopyFileToErr(Log);
218 }
219}
220
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000221std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
222 const char *X1, const char *X2) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000223 std::string Cmd;
224 for (auto &S : Args) {
225 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
226 continue;
227 Cmd += S + " ";
228 }
229 return Cmd;
230}
231
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000232static int RunInMultipleProcesses(const std::vector<std::string> &Args,
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000233 unsigned NumWorkers, unsigned NumJobs) {
234 std::atomic<unsigned> Counter(0);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000235 std::atomic<bool> HasErrors(false);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000236 std::string Cmd = CloneArgsWithoutX(Args, "jobs", "workers");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000237 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000238 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000239 Pulse.detach();
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000240 for (unsigned i = 0; i < NumWorkers; i++)
Kostya Serebryany016852c2015-02-19 18:45:37 +0000241 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
242 for (auto &T : V)
243 T.join();
244 return HasErrors ? 1 : 0;
245}
246
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000247static void RssThread(Fuzzer *F, size_t RssLimitMb) {
248 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000249 SleepSeconds(1);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000250 size_t Peak = GetPeakRSSMb();
251 if (Peak > RssLimitMb)
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000252 F->RssLimitCallback();
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000253 }
254}
255
256static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
257 if (!RssLimitMb) return;
258 std::thread T(RssThread, F, RssLimitMb);
259 T.detach();
260}
261
Kostya Serebryanya016a452016-08-30 14:52:05 +0000262int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
Ivan Krasin95e82d52015-10-01 23:23:06 +0000263 Unit U = FileToVector(InputFilePath);
Kostya Serebryanya016a452016-08-30 14:52:05 +0000264 if (MaxLen && MaxLen < U.size())
265 U.resize(MaxLen);
266 F->RunOne(U.data(), U.size());
Kostya Serebryanybb59ef72016-10-18 18:38:08 +0000267 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
Ivan Krasin95e82d52015-10-01 23:23:06 +0000268 return 0;
269}
270
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000271static bool AllInputsAreFiles() {
272 if (Inputs->empty()) return false;
273 for (auto &Path : *Inputs)
274 if (!IsFile(Path))
275 return false;
276 return true;
277}
278
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000279int MinimizeCrashInput(const std::vector<std::string> &Args) {
280 if (Inputs->size() != 1) {
281 Printf("ERROR: -minimize_crash should be given one input file\n");
282 exit(1);
283 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000284 std::string InputFilePath = Inputs->at(0);
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000285 std::string BaseCmd =
286 CloneArgsWithoutX(Args, "minimize_crash", "exact_artifact_path");
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000287 auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
288 assert(InputPos != std::string::npos);
289 BaseCmd.erase(InputPos, InputFilePath.size() + 1);
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000290 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
291 Printf("INFO: you need to specify -runs=N or "
292 "-max_total_time=N with -minimize_crash=1\n"
293 "INFO: defaulting to -max_total_time=600\n");
294 BaseCmd += " -max_total_time=600";
295 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000296 // BaseCmd += " > /dev/null 2>&1 ";
297
298 std::string CurrentFilePath = InputFilePath;
299 while (true) {
300 Unit U = FileToVector(CurrentFilePath);
301 if (U.size() < 2) {
302 Printf("CRASH_MIN: '%s' is small enough\n", CurrentFilePath.c_str());
303 return 0;
304 }
305 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
306 CurrentFilePath.c_str(), U.size());
307
308 auto Cmd = BaseCmd + " " + CurrentFilePath;
309
310 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
311 int ExitCode = ExecuteCommand(Cmd);
312 if (ExitCode == 0) {
313 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
314 exit(1);
315 }
316 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
317 "it further\n",
318 CurrentFilePath.c_str(), U.size());
319
320 std::string ArtifactPath = "minimized-from-" + Hash(U);
321 Cmd += " -minimize_crash_internal_step=1 -exact_artifact_path=" +
322 ArtifactPath;
323 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
324 ExitCode = ExecuteCommand(Cmd);
325 if (ExitCode == 0) {
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000326 if (Flags.exact_artifact_path) {
327 CurrentFilePath = Flags.exact_artifact_path;
328 WriteToFile(U, CurrentFilePath);
329 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000330 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
331 CurrentFilePath.c_str(), U.size());
332 return 0;
333 }
334 CurrentFilePath = ArtifactPath;
335 Printf("\n\n\n\n\n\n*********************************\n");
336 }
337 return 0;
338}
339
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000340int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000341 assert(Inputs->size() == 1);
342 std::string InputFilePath = Inputs->at(0);
343 Unit U = FileToVector(InputFilePath);
344 assert(U.size() > 2);
345 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000346 Corpus->AddToCorpus(U, 0);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000347 F->SetMaxInputLen(U.size());
348 F->SetMaxMutationLen(U.size() - 1);
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000349 F->MinimizeCrashLoop(U);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000350 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
351 exit(0);
352 return 0;
353}
354
Dan Liewd3c33112016-06-02 05:48:02 +0000355int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000356 using namespace fuzzer;
Dan Liewd3c33112016-06-02 05:48:02 +0000357 assert(argc && argv && "Argument pointers cannot be nullptr");
Dan Liew1873a492016-06-07 23:32:50 +0000358 EF = new ExternalFunctions();
359 if (EF->LLVMFuzzerInitialize)
360 EF->LLVMFuzzerInitialize(argc, argv);
Dan Liewd3c33112016-06-02 05:48:02 +0000361 const std::vector<std::string> Args(*argv, *argv + *argc);
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000362 assert(!Args.empty());
363 ProgName = new std::string(Args[0]);
364 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000365 if (Flags.help) {
366 PrintHelp();
367 return 0;
368 }
369
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000370 if (Flags.minimize_crash)
371 return MinimizeCrashInput(Args);
372
Kostya Serebryany49e40902016-03-18 20:58:29 +0000373 if (Flags.close_fd_mask & 2)
374 DupAndCloseStderr();
375 if (Flags.close_fd_mask & 1)
376 CloseStdout();
377
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000378 if (Flags.jobs > 0 && Flags.workers == 0) {
379 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
380 if (Flags.workers > 1)
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000381 Printf("Running %u workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000382 }
383
Kostya Serebryany016852c2015-02-19 18:45:37 +0000384 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000385 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000386
Kostya Serebryany64d24572016-03-12 01:57:04 +0000387 const size_t kMaxSaneLen = 1 << 20;
Kostya Serebryany0c5e3af2016-03-15 01:28:00 +0000388 const size_t kMinDefaultLen = 64;
Mike Aizatskyf0b3e852016-06-23 20:44:48 +0000389 FuzzingOptions Options;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000390 Options.Verbosity = Flags.verbosity;
391 Options.MaxLen = Flags.max_len;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000392 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryany8a569172016-11-03 19:31:18 +0000393 Options.ErrorExitCode = Flags.error_exitcode;
Kostya Serebryany54a63632016-01-29 23:30:07 +0000394 Options.TimeoutExitCode = Flags.timeout_exitcode;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000395 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000396 Options.DoCrossOver = Flags.cross_over;
397 Options.MutateDepth = Flags.mutate_depth;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000398 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000399 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryanyae5b9562016-01-15 06:24:05 +0000400 Options.UseMemcmp = Flags.use_memcmp;
Kostya Serebryanyc135b552016-07-15 23:27:19 +0000401 Options.UseMemmem = Flags.use_memmem;
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000402 Options.UseCmp = Flags.use_cmp;
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000403 Options.UseValueProfile = Flags.use_value_profile;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000404 Options.Shrink = Flags.shrink;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000405 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000406 Options.PreferSmall = Flags.prefer_small;
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000407 Options.ReloadIntervalSec = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000408 Options.OnlyASCII = Flags.only_ascii;
Mike Aizatskya9c23872015-11-12 04:38:40 +0000409 Options.OutputCSV = Flags.output_csv;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000410 Options.DetectLeaks = Flags.detect_leaks;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000411 Options.TraceMalloc = Flags.trace_malloc;
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000412 Options.RssLimitMb = Flags.rss_limit_mb;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000413 if (Flags.runs >= 0)
414 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000415 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000416 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000417 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000418 if (Flags.artifact_prefix)
419 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000420 if (Flags.exact_artifact_path)
421 Options.ExactArtifactPath = Flags.exact_artifact_path;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000422 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000423 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000424 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000425 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000426 if (Flags.verbosity > 0 && !Dictionary.empty())
427 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000428 bool DoPlainRun = AllInputsAreFiles();
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000429 Options.SaveArtifacts =
430 !DoPlainRun || Flags.minimize_crash_internal_step;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000431 Options.PrintNewCovPcs = Flags.print_pcs;
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000432 Options.PrintFinalStats = Flags.print_final_stats;
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000433 Options.PrintCorpusStats = Flags.print_corpus_stats;
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000434 Options.PrintCoverage = Flags.print_coverage;
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000435 if (Flags.exit_on_src_pos)
436 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000437 if (Flags.exit_on_item)
438 Options.ExitOnItem = Flags.exit_on_item;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000439
Kostya Serebryanya3992212016-02-13 03:00:53 +0000440 unsigned Seed = Flags.seed;
441 // Initialize Seed.
442 if (Seed == 0)
443 Seed = (std::chrono::system_clock::now().time_since_epoch().count() << 10) +
Zachary Turner6fa57ad2016-12-02 23:02:01 +0000444 GetPid();
Kostya Serebryanya3992212016-02-13 03:00:53 +0000445 if (Flags.verbosity)
Kostya Serebryany64d24572016-03-12 01:57:04 +0000446 Printf("INFO: Seed: %u\n", Seed);
Kostya Serebryanya3992212016-02-13 03:00:53 +0000447
448 Random Rand(Seed);
Kostya Serebryany6c778112016-11-14 19:21:38 +0000449 auto *MD = new MutationDispatcher(Rand, Options);
450 auto *Corpus = new InputCorpus(Options.OutputCorpus);
451 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000452
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000453 for (auto &U: Dictionary)
Kostya Serebryany476f0ce2016-01-16 03:53:32 +0000454 if (U.size() <= Word::GetMaxSize())
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000455 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000456
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000457 StartRssThread(F, Flags.rss_limit_mb);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000458
Marcos Pividoric59b6922016-12-13 17:45:20 +0000459 Options.HandleAbrt = Flags.handle_abrt;
460 Options.HandleBus = Flags.handle_bus;
461 Options.HandleFpe = Flags.handle_fpe;
462 Options.HandleIll = Flags.handle_ill;
463 Options.HandleInt = Flags.handle_int;
464 Options.HandleSegv = Flags.handle_segv;
465 Options.HandleTerm = Flags.handle_term;
466 SetSignalHandler(Options);
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000467
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000468 if (Flags.minimize_crash_internal_step)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000469 return MinimizeCrashInputInternalStep(F, Corpus);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000470
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000471 if (DoPlainRun) {
472 Options.SaveArtifacts = false;
Kostya Serebryany9d14e4b2016-02-12 02:32:03 +0000473 int Runs = std::max(1, Flags.runs);
474 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
475 Inputs->size(), Runs);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000476 for (auto &Path : *Inputs) {
477 auto StartTime = system_clock::now();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000478 Printf("Running: %s\n", Path.c_str());
Kostya Serebryany5c3701c2016-03-04 22:35:40 +0000479 for (int Iter = 0; Iter < Runs; Iter++)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000480 RunOneTest(F, Path.c_str(), Options.MaxLen);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000481 auto StopTime = system_clock::now();
482 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000483 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000484 }
Kostya Serebryanybdb220c2016-08-15 19:44:04 +0000485 Printf("***\n"
486 "*** NOTE: fuzzing was not performed, you have only\n"
487 "*** executed the target code on a fixed set of inputs.\n"
488 "***\n");
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000489 F->PrintFinalStats();
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000490 exit(0);
491 }
492
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000493 if (Flags.merge) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000494 if (Options.MaxLen == 0)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000495 F->SetMaxInputLen(kMaxSaneLen);
496 F->Merge(*Inputs);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000497 exit(0);
498 }
499
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000500 if (Flags.experimental_merge) {
501 if (Options.MaxLen == 0)
502 F->SetMaxInputLen(kMaxSaneLen);
503 if (Flags.merge_control_file)
504 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
505 else
506 F->CrashResistantMerge(Args, *Inputs);
507 exit(0);
508 }
509
Kostya Serebryany64d24572016-03-12 01:57:04 +0000510 size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000511
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000512 UnitVector InitialCorpus;
513 for (auto &Inp : *Inputs) {
514 Printf("Loading corpus dir: %s\n", Inp.c_str());
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000515 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
516 TemporaryMaxLen, /*ExitOnError=*/false);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000517 }
Kostya Serebryany64d24572016-03-12 01:57:04 +0000518
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000519 if (Options.MaxLen == 0) {
520 size_t MaxLen = 0;
521 for (auto &U : InitialCorpus)
522 MaxLen = std::max(U.size(), MaxLen);
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000523 F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000524 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000525
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000526 if (InitialCorpus.empty()) {
Kostya Serebryany53c894d2016-11-12 02:27:21 +0000527 InitialCorpus.push_back(Unit({'\n'})); // Valid ASCII input.
Kostya Serebryany09087bb2016-04-18 21:14:11 +0000528 if (Options.Verbosity)
529 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
530 }
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000531 F->ShuffleAndMinimize(&InitialCorpus);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000532 InitialCorpus.clear(); // Don't need this memory any more.
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000533 F->Loop();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000534
Kostya Serebryany016852c2015-02-19 18:45:37 +0000535 if (Flags.verbosity)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000536 Printf("Done %d runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
537 F->secondsSinceProcessStartUp());
538 F->PrintFinalStats();
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000539
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000540 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000541}
Dan Liew1873a492016-06-07 23:32:50 +0000542
543// Storage for global ExternalFunctions object.
544ExternalFunctions *EF = nullptr;
545
Kostya Serebryany016852c2015-02-19 18:45:37 +0000546} // namespace fuzzer