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