1 //===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // Fuzzer's main loop.
10 //===----------------------------------------------------------------------===//
11 
12 #include "FuzzerCorpus.h"
13 #include "FuzzerIO.h"
14 #include "FuzzerInternal.h"
15 #include "FuzzerMutate.h"
16 #include "FuzzerRandom.h"
17 #include "FuzzerShmem.h"
18 #include "FuzzerTracePC.h"
19 #include <algorithm>
20 #include <cstring>
21 #include <memory>
22 #include <mutex>
23 #include <set>
24 
25 #if defined(__has_include)
26 #if __has_include(<sanitizer / lsan_interface.h>)
27 #include <sanitizer/lsan_interface.h>
28 #endif
29 #endif
30 
31 #define NO_SANITIZE_MEMORY
32 #if defined(__has_feature)
33 #if __has_feature(memory_sanitizer)
34 #undef NO_SANITIZE_MEMORY
35 #define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
36 #endif
37 #endif
38 
39 namespace fuzzer {
40 static const size_t kMaxUnitSizeToPrint = 256;
41 
42 thread_local bool Fuzzer::IsMyThread;
43 
44 SharedMemoryRegion SMR;
45 
46 // Only one Fuzzer per process.
47 static Fuzzer *F;
48 
49 // Leak detection is expensive, so we first check if there were more mallocs
50 // than frees (using the sanitizer malloc hooks) and only then try to call lsan.
51 struct MallocFreeTracer {
52   void Start(int TraceLevel) {
53     this->TraceLevel = TraceLevel;
54     if (TraceLevel)
55       Printf("MallocFreeTracer: START\n");
56     Mallocs = 0;
57     Frees = 0;
58   }
59   // Returns true if there were more mallocs than frees.
60   bool Stop() {
61     if (TraceLevel)
62       Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
63              Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
64     bool Result = Mallocs > Frees;
65     Mallocs = 0;
66     Frees = 0;
67     TraceLevel = 0;
68     return Result;
69   }
70   std::atomic<size_t> Mallocs;
71   std::atomic<size_t> Frees;
72   int TraceLevel = 0;
73 
74   std::recursive_mutex TraceMutex;
75   bool TraceDisabled = false;
76 };
77 
78 static MallocFreeTracer AllocTracer;
79 
80 // Locks printing and avoids nested hooks triggered from mallocs/frees in
81 // sanitizer.
82 class TraceLock {
83 public:
84   TraceLock() : Lock(AllocTracer.TraceMutex) {
85     AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
86   }
87   ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
88 
89   bool IsDisabled() const {
90     // This is already inverted value.
91     return !AllocTracer.TraceDisabled;
92   }
93 
94 private:
95   std::lock_guard<std::recursive_mutex> Lock;
96 };
97 
98 ATTRIBUTE_NO_SANITIZE_MEMORY
99 void MallocHook(const volatile void *ptr, size_t size) {
100   size_t N = AllocTracer.Mallocs++;
101   F->HandleMalloc(size);
102   if (int TraceLevel = AllocTracer.TraceLevel) {
103     TraceLock Lock;
104     if (Lock.IsDisabled())
105       return;
106     Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
107     if (TraceLevel >= 2 && EF)
108       PrintStackTrace();
109   }
110 }
111 
112 ATTRIBUTE_NO_SANITIZE_MEMORY
113 void FreeHook(const volatile void *ptr) {
114   size_t N = AllocTracer.Frees++;
115   if (int TraceLevel = AllocTracer.TraceLevel) {
116     TraceLock Lock;
117     if (Lock.IsDisabled())
118       return;
119     Printf("FREE[%zd]   %p\n", N, ptr);
120     if (TraceLevel >= 2 && EF)
121       PrintStackTrace();
122   }
123 }
124 
125 // Crash on a single malloc that exceeds the rss limit.
126 void Fuzzer::HandleMalloc(size_t Size) {
127   if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
128     return;
129   Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
130          Size);
131   Printf("   To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
132   PrintStackTrace();
133   DumpCurrentUnit("oom-");
134   Printf("SUMMARY: libFuzzer: out-of-memory\n");
135   PrintFinalStats();
136   _Exit(Options.ErrorExitCode); // Stop right now.
137 }
138 
139 Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
140                FuzzingOptions Options)
141     : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
142   if (EF->__sanitizer_set_death_callback)
143     EF->__sanitizer_set_death_callback(StaticDeathCallback);
144   assert(!F);
145   F = this;
146   TPC.ResetMaps();
147   IsMyThread = true;
148   if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
149     EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
150   TPC.SetUseCounters(Options.UseCounters);
151   TPC.SetUseValueProfile(Options.UseValueProfile);
152 
153   if (Options.Verbosity)
154     TPC.PrintModuleInfo();
155   if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
156     EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
157   MaxInputLen = MaxMutationLen = Options.MaxLen;
158   TmpMaxMutationLen = Max(size_t(4), Corpus.MaxInputSize());
159   AllocateCurrentUnitData();
160   CurrentUnitSize = 0;
161   memset(BaseSha1, 0, sizeof(BaseSha1));
162   TPC.SetFocusFunction(Options.FocusFunction);
163   DFT.Init(Options.DataFlowTrace, Options.FocusFunction);
164 }
165 
166 Fuzzer::~Fuzzer() {}
167 
168 void Fuzzer::AllocateCurrentUnitData() {
169   if (CurrentUnitData || MaxInputLen == 0)
170     return;
171   CurrentUnitData = new uint8_t[MaxInputLen];
172 }
173 
174 void Fuzzer::StaticDeathCallback() {
175   assert(F);
176   F->DeathCallback();
177 }
178 
179 void Fuzzer::DumpCurrentUnit(const char *Prefix) {
180   if (!CurrentUnitData)
181     return; // Happens when running individual inputs.
182   MD.PrintMutationSequence();
183   Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
184   size_t UnitSize = CurrentUnitSize;
185   if (UnitSize <= kMaxUnitSizeToPrint) {
186     PrintHexArray(CurrentUnitData, UnitSize, "\n");
187     PrintASCII(CurrentUnitData, UnitSize, "\n");
188   }
189   WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
190                             Prefix);
191 }
192 
193 NO_SANITIZE_MEMORY
194 void Fuzzer::DeathCallback() {
195   DumpCurrentUnit("crash-");
196   PrintFinalStats();
197 }
198 
199 void Fuzzer::StaticAlarmCallback() {
200   assert(F);
201   F->AlarmCallback();
202 }
203 
204 void Fuzzer::StaticCrashSignalCallback() {
205   assert(F);
206   F->CrashCallback();
207 }
208 
209 void Fuzzer::StaticExitCallback() {
210   assert(F);
211   F->ExitCallback();
212 }
213 
214 void Fuzzer::StaticInterruptCallback() {
215   assert(F);
216   F->InterruptCallback();
217 }
218 
219 void Fuzzer::StaticGracefulExitCallback() {
220   assert(F);
221   F->GracefulExitRequested = true;
222   Printf("INFO: signal received, trying to exit gracefully\n");
223 }
224 
225 void Fuzzer::StaticFileSizeExceedCallback() {
226   Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
227   exit(1);
228 }
229 
230 void Fuzzer::CrashCallback() {
231   if (EF->__sanitizer_acquire_crash_state)
232     EF->__sanitizer_acquire_crash_state();
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 (!RunningCB)
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 #if !LIBFUZZER_WINDOWS
276   if (!InFuzzingThread())
277     return;
278 #endif
279   if (!RunningCB)
280     return; // We have not started running units yet.
281   size_t Seconds =
282       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
283   if (Seconds == 0)
284     return;
285   if (Options.Verbosity >= 2)
286     Printf("AlarmCallback %zd\n", Seconds);
287   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
288     if (EF->__sanitizer_acquire_crash_state &&
289         !EF->__sanitizer_acquire_crash_state())
290       return;
291     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
292     Printf("       and the timeout value is %d (use -timeout=N to change)\n",
293            Options.UnitTimeoutSec);
294     DumpCurrentUnit("timeout-");
295     Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
296            Seconds);
297     PrintStackTrace();
298     Printf("SUMMARY: libFuzzer: timeout\n");
299     PrintFinalStats();
300     _Exit(Options.TimeoutExitCode); // Stop right now.
301   }
302 }
303 
304 void Fuzzer::RssLimitCallback() {
305   if (EF->__sanitizer_acquire_crash_state &&
306       !EF->__sanitizer_acquire_crash_state())
307     return;
308   Printf(
309       "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
310       GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
311   Printf("   To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
312   PrintMemoryProfile();
313   DumpCurrentUnit("oom-");
314   Printf("SUMMARY: libFuzzer: out-of-memory\n");
315   PrintFinalStats();
316   _Exit(Options.ErrorExitCode); // Stop right now.
317 }
318 
319 void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
320   size_t ExecPerSec = execPerSec();
321   if (!Options.Verbosity)
322     return;
323   Printf("#%zd\t%s", TotalNumberOfRuns, Where);
324   if (size_t N = TPC.GetTotalPCCoverage())
325     Printf(" cov: %zd", N);
326   if (size_t N = Corpus.NumFeatures())
327     Printf(" ft: %zd", N);
328   if (!Corpus.empty()) {
329     Printf(" corp: %zd", Corpus.NumActiveUnits());
330     if (size_t N = Corpus.SizeInBytes()) {
331       if (N < (1 << 14))
332         Printf("/%zdb", N);
333       else if (N < (1 << 24))
334         Printf("/%zdKb", N >> 10);
335       else
336         Printf("/%zdMb", N >> 20);
337     }
338     if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
339       Printf(" focus: %zd", FF);
340   }
341   if (TmpMaxMutationLen)
342     Printf(" lim: %zd", TmpMaxMutationLen);
343   if (Units)
344     Printf(" units: %zd", Units);
345 
346   Printf(" exec/s: %zd", ExecPerSec);
347   Printf(" rss: %zdMb", GetPeakRSSMb());
348   Printf("%s", End);
349 }
350 
351 void Fuzzer::PrintFinalStats() {
352   if (Options.PrintCoverage)
353     TPC.PrintCoverage();
354   if (Options.DumpCoverage)
355     TPC.DumpCoverage();
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 = [&](uintptr_t PC) {
388       if (!PCsSet->insert(PC).second)
389         return;
390       std::string Descr = DescribePC("%F %L", 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(),
472                        UniqFeatureSetTmp, DFT);
473     return true;
474   }
475   if (II && FoundUniqFeaturesOfII &&
476       II->DataFlowTraceForFocusFunction.empty() &&
477       FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
478       II->U.size() > Size) {
479     Corpus.Replace(II, {Data, Data + Size});
480     return true;
481   }
482   return false;
483 }
484 
485 size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
486   assert(InFuzzingThread());
487   *Data = CurrentUnitData;
488   return CurrentUnitSize;
489 }
490 
491 void Fuzzer::CrashOnOverwrittenData() {
492   Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
493          GetPid());
494   DumpCurrentUnit("crash-");
495   Printf("SUMMARY: libFuzzer: out-of-memory\n");
496   _Exit(Options.ErrorExitCode); // Stop right now.
497 }
498 
499 // Compare two arrays, but not all bytes if the arrays are large.
500 static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
501   const size_t Limit = 64;
502   if (Size <= 64)
503     return !memcmp(A, B, Size);
504   // Compare first and last Limit/2 bytes.
505   return !memcmp(A, B, Limit / 2) &&
506          !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
507 }
508 
509 void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
510   TPC.RecordInitialStack();
511   TotalNumberOfRuns++;
512   assert(InFuzzingThread());
513   if (SMR.IsClient())
514     SMR.WriteByteArray(Data, Size);
515   // We copy the contents of Unit into a separate heap buffer
516   // so that we reliably find buffer overflows in it.
517   uint8_t *DataCopy = new uint8_t[Size];
518   memcpy(DataCopy, Data, Size);
519   if (CurrentUnitData && CurrentUnitData != Data)
520     memcpy(CurrentUnitData, Data, Size);
521   CurrentUnitSize = Size;
522   AllocTracer.Start(Options.TraceMalloc);
523   UnitStartTime = system_clock::now();
524   TPC.ResetMaps();
525   RunningCB = true;
526   int Res = CB(DataCopy, Size);
527   RunningCB = false;
528   UnitStopTime = system_clock::now();
529   (void)Res;
530   assert(Res == 0);
531   HasMoreMallocsThanFrees = AllocTracer.Stop();
532   if (!LooseMemeq(DataCopy, Data, Size))
533     CrashOnOverwrittenData();
534   CurrentUnitSize = 0;
535   delete[] DataCopy;
536 }
537 
538 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
539   if (Options.OnlyASCII)
540     assert(IsASCII(U));
541   if (Options.OutputCorpus.empty())
542     return;
543   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
544   WriteToFile(U, Path);
545   if (Options.Verbosity >= 2)
546     Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
547 }
548 
549 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
550   if (!Options.SaveArtifacts)
551     return;
552   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
553   if (!Options.ExactArtifactPath.empty())
554     Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
555   WriteToFile(U, Path);
556   Printf("artifact_prefix='%s'; Test unit written to %s\n",
557          Options.ArtifactPrefix.c_str(), Path.c_str());
558   if (U.size() <= kMaxUnitSizeToPrint)
559     Printf("Base64: %s\n", Base64(U).c_str());
560 }
561 
562 void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
563   if (!Options.PrintNEW)
564     return;
565   PrintStats(Text, "");
566   if (Options.Verbosity) {
567     Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
568     MD.PrintMutationSequence();
569     Printf("\n");
570   }
571 }
572 
573 void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
574   II->NumSuccessfullMutations++;
575   MD.RecordSuccessfulMutationSequence();
576   PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW   ");
577   WriteToOutputCorpus(U);
578   NumberOfNewUnitsAdded++;
579   CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
580   LastCorpusUpdateRun = TotalNumberOfRuns;
581 }
582 
583 // Tries detecting a memory leak on the particular input that we have just
584 // executed before calling this function.
585 void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
586                                      bool DuringInitialCorpusExecution) {
587   if (!HasMoreMallocsThanFrees)
588     return; // mallocs==frees, a leak is unlikely.
589   if (!Options.DetectLeaks)
590     return;
591   if (!DuringInitialCorpusExecution &&
592       TotalNumberOfRuns >= Options.MaxNumberOfRuns)
593     return;
594   if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
595       !(EF->__lsan_do_recoverable_leak_check))
596     return; // No lsan.
597   // Run the target once again, but with lsan disabled so that if there is
598   // a real leak we do not report it twice.
599   EF->__lsan_disable();
600   ExecuteCallback(Data, Size);
601   EF->__lsan_enable();
602   if (!HasMoreMallocsThanFrees)
603     return; // a leak is unlikely.
604   if (NumberOfLeakDetectionAttempts++ > 1000) {
605     Options.DetectLeaks = false;
606     Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
607            "      Most likely the target function accumulates allocated\n"
608            "      memory in a global state w/o actually leaking it.\n"
609            "      You may try running this binary with -trace_malloc=[12]"
610            "      to get a trace of mallocs and frees.\n"
611            "      If LeakSanitizer is enabled in this process it will still\n"
612            "      run on the process shutdown.\n");
613     return;
614   }
615   // Now perform the actual lsan pass. This is expensive and we must ensure
616   // we don't call it too often.
617   if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
618     if (DuringInitialCorpusExecution)
619       Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
620     Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
621     CurrentUnitSize = Size;
622     DumpCurrentUnit("leak-");
623     PrintFinalStats();
624     _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
625   }
626 }
627 
628 void Fuzzer::MutateAndTestOne() {
629   MD.StartMutationSequence();
630 
631   auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
632   const auto &U = II.U;
633   memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
634   assert(CurrentUnitData);
635   size_t Size = U.size();
636   assert(Size <= MaxInputLen && "Oversized Unit");
637   memcpy(CurrentUnitData, U.data(), Size);
638 
639   assert(MaxMutationLen > 0);
640 
641   size_t CurrentMaxMutationLen =
642       Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
643   assert(CurrentMaxMutationLen > 0);
644 
645   for (int i = 0; i < Options.MutateDepth; i++) {
646     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
647       break;
648     MaybeExitGracefully();
649     size_t NewSize = 0;
650     NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
651     assert(NewSize > 0 && "Mutator returned empty unit");
652     assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
653     Size = NewSize;
654     II.NumExecutedMutations++;
655 
656     bool FoundUniqFeatures = false;
657     bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
658                          &FoundUniqFeatures);
659     TryDetectingAMemoryLeak(CurrentUnitData, Size,
660                             /*DuringInitialCorpusExecution*/ false);
661     if (NewCov) {
662       ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
663       break;  // We will mutate this input more in the next rounds.
664     }
665     if (Options.ReduceDepth && !FoundUniqFeatures)
666         break;
667   }
668 }
669 
670 void Fuzzer::PurgeAllocator() {
671   if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
672     return;
673   if (duration_cast<seconds>(system_clock::now() -
674                              LastAllocatorPurgeAttemptTime)
675           .count() < Options.PurgeAllocatorIntervalSec)
676     return;
677 
678   if (Options.RssLimitMb <= 0 ||
679       GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
680     EF->__sanitizer_purge_allocator();
681 
682   LastAllocatorPurgeAttemptTime = system_clock::now();
683 }
684 
685 void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
686   const size_t kMaxSaneLen = 1 << 20;
687   const size_t kMinDefaultLen = 4096;
688   Vector<SizedFile> SizedFiles;
689   size_t MaxSize = 0;
690   size_t MinSize = -1;
691   size_t TotalSize = 0;
692   size_t LastNumFiles = 0;
693   for (auto &Dir : CorpusDirs) {
694     GetSizedFilesFromDir(Dir, &SizedFiles);
695     Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
696            Dir.c_str());
697     LastNumFiles = SizedFiles.size();
698   }
699   for (auto &File : SizedFiles) {
700     MaxSize = Max(File.Size, MaxSize);
701     MinSize = Min(File.Size, MinSize);
702     TotalSize += File.Size;
703   }
704   if (Options.MaxLen == 0)
705     SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
706   assert(MaxInputLen > 0);
707 
708   // Test the callback with empty input and never try it again.
709   uint8_t dummy = 0;
710   ExecuteCallback(&dummy, 0);
711 
712   if (SizedFiles.empty()) {
713     Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
714     Unit U({'\n'}); // Valid ASCII input.
715     RunOne(U.data(), U.size());
716   } else {
717     Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
718            " rss: %zdMb\n",
719            SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
720     if (Options.ShuffleAtStartUp)
721       std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
722 
723     if (Options.PreferSmall) {
724       std::stable_sort(SizedFiles.begin(), SizedFiles.end());
725       assert(SizedFiles.front().Size <= SizedFiles.back().Size);
726     }
727 
728     // Load and execute inputs one by one.
729     for (auto &SF : SizedFiles) {
730       auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
731       assert(U.size() <= MaxInputLen);
732       RunOne(U.data(), U.size());
733       CheckExitOnSrcPosOrItem();
734       TryDetectingAMemoryLeak(U.data(), U.size(),
735                               /*DuringInitialCorpusExecution*/ true);
736     }
737   }
738 
739   PrintStats("INITED");
740   if (!Options.FocusFunction.empty())
741     Printf("INFO: %zd/%zd inputs touch the focus function\n",
742            Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
743   if (!Options.DataFlowTrace.empty())
744     Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
745            Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
746 
747   if (Corpus.empty() && Options.MaxNumberOfRuns) {
748     Printf("ERROR: no interesting inputs were found. "
749            "Is the code instrumented for coverage? Exiting.\n");
750     exit(1);
751   }
752 }
753 
754 void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
755   ReadAndExecuteSeedCorpora(CorpusDirs);
756   DFT.Clear();  // No need for DFT any more.
757   TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
758   TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
759   system_clock::time_point LastCorpusReload = system_clock::now();
760   if (Options.DoCrossOver)
761     MD.SetCorpus(&Corpus);
762   while (true) {
763     auto Now = system_clock::now();
764     if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
765         Options.ReloadIntervalSec) {
766       RereadOutputCorpus(MaxInputLen);
767       LastCorpusReload = system_clock::now();
768     }
769     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
770       break;
771     if (TimedOut())
772       break;
773 
774     // Update TmpMaxMutationLen
775     if (Options.LenControl) {
776       if (TmpMaxMutationLen < MaxMutationLen &&
777           TotalNumberOfRuns - LastCorpusUpdateRun >
778               Options.LenControl * Log(TmpMaxMutationLen)) {
779         TmpMaxMutationLen =
780             Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
781         LastCorpusUpdateRun = TotalNumberOfRuns;
782       }
783     } else {
784       TmpMaxMutationLen = MaxMutationLen;
785     }
786 
787     // Perform several mutations and runs.
788     MutateAndTestOne();
789 
790     PurgeAllocator();
791   }
792 
793   PrintStats("DONE  ", "\n");
794   MD.PrintRecommendedDictionary();
795 }
796 
797 void Fuzzer::MinimizeCrashLoop(const Unit &U) {
798   if (U.size() <= 1)
799     return;
800   while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
801     MD.StartMutationSequence();
802     memcpy(CurrentUnitData, U.data(), U.size());
803     for (int i = 0; i < Options.MutateDepth; i++) {
804       size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
805       assert(NewSize > 0 && NewSize <= MaxMutationLen);
806       ExecuteCallback(CurrentUnitData, NewSize);
807       PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
808       TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
809                               /*DuringInitialCorpusExecution*/ false);
810     }
811   }
812 }
813 
814 void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
815   if (SMR.IsServer()) {
816     SMR.WriteByteArray(Data, Size);
817   } else if (SMR.IsClient()) {
818     SMR.PostClient();
819     SMR.WaitServer();
820     size_t OtherSize = SMR.ReadByteArraySize();
821     uint8_t *OtherData = SMR.GetByteArray();
822     if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
823       size_t i = 0;
824       for (i = 0; i < Min(Size, OtherSize); i++)
825         if (Data[i] != OtherData[i])
826           break;
827       Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
828              "offset %zd\n",
829              GetPid(), Size, OtherSize, i);
830       DumpCurrentUnit("mismatch-");
831       Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
832       PrintFinalStats();
833       _Exit(Options.ErrorExitCode);
834     }
835   }
836 }
837 
838 } // namespace fuzzer
839 
840 extern "C" {
841 
842 __attribute__((visibility("default"))) size_t
843 LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
844   assert(fuzzer::F);
845   return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
846 }
847 
848 // Experimental
849 __attribute__((visibility("default"))) void
850 LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
851   assert(fuzzer::F);
852   fuzzer::F->AnnounceOutput(Data, Size);
853 }
854 } // extern "C"
855