1 //===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // FuzzerDriver and flag parsing.
10 //===----------------------------------------------------------------------===//
12 #include "FuzzerCommand.h"
13 #include "FuzzerCorpus.h"
15 #include "FuzzerInterface.h"
16 #include "FuzzerInternal.h"
17 #include "FuzzerMutate.h"
18 #include "FuzzerRandom.h"
19 #include "FuzzerShmem.h"
20 #include "FuzzerTracePC.h"
30 // This function should be present in the libFuzzer so that the client
31 // binary can test for its existence.
32 extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
37 struct FlagDescription {
39 const char *Description;
43 unsigned int *UIntFlag;
47 #define FUZZER_DEPRECATED_FLAG(Name)
48 #define FUZZER_FLAG_INT(Name, Default, Description) int Name;
49 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
50 #define FUZZER_FLAG_STRING(Name, Description) const char *Name;
51 #include "FuzzerFlags.def"
52 #undef FUZZER_DEPRECATED_FLAG
53 #undef FUZZER_FLAG_INT
54 #undef FUZZER_FLAG_UNSIGNED
55 #undef FUZZER_FLAG_STRING
58 static const FlagDescription FlagDescriptions [] {
59 #define FUZZER_DEPRECATED_FLAG(Name) \
60 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
61 #define FUZZER_FLAG_INT(Name, Default, Description) \
62 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
63 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
64 {#Name, Description, static_cast<int>(Default), \
65 nullptr, nullptr, &Flags.Name},
66 #define FUZZER_FLAG_STRING(Name, Description) \
67 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
68 #include "FuzzerFlags.def"
69 #undef FUZZER_DEPRECATED_FLAG
70 #undef FUZZER_FLAG_INT
71 #undef FUZZER_FLAG_UNSIGNED
72 #undef FUZZER_FLAG_STRING
75 static const size_t kNumFlags =
76 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
78 static Vector<std::string> *Inputs;
79 static std::string *ProgName;
81 static void PrintHelp() {
83 auto Prog = ProgName->c_str();
84 Printf("\nTo run fuzzing pass 0 or more directories.\n");
85 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
87 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
88 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
90 Printf("\nFlags: (strictly in form -flag=value)\n");
91 size_t MaxFlagLen = 0;
92 for (size_t F = 0; F < kNumFlags; F++)
93 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
95 for (size_t F = 0; F < kNumFlags; F++) {
96 const auto &D = FlagDescriptions[F];
97 if (strstr(D.Description, "internal flag") == D.Description) continue;
98 Printf(" %s", D.Name);
99 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
102 Printf("%d\t%s\n", D.Default, D.Description);
104 Printf("\nFlags starting with '--' will be ignored and "
105 "will be passed verbatim to subprocesses.\n");
108 static const char *FlagValue(const char *Param, const char *Name) {
109 size_t Len = strlen(Name);
110 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
111 Param[Len + 1] == '=')
112 return &Param[Len + 2];
116 // Avoid calling stol as it triggers a bug in clang/glibc build.
117 static long MyStol(const char *Str) {
124 for (size_t i = 0; Str[i]; i++) {
126 if (Ch < '0' || Ch > '9')
128 Res = Res * 10 + (Ch - '0');
133 static bool ParseOneFlag(const char *Param) {
134 if (Param[0] != '-') return false;
135 if (Param[1] == '-') {
136 static bool PrintedWarning = false;
137 if (!PrintedWarning) {
138 PrintedWarning = true;
139 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
141 for (size_t F = 0; F < kNumFlags; F++)
142 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
143 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
146 for (size_t F = 0; F < kNumFlags; F++) {
147 const char *Name = FlagDescriptions[F].Name;
148 const char *Str = FlagValue(Param, Name);
150 if (FlagDescriptions[F].IntFlag) {
151 int Val = MyStol(Str);
152 *FlagDescriptions[F].IntFlag = Val;
153 if (Flags.verbosity >= 2)
154 Printf("Flag: %s %d\n", Name, Val);
156 } else if (FlagDescriptions[F].UIntFlag) {
157 unsigned int Val = std::stoul(Str);
158 *FlagDescriptions[F].UIntFlag = Val;
159 if (Flags.verbosity >= 2)
160 Printf("Flag: %s %u\n", Name, Val);
162 } else if (FlagDescriptions[F].StrFlag) {
163 *FlagDescriptions[F].StrFlag = Str;
164 if (Flags.verbosity >= 2)
165 Printf("Flag: %s %s\n", Name, Str);
167 } else { // Deprecated flag.
168 Printf("Flag: %s: deprecated, don't use\n", Name);
173 Printf("\n\nWARNING: unrecognized flag '%s'; "
174 "use -help=1 to list all flags\n\n", Param);
178 // We don't use any library to minimize dependencies.
179 static void ParseFlags(const Vector<std::string> &Args) {
180 for (size_t F = 0; F < kNumFlags; F++) {
181 if (FlagDescriptions[F].IntFlag)
182 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
183 if (FlagDescriptions[F].UIntFlag)
184 *FlagDescriptions[F].UIntFlag =
185 static_cast<unsigned int>(FlagDescriptions[F].Default);
186 if (FlagDescriptions[F].StrFlag)
187 *FlagDescriptions[F].StrFlag = nullptr;
189 Inputs = new Vector<std::string>;
190 for (size_t A = 1; A < Args.size(); A++) {
191 if (ParseOneFlag(Args[A].c_str())) {
192 if (Flags.ignore_remaining_args)
196 Inputs->push_back(Args[A]);
200 static std::mutex Mu;
202 static void PulseThread() {
205 std::lock_guard<std::mutex> Lock(Mu);
206 Printf("pulse...\n");
210 static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter,
211 unsigned NumJobs, std::atomic<bool> *HasErrors) {
213 unsigned C = (*Counter)++;
214 if (C >= NumJobs) break;
215 std::string Log = "fuzz-" + std::to_string(C) + ".log";
216 Command Cmd(BaseCmd);
217 Cmd.setOutputFile(Log);
218 Cmd.combineOutAndErr();
219 if (Flags.verbosity) {
220 std::string CommandLine = Cmd.toString();
221 Printf("%s\n", CommandLine.c_str());
223 int ExitCode = ExecuteCommand(Cmd);
226 std::lock_guard<std::mutex> Lock(Mu);
227 Printf("================== Job %u exited with exit code %d ============\n",
229 fuzzer::CopyFileToErr(Log);
233 std::string CloneArgsWithoutX(const Vector<std::string> &Args,
234 const char *X1, const char *X2) {
236 for (auto &S : Args) {
237 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
244 static int RunInMultipleProcesses(const Vector<std::string> &Args,
245 unsigned NumWorkers, unsigned NumJobs) {
246 std::atomic<unsigned> Counter(0);
247 std::atomic<bool> HasErrors(false);
249 Cmd.removeFlag("jobs");
250 Cmd.removeFlag("workers");
251 Vector<std::thread> V;
252 std::thread Pulse(PulseThread);
254 for (unsigned i = 0; i < NumWorkers; i++)
255 V.push_back(std::thread(WorkerThread, std::ref(Cmd), &Counter, NumJobs, &HasErrors));
258 return HasErrors ? 1 : 0;
261 static void RssThread(Fuzzer *F, size_t RssLimitMb) {
264 size_t Peak = GetPeakRSSMb();
265 if (Peak > RssLimitMb)
266 F->RssLimitCallback();
270 static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
271 if (!RssLimitMb) return;
272 std::thread T(RssThread, F, RssLimitMb);
276 int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
277 Unit U = FileToVector(InputFilePath);
278 if (MaxLen && MaxLen < U.size())
280 F->ExecuteCallback(U.data(), U.size());
281 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
285 static bool AllInputsAreFiles() {
286 if (Inputs->empty()) return false;
287 for (auto &Path : *Inputs)
293 static std::string GetDedupTokenFromFile(const std::string &Path) {
294 auto S = FileToString(Path);
295 auto Beg = S.find("DEDUP_TOKEN:");
296 if (Beg == std::string::npos)
298 auto End = S.find('\n', Beg);
299 if (End == std::string::npos)
301 return S.substr(Beg, End - Beg);
304 int CleanseCrashInput(const Vector<std::string> &Args,
305 const FuzzingOptions &Options) {
306 if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
307 Printf("ERROR: -cleanse_crash should be given one input file and"
308 " -exact_artifact_path\n");
311 std::string InputFilePath = Inputs->at(0);
312 std::string OutputFilePath = Flags.exact_artifact_path;
314 Cmd.removeFlag("cleanse_crash");
316 assert(Cmd.hasArgument(InputFilePath));
317 Cmd.removeArgument(InputFilePath);
319 auto LogFilePath = DirPlusFile(
320 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
321 auto TmpFilePath = DirPlusFile(
322 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".repro");
323 Cmd.addArgument(TmpFilePath);
324 Cmd.setOutputFile(LogFilePath);
325 Cmd.combineOutAndErr();
327 std::string CurrentFilePath = InputFilePath;
328 auto U = FileToVector(CurrentFilePath);
329 size_t Size = U.size();
331 const Vector<uint8_t> ReplacementBytes = {' ', 0xff};
332 for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
333 bool Changed = false;
334 for (size_t Idx = 0; Idx < Size; Idx++) {
335 Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
337 uint8_t OriginalByte = U[Idx];
338 if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
339 ReplacementBytes.end(),
342 for (auto NewByte : ReplacementBytes) {
344 WriteToFile(U, TmpFilePath);
345 auto ExitCode = ExecuteCommand(Cmd);
346 RemoveFile(TmpFilePath);
348 U[Idx] = OriginalByte;
351 Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
352 WriteToFile(U, OutputFilePath);
359 RemoveFile(LogFilePath);
363 int MinimizeCrashInput(const Vector<std::string> &Args,
364 const FuzzingOptions &Options) {
365 if (Inputs->size() != 1) {
366 Printf("ERROR: -minimize_crash should be given one input file\n");
369 std::string InputFilePath = Inputs->at(0);
370 Command BaseCmd(Args);
371 BaseCmd.removeFlag("minimize_crash");
372 BaseCmd.removeFlag("exact_artifact_path");
373 assert(BaseCmd.hasArgument(InputFilePath));
374 BaseCmd.removeArgument(InputFilePath);
375 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
376 Printf("INFO: you need to specify -runs=N or "
377 "-max_total_time=N with -minimize_crash=1\n"
378 "INFO: defaulting to -max_total_time=600\n");
379 BaseCmd.addFlag("max_total_time", "600");
382 auto LogFilePath = DirPlusFile(
383 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
384 BaseCmd.setOutputFile(LogFilePath);
385 BaseCmd.combineOutAndErr();
387 std::string CurrentFilePath = InputFilePath;
389 Unit U = FileToVector(CurrentFilePath);
390 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
391 CurrentFilePath.c_str(), U.size());
393 Command Cmd(BaseCmd);
394 Cmd.addArgument(CurrentFilePath);
396 std::string CommandLine = Cmd.toString();
397 Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
398 int ExitCode = ExecuteCommand(Cmd);
400 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
403 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
405 CurrentFilePath.c_str(), U.size());
406 auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
407 if (!DedupToken1.empty())
408 Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
410 std::string ArtifactPath =
411 Flags.exact_artifact_path
412 ? Flags.exact_artifact_path
413 : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
414 Cmd.addFlag("minimize_crash_internal_step", "1");
415 Cmd.addFlag("exact_artifact_path", ArtifactPath);
416 CommandLine = Cmd.toString();
417 Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
418 ExitCode = ExecuteCommand(Cmd);
419 CopyFileToErr(LogFilePath);
421 if (Flags.exact_artifact_path) {
422 CurrentFilePath = Flags.exact_artifact_path;
423 WriteToFile(U, CurrentFilePath);
425 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
426 CurrentFilePath.c_str(), U.size());
429 auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
430 if (!DedupToken2.empty())
431 Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
433 if (DedupToken1 != DedupToken2) {
434 if (Flags.exact_artifact_path) {
435 CurrentFilePath = Flags.exact_artifact_path;
436 WriteToFile(U, CurrentFilePath);
438 Printf("CRASH_MIN: mismatch in dedup tokens"
439 " (looks like a different bug). Won't minimize further\n");
443 CurrentFilePath = ArtifactPath;
444 Printf("*********************************\n");
446 RemoveFile(LogFilePath);
450 int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
451 assert(Inputs->size() == 1);
452 std::string InputFilePath = Inputs->at(0);
453 Unit U = FileToVector(InputFilePath);
454 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
456 Printf("INFO: The input is small enough, exiting\n");
459 F->SetMaxInputLen(U.size());
460 F->SetMaxMutationLen(U.size() - 1);
461 F->MinimizeCrashLoop(U);
462 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
467 int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict,
468 UnitVector& Corpus) {
469 Printf("Started dictionary minimization (up to %d tests)\n",
470 Dict.size() * Corpus.size() * 2);
472 // Scores and usage count for each dictionary unit.
473 Vector<int> Scores(Dict.size());
474 Vector<int> Usages(Dict.size());
476 Vector<size_t> InitialFeatures;
477 Vector<size_t> ModifiedFeatures;
478 for (auto &C : Corpus) {
479 // Get coverage for the testcase without modifications.
480 F->ExecuteCallback(C.data(), C.size());
481 InitialFeatures.clear();
482 TPC.CollectFeatures([&](size_t Feature) {
483 InitialFeatures.push_back(Feature);
486 for (size_t i = 0; i < Dict.size(); ++i) {
487 Vector<uint8_t> Data = C;
488 auto StartPos = std::search(Data.begin(), Data.end(),
489 Dict[i].begin(), Dict[i].end());
490 // Skip dictionary unit, if the testcase does not contain it.
491 if (StartPos == Data.end())
495 while (StartPos != Data.end()) {
496 // Replace all occurrences of dictionary unit in the testcase.
497 auto EndPos = StartPos + Dict[i].size();
498 for (auto It = StartPos; It != EndPos; ++It)
501 StartPos = std::search(EndPos, Data.end(),
502 Dict[i].begin(), Dict[i].end());
505 // Get coverage for testcase with masked occurrences of dictionary unit.
506 F->ExecuteCallback(Data.data(), Data.size());
507 ModifiedFeatures.clear();
508 TPC.CollectFeatures([&](size_t Feature) {
509 ModifiedFeatures.push_back(Feature);
512 if (InitialFeatures == ModifiedFeatures)
519 Printf("###### Useless dictionary elements. ######\n");
520 for (size_t i = 0; i < Dict.size(); ++i) {
521 // Dictionary units with positive score are treated as useful ones.
526 PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
527 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
529 Printf("###### End of useless dictionary elements. ######\n");
533 int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
534 using namespace fuzzer;
535 assert(argc && argv && "Argument pointers cannot be nullptr");
536 std::string Argv0((*argv)[0]);
537 EF = new ExternalFunctions();
538 if (EF->LLVMFuzzerInitialize)
539 EF->LLVMFuzzerInitialize(argc, argv);
540 if (EF->__msan_scoped_disable_interceptor_checks)
541 EF->__msan_scoped_disable_interceptor_checks();
542 const Vector<std::string> Args(*argv, *argv + *argc);
543 assert(!Args.empty());
544 ProgName = new std::string(Args[0]);
545 if (Argv0 != *ProgName) {
546 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
555 if (Flags.close_fd_mask & 2)
557 if (Flags.close_fd_mask & 1)
560 if (Flags.jobs > 0 && Flags.workers == 0) {
561 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
562 if (Flags.workers > 1)
563 Printf("Running %u workers\n", Flags.workers);
566 if (Flags.workers > 0 && Flags.jobs > 0)
567 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
569 FuzzingOptions Options;
570 Options.Verbosity = Flags.verbosity;
571 Options.MaxLen = Flags.max_len;
572 Options.LenControl = Flags.len_control;
573 Options.UnitTimeoutSec = Flags.timeout;
574 Options.ErrorExitCode = Flags.error_exitcode;
575 Options.TimeoutExitCode = Flags.timeout_exitcode;
576 Options.MaxTotalTimeSec = Flags.max_total_time;
577 Options.DoCrossOver = Flags.cross_over;
578 Options.MutateDepth = Flags.mutate_depth;
579 Options.ReduceDepth = Flags.reduce_depth;
580 Options.UseCounters = Flags.use_counters;
581 Options.UseMemmem = Flags.use_memmem;
582 Options.UseCmp = Flags.use_cmp;
583 Options.UseValueProfile = Flags.use_value_profile;
584 Options.Shrink = Flags.shrink;
585 Options.ReduceInputs = Flags.reduce_inputs;
586 Options.ShuffleAtStartUp = Flags.shuffle;
587 Options.PreferSmall = Flags.prefer_small;
588 Options.ReloadIntervalSec = Flags.reload;
589 Options.OnlyASCII = Flags.only_ascii;
590 Options.DetectLeaks = Flags.detect_leaks;
591 Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval;
592 Options.TraceMalloc = Flags.trace_malloc;
593 Options.RssLimitMb = Flags.rss_limit_mb;
594 Options.MallocLimitMb = Flags.malloc_limit_mb;
595 if (!Options.MallocLimitMb)
596 Options.MallocLimitMb = Options.RssLimitMb;
598 Options.MaxNumberOfRuns = Flags.runs;
599 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
600 Options.OutputCorpus = (*Inputs)[0];
601 Options.ReportSlowUnits = Flags.report_slow_units;
602 if (Flags.artifact_prefix)
603 Options.ArtifactPrefix = Flags.artifact_prefix;
604 if (Flags.exact_artifact_path)
605 Options.ExactArtifactPath = Flags.exact_artifact_path;
606 Vector<Unit> Dictionary;
608 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
610 if (Flags.verbosity > 0 && !Dictionary.empty())
611 Printf("Dictionary: %zd entries\n", Dictionary.size());
612 bool DoPlainRun = AllInputsAreFiles();
613 Options.SaveArtifacts =
614 !DoPlainRun || Flags.minimize_crash_internal_step;
615 Options.PrintNewCovPcs = Flags.print_pcs;
616 Options.PrintNewCovFuncs = Flags.print_funcs;
617 Options.PrintFinalStats = Flags.print_final_stats;
618 Options.PrintMutationStats = Flags.print_mutation_stats;
619 Options.PrintCorpusStats = Flags.print_corpus_stats;
620 Options.PrintCoverage = Flags.print_coverage;
621 Options.PrintUnstableStats = Flags.print_unstable_stats;
622 if (Flags.handle_unstable == TracePC::MinUnstable ||
623 Flags.handle_unstable == TracePC::ZeroUnstable)
624 Options.HandleUnstable = Flags.handle_unstable;
625 Options.DumpCoverage = Flags.dump_coverage;
626 if (Flags.exit_on_src_pos)
627 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
628 if (Flags.exit_on_item)
629 Options.ExitOnItem = Flags.exit_on_item;
630 if (Flags.focus_function)
631 Options.FocusFunction = Flags.focus_function;
632 if (Flags.data_flow_trace)
633 Options.DataFlowTrace = Flags.data_flow_trace;
635 unsigned Seed = Flags.seed;
639 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
641 Printf("INFO: Seed: %u\n", Seed);
644 auto *MD = new MutationDispatcher(Rand, Options);
645 auto *Corpus = new InputCorpus(Options.OutputCorpus);
646 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
648 for (auto &U: Dictionary)
649 if (U.size() <= Word::GetMaxSize())
650 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
652 StartRssThread(F, Flags.rss_limit_mb);
654 Options.HandleAbrt = Flags.handle_abrt;
655 Options.HandleBus = Flags.handle_bus;
656 Options.HandleFpe = Flags.handle_fpe;
657 Options.HandleIll = Flags.handle_ill;
658 Options.HandleInt = Flags.handle_int;
659 Options.HandleSegv = Flags.handle_segv;
660 Options.HandleTerm = Flags.handle_term;
661 Options.HandleXfsz = Flags.handle_xfsz;
662 Options.HandleUsr1 = Flags.handle_usr1;
663 Options.HandleUsr2 = Flags.handle_usr2;
664 SetSignalHandler(Options);
666 std::atexit(Fuzzer::StaticExitCallback);
668 if (Flags.minimize_crash)
669 return MinimizeCrashInput(Args, Options);
671 if (Flags.minimize_crash_internal_step)
672 return MinimizeCrashInputInternalStep(F, Corpus);
674 if (Flags.cleanse_crash)
675 return CleanseCrashInput(Args, Options);
677 #if 0 // deprecated, to be removed.
678 if (auto Name = Flags.run_equivalence_server) {
680 if (!SMR.Create(Name)) {
681 Printf("ERROR: can't create shared memory region\n");
684 Printf("INFO: EQUIVALENCE SERVER UP\n");
687 size_t Size = SMR.ReadByteArraySize();
688 SMR.WriteByteArray(nullptr, 0);
689 const Unit tmp(SMR.GetByteArray(), SMR.GetByteArray() + Size);
690 F->ExecuteCallback(tmp.data(), tmp.size());
696 if (auto Name = Flags.use_equivalence_server) {
697 if (!SMR.Open(Name)) {
698 Printf("ERROR: can't open shared memory region\n");
701 Printf("INFO: EQUIVALENCE CLIENT UP\n");
706 Options.SaveArtifacts = false;
707 int Runs = std::max(1, Flags.runs);
708 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
709 Inputs->size(), Runs);
710 for (auto &Path : *Inputs) {
711 auto StartTime = system_clock::now();
712 Printf("Running: %s\n", Path.c_str());
713 for (int Iter = 0; Iter < Runs; Iter++)
714 RunOneTest(F, Path.c_str(), Options.MaxLen);
715 auto StopTime = system_clock::now();
716 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
717 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
720 "*** NOTE: fuzzing was not performed, you have only\n"
721 "*** executed the target code on a fixed set of inputs.\n"
723 F->PrintFinalStats();
728 F->CrashResistantMerge(Args, *Inputs,
729 Flags.load_coverage_summary,
730 Flags.save_coverage_summary,
731 Flags.merge_control_file);
735 if (Flags.merge_inner) {
736 const size_t kDefaultMaxMergeLen = 1 << 20;
737 if (Options.MaxLen == 0)
738 F->SetMaxInputLen(kDefaultMaxMergeLen);
739 assert(Flags.merge_control_file);
740 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
744 if (Flags.analyze_dict) {
745 size_t MaxLen = INT_MAX; // Large max length.
746 UnitVector InitialCorpus;
747 for (auto &Inp : *Inputs) {
748 Printf("Loading corpus dir: %s\n", Inp.c_str());
749 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
750 MaxLen, /*ExitOnError=*/false);
753 if (Dictionary.empty() || Inputs->empty()) {
754 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
757 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
758 Printf("Dictionary analysis failed\n");
761 Printf("Dictionary analysis succeeded\n");
768 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
769 F->secondsSinceProcessStartUp());
770 F->PrintFinalStats();
772 exit(0); // Don't let F destroy itself.
775 // Storage for global ExternalFunctions object.
776 ExternalFunctions *EF = nullptr;
778 } // namespace fuzzer