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",
85 TotalNumberOfRuns, Where, Cov, TotalBits(), Corpus.size(), ExecPerSec);
86 if (TotalNumberOfExecutedTraceBasedMutations)
87 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
91 void Fuzzer::RereadOutputCorpus() {
92 if (Options.OutputCorpus.empty()) return;
93 std::vector<Unit> AdditionalCorpus;
94 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
95 &EpochOfLastReadOfOutputCorpus);
97 Corpus = AdditionalCorpus;
100 if (!Options.Reload) return;
101 if (Options.Verbosity >= 2)
102 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
103 for (auto &X : AdditionalCorpus) {
104 if (X.size() > (size_t)Options.MaxLen)
105 X.resize(Options.MaxLen);
106 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
108 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
109 size_t NewCoverage = RunOne(CurrentUnit);
112 if (Options.Verbosity >= 1)
113 PrintStats("RELOAD", NewCoverage);
119 void Fuzzer::ShuffleAndMinimize() {
121 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
122 (Options.PreferSmallDuringInitialShuffle == -1 &&
123 USF.GetRand().RandBool()));
124 if (Options.Verbosity)
125 Printf("PreferSmall: %d\n", PreferSmall);
126 PrintStats("READ ", 0);
127 std::vector<Unit> NewCorpus;
128 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
131 Corpus.begin(), Corpus.end(),
132 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
133 Unit &U = CurrentUnit;
134 for (const auto &C : Corpus) {
135 for (size_t First = 0; First < 1; First++) {
137 size_t Last = std::min(First + Options.MaxLen, C.size());
138 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
139 size_t NewCoverage = RunOne(U);
141 MaxCov = NewCoverage;
142 NewCorpus.push_back(U);
143 if (Options.Verbosity >= 2)
144 Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
149 for (auto &X : Corpus)
150 UnitHashesAddedToCorpus.insert(Hash(X));
151 PrintStats("INITED", MaxCov);
154 size_t Fuzzer::RunOne(const Unit &U) {
155 UnitStartTime = system_clock::now();
158 if (Options.UseFullCoverageSet)
159 Res = RunOneMaximizeFullCoverageSet(U);
161 Res = RunOneMaximizeTotalCoverage(U);
162 auto UnitStopTime = system_clock::now();
164 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
165 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
166 TimeOfUnit >= Options.ReportSlowUnits) {
167 TimeOfLongestUnitInSeconds = TimeOfUnit;
168 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
169 if (U.size() <= kMaxUnitSizeToPrint)
171 WriteUnitToFileWithPrefix(U, "slow-unit-");
176 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
177 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
179 if (Options.OnlyASCII)
181 ReportNewCoverage(RunOne(U), U);
184 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
186 for (uintptr_t i = 0; i < NumPCs; i++) {
187 Res = (Res + PCs[i]) * 7;
192 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
195 if (Idx < Options.Tokens.size()) {
196 std::string Token = Options.Tokens[Idx];
197 Res.insert(Res.end(), Token.begin(), Token.end());
202 // FIXME: Apply DFSan labels.
206 void Fuzzer::ExecuteCallback(const Unit &U) {
207 if (Options.Tokens.empty()) {
208 USF.TargetFunction(U.data(), U.size());
210 auto T = SubstituteTokens(U);
211 USF.TargetFunction(T.data(), T.size());
216 // Fuly reset the current coverage state, run a single unit,
217 // compute a hash function from the full coverage set,
218 // return non-zero if the hash value is new.
219 // This produces tons of new units and as is it's only suitable for small tests,
220 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
221 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
222 __sanitizer_reset_coverage();
225 uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
226 if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
227 return FullCoverageSets.size();
231 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
232 size_t NumCounters = __sanitizer_get_number_of_counters();
233 if (Options.UseCounters) {
234 CounterBitmap.resize(NumCounters);
235 __sanitizer_update_counter_bitset_and_clear_counters(0);
237 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
239 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
240 size_t NumNewBits = 0;
241 if (Options.UseCounters)
242 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
243 CounterBitmap.data());
245 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
246 PrintStats("pulse ", NewCoverage);
248 if (NewCoverage > OldCoverage || NumNewBits)
253 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
254 if (Options.OutputCorpus.empty()) return;
255 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
256 WriteToFile(U, Path);
257 if (Options.Verbosity >= 2)
258 Printf("Written to %s\n", Path.c_str());
260 if (Options.OnlyASCII)
262 assert(isprint(X) || isspace(X));
266 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
267 std::string Path = Prefix + Hash(U);
268 WriteToFile(U, Path);
269 Printf("Test unit written to %s\n", Path.c_str());
270 if (U.size() <= kMaxUnitSizeToPrint) {
272 PrintFileAsBase64(Path);
276 void Fuzzer::SaveCorpus() {
277 if (Options.OutputCorpus.empty()) return;
278 for (const auto &U : Corpus)
279 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
280 if (Options.Verbosity)
281 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
282 Options.OutputCorpus.c_str());
285 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
286 if (!NewCoverage) return;
288 UnitHashesAddedToCorpus.insert(Hash(U));
289 PrintStats("NEW ", NewCoverage, "");
290 if (Options.Verbosity) {
291 Printf(" L: %zd", U.size());
294 PrintUnitInASCIIOrTokens(U, "\t");
299 WriteToOutputCorpus(U);
300 if (Options.ExitOnFirst)
304 void Fuzzer::MutateAndTestOne(Unit *U) {
305 for (int i = 0; i < Options.MutateDepth; i++) {
306 StartTraceRecording();
307 size_t Size = U->size();
308 U->resize(Options.MaxLen);
309 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
310 assert(NewSize > 0 && "Mutator returned empty unit");
311 assert(NewSize <= (size_t)Options.MaxLen &&
312 "Mutator return overisized unit");
314 RunOneAndUpdateCorpus(*U);
315 size_t NumTraceBasedMutations = StopTraceRecording();
317 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
319 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
321 for (size_t w = 0; w < TBMWidth; w++) {
323 for (size_t d = 0; d < TBMDepth; d++) {
324 TotalNumberOfExecutedTraceBasedMutations++;
325 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
326 RunOneAndUpdateCorpus(*U);
332 void Fuzzer::Loop(size_t NumIterations) {
333 for (size_t i = 1; i <= NumIterations; i++) {
334 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
336 RereadOutputCorpus();
337 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
339 // First, simply mutate the unit w/o doing crosses.
340 CurrentUnit = Corpus[J1];
341 MutateAndTestOne(&CurrentUnit);
342 // Now, cross with others.
343 if (Options.DoCrossOver && !Corpus[J1].empty()) {
344 for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
345 CurrentUnit.resize(Options.MaxLen);
346 size_t NewSize = USF.CrossOver(
347 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
348 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
349 assert(NewSize > 0 && "CrossOver returned empty unit");
350 assert(NewSize <= (size_t)Options.MaxLen &&
351 "CrossOver return overisized unit");
352 CurrentUnit.resize(NewSize);
353 MutateAndTestOne(&CurrentUnit);
360 void Fuzzer::SyncCorpus() {
361 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
362 auto Now = system_clock::now();
363 if (duration_cast<seconds>(Now - LastExternalSync).count() <
366 LastExternalSync = Now;
367 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
370 } // namespace fuzzer