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 static const size_t kMaxUnitSizeToPrint = 4096;
19 // Only one Fuzzer per process.
22 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
23 : USF(USF), Options(Options) {
25 InitializeTraceState();
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 Printf("%s%s", T.data(), PrintAfter);
44 void Fuzzer::StaticDeathCallback() {
49 void Fuzzer::DeathCallback() {
51 Print(CurrentUnit, "\n");
52 PrintUnitInASCIIOrTokens(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 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
75 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
80 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
81 if (!Options.Verbosity) return;
82 size_t Seconds = secondsSinceProcessStartUp();
83 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
84 Printf("#%zd\t%s cov %zd bits %zd units %zd exec/s %zd %s", TotalNumberOfRuns,
85 Where, Cov, TotalBits(), Corpus.size(), ExecPerSec, End);
88 void Fuzzer::RereadOutputCorpus() {
89 if (Options.OutputCorpus.empty()) return;
90 std::vector<Unit> AdditionalCorpus;
91 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
92 &EpochOfLastReadOfOutputCorpus);
94 Corpus = AdditionalCorpus;
97 if (!Options.Reload) return;
98 if (Options.Verbosity >= 2)
99 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
100 for (auto &X : AdditionalCorpus) {
101 if (X.size() > (size_t)Options.MaxLen)
102 X.resize(Options.MaxLen);
103 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
105 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
106 size_t NewCoverage = RunOne(CurrentUnit);
109 if (Options.Verbosity >= 1)
110 PrintStats("RELOAD", NewCoverage);
116 void Fuzzer::ShuffleAndMinimize() {
118 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
119 (Options.PreferSmallDuringInitialShuffle == -1 &&
120 USF.GetRand().RandBool()));
121 if (Options.Verbosity)
122 Printf("PreferSmall: %d\n", PreferSmall);
123 PrintStats("READ ", 0);
124 std::vector<Unit> NewCorpus;
125 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
128 Corpus.begin(), Corpus.end(),
129 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
130 Unit &U = CurrentUnit;
131 for (const auto &C : Corpus) {
132 for (size_t First = 0; First < 1; First++) {
134 size_t Last = std::min(First + Options.MaxLen, C.size());
135 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
136 size_t NewCoverage = RunOne(U);
138 MaxCov = NewCoverage;
139 NewCorpus.push_back(U);
140 if (Options.Verbosity >= 2)
141 Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
146 for (auto &X : Corpus)
147 UnitHashesAddedToCorpus.insert(Hash(X));
148 PrintStats("INITED", MaxCov);
151 size_t Fuzzer::RunOne(const Unit &U) {
152 UnitStartTime = system_clock::now();
155 if (Options.UseFullCoverageSet)
156 Res = RunOneMaximizeFullCoverageSet(U);
158 Res = RunOneMaximizeTotalCoverage(U);
159 auto UnitStopTime = system_clock::now();
161 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
162 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
163 TimeOfUnit >= Options.ReportSlowUnits) {
164 TimeOfLongestUnitInSeconds = TimeOfUnit;
165 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
166 if (U.size() <= kMaxUnitSizeToPrint)
168 WriteUnitToFileWithPrefix(U, "slow-unit-");
173 void Fuzzer::RunOneAndUpdateCorpus(const Unit &U) {
174 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
176 ReportNewCoverage(RunOne(U), U);
179 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
181 for (uintptr_t i = 0; i < NumPCs; i++) {
182 Res = (Res + PCs[i]) * 7;
187 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
190 if (Idx < Options.Tokens.size()) {
191 std::string Token = Options.Tokens[Idx];
192 Res.insert(Res.end(), Token.begin(), Token.end());
197 // FIXME: Apply DFSan labels.
201 void Fuzzer::ExecuteCallback(const Unit &U) {
202 if (Options.Tokens.empty()) {
203 USF.TargetFunction(U.data(), U.size());
205 auto T = SubstituteTokens(U);
206 USF.TargetFunction(T.data(), T.size());
211 // Fuly reset the current coverage state, run a single unit,
212 // compute a hash function from the full coverage set,
213 // return non-zero if the hash value is new.
214 // This produces tons of new units and as is it's only suitable for small tests,
215 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
216 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
217 __sanitizer_reset_coverage();
220 uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
221 if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
222 return FullCoverageSets.size();
226 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
227 size_t NumCounters = __sanitizer_get_number_of_counters();
228 if (Options.UseCounters) {
229 CounterBitmap.resize(NumCounters);
230 __sanitizer_update_counter_bitset_and_clear_counters(0);
232 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
234 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
235 size_t NumNewBits = 0;
236 if (Options.UseCounters)
237 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
238 CounterBitmap.data());
240 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
241 PrintStats("pulse ", NewCoverage);
243 if (NewCoverage > OldCoverage || NumNewBits)
248 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
249 if (Options.OutputCorpus.empty()) return;
250 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
251 WriteToFile(U, Path);
252 if (Options.Verbosity >= 2)
253 Printf("Written to %s\n", Path.c_str());
256 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
257 std::string Path = Prefix + Hash(U);
258 WriteToFile(U, Path);
259 Printf("Test unit written to %s\n", Path.c_str());
260 if (U.size() <= kMaxUnitSizeToPrint) {
262 PrintFileAsBase64(Path);
266 void Fuzzer::SaveCorpus() {
267 if (Options.OutputCorpus.empty()) return;
268 for (const auto &U : Corpus)
269 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
270 if (Options.Verbosity)
271 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
272 Options.OutputCorpus.c_str());
275 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
276 if (!NewCoverage) return;
278 UnitHashesAddedToCorpus.insert(Hash(U));
279 PrintStats("NEW ", NewCoverage, "");
280 if (Options.Verbosity) {
281 Printf(" L: %zd", U.size());
284 PrintUnitInASCIIOrTokens(U, "\t");
289 WriteToOutputCorpus(U);
290 if (Options.ExitOnFirst)
294 void Fuzzer::MutateAndTestOne(Unit *U) {
295 for (int i = 0; i < Options.MutateDepth; i++) {
296 StartTraceRecording();
297 size_t Size = U->size();
298 U->resize(Options.MaxLen);
299 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
300 assert(NewSize > 0 && "Mutator returned empty unit");
301 assert(NewSize <= (size_t)Options.MaxLen &&
302 "Mutator return overisized unit");
304 RunOneAndUpdateCorpus(*U);
305 size_t NumTraceBasedMutations = StopTraceRecording();
306 for (size_t j = 0; j < NumTraceBasedMutations; j++) {
307 ApplyTraceBasedMutation(j, U);
308 RunOneAndUpdateCorpus(*U);
313 void Fuzzer::Loop(size_t NumIterations) {
314 for (size_t i = 1; i <= NumIterations; i++) {
315 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
317 RereadOutputCorpus();
318 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
320 // First, simply mutate the unit w/o doing crosses.
321 CurrentUnit = Corpus[J1];
322 MutateAndTestOne(&CurrentUnit);
323 // Now, cross with others.
324 if (Options.DoCrossOver && !Corpus[J1].empty()) {
325 for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
326 CurrentUnit.resize(Options.MaxLen);
327 size_t NewSize = USF.CrossOver(
328 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
329 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
330 assert(NewSize > 0 && "CrossOver returned empty unit");
331 assert(NewSize <= (size_t)Options.MaxLen &&
332 "CrossOver return overisized unit");
333 CurrentUnit.resize(NewSize);
334 MutateAndTestOne(&CurrentUnit);
341 void Fuzzer::SyncCorpus() {
342 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
343 auto Now = system_clock::now();
344 if (duration_cast<seconds>(Now - LastExternalSync).count() <
347 LastExternalSync = Now;
348 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
351 } // namespace fuzzer