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   if (EF->__sanitizer_acquire_crash_state)
232     EF->__sanitizer_acquire_crash_state();
233   Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
234   if (EF->__sanitizer_print_stack_trace)
235     EF->__sanitizer_print_stack_trace();
236   Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
237          "      Combine libFuzzer with AddressSanitizer or similar for better "
238          "crash reports.\n");
239   Printf("SUMMARY: libFuzzer: deadly signal\n");
240   DumpCurrentUnit("crash-");
241   PrintFinalStats();
242   _Exit(Options.ErrorExitCode); // Stop right now.
243 }
244 
245 void Fuzzer::ExitCallback() {
246   if (!RunningCB)
247     return; // This exit did not come from the user callback
248   if (EF->__sanitizer_acquire_crash_state &&
249       !EF->__sanitizer_acquire_crash_state())
250     return;
251   Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
252   if (EF->__sanitizer_print_stack_trace)
253     EF->__sanitizer_print_stack_trace();
254   Printf("SUMMARY: libFuzzer: fuzz target exited\n");
255   DumpCurrentUnit("crash-");
256   PrintFinalStats();
257   _Exit(Options.ErrorExitCode);
258 }
259 
260 void Fuzzer::MaybeExitGracefully() {
261   if (!GracefulExitRequested) return;
262   Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
263   PrintFinalStats();
264   _Exit(0);
265 }
266 
267 void Fuzzer::InterruptCallback() {
268   Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
269   PrintFinalStats();
270   _Exit(0); // Stop right now, don't perform any at-exit actions.
271 }
272 
273 NO_SANITIZE_MEMORY
274 void Fuzzer::AlarmCallback() {
275   assert(Options.UnitTimeoutSec > 0);
276   // In Windows Alarm callback is executed by a different thread.
277 #if !LIBFUZZER_WINDOWS
278   if (!InFuzzingThread())
279     return;
280 #endif
281   if (!RunningCB)
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     if (EF->__sanitizer_print_stack_trace)
300       EF->__sanitizer_print_stack_trace();
301     Printf("SUMMARY: libFuzzer: timeout\n");
302     PrintFinalStats();
303     _Exit(Options.TimeoutExitCode); // Stop right now.
304   }
305 }
306 
307 void Fuzzer::RssLimitCallback() {
308   if (EF->__sanitizer_acquire_crash_state &&
309       !EF->__sanitizer_acquire_crash_state())
310     return;
311   Printf(
312       "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
313       GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
314   Printf("   To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
315   if (EF->__sanitizer_print_memory_profile)
316     EF->__sanitizer_print_memory_profile(95, 8);
317   DumpCurrentUnit("oom-");
318   Printf("SUMMARY: libFuzzer: out-of-memory\n");
319   PrintFinalStats();
320   _Exit(Options.ErrorExitCode); // 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   }
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.DumpCoverage)
357     TPC.DumpCoverage();
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 = [&](uintptr_t PC) {
390       if (!PCsSet->insert(PC).second)
391         return;
392       std::string Descr = DescribePC("%F %L", 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 (Options.UseFeatureFrequency)
460       Corpus.UpdateFeatureFrequency(Feature);
461     if (Corpus.AddFeature(Feature, Size, Options.Shrink))
462       UniqFeatureSetTmp.push_back(Feature);
463     if (Options.ReduceInputs && II)
464       if (std::binary_search(II->UniqFeatureSet.begin(),
465                              II->UniqFeatureSet.end(), Feature))
466         FoundUniqFeaturesOfII++;
467   });
468   if (FoundUniqFeatures)
469     *FoundUniqFeatures = FoundUniqFeaturesOfII;
470   PrintPulseAndReportSlowInput(Data, Size);
471   size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
472   if (NumNewFeatures) {
473     TPC.UpdateObservedPCs();
474     Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
475                        UniqFeatureSetTmp);
476     return true;
477   }
478   if (II && FoundUniqFeaturesOfII &&
479       FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
480       II->U.size() > Size) {
481     Corpus.Replace(II, {Data, Data + Size});
482     return true;
483   }
484   return false;
485 }
486 
487 size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
488   assert(InFuzzingThread());
489   *Data = CurrentUnitData;
490   return CurrentUnitSize;
491 }
492 
493 void Fuzzer::CrashOnOverwrittenData() {
494   Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
495          GetPid());
496   DumpCurrentUnit("crash-");
497   Printf("SUMMARY: libFuzzer: out-of-memory\n");
498   _Exit(Options.ErrorExitCode); // Stop right now.
499 }
500 
501 // Compare two arrays, but not all bytes if the arrays are large.
502 static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
503   const size_t Limit = 64;
504   if (Size <= 64)
505     return !memcmp(A, B, Size);
506   // Compare first and last Limit/2 bytes.
507   return !memcmp(A, B, Limit / 2) &&
508          !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
509 }
510 
511 void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
512   TPC.RecordInitialStack();
513   TotalNumberOfRuns++;
514   assert(InFuzzingThread());
515   if (SMR.IsClient())
516     SMR.WriteByteArray(Data, Size);
517   // We copy the contents of Unit into a separate heap buffer
518   // so that we reliably find buffer overflows in it.
519   uint8_t *DataCopy = new uint8_t[Size];
520   memcpy(DataCopy, Data, Size);
521   if (CurrentUnitData && CurrentUnitData != Data)
522     memcpy(CurrentUnitData, Data, Size);
523   CurrentUnitSize = Size;
524   AllocTracer.Start(Options.TraceMalloc);
525   UnitStartTime = system_clock::now();
526   TPC.ResetMaps();
527   RunningCB = true;
528   int Res = CB(DataCopy, Size);
529   RunningCB = false;
530   UnitStopTime = system_clock::now();
531   (void)Res;
532   assert(Res == 0);
533   HasMoreMallocsThanFrees = AllocTracer.Stop();
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.UseFeatureFrequency)
635     Corpus.UpdateFeatureFrequencyScore(&II);
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     NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
655     assert(NewSize > 0 && "Mutator returned empty unit");
656     assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
657     Size = NewSize;
658     II.NumExecutedMutations++;
659 
660     bool FoundUniqFeatures = false;
661     bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
662                          &FoundUniqFeatures);
663     TryDetectingAMemoryLeak(CurrentUnitData, Size,
664                             /*DuringInitialCorpusExecution*/ false);
665     if (NewCov) {
666       ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
667       break;  // We will mutate this input more in the next rounds.
668     }
669     if (Options.ReduceDepth && !FoundUniqFeatures)
670         break;
671   }
672 }
673 
674 void Fuzzer::PurgeAllocator() {
675   if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
676     return;
677   if (duration_cast<seconds>(system_clock::now() -
678                              LastAllocatorPurgeAttemptTime)
679           .count() < Options.PurgeAllocatorIntervalSec)
680     return;
681 
682   if (Options.RssLimitMb <= 0 ||
683       GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
684     EF->__sanitizer_purge_allocator();
685 
686   LastAllocatorPurgeAttemptTime = system_clock::now();
687 }
688 
689 void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
690   const size_t kMaxSaneLen = 1 << 20;
691   const size_t kMinDefaultLen = 4096;
692   Vector<SizedFile> SizedFiles;
693   size_t MaxSize = 0;
694   size_t MinSize = -1;
695   size_t TotalSize = 0;
696   size_t LastNumFiles = 0;
697   for (auto &Dir : CorpusDirs) {
698     GetSizedFilesFromDir(Dir, &SizedFiles);
699     Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
700            Dir.c_str());
701     LastNumFiles = SizedFiles.size();
702   }
703   for (auto &File : SizedFiles) {
704     MaxSize = Max(File.Size, MaxSize);
705     MinSize = Min(File.Size, MinSize);
706     TotalSize += File.Size;
707   }
708   if (Options.MaxLen == 0)
709     SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
710   assert(MaxInputLen > 0);
711 
712   // Test the callback with empty input and never try it again.
713   uint8_t dummy = 0;
714   ExecuteCallback(&dummy, 0);
715 
716   if (SizedFiles.empty()) {
717     Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
718     Unit U({'\n'}); // Valid ASCII input.
719     RunOne(U.data(), U.size());
720   } else {
721     Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
722            " rss: %zdMb\n",
723            SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
724     if (Options.ShuffleAtStartUp)
725       std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
726 
727     if (Options.PreferSmall) {
728       std::stable_sort(SizedFiles.begin(), SizedFiles.end());
729       assert(SizedFiles.front().Size <= SizedFiles.back().Size);
730     }
731 
732     // Load and execute inputs one by one.
733     for (auto &SF : SizedFiles) {
734       auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
735       assert(U.size() <= MaxInputLen);
736       RunOne(U.data(), U.size());
737       CheckExitOnSrcPosOrItem();
738       TryDetectingAMemoryLeak(U.data(), U.size(),
739                               /*DuringInitialCorpusExecution*/ true);
740     }
741   }
742 
743   PrintStats("INITED");
744   if (Corpus.empty()) {
745     Printf("ERROR: no interesting inputs were found. "
746            "Is the code instrumented for coverage? Exiting.\n");
747     exit(1);
748   }
749 }
750 
751 void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
752   ReadAndExecuteSeedCorpora(CorpusDirs);
753   TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
754   TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
755   system_clock::time_point LastCorpusReload = system_clock::now();
756   if (Options.DoCrossOver)
757     MD.SetCorpus(&Corpus);
758   while (true) {
759     auto Now = system_clock::now();
760     if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
761         Options.ReloadIntervalSec) {
762       RereadOutputCorpus(MaxInputLen);
763       LastCorpusReload = system_clock::now();
764     }
765     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
766       break;
767     if (TimedOut())
768       break;
769 
770     // Update TmpMaxMutationLen
771     if (Options.LenControl) {
772       if (TmpMaxMutationLen < MaxMutationLen &&
773           TotalNumberOfRuns - LastCorpusUpdateRun >
774               Options.LenControl * Log(TmpMaxMutationLen)) {
775         TmpMaxMutationLen =
776             Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
777         LastCorpusUpdateRun = TotalNumberOfRuns;
778       }
779     } else {
780       TmpMaxMutationLen = MaxMutationLen;
781     }
782 
783     // Perform several mutations and runs.
784     MutateAndTestOne();
785 
786     PurgeAllocator();
787   }
788 
789   PrintStats("DONE  ", "\n");
790   MD.PrintRecommendedDictionary();
791 }
792 
793 void Fuzzer::MinimizeCrashLoop(const Unit &U) {
794   if (U.size() <= 1)
795     return;
796   while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
797     MD.StartMutationSequence();
798     memcpy(CurrentUnitData, U.data(), U.size());
799     for (int i = 0; i < Options.MutateDepth; i++) {
800       size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
801       assert(NewSize > 0 && NewSize <= MaxMutationLen);
802       ExecuteCallback(CurrentUnitData, NewSize);
803       PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
804       TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
805                               /*DuringInitialCorpusExecution*/ false);
806     }
807   }
808 }
809 
810 void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
811   if (SMR.IsServer()) {
812     SMR.WriteByteArray(Data, Size);
813   } else if (SMR.IsClient()) {
814     SMR.PostClient();
815     SMR.WaitServer();
816     size_t OtherSize = SMR.ReadByteArraySize();
817     uint8_t *OtherData = SMR.GetByteArray();
818     if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
819       size_t i = 0;
820       for (i = 0; i < Min(Size, OtherSize); i++)
821         if (Data[i] != OtherData[i])
822           break;
823       Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
824              "offset %zd\n",
825              GetPid(), Size, OtherSize, i);
826       DumpCurrentUnit("mismatch-");
827       Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
828       PrintFinalStats();
829       _Exit(Options.ErrorExitCode);
830     }
831   }
832 }
833 
834 } // namespace fuzzer
835 
836 extern "C" {
837 
838 __attribute__((visibility("default"))) size_t
839 LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
840   assert(fuzzer::F);
841   return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
842 }
843 
844 // Experimental
845 __attribute__((visibility("default"))) void
846 LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
847   assert(fuzzer::F);
848   fuzzer::F->AnnounceOutput(Data, Size);
849 }
850 } // extern "C"
851