1 //===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 // Fuzzer's main loop.
9 //===----------------------------------------------------------------------===//
10 
11 #include "FuzzerCorpus.h"
12 #include "FuzzerIO.h"
13 #include "FuzzerInternal.h"
14 #include "FuzzerMutate.h"
15 #include "FuzzerRandom.h"
16 #include "FuzzerTracePC.h"
17 #include <algorithm>
18 #include <cstring>
19 #include <memory>
20 #include <mutex>
21 #include <set>
22 
23 #if defined(__has_include)
24 #if __has_include(<sanitizer / lsan_interface.h>)
25 #include <sanitizer/lsan_interface.h>
26 #endif
27 #endif
28 
29 #define NO_SANITIZE_MEMORY
30 #if defined(__has_feature)
31 #if __has_feature(memory_sanitizer)
32 #undef NO_SANITIZE_MEMORY
33 #define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
34 #endif
35 #endif
36 
37 namespace fuzzer {
38 static const size_t kMaxUnitSizeToPrint = 256;
39 
40 thread_local bool Fuzzer::IsMyThread;
41 
42 bool RunningUserCallback = false;
43 
44 // Only one Fuzzer per process.
45 static Fuzzer *F;
46 
47 // Leak detection is expensive, so we first check if there were more mallocs
48 // than frees (using the sanitizer malloc hooks) and only then try to call lsan.
49 struct MallocFreeTracer {
50   void Start(int TraceLevel) {
51     this->TraceLevel = TraceLevel;
52     if (TraceLevel)
53       Printf("MallocFreeTracer: START\n");
54     Mallocs = 0;
55     Frees = 0;
56   }
57   // Returns true if there were more mallocs than frees.
58   bool Stop() {
59     if (TraceLevel)
60       Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
61              Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
62     bool Result = Mallocs > Frees;
63     Mallocs = 0;
64     Frees = 0;
65     TraceLevel = 0;
66     return Result;
67   }
68   std::atomic<size_t> Mallocs;
69   std::atomic<size_t> Frees;
70   int TraceLevel = 0;
71 
72   std::recursive_mutex TraceMutex;
73   bool TraceDisabled = false;
74 };
75 
76 static MallocFreeTracer AllocTracer;
77 
78 // Locks printing and avoids nested hooks triggered from mallocs/frees in
79 // sanitizer.
80 class TraceLock {
81 public:
82   TraceLock() : Lock(AllocTracer.TraceMutex) {
83     AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
84   }
85   ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
86 
87   bool IsDisabled() const {
88     // This is already inverted value.
89     return !AllocTracer.TraceDisabled;
90   }
91 
92 private:
93   std::lock_guard<std::recursive_mutex> Lock;
94 };
95 
96 ATTRIBUTE_NO_SANITIZE_MEMORY
97 void MallocHook(const volatile void *ptr, size_t size) {
98   size_t N = AllocTracer.Mallocs++;
99   F->HandleMalloc(size);
100   if (int TraceLevel = AllocTracer.TraceLevel) {
101     TraceLock Lock;
102     if (Lock.IsDisabled())
103       return;
104     Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
105     if (TraceLevel >= 2 && EF)
106       PrintStackTrace();
107   }
108 }
109 
110 ATTRIBUTE_NO_SANITIZE_MEMORY
111 void FreeHook(const volatile void *ptr) {
112   size_t N = AllocTracer.Frees++;
113   if (int TraceLevel = AllocTracer.TraceLevel) {
114     TraceLock Lock;
115     if (Lock.IsDisabled())
116       return;
117     Printf("FREE[%zd]   %p\n", N, ptr);
118     if (TraceLevel >= 2 && EF)
119       PrintStackTrace();
120   }
121 }
122 
123 // Crash on a single malloc that exceeds the rss limit.
124 void Fuzzer::HandleMalloc(size_t Size) {
125   if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
126     return;
127   Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
128          Size);
129   Printf("   To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
130   PrintStackTrace();
131   DumpCurrentUnit("oom-");
132   Printf("SUMMARY: libFuzzer: out-of-memory\n");
133   PrintFinalStats();
134   _Exit(Options.OOMExitCode); // Stop right now.
135 }
136 
137 Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
138                FuzzingOptions Options)
139     : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
140   if (EF->__sanitizer_set_death_callback)
141     EF->__sanitizer_set_death_callback(StaticDeathCallback);
142   assert(!F);
143   F = this;
144   TPC.ResetMaps();
145   IsMyThread = true;
146   if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
147     EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
148   TPC.SetUseCounters(Options.UseCounters);
149   TPC.SetUseValueProfileMask(Options.UseValueProfile);
150 
151   if (Options.Verbosity)
152     TPC.PrintModuleInfo();
153   if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
154     EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
155   MaxInputLen = MaxMutationLen = Options.MaxLen;
156   TmpMaxMutationLen = 0;  // Will be set once we load the corpus.
157   AllocateCurrentUnitData();
158   CurrentUnitSize = 0;
159   memset(BaseSha1, 0, sizeof(BaseSha1));
160   TPC.SetFocusFunction(Options.FocusFunction);
161   DFT.Init(Options.DataFlowTrace, Options.FocusFunction);
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   ScopedDisableMsanInterceptorChecks S;
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     return;
233   Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
234   PrintStackTrace();
235   Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
236          "      Combine libFuzzer with AddressSanitizer or similar for better "
237          "crash reports.\n");
238   Printf("SUMMARY: libFuzzer: deadly signal\n");
239   DumpCurrentUnit("crash-");
240   PrintFinalStats();
241   _Exit(Options.ErrorExitCode); // Stop right now.
242 }
243 
244 void Fuzzer::ExitCallback() {
245   if (!RunningUserCallback)
246     return; // This exit did not come from the user callback
247   if (EF->__sanitizer_acquire_crash_state &&
248       !EF->__sanitizer_acquire_crash_state())
249     return;
250   Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
251   PrintStackTrace();
252   Printf("SUMMARY: libFuzzer: fuzz target exited\n");
253   DumpCurrentUnit("crash-");
254   PrintFinalStats();
255   _Exit(Options.ErrorExitCode);
256 }
257 
258 void Fuzzer::MaybeExitGracefully() {
259   if (!F->GracefulExitRequested) return;
260   Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
261   RmDirRecursive(TempPath(".dir"));
262   F->PrintFinalStats();
263   _Exit(0);
264 }
265 
266 void Fuzzer::InterruptCallback() {
267   Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
268   PrintFinalStats();
269   RmDirRecursive(TempPath(".dir"));
270   // Stop right now, don't perform any at-exit actions.
271   _Exit(Options.InterruptExitCode);
272 }
273 
274 NO_SANITIZE_MEMORY
275 void Fuzzer::AlarmCallback() {
276   assert(Options.UnitTimeoutSec > 0);
277   // In Windows Alarm callback is executed by a different thread.
278   // NetBSD's current behavior needs this change too.
279 #if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD
280   if (!InFuzzingThread())
281     return;
282 #endif
283   if (!RunningUserCallback)
284     return; // We have not started running units yet.
285   size_t Seconds =
286       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
287   if (Seconds == 0)
288     return;
289   if (Options.Verbosity >= 2)
290     Printf("AlarmCallback %zd\n", Seconds);
291   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
292     if (EF->__sanitizer_acquire_crash_state &&
293         !EF->__sanitizer_acquire_crash_state())
294       return;
295     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
296     Printf("       and the timeout value is %d (use -timeout=N to change)\n",
297            Options.UnitTimeoutSec);
298     DumpCurrentUnit("timeout-");
299     Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
300            Seconds);
301     PrintStackTrace();
302     Printf("SUMMARY: libFuzzer: timeout\n");
303     PrintFinalStats();
304     _Exit(Options.TimeoutExitCode); // Stop right now.
305   }
306 }
307 
308 void Fuzzer::RssLimitCallback() {
309   if (EF->__sanitizer_acquire_crash_state &&
310       !EF->__sanitizer_acquire_crash_state())
311     return;
312   Printf(
313       "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
314       GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
315   Printf("   To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
316   PrintMemoryProfile();
317   DumpCurrentUnit("oom-");
318   Printf("SUMMARY: libFuzzer: out-of-memory\n");
319   PrintFinalStats();
320   _Exit(Options.OOMExitCode); // Stop right now.
321 }
322 
323 void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
324   size_t ExecPerSec = execPerSec();
325   if (!Options.Verbosity)
326     return;
327   Printf("#%zd\t%s", TotalNumberOfRuns, Where);
328   if (size_t N = TPC.GetTotalPCCoverage())
329     Printf(" cov: %zd", N);
330   if (size_t N = Corpus.NumFeatures())
331     Printf(" ft: %zd", N);
332   if (!Corpus.empty()) {
333     Printf(" corp: %zd", Corpus.NumActiveUnits());
334     if (size_t N = Corpus.SizeInBytes()) {
335       if (N < (1 << 14))
336         Printf("/%zdb", N);
337       else if (N < (1 << 24))
338         Printf("/%zdKb", N >> 10);
339       else
340         Printf("/%zdMb", N >> 20);
341     }
342     if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
343       Printf(" focus: %zd", FF);
344   }
345   if (TmpMaxMutationLen)
346     Printf(" lim: %zd", TmpMaxMutationLen);
347   if (Units)
348     Printf(" units: %zd", Units);
349 
350   Printf(" exec/s: %zd", ExecPerSec);
351   Printf(" rss: %zdMb", GetPeakRSSMb());
352   Printf("%s", End);
353 }
354 
355 void Fuzzer::PrintFinalStats() {
356   if (Options.PrintCoverage)
357     TPC.PrintCoverage();
358   if (Options.PrintCorpusStats)
359     Corpus.PrintStats();
360   if (!Options.PrintFinalStats)
361     return;
362   size_t ExecPerSec = execPerSec();
363   Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
364   Printf("stat::average_exec_per_sec:     %zd\n", ExecPerSec);
365   Printf("stat::new_units_added:          %zd\n", NumberOfNewUnitsAdded);
366   Printf("stat::slowest_unit_time_sec:    %zd\n", TimeOfLongestUnitInSeconds);
367   Printf("stat::peak_rss_mb:              %zd\n", GetPeakRSSMb());
368 }
369 
370 void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
371   assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
372   assert(MaxInputLen);
373   this->MaxInputLen = MaxInputLen;
374   this->MaxMutationLen = MaxInputLen;
375   AllocateCurrentUnitData();
376   Printf("INFO: -max_len is not provided; "
377          "libFuzzer will not generate inputs larger than %zd bytes\n",
378          MaxInputLen);
379 }
380 
381 void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
382   assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
383   this->MaxMutationLen = MaxMutationLen;
384 }
385 
386 void Fuzzer::CheckExitOnSrcPosOrItem() {
387   if (!Options.ExitOnSrcPos.empty()) {
388     static auto *PCsSet = new Set<uintptr_t>;
389     auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
390       if (!PCsSet->insert(TE->PC).second)
391         return;
392       std::string Descr = DescribePC("%F %L", TE->PC + 1);
393       if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
394         Printf("INFO: found line matching '%s', exiting.\n",
395                Options.ExitOnSrcPos.c_str());
396         _Exit(0);
397       }
398     };
399     TPC.ForEachObservedPC(HandlePC);
400   }
401   if (!Options.ExitOnItem.empty()) {
402     if (Corpus.HasUnit(Options.ExitOnItem)) {
403       Printf("INFO: found item with checksum '%s', exiting.\n",
404              Options.ExitOnItem.c_str());
405       _Exit(0);
406     }
407   }
408 }
409 
410 void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
411   if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
412     return;
413   Vector<Unit> AdditionalCorpus;
414   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
415                          &EpochOfLastReadOfOutputCorpus, MaxSize,
416                          /*ExitOnError*/ false);
417   if (Options.Verbosity >= 2)
418     Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
419   bool Reloaded = false;
420   for (auto &U : AdditionalCorpus) {
421     if (U.size() > MaxSize)
422       U.resize(MaxSize);
423     if (!Corpus.HasUnit(U)) {
424       if (RunOne(U.data(), U.size())) {
425         CheckExitOnSrcPosOrItem();
426         Reloaded = true;
427       }
428     }
429   }
430   if (Reloaded)
431     PrintStats("RELOAD");
432 }
433 
434 void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
435   auto TimeOfUnit =
436       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
437   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
438       secondsSinceProcessStartUp() >= 2)
439     PrintStats("pulse ");
440   if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
441       TimeOfUnit >= Options.ReportSlowUnits) {
442     TimeOfLongestUnitInSeconds = TimeOfUnit;
443     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
444     WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
445   }
446 }
447 
448 bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
449                     InputInfo *II, bool *FoundUniqFeatures) {
450   if (!Size)
451     return false;
452 
453   ExecuteCallback(Data, Size);
454 
455   UniqFeatureSetTmp.clear();
456   size_t FoundUniqFeaturesOfII = 0;
457   size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
458   TPC.CollectFeatures([&](size_t Feature) {
459     if (Corpus.AddFeature(Feature, Size, Options.Shrink))
460       UniqFeatureSetTmp.push_back(Feature);
461     if (Options.ReduceInputs && II)
462       if (std::binary_search(II->UniqFeatureSet.begin(),
463                              II->UniqFeatureSet.end(), Feature))
464         FoundUniqFeaturesOfII++;
465   });
466   if (FoundUniqFeatures)
467     *FoundUniqFeatures = FoundUniqFeaturesOfII;
468   PrintPulseAndReportSlowInput(Data, Size);
469   size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
470   if (NumNewFeatures) {
471     TPC.UpdateObservedPCs();
472     Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
473                        TPC.ObservedFocusFunction(), UniqFeatureSetTmp, DFT, II);
474     return true;
475   }
476   if (II && FoundUniqFeaturesOfII &&
477       II->DataFlowTraceForFocusFunction.empty() &&
478       FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
479       II->U.size() > Size) {
480     Corpus.Replace(II, {Data, Data + Size});
481     return true;
482   }
483   return false;
484 }
485 
486 size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
487   assert(InFuzzingThread());
488   *Data = CurrentUnitData;
489   return CurrentUnitSize;
490 }
491 
492 void Fuzzer::CrashOnOverwrittenData() {
493   Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
494          GetPid());
495   DumpCurrentUnit("crash-");
496   Printf("SUMMARY: libFuzzer: out-of-memory\n");
497   _Exit(Options.ErrorExitCode); // Stop right now.
498 }
499 
500 // Compare two arrays, but not all bytes if the arrays are large.
501 static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
502   const size_t Limit = 64;
503   if (Size <= 64)
504     return !memcmp(A, B, Size);
505   // Compare first and last Limit/2 bytes.
506   return !memcmp(A, B, Limit / 2) &&
507          !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
508 }
509 
510 void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
511   TPC.RecordInitialStack();
512   TotalNumberOfRuns++;
513   assert(InFuzzingThread());
514   // We copy the contents of Unit into a separate heap buffer
515   // so that we reliably find buffer overflows in it.
516   uint8_t *DataCopy = new uint8_t[Size];
517   memcpy(DataCopy, Data, Size);
518   if (EF->__msan_unpoison)
519     EF->__msan_unpoison(DataCopy, Size);
520   if (CurrentUnitData && CurrentUnitData != Data)
521     memcpy(CurrentUnitData, Data, Size);
522   CurrentUnitSize = Size;
523   {
524     ScopedEnableMsanInterceptorChecks S;
525     AllocTracer.Start(Options.TraceMalloc);
526     UnitStartTime = system_clock::now();
527     TPC.ResetMaps();
528     RunningUserCallback = true;
529     int Res = CB(DataCopy, Size);
530     RunningUserCallback = false;
531     UnitStopTime = system_clock::now();
532     (void)Res;
533     assert(Res == 0);
534     HasMoreMallocsThanFrees = AllocTracer.Stop();
535   }
536   if (!LooseMemeq(DataCopy, Data, Size))
537     CrashOnOverwrittenData();
538   CurrentUnitSize = 0;
539   delete[] DataCopy;
540 }
541 
542 std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
543   if (Options.OnlyASCII)
544     assert(IsASCII(U));
545   if (Options.OutputCorpus.empty())
546     return "";
547   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
548   WriteToFile(U, Path);
549   if (Options.Verbosity >= 2)
550     Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
551   return Path;
552 }
553 
554 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
555   if (!Options.SaveArtifacts)
556     return;
557   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
558   if (!Options.ExactArtifactPath.empty())
559     Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
560   WriteToFile(U, Path);
561   Printf("artifact_prefix='%s'; Test unit written to %s\n",
562          Options.ArtifactPrefix.c_str(), Path.c_str());
563   if (U.size() <= kMaxUnitSizeToPrint)
564     Printf("Base64: %s\n", Base64(U).c_str());
565 }
566 
567 void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
568   if (!Options.PrintNEW)
569     return;
570   PrintStats(Text, "");
571   if (Options.Verbosity) {
572     Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
573     MD.PrintMutationSequence();
574     Printf("\n");
575   }
576 }
577 
578 void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
579   II->NumSuccessfullMutations++;
580   MD.RecordSuccessfulMutationSequence();
581   PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW   ");
582   WriteToOutputCorpus(U);
583   NumberOfNewUnitsAdded++;
584   CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
585   LastCorpusUpdateRun = TotalNumberOfRuns;
586 }
587 
588 // Tries detecting a memory leak on the particular input that we have just
589 // executed before calling this function.
590 void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
591                                      bool DuringInitialCorpusExecution) {
592   if (!HasMoreMallocsThanFrees)
593     return; // mallocs==frees, a leak is unlikely.
594   if (!Options.DetectLeaks)
595     return;
596   if (!DuringInitialCorpusExecution &&
597       TotalNumberOfRuns >= Options.MaxNumberOfRuns)
598     return;
599   if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
600       !(EF->__lsan_do_recoverable_leak_check))
601     return; // No lsan.
602   // Run the target once again, but with lsan disabled so that if there is
603   // a real leak we do not report it twice.
604   EF->__lsan_disable();
605   ExecuteCallback(Data, Size);
606   EF->__lsan_enable();
607   if (!HasMoreMallocsThanFrees)
608     return; // a leak is unlikely.
609   if (NumberOfLeakDetectionAttempts++ > 1000) {
610     Options.DetectLeaks = false;
611     Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
612            "      Most likely the target function accumulates allocated\n"
613            "      memory in a global state w/o actually leaking it.\n"
614            "      You may try running this binary with -trace_malloc=[12]"
615            "      to get a trace of mallocs and frees.\n"
616            "      If LeakSanitizer is enabled in this process it will still\n"
617            "      run on the process shutdown.\n");
618     return;
619   }
620   // Now perform the actual lsan pass. This is expensive and we must ensure
621   // we don't call it too often.
622   if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
623     if (DuringInitialCorpusExecution)
624       Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
625     Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
626     CurrentUnitSize = Size;
627     DumpCurrentUnit("leak-");
628     PrintFinalStats();
629     _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
630   }
631 }
632 
633 void Fuzzer::MutateAndTestOne() {
634   MD.StartMutationSequence();
635 
636   auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
637   if (Options.DoCrossOver)
638     MD.SetCrossOverWith(&Corpus.ChooseUnitToMutate(MD.GetRand()).U);
639   const auto &U = II.U;
640   memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
641   assert(CurrentUnitData);
642   size_t Size = U.size();
643   assert(Size <= MaxInputLen && "Oversized Unit");
644   memcpy(CurrentUnitData, U.data(), Size);
645 
646   assert(MaxMutationLen > 0);
647 
648   size_t CurrentMaxMutationLen =
649       Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
650   assert(CurrentMaxMutationLen > 0);
651 
652   for (int i = 0; i < Options.MutateDepth; i++) {
653     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
654       break;
655     MaybeExitGracefully();
656     size_t NewSize = 0;
657     if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
658         Size <= CurrentMaxMutationLen)
659       NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
660                                   II.DataFlowTraceForFocusFunction);
661     else
662       NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
663     assert(NewSize > 0 && "Mutator returned empty unit");
664     assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
665     Size = NewSize;
666     II.NumExecutedMutations++;
667 
668     bool FoundUniqFeatures = false;
669     bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
670                          &FoundUniqFeatures);
671     TryDetectingAMemoryLeak(CurrentUnitData, Size,
672                             /*DuringInitialCorpusExecution*/ false);
673     if (NewCov) {
674       ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
675       break;  // We will mutate this input more in the next rounds.
676     }
677     if (Options.ReduceDepth && !FoundUniqFeatures)
678         break;
679   }
680 }
681 
682 void Fuzzer::PurgeAllocator() {
683   if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
684     return;
685   if (duration_cast<seconds>(system_clock::now() -
686                              LastAllocatorPurgeAttemptTime)
687           .count() < Options.PurgeAllocatorIntervalSec)
688     return;
689 
690   if (Options.RssLimitMb <= 0 ||
691       GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
692     EF->__sanitizer_purge_allocator();
693 
694   LastAllocatorPurgeAttemptTime = system_clock::now();
695 }
696 
697 void Fuzzer::ReadAndExecuteSeedCorpora(
698     const Vector<std::string> &CorpusDirs,
699     const Vector<std::string> &ExtraSeedFiles) {
700   const size_t kMaxSaneLen = 1 << 20;
701   const size_t kMinDefaultLen = 4096;
702   Vector<SizedFile> SizedFiles;
703   size_t MaxSize = 0;
704   size_t MinSize = -1;
705   size_t TotalSize = 0;
706   size_t LastNumFiles = 0;
707   for (auto &Dir : CorpusDirs) {
708     GetSizedFilesFromDir(Dir, &SizedFiles);
709     Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
710            Dir.c_str());
711     LastNumFiles = SizedFiles.size();
712   }
713   // Add files from -seed_inputs.
714   for (auto &File : ExtraSeedFiles)
715     if (auto Size = FileSize(File))
716       SizedFiles.push_back({File, Size});
717 
718   for (auto &File : SizedFiles) {
719     MaxSize = Max(File.Size, MaxSize);
720     MinSize = Min(File.Size, MinSize);
721     TotalSize += File.Size;
722   }
723   if (Options.MaxLen == 0)
724     SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
725   assert(MaxInputLen > 0);
726 
727   // Test the callback with empty input and never try it again.
728   uint8_t dummy = 0;
729   ExecuteCallback(&dummy, 0);
730 
731   // Protect lazy counters here, after the once-init code has been executed.
732   if (Options.LazyCounters)
733     TPC.ProtectLazyCounters();
734 
735   if (SizedFiles.empty()) {
736     Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
737     Unit U({'\n'}); // Valid ASCII input.
738     RunOne(U.data(), U.size());
739   } else {
740     Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
741            " rss: %zdMb\n",
742            SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
743     if (Options.ShuffleAtStartUp)
744       std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
745 
746     if (Options.PreferSmall) {
747       std::stable_sort(SizedFiles.begin(), SizedFiles.end());
748       assert(SizedFiles.front().Size <= SizedFiles.back().Size);
749     }
750 
751     // Load and execute inputs one by one.
752     for (auto &SF : SizedFiles) {
753       auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
754       assert(U.size() <= MaxInputLen);
755       RunOne(U.data(), U.size());
756       CheckExitOnSrcPosOrItem();
757       TryDetectingAMemoryLeak(U.data(), U.size(),
758                               /*DuringInitialCorpusExecution*/ true);
759     }
760   }
761 
762   PrintStats("INITED");
763   if (!Options.FocusFunction.empty())
764     Printf("INFO: %zd/%zd inputs touch the focus function\n",
765            Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
766   if (!Options.DataFlowTrace.empty())
767     Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
768            Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
769 
770   if (Corpus.empty() && Options.MaxNumberOfRuns) {
771     Printf("ERROR: no interesting inputs were found. "
772            "Is the code instrumented for coverage? Exiting.\n");
773     exit(1);
774   }
775 }
776 
777 void Fuzzer::Loop(const Vector<std::string> &CorpusDirs,
778                   const Vector<std::string> &ExtraSeedFiles) {
779   ReadAndExecuteSeedCorpora(CorpusDirs, ExtraSeedFiles);
780   DFT.Clear();  // No need for DFT any more.
781   TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
782   TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
783   system_clock::time_point LastCorpusReload = system_clock::now();
784 
785   TmpMaxMutationLen =
786       Min(MaxMutationLen, Max(size_t(4), Corpus.MaxInputSize()));
787 
788   while (true) {
789     auto Now = system_clock::now();
790     if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
791         Options.ReloadIntervalSec) {
792       RereadOutputCorpus(MaxInputLen);
793       LastCorpusReload = system_clock::now();
794     }
795     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
796       break;
797     if (TimedOut())
798       break;
799 
800     // Update TmpMaxMutationLen
801     if (Options.LenControl) {
802       if (TmpMaxMutationLen < MaxMutationLen &&
803           TotalNumberOfRuns - LastCorpusUpdateRun >
804               Options.LenControl * Log(TmpMaxMutationLen)) {
805         TmpMaxMutationLen =
806             Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
807         LastCorpusUpdateRun = TotalNumberOfRuns;
808       }
809     } else {
810       TmpMaxMutationLen = MaxMutationLen;
811     }
812 
813     // Perform several mutations and runs.
814     MutateAndTestOne();
815 
816     PurgeAllocator();
817   }
818 
819   PrintStats("DONE  ", "\n");
820   MD.PrintRecommendedDictionary();
821 }
822 
823 void Fuzzer::MinimizeCrashLoop(const Unit &U) {
824   if (U.size() <= 1)
825     return;
826   while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
827     MD.StartMutationSequence();
828     memcpy(CurrentUnitData, U.data(), U.size());
829     for (int i = 0; i < Options.MutateDepth; i++) {
830       size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
831       assert(NewSize > 0 && NewSize <= MaxMutationLen);
832       ExecuteCallback(CurrentUnitData, NewSize);
833       PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
834       TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
835                               /*DuringInitialCorpusExecution*/ false);
836     }
837   }
838 }
839 
840 } // namespace fuzzer
841 
842 extern "C" {
843 
844 ATTRIBUTE_INTERFACE size_t
845 LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
846   assert(fuzzer::F);
847   return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
848 }
849 
850 } // extern "C"
851