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