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",
85 TotalNumberOfRuns, Where, Cov, TotalBits(), Corpus.size(), 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 if (Options.Verbosity >= 2)
100 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
101 for (auto &X : AdditionalCorpus) {
102 if (X.size() > (size_t)Options.MaxLen)
103 X.resize(Options.MaxLen);
104 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
106 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
107 size_t NewCoverage = RunOne(CurrentUnit);
110 if (Options.Verbosity >= 1)
111 PrintStats("RELOAD", NewCoverage);
117 void Fuzzer::ShuffleAndMinimize() {
119 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
120 (Options.PreferSmallDuringInitialShuffle == -1 &&
121 USF.GetRand().RandBool()));
122 if (Options.Verbosity)
123 Printf("PreferSmall: %d\n", PreferSmall);
124 PrintStats("READ ", 0);
125 std::vector<Unit> NewCorpus;
126 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
129 Corpus.begin(), Corpus.end(),
130 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
131 Unit &U = CurrentUnit;
132 for (const auto &C : Corpus) {
133 for (size_t First = 0; First < 1; First++) {
135 size_t Last = std::min(First + Options.MaxLen, C.size());
136 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
137 size_t NewCoverage = RunOne(U);
139 MaxCov = NewCoverage;
140 NewCorpus.push_back(U);
141 if (Options.Verbosity >= 2)
142 Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
147 for (auto &X : Corpus)
148 UnitHashesAddedToCorpus.insert(Hash(X));
149 PrintStats("INITED", MaxCov);
152 size_t Fuzzer::RunOne(const Unit &U) {
153 UnitStartTime = system_clock::now();
156 if (Options.UseFullCoverageSet)
157 Res = RunOneMaximizeFullCoverageSet(U);
159 Res = RunOneMaximizeTotalCoverage(U);
160 auto UnitStopTime = system_clock::now();
162 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
163 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
164 TimeOfUnit >= Options.ReportSlowUnits) {
165 TimeOfLongestUnitInSeconds = TimeOfUnit;
166 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
167 if (U.size() <= kMaxUnitSizeToPrint)
169 WriteUnitToFileWithPrefix(U, "slow-unit-");
174 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
175 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
177 if (Options.OnlyASCII)
179 ReportNewCoverage(RunOne(U), U);
182 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
184 for (uintptr_t i = 0; i < NumPCs; i++) {
185 Res = (Res + PCs[i]) * 7;
190 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
193 if (Idx < Options.Tokens.size()) {
194 std::string Token = Options.Tokens[Idx];
195 Res.insert(Res.end(), Token.begin(), Token.end());
200 // FIXME: Apply DFSan labels.
204 void Fuzzer::ExecuteCallback(const Unit &U) {
205 if (Options.Tokens.empty()) {
206 USF.TargetFunction(U.data(), U.size());
208 auto T = SubstituteTokens(U);
209 USF.TargetFunction(T.data(), T.size());
214 // Fuly reset the current coverage state, run a single unit,
215 // compute a hash function from the full coverage set,
216 // return non-zero if the hash value is new.
217 // This produces tons of new units and as is it's only suitable for small tests,
218 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
219 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
220 __sanitizer_reset_coverage();
223 uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
224 if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
225 return FullCoverageSets.size();
229 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
230 size_t NumCounters = __sanitizer_get_number_of_counters();
231 if (Options.UseCounters) {
232 CounterBitmap.resize(NumCounters);
233 __sanitizer_update_counter_bitset_and_clear_counters(0);
235 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
237 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
238 size_t NumNewBits = 0;
239 if (Options.UseCounters)
240 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
241 CounterBitmap.data());
243 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
244 PrintStats("pulse ", NewCoverage);
246 if (NewCoverage > OldCoverage || NumNewBits)
251 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
252 if (Options.OutputCorpus.empty()) return;
253 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
254 WriteToFile(U, Path);
255 if (Options.Verbosity >= 2)
256 Printf("Written to %s\n", Path.c_str());
258 if (Options.OnlyASCII)
260 assert(isprint(X) || isspace(X));
264 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
265 std::string Path = Prefix + Hash(U);
266 WriteToFile(U, Path);
267 Printf("Test unit written to %s\n", Path.c_str());
268 if (U.size() <= kMaxUnitSizeToPrint) {
270 PrintFileAsBase64(Path);
274 void Fuzzer::SaveCorpus() {
275 if (Options.OutputCorpus.empty()) return;
276 for (const auto &U : Corpus)
277 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
278 if (Options.Verbosity)
279 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
280 Options.OutputCorpus.c_str());
283 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
284 if (!NewCoverage) return;
286 UnitHashesAddedToCorpus.insert(Hash(U));
287 PrintStats("NEW ", NewCoverage, "");
288 if (Options.Verbosity) {
289 Printf(" L: %zd", U.size());
292 PrintUnitInASCIIOrTokens(U, "\t");
297 WriteToOutputCorpus(U);
298 if (Options.ExitOnFirst)
302 void Fuzzer::MutateAndTestOne(Unit *U) {
303 for (int i = 0; i < Options.MutateDepth; i++) {
304 StartTraceRecording();
305 size_t Size = U->size();
306 U->resize(Options.MaxLen);
307 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
308 assert(NewSize > 0 && "Mutator returned empty unit");
309 assert(NewSize <= (size_t)Options.MaxLen &&
310 "Mutator return overisized unit");
312 RunOneAndUpdateCorpus(*U);
313 size_t NumTraceBasedMutations = StopTraceRecording();
314 for (size_t j = 0; j < NumTraceBasedMutations; j++) {
315 ApplyTraceBasedMutation(j, U);
316 RunOneAndUpdateCorpus(*U);
321 void Fuzzer::Loop(size_t NumIterations) {
322 for (size_t i = 1; i <= NumIterations; i++) {
323 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
325 RereadOutputCorpus();
326 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
328 // First, simply mutate the unit w/o doing crosses.
329 CurrentUnit = Corpus[J1];
330 MutateAndTestOne(&CurrentUnit);
331 // Now, cross with others.
332 if (Options.DoCrossOver && !Corpus[J1].empty()) {
333 for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
334 CurrentUnit.resize(Options.MaxLen);
335 size_t NewSize = USF.CrossOver(
336 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
337 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
338 assert(NewSize > 0 && "CrossOver returned empty unit");
339 assert(NewSize <= (size_t)Options.MaxLen &&
340 "CrossOver return overisized unit");
341 CurrentUnit.resize(NewSize);
342 MutateAndTestOne(&CurrentUnit);
349 void Fuzzer::SyncCorpus() {
350 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
351 auto Now = system_clock::now();
352 if (duration_cast<seconds>(Now - LastExternalSync).count() <
355 LastExternalSync = Now;
356 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
359 } // namespace fuzzer