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