1 //===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
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 // Fuzzer's main loop.
9 //===----------------------------------------------------------------------===//
10 
11 #include "FuzzerCorpus.h"
12 #include "FuzzerIO.h"
13 #include "FuzzerInternal.h"
14 #include "FuzzerMutate.h"
15 #include "FuzzerRandom.h"
16 #include "FuzzerTracePC.h"
17 #include <algorithm>
18 #include <cstring>
19 #include <memory>
20 #include <mutex>
21 #include <set>
22 
23 #if defined(__has_include)
24 #if __has_include(<sanitizer / lsan_interface.h>)
25 #include <sanitizer/lsan_interface.h>
26 #endif
27 #endif
28 
29 #define NO_SANITIZE_MEMORY
30 #if defined(__has_feature)
31 #if __has_feature(memory_sanitizer)
32 #undef NO_SANITIZE_MEMORY
33 #define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
34 #endif
35 #endif
36 
37 namespace fuzzer {
38 static const size_t kMaxUnitSizeToPrint = 256;
39 
40 thread_local bool Fuzzer::IsMyThread;
41 
42 bool RunningUserCallback = false;
43 
44 // Only one Fuzzer per process.
45 static Fuzzer *F;
46 
47 // Leak detection is expensive, so we first check if there were more mallocs
48 // than frees (using the sanitizer malloc hooks) and only then try to call lsan.
49 struct MallocFreeTracer {
50   void Start(int TraceLevel) {
51     this->TraceLevel = TraceLevel;
52     if (TraceLevel)
53       Printf("MallocFreeTracer: START\n");
54     Mallocs = 0;
55     Frees = 0;
56   }
57   // Returns true if there were more mallocs than frees.
58   bool Stop() {
59     if (TraceLevel)
60       Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
61              Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
62     bool Result = Mallocs > Frees;
63     Mallocs = 0;
64     Frees = 0;
65     TraceLevel = 0;
66     return Result;
67   }
68   std::atomic<size_t> Mallocs;
69   std::atomic<size_t> Frees;
70   int TraceLevel = 0;
71 
72   std::recursive_mutex TraceMutex;
73   bool TraceDisabled = false;
74 };
75 
76 static MallocFreeTracer AllocTracer;
77 
78 // Locks printing and avoids nested hooks triggered from mallocs/frees in
79 // sanitizer.
80 class TraceLock {
81 public:
82   TraceLock() : Lock(AllocTracer.TraceMutex) {
83     AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
84   }
85   ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
86 
87   bool IsDisabled() const {
88     // This is already inverted value.
89     return !AllocTracer.TraceDisabled;
90   }
91 
92 private:
93   std::lock_guard<std::recursive_mutex> Lock;
94 };
95 
96 ATTRIBUTE_NO_SANITIZE_MEMORY
97 void MallocHook(const volatile void *ptr, size_t size) {
98   size_t N = AllocTracer.Mallocs++;
99   F->HandleMalloc(size);
100   if (int TraceLevel = AllocTracer.TraceLevel) {
101     TraceLock Lock;
102     if (Lock.IsDisabled())
103       return;
104     Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
105     if (TraceLevel >= 2 && EF)
106       PrintStackTrace();
107   }
108 }
109 
110 ATTRIBUTE_NO_SANITIZE_MEMORY
111 void FreeHook(const volatile void *ptr) {
112   size_t N = AllocTracer.Frees++;
113   if (int TraceLevel = AllocTracer.TraceLevel) {
114     TraceLock Lock;
115     if (Lock.IsDisabled())
116       return;
117     Printf("FREE[%zd]   %p\n", N, ptr);
118     if (TraceLevel >= 2 && EF)
119       PrintStackTrace();
120   }
121 }
122 
123 // Crash on a single malloc that exceeds the rss limit.
124 void Fuzzer::HandleMalloc(size_t Size) {
125   if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
126     return;
127   Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
128          Size);
129   Printf("   To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
130   PrintStackTrace();
131   DumpCurrentUnit("oom-");
132   Printf("SUMMARY: libFuzzer: out-of-memory\n");
133   PrintFinalStats();
134   _Exit(Options.OOMExitCode); // Stop right now.
135 }
136 
137 Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
138                FuzzingOptions Options)
139     : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
140   if (EF->__sanitizer_set_death_callback)
141     EF->__sanitizer_set_death_callback(StaticDeathCallback);
142   assert(!F);
143   F = this;
144   TPC.ResetMaps();
145   IsMyThread = true;
146   if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
147     EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
148   TPC.SetUseCounters(Options.UseCounters);
149   TPC.SetUseValueProfileMask(Options.UseValueProfile);
150 
151   if (Options.Verbosity)
152     TPC.PrintModuleInfo();
153   if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
154     EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
155   MaxInputLen = MaxMutationLen = Options.MaxLen;
156   TmpMaxMutationLen = 0;  // Will be set once we load the corpus.
157   AllocateCurrentUnitData();
158   CurrentUnitSize = 0;
159   memset(BaseSha1, 0, sizeof(BaseSha1));
160   TPC.SetFocusFunction(Options.FocusFunction);
161   DFT.Init(Options.DataFlowTrace, Options.FocusFunction);
162 }
163 
164 Fuzzer::~Fuzzer() {}
165 
166 void Fuzzer::AllocateCurrentUnitData() {
167   if (CurrentUnitData || MaxInputLen == 0)
168     return;
169   CurrentUnitData = new uint8_t[MaxInputLen];
170 }
171 
172 void Fuzzer::StaticDeathCallback() {
173   assert(F);
174   F->DeathCallback();
175 }
176 
177 void Fuzzer::DumpCurrentUnit(const char *Prefix) {
178   if (!CurrentUnitData)
179     return; // Happens when running individual inputs.
180   ScopedDisableMsanInterceptorChecks S;
181   MD.PrintMutationSequence();
182   Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
183   size_t UnitSize = CurrentUnitSize;
184   if (UnitSize <= kMaxUnitSizeToPrint) {
185     PrintHexArray(CurrentUnitData, UnitSize, "\n");
186     PrintASCII(CurrentUnitData, UnitSize, "\n");
187   }
188   WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
189                             Prefix);
190 }
191 
192 NO_SANITIZE_MEMORY
193 void Fuzzer::DeathCallback() {
194   DumpCurrentUnit("crash-");
195   PrintFinalStats();
196 }
197 
198 void Fuzzer::StaticAlarmCallback() {
199   assert(F);
200   F->AlarmCallback();
201 }
202 
203 void Fuzzer::StaticCrashSignalCallback() {
204   assert(F);
205   F->CrashCallback();
206 }
207 
208 void Fuzzer::StaticExitCallback() {
209   assert(F);
210   F->ExitCallback();
211 }
212 
213 void Fuzzer::StaticInterruptCallback() {
214   assert(F);
215   F->InterruptCallback();
216 }
217 
218 void Fuzzer::StaticGracefulExitCallback() {
219   assert(F);
220   F->GracefulExitRequested = true;
221   Printf("INFO: signal received, trying to exit gracefully\n");
222 }
223 
224 void Fuzzer::StaticFileSizeExceedCallback() {
225   Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
226   exit(1);
227 }
228 
229 void Fuzzer::CrashCallback() {
230   if (EF->__sanitizer_acquire_crash_state &&
231       !EF->__sanitizer_acquire_crash_state())
232     return;
233   Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
234   PrintStackTrace();
235   Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
236          "      Combine libFuzzer with AddressSanitizer or similar for better "
237          "crash reports.\n");
238   Printf("SUMMARY: libFuzzer: deadly signal\n");
239   DumpCurrentUnit("crash-");
240   PrintFinalStats();
241   _Exit(Options.ErrorExitCode); // Stop right now.
242 }
243 
244 void Fuzzer::ExitCallback() {
245   if (!RunningUserCallback)
246     return; // This exit did not come from the user callback
247   if (EF->__sanitizer_acquire_crash_state &&
248       !EF->__sanitizer_acquire_crash_state())
249     return;
250   Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
251   PrintStackTrace();
252   Printf("SUMMARY: libFuzzer: fuzz target exited\n");
253   DumpCurrentUnit("crash-");
254   PrintFinalStats();
255   _Exit(Options.ErrorExitCode);
256 }
257 
258 void Fuzzer::MaybeExitGracefully() {
259   if (!F->GracefulExitRequested) return;
260   Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
261   RmDirRecursive(TempPath(".dir"));
262   F->PrintFinalStats();
263   _Exit(0);
264 }
265 
266 void Fuzzer::InterruptCallback() {
267   Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
268   PrintFinalStats();
269   ScopedDisableMsanInterceptorChecks S; // RmDirRecursive may call opendir().
270   RmDirRecursive(TempPath(".dir"));
271   // Stop right now, don't perform any at-exit actions.
272   _Exit(Options.InterruptExitCode);
273 }
274 
275 NO_SANITIZE_MEMORY
276 void Fuzzer::AlarmCallback() {
277   assert(Options.UnitTimeoutSec > 0);
278   // In Windows Alarm callback is executed by a different thread.
279   // NetBSD's current behavior needs this change too.
280 #if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD
281   if (!InFuzzingThread())
282     return;
283 #endif
284   if (!RunningUserCallback)
285     return; // We have not started running units yet.
286   size_t Seconds =
287       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
288   if (Seconds == 0)
289     return;
290   if (Options.Verbosity >= 2)
291     Printf("AlarmCallback %zd\n", Seconds);
292   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
293     if (EF->__sanitizer_acquire_crash_state &&
294         !EF->__sanitizer_acquire_crash_state())
295       return;
296     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
297     Printf("       and the timeout value is %d (use -timeout=N to change)\n",
298            Options.UnitTimeoutSec);
299     DumpCurrentUnit("timeout-");
300     Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
301            Seconds);
302     PrintStackTrace();
303     Printf("SUMMARY: libFuzzer: timeout\n");
304     PrintFinalStats();
305     _Exit(Options.TimeoutExitCode); // Stop right now.
306   }
307 }
308 
309 void Fuzzer::RssLimitCallback() {
310   if (EF->__sanitizer_acquire_crash_state &&
311       !EF->__sanitizer_acquire_crash_state())
312     return;
313   Printf(
314       "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
315       GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
316   Printf("   To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
317   PrintMemoryProfile();
318   DumpCurrentUnit("oom-");
319   Printf("SUMMARY: libFuzzer: out-of-memory\n");
320   PrintFinalStats();
321   _Exit(Options.OOMExitCode); // Stop right now.
322 }
323 
324 void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
325   size_t ExecPerSec = execPerSec();
326   if (!Options.Verbosity)
327     return;
328   Printf("#%zd\t%s", TotalNumberOfRuns, Where);
329   if (size_t N = TPC.GetTotalPCCoverage())
330     Printf(" cov: %zd", N);
331   if (size_t N = Corpus.NumFeatures())
332     Printf(" ft: %zd", N);
333   if (!Corpus.empty()) {
334     Printf(" corp: %zd", Corpus.NumActiveUnits());
335     if (size_t N = Corpus.SizeInBytes()) {
336       if (N < (1 << 14))
337         Printf("/%zdb", N);
338       else if (N < (1 << 24))
339         Printf("/%zdKb", N >> 10);
340       else
341         Printf("/%zdMb", N >> 20);
342     }
343     if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
344       Printf(" focus: %zd", FF);
345   }
346   if (TmpMaxMutationLen)
347     Printf(" lim: %zd", TmpMaxMutationLen);
348   if (Units)
349     Printf(" units: %zd", Units);
350 
351   Printf(" exec/s: %zd", ExecPerSec);
352   Printf(" rss: %zdMb", GetPeakRSSMb());
353   Printf("%s", End);
354 }
355 
356 void Fuzzer::PrintFinalStats() {
357   if (Options.PrintCoverage)
358     TPC.PrintCoverage();
359   if (Options.PrintCorpusStats)
360     Corpus.PrintStats();
361   if (!Options.PrintFinalStats)
362     return;
363   size_t ExecPerSec = execPerSec();
364   Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
365   Printf("stat::average_exec_per_sec:     %zd\n", ExecPerSec);
366   Printf("stat::new_units_added:          %zd\n", NumberOfNewUnitsAdded);
367   Printf("stat::slowest_unit_time_sec:    %zd\n", TimeOfLongestUnitInSeconds);
368   Printf("stat::peak_rss_mb:              %zd\n", GetPeakRSSMb());
369 }
370 
371 void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
372   assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
373   assert(MaxInputLen);
374   this->MaxInputLen = MaxInputLen;
375   this->MaxMutationLen = MaxInputLen;
376   AllocateCurrentUnitData();
377   Printf("INFO: -max_len is not provided; "
378          "libFuzzer will not generate inputs larger than %zd bytes\n",
379          MaxInputLen);
380 }
381 
382 void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
383   assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
384   this->MaxMutationLen = MaxMutationLen;
385 }
386 
387 void Fuzzer::CheckExitOnSrcPosOrItem() {
388   if (!Options.ExitOnSrcPos.empty()) {
389     static auto *PCsSet = new Set<uintptr_t>;
390     auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
391       if (!PCsSet->insert(TE->PC).second)
392         return;
393       std::string Descr = DescribePC("%F %L", TE->PC + 1);
394       if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
395         Printf("INFO: found line matching '%s', exiting.\n",
396                Options.ExitOnSrcPos.c_str());
397         _Exit(0);
398       }
399     };
400     TPC.ForEachObservedPC(HandlePC);
401   }
402   if (!Options.ExitOnItem.empty()) {
403     if (Corpus.HasUnit(Options.ExitOnItem)) {
404       Printf("INFO: found item with checksum '%s', exiting.\n",
405              Options.ExitOnItem.c_str());
406       _Exit(0);
407     }
408   }
409 }
410 
411 void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
412   if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
413     return;
414   Vector<Unit> AdditionalCorpus;
415   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
416                          &EpochOfLastReadOfOutputCorpus, MaxSize,
417                          /*ExitOnError*/ false);
418   if (Options.Verbosity >= 2)
419     Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
420   bool Reloaded = false;
421   for (auto &U : AdditionalCorpus) {
422     if (U.size() > MaxSize)
423       U.resize(MaxSize);
424     if (!Corpus.HasUnit(U)) {
425       if (RunOne(U.data(), U.size())) {
426         CheckExitOnSrcPosOrItem();
427         Reloaded = true;
428       }
429     }
430   }
431   if (Reloaded)
432     PrintStats("RELOAD");
433 }
434 
435 void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
436   auto TimeOfUnit =
437       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
438   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
439       secondsSinceProcessStartUp() >= 2)
440     PrintStats("pulse ");
441   if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
442       TimeOfUnit >= Options.ReportSlowUnits) {
443     TimeOfLongestUnitInSeconds = TimeOfUnit;
444     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
445     WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
446   }
447 }
448 
449 static void WriteFeatureSetToFile(const std::string &FeaturesDir,
450                                   const std::string &FileName,
451                                   const Vector<uint32_t> &FeatureSet) {
452   if (FeaturesDir.empty() || FeatureSet.empty()) return;
453   WriteToFile(reinterpret_cast<const uint8_t *>(FeatureSet.data()),
454               FeatureSet.size() * sizeof(FeatureSet[0]),
455               DirPlusFile(FeaturesDir, FileName));
456 }
457 
458 static void RenameFeatureSetFile(const std::string &FeaturesDir,
459                                  const std::string &OldFile,
460                                  const std::string &NewFile) {
461   if (FeaturesDir.empty()) return;
462   RenameFile(DirPlusFile(FeaturesDir, OldFile),
463              DirPlusFile(FeaturesDir, NewFile));
464 }
465 
466 bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
467                     InputInfo *II, bool *FoundUniqFeatures) {
468   if (!Size)
469     return false;
470 
471   ExecuteCallback(Data, Size);
472 
473   UniqFeatureSetTmp.clear();
474   size_t FoundUniqFeaturesOfII = 0;
475   size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
476   TPC.CollectFeatures([&](size_t Feature) {
477     if (Corpus.AddFeature(Feature, Size, Options.Shrink))
478       UniqFeatureSetTmp.push_back(Feature);
479     if (Options.ReduceInputs && II)
480       if (std::binary_search(II->UniqFeatureSet.begin(),
481                              II->UniqFeatureSet.end(), Feature))
482         FoundUniqFeaturesOfII++;
483   });
484   if (FoundUniqFeatures)
485     *FoundUniqFeatures = FoundUniqFeaturesOfII;
486   PrintPulseAndReportSlowInput(Data, Size);
487   size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
488   if (NumNewFeatures) {
489     TPC.UpdateObservedPCs();
490     auto NewII = Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures,
491                                     MayDeleteFile, TPC.ObservedFocusFunction(),
492                                     UniqFeatureSetTmp, DFT, II);
493     WriteFeatureSetToFile(Options.FeaturesDir, Sha1ToString(NewII->Sha1),
494                           NewII->UniqFeatureSet);
495     return true;
496   }
497   if (II && FoundUniqFeaturesOfII &&
498       II->DataFlowTraceForFocusFunction.empty() &&
499       FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
500       II->U.size() > Size) {
501     auto OldFeaturesFile = Sha1ToString(II->Sha1);
502     Corpus.Replace(II, {Data, Data + Size});
503     RenameFeatureSetFile(Options.FeaturesDir, OldFeaturesFile,
504                          Sha1ToString(II->Sha1));
505     return true;
506   }
507   return false;
508 }
509 
510 size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
511   assert(InFuzzingThread());
512   *Data = CurrentUnitData;
513   return CurrentUnitSize;
514 }
515 
516 void Fuzzer::CrashOnOverwrittenData() {
517   Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
518          GetPid());
519   DumpCurrentUnit("crash-");
520   Printf("SUMMARY: libFuzzer: out-of-memory\n");
521   _Exit(Options.ErrorExitCode); // Stop right now.
522 }
523 
524 // Compare two arrays, but not all bytes if the arrays are large.
525 static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
526   const size_t Limit = 64;
527   if (Size <= 64)
528     return !memcmp(A, B, Size);
529   // Compare first and last Limit/2 bytes.
530   return !memcmp(A, B, Limit / 2) &&
531          !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
532 }
533 
534 void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
535   TPC.RecordInitialStack();
536   TotalNumberOfRuns++;
537   assert(InFuzzingThread());
538   // We copy the contents of Unit into a separate heap buffer
539   // so that we reliably find buffer overflows in it.
540   uint8_t *DataCopy = new uint8_t[Size];
541   memcpy(DataCopy, Data, Size);
542   if (EF->__msan_unpoison)
543     EF->__msan_unpoison(DataCopy, Size);
544   if (CurrentUnitData && CurrentUnitData != Data)
545     memcpy(CurrentUnitData, Data, Size);
546   CurrentUnitSize = Size;
547   {
548     ScopedEnableMsanInterceptorChecks S;
549     AllocTracer.Start(Options.TraceMalloc);
550     UnitStartTime = system_clock::now();
551     TPC.ResetMaps();
552     RunningUserCallback = true;
553     int Res = CB(DataCopy, Size);
554     RunningUserCallback = false;
555     UnitStopTime = system_clock::now();
556     (void)Res;
557     assert(Res == 0);
558     HasMoreMallocsThanFrees = AllocTracer.Stop();
559   }
560   if (!LooseMemeq(DataCopy, Data, Size))
561     CrashOnOverwrittenData();
562   CurrentUnitSize = 0;
563   delete[] DataCopy;
564 }
565 
566 std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
567   if (Options.OnlyASCII)
568     assert(IsASCII(U));
569   if (Options.OutputCorpus.empty())
570     return "";
571   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
572   WriteToFile(U, Path);
573   if (Options.Verbosity >= 2)
574     Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
575   return Path;
576 }
577 
578 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
579   if (!Options.SaveArtifacts)
580     return;
581   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
582   if (!Options.ExactArtifactPath.empty())
583     Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
584   WriteToFile(U, Path);
585   Printf("artifact_prefix='%s'; Test unit written to %s\n",
586          Options.ArtifactPrefix.c_str(), Path.c_str());
587   if (U.size() <= kMaxUnitSizeToPrint)
588     Printf("Base64: %s\n", Base64(U).c_str());
589 }
590 
591 void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
592   if (!Options.PrintNEW)
593     return;
594   PrintStats(Text, "");
595   if (Options.Verbosity) {
596     Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
597     MD.PrintMutationSequence();
598     Printf("\n");
599   }
600 }
601 
602 void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
603   II->NumSuccessfullMutations++;
604   MD.RecordSuccessfulMutationSequence();
605   PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW   ");
606   WriteToOutputCorpus(U);
607   NumberOfNewUnitsAdded++;
608   CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
609   LastCorpusUpdateRun = TotalNumberOfRuns;
610 }
611 
612 // Tries detecting a memory leak on the particular input that we have just
613 // executed before calling this function.
614 void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
615                                      bool DuringInitialCorpusExecution) {
616   if (!HasMoreMallocsThanFrees)
617     return; // mallocs==frees, a leak is unlikely.
618   if (!Options.DetectLeaks)
619     return;
620   if (!DuringInitialCorpusExecution &&
621       TotalNumberOfRuns >= Options.MaxNumberOfRuns)
622     return;
623   if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
624       !(EF->__lsan_do_recoverable_leak_check))
625     return; // No lsan.
626   // Run the target once again, but with lsan disabled so that if there is
627   // a real leak we do not report it twice.
628   EF->__lsan_disable();
629   ExecuteCallback(Data, Size);
630   EF->__lsan_enable();
631   if (!HasMoreMallocsThanFrees)
632     return; // a leak is unlikely.
633   if (NumberOfLeakDetectionAttempts++ > 1000) {
634     Options.DetectLeaks = false;
635     Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
636            "      Most likely the target function accumulates allocated\n"
637            "      memory in a global state w/o actually leaking it.\n"
638            "      You may try running this binary with -trace_malloc=[12]"
639            "      to get a trace of mallocs and frees.\n"
640            "      If LeakSanitizer is enabled in this process it will still\n"
641            "      run on the process shutdown.\n");
642     return;
643   }
644   // Now perform the actual lsan pass. This is expensive and we must ensure
645   // we don't call it too often.
646   if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
647     if (DuringInitialCorpusExecution)
648       Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
649     Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
650     CurrentUnitSize = Size;
651     DumpCurrentUnit("leak-");
652     PrintFinalStats();
653     _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
654   }
655 }
656 
657 void Fuzzer::MutateAndTestOne() {
658   MD.StartMutationSequence();
659 
660   auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
661   if (Options.DoCrossOver)
662     MD.SetCrossOverWith(&Corpus.ChooseUnitToMutate(MD.GetRand()).U);
663   const auto &U = II.U;
664   memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
665   assert(CurrentUnitData);
666   size_t Size = U.size();
667   assert(Size <= MaxInputLen && "Oversized Unit");
668   memcpy(CurrentUnitData, U.data(), Size);
669 
670   assert(MaxMutationLen > 0);
671 
672   size_t CurrentMaxMutationLen =
673       Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
674   assert(CurrentMaxMutationLen > 0);
675 
676   for (int i = 0; i < Options.MutateDepth; i++) {
677     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
678       break;
679     MaybeExitGracefully();
680     size_t NewSize = 0;
681     if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
682         Size <= CurrentMaxMutationLen)
683       NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
684                                   II.DataFlowTraceForFocusFunction);
685 
686     // If MutateWithMask either failed or wasn't called, call default Mutate.
687     if (!NewSize)
688       NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
689     assert(NewSize > 0 && "Mutator returned empty unit");
690     assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
691     Size = NewSize;
692     II.NumExecutedMutations++;
693 
694     bool FoundUniqFeatures = false;
695     bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
696                          &FoundUniqFeatures);
697     TryDetectingAMemoryLeak(CurrentUnitData, Size,
698                             /*DuringInitialCorpusExecution*/ false);
699     if (NewCov) {
700       ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
701       break;  // We will mutate this input more in the next rounds.
702     }
703     if (Options.ReduceDepth && !FoundUniqFeatures)
704         break;
705   }
706 }
707 
708 void Fuzzer::PurgeAllocator() {
709   if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
710     return;
711   if (duration_cast<seconds>(system_clock::now() -
712                              LastAllocatorPurgeAttemptTime)
713           .count() < Options.PurgeAllocatorIntervalSec)
714     return;
715 
716   if (Options.RssLimitMb <= 0 ||
717       GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
718     EF->__sanitizer_purge_allocator();
719 
720   LastAllocatorPurgeAttemptTime = system_clock::now();
721 }
722 
723 void Fuzzer::ReadAndExecuteSeedCorpora(
724     const Vector<std::string> &CorpusDirs,
725     const Vector<std::string> &ExtraSeedFiles) {
726   const size_t kMaxSaneLen = 1 << 20;
727   const size_t kMinDefaultLen = 4096;
728   Vector<SizedFile> SizedFiles;
729   size_t MaxSize = 0;
730   size_t MinSize = -1;
731   size_t TotalSize = 0;
732   size_t LastNumFiles = 0;
733   for (auto &Dir : CorpusDirs) {
734     GetSizedFilesFromDir(Dir, &SizedFiles);
735     Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
736            Dir.c_str());
737     LastNumFiles = SizedFiles.size();
738   }
739   // Add files from -seed_inputs.
740   for (auto &File : ExtraSeedFiles)
741     if (auto Size = FileSize(File))
742       SizedFiles.push_back({File, Size});
743 
744   for (auto &File : SizedFiles) {
745     MaxSize = Max(File.Size, MaxSize);
746     MinSize = Min(File.Size, MinSize);
747     TotalSize += File.Size;
748   }
749   if (Options.MaxLen == 0)
750     SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
751   assert(MaxInputLen > 0);
752 
753   // Test the callback with empty input and never try it again.
754   uint8_t dummy = 0;
755   ExecuteCallback(&dummy, 0);
756 
757   // Protect lazy counters here, after the once-init code has been executed.
758   if (Options.LazyCounters)
759     TPC.ProtectLazyCounters();
760 
761   if (SizedFiles.empty()) {
762     Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
763     Unit U({'\n'}); // Valid ASCII input.
764     RunOne(U.data(), U.size());
765   } else {
766     Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
767            " rss: %zdMb\n",
768            SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
769     if (Options.ShuffleAtStartUp)
770       std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
771 
772     if (Options.PreferSmall) {
773       std::stable_sort(SizedFiles.begin(), SizedFiles.end());
774       assert(SizedFiles.front().Size <= SizedFiles.back().Size);
775     }
776 
777     // Load and execute inputs one by one.
778     for (auto &SF : SizedFiles) {
779       auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
780       assert(U.size() <= MaxInputLen);
781       RunOne(U.data(), U.size());
782       CheckExitOnSrcPosOrItem();
783       TryDetectingAMemoryLeak(U.data(), U.size(),
784                               /*DuringInitialCorpusExecution*/ true);
785     }
786   }
787 
788   PrintStats("INITED");
789   if (!Options.FocusFunction.empty())
790     Printf("INFO: %zd/%zd inputs touch the focus function\n",
791            Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
792   if (!Options.DataFlowTrace.empty())
793     Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
794            Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
795 
796   if (Corpus.empty() && Options.MaxNumberOfRuns) {
797     Printf("ERROR: no interesting inputs were found. "
798            "Is the code instrumented for coverage? Exiting.\n");
799     exit(1);
800   }
801 }
802 
803 void Fuzzer::Loop(const Vector<std::string> &CorpusDirs,
804                   const Vector<std::string> &ExtraSeedFiles) {
805   ReadAndExecuteSeedCorpora(CorpusDirs, ExtraSeedFiles);
806   DFT.Clear();  // No need for DFT any more.
807   TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
808   TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
809   system_clock::time_point LastCorpusReload = system_clock::now();
810 
811   TmpMaxMutationLen =
812       Min(MaxMutationLen, Max(size_t(4), Corpus.MaxInputSize()));
813 
814   while (true) {
815     auto Now = system_clock::now();
816     if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
817         Options.ReloadIntervalSec) {
818       RereadOutputCorpus(MaxInputLen);
819       LastCorpusReload = system_clock::now();
820     }
821     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
822       break;
823     if (TimedOut())
824       break;
825 
826     // Update TmpMaxMutationLen
827     if (Options.LenControl) {
828       if (TmpMaxMutationLen < MaxMutationLen &&
829           TotalNumberOfRuns - LastCorpusUpdateRun >
830               Options.LenControl * Log(TmpMaxMutationLen)) {
831         TmpMaxMutationLen =
832             Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
833         LastCorpusUpdateRun = TotalNumberOfRuns;
834       }
835     } else {
836       TmpMaxMutationLen = MaxMutationLen;
837     }
838 
839     // Perform several mutations and runs.
840     MutateAndTestOne();
841 
842     PurgeAllocator();
843   }
844 
845   PrintStats("DONE  ", "\n");
846   MD.PrintRecommendedDictionary();
847 }
848 
849 void Fuzzer::MinimizeCrashLoop(const Unit &U) {
850   if (U.size() <= 1)
851     return;
852   while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
853     MD.StartMutationSequence();
854     memcpy(CurrentUnitData, U.data(), U.size());
855     for (int i = 0; i < Options.MutateDepth; i++) {
856       size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
857       assert(NewSize > 0 && NewSize <= MaxMutationLen);
858       ExecuteCallback(CurrentUnitData, NewSize);
859       PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
860       TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
861                               /*DuringInitialCorpusExecution*/ false);
862     }
863   }
864 }
865 
866 } // namespace fuzzer
867 
868 extern "C" {
869 
870 ATTRIBUTE_INTERFACE size_t
871 LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
872   assert(fuzzer::F);
873   return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
874 }
875 
876 } // extern "C"
877