blob: 1ed7092377309973a33389adc099403cf56fb7e4 [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +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
12#include "FuzzerCorpus.h"
13#include "FuzzerIO.h"
14#include "FuzzerInterface.h"
15#include "FuzzerInternal.h"
16#include "FuzzerMutate.h"
17#include "FuzzerRandom.h"
18#include "FuzzerShmem.h"
19#include "FuzzerTracePC.h"
20#include <algorithm>
21#include <atomic>
22#include <chrono>
23#include <cstdlib>
24#include <cstring>
25#include <mutex>
26#include <string>
27#include <thread>
28
29// 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
33namespace fuzzer {
34
35// Program arguments.
36struct FlagDescription {
37 const char *Name;
38 const char *Description;
39 int Default;
40 int *IntFlag;
41 const char **StrFlag;
42 unsigned int *UIntFlag;
43};
44
45struct {
46#define FUZZER_DEPRECATED_FLAG(Name)
47#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
48#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
49#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
50#include "FuzzerFlags.def"
51#undef FUZZER_DEPRECATED_FLAG
52#undef FUZZER_FLAG_INT
53#undef FUZZER_FLAG_UNSIGNED
54#undef FUZZER_FLAG_STRING
55} Flags;
56
57static const FlagDescription FlagDescriptions [] {
58#define FUZZER_DEPRECATED_FLAG(Name) \
59 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
60#define FUZZER_FLAG_INT(Name, Default, Description) \
61 {#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},
65#define FUZZER_FLAG_STRING(Name, Description) \
66 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
67#include "FuzzerFlags.def"
68#undef FUZZER_DEPRECATED_FLAG
69#undef FUZZER_FLAG_INT
70#undef FUZZER_FLAG_UNSIGNED
71#undef FUZZER_FLAG_STRING
72};
73
74static const size_t kNumFlags =
75 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
76
george.karpenkovfbfa45c2017-08-27 23:20:09 +000077static Vector<std::string> *Inputs;
george.karpenkov29efa6d2017-08-21 23:25:50 +000078static std::string *ProgName;
79
80static void PrintHelp() {
81 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
89 Printf("\nFlags: (strictly in form -flag=value)\n");
90 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];
96 if (strstr(D.Description, "internal flag") == D.Description) continue;
97 Printf(" %s", D.Name);
98 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
99 Printf(" ");
100 Printf("\t");
101 Printf("%d\t%s\n", D.Default, D.Description);
102 }
103 Printf("\nFlags starting with '--' will be ignored and "
104 "will be passed verbatim to subprocesses.\n");
105}
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
115// Avoid calling stol as it triggers a bug in clang/glibc build.
116static long MyStol(const char *Str) {
117 long Res = 0;
118 long Sign = 1;
119 if (*Str == '-') {
120 Str++;
121 Sign = -1;
122 }
123 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 }
129 return Res * Sign;
130}
131
132static bool ParseOneFlag(const char *Param) {
133 if (Param[0] != '-') return false;
134 if (Param[1] == '-') {
135 static bool PrintedWarning = false;
136 if (!PrintedWarning) {
137 PrintedWarning = true;
138 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
139 }
140 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);
143 return true;
144 }
145 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) {
149 if (FlagDescriptions[F].IntFlag) {
150 int Val = MyStol(Str);
151 *FlagDescriptions[F].IntFlag = Val;
152 if (Flags.verbosity >= 2)
153 Printf("Flag: %s %d\n", Name, Val);
154 return true;
155 } 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;
161 } else if (FlagDescriptions[F].StrFlag) {
162 *FlagDescriptions[F].StrFlag = Str;
163 if (Flags.verbosity >= 2)
164 Printf("Flag: %s %s\n", Name, Str);
165 return true;
166 } else { // Deprecated flag.
167 Printf("Flag: %s: deprecated, don't use\n", Name);
168 return true;
169 }
170 }
171 }
172 Printf("\n\nWARNING: unrecognized flag '%s'; "
173 "use -help=1 to list all flags\n\n", Param);
174 return true;
175}
176
177// We don't use any library to minimize dependencies.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000178static void ParseFlags(const Vector<std::string> &Args) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000179 for (size_t F = 0; F < kNumFlags; F++) {
180 if (FlagDescriptions[F].IntFlag)
181 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
182 if (FlagDescriptions[F].UIntFlag)
183 *FlagDescriptions[F].UIntFlag =
184 static_cast<unsigned int>(FlagDescriptions[F].Default);
185 if (FlagDescriptions[F].StrFlag)
186 *FlagDescriptions[F].StrFlag = nullptr;
187 }
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000188 Inputs = new Vector<std::string>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000189 for (size_t A = 1; A < Args.size(); A++) {
190 if (ParseOneFlag(Args[A].c_str())) {
191 if (Flags.ignore_remaining_args)
192 break;
193 continue;
194 }
195 Inputs->push_back(Args[A]);
196 }
197}
198
199static std::mutex Mu;
200
201static void PulseThread() {
202 while (true) {
203 SleepSeconds(600);
204 std::lock_guard<std::mutex> Lock(Mu);
205 Printf("pulse...\n");
206 }
207}
208
209static void WorkerThread(const std::string &Cmd, std::atomic<unsigned> *Counter,
210 unsigned NumJobs, std::atomic<bool> *HasErrors) {
211 while (true) {
212 unsigned C = (*Counter)++;
213 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)
217 Printf("%s", ToRun.c_str());
218 int ExitCode = ExecuteCommand(ToRun);
219 if (ExitCode != 0)
220 *HasErrors = true;
221 std::lock_guard<std::mutex> Lock(Mu);
222 Printf("================== Job %u exited with exit code %d ============\n",
223 C, ExitCode);
224 fuzzer::CopyFileToErr(Log);
225 }
226}
227
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000228std::string CloneArgsWithoutX(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000229 const char *X1, const char *X2) {
230 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
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000239static int RunInMultipleProcesses(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000240 unsigned NumWorkers, unsigned NumJobs) {
241 std::atomic<unsigned> Counter(0);
242 std::atomic<bool> HasErrors(false);
243 std::string Cmd = CloneArgsWithoutX(Args, "jobs", "workers");
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000244 Vector<std::thread> V;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000245 std::thread Pulse(PulseThread);
246 Pulse.detach();
247 for (unsigned i = 0; i < NumWorkers; i++)
248 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
254static void RssThread(Fuzzer *F, size_t RssLimitMb) {
255 while (true) {
256 SleepSeconds(1);
257 size_t Peak = GetPeakRSSMb();
258 if (Peak > RssLimitMb)
259 F->RssLimitCallback();
260 }
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
269int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
270 Unit U = FileToVector(InputFilePath);
271 if (MaxLen && MaxLen < U.size())
272 U.resize(MaxLen);
273 F->ExecuteCallback(U.data(), U.size());
274 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
275 return 0;
276}
277
278static 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
286static 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
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000297int CleanseCrashInput(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000298 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
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000325 const Vector<uint8_t> ReplacementBytes = {' ', 0xff};
george.karpenkov29efa6d2017-08-21 23:25:50 +0000326 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
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000357int MinimizeCrashInput(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000358 const FuzzingOptions &Options) {
359 if (Inputs->size() != 1) {
360 Printf("ERROR: -minimize_crash should be given one input file\n");
361 exit(1);
362 }
363 std::string InputFilePath = Inputs->at(0);
364 auto BaseCmd = SplitBefore(
365 "-ignore_remaining_args=1",
366 CloneArgsWithoutX(Args, "minimize_crash", "exact_artifact_path"));
367 auto InputPos = BaseCmd.first.find(" " + InputFilePath + " ");
368 assert(InputPos != std::string::npos);
369 BaseCmd.first.erase(InputPos, InputFilePath.size() + 1);
370 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");
374 BaseCmd.first += " -max_total_time=600";
375 }
376
377 auto LogFilePath = DirPlusFile(
378 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
379 auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
380
381 std::string CurrentFilePath = InputFilePath;
382 while (true) {
383 Unit U = FileToVector(CurrentFilePath);
384 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
385 CurrentFilePath.c_str(), U.size());
386
387 auto Cmd = BaseCmd.first + " " + CurrentFilePath + LogFileRedirect + " " +
388 BaseCmd.second;
389
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());
399 auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
400 if (!DedupToken1.empty())
401 Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
402
403 std::string ArtifactPath =
404 Flags.exact_artifact_path
405 ? Flags.exact_artifact_path
406 : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
407 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);
411 CopyFileToErr(LogFilePath);
412 if (ExitCode == 0) {
413 if (Flags.exact_artifact_path) {
414 CurrentFilePath = Flags.exact_artifact_path;
415 WriteToFile(U, CurrentFilePath);
416 }
417 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
418 CurrentFilePath.c_str(), U.size());
419 break;
420 }
421 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
435 CurrentFilePath = ArtifactPath;
436 Printf("*********************************\n");
437 }
438 RemoveFile(LogFilePath);
439 return 0;
440}
441
442int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
443 assert(Inputs->size() == 1);
444 std::string InputFilePath = Inputs->at(0);
445 Unit U = FileToVector(InputFilePath);
446 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
447 if (U.size() < 2) {
448 Printf("INFO: The input is small enough, exiting\n");
449 exit(0);
450 }
451 F->SetMaxInputLen(U.size());
452 F->SetMaxMutationLen(U.size() - 1);
453 F->MinimizeCrashLoop(U);
454 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
455 exit(0);
456 return 0;
457}
458
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000459int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000460 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.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000465 Vector<int> Scores(Dict.size());
466 Vector<int> Usages(Dict.size());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000467
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000468 Vector<size_t> InitialFeatures;
469 Vector<size_t> ModifiedFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000470 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) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000480 Vector<uint8_t> Data = C;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000481 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
527int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
528 using namespace fuzzer;
529 assert(argc && argv && "Argument pointers cannot be nullptr");
530 std::string Argv0((*argv)[0]);
531 EF = new ExternalFunctions();
532 if (EF->LLVMFuzzerInitialize)
533 EF->LLVMFuzzerInitialize(argc, argv);
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000534 const Vector<std::string> Args(*argv, *argv + *argc);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000535 assert(!Args.empty());
536 ProgName = new std::string(Args[0]);
537 if (Argv0 != *ProgName) {
538 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
539 exit(1);
540 }
541 ParseFlags(Args);
542 if (Flags.help) {
543 PrintHelp();
544 return 0;
545 }
546
547 if (Flags.close_fd_mask & 2)
548 DupAndCloseStderr();
549 if (Flags.close_fd_mask & 1)
550 CloseStdout();
551
552 if (Flags.jobs > 0 && Flags.workers == 0) {
553 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
554 if (Flags.workers > 1)
555 Printf("Running %u workers\n", Flags.workers);
556 }
557
558 if (Flags.workers > 0 && Flags.jobs > 0)
559 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
560
561 const size_t kMaxSaneLen = 1 << 20;
562 const size_t kMinDefaultLen = 4096;
563 FuzzingOptions Options;
564 Options.Verbosity = Flags.verbosity;
565 Options.MaxLen = Flags.max_len;
566 Options.ExperimentalLenControl = Flags.experimental_len_control;
567 Options.UnitTimeoutSec = Flags.timeout;
568 Options.ErrorExitCode = Flags.error_exitcode;
569 Options.TimeoutExitCode = Flags.timeout_exitcode;
570 Options.MaxTotalTimeSec = Flags.max_total_time;
571 Options.DoCrossOver = Flags.cross_over;
572 Options.MutateDepth = Flags.mutate_depth;
573 Options.UseCounters = Flags.use_counters;
574 Options.UseIndirCalls = Flags.use_indir_calls;
575 Options.UseMemmem = Flags.use_memmem;
576 Options.UseCmp = Flags.use_cmp;
577 Options.UseValueProfile = Flags.use_value_profile;
578 Options.Shrink = Flags.shrink;
579 Options.ReduceInputs = Flags.reduce_inputs;
580 Options.ShuffleAtStartUp = Flags.shuffle;
581 Options.PreferSmall = Flags.prefer_small;
582 Options.ReloadIntervalSec = Flags.reload;
583 Options.OnlyASCII = Flags.only_ascii;
584 Options.DetectLeaks = Flags.detect_leaks;
585 Options.TraceMalloc = Flags.trace_malloc;
586 Options.RssLimitMb = Flags.rss_limit_mb;
587 if (Flags.runs >= 0)
588 Options.MaxNumberOfRuns = Flags.runs;
589 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
590 Options.OutputCorpus = (*Inputs)[0];
591 Options.ReportSlowUnits = Flags.report_slow_units;
592 if (Flags.artifact_prefix)
593 Options.ArtifactPrefix = Flags.artifact_prefix;
594 if (Flags.exact_artifact_path)
595 Options.ExactArtifactPath = Flags.exact_artifact_path;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000596 Vector<Unit> Dictionary;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000597 if (Flags.dict)
598 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
599 return 1;
600 if (Flags.verbosity > 0 && !Dictionary.empty())
601 Printf("Dictionary: %zd entries\n", Dictionary.size());
602 bool DoPlainRun = AllInputsAreFiles();
603 Options.SaveArtifacts =
604 !DoPlainRun || Flags.minimize_crash_internal_step;
605 Options.PrintNewCovPcs = Flags.print_pcs;
kcc00da6482017-08-25 20:09:25 +0000606 Options.PrintNewCovFuncs = Flags.print_funcs;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000607 Options.PrintFinalStats = Flags.print_final_stats;
608 Options.PrintCorpusStats = Flags.print_corpus_stats;
609 Options.PrintCoverage = Flags.print_coverage;
610 Options.DumpCoverage = Flags.dump_coverage;
611 if (Flags.exit_on_src_pos)
612 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
613 if (Flags.exit_on_item)
614 Options.ExitOnItem = Flags.exit_on_item;
615
616 unsigned Seed = Flags.seed;
617 // Initialize Seed.
618 if (Seed == 0)
619 Seed =
620 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
621 if (Flags.verbosity)
622 Printf("INFO: Seed: %u\n", Seed);
623
624 Random Rand(Seed);
625 auto *MD = new MutationDispatcher(Rand, Options);
626 auto *Corpus = new InputCorpus(Options.OutputCorpus);
627 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
628
629 for (auto &U: Dictionary)
630 if (U.size() <= Word::GetMaxSize())
631 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
632
633 StartRssThread(F, Flags.rss_limit_mb);
634
635 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;
642 Options.HandleXfsz = Flags.handle_xfsz;
643 SetSignalHandler(Options);
644
645 std::atexit(Fuzzer::StaticExitCallback);
646
647 if (Flags.minimize_crash)
648 return MinimizeCrashInput(Args, Options);
649
650 if (Flags.minimize_crash_internal_step)
651 return MinimizeCrashInputInternalStep(F, Corpus);
652
653 if (Flags.cleanse_crash)
654 return CleanseCrashInput(Args, Options);
655
656 if (auto Name = Flags.run_equivalence_server) {
657 SMR.Destroy(Name);
658 if (!SMR.Create(Name)) {
659 Printf("ERROR: can't create shared memory region\n");
660 return 1;
661 }
662 Printf("INFO: EQUIVALENCE SERVER UP\n");
663 while (true) {
664 SMR.WaitClient();
665 size_t Size = SMR.ReadByteArraySize();
666 SMR.WriteByteArray(nullptr, 0);
667 const Unit tmp(SMR.GetByteArray(), SMR.GetByteArray() + Size);
668 F->ExecuteCallback(tmp.data(), tmp.size());
669 SMR.PostServer();
670 }
671 return 0;
672 }
673
674 if (auto Name = Flags.use_equivalence_server) {
675 if (!SMR.Open(Name)) {
676 Printf("ERROR: can't open shared memory region\n");
677 return 1;
678 }
679 Printf("INFO: EQUIVALENCE CLIENT UP\n");
680 }
681
682 if (DoPlainRun) {
683 Options.SaveArtifacts = false;
684 int Runs = std::max(1, Flags.runs);
685 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
686 Inputs->size(), Runs);
687 for (auto &Path : *Inputs) {
688 auto StartTime = system_clock::now();
689 Printf("Running: %s\n", Path.c_str());
690 for (int Iter = 0; Iter < Runs; Iter++)
691 RunOneTest(F, Path.c_str(), Options.MaxLen);
692 auto StopTime = system_clock::now();
693 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
694 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
695 }
696 Printf("***\n"
697 "*** NOTE: fuzzing was not performed, you have only\n"
698 "*** executed the target code on a fixed set of inputs.\n"
699 "***\n");
700 F->PrintFinalStats();
701 exit(0);
702 }
703
704 if (Flags.merge) {
705 if (Options.MaxLen == 0)
706 F->SetMaxInputLen(kMaxSaneLen);
707 if (Flags.merge_control_file)
708 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
709 else
710 F->CrashResistantMerge(Args, *Inputs,
711 Flags.load_coverage_summary,
712 Flags.save_coverage_summary);
713 exit(0);
714 }
715
716 size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
717
718 UnitVector InitialCorpus;
719 for (auto &Inp : *Inputs) {
720 Printf("Loading corpus dir: %s\n", Inp.c_str());
721 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
722 TemporaryMaxLen, /*ExitOnError=*/false);
723 }
724
725 if (Flags.analyze_dict) {
726 if (Dictionary.empty() || Inputs->empty()) {
727 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
728 return 1;
729 }
730 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
731 Printf("Dictionary analysis failed\n");
732 exit(1);
733 }
734 Printf("Dictionary analysis suceeded\n");
735 exit(0);
736 }
737
738 if (Options.MaxLen == 0) {
739 size_t MaxLen = 0;
740 for (auto &U : InitialCorpus)
741 MaxLen = std::max(U.size(), MaxLen);
742 F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
743 }
744
745 if (InitialCorpus.empty()) {
746 InitialCorpus.push_back(Unit({'\n'})); // Valid ASCII input.
747 if (Options.Verbosity)
748 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
749 }
750 F->ShuffleAndMinimize(&InitialCorpus);
751 InitialCorpus.clear(); // Don't need this memory any more.
752 F->Loop();
753
754 if (Flags.verbosity)
755 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
756 F->secondsSinceProcessStartUp());
757 F->PrintFinalStats();
758
759 exit(0); // Don't let F destroy itself.
760}
761
762// Storage for global ExternalFunctions object.
763ExternalFunctions *EF = nullptr;
764
765} // namespace fuzzer