blob: fd8cab38a7bb40b36fa53c567107052fe9771a30 [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>
23#include <cstring>
Kostya Serebryany016852c2015-02-19 18:45:37 +000024#include <mutex>
Kostya Serebryany52a788e2015-03-31 20:13:20 +000025#include <string>
Mehdi Aminib550cb12016-04-18 09:17:29 +000026#include <thread>
Kostya Serebryany016852c2015-02-19 18:45:37 +000027
Kostya Serebryany4282d302016-01-15 00:17:37 +000028// This function should be present in the libFuzzer so that the client
29// binary can test for its existence.
30extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
31
Kostya Serebryany016852c2015-02-19 18:45:37 +000032namespace fuzzer {
33
34// Program arguments.
35struct FlagDescription {
36 const char *Name;
37 const char *Description;
38 int Default;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000039 int *IntFlag;
40 const char **StrFlag;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000041 unsigned int *UIntFlag;
Kostya Serebryany016852c2015-02-19 18:45:37 +000042};
43
44struct {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000045#define FUZZER_DEPRECATED_FLAG(Name)
Kostya Serebryany52a788e2015-03-31 20:13:20 +000046#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
Mike Aizatskya1a5c692015-12-10 20:41:53 +000047#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
Kostya Serebryany52a788e2015-03-31 20:13:20 +000048#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
Kostya Serebryany016852c2015-02-19 18:45:37 +000049#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000050#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000051#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000052#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000053#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000054} Flags;
55
Craig Topper26260942015-10-18 05:15:34 +000056static const FlagDescription FlagDescriptions [] {
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000057#define FUZZER_DEPRECATED_FLAG(Name) \
58 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000059#define FUZZER_FLAG_INT(Name, Default, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000060 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
61#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
62 {#Name, Description, static_cast<int>(Default), \
63 nullptr, nullptr, &Flags.Name},
Kostya Serebryany52a788e2015-03-31 20:13:20 +000064#define FUZZER_FLAG_STRING(Name, Description) \
Mike Aizatskya1a5c692015-12-10 20:41:53 +000065 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
Kostya Serebryany016852c2015-02-19 18:45:37 +000066#include "FuzzerFlags.def"
Kostya Serebryany3d95dd92016-03-01 22:33:14 +000067#undef FUZZER_DEPRECATED_FLAG
Kostya Serebryany52a788e2015-03-31 20:13:20 +000068#undef FUZZER_FLAG_INT
Mike Aizatskya1a5c692015-12-10 20:41:53 +000069#undef FUZZER_FLAG_UNSIGNED
Kostya Serebryany52a788e2015-03-31 20:13:20 +000070#undef FUZZER_FLAG_STRING
Kostya Serebryany016852c2015-02-19 18:45:37 +000071};
72
73static const size_t kNumFlags =
74 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
75
Kostya Serebryanya938bcb2015-09-10 16:57:57 +000076static std::vector<std::string> *Inputs;
77static std::string *ProgName;
Kostya Serebryany016852c2015-02-19 18:45:37 +000078
79static void PrintHelp() {
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +000080 Printf("Usage:\n");
81 auto Prog = ProgName->c_str();
82 Printf("\nTo run fuzzing pass 0 or more directories.\n");
83 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
84
85 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
86 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
87
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000088 Printf("\nFlags: (strictly in form -flag=value)\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +000089 size_t MaxFlagLen = 0;
90 for (size_t F = 0; F < kNumFlags; F++)
91 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
92
93 for (size_t F = 0; F < kNumFlags; F++) {
94 const auto &D = FlagDescriptions[F];
Kostya Serebryany45299602016-09-10 00:35:30 +000095 if (strstr(D.Description, "internal flag") == D.Description) continue;
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000096 Printf(" %s", D.Name);
Kostya Serebryany016852c2015-02-19 18:45:37 +000097 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +000098 Printf(" ");
99 Printf("\t");
100 Printf("%d\t%s\n", D.Default, D.Description);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000101 }
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000102 Printf("\nFlags starting with '--' will be ignored and "
103 "will be passed verbatim to subprocesses.\n");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000104}
105
106static const char *FlagValue(const char *Param, const char *Name) {
107 size_t Len = strlen(Name);
108 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
109 Param[Len + 1] == '=')
110 return &Param[Len + 2];
111 return nullptr;
112}
113
Kostya Serebryany4282d302016-01-15 00:17:37 +0000114// Avoid calling stol as it triggers a bug in clang/glibc build.
115static long MyStol(const char *Str) {
116 long Res = 0;
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000117 long Sign = 1;
118 if (*Str == '-') {
119 Str++;
120 Sign = -1;
121 }
Kostya Serebryany4282d302016-01-15 00:17:37 +0000122 for (size_t i = 0; Str[i]; i++) {
123 char Ch = Str[i];
124 if (Ch < '0' || Ch > '9')
125 return Res;
126 Res = Res * 10 + (Ch - '0');
127 }
Kostya Serebryany311f27c2016-01-19 20:33:57 +0000128 return Res * Sign;
Kostya Serebryany4282d302016-01-15 00:17:37 +0000129}
130
Kostya Serebryany016852c2015-02-19 18:45:37 +0000131static bool ParseOneFlag(const char *Param) {
132 if (Param[0] != '-') return false;
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000133 if (Param[1] == '-') {
134 static bool PrintedWarning = false;
135 if (!PrintedWarning) {
136 PrintedWarning = true;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000137 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000138 }
Kostya Serebryanyb60397f2016-04-15 21:56:29 +0000139 for (size_t F = 0; F < kNumFlags; F++)
140 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
141 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
Kostya Serebryany71e0feb2015-05-21 20:39:13 +0000142 return true;
143 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000144 for (size_t F = 0; F < kNumFlags; F++) {
145 const char *Name = FlagDescriptions[F].Name;
146 const char *Str = FlagValue(Param, Name);
147 if (Str) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000148 if (FlagDescriptions[F].IntFlag) {
Kostya Serebryany4282d302016-01-15 00:17:37 +0000149 int Val = MyStol(Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000150 *FlagDescriptions[F].IntFlag = Val;
151 if (Flags.verbosity >= 2)
Mandeep Singh Grang5e1697e2017-06-06 05:08:36 +0000152 Printf("Flag: %s %d\n", Name, Val);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000153 return true;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000154 } else if (FlagDescriptions[F].UIntFlag) {
155 unsigned int Val = std::stoul(Str);
156 *FlagDescriptions[F].UIntFlag = Val;
157 if (Flags.verbosity >= 2)
158 Printf("Flag: %s %u\n", Name, Val);
159 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000160 } else if (FlagDescriptions[F].StrFlag) {
161 *FlagDescriptions[F].StrFlag = Str;
162 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000163 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000164 return true;
Kostya Serebryany3d95dd92016-03-01 22:33:14 +0000165 } else { // Deprecated flag.
166 Printf("Flag: %s: deprecated, don't use\n", Name);
167 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000168 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000169 }
170 }
Kostya Serebryanyf8177312016-06-01 16:41:12 +0000171 Printf("\n\nWARNING: unrecognized flag '%s'; "
172 "use -help=1 to list all flags\n\n", Param);
173 return true;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000174}
175
176// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000177static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000178 for (size_t F = 0; F < kNumFlags; F++) {
179 if (FlagDescriptions[F].IntFlag)
180 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000181 if (FlagDescriptions[F].UIntFlag)
182 *FlagDescriptions[F].UIntFlag =
183 static_cast<unsigned int>(FlagDescriptions[F].Default);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000184 if (FlagDescriptions[F].StrFlag)
185 *FlagDescriptions[F].StrFlag = nullptr;
186 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000187 Inputs = new std::vector<std::string>;
188 for (size_t A = 1; A < Args.size(); A++) {
Justin Bognerc27a70d2017-07-14 23:33:04 +0000189 if (ParseOneFlag(Args[A].c_str())) {
190 if (Flags.ignore_remaining_args)
191 break;
192 continue;
193 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000194 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000195 }
196}
197
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000198static std::mutex Mu;
199
200static void PulseThread() {
201 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000202 SleepSeconds(600);
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000203 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000204 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000205 }
206}
207
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000208static void WorkerThread(const std::string &Cmd, std::atomic<unsigned> *Counter,
209 unsigned NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000210 while (true) {
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000211 unsigned C = (*Counter)++;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000212 if (C >= NumJobs) break;
213 std::string Log = "fuzz-" + std::to_string(C) + ".log";
214 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
215 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000216 Printf("%s", ToRun.c_str());
Hans Wennborge6319962016-04-11 20:35:17 +0000217 int ExitCode = ExecuteCommand(ToRun);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000218 if (ExitCode != 0)
219 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000220 std::lock_guard<std::mutex> Lock(Mu);
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000221 Printf("================== Job %u exited with exit code %d ============\n",
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000222 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000223 fuzzer::CopyFileToErr(Log);
224 }
225}
226
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000227std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
228 const char *X1, const char *X2) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000229 std::string Cmd;
230 for (auto &S : Args) {
231 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
232 continue;
233 Cmd += S + " ";
234 }
235 return Cmd;
236}
237
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000238static int RunInMultipleProcesses(const std::vector<std::string> &Args,
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000239 unsigned NumWorkers, unsigned NumJobs) {
240 std::atomic<unsigned> Counter(0);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000241 std::atomic<bool> HasErrors(false);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000242 std::string Cmd = CloneArgsWithoutX(Args, "jobs", "workers");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000243 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000244 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000245 Pulse.detach();
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000246 for (unsigned i = 0; i < NumWorkers; i++)
Kostya Serebryany016852c2015-02-19 18:45:37 +0000247 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
248 for (auto &T : V)
249 T.join();
250 return HasErrors ? 1 : 0;
251}
252
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000253static void RssThread(Fuzzer *F, size_t RssLimitMb) {
254 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000255 SleepSeconds(1);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000256 size_t Peak = GetPeakRSSMb();
257 if (Peak > RssLimitMb)
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000258 F->RssLimitCallback();
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000259 }
260}
261
262static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
263 if (!RssLimitMb) return;
264 std::thread T(RssThread, F, RssLimitMb);
265 T.detach();
266}
267
Kostya Serebryanya016a452016-08-30 14:52:05 +0000268int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
Ivan Krasin95e82d52015-10-01 23:23:06 +0000269 Unit U = FileToVector(InputFilePath);
Kostya Serebryanya016a452016-08-30 14:52:05 +0000270 if (MaxLen && MaxLen < U.size())
271 U.resize(MaxLen);
Kostya Serebryany1e99d542017-07-12 22:20:04 +0000272 F->ExecuteCallback(U.data(), U.size());
Kostya Serebryanybb59ef72016-10-18 18:38:08 +0000273 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
Ivan Krasin95e82d52015-10-01 23:23:06 +0000274 return 0;
275}
276
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000277static bool AllInputsAreFiles() {
278 if (Inputs->empty()) return false;
279 for (auto &Path : *Inputs)
280 if (!IsFile(Path))
281 return false;
282 return true;
283}
284
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000285static std::string GetDedupTokenFromFile(const std::string &Path) {
286 auto S = FileToString(Path);
287 auto Beg = S.find("DEDUP_TOKEN:");
288 if (Beg == std::string::npos)
289 return "";
290 auto End = S.find('\n', Beg);
291 if (End == std::string::npos)
292 return "";
293 return S.substr(Beg, End - Beg);
294}
295
Kostya Serebryanyac7a9ea2017-04-17 20:58:21 +0000296int CleanseCrashInput(const std::vector<std::string> &Args,
297 const FuzzingOptions &Options) {
298 if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
299 Printf("ERROR: -cleanse_crash should be given one input file and"
300 " -exact_artifact_path\n");
301 exit(1);
302 }
303 std::string InputFilePath = Inputs->at(0);
304 std::string OutputFilePath = Flags.exact_artifact_path;
305 std::string BaseCmd =
306 CloneArgsWithoutX(Args, "cleanse_crash", "cleanse_crash");
307
308 auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
309 assert(InputPos != std::string::npos);
310 BaseCmd.erase(InputPos, InputFilePath.size() + 1);
311
312 auto LogFilePath = DirPlusFile(
313 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
314 auto TmpFilePath = DirPlusFile(
315 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".repro");
316 auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
317
318 auto Cmd = BaseCmd + " " + TmpFilePath + LogFileRedirect;
319
320 std::string CurrentFilePath = InputFilePath;
321 auto U = FileToVector(CurrentFilePath);
322 size_t Size = U.size();
323
324 const std::vector<uint8_t> ReplacementBytes = {' ', 0xff};
325 for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
326 bool Changed = false;
327 for (size_t Idx = 0; Idx < Size; Idx++) {
328 Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
329 Idx, Size);
330 uint8_t OriginalByte = U[Idx];
331 if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
332 ReplacementBytes.end(),
333 OriginalByte))
334 continue;
335 for (auto NewByte : ReplacementBytes) {
336 U[Idx] = NewByte;
337 WriteToFile(U, TmpFilePath);
338 auto ExitCode = ExecuteCommand(Cmd);
339 RemoveFile(TmpFilePath);
340 if (!ExitCode) {
341 U[Idx] = OriginalByte;
342 } else {
343 Changed = true;
344 Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
345 WriteToFile(U, OutputFilePath);
346 break;
347 }
348 }
349 }
350 if (!Changed) break;
351 }
352 RemoveFile(LogFilePath);
353 return 0;
354}
355
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000356int MinimizeCrashInput(const std::vector<std::string> &Args,
357 const FuzzingOptions &Options) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000358 if (Inputs->size() != 1) {
359 Printf("ERROR: -minimize_crash should be given one input file\n");
360 exit(1);
361 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000362 std::string InputFilePath = Inputs->at(0);
Justin Bognerc27a70d2017-07-14 23:33:04 +0000363 auto BaseCmd = SplitBefore(
364 "-ignore_remaining_args=1",
365 CloneArgsWithoutX(Args, "minimize_crash", "exact_artifact_path"));
366 auto InputPos = BaseCmd.first.find(" " + InputFilePath + " ");
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000367 assert(InputPos != std::string::npos);
Justin Bognerc27a70d2017-07-14 23:33:04 +0000368 BaseCmd.first.erase(InputPos, InputFilePath.size() + 1);
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000369 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
370 Printf("INFO: you need to specify -runs=N or "
371 "-max_total_time=N with -minimize_crash=1\n"
372 "INFO: defaulting to -max_total_time=600\n");
Justin Bognerc27a70d2017-07-14 23:33:04 +0000373 BaseCmd.first += " -max_total_time=600";
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000374 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000375
376 auto LogFilePath = DirPlusFile(
377 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
378 auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000379
380 std::string CurrentFilePath = InputFilePath;
381 while (true) {
382 Unit U = FileToVector(CurrentFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000383 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
384 CurrentFilePath.c_str(), U.size());
385
Justin Bognerc27a70d2017-07-14 23:33:04 +0000386 auto Cmd = BaseCmd.first + " " + CurrentFilePath + LogFileRedirect + " " +
387 BaseCmd.second;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000388
389 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
390 int ExitCode = ExecuteCommand(Cmd);
391 if (ExitCode == 0) {
392 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
393 exit(1);
394 }
395 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
396 "it further\n",
397 CurrentFilePath.c_str(), U.size());
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000398 auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
399 if (!DedupToken1.empty())
400 Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000401
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000402 std::string ArtifactPath =
Kostya Serebryanydba9ded2017-03-24 21:09:16 +0000403 Flags.exact_artifact_path
404 ? Flags.exact_artifact_path
405 : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000406 Cmd += " -minimize_crash_internal_step=1 -exact_artifact_path=" +
407 ArtifactPath;
408 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
409 ExitCode = ExecuteCommand(Cmd);
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000410 CopyFileToErr(LogFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000411 if (ExitCode == 0) {
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000412 if (Flags.exact_artifact_path) {
413 CurrentFilePath = Flags.exact_artifact_path;
414 WriteToFile(U, CurrentFilePath);
415 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000416 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
417 CurrentFilePath.c_str(), U.size());
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000418 break;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000419 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000420 auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
421 if (!DedupToken2.empty())
422 Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
423
424 if (DedupToken1 != DedupToken2) {
425 if (Flags.exact_artifact_path) {
426 CurrentFilePath = Flags.exact_artifact_path;
427 WriteToFile(U, CurrentFilePath);
428 }
429 Printf("CRASH_MIN: mismatch in dedup tokens"
430 " (looks like a different bug). Won't minimize further\n");
431 break;
432 }
433
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000434 CurrentFilePath = ArtifactPath;
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000435 Printf("*********************************\n");
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000436 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000437 RemoveFile(LogFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000438 return 0;
439}
440
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000441int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000442 assert(Inputs->size() == 1);
443 std::string InputFilePath = Inputs->at(0);
444 Unit U = FileToVector(InputFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000445 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000446 if (U.size() < 2) {
447 Printf("INFO: The input is small enough, exiting\n");
448 exit(0);
449 }
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000450 F->SetMaxInputLen(U.size());
451 F->SetMaxMutationLen(U.size() - 1);
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000452 F->MinimizeCrashLoop(U);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000453 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
454 exit(0);
455 return 0;
456}
457
Kostya Serebryanyf7e610e2017-03-17 01:40:09 +0000458int AnalyzeDictionary(Fuzzer *F, const std::vector<Unit>& Dict,
459 UnitVector& Corpus) {
460 Printf("Started dictionary minimization (up to %d tests)\n",
461 Dict.size() * Corpus.size() * 2);
462
463 // Scores and usage count for each dictionary unit.
464 std::vector<int> Scores(Dict.size());
465 std::vector<int> Usages(Dict.size());
466
467 std::vector<size_t> InitialFeatures;
468 std::vector<size_t> ModifiedFeatures;
469 for (auto &C : Corpus) {
470 // Get coverage for the testcase without modifications.
471 F->ExecuteCallback(C.data(), C.size());
472 InitialFeatures.clear();
473 TPC.CollectFeatures([&](size_t Feature) -> bool {
474 InitialFeatures.push_back(Feature);
475 return true;
476 });
477
478 for (size_t i = 0; i < Dict.size(); ++i) {
479 auto Data = C;
480 auto StartPos = std::search(Data.begin(), Data.end(),
481 Dict[i].begin(), Dict[i].end());
482 // Skip dictionary unit, if the testcase does not contain it.
483 if (StartPos == Data.end())
484 continue;
485
486 ++Usages[i];
487 while (StartPos != Data.end()) {
488 // Replace all occurrences of dictionary unit in the testcase.
489 auto EndPos = StartPos + Dict[i].size();
490 for (auto It = StartPos; It != EndPos; ++It)
491 *It ^= 0xFF;
492
493 StartPos = std::search(EndPos, Data.end(),
494 Dict[i].begin(), Dict[i].end());
495 }
496
497 // Get coverage for testcase with masked occurrences of dictionary unit.
498 F->ExecuteCallback(Data.data(), Data.size());
499 ModifiedFeatures.clear();
500 TPC.CollectFeatures([&](size_t Feature) -> bool {
501 ModifiedFeatures.push_back(Feature);
502 return true;
503 });
504
505 if (InitialFeatures == ModifiedFeatures)
506 --Scores[i];
507 else
508 Scores[i] += 2;
509 }
510 }
511
512 Printf("###### Useless dictionary elements. ######\n");
513 for (size_t i = 0; i < Dict.size(); ++i) {
514 // Dictionary units with positive score are treated as useful ones.
515 if (Scores[i] > 0)
516 continue;
517
518 Printf("\"");
519 PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
520 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
521 }
522 Printf("###### End of useless dictionary elements. ######\n");
523 return 0;
524}
525
Dan Liewd3c33112016-06-02 05:48:02 +0000526int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000527 using namespace fuzzer;
Dan Liewd3c33112016-06-02 05:48:02 +0000528 assert(argc && argv && "Argument pointers cannot be nullptr");
Kostya Serebryany87a38112017-01-20 21:34:24 +0000529 std::string Argv0((*argv)[0]);
Dan Liew1873a492016-06-07 23:32:50 +0000530 EF = new ExternalFunctions();
531 if (EF->LLVMFuzzerInitialize)
532 EF->LLVMFuzzerInitialize(argc, argv);
Dan Liewd3c33112016-06-02 05:48:02 +0000533 const std::vector<std::string> Args(*argv, *argv + *argc);
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000534 assert(!Args.empty());
535 ProgName = new std::string(Args[0]);
Kostya Serebryanyd9667912017-01-21 00:13:50 +0000536 if (Argv0 != *ProgName) {
537 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
538 exit(1);
539 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000540 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000541 if (Flags.help) {
542 PrintHelp();
543 return 0;
544 }
545
Kostya Serebryany49e40902016-03-18 20:58:29 +0000546 if (Flags.close_fd_mask & 2)
547 DupAndCloseStderr();
548 if (Flags.close_fd_mask & 1)
549 CloseStdout();
550
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000551 if (Flags.jobs > 0 && Flags.workers == 0) {
552 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
553 if (Flags.workers > 1)
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000554 Printf("Running %u workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000555 }
556
Kostya Serebryany016852c2015-02-19 18:45:37 +0000557 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000558 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000559
Kostya Serebryany64d24572016-03-12 01:57:04 +0000560 const size_t kMaxSaneLen = 1 << 20;
Kostya Serebryany589eae52017-06-15 22:43:40 +0000561 const size_t kMinDefaultLen = 4096;
Mike Aizatskyf0b3e852016-06-23 20:44:48 +0000562 FuzzingOptions Options;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000563 Options.Verbosity = Flags.verbosity;
564 Options.MaxLen = Flags.max_len;
Kostya Serebryany2a8440d2016-12-27 23:24:55 +0000565 Options.ExperimentalLenControl = Flags.experimental_len_control;
Kostya Serebryany589eae52017-06-15 22:43:40 +0000566 if (Flags.experimental_len_control && Flags.max_len == kMinDefaultLen)
Kostya Serebryany2a8440d2016-12-27 23:24:55 +0000567 Options.MaxLen = 1 << 20;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000568 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryany8a569172016-11-03 19:31:18 +0000569 Options.ErrorExitCode = Flags.error_exitcode;
Kostya Serebryany54a63632016-01-29 23:30:07 +0000570 Options.TimeoutExitCode = Flags.timeout_exitcode;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000571 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000572 Options.DoCrossOver = Flags.cross_over;
573 Options.MutateDepth = Flags.mutate_depth;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000574 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000575 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryanyc135b552016-07-15 23:27:19 +0000576 Options.UseMemmem = Flags.use_memmem;
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000577 Options.UseCmp = Flags.use_cmp;
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000578 Options.UseValueProfile = Flags.use_value_profile;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000579 Options.Shrink = Flags.shrink;
Kostya Serebryany1e99d542017-07-12 22:20:04 +0000580 Options.ReduceInputs = Flags.reduce_inputs;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000581 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000582 Options.PreferSmall = Flags.prefer_small;
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000583 Options.ReloadIntervalSec = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000584 Options.OnlyASCII = Flags.only_ascii;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000585 Options.DetectLeaks = Flags.detect_leaks;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000586 Options.TraceMalloc = Flags.trace_malloc;
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000587 Options.RssLimitMb = Flags.rss_limit_mb;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000588 if (Flags.runs >= 0)
589 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000590 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000591 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000592 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000593 if (Flags.artifact_prefix)
594 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000595 if (Flags.exact_artifact_path)
596 Options.ExactArtifactPath = Flags.exact_artifact_path;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000597 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000598 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000599 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000600 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000601 if (Flags.verbosity > 0 && !Dictionary.empty())
602 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000603 bool DoPlainRun = AllInputsAreFiles();
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000604 Options.SaveArtifacts =
605 !DoPlainRun || Flags.minimize_crash_internal_step;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000606 Options.PrintNewCovPcs = Flags.print_pcs;
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000607 Options.PrintFinalStats = Flags.print_final_stats;
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000608 Options.PrintCorpusStats = Flags.print_corpus_stats;
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000609 Options.PrintCoverage = Flags.print_coverage;
Mike Aizatsky9b415be2016-12-19 22:18:08 +0000610 Options.DumpCoverage = Flags.dump_coverage;
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000611 if (Flags.exit_on_src_pos)
612 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000613 if (Flags.exit_on_item)
614 Options.ExitOnItem = Flags.exit_on_item;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000615
Kostya Serebryanya3992212016-02-13 03:00:53 +0000616 unsigned Seed = Flags.seed;
617 // Initialize Seed.
618 if (Seed == 0)
Kostya Serebryany823c1812016-12-27 19:51:34 +0000619 Seed =
620 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
Kostya Serebryanya3992212016-02-13 03:00:53 +0000621 if (Flags.verbosity)
Kostya Serebryany64d24572016-03-12 01:57:04 +0000622 Printf("INFO: Seed: %u\n", Seed);
Kostya Serebryanya3992212016-02-13 03:00:53 +0000623
624 Random Rand(Seed);
Kostya Serebryany6c778112016-11-14 19:21:38 +0000625 auto *MD = new MutationDispatcher(Rand, Options);
626 auto *Corpus = new InputCorpus(Options.OutputCorpus);
627 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000628
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000629 for (auto &U: Dictionary)
Kostya Serebryany476f0ce2016-01-16 03:53:32 +0000630 if (U.size() <= Word::GetMaxSize())
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000631 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000632
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000633 StartRssThread(F, Flags.rss_limit_mb);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000634
Marcos Pividoric59b6922016-12-13 17:45:20 +0000635 Options.HandleAbrt = Flags.handle_abrt;
636 Options.HandleBus = Flags.handle_bus;
637 Options.HandleFpe = Flags.handle_fpe;
638 Options.HandleIll = Flags.handle_ill;
639 Options.HandleInt = Flags.handle_int;
640 Options.HandleSegv = Flags.handle_segv;
641 Options.HandleTerm = Flags.handle_term;
Kostya Serebryany4aa05902017-01-05 22:05:47 +0000642 Options.HandleXfsz = Flags.handle_xfsz;
Marcos Pividoric59b6922016-12-13 17:45:20 +0000643 SetSignalHandler(Options);
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000644
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000645 if (Flags.minimize_crash)
646 return MinimizeCrashInput(Args, Options);
647
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000648 if (Flags.minimize_crash_internal_step)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000649 return MinimizeCrashInputInternalStep(F, Corpus);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000650
Kostya Serebryanyac7a9ea2017-04-17 20:58:21 +0000651 if (Flags.cleanse_crash)
652 return CleanseCrashInput(Args, Options);
653
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000654 if (auto Name = Flags.run_equivalence_server) {
655 SMR.Destroy(Name);
Kostya Serebryany5c76e3d2017-02-01 00:07:47 +0000656 if (!SMR.Create(Name)) {
657 Printf("ERROR: can't create shared memory region\n");
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000658 return 1;
659 }
660 Printf("INFO: EQUIVALENCE SERVER UP\n");
661 while (true) {
662 SMR.WaitClient();
663 size_t Size = SMR.ReadByteArraySize();
664 SMR.WriteByteArray(nullptr, 0);
Kostya Serebryanyfe4ed9b2017-05-09 01:17:29 +0000665 const Unit tmp(SMR.GetByteArray(), SMR.GetByteArray() + Size);
Kostya Serebryany1e99d542017-07-12 22:20:04 +0000666 F->ExecuteCallback(tmp.data(), tmp.size());
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000667 SMR.PostServer();
668 }
669 return 0;
670 }
671
672 if (auto Name = Flags.use_equivalence_server) {
673 if (!SMR.Open(Name)) {
674 Printf("ERROR: can't open shared memory region\n");
675 return 1;
676 }
677 Printf("INFO: EQUIVALENCE CLIENT UP\n");
678 }
679
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000680 if (DoPlainRun) {
681 Options.SaveArtifacts = false;
Kostya Serebryany9d14e4b2016-02-12 02:32:03 +0000682 int Runs = std::max(1, Flags.runs);
683 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
684 Inputs->size(), Runs);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000685 for (auto &Path : *Inputs) {
686 auto StartTime = system_clock::now();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000687 Printf("Running: %s\n", Path.c_str());
Kostya Serebryany5c3701c2016-03-04 22:35:40 +0000688 for (int Iter = 0; Iter < Runs; Iter++)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000689 RunOneTest(F, Path.c_str(), Options.MaxLen);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000690 auto StopTime = system_clock::now();
691 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000692 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000693 }
Kostya Serebryanybdb220c2016-08-15 19:44:04 +0000694 Printf("***\n"
695 "*** NOTE: fuzzing was not performed, you have only\n"
696 "*** executed the target code on a fixed set of inputs.\n"
697 "***\n");
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000698 F->PrintFinalStats();
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000699 exit(0);
700 }
701
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000702 if (Flags.merge) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000703 if (Options.MaxLen == 0)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000704 F->SetMaxInputLen(kMaxSaneLen);
Kostya Serebryanyf81cc092017-03-14 21:47:52 +0000705 if (Flags.merge_control_file)
706 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
707 else
Kostya Serebryany4fc6dd72017-03-22 20:32:44 +0000708 F->CrashResistantMerge(Args, *Inputs,
709 Flags.load_coverage_summary,
710 Flags.save_coverage_summary);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000711 exit(0);
712 }
713
Kostya Serebryany64d24572016-03-12 01:57:04 +0000714 size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000715
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000716 UnitVector InitialCorpus;
717 for (auto &Inp : *Inputs) {
718 Printf("Loading corpus dir: %s\n", Inp.c_str());
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000719 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
720 TemporaryMaxLen, /*ExitOnError=*/false);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000721 }
Kostya Serebryany64d24572016-03-12 01:57:04 +0000722
Kostya Serebryanyf7e610e2017-03-17 01:40:09 +0000723 if (Flags.analyze_dict) {
724 if (Dictionary.empty() || Inputs->empty()) {
725 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
726 return 1;
727 }
728 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
729 Printf("Dictionary analysis failed\n");
730 exit(1);
731 }
732 Printf("Dictionary analysis suceeded\n");
733 exit(0);
734 }
735
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000736 if (Options.MaxLen == 0) {
737 size_t MaxLen = 0;
738 for (auto &U : InitialCorpus)
739 MaxLen = std::max(U.size(), MaxLen);
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000740 F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000741 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000742
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000743 if (InitialCorpus.empty()) {
Kostya Serebryany53c894d2016-11-12 02:27:21 +0000744 InitialCorpus.push_back(Unit({'\n'})); // Valid ASCII input.
Kostya Serebryany09087bb2016-04-18 21:14:11 +0000745 if (Options.Verbosity)
746 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
747 }
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000748 F->ShuffleAndMinimize(&InitialCorpus);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000749 InitialCorpus.clear(); // Don't need this memory any more.
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000750 F->Loop();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000751
Kostya Serebryany016852c2015-02-19 18:45:37 +0000752 if (Flags.verbosity)
Kostya Serebryanyae579a72017-02-14 22:14:36 +0000753 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000754 F->secondsSinceProcessStartUp());
755 F->PrintFinalStats();
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000756
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000757 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000758}
Dan Liew1873a492016-06-07 23:32:50 +0000759
760// Storage for global ExternalFunctions object.
761ExternalFunctions *EF = nullptr;
762
Kostya Serebryany016852c2015-02-19 18:45:37 +0000763} // namespace fuzzer