1 //===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 //===----------------------------------------------------------------------===//
12 #include "FuzzerInternal.h"
15 #if defined(__has_include)
16 # if __has_include(<sanitizer/coverage_interface.h>)
17 # include <sanitizer/coverage_interface.h>
22 // Re-declare some of the sanitizer functions as "weak" so that
23 // libFuzzer can be linked w/o the sanitizers and sanitizer-coverage
24 // (in which case it will complain at start-up time).
25 __attribute__((weak)) void __sanitizer_print_stack_trace();
26 __attribute__((weak)) void __sanitizer_reset_coverage();
27 __attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
28 __attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
30 void __sanitizer_set_death_callback(void (*callback)(void));
31 __attribute__((weak)) size_t __sanitizer_get_number_of_counters();
33 uintptr_t __sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
37 static const size_t kMaxUnitSizeToPrint = 256;
39 static void MissingWeakApiFunction(const char *FnName) {
40 Printf("ERROR: %s is not defined. Exiting.\n"
41 "Did you use -fsanitize-coverage=... to build your code?\n", FnName);
45 #define CHECK_WEAK_API_FUNCTION(fn) \
48 MissingWeakApiFunction(#fn); \
51 // Only one Fuzzer per process.
54 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
55 : USF(USF), Options(Options) {
57 InitializeTraceState();
62 void Fuzzer::SetDeathCallback() {
63 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
64 __sanitizer_set_death_callback(StaticDeathCallback);
67 void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
68 PrintASCII(U, PrintAfter);
71 void Fuzzer::StaticDeathCallback() {
76 void Fuzzer::DeathCallback() {
78 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
79 Print(CurrentUnit, "\n");
80 PrintUnitInASCII(CurrentUnit, "\n");
82 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
85 void Fuzzer::StaticAlarmCallback() {
90 void Fuzzer::AlarmCallback() {
91 assert(Options.UnitTimeoutSec > 0);
93 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
94 if (Seconds == 0) return;
95 if (Options.Verbosity >= 2)
96 Printf("AlarmCallback %zd\n", Seconds);
97 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
98 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
99 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
100 Options.UnitTimeoutSec);
101 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
102 Print(CurrentUnit, "\n");
103 PrintUnitInASCII(CurrentUnit, "\n");
105 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
106 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
108 if (__sanitizer_print_stack_trace)
109 __sanitizer_print_stack_trace();
110 Printf("SUMMARY: libFuzzer: timeout\n");
115 void Fuzzer::PrintStats(const char *Where, const char *End) {
116 size_t Seconds = secondsSinceProcessStartUp();
117 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
119 if (Options.OutputCSV) {
120 static bool csvHeaderPrinted = false;
121 if (!csvHeaderPrinted) {
122 csvHeaderPrinted = true;
123 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
125 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
126 LastRecordedBlockCoverage, TotalBits(),
127 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
128 TotalNumberOfExecutedTraceBasedMutations, Where);
131 if (!Options.Verbosity)
133 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
134 if (LastRecordedBlockCoverage)
135 Printf(" cov: %zd", LastRecordedBlockCoverage);
136 if (auto TB = TotalBits())
137 Printf(" bits: %zd", TB);
138 if (LastRecordedCallerCalleeCoverage)
139 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
140 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
141 if (TotalNumberOfExecutedTraceBasedMutations)
142 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
146 void Fuzzer::RereadOutputCorpus() {
147 if (Options.OutputCorpus.empty()) return;
148 std::vector<Unit> AdditionalCorpus;
149 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
150 &EpochOfLastReadOfOutputCorpus);
151 if (Corpus.empty()) {
152 Corpus = AdditionalCorpus;
155 if (!Options.Reload) return;
156 if (Options.Verbosity >= 2)
157 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
158 for (auto &X : AdditionalCorpus) {
159 if (X.size() > (size_t)Options.MaxLen)
160 X.resize(Options.MaxLen);
161 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
163 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
164 if (RunOne(CurrentUnit)) {
166 PrintStats("RELOAD");
172 void Fuzzer::ShuffleAndMinimize() {
173 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
174 (Options.PreferSmallDuringInitialShuffle == -1 &&
175 USF.GetRand().RandBool()));
176 if (Options.Verbosity)
177 Printf("PreferSmall: %d\n", PreferSmall);
179 std::vector<Unit> NewCorpus;
180 if (Options.ShuffleAtStartUp) {
181 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
184 Corpus.begin(), Corpus.end(),
185 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
187 Unit &U = CurrentUnit;
188 for (const auto &C : Corpus) {
189 for (size_t First = 0; First < 1; First++) {
191 size_t Last = std::min(First + Options.MaxLen, C.size());
192 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
193 if (Options.OnlyASCII)
196 NewCorpus.push_back(U);
197 if (Options.Verbosity >= 2)
198 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
203 for (auto &X : Corpus)
204 UnitHashesAddedToCorpus.insert(Hash(X));
205 PrintStats("INITED");
208 bool Fuzzer::RunOne(const Unit &U) {
209 UnitStartTime = system_clock::now();
212 PrepareCoverageBeforeRun();
214 bool Res = CheckCoverageAfterRun();
216 auto UnitStopTime = system_clock::now();
218 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
219 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
220 secondsSinceProcessStartUp() >= 2)
221 PrintStats("pulse ");
222 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
223 TimeOfUnit >= Options.ReportSlowUnits) {
224 TimeOfLongestUnitInSeconds = TimeOfUnit;
225 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
226 WriteUnitToFileWithPrefix(U, "slow-unit-");
231 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
232 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
234 if (Options.OnlyASCII)
237 ReportNewCoverage(U);
240 void Fuzzer::ExecuteCallback(const Unit &U) {
241 const uint8_t *Data = U.data();
245 int Res = USF.TargetFunction(Data, U.size());
250 size_t Fuzzer::RecordBlockCoverage() {
251 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
252 return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
255 size_t Fuzzer::RecordCallerCalleeCoverage() {
256 if (!Options.UseIndirCalls)
258 if (!__sanitizer_get_total_unique_caller_callee_pairs)
260 return LastRecordedCallerCalleeCoverage =
261 __sanitizer_get_total_unique_caller_callee_pairs();
264 void Fuzzer::PrepareCoverageBeforeRun() {
265 if (Options.UseCounters) {
266 size_t NumCounters = __sanitizer_get_number_of_counters();
267 CounterBitmap.resize(NumCounters);
268 __sanitizer_update_counter_bitset_and_clear_counters(0);
270 RecordBlockCoverage();
271 RecordCallerCalleeCoverage();
274 bool Fuzzer::CheckCoverageAfterRun() {
275 size_t OldCoverage = LastRecordedBlockCoverage;
276 size_t NewCoverage = RecordBlockCoverage();
277 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
278 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
279 size_t NumNewBits = 0;
280 if (Options.UseCounters)
281 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
282 CounterBitmap.data());
283 return NewCoverage > OldCoverage ||
284 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
287 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
288 if (Options.OutputCorpus.empty()) return;
289 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
290 WriteToFile(U, Path);
291 if (Options.Verbosity >= 2)
292 Printf("Written to %s\n", Path.c_str());
293 assert(!Options.OnlyASCII || IsASCII(U));
296 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
297 if (!Options.SaveArtifacts)
299 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
300 if (!Options.ExactArtifactPath.empty())
301 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
302 WriteToFile(U, Path);
303 Printf("artifact_prefix='%s'; Test unit written to %s\n",
304 Options.ArtifactPrefix.c_str(), Path.c_str());
305 if (U.size() <= kMaxUnitSizeToPrint) {
307 PrintFileAsBase64(Path);
311 void Fuzzer::SaveCorpus() {
312 if (Options.OutputCorpus.empty()) return;
313 for (const auto &U : Corpus)
314 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
315 if (Options.Verbosity)
316 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
317 Options.OutputCorpus.c_str());
320 void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
321 if (!Options.PrintNEW)
323 PrintStats("NEW ", "");
324 if (Options.Verbosity) {
325 Printf(" L: %zd", U.size());
328 PrintUnitInASCII(U, "\t");
335 void Fuzzer::ReportNewCoverage(const Unit &U) {
337 UnitHashesAddedToCorpus.insert(Hash(U));
338 PrintStatusForNewUnit(U);
339 WriteToOutputCorpus(U);
340 if (Options.ExitOnFirst)
344 void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
345 if (Corpora.size() <= 1) {
346 Printf("Merge requires two or more corpus dirs\n");
349 auto InitialCorpusDir = Corpora[0];
350 ReadDir(InitialCorpusDir, nullptr);
351 Printf("Merge: running the initial corpus '%s' of %d units\n",
352 InitialCorpusDir.c_str(), Corpus.size());
353 for (auto &U : Corpus)
356 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
359 size_t NumMerged = 0;
360 for (auto &C : ExtraCorpora) {
363 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
365 for (auto &U : Corpus) {
368 WriteToOutputCorpus(U);
373 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
376 void Fuzzer::MutateAndTestOne(Unit *U) {
377 for (int i = 0; i < Options.MutateDepth; i++) {
378 StartTraceRecording();
379 size_t Size = U->size();
380 U->resize(Options.MaxLen);
381 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
382 assert(NewSize > 0 && "Mutator returned empty unit");
383 assert(NewSize <= (size_t)Options.MaxLen &&
384 "Mutator return overisized unit");
386 RunOneAndUpdateCorpus(*U);
387 size_t NumTraceBasedMutations = StopTraceRecording();
389 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
391 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
393 for (size_t w = 0; w < TBMWidth; w++) {
395 for (size_t d = 0; d < TBMDepth; d++) {
396 TotalNumberOfExecutedTraceBasedMutations++;
397 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
398 RunOneAndUpdateCorpus(*U);
404 // Returns an index of random unit from the corpus to mutate.
405 // Hypothesis: units added to the corpus last are more likely to be interesting.
406 // This function gives more wieght to the more recent units.
407 size_t Fuzzer::ChooseUnitIdxToMutate() {
408 size_t N = Corpus.size();
409 size_t Total = (N + 1) * N / 2;
410 size_t R = USF.GetRand()(Total);
411 size_t IdxBeg = 0, IdxEnd = N;
413 while (IdxEnd - IdxBeg >= 2) {
414 size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
415 if (R > (Idx + 1) * Idx / 2)
424 // Experimental search heuristic: drilling.
425 // - Read, shuffle, execute and minimize the corpus.
426 // - Choose one random unit.
427 // - Reset the coverage.
428 // - Start fuzzing as if the chosen unit was the only element of the corpus.
429 // - When done, reset the coverage again.
430 // - Merge the newly created corpus into the original one.
431 void Fuzzer::Drill() {
432 // The corpus is already read, shuffled, and minimized.
433 assert(!Corpus.empty());
434 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
436 Unit U = ChooseUnitToMutate();
438 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
439 __sanitizer_reset_coverage();
441 std::vector<Unit> SavedCorpus;
442 SavedCorpus.swap(Corpus);
444 assert(Corpus.size() == 1);
446 PrintStats("DRILL ");
447 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
448 SavedOutputCorpusPath.swap(Options.OutputCorpus);
451 __sanitizer_reset_coverage();
453 PrintStats("REINIT");
454 SavedOutputCorpusPath.swap(Options.OutputCorpus);
455 for (auto &U : SavedCorpus)
457 PrintStats("MERGE ");
458 Options.PrintNEW = true;
459 size_t NumMerged = 0;
460 for (auto &U : Corpus) {
462 PrintStatusForNewUnit(U);
464 WriteToOutputCorpus(U);
467 PrintStats("MERGED");
468 if (NumMerged && Options.Verbosity)
469 Printf("Drilling discovered %zd new units\n", NumMerged);
472 void Fuzzer::Loop() {
474 size_t J1 = ChooseUnitIdxToMutate();;
476 RereadOutputCorpus();
477 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
479 if (Options.MaxTotalTimeSec > 0 &&
480 secondsSinceProcessStartUp() >
481 static_cast<size_t>(Options.MaxTotalTimeSec))
483 CurrentUnit = Corpus[J1];
484 // Optionally, cross with another unit.
485 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
486 size_t J2 = ChooseUnitIdxToMutate();
487 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
488 assert(!Corpus[J2].empty());
489 CurrentUnit.resize(Options.MaxLen);
490 size_t NewSize = USF.CrossOver(
491 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
492 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
493 assert(NewSize > 0 && "CrossOver returned empty unit");
494 assert(NewSize <= (size_t)Options.MaxLen &&
495 "CrossOver returned overisized unit");
496 CurrentUnit.resize(NewSize);
499 // Perform several mutations and runs.
500 MutateAndTestOne(&CurrentUnit);
503 PrintStats("DONE ", "\n");
506 void Fuzzer::SyncCorpus() {
507 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
508 auto Now = system_clock::now();
509 if (duration_cast<seconds>(Now - LastExternalSync).count() <
512 LastExternalSync = Now;
513 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
516 } // namespace fuzzer