blob: f4f1a4d47d14f79d8853bba615ee54790988dfba [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>
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
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000203static void WorkerThread(const std::string &Cmd, std::atomic<unsigned> *Counter,
204 unsigned NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000205 while (true) {
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000206 unsigned C = (*Counter)++;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000207 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);
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000216 Printf("================== Job %u exited with exit code %d ============\n",
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000217 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000218 fuzzer::CopyFileToErr(Log);
219 }
220}
221
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000222std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
223 const char *X1, const char *X2) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000224 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
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000233static int RunInMultipleProcesses(const std::vector<std::string> &Args,
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000234 unsigned NumWorkers, unsigned NumJobs) {
235 std::atomic<unsigned> Counter(0);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000236 std::atomic<bool> HasErrors(false);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000237 std::string Cmd = CloneArgsWithoutX(Args, "jobs", "workers");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000238 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000239 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000240 Pulse.detach();
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000241 for (unsigned i = 0; i < NumWorkers; i++)
Kostya Serebryany016852c2015-02-19 18:45:37 +0000242 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
243 for (auto &T : V)
244 T.join();
245 return HasErrors ? 1 : 0;
246}
247
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000248static void RssThread(Fuzzer *F, size_t RssLimitMb) {
249 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000250 SleepSeconds(1);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000251 size_t Peak = GetPeakRSSMb();
252 if (Peak > RssLimitMb)
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000253 F->RssLimitCallback();
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000254 }
255}
256
257static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
258 if (!RssLimitMb) return;
259 std::thread T(RssThread, F, RssLimitMb);
260 T.detach();
261}
262
Kostya Serebryanya016a452016-08-30 14:52:05 +0000263int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
Ivan Krasin95e82d52015-10-01 23:23:06 +0000264 Unit U = FileToVector(InputFilePath);
Kostya Serebryanya016a452016-08-30 14:52:05 +0000265 if (MaxLen && MaxLen < U.size())
266 U.resize(MaxLen);
267 F->RunOne(U.data(), U.size());
Kostya Serebryanybb59ef72016-10-18 18:38:08 +0000268 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
Ivan Krasin95e82d52015-10-01 23:23:06 +0000269 return 0;
270}
271
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000272static bool AllInputsAreFiles() {
273 if (Inputs->empty()) return false;
274 for (auto &Path : *Inputs)
275 if (!IsFile(Path))
276 return false;
277 return true;
278}
279
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000280int MinimizeCrashInput(const std::vector<std::string> &Args) {
281 if (Inputs->size() != 1) {
282 Printf("ERROR: -minimize_crash should be given one input file\n");
283 exit(1);
284 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000285 std::string InputFilePath = Inputs->at(0);
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000286 std::string BaseCmd =
287 CloneArgsWithoutX(Args, "minimize_crash", "exact_artifact_path");
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000288 auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
289 assert(InputPos != std::string::npos);
290 BaseCmd.erase(InputPos, InputFilePath.size() + 1);
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000291 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
292 Printf("INFO: you need to specify -runs=N or "
293 "-max_total_time=N with -minimize_crash=1\n"
294 "INFO: defaulting to -max_total_time=600\n");
295 BaseCmd += " -max_total_time=600";
296 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000297 // BaseCmd += " > /dev/null 2>&1 ";
298
299 std::string CurrentFilePath = InputFilePath;
300 while (true) {
301 Unit U = FileToVector(CurrentFilePath);
302 if (U.size() < 2) {
303 Printf("CRASH_MIN: '%s' is small enough\n", CurrentFilePath.c_str());
304 return 0;
305 }
306 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
307 CurrentFilePath.c_str(), U.size());
308
309 auto Cmd = BaseCmd + " " + CurrentFilePath;
310
311 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
312 int ExitCode = ExecuteCommand(Cmd);
313 if (ExitCode == 0) {
314 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
315 exit(1);
316 }
317 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
318 "it further\n",
319 CurrentFilePath.c_str(), U.size());
320
321 std::string ArtifactPath = "minimized-from-" + Hash(U);
322 Cmd += " -minimize_crash_internal_step=1 -exact_artifact_path=" +
323 ArtifactPath;
324 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
325 ExitCode = ExecuteCommand(Cmd);
326 if (ExitCode == 0) {
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000327 if (Flags.exact_artifact_path) {
328 CurrentFilePath = Flags.exact_artifact_path;
329 WriteToFile(U, CurrentFilePath);
330 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000331 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)
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000382 Printf("Running %u 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) +
Zachary Turner6fa57ad2016-12-02 23:02:01 +0000445 GetPid();
Kostya Serebryanya3992212016-02-13 03:00:53 +0000446 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
Marcos Pividoric59b6922016-12-13 17:45:20 +0000460 Options.HandleAbrt = Flags.handle_abrt;
461 Options.HandleBus = Flags.handle_bus;
462 Options.HandleFpe = Flags.handle_fpe;
463 Options.HandleIll = Flags.handle_ill;
464 Options.HandleInt = Flags.handle_int;
465 Options.HandleSegv = Flags.handle_segv;
466 Options.HandleTerm = Flags.handle_term;
467 SetSignalHandler(Options);
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000468
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000469 if (Flags.minimize_crash_internal_step)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000470 return MinimizeCrashInputInternalStep(F, Corpus);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000471
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000472 if (DoPlainRun) {
473 Options.SaveArtifacts = false;
Kostya Serebryany9d14e4b2016-02-12 02:32:03 +0000474 int Runs = std::max(1, Flags.runs);
475 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
476 Inputs->size(), Runs);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000477 for (auto &Path : *Inputs) {
478 auto StartTime = system_clock::now();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000479 Printf("Running: %s\n", Path.c_str());
Kostya Serebryany5c3701c2016-03-04 22:35:40 +0000480 for (int Iter = 0; Iter < Runs; Iter++)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000481 RunOneTest(F, Path.c_str(), Options.MaxLen);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000482 auto StopTime = system_clock::now();
483 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000484 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000485 }
Kostya Serebryanybdb220c2016-08-15 19:44:04 +0000486 Printf("***\n"
487 "*** NOTE: fuzzing was not performed, you have only\n"
488 "*** executed the target code on a fixed set of inputs.\n"
489 "***\n");
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000490 F->PrintFinalStats();
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000491 exit(0);
492 }
493
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000494 if (Flags.merge) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000495 if (Options.MaxLen == 0)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000496 F->SetMaxInputLen(kMaxSaneLen);
497 F->Merge(*Inputs);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000498 exit(0);
499 }
500
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000501 if (Flags.experimental_merge) {
502 if (Options.MaxLen == 0)
503 F->SetMaxInputLen(kMaxSaneLen);
504 if (Flags.merge_control_file)
505 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
506 else
507 F->CrashResistantMerge(Args, *Inputs);
508 exit(0);
509 }
510
Kostya Serebryany64d24572016-03-12 01:57:04 +0000511 size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000512
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000513 UnitVector InitialCorpus;
514 for (auto &Inp : *Inputs) {
515 Printf("Loading corpus dir: %s\n", Inp.c_str());
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000516 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
517 TemporaryMaxLen, /*ExitOnError=*/false);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000518 }
Kostya Serebryany64d24572016-03-12 01:57:04 +0000519
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000520 if (Options.MaxLen == 0) {
521 size_t MaxLen = 0;
522 for (auto &U : InitialCorpus)
523 MaxLen = std::max(U.size(), MaxLen);
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000524 F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000525 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000526
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000527 if (InitialCorpus.empty()) {
Kostya Serebryany53c894d2016-11-12 02:27:21 +0000528 InitialCorpus.push_back(Unit({'\n'})); // Valid ASCII input.
Kostya Serebryany09087bb2016-04-18 21:14:11 +0000529 if (Options.Verbosity)
530 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
531 }
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000532 F->ShuffleAndMinimize(&InitialCorpus);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000533 InitialCorpus.clear(); // Don't need this memory any more.
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000534 F->Loop();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000535
Kostya Serebryany016852c2015-02-19 18:45:37 +0000536 if (Flags.verbosity)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000537 Printf("Done %d runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
538 F->secondsSinceProcessStartUp());
539 F->PrintFinalStats();
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000540
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000541 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000542}
Dan Liew1873a492016-06-07 23:32:50 +0000543
544// Storage for global ExternalFunctions object.
545ExternalFunctions *EF = nullptr;
546
Kostya Serebryany016852c2015-02-19 18:45:37 +0000547} // namespace fuzzer