blob: 17891d29c5d5adc9da3a62d327e4187f7698cef5 [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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000013#include "FuzzerIO.h"
Kostya Serebryany016852c2015-02-19 18:45:37 +000014#include "FuzzerInterface.h"
15#include "FuzzerInternal.h"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000016#include "FuzzerMutate.h"
17#include "FuzzerRandom.h"
Kostya Serebryany98d592c2017-01-20 20:57:07 +000018#include "FuzzerShmem.h"
Kostya Serebryany628b43a2016-12-15 06:21:21 +000019#include "FuzzerTracePC.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000020#include <algorithm>
Kostya Serebryany016852c2015-02-19 18:45:37 +000021#include <atomic>
Mehdi Aminib550cb12016-04-18 09:17:29 +000022#include <chrono>
Matt Morehouse9e689792017-07-20 20:43:39 +000023#include <cstdlib>
Mehdi Aminib550cb12016-04-18 09:17:29 +000024#include <cstring>
Kostya Serebryany016852c2015-02-19 18:45:37 +000025#include <mutex>
Kostya Serebryany52a788e2015-03-31 20:13:20 +000026#include <string>
Mehdi Aminib550cb12016-04-18 09:17:29 +000027#include <thread>
Kostya Serebryany016852c2015-02-19 18:45:37 +000028
Kostya Serebryany4282d302016-01-15 00:17:37 +000029// This function should be present in the libFuzzer so that the client
30// binary can test for its existence.
31extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
32
Kostya Serebryany016852c2015-02-19 18:45:37 +000033namespace fuzzer {
34
35// Program arguments.
36struct FlagDescription {
37 const char *Name;
38 const char *Description;
39 int Default;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000040 int *IntFlag;
41 const char **StrFlag;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000042 unsigned int *UIntFlag;
Kostya Serebryany016852c2015-02-19 18:45:37 +000043};
44
45struct {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000046#define FUZZER_DEPRECATED_FLAG(Name)
Kostya Serebryany52a788e2015-03-31 20:13:20 +000047#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000048#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000049#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
Kostya Serebryany016852c2015-02-19 18:45:37 +000050#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000051#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000052#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000053#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000054#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000055} Flags;
56
Craig Topper26260942015-10-18 05:15:34 +000057static const FlagDescription FlagDescriptions [] {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000058#define FUZZER_DEPRECATED_FLAG(Name) \
59 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000060#define FUZZER_FLAG_INT(Name, Default, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000061 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
62#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
63 {#Name, Description, static_cast<int>(Default), \
64 nullptr, nullptr, &Flags.Name},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000065#define FUZZER_FLAG_STRING(Name, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000066 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
Kostya Serebryany016852c2015-02-19 18:45:37 +000067#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000068#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000069#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000070#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000071#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000072};
73
74static const size_t kNumFlags =
75 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
76
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000077static std::vector<std::string> *Inputs;
78static std::string *ProgName;
Kostya Serebryany016852c2015-02-19 18:45:37 +000079
80static void PrintHelp() {
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +000081 Printf("Usage:\n");
82 auto Prog = ProgName->c_str();
83 Printf("\nTo run fuzzing pass 0 or more directories.\n");
84 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
85
86 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
87 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
88
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000089 Printf("\nFlags: (strictly in form -flag=value)\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000090 size_t MaxFlagLen = 0;
91 for (size_t F = 0; F < kNumFlags; F++)
92 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
93
94 for (size_t F = 0; F < kNumFlags; F++) {
95 const auto &D = FlagDescriptions[F];
Kostya Serebryany45299602016-09-10 00:35:30 +000096 if (strstr(D.Description, "internal flag") == D.Description) continue;
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000097 Printf(" %s", D.Name);
Kostya Serebryany016852c2015-02-19 18:45:37 +000098 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000099 Printf(" ");
100 Printf("\t");
101 Printf("%d\t%s\n", D.Default, D.Description);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000102 }
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000103 Printf("\nFlags starting with '--' will be ignored and "
104 "will be passed verbatim to subprocesses.\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000105}
106
107static const char *FlagValue(const char *Param, const char *Name) {
108 size_t Len = strlen(Name);
109 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
110 Param[Len + 1] == '=')
111 return &Param[Len + 2];
112 return nullptr;
113}
114
Kostya Serebryany4282d302016-01-15 00:17:37 +0000115// Avoid calling stol as it triggers a bug in clang/glibc build.
116static long MyStol(const char *Str) {
117 long Res = 0;
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000118 long Sign = 1;
119 if (*Str == '-') {
120 Str++;
121 Sign = -1;
122 }
Kostya Serebryany4282d302016-01-15 00:17:37 +0000123 for (size_t i = 0; Str[i]; i++) {
124 char Ch = Str[i];
125 if (Ch < '0' || Ch > '9')
126 return Res;
127 Res = Res * 10 + (Ch - '0');
128 }
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000129 return Res * Sign;
Kostya Serebryany4282d302016-01-15 00:17:37 +0000130}
131
Kostya Serebryany016852c2015-02-19 18:45:37 +0000132static bool ParseOneFlag(const char *Param) {
133 if (Param[0] != '-') return false;
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000134 if (Param[1] == '-') {
135 static bool PrintedWarning = false;
136 if (!PrintedWarning) {
137 PrintedWarning = true;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000138 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000139 }
Kostya Serebryanyb60397f2016-04-15 21:56:29 +0000140 for (size_t F = 0; F < kNumFlags; F++)
141 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
142 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000143 return true;
144 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000145 for (size_t F = 0; F < kNumFlags; F++) {
146 const char *Name = FlagDescriptions[F].Name;
147 const char *Str = FlagValue(Param, Name);
148 if (Str) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000149 if (FlagDescriptions[F].IntFlag) {
Kostya Serebryany4282d302016-01-15 00:17:37 +0000150 int Val = MyStol(Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000151 *FlagDescriptions[F].IntFlag = Val;
152 if (Flags.verbosity >= 2)
Mandeep Singh Grang5e1697e2017-06-06 05:08:36 +0000153 Printf("Flag: %s %d\n", Name, Val);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000154 return true;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000155 } else if (FlagDescriptions[F].UIntFlag) {
156 unsigned int Val = std::stoul(Str);
157 *FlagDescriptions[F].UIntFlag = Val;
158 if (Flags.verbosity >= 2)
159 Printf("Flag: %s %u\n", Name, Val);
160 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000161 } else if (FlagDescriptions[F].StrFlag) {
162 *FlagDescriptions[F].StrFlag = Str;
163 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000164 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000165 return true;
Kostya Serebryany3d95dd92016-03-01 22:33:14 +0000166 } else { // Deprecated flag.
167 Printf("Flag: %s: deprecated, don't use\n", Name);
168 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000169 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000170 }
171 }
Kostya Serebryanyf8177312016-06-01 16:41:12 +0000172 Printf("\n\nWARNING: unrecognized flag '%s'; "
173 "use -help=1 to list all flags\n\n", Param);
174 return true;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000175}
176
177// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000178static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000179 for (size_t F = 0; F < kNumFlags; F++) {
180 if (FlagDescriptions[F].IntFlag)
181 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000182 if (FlagDescriptions[F].UIntFlag)
183 *FlagDescriptions[F].UIntFlag =
184 static_cast<unsigned int>(FlagDescriptions[F].Default);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000185 if (FlagDescriptions[F].StrFlag)
186 *FlagDescriptions[F].StrFlag = nullptr;
187 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000188 Inputs = new std::vector<std::string>;
189 for (size_t A = 1; A < Args.size(); A++) {
Justin Bognerc27a70d2017-07-14 23:33:04 +0000190 if (ParseOneFlag(Args[A].c_str())) {
191 if (Flags.ignore_remaining_args)
192 break;
193 continue;
194 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000195 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000196 }
197}
198
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000199static std::mutex Mu;
200
201static void PulseThread() {
202 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000203 SleepSeconds(600);
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000204 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000205 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000206 }
207}
208
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000209static void WorkerThread(const std::string &Cmd, std::atomic<unsigned> *Counter,
210 unsigned NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000211 while (true) {
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000212 unsigned C = (*Counter)++;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000213 if (C >= NumJobs) break;
214 std::string Log = "fuzz-" + std::to_string(C) + ".log";
215 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
216 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000217 Printf("%s", ToRun.c_str());
Hans Wennborge6319962016-04-11 20:35:17 +0000218 int ExitCode = ExecuteCommand(ToRun);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000219 if (ExitCode != 0)
220 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000221 std::lock_guard<std::mutex> Lock(Mu);
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000222 Printf("================== Job %u exited with exit code %d ============\n",
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000223 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000224 fuzzer::CopyFileToErr(Log);
225 }
226}
227
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000228std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
229 const char *X1, const char *X2) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000230 std::string Cmd;
231 for (auto &S : Args) {
232 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
233 continue;
234 Cmd += S + " ";
235 }
236 return Cmd;
237}
238
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000239static int RunInMultipleProcesses(const std::vector<std::string> &Args,
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000240 unsigned NumWorkers, unsigned NumJobs) {
241 std::atomic<unsigned> Counter(0);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000242 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();
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000247 for (unsigned i = 0; i < NumWorkers; i++)
Kostya Serebryany016852c2015-02-19 18:45:37 +0000248 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);
Kostya Serebryany1e99d542017-07-12 22:20:04 +0000273 F->ExecuteCallback(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 Serebryany86e630b2017-03-25 00:56:08 +0000286static std::string GetDedupTokenFromFile(const std::string &Path) {
287 auto S = FileToString(Path);
288 auto Beg = S.find("DEDUP_TOKEN:");
289 if (Beg == std::string::npos)
290 return "";
291 auto End = S.find('\n', Beg);
292 if (End == std::string::npos)
293 return "";
294 return S.substr(Beg, End - Beg);
295}
296
Kostya Serebryanyac7a9ea2017-04-17 20:58:21 +0000297int CleanseCrashInput(const std::vector<std::string> &Args,
298 const FuzzingOptions &Options) {
299 if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
300 Printf("ERROR: -cleanse_crash should be given one input file and"
301 " -exact_artifact_path\n");
302 exit(1);
303 }
304 std::string InputFilePath = Inputs->at(0);
305 std::string OutputFilePath = Flags.exact_artifact_path;
306 std::string BaseCmd =
307 CloneArgsWithoutX(Args, "cleanse_crash", "cleanse_crash");
308
309 auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
310 assert(InputPos != std::string::npos);
311 BaseCmd.erase(InputPos, InputFilePath.size() + 1);
312
313 auto LogFilePath = DirPlusFile(
314 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
315 auto TmpFilePath = DirPlusFile(
316 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".repro");
317 auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
318
319 auto Cmd = BaseCmd + " " + TmpFilePath + LogFileRedirect;
320
321 std::string CurrentFilePath = InputFilePath;
322 auto U = FileToVector(CurrentFilePath);
323 size_t Size = U.size();
324
325 const std::vector<uint8_t> ReplacementBytes = {' ', 0xff};
326 for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
327 bool Changed = false;
328 for (size_t Idx = 0; Idx < Size; Idx++) {
329 Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
330 Idx, Size);
331 uint8_t OriginalByte = U[Idx];
332 if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
333 ReplacementBytes.end(),
334 OriginalByte))
335 continue;
336 for (auto NewByte : ReplacementBytes) {
337 U[Idx] = NewByte;
338 WriteToFile(U, TmpFilePath);
339 auto ExitCode = ExecuteCommand(Cmd);
340 RemoveFile(TmpFilePath);
341 if (!ExitCode) {
342 U[Idx] = OriginalByte;
343 } else {
344 Changed = true;
345 Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
346 WriteToFile(U, OutputFilePath);
347 break;
348 }
349 }
350 }
351 if (!Changed) break;
352 }
353 RemoveFile(LogFilePath);
354 return 0;
355}
356
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000357int MinimizeCrashInput(const std::vector<std::string> &Args,
358 const FuzzingOptions &Options) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000359 if (Inputs->size() != 1) {
360 Printf("ERROR: -minimize_crash should be given one input file\n");
361 exit(1);
362 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000363 std::string InputFilePath = Inputs->at(0);
Justin Bognerc27a70d2017-07-14 23:33:04 +0000364 auto BaseCmd = SplitBefore(
365 "-ignore_remaining_args=1",
366 CloneArgsWithoutX(Args, "minimize_crash", "exact_artifact_path"));
367 auto InputPos = BaseCmd.first.find(" " + InputFilePath + " ");
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000368 assert(InputPos != std::string::npos);
Justin Bognerc27a70d2017-07-14 23:33:04 +0000369 BaseCmd.first.erase(InputPos, InputFilePath.size() + 1);
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000370 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
371 Printf("INFO: you need to specify -runs=N or "
372 "-max_total_time=N with -minimize_crash=1\n"
373 "INFO: defaulting to -max_total_time=600\n");
Justin Bognerc27a70d2017-07-14 23:33:04 +0000374 BaseCmd.first += " -max_total_time=600";
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000375 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000376
377 auto LogFilePath = DirPlusFile(
378 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
379 auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000380
381 std::string CurrentFilePath = InputFilePath;
382 while (true) {
383 Unit U = FileToVector(CurrentFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000384 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
385 CurrentFilePath.c_str(), U.size());
386
Justin Bognerc27a70d2017-07-14 23:33:04 +0000387 auto Cmd = BaseCmd.first + " " + CurrentFilePath + LogFileRedirect + " " +
388 BaseCmd.second;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000389
390 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
391 int ExitCode = ExecuteCommand(Cmd);
392 if (ExitCode == 0) {
393 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
394 exit(1);
395 }
396 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
397 "it further\n",
398 CurrentFilePath.c_str(), U.size());
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000399 auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
400 if (!DedupToken1.empty())
401 Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000402
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000403 std::string ArtifactPath =
Kostya Serebryanydba9ded2017-03-24 21:09:16 +0000404 Flags.exact_artifact_path
405 ? Flags.exact_artifact_path
406 : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000407 Cmd += " -minimize_crash_internal_step=1 -exact_artifact_path=" +
408 ArtifactPath;
409 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
410 ExitCode = ExecuteCommand(Cmd);
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000411 CopyFileToErr(LogFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000412 if (ExitCode == 0) {
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000413 if (Flags.exact_artifact_path) {
414 CurrentFilePath = Flags.exact_artifact_path;
415 WriteToFile(U, CurrentFilePath);
416 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000417 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
418 CurrentFilePath.c_str(), U.size());
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000419 break;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000420 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000421 auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
422 if (!DedupToken2.empty())
423 Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
424
425 if (DedupToken1 != DedupToken2) {
426 if (Flags.exact_artifact_path) {
427 CurrentFilePath = Flags.exact_artifact_path;
428 WriteToFile(U, CurrentFilePath);
429 }
430 Printf("CRASH_MIN: mismatch in dedup tokens"
431 " (looks like a different bug). Won't minimize further\n");
432 break;
433 }
434
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000435 CurrentFilePath = ArtifactPath;
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000436 Printf("*********************************\n");
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000437 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000438 RemoveFile(LogFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000439 return 0;
440}
441
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000442int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000443 assert(Inputs->size() == 1);
444 std::string InputFilePath = Inputs->at(0);
445 Unit U = FileToVector(InputFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000446 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000447 if (U.size() < 2) {
448 Printf("INFO: The input is small enough, exiting\n");
449 exit(0);
450 }
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000451 F->SetMaxInputLen(U.size());
452 F->SetMaxMutationLen(U.size() - 1);
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000453 F->MinimizeCrashLoop(U);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000454 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
455 exit(0);
456 return 0;
457}
458
Kostya Serebryanyf7e610e2017-03-17 01:40:09 +0000459int AnalyzeDictionary(Fuzzer *F, const std::vector<Unit>& Dict,
460 UnitVector& Corpus) {
461 Printf("Started dictionary minimization (up to %d tests)\n",
462 Dict.size() * Corpus.size() * 2);
463
464 // Scores and usage count for each dictionary unit.
465 std::vector<int> Scores(Dict.size());
466 std::vector<int> Usages(Dict.size());
467
468 std::vector<size_t> InitialFeatures;
469 std::vector<size_t> ModifiedFeatures;
470 for (auto &C : Corpus) {
471 // Get coverage for the testcase without modifications.
472 F->ExecuteCallback(C.data(), C.size());
473 InitialFeatures.clear();
474 TPC.CollectFeatures([&](size_t Feature) -> bool {
475 InitialFeatures.push_back(Feature);
476 return true;
477 });
478
479 for (size_t i = 0; i < Dict.size(); ++i) {
480 auto Data = C;
481 auto StartPos = std::search(Data.begin(), Data.end(),
482 Dict[i].begin(), Dict[i].end());
483 // Skip dictionary unit, if the testcase does not contain it.
484 if (StartPos == Data.end())
485 continue;
486
487 ++Usages[i];
488 while (StartPos != Data.end()) {
489 // Replace all occurrences of dictionary unit in the testcase.
490 auto EndPos = StartPos + Dict[i].size();
491 for (auto It = StartPos; It != EndPos; ++It)
492 *It ^= 0xFF;
493
494 StartPos = std::search(EndPos, Data.end(),
495 Dict[i].begin(), Dict[i].end());
496 }
497
498 // Get coverage for testcase with masked occurrences of dictionary unit.
499 F->ExecuteCallback(Data.data(), Data.size());
500 ModifiedFeatures.clear();
501 TPC.CollectFeatures([&](size_t Feature) -> bool {
502 ModifiedFeatures.push_back(Feature);
503 return true;
504 });
505
506 if (InitialFeatures == ModifiedFeatures)
507 --Scores[i];
508 else
509 Scores[i] += 2;
510 }
511 }
512
513 Printf("###### Useless dictionary elements. ######\n");
514 for (size_t i = 0; i < Dict.size(); ++i) {
515 // Dictionary units with positive score are treated as useful ones.
516 if (Scores[i] > 0)
517 continue;
518
519 Printf("\"");
520 PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
521 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
522 }
523 Printf("###### End of useless dictionary elements. ######\n");
524 return 0;
525}
526
Dan Liewd3c33112016-06-02 05:48:02 +0000527int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000528 using namespace fuzzer;
Dan Liewd3c33112016-06-02 05:48:02 +0000529 assert(argc && argv && "Argument pointers cannot be nullptr");
Kostya Serebryany87a38112017-01-20 21:34:24 +0000530 std::string Argv0((*argv)[0]);
Dan Liew1873a492016-06-07 23:32:50 +0000531 EF = new ExternalFunctions();
532 if (EF->LLVMFuzzerInitialize)
533 EF->LLVMFuzzerInitialize(argc, argv);
Dan Liewd3c33112016-06-02 05:48:02 +0000534 const std::vector<std::string> Args(*argv, *argv + *argc);
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000535 assert(!Args.empty());
536 ProgName = new std::string(Args[0]);
Kostya Serebryanyd9667912017-01-21 00:13:50 +0000537 if (Argv0 != *ProgName) {
538 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
539 exit(1);
540 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000541 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000542 if (Flags.help) {
543 PrintHelp();
544 return 0;
545 }
546
Kostya Serebryany49e40902016-03-18 20:58:29 +0000547 if (Flags.close_fd_mask & 2)
548 DupAndCloseStderr();
549 if (Flags.close_fd_mask & 1)
550 CloseStdout();
551
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000552 if (Flags.jobs > 0 && Flags.workers == 0) {
553 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
554 if (Flags.workers > 1)
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000555 Printf("Running %u workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000556 }
557
Kostya Serebryany016852c2015-02-19 18:45:37 +0000558 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000559 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000560
Kostya Serebryany64d24572016-03-12 01:57:04 +0000561 const size_t kMaxSaneLen = 1 << 20;
Kostya Serebryany589eae52017-06-15 22:43:40 +0000562 const size_t kMinDefaultLen = 4096;
Mike Aizatskyf0b3e852016-06-23 20:44:48 +0000563 FuzzingOptions Options;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000564 Options.Verbosity = Flags.verbosity;
565 Options.MaxLen = Flags.max_len;
Kostya Serebryany2a8440d2016-12-27 23:24:55 +0000566 Options.ExperimentalLenControl = Flags.experimental_len_control;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000567 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryany8a569172016-11-03 19:31:18 +0000568 Options.ErrorExitCode = Flags.error_exitcode;
Kostya Serebryany54a63632016-01-29 23:30:07 +0000569 Options.TimeoutExitCode = Flags.timeout_exitcode;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000570 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000571 Options.DoCrossOver = Flags.cross_over;
572 Options.MutateDepth = Flags.mutate_depth;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000573 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000574 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryanyc135b552016-07-15 23:27:19 +0000575 Options.UseMemmem = Flags.use_memmem;
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000576 Options.UseCmp = Flags.use_cmp;
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000577 Options.UseValueProfile = Flags.use_value_profile;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000578 Options.Shrink = Flags.shrink;
Kostya Serebryany1e99d542017-07-12 22:20:04 +0000579 Options.ReduceInputs = Flags.reduce_inputs;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000580 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000581 Options.PreferSmall = Flags.prefer_small;
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000582 Options.ReloadIntervalSec = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000583 Options.OnlyASCII = Flags.only_ascii;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000584 Options.DetectLeaks = Flags.detect_leaks;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000585 Options.TraceMalloc = Flags.trace_malloc;
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000586 Options.RssLimitMb = Flags.rss_limit_mb;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000587 if (Flags.runs >= 0)
588 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000589 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000590 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000591 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000592 if (Flags.artifact_prefix)
593 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000594 if (Flags.exact_artifact_path)
595 Options.ExactArtifactPath = Flags.exact_artifact_path;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000596 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000597 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000598 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000599 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000600 if (Flags.verbosity > 0 && !Dictionary.empty())
601 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000602 bool DoPlainRun = AllInputsAreFiles();
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000603 Options.SaveArtifacts =
604 !DoPlainRun || Flags.minimize_crash_internal_step;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000605 Options.PrintNewCovPcs = Flags.print_pcs;
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000606 Options.PrintFinalStats = Flags.print_final_stats;
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000607 Options.PrintCorpusStats = Flags.print_corpus_stats;
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000608 Options.PrintCoverage = Flags.print_coverage;
Mike Aizatsky9b415be2016-12-19 22:18:08 +0000609 Options.DumpCoverage = Flags.dump_coverage;
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000610 if (Flags.exit_on_src_pos)
611 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000612 if (Flags.exit_on_item)
613 Options.ExitOnItem = Flags.exit_on_item;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000614
Kostya Serebryanya3992212016-02-13 03:00:53 +0000615 unsigned Seed = Flags.seed;
616 // Initialize Seed.
617 if (Seed == 0)
Kostya Serebryany823c1812016-12-27 19:51:34 +0000618 Seed =
619 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
Kostya Serebryanya3992212016-02-13 03:00:53 +0000620 if (Flags.verbosity)
Kostya Serebryany64d24572016-03-12 01:57:04 +0000621 Printf("INFO: Seed: %u\n", Seed);
Kostya Serebryanya3992212016-02-13 03:00:53 +0000622
623 Random Rand(Seed);
Kostya Serebryany6c778112016-11-14 19:21:38 +0000624 auto *MD = new MutationDispatcher(Rand, Options);
625 auto *Corpus = new InputCorpus(Options.OutputCorpus);
626 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000627
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000628 for (auto &U: Dictionary)
Kostya Serebryany476f0ce2016-01-16 03:53:32 +0000629 if (U.size() <= Word::GetMaxSize())
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000630 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000631
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000632 StartRssThread(F, Flags.rss_limit_mb);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000633
Marcos Pividoric59b6922016-12-13 17:45:20 +0000634 Options.HandleAbrt = Flags.handle_abrt;
635 Options.HandleBus = Flags.handle_bus;
636 Options.HandleFpe = Flags.handle_fpe;
637 Options.HandleIll = Flags.handle_ill;
638 Options.HandleInt = Flags.handle_int;
639 Options.HandleSegv = Flags.handle_segv;
640 Options.HandleTerm = Flags.handle_term;
Kostya Serebryany4aa05902017-01-05 22:05:47 +0000641 Options.HandleXfsz = Flags.handle_xfsz;
Marcos Pividoric59b6922016-12-13 17:45:20 +0000642 SetSignalHandler(Options);
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000643
Matt Morehouse9e689792017-07-20 20:43:39 +0000644 std::atexit(Fuzzer::StaticExitCallback);
645
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000646 if (Flags.minimize_crash)
647 return MinimizeCrashInput(Args, Options);
648
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000649 if (Flags.minimize_crash_internal_step)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000650 return MinimizeCrashInputInternalStep(F, Corpus);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000651
Kostya Serebryanyac7a9ea2017-04-17 20:58:21 +0000652 if (Flags.cleanse_crash)
653 return CleanseCrashInput(Args, Options);
654
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000655 if (auto Name = Flags.run_equivalence_server) {
656 SMR.Destroy(Name);
Kostya Serebryany5c76e3d2017-02-01 00:07:47 +0000657 if (!SMR.Create(Name)) {
658 Printf("ERROR: can't create shared memory region\n");
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000659 return 1;
660 }
661 Printf("INFO: EQUIVALENCE SERVER UP\n");
662 while (true) {
663 SMR.WaitClient();
664 size_t Size = SMR.ReadByteArraySize();
665 SMR.WriteByteArray(nullptr, 0);
Kostya Serebryanyfe4ed9b2017-05-09 01:17:29 +0000666 const Unit tmp(SMR.GetByteArray(), SMR.GetByteArray() + Size);
Kostya Serebryany1e99d542017-07-12 22:20:04 +0000667 F->ExecuteCallback(tmp.data(), tmp.size());
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000668 SMR.PostServer();
669 }
670 return 0;
671 }
672
673 if (auto Name = Flags.use_equivalence_server) {
674 if (!SMR.Open(Name)) {
675 Printf("ERROR: can't open shared memory region\n");
676 return 1;
677 }
678 Printf("INFO: EQUIVALENCE CLIENT UP\n");
679 }
680
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000681 if (DoPlainRun) {
682 Options.SaveArtifacts = false;
Kostya Serebryany9d14e4b2016-02-12 02:32:03 +0000683 int Runs = std::max(1, Flags.runs);
684 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
685 Inputs->size(), Runs);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000686 for (auto &Path : *Inputs) {
687 auto StartTime = system_clock::now();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000688 Printf("Running: %s\n", Path.c_str());
Kostya Serebryany5c3701c2016-03-04 22:35:40 +0000689 for (int Iter = 0; Iter < Runs; Iter++)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000690 RunOneTest(F, Path.c_str(), Options.MaxLen);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000691 auto StopTime = system_clock::now();
692 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000693 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000694 }
Kostya Serebryanybdb220c2016-08-15 19:44:04 +0000695 Printf("***\n"
696 "*** NOTE: fuzzing was not performed, you have only\n"
697 "*** executed the target code on a fixed set of inputs.\n"
698 "***\n");
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000699 F->PrintFinalStats();
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000700 exit(0);
701 }
702
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000703 if (Flags.merge) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000704 if (Options.MaxLen == 0)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000705 F->SetMaxInputLen(kMaxSaneLen);
Kostya Serebryanyf81cc092017-03-14 21:47:52 +0000706 if (Flags.merge_control_file)
707 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
708 else
Kostya Serebryany4fc6dd72017-03-22 20:32:44 +0000709 F->CrashResistantMerge(Args, *Inputs,
710 Flags.load_coverage_summary,
711 Flags.save_coverage_summary);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000712 exit(0);
713 }
714
Kostya Serebryany64d24572016-03-12 01:57:04 +0000715 size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000716
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000717 UnitVector InitialCorpus;
718 for (auto &Inp : *Inputs) {
719 Printf("Loading corpus dir: %s\n", Inp.c_str());
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000720 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
721 TemporaryMaxLen, /*ExitOnError=*/false);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000722 }
Kostya Serebryany64d24572016-03-12 01:57:04 +0000723
Kostya Serebryanyf7e610e2017-03-17 01:40:09 +0000724 if (Flags.analyze_dict) {
725 if (Dictionary.empty() || Inputs->empty()) {
726 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
727 return 1;
728 }
729 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
730 Printf("Dictionary analysis failed\n");
731 exit(1);
732 }
733 Printf("Dictionary analysis suceeded\n");
734 exit(0);
735 }
736
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000737 if (Options.MaxLen == 0) {
738 size_t MaxLen = 0;
739 for (auto &U : InitialCorpus)
740 MaxLen = std::max(U.size(), MaxLen);
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000741 F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000742 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000743
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000744 if (InitialCorpus.empty()) {
Kostya Serebryany53c894d2016-11-12 02:27:21 +0000745 InitialCorpus.push_back(Unit({'\n'})); // Valid ASCII input.
Kostya Serebryany09087bb2016-04-18 21:14:11 +0000746 if (Options.Verbosity)
747 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
748 }
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000749 F->ShuffleAndMinimize(&InitialCorpus);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000750 InitialCorpus.clear(); // Don't need this memory any more.
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000751 F->Loop();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000752
Kostya Serebryany016852c2015-02-19 18:45:37 +0000753 if (Flags.verbosity)
Kostya Serebryanyae579a72017-02-14 22:14:36 +0000754 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000755 F->secondsSinceProcessStartUp());
756 F->PrintFinalStats();
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000757
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000758 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000759}
Dan Liew1873a492016-06-07 23:32:50 +0000760
761// Storage for global ExternalFunctions object.
762ExternalFunctions *EF = nullptr;
763
Kostya Serebryany016852c2015-02-19 18:45:37 +0000764} // namespace fuzzer