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 
201   Inputs = new Vector<std::string>;
202   for (size_t A = 1; A < Args.size(); A++) {
203     if (ParseOneFlag(Args[A].c_str())) {
204       if (Flags.ignore_remaining_args)
205         break;
206       continue;
207     }
208     Inputs->push_back(Args[A]);
209   }
210 }
211 
212 static std::mutex Mu;
213 
214 static void PulseThread() {
215   while (true) {
216     SleepSeconds(600);
217     std::lock_guard<std::mutex> Lock(Mu);
218     Printf("pulse...\n");
219   }
220 }
221 
222 static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter,
223                          unsigned NumJobs, std::atomic<bool> *HasErrors) {
224   while (true) {
225     unsigned C = (*Counter)++;
226     if (C >= NumJobs) break;
227     std::string Log = "fuzz-" + std::to_string(C) + ".log";
228     Command Cmd(BaseCmd);
229     Cmd.setOutputFile(Log);
230     Cmd.combineOutAndErr();
231     if (Flags.verbosity) {
232       std::string CommandLine = Cmd.toString();
233       Printf("%s\n", CommandLine.c_str());
234     }
235     int ExitCode = ExecuteCommand(Cmd);
236     if (ExitCode != 0)
237       *HasErrors = true;
238     std::lock_guard<std::mutex> Lock(Mu);
239     Printf("================== Job %u exited with exit code %d ============\n",
240            C, ExitCode);
241     fuzzer::CopyFileToErr(Log);
242   }
243 }
244 
245 std::string CloneArgsWithoutX(const Vector<std::string> &Args,
246                               const char *X1, const char *X2) {
247   std::string Cmd;
248   for (auto &S : Args) {
249     if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
250       continue;
251     Cmd += S + " ";
252   }
253   return Cmd;
254 }
255 
256 static int RunInMultipleProcesses(const Vector<std::string> &Args,
257                                   unsigned NumWorkers, unsigned NumJobs) {
258   std::atomic<unsigned> Counter(0);
259   std::atomic<bool> HasErrors(false);
260   Command Cmd(Args);
261   Cmd.removeFlag("jobs");
262   Cmd.removeFlag("workers");
263   Vector<std::thread> V;
264   std::thread Pulse(PulseThread);
265   Pulse.detach();
266   for (unsigned i = 0; i < NumWorkers; i++)
267     V.push_back(std::thread(WorkerThread, std::ref(Cmd), &Counter, NumJobs, &HasErrors));
268   for (auto &T : V)
269     T.join();
270   return HasErrors ? 1 : 0;
271 }
272 
273 static void RssThread(Fuzzer *F, size_t RssLimitMb) {
274   while (true) {
275     SleepSeconds(1);
276     size_t Peak = GetPeakRSSMb();
277     if (Peak > RssLimitMb)
278       F->RssLimitCallback();
279   }
280 }
281 
282 static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
283   if (!RssLimitMb)
284     return;
285   std::thread T(RssThread, F, RssLimitMb);
286   T.detach();
287 }
288 
289 int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
290   Unit U = FileToVector(InputFilePath);
291   if (MaxLen && MaxLen < U.size())
292     U.resize(MaxLen);
293   F->ExecuteCallback(U.data(), U.size());
294   F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
295   return 0;
296 }
297 
298 static bool AllInputsAreFiles() {
299   if (Inputs->empty()) return false;
300   for (auto &Path : *Inputs)
301     if (!IsFile(Path))
302       return false;
303   return true;
304 }
305 
306 static std::string GetDedupTokenFromFile(const std::string &Path) {
307   auto S = FileToString(Path);
308   auto Beg = S.find("DEDUP_TOKEN:");
309   if (Beg == std::string::npos)
310     return "";
311   auto End = S.find('\n', Beg);
312   if (End == std::string::npos)
313     return "";
314   return S.substr(Beg, End - Beg);
315 }
316 
317 int CleanseCrashInput(const Vector<std::string> &Args,
318                        const FuzzingOptions &Options) {
319   if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
320     Printf("ERROR: -cleanse_crash should be given one input file and"
321           " -exact_artifact_path\n");
322     exit(1);
323   }
324   std::string InputFilePath = Inputs->at(0);
325   std::string OutputFilePath = Flags.exact_artifact_path;
326   Command Cmd(Args);
327   Cmd.removeFlag("cleanse_crash");
328 
329   assert(Cmd.hasArgument(InputFilePath));
330   Cmd.removeArgument(InputFilePath);
331 
332   auto LogFilePath = TempPath(".txt");
333   auto TmpFilePath = TempPath(".repro");
334   Cmd.addArgument(TmpFilePath);
335   Cmd.setOutputFile(LogFilePath);
336   Cmd.combineOutAndErr();
337 
338   std::string CurrentFilePath = InputFilePath;
339   auto U = FileToVector(CurrentFilePath);
340   size_t Size = U.size();
341 
342   const Vector<uint8_t> ReplacementBytes = {' ', 0xff};
343   for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
344     bool Changed = false;
345     for (size_t Idx = 0; Idx < Size; Idx++) {
346       Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
347              Idx, Size);
348       uint8_t OriginalByte = U[Idx];
349       if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
350                                               ReplacementBytes.end(),
351                                               OriginalByte))
352         continue;
353       for (auto NewByte : ReplacementBytes) {
354         U[Idx] = NewByte;
355         WriteToFile(U, TmpFilePath);
356         auto ExitCode = ExecuteCommand(Cmd);
357         RemoveFile(TmpFilePath);
358         if (!ExitCode) {
359           U[Idx] = OriginalByte;
360         } else {
361           Changed = true;
362           Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
363           WriteToFile(U, OutputFilePath);
364           break;
365         }
366       }
367     }
368     if (!Changed) break;
369   }
370   RemoveFile(LogFilePath);
371   return 0;
372 }
373 
374 int MinimizeCrashInput(const Vector<std::string> &Args,
375                        const FuzzingOptions &Options) {
376   if (Inputs->size() != 1) {
377     Printf("ERROR: -minimize_crash should be given one input file\n");
378     exit(1);
379   }
380   std::string InputFilePath = Inputs->at(0);
381   Command BaseCmd(Args);
382   BaseCmd.removeFlag("minimize_crash");
383   BaseCmd.removeFlag("exact_artifact_path");
384   assert(BaseCmd.hasArgument(InputFilePath));
385   BaseCmd.removeArgument(InputFilePath);
386   if (Flags.runs <= 0 && Flags.max_total_time == 0) {
387     Printf("INFO: you need to specify -runs=N or "
388            "-max_total_time=N with -minimize_crash=1\n"
389            "INFO: defaulting to -max_total_time=600\n");
390     BaseCmd.addFlag("max_total_time", "600");
391   }
392 
393   auto LogFilePath = TempPath(".txt");
394   BaseCmd.setOutputFile(LogFilePath);
395   BaseCmd.combineOutAndErr();
396 
397   std::string CurrentFilePath = InputFilePath;
398   while (true) {
399     Unit U = FileToVector(CurrentFilePath);
400     Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
401            CurrentFilePath.c_str(), U.size());
402 
403     Command Cmd(BaseCmd);
404     Cmd.addArgument(CurrentFilePath);
405 
406     std::string CommandLine = Cmd.toString();
407     Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
408     int ExitCode = ExecuteCommand(Cmd);
409     if (ExitCode == 0) {
410       Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
411       exit(1);
412     }
413     Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
414            "it further\n",
415            CurrentFilePath.c_str(), U.size());
416     auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
417     if (!DedupToken1.empty())
418       Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
419 
420     std::string ArtifactPath =
421         Flags.exact_artifact_path
422             ? Flags.exact_artifact_path
423             : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
424     Cmd.addFlag("minimize_crash_internal_step", "1");
425     Cmd.addFlag("exact_artifact_path", ArtifactPath);
426     CommandLine = Cmd.toString();
427     Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
428     ExitCode = ExecuteCommand(Cmd);
429     CopyFileToErr(LogFilePath);
430     if (ExitCode == 0) {
431       if (Flags.exact_artifact_path) {
432         CurrentFilePath = Flags.exact_artifact_path;
433         WriteToFile(U, CurrentFilePath);
434       }
435       Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
436              CurrentFilePath.c_str(), U.size());
437       break;
438     }
439     auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
440     if (!DedupToken2.empty())
441       Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
442 
443     if (DedupToken1 != DedupToken2) {
444       if (Flags.exact_artifact_path) {
445         CurrentFilePath = Flags.exact_artifact_path;
446         WriteToFile(U, CurrentFilePath);
447       }
448       Printf("CRASH_MIN: mismatch in dedup tokens"
449              " (looks like a different bug). Won't minimize further\n");
450       break;
451     }
452 
453     CurrentFilePath = ArtifactPath;
454     Printf("*********************************\n");
455   }
456   RemoveFile(LogFilePath);
457   return 0;
458 }
459 
460 int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
461   assert(Inputs->size() == 1);
462   std::string InputFilePath = Inputs->at(0);
463   Unit U = FileToVector(InputFilePath);
464   Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
465   if (U.size() < 2) {
466     Printf("INFO: The input is small enough, exiting\n");
467     exit(0);
468   }
469   F->SetMaxInputLen(U.size());
470   F->SetMaxMutationLen(U.size() - 1);
471   F->MinimizeCrashLoop(U);
472   Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
473   exit(0);
474   return 0;
475 }
476 
477 void Merge(Fuzzer *F, FuzzingOptions &Options, const Vector<std::string> &Args,
478            const Vector<std::string> &Corpora, const char *CFPathOrNull) {
479   if (Corpora.size() < 2) {
480     Printf("INFO: Merge requires two or more corpus dirs\n");
481     exit(0);
482   }
483 
484   Vector<SizedFile> OldCorpus, NewCorpus;
485   GetSizedFilesFromDir(Corpora[0], &OldCorpus);
486   for (size_t i = 1; i < Corpora.size(); i++)
487     GetSizedFilesFromDir(Corpora[i], &NewCorpus);
488   std::sort(OldCorpus.begin(), OldCorpus.end());
489   std::sort(NewCorpus.begin(), NewCorpus.end());
490 
491   std::string CFPath = CFPathOrNull ? CFPathOrNull : TempPath(".txt");
492   Vector<std::string> NewFiles;
493   Set<uint32_t> NewFeatures, NewCov;
494   CrashResistantMerge(Args, OldCorpus, NewCorpus, &NewFiles, {}, &NewFeatures,
495                       {}, &NewCov, CFPath, true);
496   for (auto &Path : NewFiles)
497     F->WriteToOutputCorpus(FileToVector(Path, Options.MaxLen));
498   // We are done, delete the control file if it was a temporary one.
499   if (!Flags.merge_control_file)
500     RemoveFile(CFPath);
501 
502   exit(0);
503 }
504 
505 int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict,
506                       UnitVector& Corpus) {
507   Printf("Started dictionary minimization (up to %d tests)\n",
508          Dict.size() * Corpus.size() * 2);
509 
510   // Scores and usage count for each dictionary unit.
511   Vector<int> Scores(Dict.size());
512   Vector<int> Usages(Dict.size());
513 
514   Vector<size_t> InitialFeatures;
515   Vector<size_t> ModifiedFeatures;
516   for (auto &C : Corpus) {
517     // Get coverage for the testcase without modifications.
518     F->ExecuteCallback(C.data(), C.size());
519     InitialFeatures.clear();
520     TPC.CollectFeatures([&](size_t Feature) {
521       InitialFeatures.push_back(Feature);
522     });
523 
524     for (size_t i = 0; i < Dict.size(); ++i) {
525       Vector<uint8_t> Data = C;
526       auto StartPos = std::search(Data.begin(), Data.end(),
527                                   Dict[i].begin(), Dict[i].end());
528       // Skip dictionary unit, if the testcase does not contain it.
529       if (StartPos == Data.end())
530         continue;
531 
532       ++Usages[i];
533       while (StartPos != Data.end()) {
534         // Replace all occurrences of dictionary unit in the testcase.
535         auto EndPos = StartPos + Dict[i].size();
536         for (auto It = StartPos; It != EndPos; ++It)
537           *It ^= 0xFF;
538 
539         StartPos = std::search(EndPos, Data.end(),
540                                Dict[i].begin(), Dict[i].end());
541       }
542 
543       // Get coverage for testcase with masked occurrences of dictionary unit.
544       F->ExecuteCallback(Data.data(), Data.size());
545       ModifiedFeatures.clear();
546       TPC.CollectFeatures([&](size_t Feature) {
547         ModifiedFeatures.push_back(Feature);
548       });
549 
550       if (InitialFeatures == ModifiedFeatures)
551         --Scores[i];
552       else
553         Scores[i] += 2;
554     }
555   }
556 
557   Printf("###### Useless dictionary elements. ######\n");
558   for (size_t i = 0; i < Dict.size(); ++i) {
559     // Dictionary units with positive score are treated as useful ones.
560     if (Scores[i] > 0)
561        continue;
562 
563     Printf("\"");
564     PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
565     Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
566   }
567   Printf("###### End of useless dictionary elements. ######\n");
568   return 0;
569 }
570 
571 Vector<std::string> ParseSeedInuts(const char *seed_inputs) {
572   // Parse -seed_inputs=file1,file2,... or -seed_inputs=@seed_inputs_file
573   Vector<std::string> Files;
574   if (!seed_inputs) return Files;
575   std::string SeedInputs;
576   if (Flags.seed_inputs[0] == '@')
577     SeedInputs = FileToString(Flags.seed_inputs + 1); // File contains list.
578   else
579     SeedInputs = Flags.seed_inputs; // seed_inputs contains the list.
580   if (SeedInputs.empty()) {
581     Printf("seed_inputs is empty or @file does not exist.\n");
582     exit(1);
583   }
584   // Parse SeedInputs.
585   size_t comma_pos = 0;
586   while ((comma_pos = SeedInputs.find_last_of(',')) != std::string::npos) {
587     Files.push_back(SeedInputs.substr(comma_pos + 1));
588     SeedInputs = SeedInputs.substr(0, comma_pos);
589   }
590   Files.push_back(SeedInputs);
591   return Files;
592 }
593 
594 static Vector<SizedFile> ReadCorpora(const Vector<std::string> &CorpusDirs,
595     const Vector<std::string> &ExtraSeedFiles) {
596   Vector<SizedFile> SizedFiles;
597   size_t LastNumFiles = 0;
598   for (auto &Dir : CorpusDirs) {
599     GetSizedFilesFromDir(Dir, &SizedFiles);
600     Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
601            Dir.c_str());
602     LastNumFiles = SizedFiles.size();
603   }
604   for (auto &File : ExtraSeedFiles)
605     if (auto Size = FileSize(File))
606       SizedFiles.push_back({File, Size});
607   return SizedFiles;
608 }
609 
610 int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
611   using namespace fuzzer;
612   assert(argc && argv && "Argument pointers cannot be nullptr");
613   std::string Argv0((*argv)[0]);
614   EF = new ExternalFunctions();
615   if (EF->LLVMFuzzerInitialize)
616     EF->LLVMFuzzerInitialize(argc, argv);
617   if (EF->__msan_scoped_disable_interceptor_checks)
618     EF->__msan_scoped_disable_interceptor_checks();
619   const Vector<std::string> Args(*argv, *argv + *argc);
620   assert(!Args.empty());
621   ProgName = new std::string(Args[0]);
622   if (Argv0 != *ProgName) {
623     Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
624     exit(1);
625   }
626   ParseFlags(Args, EF);
627   if (Flags.help) {
628     PrintHelp();
629     return 0;
630   }
631 
632   if (Flags.close_fd_mask & 2)
633     DupAndCloseStderr();
634   if (Flags.close_fd_mask & 1)
635     CloseStdout();
636 
637   if (Flags.jobs > 0 && Flags.workers == 0) {
638     Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
639     if (Flags.workers > 1)
640       Printf("Running %u workers\n", Flags.workers);
641   }
642 
643   if (Flags.workers > 0 && Flags.jobs > 0)
644     return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
645 
646   FuzzingOptions Options;
647   Options.Verbosity = Flags.verbosity;
648   Options.MaxLen = Flags.max_len;
649   Options.LenControl = Flags.len_control;
650   Options.UnitTimeoutSec = Flags.timeout;
651   Options.ErrorExitCode = Flags.error_exitcode;
652   Options.TimeoutExitCode = Flags.timeout_exitcode;
653   Options.IgnoreTimeouts = Flags.ignore_timeouts;
654   Options.IgnoreOOMs = Flags.ignore_ooms;
655   Options.IgnoreCrashes = Flags.ignore_crashes;
656   Options.MaxTotalTimeSec = Flags.max_total_time;
657   Options.DoCrossOver = Flags.cross_over;
658   Options.MutateDepth = Flags.mutate_depth;
659   Options.ReduceDepth = Flags.reduce_depth;
660   Options.UseCounters = Flags.use_counters;
661   Options.UseMemmem = Flags.use_memmem;
662   Options.UseCmp = Flags.use_cmp;
663   Options.UseValueProfile = Flags.use_value_profile;
664   Options.Shrink = Flags.shrink;
665   Options.ReduceInputs = Flags.reduce_inputs;
666   Options.ShuffleAtStartUp = Flags.shuffle;
667   Options.PreferSmall = Flags.prefer_small;
668   Options.ReloadIntervalSec = Flags.reload;
669   Options.OnlyASCII = Flags.only_ascii;
670   Options.DetectLeaks = Flags.detect_leaks;
671   Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval;
672   Options.TraceMalloc = Flags.trace_malloc;
673   Options.RssLimitMb = Flags.rss_limit_mb;
674   Options.MallocLimitMb = Flags.malloc_limit_mb;
675   if (!Options.MallocLimitMb)
676     Options.MallocLimitMb = Options.RssLimitMb;
677   if (Flags.runs >= 0)
678     Options.MaxNumberOfRuns = Flags.runs;
679   if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
680     Options.OutputCorpus = (*Inputs)[0];
681   Options.ReportSlowUnits = Flags.report_slow_units;
682   if (Flags.artifact_prefix)
683     Options.ArtifactPrefix = Flags.artifact_prefix;
684   if (Flags.exact_artifact_path)
685     Options.ExactArtifactPath = Flags.exact_artifact_path;
686   Vector<Unit> Dictionary;
687   if (Flags.dict)
688     if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
689       return 1;
690   if (Flags.verbosity > 0 && !Dictionary.empty())
691     Printf("Dictionary: %zd entries\n", Dictionary.size());
692   bool RunIndividualFiles = AllInputsAreFiles();
693   Options.SaveArtifacts =
694       !RunIndividualFiles || Flags.minimize_crash_internal_step;
695   Options.PrintNewCovPcs = Flags.print_pcs;
696   Options.PrintNewCovFuncs = Flags.print_funcs;
697   Options.PrintFinalStats = Flags.print_final_stats;
698   Options.PrintCorpusStats = Flags.print_corpus_stats;
699   Options.PrintCoverage = Flags.print_coverage;
700   if (Flags.exit_on_src_pos)
701     Options.ExitOnSrcPos = Flags.exit_on_src_pos;
702   if (Flags.exit_on_item)
703     Options.ExitOnItem = Flags.exit_on_item;
704   if (Flags.focus_function)
705     Options.FocusFunction = Flags.focus_function;
706   if (Flags.data_flow_trace)
707     Options.DataFlowTrace = Flags.data_flow_trace;
708   if (Flags.features_dir)
709     Options.FeaturesDir = Flags.features_dir;
710   if (Flags.collect_data_flow)
711     Options.CollectDataFlow = Flags.collect_data_flow;
712   if (Flags.stop_file)
713     Options.StopFile = Flags.stop_file;
714 
715   unsigned Seed = Flags.seed;
716   // Initialize Seed.
717   if (Seed == 0)
718     Seed =
719         std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
720   if (Flags.verbosity)
721     Printf("INFO: Seed: %u\n", Seed);
722 
723   if (Flags.collect_data_flow && !Flags.fork && !Flags.merge) {
724     if (RunIndividualFiles)
725       return CollectDataFlow(Flags.collect_data_flow, Flags.data_flow_trace,
726                         ReadCorpora({}, *Inputs));
727     else
728       return CollectDataFlow(Flags.collect_data_flow, Flags.data_flow_trace,
729                         ReadCorpora(*Inputs, {}));
730   }
731 
732   Random Rand(Seed);
733   auto *MD = new MutationDispatcher(Rand, Options);
734   auto *Corpus = new InputCorpus(Options.OutputCorpus);
735   auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
736 
737   for (auto &U: Dictionary)
738     if (U.size() <= Word::GetMaxSize())
739       MD->AddWordToManualDictionary(Word(U.data(), U.size()));
740 
741       // Threads are only supported by Chrome. Don't use them with emscripten
742       // for now.
743 #if !LIBFUZZER_EMSCRIPTEN
744   StartRssThread(F, Flags.rss_limit_mb);
745 #endif // LIBFUZZER_EMSCRIPTEN
746 
747   Options.HandleAbrt = Flags.handle_abrt;
748   Options.HandleBus = Flags.handle_bus;
749   Options.HandleFpe = Flags.handle_fpe;
750   Options.HandleIll = Flags.handle_ill;
751   Options.HandleInt = Flags.handle_int;
752   Options.HandleSegv = Flags.handle_segv;
753   Options.HandleTerm = Flags.handle_term;
754   Options.HandleXfsz = Flags.handle_xfsz;
755   Options.HandleUsr1 = Flags.handle_usr1;
756   Options.HandleUsr2 = Flags.handle_usr2;
757   SetSignalHandler(Options);
758 
759   std::atexit(Fuzzer::StaticExitCallback);
760 
761   if (Flags.minimize_crash)
762     return MinimizeCrashInput(Args, Options);
763 
764   if (Flags.minimize_crash_internal_step)
765     return MinimizeCrashInputInternalStep(F, Corpus);
766 
767   if (Flags.cleanse_crash)
768     return CleanseCrashInput(Args, Options);
769 
770   if (RunIndividualFiles) {
771     Options.SaveArtifacts = false;
772     int Runs = std::max(1, Flags.runs);
773     Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
774            Inputs->size(), Runs);
775     for (auto &Path : *Inputs) {
776       auto StartTime = system_clock::now();
777       Printf("Running: %s\n", Path.c_str());
778       for (int Iter = 0; Iter < Runs; Iter++)
779         RunOneTest(F, Path.c_str(), Options.MaxLen);
780       auto StopTime = system_clock::now();
781       auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
782       Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
783     }
784     Printf("***\n"
785            "*** NOTE: fuzzing was not performed, you have only\n"
786            "***       executed the target code on a fixed set of inputs.\n"
787            "***\n");
788     F->PrintFinalStats();
789     exit(0);
790   }
791 
792   if (Flags.fork)
793     FuzzWithFork(F->GetMD().GetRand(), Options, Args, *Inputs, Flags.fork);
794 
795   if (Flags.merge)
796     Merge(F, Options, Args, *Inputs, Flags.merge_control_file);
797 
798   if (Flags.merge_inner) {
799     const size_t kDefaultMaxMergeLen = 1 << 20;
800     if (Options.MaxLen == 0)
801       F->SetMaxInputLen(kDefaultMaxMergeLen);
802     assert(Flags.merge_control_file);
803     F->CrashResistantMergeInternalStep(Flags.merge_control_file);
804     exit(0);
805   }
806 
807   if (Flags.analyze_dict) {
808     size_t MaxLen = INT_MAX;  // Large max length.
809     UnitVector InitialCorpus;
810     for (auto &Inp : *Inputs) {
811       Printf("Loading corpus dir: %s\n", Inp.c_str());
812       ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
813                              MaxLen, /*ExitOnError=*/false);
814     }
815 
816     if (Dictionary.empty() || Inputs->empty()) {
817       Printf("ERROR: can't analyze dict without dict and corpus provided\n");
818       return 1;
819     }
820     if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
821       Printf("Dictionary analysis failed\n");
822       exit(1);
823     }
824     Printf("Dictionary analysis succeeded\n");
825     exit(0);
826   }
827 
828   auto CorporaFiles = ReadCorpora(*Inputs, ParseSeedInuts(Flags.seed_inputs));
829   F->Loop(CorporaFiles);
830 
831   if (Flags.verbosity)
832     Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
833            F->secondsSinceProcessStartUp());
834   F->PrintFinalStats();
835 
836   exit(0);  // Don't let F destroy itself.
837 }
838 
839 // Storage for global ExternalFunctions object.
840 ExternalFunctions *EF = nullptr;
841 
842 }  // namespace fuzzer
843