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();
21 static const size_t kMaxUnitSizeToPrint = 256;
23 // Only one Fuzzer per process.
26 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
27 : USF(USF), Options(Options) {
29 InitializeTraceState();
34 void Fuzzer::SetDeathCallback() {
35 __sanitizer_set_death_callback(StaticDeathCallback);
38 void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
39 PrintASCII(U, PrintAfter);
42 void Fuzzer::StaticDeathCallback() {
47 void Fuzzer::DeathCallback() {
49 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
50 Print(CurrentUnit, "\n");
51 PrintUnitInASCII(CurrentUnit, "\n");
53 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
56 void Fuzzer::StaticAlarmCallback() {
61 void Fuzzer::AlarmCallback() {
62 assert(Options.UnitTimeoutSec > 0);
64 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
65 if (Seconds == 0) return;
66 if (Options.Verbosity >= 2)
67 Printf("AlarmCallback %zd\n", Seconds);
68 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
69 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
70 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
71 Options.UnitTimeoutSec);
72 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
73 Print(CurrentUnit, "\n");
74 PrintUnitInASCII(CurrentUnit, "\n");
76 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
77 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
79 if (__sanitizer_print_stack_trace)
80 __sanitizer_print_stack_trace();
81 Printf("SUMMARY: libFuzzer: timeout\n");
86 void Fuzzer::PrintStats(const char *Where, const char *End) {
87 if (!Options.Verbosity) return;
88 size_t Seconds = secondsSinceProcessStartUp();
89 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
90 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
91 if (LastRecordedBlockCoverage)
92 Printf(" cov: %zd", LastRecordedBlockCoverage);
93 if (auto TB = TotalBits())
94 Printf(" bits: %zd", TB);
95 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
96 if (TotalNumberOfExecutedTraceBasedMutations)
97 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
101 void Fuzzer::RereadOutputCorpus() {
102 if (Options.OutputCorpus.empty()) return;
103 std::vector<Unit> AdditionalCorpus;
104 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
105 &EpochOfLastReadOfOutputCorpus);
106 if (Corpus.empty()) {
107 Corpus = AdditionalCorpus;
110 if (!Options.Reload) return;
111 if (Options.Verbosity >= 2)
112 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
113 for (auto &X : AdditionalCorpus) {
114 if (X.size() > (size_t)Options.MaxLen)
115 X.resize(Options.MaxLen);
116 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
118 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
119 if (RunOne(CurrentUnit)) {
121 if (Options.Verbosity >= 1)
122 PrintStats("RELOAD");
128 void Fuzzer::ShuffleAndMinimize() {
129 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
130 (Options.PreferSmallDuringInitialShuffle == -1 &&
131 USF.GetRand().RandBool()));
132 if (Options.Verbosity)
133 Printf("PreferSmall: %d\n", PreferSmall);
135 std::vector<Unit> NewCorpus;
136 if (Options.ShuffleAtStartUp) {
137 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
140 Corpus.begin(), Corpus.end(),
141 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
143 Unit &U = CurrentUnit;
144 for (const auto &C : Corpus) {
145 for (size_t First = 0; First < 1; First++) {
147 size_t Last = std::min(First + Options.MaxLen, C.size());
148 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
149 if (Options.OnlyASCII)
152 NewCorpus.push_back(U);
153 if (Options.Verbosity >= 2)
154 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
159 for (auto &X : Corpus)
160 UnitHashesAddedToCorpus.insert(Hash(X));
161 PrintStats("INITED");
164 bool Fuzzer::RunOne(const Unit &U) {
165 UnitStartTime = system_clock::now();
168 PrepareCoverageBeforeRun();
170 bool Res = CheckCoverageAfterRun();
172 auto UnitStopTime = system_clock::now();
174 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
175 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
176 PrintStats("pulse ");
177 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
178 TimeOfUnit >= Options.ReportSlowUnits) {
179 TimeOfLongestUnitInSeconds = TimeOfUnit;
180 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
181 WriteUnitToFileWithPrefix(U, "slow-unit-");
186 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
187 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
189 if (Options.OnlyASCII)
192 ReportNewCoverage(U);
195 void Fuzzer::ExecuteCallback(const Unit &U) {
196 int Res = USF.TargetFunction(U.data(), U.size());
201 size_t Fuzzer::RecordBlockCoverage() {
202 return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
205 void Fuzzer::PrepareCoverageBeforeRun() {
206 if (Options.UseCounters) {
207 size_t NumCounters = __sanitizer_get_number_of_counters();
208 CounterBitmap.resize(NumCounters);
209 __sanitizer_update_counter_bitset_and_clear_counters(0);
211 RecordBlockCoverage();
214 bool Fuzzer::CheckCoverageAfterRun() {
215 size_t OldCoverage = LastRecordedBlockCoverage;
216 size_t NewCoverage = RecordBlockCoverage();
217 size_t NumNewBits = 0;
218 if (Options.UseCounters)
219 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
220 CounterBitmap.data());
221 return NewCoverage > OldCoverage || NumNewBits;
224 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
225 if (Options.OutputCorpus.empty()) return;
226 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
227 WriteToFile(U, Path);
228 if (Options.Verbosity >= 2)
229 Printf("Written to %s\n", Path.c_str());
230 assert(!Options.OnlyASCII || IsASCII(U));
233 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
234 if (!Options.SaveArtifacts)
236 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
237 WriteToFile(U, Path);
238 Printf("artifact_prefix='%s'; Test unit written to %s\n",
239 Options.ArtifactPrefix.c_str(), Path.c_str());
240 if (U.size() <= kMaxUnitSizeToPrint) {
242 PrintFileAsBase64(Path);
246 void Fuzzer::SaveCorpus() {
247 if (Options.OutputCorpus.empty()) return;
248 for (const auto &U : Corpus)
249 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
250 if (Options.Verbosity)
251 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
252 Options.OutputCorpus.c_str());
255 void Fuzzer::ReportNewCoverage(const Unit &U) {
257 UnitHashesAddedToCorpus.insert(Hash(U));
258 PrintStats("NEW ", "");
259 if (Options.Verbosity) {
260 Printf(" L: %zd", U.size());
263 PrintUnitInASCII(U, "\t");
268 WriteToOutputCorpus(U);
269 if (Options.ExitOnFirst)
273 void Fuzzer::MutateAndTestOne(Unit *U) {
274 for (int i = 0; i < Options.MutateDepth; i++) {
275 StartTraceRecording();
276 size_t Size = U->size();
277 U->resize(Options.MaxLen);
278 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
279 assert(NewSize > 0 && "Mutator returned empty unit");
280 assert(NewSize <= (size_t)Options.MaxLen &&
281 "Mutator return overisized unit");
283 RunOneAndUpdateCorpus(*U);
284 size_t NumTraceBasedMutations = StopTraceRecording();
286 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
288 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
290 for (size_t w = 0; w < TBMWidth; w++) {
292 for (size_t d = 0; d < TBMDepth; d++) {
293 TotalNumberOfExecutedTraceBasedMutations++;
294 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
295 RunOneAndUpdateCorpus(*U);
301 void Fuzzer::Loop() {
302 for (auto &U: Options.Dictionary)
303 USF.GetMD().AddWordToDictionary(U.data(), U.size());
306 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
308 RereadOutputCorpus();
309 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
311 if (Options.MaxTotalTimeSec > 0 &&
312 secondsSinceProcessStartUp() >
313 static_cast<size_t>(Options.MaxTotalTimeSec))
315 CurrentUnit = Corpus[J1];
316 // Optionally, cross with another unit.
317 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
318 size_t J2 = USF.GetRand()(Corpus.size());
319 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
320 assert(!Corpus[J2].empty());
321 CurrentUnit.resize(Options.MaxLen);
322 size_t NewSize = USF.CrossOver(
323 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
324 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
325 assert(NewSize > 0 && "CrossOver returned empty unit");
326 assert(NewSize <= (size_t)Options.MaxLen &&
327 "CrossOver returned overisized unit");
328 CurrentUnit.resize(NewSize);
331 // Perform several mutations and runs.
332 MutateAndTestOne(&CurrentUnit);
337 void Fuzzer::SyncCorpus() {
338 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
339 auto Now = system_clock::now();
340 if (duration_cast<seconds>(Now - LastExternalSync).count() <
343 LastExternalSync = Now;
344 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
347 } // namespace fuzzer