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