Debian Codegraph @

tools/fuzzing/libfuzzer/FuzzerDriver.cpp

raw
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 "FuzzerPlatform.h"
20 #include "FuzzerRandom.h"
21 #include "FuzzerTracePC.h"
22 #include <algorithm>
23 #include <atomic>
24 #include <chrono>
25 #include <cstdlib>
26 #include <cstring>
27 #include <mutex>
28 #include <string>
29 #include <thread>
30 #include <fstream>
31
32 // This function should be present in the libFuzzer so that the client
33 // binary can test for its existence.
34 #if LIBFUZZER_MSVC
35 extern "C" void __libfuzzer_is_present() {}
36 #if defined(_M_IX86) || defined(__i386__)
37 #pragma comment(linker, "/include:___libfuzzer_is_present")
38 #else
39 #pragma comment(linker, "/include:__libfuzzer_is_present")
40 #endif
41 #else
42 extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
43 #endif // LIBFUZZER_MSVC
44
45 namespace fuzzer {
46
47 // Program arguments.
48 struct FlagDescription {
49 const char *Name;
50 const char *Description;
51 int Default;
52 int *IntFlag;
53 const char **StrFlag;
54 unsigned int *UIntFlag;
55 };
56
57 struct {
58 #define FUZZER_DEPRECATED_FLAG(Name)
59 #define FUZZER_FLAG_INT(Name, Default, Description) int Name;
60 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
61 #define FUZZER_FLAG_STRING(Name, Description) const char *Name;
62 #include "FuzzerFlags.def"
63 #undef FUZZER_DEPRECATED_FLAG
64 #undef FUZZER_FLAG_INT
65 #undef FUZZER_FLAG_UNSIGNED
66 #undef FUZZER_FLAG_STRING
67 } Flags;
68
69 static const FlagDescription FlagDescriptions [] {
70 #define FUZZER_DEPRECATED_FLAG(Name) \
71 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
72 #define FUZZER_FLAG_INT(Name, Default, Description) \
73 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
74 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
75 {#Name, Description, static_cast<int>(Default), \
76 nullptr, nullptr, &Flags.Name},
77 #define FUZZER_FLAG_STRING(Name, Description) \
78 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
79 #include "FuzzerFlags.def"
80 #undef FUZZER_DEPRECATED_FLAG
81 #undef FUZZER_FLAG_INT
82 #undef FUZZER_FLAG_UNSIGNED
83 #undef FUZZER_FLAG_STRING
84 };
85
86 static const size_t kNumFlags =
87 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
88
89 static Vector<std::string> *Inputs;
90 static std::string *ProgName;
91
92 static void PrintHelp() {
93 Printf("Usage:\n");
94 auto Prog = ProgName->c_str();
95 Printf("\nTo run fuzzing pass 0 or more directories.\n");
96 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
97
98 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
99 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
100
101 Printf("\nFlags: (strictly in form -flag=value)\n");
102 size_t MaxFlagLen = 0;
103 for (size_t F = 0; F < kNumFlags; F++)
104 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
105
106 for (size_t F = 0; F < kNumFlags; F++) {
107 const auto &D = FlagDescriptions[F];
108 if (strstr(D.Description, "internal flag") == D.Description) continue;
109 Printf(" %s", D.Name);
110 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
111 Printf(" ");
112 Printf("\t");
113 Printf("%d\t%s\n", D.Default, D.Description);
114 }
115 Printf("\nFlags starting with '--' will be ignored and "
116 "will be passed verbatim to subprocesses.\n");
117 }
118
119 static const char *FlagValue(const char *Param, const char *Name) {
120 size_t Len = strlen(Name);
121 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
122 Param[Len + 1] == '=')
123 return &Param[Len + 2];
124 return nullptr;
125 }
126
127 // Avoid calling stol as it triggers a bug in clang/glibc build.
128 static long MyStol(const char *Str) {
129 long Res = 0;
130 long Sign = 1;
131 if (*Str == '-') {
132 Str++;
133 Sign = -1;
134 }
135 for (size_t i = 0; Str[i]; i++) {
136 char Ch = Str[i];
137 if (Ch < '0' || Ch > '9')
138 return Res;
139 Res = Res * 10 + (Ch - '0');
140 }
141 return Res * Sign;
142 }
143
144 static bool ParseOneFlag(const char *Param) {
145 if (Param[0] != '-') return false;
146 if (Param[1] == '-') {
147 static bool PrintedWarning = false;
148 if (!PrintedWarning) {
149 PrintedWarning = true;
150 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
151 }
152 for (size_t F = 0; F < kNumFlags; F++)
153 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
154 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
155 return true;
156 }
157 for (size_t F = 0; F < kNumFlags; F++) {
158 const char *Name = FlagDescriptions[F].Name;
159 const char *Str = FlagValue(Param, Name);
160 if (Str) {
161 if (FlagDescriptions[F].IntFlag) {
162 int Val = MyStol(Str);
163 *FlagDescriptions[F].IntFlag = Val;
164 if (Flags.verbosity >= 2)
165 Printf("Flag: %s %d\n", Name, Val);
166 return true;
167 } else if (FlagDescriptions[F].UIntFlag) {
168 unsigned int Val = std::stoul(Str);
169 *FlagDescriptions[F].UIntFlag = Val;
170 if (Flags.verbosity >= 2)
171 Printf("Flag: %s %u\n", Name, Val);
172 return true;
173 } else if (FlagDescriptions[F].StrFlag) {
174 *FlagDescriptions[F].StrFlag = Str;
175 if (Flags.verbosity >= 2)
176 Printf("Flag: %s %s\n", Name, Str);
177 return true;
178 } else { // Deprecated flag.
179 Printf("Flag: %s: deprecated, don't use\n", Name);
180 return true;
181 }
182 }
183 }
184 Printf("\n\nWARNING: unrecognized flag '%s'; "
185 "use -help=1 to list all flags\n\n", Param);
186 return true;
187 }
188
189 // We don't use any library to minimize dependencies.
190 static void ParseFlags(const Vector<std::string> &Args,
191 const ExternalFunctions *EF) {
192 for (size_t F = 0; F < kNumFlags; F++) {
193 if (FlagDescriptions[F].IntFlag)
194 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
195 if (FlagDescriptions[F].UIntFlag)
196 *FlagDescriptions[F].UIntFlag =
197 static_cast<unsigned int>(FlagDescriptions[F].Default);
198 if (FlagDescriptions[F].StrFlag)
199 *FlagDescriptions[F].StrFlag = nullptr;
200 }
201
202 // Disable len_control by default, if LLVMFuzzerCustomMutator is used.
203 if (EF->LLVMFuzzerCustomMutator) {
204 Flags.len_control = 0;
205 Printf("INFO: found LLVMFuzzerCustomMutator (%p). "
206 "Disabling -len_control by default.\n", EF->LLVMFuzzerCustomMutator);
207 }
208
209 Inputs = new Vector<std::string>;
210 for (size_t A = 1; A < Args.size(); A++) {
211 if (ParseOneFlag(Args[A].c_str())) {
212 if (Flags.ignore_remaining_args)
213 break;
214 continue;
215 }
216 Inputs->push_back(Args[A]);
217 }
218 }
219
220 static std::mutex Mu;
221
222 static void PulseThread() {
223 while (true) {
224 SleepSeconds(600);
225 std::lock_guard<std::mutex> Lock(Mu);
226 Printf("pulse...\n");
227 }
228 }
229
230 static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter,
231 unsigned NumJobs, std::atomic<bool> *HasErrors) {
232 while (true) {
233 unsigned C = (*Counter)++;
234 if (C >= NumJobs) break;
235 std::string Log = "fuzz-" + std::to_string(C) + ".log";
236 Command Cmd(BaseCmd);
237 Cmd.setOutputFile(Log);
238 Cmd.combineOutAndErr();
239 if (Flags.verbosity) {
240 std::string CommandLine = Cmd.toString();
241 Printf("%s\n", CommandLine.c_str());
242 }
243 int ExitCode = ExecuteCommand(Cmd);
244 if (ExitCode != 0)
245 *HasErrors = true;
246 std::lock_guard<std::mutex> Lock(Mu);
247 Printf("================== Job %u exited with exit code %d ============\n",
248 C, ExitCode);
249 fuzzer::CopyFileToErr(Log);
250 }
251 }
252
253 std::string CloneArgsWithoutX(const Vector<std::string> &Args,
254 const char *X1, const char *X2) {
255 std::string Cmd;
256 for (auto &S : Args) {
257 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
258 continue;
259 Cmd += S + " ";
260 }
261 return Cmd;
262 }
263
264 static int RunInMultipleProcesses(const Vector<std::string> &Args,
265 unsigned NumWorkers, unsigned NumJobs) {
266 std::atomic<unsigned> Counter(0);
267 std::atomic<bool> HasErrors(false);
268 Command Cmd(Args);
269 Cmd.removeFlag("jobs");
270 Cmd.removeFlag("workers");
271 Vector<std::thread> V;
272 std::thread Pulse(PulseThread);
273 Pulse.detach();
274 for (unsigned i = 0; i < NumWorkers; i++)
275 V.push_back(std::thread(WorkerThread, std::ref(Cmd), &Counter, NumJobs, &HasErrors));
276 for (auto &T : V)
277 T.join();
278 return HasErrors ? 1 : 0;
279 }
280
281 static void RssThread(Fuzzer *F, size_t RssLimitMb) {
282 while (true) {
283 SleepSeconds(1);
284 size_t Peak = GetPeakRSSMb();
285 if (Peak > RssLimitMb)
286 F->RssLimitCallback();
287 }
288 }
289
290 static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
291 if (!RssLimitMb)
292 return;
293 std::thread T(RssThread, F, RssLimitMb);
294 T.detach();
295 }
296
297 int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
298 Unit U = FileToVector(InputFilePath);
299 if (MaxLen && MaxLen < U.size())
300 U.resize(MaxLen);
301 F->ExecuteCallback(U.data(), U.size());
302 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
303 return 0;
304 }
305
306 static bool AllInputsAreFiles() {
307 if (Inputs->empty()) return false;
308 for (auto &Path : *Inputs)
309 if (!IsFile(Path))
310 return false;
311 return true;
312 }
313
314 static std::string GetDedupTokenFromCmdOutput(const std::string &S) {
315 auto Beg = S.find("DEDUP_TOKEN:");
316 if (Beg == std::string::npos)
317 return "";
318 auto End = S.find('\n', Beg);
319 if (End == std::string::npos)
320 return "";
321 return S.substr(Beg, End - Beg);
322 }
323
324 int CleanseCrashInput(const Vector<std::string> &Args,
325 const FuzzingOptions &Options) {
326 if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
327 Printf("ERROR: -cleanse_crash should be given one input file and"
328 " -exact_artifact_path\n");
329 return 1;
330 }
331 std::string InputFilePath = Inputs->at(0);
332 std::string OutputFilePath = Flags.exact_artifact_path;
333 Command Cmd(Args);
334 Cmd.removeFlag("cleanse_crash");
335
336 assert(Cmd.hasArgument(InputFilePath));
337 Cmd.removeArgument(InputFilePath);
338
339 auto TmpFilePath = TempPath("CleanseCrashInput", ".repro");
340 Cmd.addArgument(TmpFilePath);
341 Cmd.setOutputFile(getDevNull());
342 Cmd.combineOutAndErr();
343
344 std::string CurrentFilePath = InputFilePath;
345 auto U = FileToVector(CurrentFilePath);
346 size_t Size = U.size();
347
348 const Vector<uint8_t> ReplacementBytes = {' ', 0xff};
349 for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
350 bool Changed = false;
351 for (size_t Idx = 0; Idx < Size; Idx++) {
352 Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
353 Idx, Size);
354 uint8_t OriginalByte = U[Idx];
355 if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
356 ReplacementBytes.end(),
357 OriginalByte))
358 continue;
359 for (auto NewByte : ReplacementBytes) {
360 U[Idx] = NewByte;
361 WriteToFile(U, TmpFilePath);
362 auto ExitCode = ExecuteCommand(Cmd);
363 RemoveFile(TmpFilePath);
364 if (!ExitCode) {
365 U[Idx] = OriginalByte;
366 } else {
367 Changed = true;
368 Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
369 WriteToFile(U, OutputFilePath);
370 break;
371 }
372 }
373 }
374 if (!Changed) break;
375 }
376 return 0;
377 }
378
379 int MinimizeCrashInput(const Vector<std::string> &Args,
380 const FuzzingOptions &Options) {
381 if (Inputs->size() != 1) {
382 Printf("ERROR: -minimize_crash should be given one input file\n");
383 return 1;
384 }
385 std::string InputFilePath = Inputs->at(0);
386 Command BaseCmd(Args);
387 BaseCmd.removeFlag("minimize_crash");
388 BaseCmd.removeFlag("exact_artifact_path");
389 assert(BaseCmd.hasArgument(InputFilePath));
390 BaseCmd.removeArgument(InputFilePath);
391 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
392 Printf("INFO: you need to specify -runs=N or "
393 "-max_total_time=N with -minimize_crash=1\n"
394 "INFO: defaulting to -max_total_time=600\n");
395 BaseCmd.addFlag("max_total_time", "600");
396 }
397
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 Printf("CRASH_MIN: executing: %s\n", Cmd.toString().c_str());
410 std::string CmdOutput;
411 bool Success = ExecuteCommand(Cmd, &CmdOutput);
412 if (Success) {
413 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
414 return 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 = GetDedupTokenFromCmdOutput(CmdOutput);
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 Printf("CRASH_MIN: executing: %s\n", Cmd.toString().c_str());
430 CmdOutput.clear();
431 Success = ExecuteCommand(Cmd, &CmdOutput);
432 Printf("%s", CmdOutput.c_str());
433 if (Success) {
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 = GetDedupTokenFromCmdOutput(CmdOutput);
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 return 0;
460 }
461
462 int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
463 assert(Inputs->size() == 1);
464 std::string InputFilePath = Inputs->at(0);
465 Unit U = FileToVector(InputFilePath);
466 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
467 if (U.size() < 2) {
468 Printf("INFO: The input is small enough, exiting\n");
469 return 0;
470 }
471 F->SetMaxInputLen(U.size());
472 F->SetMaxMutationLen(U.size() - 1);
473 F->MinimizeCrashLoop(U);
474 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
475 return 0;
476 }
477
478 int Merge(Fuzzer *F, FuzzingOptions &Options, const Vector<std::string> &Args,
479 const Vector<std::string> &Corpora, const char *CFPathOrNull) {
480 if (Corpora.size() < 2) {
481 Printf("INFO: Merge requires two or more corpus dirs\n");
482 return 0;
483 }
484
485 Vector<SizedFile> OldCorpus, NewCorpus;
486 int Res = GetSizedFilesFromDir(Corpora[0], &OldCorpus);
487 if (Res != 0)
488 return Res;
489 for (size_t i = 1; i < Corpora.size(); i++) {
490 Res = GetSizedFilesFromDir(Corpora[i], &NewCorpus);
491 if (Res != 0)
492 return Res;
493 }
494 std::sort(OldCorpus.begin(), OldCorpus.end());
495 std::sort(NewCorpus.begin(), NewCorpus.end());
496
497 std::string CFPath = CFPathOrNull ? CFPathOrNull : TempPath("Merge", ".txt");
498 Vector<std::string> NewFiles;
499 Set<uint32_t> NewFeatures, NewCov;
500 Res = CrashResistantMerge(Args, OldCorpus, NewCorpus, &NewFiles, {}, &NewFeatures,
501 {}, &NewCov, CFPath, true);
502 if (Res != 0)
503 return Res;
504
505 if (F->isGracefulExitRequested())
506 return 0;
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 return 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 int ParseSeedInuts(const char *seed_inputs, Vector<std::string> &Files) {
583 // Parse -seed_inputs=file1,file2,... or -seed_inputs=@seed_inputs_file
584 if (!seed_inputs) return 0;
585 std::string SeedInputs;
586 if (Flags.seed_inputs[0] == '@')
587 SeedInputs = FileToString(Flags.seed_inputs + 1); // File contains list.
588 else
589 SeedInputs = Flags.seed_inputs; // seed_inputs contains the list.
590 if (SeedInputs.empty()) {
591 Printf("seed_inputs is empty or @file does not exist.\n");
592 return 1;
593 }
594 // Parse SeedInputs.
595 size_t comma_pos = 0;
596 while ((comma_pos = SeedInputs.find_last_of(',')) != std::string::npos) {
597 Files.push_back(SeedInputs.substr(comma_pos + 1));
598 SeedInputs = SeedInputs.substr(0, comma_pos);
599 }
600 Files.push_back(SeedInputs);
601 return 0;
602 }
603
604 static Vector<SizedFile> ReadCorpora(const Vector<std::string> &CorpusDirs,
605 const Vector<std::string> &ExtraSeedFiles) {
606 Vector<SizedFile> SizedFiles;
607 size_t LastNumFiles = 0;
608 for (auto &Dir : CorpusDirs) {
609 GetSizedFilesFromDir(Dir, &SizedFiles);
610 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
611 Dir.c_str());
612 LastNumFiles = SizedFiles.size();
613 }
614 for (auto &File : ExtraSeedFiles)
615 if (auto Size = FileSize(File))
616 SizedFiles.push_back({File, Size});
617 return SizedFiles;
618 }
619
620 int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
621 using namespace fuzzer;
622 assert(argc && argv && "Argument pointers cannot be nullptr");
623 std::string Argv0((*argv)[0]);
624 if (!EF)
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 return 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 Options.Entropic = Flags.entropic;
726 Options.EntropicFeatureFrequencyThreshold =
727 (size_t)Flags.entropic_feature_frequency_threshold;
728 Options.EntropicNumberOfRarestFeatures =
729 (size_t)Flags.entropic_number_of_rarest_features;
730 if (Options.Entropic) {
731 if (!Options.FocusFunction.empty()) {
732 Printf("ERROR: The parameters `--entropic` and `--focus_function` cannot "
733 "be used together.\n");
734 return 1;
735 }
736 Printf("INFO: Running with entropic power schedule (0x%X, %d).\n",
737 Options.EntropicFeatureFrequencyThreshold,
738 Options.EntropicNumberOfRarestFeatures);
739 }
740 struct EntropicOptions Entropic;
741 Entropic.Enabled = Options.Entropic;
742 Entropic.FeatureFrequencyThreshold =
743 Options.EntropicFeatureFrequencyThreshold;
744 Entropic.NumberOfRarestFeatures = Options.EntropicNumberOfRarestFeatures;
745
746 unsigned Seed = Flags.seed;
747 // Initialize Seed.
748 if (Seed == 0)
749 Seed =
750 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
751 if (Flags.verbosity)
752 Printf("INFO: Seed: %u\n", Seed);
753
754 if (Flags.collect_data_flow && !Flags.fork && !Flags.merge) {
755 if (RunIndividualFiles)
756 return CollectDataFlow(Flags.collect_data_flow, Flags.data_flow_trace,
757 ReadCorpora({}, *Inputs));
758 else
759 return CollectDataFlow(Flags.collect_data_flow, Flags.data_flow_trace,
760 ReadCorpora(*Inputs, {}));
761 }
762
763 Random Rand(Seed);
764 auto *MD = new MutationDispatcher(Rand, Options);
765 auto *Corpus = new InputCorpus(Options.OutputCorpus, Entropic);
766 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
767
768 for (auto &U: Dictionary)
769 if (U.size() <= Word::GetMaxSize())
770 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
771
772 // Threads are only supported by Chrome. Don't use them with emscripten
773 // for now.
774 #if !LIBFUZZER_EMSCRIPTEN
775 StartRssThread(F, Flags.rss_limit_mb);
776 #endif // LIBFUZZER_EMSCRIPTEN
777
778 Options.HandleAbrt = Flags.handle_abrt;
779 Options.HandleBus = Flags.handle_bus;
780 Options.HandleFpe = Flags.handle_fpe;
781 Options.HandleIll = Flags.handle_ill;
782 Options.HandleInt = Flags.handle_int;
783 Options.HandleSegv = Flags.handle_segv;
784 Options.HandleTerm = Flags.handle_term;
785 Options.HandleXfsz = Flags.handle_xfsz;
786 Options.HandleUsr1 = Flags.handle_usr1;
787 Options.HandleUsr2 = Flags.handle_usr2;
788 SetSignalHandler(Options);
789
790 std::atexit(Fuzzer::StaticExitCallback);
791
792 if (Flags.minimize_crash)
793 return MinimizeCrashInput(Args, Options);
794
795 if (Flags.minimize_crash_internal_step)
796 return MinimizeCrashInputInternalStep(F, Corpus);
797
798 if (Flags.cleanse_crash)
799 return CleanseCrashInput(Args, Options);
800
801 if (RunIndividualFiles) {
802 Options.SaveArtifacts = false;
803 int Runs = std::max(1, Flags.runs);
804 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
805 Inputs->size(), Runs);
806 for (auto &Path : *Inputs) {
807 auto StartTime = system_clock::now();
808 Printf("Running: %s\n", Path.c_str());
809 for (int Iter = 0; Iter < Runs; Iter++)
810 RunOneTest(F, Path.c_str(), Options.MaxLen);
811 auto StopTime = system_clock::now();
812 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
813 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
814 }
815 Printf("***\n"
816 "*** NOTE: fuzzing was not performed, you have only\n"
817 "*** executed the target code on a fixed set of inputs.\n"
818 "***\n");
819 F->PrintFinalStats();
820 return 0;
821 }
822
823 if (Flags.fork)
824 return FuzzWithFork(F->GetMD().GetRand(), Options, Args, *Inputs, Flags.fork);
825
826 if (Flags.merge)
827 return Merge(F, Options, Args, *Inputs, Flags.merge_control_file);
828
829 if (Flags.merge_inner) {
830 const size_t kDefaultMaxMergeLen = 1 << 20;
831 if (Options.MaxLen == 0)
832 F->SetMaxInputLen(kDefaultMaxMergeLen);
833 assert(Flags.merge_control_file);
834 return F->CrashResistantMergeInternalStep(Flags.merge_control_file);
835 }
836
837 if (Flags.analyze_dict) {
838 size_t MaxLen = INT_MAX; // Large max length.
839 UnitVector InitialCorpus;
840 for (auto &Inp : *Inputs) {
841 Printf("Loading corpus dir: %s\n", Inp.c_str());
842 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
843 MaxLen, /*ExitOnError=*/false);
844 }
845
846 if (Dictionary.empty() || Inputs->empty()) {
847 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
848 return 1;
849 }
850 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
851 Printf("Dictionary analysis failed\n");
852 return 1;
853 }
854 Printf("Dictionary analysis succeeded\n");
855 return 0;
856 }
857
858 {
859 Vector<std::string> Files;
860 int Res = ParseSeedInuts(Flags.seed_inputs, Files);
861 if (Res != 0)
862 return Res;
863 auto CorporaFiles = ReadCorpora(*Inputs, Files);
864 Res = F->Loop(CorporaFiles);
865 if (Res != 0)
866 return Res;
867 if (F->isGracefulExitRequested())
868 return 0;
869 }
870
871 if (Flags.verbosity)
872 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
873 F->secondsSinceProcessStartUp());
874 F->PrintFinalStats();
875
876 return 0; // Don't let F destroy itself.
877 }
878
879 extern "C" ATTRIBUTE_INTERFACE int
880 LLVMFuzzerRunDriver(int *argc, char ***argv,
881 int (*UserCb)(const uint8_t *Data, size_t Size)) {
882 return FuzzerDriver(argc, argv, UserCb);
883 }
884
885 // Storage for global ExternalFunctions object.
886 ExternalFunctions *EF = nullptr;
887
888 } // namespace fuzzer