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"
13 #include <sanitizer/coverage_interface.h>
17 __attribute__((weak)) void __sanitizer_print_stack_trace();
18 __attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
22 static const size_t kMaxUnitSizeToPrint = 256;
24 // Only one Fuzzer per process.
27 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
28 : USF(USF), Options(Options) {
30 InitializeTraceState();
35 void Fuzzer::SetDeathCallback() {
36 __sanitizer_set_death_callback(StaticDeathCallback);
39 void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
40 PrintASCII(U, PrintAfter);
43 void Fuzzer::StaticDeathCallback() {
48 void Fuzzer::DeathCallback() {
50 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
51 Print(CurrentUnit, "\n");
52 PrintUnitInASCII(CurrentUnit, "\n");
54 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
57 void Fuzzer::StaticAlarmCallback() {
62 void Fuzzer::AlarmCallback() {
63 assert(Options.UnitTimeoutSec > 0);
65 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
66 if (Seconds == 0) return;
67 if (Options.Verbosity >= 2)
68 Printf("AlarmCallback %zd\n", Seconds);
69 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
70 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
71 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
72 Options.UnitTimeoutSec);
73 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
74 Print(CurrentUnit, "\n");
75 PrintUnitInASCII(CurrentUnit, "\n");
77 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
78 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
80 if (__sanitizer_print_stack_trace)
81 __sanitizer_print_stack_trace();
82 Printf("SUMMARY: libFuzzer: timeout\n");
87 void Fuzzer::PrintStats(const char *Where, const char *End) {
88 if (!Options.Verbosity) return;
89 size_t Seconds = secondsSinceProcessStartUp();
90 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
91 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
92 if (LastRecordedBlockCoverage)
93 Printf(" cov: %zd", LastRecordedBlockCoverage);
94 if (auto TB = TotalBits())
95 Printf(" bits: %zd", TB);
96 if (LastRecordedCallerCalleeCoverage)
97 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
98 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
99 if (TotalNumberOfExecutedTraceBasedMutations)
100 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
104 void Fuzzer::RereadOutputCorpus() {
105 if (Options.OutputCorpus.empty()) return;
106 std::vector<Unit> AdditionalCorpus;
107 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
108 &EpochOfLastReadOfOutputCorpus);
109 if (Corpus.empty()) {
110 Corpus = AdditionalCorpus;
113 if (!Options.Reload) return;
114 if (Options.Verbosity >= 2)
115 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
116 for (auto &X : AdditionalCorpus) {
117 if (X.size() > (size_t)Options.MaxLen)
118 X.resize(Options.MaxLen);
119 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
121 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
122 if (RunOne(CurrentUnit)) {
124 if (Options.Verbosity >= 1)
125 PrintStats("RELOAD");
131 void Fuzzer::ShuffleAndMinimize() {
132 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
133 (Options.PreferSmallDuringInitialShuffle == -1 &&
134 USF.GetRand().RandBool()));
135 if (Options.Verbosity)
136 Printf("PreferSmall: %d\n", PreferSmall);
138 std::vector<Unit> NewCorpus;
139 if (Options.ShuffleAtStartUp) {
140 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
143 Corpus.begin(), Corpus.end(),
144 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
146 Unit &U = CurrentUnit;
147 for (const auto &C : Corpus) {
148 for (size_t First = 0; First < 1; First++) {
150 size_t Last = std::min(First + Options.MaxLen, C.size());
151 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
152 if (Options.OnlyASCII)
155 NewCorpus.push_back(U);
156 if (Options.Verbosity >= 2)
157 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
162 for (auto &X : Corpus)
163 UnitHashesAddedToCorpus.insert(Hash(X));
164 PrintStats("INITED");
167 bool Fuzzer::RunOne(const Unit &U) {
168 UnitStartTime = system_clock::now();
171 PrepareCoverageBeforeRun();
173 bool Res = CheckCoverageAfterRun();
175 auto UnitStopTime = system_clock::now();
177 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
178 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
179 PrintStats("pulse ");
180 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
181 TimeOfUnit >= Options.ReportSlowUnits) {
182 TimeOfLongestUnitInSeconds = TimeOfUnit;
183 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
184 WriteUnitToFileWithPrefix(U, "slow-unit-");
189 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
190 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
192 if (Options.OnlyASCII)
195 ReportNewCoverage(U);
198 void Fuzzer::ExecuteCallback(const Unit &U) {
199 int Res = USF.TargetFunction(U.data(), U.size());
204 size_t Fuzzer::RecordBlockCoverage() {
205 return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
208 size_t Fuzzer::RecordCallerCalleeCoverage() {
209 if (!Options.UseIndirCalls)
211 if (!__sanitizer_get_total_unique_caller_callee_pairs)
213 return LastRecordedCallerCalleeCoverage =
214 __sanitizer_get_total_unique_caller_callee_pairs();
217 void Fuzzer::PrepareCoverageBeforeRun() {
218 if (Options.UseCounters) {
219 size_t NumCounters = __sanitizer_get_number_of_counters();
220 CounterBitmap.resize(NumCounters);
221 __sanitizer_update_counter_bitset_and_clear_counters(0);
223 RecordBlockCoverage();
224 RecordCallerCalleeCoverage();
227 bool Fuzzer::CheckCoverageAfterRun() {
228 size_t OldCoverage = LastRecordedBlockCoverage;
229 size_t NewCoverage = RecordBlockCoverage();
230 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
231 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
232 size_t NumNewBits = 0;
233 if (Options.UseCounters)
234 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
235 CounterBitmap.data());
236 return NewCoverage > OldCoverage ||
237 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
240 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
241 if (Options.OutputCorpus.empty()) return;
242 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
243 WriteToFile(U, Path);
244 if (Options.Verbosity >= 2)
245 Printf("Written to %s\n", Path.c_str());
246 assert(!Options.OnlyASCII || IsASCII(U));
249 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
250 if (!Options.SaveArtifacts)
252 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
253 WriteToFile(U, Path);
254 Printf("artifact_prefix='%s'; Test unit written to %s\n",
255 Options.ArtifactPrefix.c_str(), Path.c_str());
256 if (U.size() <= kMaxUnitSizeToPrint) {
258 PrintFileAsBase64(Path);
262 void Fuzzer::SaveCorpus() {
263 if (Options.OutputCorpus.empty()) return;
264 for (const auto &U : Corpus)
265 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
266 if (Options.Verbosity)
267 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
268 Options.OutputCorpus.c_str());
271 void Fuzzer::ReportNewCoverage(const Unit &U) {
273 UnitHashesAddedToCorpus.insert(Hash(U));
274 PrintStats("NEW ", "");
275 if (Options.Verbosity) {
276 Printf(" L: %zd", U.size());
279 PrintUnitInASCII(U, "\t");
284 WriteToOutputCorpus(U);
285 if (Options.ExitOnFirst)
289 void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
290 if (Corpora.size() <= 1) {
291 Printf("Merge requires two or more corpus dirs\n");
294 auto InitialCorpusDir = Corpora[0];
295 ReadDir(InitialCorpusDir, nullptr);
296 Printf("Merge: running the initial corpus '%s' of %d units\n",
297 InitialCorpusDir.c_str(), Corpus.size());
298 for (auto &U : Corpus)
301 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
304 size_t NumMerged = 0;
305 for (auto &C : ExtraCorpora) {
308 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
310 for (auto &U : Corpus) {
313 WriteToOutputCorpus(U);
318 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
321 void Fuzzer::MutateAndTestOne(Unit *U) {
322 for (int i = 0; i < Options.MutateDepth; i++) {
323 StartTraceRecording();
324 size_t Size = U->size();
325 U->resize(Options.MaxLen);
326 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
327 assert(NewSize > 0 && "Mutator returned empty unit");
328 assert(NewSize <= (size_t)Options.MaxLen &&
329 "Mutator return overisized unit");
331 RunOneAndUpdateCorpus(*U);
332 size_t NumTraceBasedMutations = StopTraceRecording();
334 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
336 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
338 for (size_t w = 0; w < TBMWidth; w++) {
340 for (size_t d = 0; d < TBMDepth; d++) {
341 TotalNumberOfExecutedTraceBasedMutations++;
342 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
343 RunOneAndUpdateCorpus(*U);
349 void Fuzzer::Loop() {
350 for (auto &U: Options.Dictionary)
351 USF.GetMD().AddWordToDictionary(U.data(), U.size());
354 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
356 RereadOutputCorpus();
357 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
359 if (Options.MaxTotalTimeSec > 0 &&
360 secondsSinceProcessStartUp() >
361 static_cast<size_t>(Options.MaxTotalTimeSec))
363 CurrentUnit = Corpus[J1];
364 // Optionally, cross with another unit.
365 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
366 size_t J2 = USF.GetRand()(Corpus.size());
367 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
368 assert(!Corpus[J2].empty());
369 CurrentUnit.resize(Options.MaxLen);
370 size_t NewSize = USF.CrossOver(
371 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
372 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
373 assert(NewSize > 0 && "CrossOver returned empty unit");
374 assert(NewSize <= (size_t)Options.MaxLen &&
375 "CrossOver returned overisized unit");
376 CurrentUnit.resize(NewSize);
379 // Perform several mutations and runs.
380 MutateAndTestOne(&CurrentUnit);
385 void Fuzzer::SyncCorpus() {
386 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
387 auto Now = system_clock::now();
388 if (duration_cast<seconds>(Now - LastExternalSync).count() <
391 LastExternalSync = Now;
392 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
395 } // namespace fuzzer