blob: e93c79cfcec6c55e19bd36c52ebcc96e580fbd71 [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 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)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000152 Printf("Flag: %s %d\n", Name, Val);;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000153 return true;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000154 } else if (FlagDescriptions[F].UIntFlag) {
155 unsigned int Val = std::stoul(Str);
156 *FlagDescriptions[F].UIntFlag = Val;
157 if (Flags.verbosity >= 2)
158 Printf("Flag: %s %u\n", Name, Val);
159 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000160 } else if (FlagDescriptions[F].StrFlag) {
161 *FlagDescriptions[F].StrFlag = Str;
162 if (Flags.verbosity >= 2)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000163 Printf("Flag: %s %s\n", Name, Str);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000164 return true;
Kostya Serebryany3d95dd92016-03-01 22:33:14 +0000165 } else { // Deprecated flag.
166 Printf("Flag: %s: deprecated, don't use\n", Name);
167 return true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000168 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000169 }
170 }
Kostya Serebryanyf8177312016-06-01 16:41:12 +0000171 Printf("\n\nWARNING: unrecognized flag '%s'; "
172 "use -help=1 to list all flags\n\n", Param);
173 return true;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000174}
175
176// We don't use any library to minimize dependencies.
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000177static void ParseFlags(const std::vector<std::string> &Args) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000178 for (size_t F = 0; F < kNumFlags; F++) {
179 if (FlagDescriptions[F].IntFlag)
180 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
Mike Aizatskya1a5c692015-12-10 20:41:53 +0000181 if (FlagDescriptions[F].UIntFlag)
182 *FlagDescriptions[F].UIntFlag =
183 static_cast<unsigned int>(FlagDescriptions[F].Default);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000184 if (FlagDescriptions[F].StrFlag)
185 *FlagDescriptions[F].StrFlag = nullptr;
186 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000187 Inputs = new std::vector<std::string>;
188 for (size_t A = 1; A < Args.size(); A++) {
189 if (ParseOneFlag(Args[A].c_str())) continue;
190 Inputs->push_back(Args[A]);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000191 }
192}
193
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000194static std::mutex Mu;
195
196static void PulseThread() {
197 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000198 SleepSeconds(600);
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000199 std::lock_guard<std::mutex> Lock(Mu);
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000200 Printf("pulse...\n");
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000201 }
202}
203
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000204static void WorkerThread(const std::string &Cmd, std::atomic<unsigned> *Counter,
205 unsigned NumJobs, std::atomic<bool> *HasErrors) {
Kostya Serebryany016852c2015-02-19 18:45:37 +0000206 while (true) {
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000207 unsigned C = (*Counter)++;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000208 if (C >= NumJobs) break;
209 std::string Log = "fuzz-" + std::to_string(C) + ".log";
210 std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
211 if (Flags.verbosity)
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000212 Printf("%s", ToRun.c_str());
Hans Wennborge6319962016-04-11 20:35:17 +0000213 int ExitCode = ExecuteCommand(ToRun);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000214 if (ExitCode != 0)
215 *HasErrors = true;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000216 std::lock_guard<std::mutex> Lock(Mu);
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000217 Printf("================== Job %u exited with exit code %d ============\n",
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000218 C, ExitCode);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000219 fuzzer::CopyFileToErr(Log);
220 }
221}
222
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000223std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
224 const char *X1, const char *X2) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000225 std::string Cmd;
226 for (auto &S : Args) {
227 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
228 continue;
229 Cmd += S + " ";
230 }
231 return Cmd;
232}
233
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000234static int RunInMultipleProcesses(const std::vector<std::string> &Args,
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000235 unsigned NumWorkers, unsigned NumJobs) {
236 std::atomic<unsigned> Counter(0);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000237 std::atomic<bool> HasErrors(false);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000238 std::string Cmd = CloneArgsWithoutX(Args, "jobs", "workers");
Kostya Serebryany016852c2015-02-19 18:45:37 +0000239 std::vector<std::thread> V;
Kostya Serebryany83fd4862015-05-11 21:31:51 +0000240 std::thread Pulse(PulseThread);
Kostya Serebryanycd7629c2015-05-12 01:43:20 +0000241 Pulse.detach();
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000242 for (unsigned i = 0; i < NumWorkers; i++)
Kostya Serebryany016852c2015-02-19 18:45:37 +0000243 V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
244 for (auto &T : V)
245 T.join();
246 return HasErrors ? 1 : 0;
247}
248
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000249static void RssThread(Fuzzer *F, size_t RssLimitMb) {
250 while (true) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000251 SleepSeconds(1);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000252 size_t Peak = GetPeakRSSMb();
253 if (Peak > RssLimitMb)
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000254 F->RssLimitCallback();
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000255 }
256}
257
258static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
259 if (!RssLimitMb) return;
260 std::thread T(RssThread, F, RssLimitMb);
261 T.detach();
262}
263
Kostya Serebryanya016a452016-08-30 14:52:05 +0000264int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
Ivan Krasin95e82d52015-10-01 23:23:06 +0000265 Unit U = FileToVector(InputFilePath);
Kostya Serebryanya016a452016-08-30 14:52:05 +0000266 if (MaxLen && MaxLen < U.size())
267 U.resize(MaxLen);
268 F->RunOne(U.data(), U.size());
Kostya Serebryanybb59ef72016-10-18 18:38:08 +0000269 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
Ivan Krasin95e82d52015-10-01 23:23:06 +0000270 return 0;
271}
272
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000273static bool AllInputsAreFiles() {
274 if (Inputs->empty()) return false;
275 for (auto &Path : *Inputs)
276 if (!IsFile(Path))
277 return false;
278 return true;
279}
280
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000281static std::string GetDedupTokenFromFile(const std::string &Path) {
282 auto S = FileToString(Path);
283 auto Beg = S.find("DEDUP_TOKEN:");
284 if (Beg == std::string::npos)
285 return "";
286 auto End = S.find('\n', Beg);
287 if (End == std::string::npos)
288 return "";
289 return S.substr(Beg, End - Beg);
290}
291
Kostya Serebryanyac7a9ea2017-04-17 20:58:21 +0000292int CleanseCrashInput(const std::vector<std::string> &Args,
293 const FuzzingOptions &Options) {
294 if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
295 Printf("ERROR: -cleanse_crash should be given one input file and"
296 " -exact_artifact_path\n");
297 exit(1);
298 }
299 std::string InputFilePath = Inputs->at(0);
300 std::string OutputFilePath = Flags.exact_artifact_path;
301 std::string BaseCmd =
302 CloneArgsWithoutX(Args, "cleanse_crash", "cleanse_crash");
303
304 auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
305 assert(InputPos != std::string::npos);
306 BaseCmd.erase(InputPos, InputFilePath.size() + 1);
307
308 auto LogFilePath = DirPlusFile(
309 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
310 auto TmpFilePath = DirPlusFile(
311 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".repro");
312 auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
313
314 auto Cmd = BaseCmd + " " + TmpFilePath + LogFileRedirect;
315
316 std::string CurrentFilePath = InputFilePath;
317 auto U = FileToVector(CurrentFilePath);
318 size_t Size = U.size();
319
320 const std::vector<uint8_t> ReplacementBytes = {' ', 0xff};
321 for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
322 bool Changed = false;
323 for (size_t Idx = 0; Idx < Size; Idx++) {
324 Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
325 Idx, Size);
326 uint8_t OriginalByte = U[Idx];
327 if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
328 ReplacementBytes.end(),
329 OriginalByte))
330 continue;
331 for (auto NewByte : ReplacementBytes) {
332 U[Idx] = NewByte;
333 WriteToFile(U, TmpFilePath);
334 auto ExitCode = ExecuteCommand(Cmd);
335 RemoveFile(TmpFilePath);
336 if (!ExitCode) {
337 U[Idx] = OriginalByte;
338 } else {
339 Changed = true;
340 Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
341 WriteToFile(U, OutputFilePath);
342 break;
343 }
344 }
345 }
346 if (!Changed) break;
347 }
348 RemoveFile(LogFilePath);
349 return 0;
350}
351
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000352int MinimizeCrashInput(const std::vector<std::string> &Args,
353 const FuzzingOptions &Options) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000354 if (Inputs->size() != 1) {
355 Printf("ERROR: -minimize_crash should be given one input file\n");
356 exit(1);
357 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000358 std::string InputFilePath = Inputs->at(0);
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000359 std::string BaseCmd =
360 CloneArgsWithoutX(Args, "minimize_crash", "exact_artifact_path");
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000361 auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
362 assert(InputPos != std::string::npos);
363 BaseCmd.erase(InputPos, InputFilePath.size() + 1);
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000364 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
365 Printf("INFO: you need to specify -runs=N or "
366 "-max_total_time=N with -minimize_crash=1\n"
367 "INFO: defaulting to -max_total_time=600\n");
368 BaseCmd += " -max_total_time=600";
369 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000370
371 auto LogFilePath = DirPlusFile(
372 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
373 auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000374
375 std::string CurrentFilePath = InputFilePath;
376 while (true) {
377 Unit U = FileToVector(CurrentFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000378 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
379 CurrentFilePath.c_str(), U.size());
380
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000381 auto Cmd = BaseCmd + " " + CurrentFilePath + LogFileRedirect;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000382
383 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
384 int ExitCode = ExecuteCommand(Cmd);
385 if (ExitCode == 0) {
386 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
387 exit(1);
388 }
389 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
390 "it further\n",
391 CurrentFilePath.c_str(), U.size());
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000392 auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
393 if (!DedupToken1.empty())
394 Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000395
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000396 std::string ArtifactPath =
Kostya Serebryanydba9ded2017-03-24 21:09:16 +0000397 Flags.exact_artifact_path
398 ? Flags.exact_artifact_path
399 : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000400 Cmd += " -minimize_crash_internal_step=1 -exact_artifact_path=" +
401 ArtifactPath;
402 Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
403 ExitCode = ExecuteCommand(Cmd);
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000404 CopyFileToErr(LogFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000405 if (ExitCode == 0) {
Kostya Serebryanya31300e2016-12-13 00:40:47 +0000406 if (Flags.exact_artifact_path) {
407 CurrentFilePath = Flags.exact_artifact_path;
408 WriteToFile(U, CurrentFilePath);
409 }
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000410 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
411 CurrentFilePath.c_str(), U.size());
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000412 break;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000413 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000414 auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
415 if (!DedupToken2.empty())
416 Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
417
418 if (DedupToken1 != DedupToken2) {
419 if (Flags.exact_artifact_path) {
420 CurrentFilePath = Flags.exact_artifact_path;
421 WriteToFile(U, CurrentFilePath);
422 }
423 Printf("CRASH_MIN: mismatch in dedup tokens"
424 " (looks like a different bug). Won't minimize further\n");
425 break;
426 }
427
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000428 CurrentFilePath = ArtifactPath;
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000429 Printf("*********************************\n");
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000430 }
Kostya Serebryany86e630b2017-03-25 00:56:08 +0000431 RemoveFile(LogFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000432 return 0;
433}
434
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000435int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000436 assert(Inputs->size() == 1);
437 std::string InputFilePath = Inputs->at(0);
438 Unit U = FileToVector(InputFilePath);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000439 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000440 if (U.size() < 2) {
441 Printf("INFO: The input is small enough, exiting\n");
442 exit(0);
443 }
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000444 Corpus->AddToCorpus(U, 0);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000445 F->SetMaxInputLen(U.size());
446 F->SetMaxMutationLen(U.size() - 1);
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000447 F->MinimizeCrashLoop(U);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000448 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
449 exit(0);
450 return 0;
451}
452
Kostya Serebryanyf7e610e2017-03-17 01:40:09 +0000453int AnalyzeDictionary(Fuzzer *F, const std::vector<Unit>& Dict,
454 UnitVector& Corpus) {
455 Printf("Started dictionary minimization (up to %d tests)\n",
456 Dict.size() * Corpus.size() * 2);
457
458 // Scores and usage count for each dictionary unit.
459 std::vector<int> Scores(Dict.size());
460 std::vector<int> Usages(Dict.size());
461
462 std::vector<size_t> InitialFeatures;
463 std::vector<size_t> ModifiedFeatures;
464 for (auto &C : Corpus) {
465 // Get coverage for the testcase without modifications.
466 F->ExecuteCallback(C.data(), C.size());
467 InitialFeatures.clear();
468 TPC.CollectFeatures([&](size_t Feature) -> bool {
469 InitialFeatures.push_back(Feature);
470 return true;
471 });
472
473 for (size_t i = 0; i < Dict.size(); ++i) {
474 auto Data = C;
475 auto StartPos = std::search(Data.begin(), Data.end(),
476 Dict[i].begin(), Dict[i].end());
477 // Skip dictionary unit, if the testcase does not contain it.
478 if (StartPos == Data.end())
479 continue;
480
481 ++Usages[i];
482 while (StartPos != Data.end()) {
483 // Replace all occurrences of dictionary unit in the testcase.
484 auto EndPos = StartPos + Dict[i].size();
485 for (auto It = StartPos; It != EndPos; ++It)
486 *It ^= 0xFF;
487
488 StartPos = std::search(EndPos, Data.end(),
489 Dict[i].begin(), Dict[i].end());
490 }
491
492 // Get coverage for testcase with masked occurrences of dictionary unit.
493 F->ExecuteCallback(Data.data(), Data.size());
494 ModifiedFeatures.clear();
495 TPC.CollectFeatures([&](size_t Feature) -> bool {
496 ModifiedFeatures.push_back(Feature);
497 return true;
498 });
499
500 if (InitialFeatures == ModifiedFeatures)
501 --Scores[i];
502 else
503 Scores[i] += 2;
504 }
505 }
506
507 Printf("###### Useless dictionary elements. ######\n");
508 for (size_t i = 0; i < Dict.size(); ++i) {
509 // Dictionary units with positive score are treated as useful ones.
510 if (Scores[i] > 0)
511 continue;
512
513 Printf("\"");
514 PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
515 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
516 }
517 Printf("###### End of useless dictionary elements. ######\n");
518 return 0;
519}
520
Dan Liewd3c33112016-06-02 05:48:02 +0000521int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000522 using namespace fuzzer;
Dan Liewd3c33112016-06-02 05:48:02 +0000523 assert(argc && argv && "Argument pointers cannot be nullptr");
Kostya Serebryany87a38112017-01-20 21:34:24 +0000524 std::string Argv0((*argv)[0]);
Dan Liew1873a492016-06-07 23:32:50 +0000525 EF = new ExternalFunctions();
526 if (EF->LLVMFuzzerInitialize)
527 EF->LLVMFuzzerInitialize(argc, argv);
Dan Liewd3c33112016-06-02 05:48:02 +0000528 const std::vector<std::string> Args(*argv, *argv + *argc);
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000529 assert(!Args.empty());
530 ProgName = new std::string(Args[0]);
Kostya Serebryanyd9667912017-01-21 00:13:50 +0000531 if (Argv0 != *ProgName) {
532 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
533 exit(1);
534 }
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000535 ParseFlags(Args);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000536 if (Flags.help) {
537 PrintHelp();
538 return 0;
539 }
540
Kostya Serebryany49e40902016-03-18 20:58:29 +0000541 if (Flags.close_fd_mask & 2)
542 DupAndCloseStderr();
543 if (Flags.close_fd_mask & 1)
544 CloseStdout();
545
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000546 if (Flags.jobs > 0 && Flags.workers == 0) {
547 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
548 if (Flags.workers > 1)
Marcos Pividori6e3d8852016-12-13 17:45:53 +0000549 Printf("Running %u workers\n", Flags.workers);
Kostya Serebryany9690fcf2015-05-12 18:51:57 +0000550 }
551
Kostya Serebryany016852c2015-02-19 18:45:37 +0000552 if (Flags.workers > 0 && Flags.jobs > 0)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000553 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000554
Kostya Serebryany64d24572016-03-12 01:57:04 +0000555 const size_t kMaxSaneLen = 1 << 20;
Kostya Serebryany0c5e3af2016-03-15 01:28:00 +0000556 const size_t kMinDefaultLen = 64;
Mike Aizatskyf0b3e852016-06-23 20:44:48 +0000557 FuzzingOptions Options;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000558 Options.Verbosity = Flags.verbosity;
559 Options.MaxLen = Flags.max_len;
Kostya Serebryany2a8440d2016-12-27 23:24:55 +0000560 Options.ExperimentalLenControl = Flags.experimental_len_control;
561 if (Flags.experimental_len_control && Flags.max_len == 64)
562 Options.MaxLen = 1 << 20;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000563 Options.UnitTimeoutSec = Flags.timeout;
Kostya Serebryany8a569172016-11-03 19:31:18 +0000564 Options.ErrorExitCode = Flags.error_exitcode;
Kostya Serebryany54a63632016-01-29 23:30:07 +0000565 Options.TimeoutExitCode = Flags.timeout_exitcode;
Kostya Serebryanyb85db172015-10-02 20:47:55 +0000566 Options.MaxTotalTimeSec = Flags.max_total_time;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000567 Options.DoCrossOver = Flags.cross_over;
568 Options.MutateDepth = Flags.mutate_depth;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000569 Options.UseCounters = Flags.use_counters;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000570 Options.UseIndirCalls = Flags.use_indir_calls;
Kostya Serebryanyc135b552016-07-15 23:27:19 +0000571 Options.UseMemmem = Flags.use_memmem;
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000572 Options.UseCmp = Flags.use_cmp;
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000573 Options.UseValueProfile = Flags.use_value_profile;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000574 Options.Shrink = Flags.shrink;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000575 Options.ShuffleAtStartUp = Flags.shuffle;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000576 Options.PreferSmall = Flags.prefer_small;
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000577 Options.ReloadIntervalSec = Flags.reload;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000578 Options.OnlyASCII = Flags.only_ascii;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000579 Options.DetectLeaks = Flags.detect_leaks;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000580 Options.TraceMalloc = Flags.trace_malloc;
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000581 Options.RssLimitMb = Flags.rss_limit_mb;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000582 if (Flags.runs >= 0)
583 Options.MaxNumberOfRuns = Flags.runs;
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000584 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
Kostya Serebryanya938bcb2015-09-10 16:57:57 +0000585 Options.OutputCorpus = (*Inputs)[0];
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000586 Options.ReportSlowUnits = Flags.report_slow_units;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000587 if (Flags.artifact_prefix)
588 Options.ArtifactPrefix = Flags.artifact_prefix;
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000589 if (Flags.exact_artifact_path)
590 Options.ExactArtifactPath = Flags.exact_artifact_path;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000591 std::vector<Unit> Dictionary;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000592 if (Flags.dict)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000593 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
Kostya Serebryany7d211662015-09-04 00:12:11 +0000594 return 1;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000595 if (Flags.verbosity > 0 && !Dictionary.empty())
596 Printf("Dictionary: %zd entries\n", Dictionary.size());
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000597 bool DoPlainRun = AllInputsAreFiles();
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000598 Options.SaveArtifacts =
599 !DoPlainRun || Flags.minimize_crash_internal_step;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000600 Options.PrintNewCovPcs = Flags.print_pcs;
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000601 Options.PrintFinalStats = Flags.print_final_stats;
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000602 Options.PrintCorpusStats = Flags.print_corpus_stats;
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000603 Options.PrintCoverage = Flags.print_coverage;
Mike Aizatsky9b415be2016-12-19 22:18:08 +0000604 Options.DumpCoverage = Flags.dump_coverage;
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000605 if (Flags.exit_on_src_pos)
606 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000607 if (Flags.exit_on_item)
608 Options.ExitOnItem = Flags.exit_on_item;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000609
Kostya Serebryanya3992212016-02-13 03:00:53 +0000610 unsigned Seed = Flags.seed;
611 // Initialize Seed.
612 if (Seed == 0)
Kostya Serebryany823c1812016-12-27 19:51:34 +0000613 Seed =
614 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
Kostya Serebryanya3992212016-02-13 03:00:53 +0000615 if (Flags.verbosity)
Kostya Serebryany64d24572016-03-12 01:57:04 +0000616 Printf("INFO: Seed: %u\n", Seed);
Kostya Serebryanya3992212016-02-13 03:00:53 +0000617
618 Random Rand(Seed);
Kostya Serebryany6c778112016-11-14 19:21:38 +0000619 auto *MD = new MutationDispatcher(Rand, Options);
620 auto *Corpus = new InputCorpus(Options.OutputCorpus);
621 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
Kostya Serebryany016852c2015-02-19 18:45:37 +0000622
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000623 for (auto &U: Dictionary)
Kostya Serebryany476f0ce2016-01-16 03:53:32 +0000624 if (U.size() <= Word::GetMaxSize())
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000625 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000626
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000627 StartRssThread(F, Flags.rss_limit_mb);
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000628
Marcos Pividoric59b6922016-12-13 17:45:20 +0000629 Options.HandleAbrt = Flags.handle_abrt;
630 Options.HandleBus = Flags.handle_bus;
631 Options.HandleFpe = Flags.handle_fpe;
632 Options.HandleIll = Flags.handle_ill;
633 Options.HandleInt = Flags.handle_int;
634 Options.HandleSegv = Flags.handle_segv;
635 Options.HandleTerm = Flags.handle_term;
Kostya Serebryany4aa05902017-01-05 22:05:47 +0000636 Options.HandleXfsz = Flags.handle_xfsz;
Marcos Pividoric59b6922016-12-13 17:45:20 +0000637 SetSignalHandler(Options);
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000638
Kostya Serebryany38b5d3c2017-01-19 19:38:12 +0000639 if (Flags.minimize_crash)
640 return MinimizeCrashInput(Args, Options);
641
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000642 if (Flags.minimize_crash_internal_step)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000643 return MinimizeCrashInputInternalStep(F, Corpus);
Kostya Serebryanye2d0f632016-09-01 01:22:27 +0000644
Kostya Serebryanyac7a9ea2017-04-17 20:58:21 +0000645 if (Flags.cleanse_crash)
646 return CleanseCrashInput(Args, Options);
647
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000648 if (auto Name = Flags.run_equivalence_server) {
649 SMR.Destroy(Name);
Kostya Serebryany5c76e3d2017-02-01 00:07:47 +0000650 if (!SMR.Create(Name)) {
651 Printf("ERROR: can't create shared memory region\n");
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000652 return 1;
653 }
654 Printf("INFO: EQUIVALENCE SERVER UP\n");
655 while (true) {
656 SMR.WaitClient();
657 size_t Size = SMR.ReadByteArraySize();
658 SMR.WriteByteArray(nullptr, 0);
Kostya Serebryanyfe4ed9b2017-05-09 01:17:29 +0000659 const Unit tmp(SMR.GetByteArray(), SMR.GetByteArray() + Size);
660 F->RunOne(tmp.data(), tmp.size());
Kostya Serebryany98d592c2017-01-20 20:57:07 +0000661 SMR.PostServer();
662 }
663 return 0;
664 }
665
666 if (auto Name = Flags.use_equivalence_server) {
667 if (!SMR.Open(Name)) {
668 Printf("ERROR: can't open shared memory region\n");
669 return 1;
670 }
671 Printf("INFO: EQUIVALENCE CLIENT UP\n");
672 }
673
Kostya Serebryanyc5575aa2016-03-17 19:59:39 +0000674 if (DoPlainRun) {
675 Options.SaveArtifacts = false;
Kostya Serebryany9d14e4b2016-02-12 02:32:03 +0000676 int Runs = std::max(1, Flags.runs);
677 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
678 Inputs->size(), Runs);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000679 for (auto &Path : *Inputs) {
680 auto StartTime = system_clock::now();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000681 Printf("Running: %s\n", Path.c_str());
Kostya Serebryany5c3701c2016-03-04 22:35:40 +0000682 for (int Iter = 0; Iter < Runs; Iter++)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000683 RunOneTest(F, Path.c_str(), Options.MaxLen);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000684 auto StopTime = system_clock::now();
685 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
Kostya Serebryany042d1a72016-06-17 13:07:06 +0000686 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000687 }
Kostya Serebryanybdb220c2016-08-15 19:44:04 +0000688 Printf("***\n"
689 "*** NOTE: fuzzing was not performed, you have only\n"
690 "*** executed the target code on a fixed set of inputs.\n"
691 "***\n");
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000692 F->PrintFinalStats();
Kostya Serebryanybfbe7fc2016-02-02 03:03:47 +0000693 exit(0);
694 }
695
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000696 if (Flags.merge) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000697 if (Options.MaxLen == 0)
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000698 F->SetMaxInputLen(kMaxSaneLen);
Kostya Serebryanyf81cc092017-03-14 21:47:52 +0000699 if (Flags.merge_control_file)
700 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
701 else
Kostya Serebryany4fc6dd72017-03-22 20:32:44 +0000702 F->CrashResistantMerge(Args, *Inputs,
703 Flags.load_coverage_summary,
704 Flags.save_coverage_summary);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000705 exit(0);
706 }
707
Kostya Serebryany64d24572016-03-12 01:57:04 +0000708 size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
Kostya Serebryany016852c2015-02-19 18:45:37 +0000709
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000710 UnitVector InitialCorpus;
711 for (auto &Inp : *Inputs) {
712 Printf("Loading corpus dir: %s\n", Inp.c_str());
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000713 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
714 TemporaryMaxLen, /*ExitOnError=*/false);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000715 }
Kostya Serebryany64d24572016-03-12 01:57:04 +0000716
Kostya Serebryanyf7e610e2017-03-17 01:40:09 +0000717 if (Flags.analyze_dict) {
718 if (Dictionary.empty() || Inputs->empty()) {
719 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
720 return 1;
721 }
722 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
723 Printf("Dictionary analysis failed\n");
724 exit(1);
725 }
726 Printf("Dictionary analysis suceeded\n");
727 exit(0);
728 }
729
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000730 if (Options.MaxLen == 0) {
731 size_t MaxLen = 0;
732 for (auto &U : InitialCorpus)
733 MaxLen = std::max(U.size(), MaxLen);
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000734 F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000735 }
Kostya Serebryany016852c2015-02-19 18:45:37 +0000736
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000737 if (InitialCorpus.empty()) {
Kostya Serebryany53c894d2016-11-12 02:27:21 +0000738 InitialCorpus.push_back(Unit({'\n'})); // Valid ASCII input.
Kostya Serebryany09087bb2016-04-18 21:14:11 +0000739 if (Options.Verbosity)
740 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
741 }
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000742 F->ShuffleAndMinimize(&InitialCorpus);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000743 InitialCorpus.clear(); // Don't need this memory any more.
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000744 F->Loop();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000745
Kostya Serebryany016852c2015-02-19 18:45:37 +0000746 if (Flags.verbosity)
Kostya Serebryanyae579a72017-02-14 22:14:36 +0000747 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
Kostya Serebryanyfc1c4052016-11-12 00:24:35 +0000748 F->secondsSinceProcessStartUp());
749 F->PrintFinalStats();
Kostya Serebryany20e9bcb2015-05-23 01:07:46 +0000750
Kostya Serebryanyc8cd29f2015-10-03 07:02:05 +0000751 exit(0); // Don't let F destroy itself.
Kostya Serebryany016852c2015-02-19 18:45:37 +0000752}
Dan Liew1873a492016-06-07 23:32:50 +0000753
754// Storage for global ExternalFunctions object.
755ExternalFunctions *EF = nullptr;
756
Kostya Serebryany016852c2015-02-19 18:45:37 +0000757} // namespace fuzzer