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