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