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>
18 // Only one Fuzzer per process.
21 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
22 : USF(USF), Options(Options) {
24 InitializeTraceState();
29 void Fuzzer::SetDeathCallback() {
30 __sanitizer_set_death_callback(StaticDeathCallback);
33 void Fuzzer::PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter) {
34 if (Options.Tokens.empty()) {
35 PrintASCII(U, PrintAfter);
37 auto T = SubstituteTokens(U);
39 Printf("%s%s", T.data(), PrintAfter);
43 void Fuzzer::StaticDeathCallback() {
48 void Fuzzer::DeathCallback() {
50 Print(CurrentUnit, "\n");
51 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
52 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
55 void Fuzzer::StaticAlarmCallback() {
60 void Fuzzer::AlarmCallback() {
61 assert(Options.UnitTimeoutSec > 0);
63 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
64 if (Seconds == 0) return;
65 if (Options.Verbosity >= 2)
66 Printf("AlarmCallback %zd\n", Seconds);
67 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
68 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
69 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
70 Options.UnitTimeoutSec);
71 Print(CurrentUnit, "\n");
72 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
73 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
78 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
79 if (!Options.Verbosity) return;
80 size_t Seconds = secondsSinceProcessStartUp();
81 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
82 Printf("#%zd\t%s cov %zd bits %zd units %zd exec/s %zd %s", TotalNumberOfRuns,
83 Where, Cov, TotalBits(), Corpus.size(), ExecPerSec, End);
86 void Fuzzer::RereadOutputCorpus() {
87 if (Options.OutputCorpus.empty()) return;
88 std::vector<Unit> AdditionalCorpus;
89 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
90 &EpochOfLastReadOfOutputCorpus);
92 Corpus = AdditionalCorpus;
95 if (!Options.Reload) return;
96 if (Options.Verbosity >= 2)
97 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
98 for (auto &X : AdditionalCorpus) {
99 if (X.size() > (size_t)Options.MaxLen)
100 X.resize(Options.MaxLen);
101 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
103 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
104 size_t NewCoverage = RunOne(CurrentUnit);
107 if (Options.Verbosity >= 1)
108 PrintStats("RELOAD", NewCoverage);
114 void Fuzzer::ShuffleAndMinimize() {
116 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
117 (Options.PreferSmallDuringInitialShuffle == -1 &&
118 USF.GetRand().RandBool()));
119 if (Options.Verbosity)
120 Printf("PreferSmall: %d\n", PreferSmall);
121 PrintStats("READ ", 0);
122 std::vector<Unit> NewCorpus;
123 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
126 Corpus.begin(), Corpus.end(),
127 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
128 Unit &U = CurrentUnit;
129 for (const auto &C : Corpus) {
130 for (size_t First = 0; First < 1; First++) {
132 size_t Last = std::min(First + Options.MaxLen, C.size());
133 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
134 size_t NewCoverage = RunOne(U);
136 MaxCov = NewCoverage;
137 NewCorpus.push_back(U);
138 if (Options.Verbosity >= 2)
139 Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
144 for (auto &X : Corpus)
145 UnitHashesAddedToCorpus.insert(Hash(X));
146 PrintStats("INITED", MaxCov);
149 size_t Fuzzer::RunOne(const Unit &U) {
150 UnitStartTime = system_clock::now();
153 if (Options.UseFullCoverageSet)
154 Res = RunOneMaximizeFullCoverageSet(U);
156 Res = RunOneMaximizeTotalCoverage(U);
157 auto UnitStopTime = system_clock::now();
159 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
160 if (TimeOfUnit > TimeOfLongestUnitInSeconds) {
161 TimeOfLongestUnitInSeconds = TimeOfUnit;
162 Printf("Longest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
164 WriteUnitToFileWithPrefix(U, "long-running-unit-");
169 void Fuzzer::RunOneAndUpdateCorpus(const Unit &U) {
170 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
172 ReportNewCoverage(RunOne(U), U);
175 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
177 for (uintptr_t i = 0; i < NumPCs; i++) {
178 Res = (Res + PCs[i]) * 7;
183 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
186 if (Idx < Options.Tokens.size()) {
187 std::string Token = Options.Tokens[Idx];
188 Res.insert(Res.end(), Token.begin(), Token.end());
193 // FIXME: Apply DFSan labels.
197 void Fuzzer::ExecuteCallback(const Unit &U) {
198 if (Options.Tokens.empty()) {
199 USF.TargetFunction(U.data(), U.size());
201 auto T = SubstituteTokens(U);
202 USF.TargetFunction(T.data(), T.size());
207 // Fuly reset the current coverage state, run a single unit,
208 // compute a hash function from the full coverage set,
209 // return non-zero if the hash value is new.
210 // This produces tons of new units and as is it's only suitable for small tests,
211 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
212 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
213 __sanitizer_reset_coverage();
216 uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
217 if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
218 return FullCoverageSets.size();
222 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
223 size_t NumCounters = __sanitizer_get_number_of_counters();
224 if (Options.UseCounters) {
225 CounterBitmap.resize(NumCounters);
226 __sanitizer_update_counter_bitset_and_clear_counters(0);
228 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
230 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
231 size_t NumNewBits = 0;
232 if (Options.UseCounters)
233 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
234 CounterBitmap.data());
236 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
237 PrintStats("pulse ", NewCoverage);
239 if (NewCoverage > OldCoverage || NumNewBits)
244 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
245 if (Options.OutputCorpus.empty()) return;
246 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
247 WriteToFile(U, Path);
248 if (Options.Verbosity >= 2)
249 Printf("Written to %s\n", Path.c_str());
252 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
253 std::string Path = Prefix + Hash(U);
254 WriteToFile(U, Path);
255 Printf("Test unit written to %s\nBase64: ", Path.c_str());
256 PrintFileAsBase64(Path);
259 void Fuzzer::SaveCorpus() {
260 if (Options.OutputCorpus.empty()) return;
261 for (const auto &U : Corpus)
262 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
263 if (Options.Verbosity)
264 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
265 Options.OutputCorpus.c_str());
268 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
269 if (!NewCoverage) return;
271 UnitHashesAddedToCorpus.insert(Hash(U));
272 PrintStats("NEW ", NewCoverage, "");
273 if (Options.Verbosity) {
274 Printf(" L: %zd", U.size());
277 PrintUnitInASCIIOrTokens(U, "\t");
282 WriteToOutputCorpus(U);
283 if (Options.ExitOnFirst)
287 void Fuzzer::MutateAndTestOne(Unit *U) {
288 for (int i = 0; i < Options.MutateDepth; i++) {
289 StartTraceRecording();
290 size_t Size = U->size();
291 U->resize(Options.MaxLen);
292 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
293 assert(NewSize > 0 && "Mutator returned empty unit");
294 assert(NewSize <= (size_t)Options.MaxLen &&
295 "Mutator return overisized unit");
297 RunOneAndUpdateCorpus(*U);
298 size_t NumTraceBasedMutations = StopTraceRecording();
299 for (size_t j = 0; j < NumTraceBasedMutations; j++) {
300 ApplyTraceBasedMutation(j, U);
301 RunOneAndUpdateCorpus(*U);
306 void Fuzzer::Loop(size_t NumIterations) {
307 for (size_t i = 1; i <= NumIterations; i++) {
308 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
310 RereadOutputCorpus();
311 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
313 // First, simply mutate the unit w/o doing crosses.
314 CurrentUnit = Corpus[J1];
315 MutateAndTestOne(&CurrentUnit);
316 // Now, cross with others.
317 if (Options.DoCrossOver && !Corpus[J1].empty()) {
318 for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
319 CurrentUnit.resize(Options.MaxLen);
320 size_t NewSize = USF.CrossOver(
321 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
322 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
323 assert(NewSize > 0 && "CrossOver returned empty unit");
324 assert(NewSize <= (size_t)Options.MaxLen &&
325 "CrossOver return overisized unit");
326 CurrentUnit.resize(NewSize);
327 MutateAndTestOne(&CurrentUnit);
334 void Fuzzer::SyncCorpus() {
335 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
336 auto Now = system_clock::now();
337 if (duration_cast<seconds>(Now - LastExternalSync).count() <
340 LastExternalSync = Now;
341 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
344 } // namespace fuzzer