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 if (Options.OnlyASCII)
141 size_t NewCoverage = RunOne(U);
143 MaxCov = NewCoverage;
144 NewCorpus.push_back(U);
145 if (Options.Verbosity >= 2)
146 Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
151 for (auto &X : Corpus)
152 UnitHashesAddedToCorpus.insert(Hash(X));
153 PrintStats("INITED", MaxCov);
156 size_t Fuzzer::RunOne(const Unit &U) {
157 UnitStartTime = system_clock::now();
160 if (Options.UseFullCoverageSet)
161 Res = RunOneMaximizeFullCoverageSet(U);
163 Res = RunOneMaximizeTotalCoverage(U);
164 auto UnitStopTime = system_clock::now();
166 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
167 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
168 TimeOfUnit >= Options.ReportSlowUnits) {
169 TimeOfLongestUnitInSeconds = TimeOfUnit;
170 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
171 if (U.size() <= kMaxUnitSizeToPrint)
173 WriteUnitToFileWithPrefix(U, "slow-unit-");
178 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
179 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
181 if (Options.OnlyASCII)
183 ReportNewCoverage(RunOne(U), U);
186 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
188 for (uintptr_t i = 0; i < NumPCs; i++) {
189 Res = (Res + PCs[i]) * 7;
194 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
197 if (Idx < Options.Tokens.size()) {
198 std::string Token = Options.Tokens[Idx];
199 Res.insert(Res.end(), Token.begin(), Token.end());
204 // FIXME: Apply DFSan labels.
208 void Fuzzer::ExecuteCallback(const Unit &U) {
209 if (Options.Tokens.empty()) {
210 USF.TargetFunction(U.data(), U.size());
212 auto T = SubstituteTokens(U);
213 USF.TargetFunction(T.data(), T.size());
218 // Fuly reset the current coverage state, run a single unit,
219 // compute a hash function from the full coverage set,
220 // return non-zero if the hash value is new.
221 // This produces tons of new units and as is it's only suitable for small tests,
222 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
223 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
224 __sanitizer_reset_coverage();
227 uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
228 if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
229 return FullCoverageSets.size();
233 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
234 size_t NumCounters = __sanitizer_get_number_of_counters();
235 if (Options.UseCounters) {
236 CounterBitmap.resize(NumCounters);
237 __sanitizer_update_counter_bitset_and_clear_counters(0);
239 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
241 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
242 size_t NumNewBits = 0;
243 if (Options.UseCounters)
244 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
245 CounterBitmap.data());
247 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
248 PrintStats("pulse ", NewCoverage);
250 if (NewCoverage > OldCoverage || NumNewBits)
255 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
256 if (Options.OutputCorpus.empty()) return;
257 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
258 WriteToFile(U, Path);
259 if (Options.Verbosity >= 2)
260 Printf("Written to %s\n", Path.c_str());
261 assert(!Options.OnlyASCII || IsASCII(U));
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();
315 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
317 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
319 for (size_t w = 0; w < TBMWidth; w++) {
321 for (size_t d = 0; d < TBMDepth; d++) {
322 TotalNumberOfExecutedTraceBasedMutations++;
323 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
324 RunOneAndUpdateCorpus(*U);
330 void Fuzzer::Loop() {
331 for (auto &U: Options.Dictionary)
332 USF.GetMD().AddWordToDictionary(U.data(), U.size());
335 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
337 RereadOutputCorpus();
338 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
340 CurrentUnit = Corpus[J1];
341 // Optionally, cross with another unit.
342 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
343 size_t J2 = USF.GetRand()(Corpus.size());
344 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
345 assert(!Corpus[J2].empty());
346 CurrentUnit.resize(Options.MaxLen);
347 size_t NewSize = USF.CrossOver(
348 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
349 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
350 assert(NewSize > 0 && "CrossOver returned empty unit");
351 assert(NewSize <= (size_t)Options.MaxLen &&
352 "CrossOver returned overisized unit");
353 CurrentUnit.resize(NewSize);
356 // Perform several mutations and runs.
357 MutateAndTestOne(&CurrentUnit);
362 void Fuzzer::SyncCorpus() {
363 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
364 auto Now = system_clock::now();
365 if (duration_cast<seconds>(Now - LastExternalSync).count() <
368 LastExternalSync = Now;
369 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
372 } // namespace fuzzer