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