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();
159 size_t 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 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
185 if (Idx < Options.Tokens.size()) {
186 std::string Token = Options.Tokens[Idx];
187 Res.insert(Res.end(), Token.begin(), Token.end());
192 // FIXME: Apply DFSan labels.
196 void Fuzzer::ExecuteCallback(const Unit &U) {
197 if (Options.Tokens.empty()) {
198 USF.TargetFunction(U.data(), U.size());
200 auto T = SubstituteTokens(U);
201 USF.TargetFunction(T.data(), T.size());
205 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
206 size_t NumCounters = __sanitizer_get_number_of_counters();
207 if (Options.UseCounters) {
208 CounterBitmap.resize(NumCounters);
209 __sanitizer_update_counter_bitset_and_clear_counters(0);
211 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
213 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
214 size_t NumNewBits = 0;
215 if (Options.UseCounters)
216 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
217 CounterBitmap.data());
219 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
220 PrintStats("pulse ", NewCoverage);
222 if (NewCoverage > OldCoverage || NumNewBits)
227 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
228 if (Options.OutputCorpus.empty()) return;
229 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
230 WriteToFile(U, Path);
231 if (Options.Verbosity >= 2)
232 Printf("Written to %s\n", Path.c_str());
233 assert(!Options.OnlyASCII || IsASCII(U));
236 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
237 std::string Path = Prefix + Hash(U);
238 WriteToFile(U, Path);
239 Printf("Test unit written to %s\n", Path.c_str());
240 if (U.size() <= kMaxUnitSizeToPrint) {
242 PrintFileAsBase64(Path);
246 void Fuzzer::SaveCorpus() {
247 if (Options.OutputCorpus.empty()) return;
248 for (const auto &U : Corpus)
249 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
250 if (Options.Verbosity)
251 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
252 Options.OutputCorpus.c_str());
255 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
256 if (!NewCoverage) return;
258 UnitHashesAddedToCorpus.insert(Hash(U));
259 PrintStats("NEW ", NewCoverage, "");
260 if (Options.Verbosity) {
261 Printf(" L: %zd", U.size());
264 PrintUnitInASCIIOrTokens(U, "\t");
269 WriteToOutputCorpus(U);
270 if (Options.ExitOnFirst)
274 void Fuzzer::MutateAndTestOne(Unit *U) {
275 for (int i = 0; i < Options.MutateDepth; i++) {
276 StartTraceRecording();
277 size_t Size = U->size();
278 U->resize(Options.MaxLen);
279 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
280 assert(NewSize > 0 && "Mutator returned empty unit");
281 assert(NewSize <= (size_t)Options.MaxLen &&
282 "Mutator return overisized unit");
284 RunOneAndUpdateCorpus(*U);
285 size_t NumTraceBasedMutations = StopTraceRecording();
287 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
289 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
291 for (size_t w = 0; w < TBMWidth; w++) {
293 for (size_t d = 0; d < TBMDepth; d++) {
294 TotalNumberOfExecutedTraceBasedMutations++;
295 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
296 RunOneAndUpdateCorpus(*U);
302 void Fuzzer::Loop() {
303 for (auto &U: Options.Dictionary)
304 USF.GetMD().AddWordToDictionary(U.data(), U.size());
307 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
309 RereadOutputCorpus();
310 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
312 if (Options.MaxTotalTimeSec > 0 &&
313 secondsSinceProcessStartUp() >
314 static_cast<size_t>(Options.MaxTotalTimeSec))
316 CurrentUnit = Corpus[J1];
317 // Optionally, cross with another unit.
318 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
319 size_t J2 = USF.GetRand()(Corpus.size());
320 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
321 assert(!Corpus[J2].empty());
322 CurrentUnit.resize(Options.MaxLen);
323 size_t NewSize = USF.CrossOver(
324 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
325 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
326 assert(NewSize > 0 && "CrossOver returned empty unit");
327 assert(NewSize <= (size_t)Options.MaxLen &&
328 "CrossOver returned overisized unit");
329 CurrentUnit.resize(NewSize);
332 // Perform several mutations and runs.
333 MutateAndTestOne(&CurrentUnit);
338 void Fuzzer::SyncCorpus() {
339 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
340 auto Now = system_clock::now();
341 if (duration_cast<seconds>(Now - LastExternalSync).count() <
344 LastExternalSync = Now;
345 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
348 } // namespace fuzzer