1 //===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 // FuzzerDriver and flag parsing.
9 //===----------------------------------------------------------------------===//
10 
11 #include "FuzzerCommand.h"
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 "FuzzerTracePC.h"
19 #include <algorithm>
20 #include <atomic>
21 #include <chrono>
22 #include <cstdlib>
23 #include <cstring>
24 #include <mutex>
25 #include <string>
26 #include <thread>
27 
28 // This function should be present in the libFuzzer so that the client
29 // binary can test for its existence.
30 #if LIBFUZZER_MSVC
31 extern "C" void __libfuzzer_is_present() {}
32 #pragma comment(linker, "/include:__libfuzzer_is_present")
33 #else
34 extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
35 #endif  // LIBFUZZER_MSVC
36 
37 namespace fuzzer {
38 
39 // Program arguments.
40 struct FlagDescription {
41   const char *Name;
42   const char *Description;
43   int   Default;
44   int   *IntFlag;
45   const char **StrFlag;
46   unsigned int *UIntFlag;
47 };
48 
49 struct {
50 #define FUZZER_DEPRECATED_FLAG(Name)
51 #define FUZZER_FLAG_INT(Name, Default, Description) int Name;
52 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
53 #define FUZZER_FLAG_STRING(Name, Description) const char *Name;
54 #include "FuzzerFlags.def"
55 #undef FUZZER_DEPRECATED_FLAG
56 #undef FUZZER_FLAG_INT
57 #undef FUZZER_FLAG_UNSIGNED
58 #undef FUZZER_FLAG_STRING
59 } Flags;
60 
61 static const FlagDescription FlagDescriptions [] {
62 #define FUZZER_DEPRECATED_FLAG(Name)                                           \
63   {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
64 #define FUZZER_FLAG_INT(Name, Default, Description)                            \
65   {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
66 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description)                       \
67   {#Name,   Description, static_cast<int>(Default),                            \
68    nullptr, nullptr, &Flags.Name},
69 #define FUZZER_FLAG_STRING(Name, Description)                                  \
70   {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
71 #include "FuzzerFlags.def"
72 #undef FUZZER_DEPRECATED_FLAG
73 #undef FUZZER_FLAG_INT
74 #undef FUZZER_FLAG_UNSIGNED
75 #undef FUZZER_FLAG_STRING
76 };
77 
78 static const size_t kNumFlags =
79     sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
80 
81 static Vector<std::string> *Inputs;
82 static std::string *ProgName;
83 
84 static void PrintHelp() {
85   Printf("Usage:\n");
86   auto Prog = ProgName->c_str();
87   Printf("\nTo run fuzzing pass 0 or more directories.\n");
88   Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
89 
90   Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
91   Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
92 
93   Printf("\nFlags: (strictly in form -flag=value)\n");
94   size_t MaxFlagLen = 0;
95   for (size_t F = 0; F < kNumFlags; F++)
96     MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
97 
98   for (size_t F = 0; F < kNumFlags; F++) {
99     const auto &D = FlagDescriptions[F];
100     if (strstr(D.Description, "internal flag") == D.Description) continue;
101     Printf(" %s", D.Name);
102     for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
103       Printf(" ");
104     Printf("\t");
105     Printf("%d\t%s\n", D.Default, D.Description);
106   }
107   Printf("\nFlags starting with '--' will be ignored and "
108             "will be passed verbatim to subprocesses.\n");
109 }
110 
111 static const char *FlagValue(const char *Param, const char *Name) {
112   size_t Len = strlen(Name);
113   if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
114       Param[Len + 1] == '=')
115       return &Param[Len + 2];
116   return nullptr;
117 }
118 
119 // Avoid calling stol as it triggers a bug in clang/glibc build.
120 static long MyStol(const char *Str) {
121   long Res = 0;
122   long Sign = 1;
123   if (*Str == '-') {
124     Str++;
125     Sign = -1;
126   }
127   for (size_t i = 0; Str[i]; i++) {
128     char Ch = Str[i];
129     if (Ch < '0' || Ch > '9')
130       return Res;
131     Res = Res * 10 + (Ch - '0');
132   }
133   return Res * Sign;
134 }
135 
136 static bool ParseOneFlag(const char *Param) {
137   if (Param[0] != '-') return false;
138   if (Param[1] == '-') {
139     static bool PrintedWarning = false;
140     if (!PrintedWarning) {
141       PrintedWarning = true;
142       Printf("INFO: libFuzzer ignores flags that start with '--'\n");
143     }
144     for (size_t F = 0; F < kNumFlags; F++)
145       if (FlagValue(Param + 1, FlagDescriptions[F].Name))
146         Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
147     return true;
148   }
149   for (size_t F = 0; F < kNumFlags; F++) {
150     const char *Name = FlagDescriptions[F].Name;
151     const char *Str = FlagValue(Param, Name);
152     if (Str)  {
153       if (FlagDescriptions[F].IntFlag) {
154         int Val = MyStol(Str);
155         *FlagDescriptions[F].IntFlag = Val;
156         if (Flags.verbosity >= 2)
157           Printf("Flag: %s %d\n", Name, Val);
158         return true;
159       } else if (FlagDescriptions[F].UIntFlag) {
160         unsigned int Val = std::stoul(Str);
161         *FlagDescriptions[F].UIntFlag = Val;
162         if (Flags.verbosity >= 2)
163           Printf("Flag: %s %u\n", Name, Val);
164         return true;
165       } else if (FlagDescriptions[F].StrFlag) {
166         *FlagDescriptions[F].StrFlag = Str;
167         if (Flags.verbosity >= 2)
168           Printf("Flag: %s %s\n", Name, Str);
169         return true;
170       } else {  // Deprecated flag.
171         Printf("Flag: %s: deprecated, don't use\n", Name);
172         return true;
173       }
174     }
175   }
176   Printf("\n\nWARNING: unrecognized flag '%s'; "
177          "use -help=1 to list all flags\n\n", Param);
178   return true;
179 }
180 
181 // We don't use any library to minimize dependencies.
182 static void ParseFlags(const Vector<std::string> &Args) {
183   for (size_t F = 0; F < kNumFlags; F++) {
184     if (FlagDescriptions[F].IntFlag)
185       *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
186     if (FlagDescriptions[F].UIntFlag)
187       *FlagDescriptions[F].UIntFlag =
188           static_cast<unsigned int>(FlagDescriptions[F].Default);
189     if (FlagDescriptions[F].StrFlag)
190       *FlagDescriptions[F].StrFlag = nullptr;
191   }
192   Inputs = new Vector<std::string>;
193   for (size_t A = 1; A < Args.size(); A++) {
194     if (ParseOneFlag(Args[A].c_str())) {
195       if (Flags.ignore_remaining_args)
196         break;
197       continue;
198     }
199     Inputs->push_back(Args[A]);
200   }
201 }
202 
203 static std::mutex Mu;
204 
205 static void PulseThread() {
206   while (true) {
207     SleepSeconds(600);
208     std::lock_guard<std::mutex> Lock(Mu);
209     Printf("pulse...\n");
210   }
211 }
212 
213 static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter,
214                          unsigned NumJobs, std::atomic<bool> *HasErrors) {
215   while (true) {
216     unsigned C = (*Counter)++;
217     if (C >= NumJobs) break;
218     std::string Log = "fuzz-" + std::to_string(C) + ".log";
219     Command Cmd(BaseCmd);
220     Cmd.setOutputFile(Log);
221     Cmd.combineOutAndErr();
222     if (Flags.verbosity) {
223       std::string CommandLine = Cmd.toString();
224       Printf("%s\n", CommandLine.c_str());
225     }
226     int ExitCode = ExecuteCommand(Cmd);
227     if (ExitCode != 0)
228       *HasErrors = true;
229     std::lock_guard<std::mutex> Lock(Mu);
230     Printf("================== Job %u exited with exit code %d ============\n",
231            C, ExitCode);
232     fuzzer::CopyFileToErr(Log);
233   }
234 }
235 
236 std::string CloneArgsWithoutX(const Vector<std::string> &Args,
237                               const char *X1, const char *X2) {
238   std::string Cmd;
239   for (auto &S : Args) {
240     if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
241       continue;
242     Cmd += S + " ";
243   }
244   return Cmd;
245 }
246 
247 static int RunInMultipleProcesses(const Vector<std::string> &Args,
248                                   unsigned NumWorkers, unsigned NumJobs) {
249   std::atomic<unsigned> Counter(0);
250   std::atomic<bool> HasErrors(false);
251   Command Cmd(Args);
252   Cmd.removeFlag("jobs");
253   Cmd.removeFlag("workers");
254   Vector<std::thread> V;
255   std::thread Pulse(PulseThread);
256   Pulse.detach();
257   for (unsigned i = 0; i < NumWorkers; i++)
258     V.push_back(std::thread(WorkerThread, std::ref(Cmd), &Counter, NumJobs, &HasErrors));
259   for (auto &T : V)
260     T.join();
261   return HasErrors ? 1 : 0;
262 }
263 
264 static void RssThread(Fuzzer *F, size_t RssLimitMb) {
265   while (true) {
266     SleepSeconds(1);
267     size_t Peak = GetPeakRSSMb();
268     if (Peak > RssLimitMb)
269       F->RssLimitCallback();
270   }
271 }
272 
273 static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
274   if (!RssLimitMb) return;
275   std::thread T(RssThread, F, RssLimitMb);
276   T.detach();
277 }
278 
279 int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
280   Unit U = FileToVector(InputFilePath);
281   if (MaxLen && MaxLen < U.size())
282     U.resize(MaxLen);
283   F->ExecuteCallback(U.data(), U.size());
284   F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
285   return 0;
286 }
287 
288 static bool AllInputsAreFiles() {
289   if (Inputs->empty()) return false;
290   for (auto &Path : *Inputs)
291     if (!IsFile(Path))
292       return false;
293   return true;
294 }
295 
296 static std::string GetDedupTokenFromFile(const std::string &Path) {
297   auto S = FileToString(Path);
298   auto Beg = S.find("DEDUP_TOKEN:");
299   if (Beg == std::string::npos)
300     return "";
301   auto End = S.find('\n', Beg);
302   if (End == std::string::npos)
303     return "";
304   return S.substr(Beg, End - Beg);
305 }
306 
307 int CleanseCrashInput(const Vector<std::string> &Args,
308                        const FuzzingOptions &Options) {
309   if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
310     Printf("ERROR: -cleanse_crash should be given one input file and"
311           " -exact_artifact_path\n");
312     exit(1);
313   }
314   std::string InputFilePath = Inputs->at(0);
315   std::string OutputFilePath = Flags.exact_artifact_path;
316   Command Cmd(Args);
317   Cmd.removeFlag("cleanse_crash");
318 
319   assert(Cmd.hasArgument(InputFilePath));
320   Cmd.removeArgument(InputFilePath);
321 
322   auto LogFilePath = DirPlusFile(
323       TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
324   auto TmpFilePath = DirPlusFile(
325       TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".repro");
326   Cmd.addArgument(TmpFilePath);
327   Cmd.setOutputFile(LogFilePath);
328   Cmd.combineOutAndErr();
329 
330   std::string CurrentFilePath = InputFilePath;
331   auto U = FileToVector(CurrentFilePath);
332   size_t Size = U.size();
333 
334   const Vector<uint8_t> ReplacementBytes = {' ', 0xff};
335   for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
336     bool Changed = false;
337     for (size_t Idx = 0; Idx < Size; Idx++) {
338       Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
339              Idx, Size);
340       uint8_t OriginalByte = U[Idx];
341       if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
342                                               ReplacementBytes.end(),
343                                               OriginalByte))
344         continue;
345       for (auto NewByte : ReplacementBytes) {
346         U[Idx] = NewByte;
347         WriteToFile(U, TmpFilePath);
348         auto ExitCode = ExecuteCommand(Cmd);
349         RemoveFile(TmpFilePath);
350         if (!ExitCode) {
351           U[Idx] = OriginalByte;
352         } else {
353           Changed = true;
354           Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
355           WriteToFile(U, OutputFilePath);
356           break;
357         }
358       }
359     }
360     if (!Changed) break;
361   }
362   RemoveFile(LogFilePath);
363   return 0;
364 }
365 
366 int MinimizeCrashInput(const Vector<std::string> &Args,
367                        const FuzzingOptions &Options) {
368   if (Inputs->size() != 1) {
369     Printf("ERROR: -minimize_crash should be given one input file\n");
370     exit(1);
371   }
372   std::string InputFilePath = Inputs->at(0);
373   Command BaseCmd(Args);
374   BaseCmd.removeFlag("minimize_crash");
375   BaseCmd.removeFlag("exact_artifact_path");
376   assert(BaseCmd.hasArgument(InputFilePath));
377   BaseCmd.removeArgument(InputFilePath);
378   if (Flags.runs <= 0 && Flags.max_total_time == 0) {
379     Printf("INFO: you need to specify -runs=N or "
380            "-max_total_time=N with -minimize_crash=1\n"
381            "INFO: defaulting to -max_total_time=600\n");
382     BaseCmd.addFlag("max_total_time", "600");
383   }
384 
385   auto LogFilePath = DirPlusFile(
386       TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
387   BaseCmd.setOutputFile(LogFilePath);
388   BaseCmd.combineOutAndErr();
389 
390   std::string CurrentFilePath = InputFilePath;
391   while (true) {
392     Unit U = FileToVector(CurrentFilePath);
393     Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
394            CurrentFilePath.c_str(), U.size());
395 
396     Command Cmd(BaseCmd);
397     Cmd.addArgument(CurrentFilePath);
398 
399     std::string CommandLine = Cmd.toString();
400     Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
401     int ExitCode = ExecuteCommand(Cmd);
402     if (ExitCode == 0) {
403       Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
404       exit(1);
405     }
406     Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
407            "it further\n",
408            CurrentFilePath.c_str(), U.size());
409     auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
410     if (!DedupToken1.empty())
411       Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
412 
413     std::string ArtifactPath =
414         Flags.exact_artifact_path
415             ? Flags.exact_artifact_path
416             : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
417     Cmd.addFlag("minimize_crash_internal_step", "1");
418     Cmd.addFlag("exact_artifact_path", ArtifactPath);
419     CommandLine = Cmd.toString();
420     Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
421     ExitCode = ExecuteCommand(Cmd);
422     CopyFileToErr(LogFilePath);
423     if (ExitCode == 0) {
424       if (Flags.exact_artifact_path) {
425         CurrentFilePath = Flags.exact_artifact_path;
426         WriteToFile(U, CurrentFilePath);
427       }
428       Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
429              CurrentFilePath.c_str(), U.size());
430       break;
431     }
432     auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
433     if (!DedupToken2.empty())
434       Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
435 
436     if (DedupToken1 != DedupToken2) {
437       if (Flags.exact_artifact_path) {
438         CurrentFilePath = Flags.exact_artifact_path;
439         WriteToFile(U, CurrentFilePath);
440       }
441       Printf("CRASH_MIN: mismatch in dedup tokens"
442              " (looks like a different bug). Won't minimize further\n");
443       break;
444     }
445 
446     CurrentFilePath = ArtifactPath;
447     Printf("*********************************\n");
448   }
449   RemoveFile(LogFilePath);
450   return 0;
451 }
452 
453 int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
454   assert(Inputs->size() == 1);
455   std::string InputFilePath = Inputs->at(0);
456   Unit U = FileToVector(InputFilePath);
457   Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
458   if (U.size() < 2) {
459     Printf("INFO: The input is small enough, exiting\n");
460     exit(0);
461   }
462   F->SetMaxInputLen(U.size());
463   F->SetMaxMutationLen(U.size() - 1);
464   F->MinimizeCrashLoop(U);
465   Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
466   exit(0);
467   return 0;
468 }
469 
470 int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict,
471                       UnitVector& Corpus) {
472   Printf("Started dictionary minimization (up to %d tests)\n",
473          Dict.size() * Corpus.size() * 2);
474 
475   // Scores and usage count for each dictionary unit.
476   Vector<int> Scores(Dict.size());
477   Vector<int> Usages(Dict.size());
478 
479   Vector<size_t> InitialFeatures;
480   Vector<size_t> ModifiedFeatures;
481   for (auto &C : Corpus) {
482     // Get coverage for the testcase without modifications.
483     F->ExecuteCallback(C.data(), C.size());
484     InitialFeatures.clear();
485     TPC.CollectFeatures([&](size_t Feature) {
486       InitialFeatures.push_back(Feature);
487     });
488 
489     for (size_t i = 0; i < Dict.size(); ++i) {
490       Vector<uint8_t> Data = C;
491       auto StartPos = std::search(Data.begin(), Data.end(),
492                                   Dict[i].begin(), Dict[i].end());
493       // Skip dictionary unit, if the testcase does not contain it.
494       if (StartPos == Data.end())
495         continue;
496 
497       ++Usages[i];
498       while (StartPos != Data.end()) {
499         // Replace all occurrences of dictionary unit in the testcase.
500         auto EndPos = StartPos + Dict[i].size();
501         for (auto It = StartPos; It != EndPos; ++It)
502           *It ^= 0xFF;
503 
504         StartPos = std::search(EndPos, Data.end(),
505                                Dict[i].begin(), Dict[i].end());
506       }
507 
508       // Get coverage for testcase with masked occurrences of dictionary unit.
509       F->ExecuteCallback(Data.data(), Data.size());
510       ModifiedFeatures.clear();
511       TPC.CollectFeatures([&](size_t Feature) {
512         ModifiedFeatures.push_back(Feature);
513       });
514 
515       if (InitialFeatures == ModifiedFeatures)
516         --Scores[i];
517       else
518         Scores[i] += 2;
519     }
520   }
521 
522   Printf("###### Useless dictionary elements. ######\n");
523   for (size_t i = 0; i < Dict.size(); ++i) {
524     // Dictionary units with positive score are treated as useful ones.
525     if (Scores[i] > 0)
526        continue;
527 
528     Printf("\"");
529     PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
530     Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
531   }
532   Printf("###### End of useless dictionary elements. ######\n");
533   return 0;
534 }
535 
536 int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
537   using namespace fuzzer;
538   assert(argc && argv && "Argument pointers cannot be nullptr");
539   std::string Argv0((*argv)[0]);
540   EF = new ExternalFunctions();
541   if (EF->LLVMFuzzerInitialize)
542     EF->LLVMFuzzerInitialize(argc, argv);
543   if (EF->__msan_scoped_disable_interceptor_checks)
544     EF->__msan_scoped_disable_interceptor_checks();
545   const Vector<std::string> Args(*argv, *argv + *argc);
546   assert(!Args.empty());
547   ProgName = new std::string(Args[0]);
548   if (Argv0 != *ProgName) {
549     Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
550     exit(1);
551   }
552   ParseFlags(Args);
553   if (Flags.help) {
554     PrintHelp();
555     return 0;
556   }
557 
558   if (Flags.close_fd_mask & 2)
559     DupAndCloseStderr();
560   if (Flags.close_fd_mask & 1)
561     CloseStdout();
562 
563   if (Flags.jobs > 0 && Flags.workers == 0) {
564     Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
565     if (Flags.workers > 1)
566       Printf("Running %u workers\n", Flags.workers);
567   }
568 
569   if (Flags.workers > 0 && Flags.jobs > 0)
570     return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
571 
572   FuzzingOptions Options;
573   Options.Verbosity = Flags.verbosity;
574   Options.MaxLen = Flags.max_len;
575   Options.LenControl = Flags.len_control;
576   Options.UnitTimeoutSec = Flags.timeout;
577   Options.ErrorExitCode = Flags.error_exitcode;
578   Options.TimeoutExitCode = Flags.timeout_exitcode;
579   Options.MaxTotalTimeSec = Flags.max_total_time;
580   Options.DoCrossOver = Flags.cross_over;
581   Options.MutateDepth = Flags.mutate_depth;
582   Options.ReduceDepth = Flags.reduce_depth;
583   Options.UseCounters = Flags.use_counters;
584   Options.UseMemmem = Flags.use_memmem;
585   Options.UseCmp = Flags.use_cmp;
586   Options.UseValueProfile = Flags.use_value_profile;
587   Options.Shrink = Flags.shrink;
588   Options.ReduceInputs = Flags.reduce_inputs;
589   Options.ShuffleAtStartUp = Flags.shuffle;
590   Options.PreferSmall = Flags.prefer_small;
591   Options.ReloadIntervalSec = Flags.reload;
592   Options.OnlyASCII = Flags.only_ascii;
593   Options.DetectLeaks = Flags.detect_leaks;
594   Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval;
595   Options.TraceMalloc = Flags.trace_malloc;
596   Options.RssLimitMb = Flags.rss_limit_mb;
597   Options.MallocLimitMb = Flags.malloc_limit_mb;
598   if (!Options.MallocLimitMb)
599     Options.MallocLimitMb = Options.RssLimitMb;
600   if (Flags.runs >= 0)
601     Options.MaxNumberOfRuns = Flags.runs;
602   if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
603     Options.OutputCorpus = (*Inputs)[0];
604   Options.ReportSlowUnits = Flags.report_slow_units;
605   if (Flags.artifact_prefix)
606     Options.ArtifactPrefix = Flags.artifact_prefix;
607   if (Flags.exact_artifact_path)
608     Options.ExactArtifactPath = Flags.exact_artifact_path;
609   Vector<Unit> Dictionary;
610   if (Flags.dict)
611     if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
612       return 1;
613   if (Flags.verbosity > 0 && !Dictionary.empty())
614     Printf("Dictionary: %zd entries\n", Dictionary.size());
615   bool DoPlainRun = AllInputsAreFiles();
616   Options.SaveArtifacts =
617       !DoPlainRun || Flags.minimize_crash_internal_step;
618   Options.PrintNewCovPcs = Flags.print_pcs;
619   Options.PrintNewCovFuncs = Flags.print_funcs;
620   Options.PrintFinalStats = Flags.print_final_stats;
621   Options.PrintCorpusStats = Flags.print_corpus_stats;
622   Options.PrintCoverage = Flags.print_coverage;
623   if (Flags.exit_on_src_pos)
624     Options.ExitOnSrcPos = Flags.exit_on_src_pos;
625   if (Flags.exit_on_item)
626     Options.ExitOnItem = Flags.exit_on_item;
627   if (Flags.focus_function)
628     Options.FocusFunction = Flags.focus_function;
629   if (Flags.data_flow_trace)
630     Options.DataFlowTrace = Flags.data_flow_trace;
631   Options.LazyCounters = Flags.lazy_counters;
632 
633   unsigned Seed = Flags.seed;
634   // Initialize Seed.
635   if (Seed == 0)
636     Seed =
637         std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
638   if (Flags.verbosity)
639     Printf("INFO: Seed: %u\n", Seed);
640 
641   Random Rand(Seed);
642   auto *MD = new MutationDispatcher(Rand, Options);
643   auto *Corpus = new InputCorpus(Options.OutputCorpus);
644   auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
645 
646   for (auto &U: Dictionary)
647     if (U.size() <= Word::GetMaxSize())
648       MD->AddWordToManualDictionary(Word(U.data(), U.size()));
649 
650   StartRssThread(F, Flags.rss_limit_mb);
651 
652   Options.HandleAbrt = Flags.handle_abrt;
653   Options.HandleBus = Flags.handle_bus;
654   Options.HandleFpe = Flags.handle_fpe;
655   Options.HandleIll = Flags.handle_ill;
656   Options.HandleInt = Flags.handle_int;
657   Options.HandleSegv = Flags.handle_segv;
658   Options.HandleTerm = Flags.handle_term;
659   Options.HandleXfsz = Flags.handle_xfsz;
660   Options.HandleUsr1 = Flags.handle_usr1;
661   Options.HandleUsr2 = Flags.handle_usr2;
662   SetSignalHandler(Options);
663 
664   std::atexit(Fuzzer::StaticExitCallback);
665 
666   if (Flags.minimize_crash)
667     return MinimizeCrashInput(Args, Options);
668 
669   if (Flags.minimize_crash_internal_step)
670     return MinimizeCrashInputInternalStep(F, Corpus);
671 
672   if (Flags.cleanse_crash)
673     return CleanseCrashInput(Args, Options);
674 
675   if (DoPlainRun) {
676     Options.SaveArtifacts = false;
677     int Runs = std::max(1, Flags.runs);
678     Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
679            Inputs->size(), Runs);
680     for (auto &Path : *Inputs) {
681       auto StartTime = system_clock::now();
682       Printf("Running: %s\n", Path.c_str());
683       for (int Iter = 0; Iter < Runs; Iter++)
684         RunOneTest(F, Path.c_str(), Options.MaxLen);
685       auto StopTime = system_clock::now();
686       auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
687       Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
688     }
689     Printf("***\n"
690            "*** NOTE: fuzzing was not performed, you have only\n"
691            "***       executed the target code on a fixed set of inputs.\n"
692            "***\n");
693     F->PrintFinalStats();
694     exit(0);
695   }
696 
697   if (Flags.merge) {
698     F->CrashResistantMerge(Args, *Inputs,
699                            Flags.load_coverage_summary,
700                            Flags.save_coverage_summary,
701                            Flags.merge_control_file);
702     exit(0);
703   }
704 
705   if (Flags.merge_inner) {
706     const size_t kDefaultMaxMergeLen = 1 << 20;
707     if (Options.MaxLen == 0)
708       F->SetMaxInputLen(kDefaultMaxMergeLen);
709     assert(Flags.merge_control_file);
710     F->CrashResistantMergeInternalStep(Flags.merge_control_file);
711     exit(0);
712   }
713 
714   if (Flags.analyze_dict) {
715     size_t MaxLen = INT_MAX;  // Large max length.
716     UnitVector InitialCorpus;
717     for (auto &Inp : *Inputs) {
718       Printf("Loading corpus dir: %s\n", Inp.c_str());
719       ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
720                              MaxLen, /*ExitOnError=*/false);
721     }
722 
723     if (Dictionary.empty() || Inputs->empty()) {
724       Printf("ERROR: can't analyze dict without dict and corpus provided\n");
725       return 1;
726     }
727     if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
728       Printf("Dictionary analysis failed\n");
729       exit(1);
730     }
731     Printf("Dictionary analysis succeeded\n");
732     exit(0);
733   }
734 
735   F->Loop(*Inputs);
736 
737   if (Flags.verbosity)
738     Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
739            F->secondsSinceProcessStartUp());
740   F->PrintFinalStats();
741 
742   exit(0);  // Don't let F destroy itself.
743 }
744 
745 // Storage for global ExternalFunctions object.
746 ExternalFunctions *EF = nullptr;
747 
748 }  // namespace fuzzer
749