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