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 = 256;
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 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
52 Print(CurrentUnit, "\n");
53 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
55 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
58 void Fuzzer::StaticAlarmCallback() {
63 void Fuzzer::AlarmCallback() {
64 assert(Options.UnitTimeoutSec > 0);
66 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
67 if (Seconds == 0) return;
68 if (Options.Verbosity >= 2)
69 Printf("AlarmCallback %zd\n", Seconds);
70 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
71 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
72 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
73 Options.UnitTimeoutSec);
74 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
75 Print(CurrentUnit, "\n");
76 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
78 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
83 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
84 if (!Options.Verbosity) return;
85 size_t Seconds = secondsSinceProcessStartUp();
86 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
87 Printf("#%zd\t%s cov: %zd bits: %zd units: %zd exec/s: %zd",
88 TotalNumberOfRuns, Where, Cov, TotalBits(), Corpus.size(), ExecPerSec);
89 if (TotalNumberOfExecutedTraceBasedMutations)
90 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
94 void Fuzzer::RereadOutputCorpus() {
95 if (Options.OutputCorpus.empty()) return;
96 std::vector<Unit> AdditionalCorpus;
97 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
98 &EpochOfLastReadOfOutputCorpus);
100 Corpus = AdditionalCorpus;
103 if (!Options.Reload) return;
104 if (Options.Verbosity >= 2)
105 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
106 for (auto &X : AdditionalCorpus) {
107 if (X.size() > (size_t)Options.MaxLen)
108 X.resize(Options.MaxLen);
109 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
111 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
112 size_t NewCoverage = RunOne(CurrentUnit);
115 if (Options.Verbosity >= 1)
116 PrintStats("RELOAD", NewCoverage);
122 void Fuzzer::ShuffleAndMinimize() {
124 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
125 (Options.PreferSmallDuringInitialShuffle == -1 &&
126 USF.GetRand().RandBool()));
127 if (Options.Verbosity)
128 Printf("PreferSmall: %d\n", PreferSmall);
129 PrintStats("READ ", 0);
130 std::vector<Unit> NewCorpus;
131 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
134 Corpus.begin(), Corpus.end(),
135 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
136 Unit &U = CurrentUnit;
137 for (const auto &C : Corpus) {
138 for (size_t First = 0; First < 1; First++) {
140 size_t Last = std::min(First + Options.MaxLen, C.size());
141 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
142 if (Options.OnlyASCII)
144 size_t NewCoverage = RunOne(U);
146 MaxCov = NewCoverage;
147 NewCorpus.push_back(U);
148 if (Options.Verbosity >= 2)
149 Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
154 for (auto &X : Corpus)
155 UnitHashesAddedToCorpus.insert(Hash(X));
156 PrintStats("INITED", MaxCov);
159 size_t Fuzzer::RunOne(const Unit &U) {
160 UnitStartTime = system_clock::now();
162 size_t Res = RunOneMaximizeTotalCoverage(U);
163 auto UnitStopTime = system_clock::now();
165 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
166 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
167 TimeOfUnit >= Options.ReportSlowUnits) {
168 TimeOfLongestUnitInSeconds = TimeOfUnit;
169 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
170 WriteUnitToFileWithPrefix(U, "slow-unit-");
175 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
176 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
178 if (Options.OnlyASCII)
180 ReportNewCoverage(RunOne(U), U);
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) {
199 if (Options.Tokens.empty()) {
200 Res = USF.TargetFunction(U.data(), U.size());
202 auto T = SubstituteTokens(U);
203 Res = USF.TargetFunction(T.data(), T.size());
208 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
209 size_t NumCounters = __sanitizer_get_number_of_counters();
210 if (Options.UseCounters) {
211 CounterBitmap.resize(NumCounters);
212 __sanitizer_update_counter_bitset_and_clear_counters(0);
214 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
216 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
217 size_t NumNewBits = 0;
218 if (Options.UseCounters)
219 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
220 CounterBitmap.data());
222 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
223 PrintStats("pulse ", NewCoverage);
225 if (NewCoverage > OldCoverage || NumNewBits)
230 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
231 if (Options.OutputCorpus.empty()) return;
232 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
233 WriteToFile(U, Path);
234 if (Options.Verbosity >= 2)
235 Printf("Written to %s\n", Path.c_str());
236 assert(!Options.OnlyASCII || IsASCII(U));
239 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
240 if (!Options.SaveArtifacts)
242 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
243 WriteToFile(U, Path);
244 Printf("artifact_prefix='%s'; Test unit written to %s\n",
245 Options.ArtifactPrefix.c_str(), Path.c_str());
246 if (U.size() <= kMaxUnitSizeToPrint) {
248 PrintFileAsBase64(Path);
252 void Fuzzer::SaveCorpus() {
253 if (Options.OutputCorpus.empty()) return;
254 for (const auto &U : Corpus)
255 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
256 if (Options.Verbosity)
257 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
258 Options.OutputCorpus.c_str());
261 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
262 if (!NewCoverage) return;
264 UnitHashesAddedToCorpus.insert(Hash(U));
265 PrintStats("NEW ", NewCoverage, "");
266 if (Options.Verbosity) {
267 Printf(" L: %zd", U.size());
270 PrintUnitInASCIIOrTokens(U, "\t");
275 WriteToOutputCorpus(U);
276 if (Options.ExitOnFirst)
280 void Fuzzer::MutateAndTestOne(Unit *U) {
281 for (int i = 0; i < Options.MutateDepth; i++) {
282 StartTraceRecording();
283 size_t Size = U->size();
284 U->resize(Options.MaxLen);
285 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
286 assert(NewSize > 0 && "Mutator returned empty unit");
287 assert(NewSize <= (size_t)Options.MaxLen &&
288 "Mutator return overisized unit");
290 RunOneAndUpdateCorpus(*U);
291 size_t NumTraceBasedMutations = StopTraceRecording();
293 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
295 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
297 for (size_t w = 0; w < TBMWidth; w++) {
299 for (size_t d = 0; d < TBMDepth; d++) {
300 TotalNumberOfExecutedTraceBasedMutations++;
301 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
302 RunOneAndUpdateCorpus(*U);
308 void Fuzzer::Loop() {
309 for (auto &U: Options.Dictionary)
310 USF.GetMD().AddWordToDictionary(U.data(), U.size());
313 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
315 RereadOutputCorpus();
316 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
318 if (Options.MaxTotalTimeSec > 0 &&
319 secondsSinceProcessStartUp() >
320 static_cast<size_t>(Options.MaxTotalTimeSec))
322 CurrentUnit = Corpus[J1];
323 // Optionally, cross with another unit.
324 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
325 size_t J2 = USF.GetRand()(Corpus.size());
326 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
327 assert(!Corpus[J2].empty());
328 CurrentUnit.resize(Options.MaxLen);
329 size_t NewSize = USF.CrossOver(
330 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
331 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
332 assert(NewSize > 0 && "CrossOver returned empty unit");
333 assert(NewSize <= (size_t)Options.MaxLen &&
334 "CrossOver returned overisized unit");
335 CurrentUnit.resize(NewSize);
338 // Perform several mutations and runs.
339 MutateAndTestOne(&CurrentUnit);
344 void Fuzzer::SyncCorpus() {
345 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
346 auto Now = system_clock::now();
347 if (duration_cast<seconds>(Now - LastExternalSync).count() <
350 LastExternalSync = Now;
351 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
354 } // namespace fuzzer