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 = Max(size_t(4), Corpus.MaxInputSize());
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   F->PrintFinalStats();
262   _Exit(0);
263 }
264 
265 void Fuzzer::InterruptCallback() {
266   Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
267   PrintFinalStats();
268   // Stop right now, don't perform any at-exit actions.
269   _Exit(Options.InterruptExitCode);
270 }
271 
272 NO_SANITIZE_MEMORY
273 void Fuzzer::AlarmCallback() {
274   assert(Options.UnitTimeoutSec > 0);
275   // In Windows Alarm callback is executed by a different thread.
276   // NetBSD's current behavior needs this change too.
277 #if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD
278   if (!InFuzzingThread())
279     return;
280 #endif
281   if (!RunningUserCallback)
282     return; // We have not started running units yet.
283   size_t Seconds =
284       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
285   if (Seconds == 0)
286     return;
287   if (Options.Verbosity >= 2)
288     Printf("AlarmCallback %zd\n", Seconds);
289   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
290     if (EF->__sanitizer_acquire_crash_state &&
291         !EF->__sanitizer_acquire_crash_state())
292       return;
293     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
294     Printf("       and the timeout value is %d (use -timeout=N to change)\n",
295            Options.UnitTimeoutSec);
296     DumpCurrentUnit("timeout-");
297     Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
298            Seconds);
299     PrintStackTrace();
300     Printf("SUMMARY: libFuzzer: timeout\n");
301     PrintFinalStats();
302     _Exit(Options.TimeoutExitCode); // Stop right now.
303   }
304 }
305 
306 void Fuzzer::RssLimitCallback() {
307   if (EF->__sanitizer_acquire_crash_state &&
308       !EF->__sanitizer_acquire_crash_state())
309     return;
310   Printf(
311       "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
312       GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
313   Printf("   To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
314   PrintMemoryProfile();
315   DumpCurrentUnit("oom-");
316   Printf("SUMMARY: libFuzzer: out-of-memory\n");
317   PrintFinalStats();
318   _Exit(Options.OOMExitCode); // Stop right now.
319 }
320 
321 void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
322   size_t ExecPerSec = execPerSec();
323   if (!Options.Verbosity)
324     return;
325   Printf("#%zd\t%s", TotalNumberOfRuns, Where);
326   if (size_t N = TPC.GetTotalPCCoverage())
327     Printf(" cov: %zd", N);
328   if (size_t N = Corpus.NumFeatures())
329     Printf(" ft: %zd", N);
330   if (!Corpus.empty()) {
331     Printf(" corp: %zd", Corpus.NumActiveUnits());
332     if (size_t N = Corpus.SizeInBytes()) {
333       if (N < (1 << 14))
334         Printf("/%zdb", N);
335       else if (N < (1 << 24))
336         Printf("/%zdKb", N >> 10);
337       else
338         Printf("/%zdMb", N >> 20);
339     }
340     if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
341       Printf(" focus: %zd", FF);
342   }
343   if (TmpMaxMutationLen)
344     Printf(" lim: %zd", TmpMaxMutationLen);
345   if (Units)
346     Printf(" units: %zd", Units);
347 
348   Printf(" exec/s: %zd", ExecPerSec);
349   Printf(" rss: %zdMb", GetPeakRSSMb());
350   Printf("%s", End);
351 }
352 
353 void Fuzzer::PrintFinalStats() {
354   if (Options.PrintCoverage)
355     TPC.PrintCoverage();
356   if (Options.PrintCorpusStats)
357     Corpus.PrintStats();
358   if (!Options.PrintFinalStats)
359     return;
360   size_t ExecPerSec = execPerSec();
361   Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
362   Printf("stat::average_exec_per_sec:     %zd\n", ExecPerSec);
363   Printf("stat::new_units_added:          %zd\n", NumberOfNewUnitsAdded);
364   Printf("stat::slowest_unit_time_sec:    %zd\n", TimeOfLongestUnitInSeconds);
365   Printf("stat::peak_rss_mb:              %zd\n", GetPeakRSSMb());
366 }
367 
368 void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
369   assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
370   assert(MaxInputLen);
371   this->MaxInputLen = MaxInputLen;
372   this->MaxMutationLen = MaxInputLen;
373   AllocateCurrentUnitData();
374   Printf("INFO: -max_len is not provided; "
375          "libFuzzer will not generate inputs larger than %zd bytes\n",
376          MaxInputLen);
377 }
378 
379 void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
380   assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
381   this->MaxMutationLen = MaxMutationLen;
382 }
383 
384 void Fuzzer::CheckExitOnSrcPosOrItem() {
385   if (!Options.ExitOnSrcPos.empty()) {
386     static auto *PCsSet = new Set<uintptr_t>;
387     auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
388       if (!PCsSet->insert(TE->PC).second)
389         return;
390       std::string Descr = DescribePC("%F %L", TE->PC + 1);
391       if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
392         Printf("INFO: found line matching '%s', exiting.\n",
393                Options.ExitOnSrcPos.c_str());
394         _Exit(0);
395       }
396     };
397     TPC.ForEachObservedPC(HandlePC);
398   }
399   if (!Options.ExitOnItem.empty()) {
400     if (Corpus.HasUnit(Options.ExitOnItem)) {
401       Printf("INFO: found item with checksum '%s', exiting.\n",
402              Options.ExitOnItem.c_str());
403       _Exit(0);
404     }
405   }
406 }
407 
408 void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
409   if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
410     return;
411   Vector<Unit> AdditionalCorpus;
412   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
413                          &EpochOfLastReadOfOutputCorpus, MaxSize,
414                          /*ExitOnError*/ false);
415   if (Options.Verbosity >= 2)
416     Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
417   bool Reloaded = false;
418   for (auto &U : AdditionalCorpus) {
419     if (U.size() > MaxSize)
420       U.resize(MaxSize);
421     if (!Corpus.HasUnit(U)) {
422       if (RunOne(U.data(), U.size())) {
423         CheckExitOnSrcPosOrItem();
424         Reloaded = true;
425       }
426     }
427   }
428   if (Reloaded)
429     PrintStats("RELOAD");
430 }
431 
432 void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
433   auto TimeOfUnit =
434       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
435   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
436       secondsSinceProcessStartUp() >= 2)
437     PrintStats("pulse ");
438   if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
439       TimeOfUnit >= Options.ReportSlowUnits) {
440     TimeOfLongestUnitInSeconds = TimeOfUnit;
441     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
442     WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
443   }
444 }
445 
446 bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
447                     InputInfo *II, bool *FoundUniqFeatures) {
448   if (!Size)
449     return false;
450 
451   ExecuteCallback(Data, Size);
452 
453   UniqFeatureSetTmp.clear();
454   size_t FoundUniqFeaturesOfII = 0;
455   size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
456   TPC.CollectFeatures([&](size_t Feature) {
457     if (Corpus.AddFeature(Feature, Size, Options.Shrink))
458       UniqFeatureSetTmp.push_back(Feature);
459     if (Options.ReduceInputs && II)
460       if (std::binary_search(II->UniqFeatureSet.begin(),
461                              II->UniqFeatureSet.end(), Feature))
462         FoundUniqFeaturesOfII++;
463   });
464   if (FoundUniqFeatures)
465     *FoundUniqFeatures = FoundUniqFeaturesOfII;
466   PrintPulseAndReportSlowInput(Data, Size);
467   size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
468   if (NumNewFeatures) {
469     TPC.UpdateObservedPCs();
470     Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
471                        TPC.ObservedFocusFunction(), UniqFeatureSetTmp, DFT, II);
472     return true;
473   }
474   if (II && FoundUniqFeaturesOfII &&
475       II->DataFlowTraceForFocusFunction.empty() &&
476       FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
477       II->U.size() > Size) {
478     Corpus.Replace(II, {Data, Data + Size});
479     return true;
480   }
481   return false;
482 }
483 
484 size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
485   assert(InFuzzingThread());
486   *Data = CurrentUnitData;
487   return CurrentUnitSize;
488 }
489 
490 void Fuzzer::CrashOnOverwrittenData() {
491   Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
492          GetPid());
493   DumpCurrentUnit("crash-");
494   Printf("SUMMARY: libFuzzer: out-of-memory\n");
495   _Exit(Options.ErrorExitCode); // Stop right now.
496 }
497 
498 // Compare two arrays, but not all bytes if the arrays are large.
499 static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
500   const size_t Limit = 64;
501   if (Size <= 64)
502     return !memcmp(A, B, Size);
503   // Compare first and last Limit/2 bytes.
504   return !memcmp(A, B, Limit / 2) &&
505          !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
506 }
507 
508 void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
509   TPC.RecordInitialStack();
510   TotalNumberOfRuns++;
511   assert(InFuzzingThread());
512   // We copy the contents of Unit into a separate heap buffer
513   // so that we reliably find buffer overflows in it.
514   uint8_t *DataCopy = new uint8_t[Size];
515   memcpy(DataCopy, Data, Size);
516   if (EF->__msan_unpoison)
517     EF->__msan_unpoison(DataCopy, Size);
518   if (CurrentUnitData && CurrentUnitData != Data)
519     memcpy(CurrentUnitData, Data, Size);
520   CurrentUnitSize = Size;
521   {
522     ScopedEnableMsanInterceptorChecks S;
523     AllocTracer.Start(Options.TraceMalloc);
524     UnitStartTime = system_clock::now();
525     TPC.ResetMaps();
526     RunningUserCallback = true;
527     int Res = CB(DataCopy, Size);
528     RunningUserCallback = false;
529     UnitStopTime = system_clock::now();
530     (void)Res;
531     assert(Res == 0);
532     HasMoreMallocsThanFrees = AllocTracer.Stop();
533   }
534   if (!LooseMemeq(DataCopy, Data, Size))
535     CrashOnOverwrittenData();
536   CurrentUnitSize = 0;
537   delete[] DataCopy;
538 }
539 
540 std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
541   if (Options.OnlyASCII)
542     assert(IsASCII(U));
543   if (Options.OutputCorpus.empty())
544     return "";
545   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
546   WriteToFile(U, Path);
547   if (Options.Verbosity >= 2)
548     Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
549   return Path;
550 }
551 
552 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
553   if (!Options.SaveArtifacts)
554     return;
555   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
556   if (!Options.ExactArtifactPath.empty())
557     Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
558   WriteToFile(U, Path);
559   Printf("artifact_prefix='%s'; Test unit written to %s\n",
560          Options.ArtifactPrefix.c_str(), Path.c_str());
561   if (U.size() <= kMaxUnitSizeToPrint)
562     Printf("Base64: %s\n", Base64(U).c_str());
563 }
564 
565 void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
566   if (!Options.PrintNEW)
567     return;
568   PrintStats(Text, "");
569   if (Options.Verbosity) {
570     Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
571     MD.PrintMutationSequence();
572     Printf("\n");
573   }
574 }
575 
576 void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
577   II->NumSuccessfullMutations++;
578   MD.RecordSuccessfulMutationSequence();
579   PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW   ");
580   WriteToOutputCorpus(U);
581   NumberOfNewUnitsAdded++;
582   CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
583   LastCorpusUpdateRun = TotalNumberOfRuns;
584 }
585 
586 // Tries detecting a memory leak on the particular input that we have just
587 // executed before calling this function.
588 void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
589                                      bool DuringInitialCorpusExecution) {
590   if (!HasMoreMallocsThanFrees)
591     return; // mallocs==frees, a leak is unlikely.
592   if (!Options.DetectLeaks)
593     return;
594   if (!DuringInitialCorpusExecution &&
595       TotalNumberOfRuns >= Options.MaxNumberOfRuns)
596     return;
597   if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
598       !(EF->__lsan_do_recoverable_leak_check))
599     return; // No lsan.
600   // Run the target once again, but with lsan disabled so that if there is
601   // a real leak we do not report it twice.
602   EF->__lsan_disable();
603   ExecuteCallback(Data, Size);
604   EF->__lsan_enable();
605   if (!HasMoreMallocsThanFrees)
606     return; // a leak is unlikely.
607   if (NumberOfLeakDetectionAttempts++ > 1000) {
608     Options.DetectLeaks = false;
609     Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
610            "      Most likely the target function accumulates allocated\n"
611            "      memory in a global state w/o actually leaking it.\n"
612            "      You may try running this binary with -trace_malloc=[12]"
613            "      to get a trace of mallocs and frees.\n"
614            "      If LeakSanitizer is enabled in this process it will still\n"
615            "      run on the process shutdown.\n");
616     return;
617   }
618   // Now perform the actual lsan pass. This is expensive and we must ensure
619   // we don't call it too often.
620   if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
621     if (DuringInitialCorpusExecution)
622       Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
623     Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
624     CurrentUnitSize = Size;
625     DumpCurrentUnit("leak-");
626     PrintFinalStats();
627     _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
628   }
629 }
630 
631 void Fuzzer::MutateAndTestOne() {
632   MD.StartMutationSequence();
633 
634   auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
635   if (Options.DoCrossOver)
636     MD.SetCrossOverWith(&Corpus.ChooseUnitToMutate(MD.GetRand()).U);
637   const auto &U = II.U;
638   memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
639   assert(CurrentUnitData);
640   size_t Size = U.size();
641   assert(Size <= MaxInputLen && "Oversized Unit");
642   memcpy(CurrentUnitData, U.data(), Size);
643 
644   assert(MaxMutationLen > 0);
645 
646   size_t CurrentMaxMutationLen =
647       Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
648   assert(CurrentMaxMutationLen > 0);
649 
650   for (int i = 0; i < Options.MutateDepth; i++) {
651     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
652       break;
653     MaybeExitGracefully();
654     size_t NewSize = 0;
655     if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
656         Size <= CurrentMaxMutationLen)
657       NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
658                                   II.DataFlowTraceForFocusFunction);
659     else
660       NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
661     assert(NewSize > 0 && "Mutator returned empty unit");
662     assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
663     Size = NewSize;
664     II.NumExecutedMutations++;
665 
666     bool FoundUniqFeatures = false;
667     bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
668                          &FoundUniqFeatures);
669     TryDetectingAMemoryLeak(CurrentUnitData, Size,
670                             /*DuringInitialCorpusExecution*/ false);
671     if (NewCov) {
672       ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
673       break;  // We will mutate this input more in the next rounds.
674     }
675     if (Options.ReduceDepth && !FoundUniqFeatures)
676         break;
677   }
678 }
679 
680 void Fuzzer::PurgeAllocator() {
681   if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
682     return;
683   if (duration_cast<seconds>(system_clock::now() -
684                              LastAllocatorPurgeAttemptTime)
685           .count() < Options.PurgeAllocatorIntervalSec)
686     return;
687 
688   if (Options.RssLimitMb <= 0 ||
689       GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
690     EF->__sanitizer_purge_allocator();
691 
692   LastAllocatorPurgeAttemptTime = system_clock::now();
693 }
694 
695 void Fuzzer::ReadAndExecuteSeedCorpora(
696     const Vector<std::string> &CorpusDirs,
697     const Vector<std::string> &ExtraSeedFiles) {
698   const size_t kMaxSaneLen = 1 << 20;
699   const size_t kMinDefaultLen = 4096;
700   Vector<SizedFile> SizedFiles;
701   size_t MaxSize = 0;
702   size_t MinSize = -1;
703   size_t TotalSize = 0;
704   size_t LastNumFiles = 0;
705   for (auto &Dir : CorpusDirs) {
706     GetSizedFilesFromDir(Dir, &SizedFiles);
707     Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
708            Dir.c_str());
709     LastNumFiles = SizedFiles.size();
710   }
711   // Add files from -seed_inputs.
712   for (auto &File : ExtraSeedFiles)
713     if (auto Size = FileSize(File))
714       SizedFiles.push_back({File, Size});
715 
716   for (auto &File : SizedFiles) {
717     MaxSize = Max(File.Size, MaxSize);
718     MinSize = Min(File.Size, MinSize);
719     TotalSize += File.Size;
720   }
721   if (Options.MaxLen == 0)
722     SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
723   assert(MaxInputLen > 0);
724 
725   // Test the callback with empty input and never try it again.
726   uint8_t dummy = 0;
727   ExecuteCallback(&dummy, 0);
728 
729   // Protect lazy counters here, after the once-init code has been executed.
730   if (Options.LazyCounters)
731     TPC.ProtectLazyCounters();
732 
733   if (SizedFiles.empty()) {
734     Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
735     Unit U({'\n'}); // Valid ASCII input.
736     RunOne(U.data(), U.size());
737   } else {
738     Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
739            " rss: %zdMb\n",
740            SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
741     if (Options.ShuffleAtStartUp)
742       std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
743 
744     if (Options.PreferSmall) {
745       std::stable_sort(SizedFiles.begin(), SizedFiles.end());
746       assert(SizedFiles.front().Size <= SizedFiles.back().Size);
747     }
748 
749     // Load and execute inputs one by one.
750     for (auto &SF : SizedFiles) {
751       auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
752       assert(U.size() <= MaxInputLen);
753       RunOne(U.data(), U.size());
754       CheckExitOnSrcPosOrItem();
755       TryDetectingAMemoryLeak(U.data(), U.size(),
756                               /*DuringInitialCorpusExecution*/ true);
757     }
758   }
759 
760   PrintStats("INITED");
761   if (!Options.FocusFunction.empty())
762     Printf("INFO: %zd/%zd inputs touch the focus function\n",
763            Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
764   if (!Options.DataFlowTrace.empty())
765     Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
766            Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
767 
768   if (Corpus.empty() && Options.MaxNumberOfRuns) {
769     Printf("ERROR: no interesting inputs were found. "
770            "Is the code instrumented for coverage? Exiting.\n");
771     exit(1);
772   }
773 }
774 
775 void Fuzzer::Loop(const Vector<std::string> &CorpusDirs,
776                   const Vector<std::string> &ExtraSeedFiles) {
777   ReadAndExecuteSeedCorpora(CorpusDirs, ExtraSeedFiles);
778   DFT.Clear();  // No need for DFT any more.
779   TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
780   TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
781   system_clock::time_point LastCorpusReload = system_clock::now();
782   while (true) {
783     auto Now = system_clock::now();
784     if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
785         Options.ReloadIntervalSec) {
786       RereadOutputCorpus(MaxInputLen);
787       LastCorpusReload = system_clock::now();
788     }
789     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
790       break;
791     if (TimedOut())
792       break;
793 
794     // Update TmpMaxMutationLen
795     if (Options.LenControl) {
796       if (TmpMaxMutationLen < MaxMutationLen &&
797           TotalNumberOfRuns - LastCorpusUpdateRun >
798               Options.LenControl * Log(TmpMaxMutationLen)) {
799         TmpMaxMutationLen =
800             Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
801         LastCorpusUpdateRun = TotalNumberOfRuns;
802       }
803     } else {
804       TmpMaxMutationLen = MaxMutationLen;
805     }
806 
807     // Perform several mutations and runs.
808     MutateAndTestOne();
809 
810     PurgeAllocator();
811   }
812 
813   PrintStats("DONE  ", "\n");
814   MD.PrintRecommendedDictionary();
815 }
816 
817 void Fuzzer::MinimizeCrashLoop(const Unit &U) {
818   if (U.size() <= 1)
819     return;
820   while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
821     MD.StartMutationSequence();
822     memcpy(CurrentUnitData, U.data(), U.size());
823     for (int i = 0; i < Options.MutateDepth; i++) {
824       size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
825       assert(NewSize > 0 && NewSize <= MaxMutationLen);
826       ExecuteCallback(CurrentUnitData, NewSize);
827       PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
828       TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
829                               /*DuringInitialCorpusExecution*/ false);
830     }
831   }
832 }
833 
834 } // namespace fuzzer
835 
836 extern "C" {
837 
838 ATTRIBUTE_INTERFACE size_t
839 LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
840   assert(fuzzer::F);
841   return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
842 }
843 
844 } // extern "C"
845