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>
19 // Only one Fuzzer per process.
22 Fuzzer::Fuzzer(UserCallback Callback, FuzzingOptions Options)
23 : Callback(Callback), Options(Options) {
30 void Fuzzer::SetDeathCallback() {
31 __sanitizer_set_death_callback(StaticDeathCallback);
34 void Fuzzer::PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter) {
35 if (Options.Tokens.empty()) {
36 PrintASCII(U, PrintAfter);
38 auto T = SubstituteTokens(U);
40 std::cerr << T.data();
41 std::cerr << PrintAfter;
45 void Fuzzer::StaticDeathCallback() {
50 void Fuzzer::DeathCallback() {
51 std::cerr << "DEATH: " << std::endl;
52 Print(CurrentUnit, "\n");
53 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
54 WriteToCrash(CurrentUnit, "crash-");
57 void Fuzzer::StaticAlarmCallback() {
62 void Fuzzer::AlarmCallback() {
64 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
65 std::cerr << "ALARM: working on the last Unit for " << Seconds << " seconds"
68 Print(CurrentUnit, "\n");
69 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
70 WriteToCrash(CurrentUnit, "timeout-");
75 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
76 if (!Options.Verbosity) return;
77 size_t Seconds = secondsSinceProcessStartUp();
78 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
80 << "#" << TotalNumberOfRuns
83 << " bits " << TotalBits()
84 << " units " << Corpus.size()
85 << " exec/s " << ExecPerSec
89 void Fuzzer::RereadOutputCorpus() {
90 if (Options.OutputCorpus.empty()) return;
91 std::vector<Unit> AdditionalCorpus;
92 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
93 &EpochOfLastReadOfOutputCorpus);
95 Corpus = AdditionalCorpus;
98 if (!Options.Reload) return;
99 for (auto &X : AdditionalCorpus) {
100 if (X.size() > (size_t)Options.MaxLen)
101 X.resize(Options.MaxLen);
102 if (UnitsAddedAfterInitialLoad.insert(X).second) {
105 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
106 size_t NewCoverage = RunOne(CurrentUnit);
107 if (NewCoverage && Options.Verbosity >= 1)
108 PrintStats("RELOAD", NewCoverage);
113 void Fuzzer::ShuffleAndMinimize() {
116 (Options.PreferSmallDuringInitialShuffle == 1 ||
117 (Options.PreferSmallDuringInitialShuffle == -1 && rand() % 2));
118 if (Options.Verbosity)
119 std::cerr << "PreferSmall: " << PreferSmall << "\n";
120 PrintStats("READ ", 0);
121 std::vector<Unit> NewCorpus;
122 std::random_shuffle(Corpus.begin(), Corpus.end());
125 Corpus.begin(), Corpus.end(),
126 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
127 Unit &U = CurrentUnit;
128 for (const auto &C : Corpus) {
129 for (size_t First = 0; First < 1; First++) {
131 size_t Last = std::min(First + Options.MaxLen, C.size());
132 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
133 size_t NewCoverage = RunOne(U);
135 MaxCov = NewCoverage;
136 NewCorpus.push_back(U);
137 if (Options.Verbosity >= 2)
138 std::cerr << "NEW0: " << NewCoverage
145 PrintStats("INITED", MaxCov);
148 size_t Fuzzer::RunOne(const Unit &U) {
149 UnitStartTime = system_clock::now();
152 if (Options.UseFullCoverageSet)
153 Res = RunOneMaximizeFullCoverageSet(U);
154 else if (Options.UseCoveragePairs)
155 Res = RunOneMaximizeCoveragePairs(U);
157 Res = RunOneMaximizeTotalCoverage(U);
158 auto UnitStopTime = system_clock::now();
160 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
161 if (TimeOfUnit > TimeOfLongestUnitInSeconds) {
162 TimeOfLongestUnitInSeconds = TimeOfUnit;
163 std::cerr << "Longest unit: " << TimeOfLongestUnitInSeconds
170 void Fuzzer::RunOneAndUpdateCorpus(const Unit &U) {
171 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
173 ReportNewCoverage(RunOne(U), U);
176 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
178 for (uintptr_t i = 0; i < NumPCs; i++) {
179 Res = (Res + PCs[i]) * 7;
184 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
187 if (Idx < Options.Tokens.size()) {
188 std::string Token = Options.Tokens[Idx];
189 Res.insert(Res.end(), Token.begin(), Token.end());
194 // FIXME: Apply DFSan labels.
198 void Fuzzer::ExecuteCallback(const Unit &U) {
199 if (Options.Tokens.empty()) {
200 Callback(U.data(), U.size());
202 auto T = SubstituteTokens(U);
203 Callback(T.data(), T.size());
207 // Experimental. Does not yet scale.
208 // Fuly reset the current coverage state, run a single unit,
209 // collect all coverage pairs and return non-zero if a new pair is observed.
210 size_t Fuzzer::RunOneMaximizeCoveragePairs(const Unit &U) {
211 __sanitizer_reset_coverage();
214 uintptr_t NumPCs = __sanitizer_get_coverage_guards(&PCs);
215 bool HasNewPairs = false;
216 for (uintptr_t i = 0; i < NumPCs; i++) {
217 if (!PCs[i]) continue;
218 for (uintptr_t j = 0; j < NumPCs; j++) {
219 if (!PCs[j]) continue;
220 uint64_t Pair = (i << 32) | j;
221 HasNewPairs |= CoveragePairs.insert(Pair).second;
225 return CoveragePairs.size();
230 // Fuly reset the current coverage state, run a single unit,
231 // compute a hash function from the full coverage set,
232 // return non-zero if the hash value is new.
233 // This produces tons of new units and as is it's only suitable for small tests,
234 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
235 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
236 __sanitizer_reset_coverage();
239 uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
240 if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
241 return FullCoverageSets.size();
245 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
246 size_t NumCounters = __sanitizer_get_number_of_counters();
247 if (Options.UseCounters) {
248 CounterBitmap.resize(NumCounters);
249 __sanitizer_update_counter_bitset_and_clear_counters(0);
251 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
253 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
254 size_t NumNewBits = 0;
255 if (Options.UseCounters)
256 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
257 CounterBitmap.data());
259 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
260 PrintStats("pulse ", NewCoverage);
262 if (NewCoverage > OldCoverage || NumNewBits)
267 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
268 if (Options.OutputCorpus.empty()) return;
269 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
270 WriteToFile(U, Path);
271 if (Options.Verbosity >= 2)
272 std::cerr << "Written to " << Path << std::endl;
275 void Fuzzer::WriteToCrash(const Unit &U, const char *Prefix) {
276 std::string Path = Prefix + Hash(U);
277 WriteToFile(U, Path);
278 std::cerr << "CRASHED; file written to " << Path << std::endl;
279 std::cerr << "Base64: ";
280 PrintFileAsBase64(Path);
283 void Fuzzer::SaveCorpus() {
284 if (Options.OutputCorpus.empty()) return;
285 for (const auto &U : Corpus)
286 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
287 if (Options.Verbosity)
288 std::cerr << "Written corpus of " << Corpus.size() << " files to "
289 << Options.OutputCorpus << "\n";
292 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
293 if (!NewCoverage) return;
295 UnitsAddedAfterInitialLoad.insert(U);
296 PrintStats("NEW ", NewCoverage, "");
297 if (Options.Verbosity) {
298 std::cerr << " L: " << U.size();
301 PrintUnitInASCIIOrTokens(U, "\t");
306 WriteToOutputCorpus(U);
307 if (Options.ExitOnFirst)
311 void Fuzzer::MutateAndTestOne(Unit *U) {
312 for (int i = 0; i < Options.MutateDepth; i++) {
313 StartTraceRecording();
314 Mutate(U, Options.MaxLen);
315 RunOneAndUpdateCorpus(*U);
316 size_t NumTraceBasedMutations = StopTraceRecording();
317 for (size_t j = 0; j < NumTraceBasedMutations; j++) {
318 ApplyTraceBasedMutation(j, U);
319 RunOneAndUpdateCorpus(*U);
324 void Fuzzer::Loop(size_t NumIterations) {
325 for (size_t i = 1; i <= NumIterations; i++) {
326 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
327 RereadOutputCorpus();
328 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
330 // First, simply mutate the unit w/o doing crosses.
331 CurrentUnit = Corpus[J1];
332 MutateAndTestOne(&CurrentUnit);
333 // Now, cross with others.
334 if (Options.DoCrossOver) {
335 for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
337 CrossOver(Corpus[J1], Corpus[J2], &CurrentUnit, Options.MaxLen);
338 MutateAndTestOne(&CurrentUnit);
345 } // namespace fuzzer