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