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