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