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