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