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