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 __attribute__((weak)) void __sanitizer_print_stack_trace();
21 static const size_t kMaxUnitSizeToPrint = 256;
23 // Only one Fuzzer per process.
26 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
27 : USF(USF), Options(Options) {
29 InitializeTraceState();
34 void Fuzzer::SetDeathCallback() {
35 __sanitizer_set_death_callback(StaticDeathCallback);
38 void Fuzzer::PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter) {
39 if (Options.Tokens.empty()) {
40 PrintASCII(U, PrintAfter);
42 auto T = SubstituteTokens(U);
44 Printf("%s%s", T.data(), PrintAfter);
48 void Fuzzer::StaticDeathCallback() {
53 void Fuzzer::DeathCallback() {
55 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
56 Print(CurrentUnit, "\n");
57 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
59 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
62 void Fuzzer::StaticAlarmCallback() {
67 void Fuzzer::AlarmCallback() {
68 assert(Options.UnitTimeoutSec > 0);
70 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
71 if (Seconds == 0) return;
72 if (Options.Verbosity >= 2)
73 Printf("AlarmCallback %zd\n", Seconds);
74 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
75 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
76 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
77 Options.UnitTimeoutSec);
78 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
79 Print(CurrentUnit, "\n");
80 PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
82 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
83 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
85 if (__sanitizer_print_stack_trace)
86 __sanitizer_print_stack_trace();
87 Printf("SUMMARY: libFuzzer: timeout\n");
92 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
93 if (!Options.Verbosity) return;
94 size_t Seconds = secondsSinceProcessStartUp();
95 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
96 Printf("#%zd\t%s cov: %zd bits: %zd units: %zd exec/s: %zd",
97 TotalNumberOfRuns, Where, Cov, TotalBits(), Corpus.size(), ExecPerSec);
98 if (TotalNumberOfExecutedTraceBasedMutations)
99 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
103 void Fuzzer::RereadOutputCorpus() {
104 if (Options.OutputCorpus.empty()) return;
105 std::vector<Unit> AdditionalCorpus;
106 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
107 &EpochOfLastReadOfOutputCorpus);
108 if (Corpus.empty()) {
109 Corpus = AdditionalCorpus;
112 if (!Options.Reload) return;
113 if (Options.Verbosity >= 2)
114 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
115 for (auto &X : AdditionalCorpus) {
116 if (X.size() > (size_t)Options.MaxLen)
117 X.resize(Options.MaxLen);
118 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
120 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
121 size_t NewCoverage = RunOne(CurrentUnit);
124 if (Options.Verbosity >= 1)
125 PrintStats("RELOAD", NewCoverage);
131 void Fuzzer::ShuffleAndMinimize() {
133 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
134 (Options.PreferSmallDuringInitialShuffle == -1 &&
135 USF.GetRand().RandBool()));
136 if (Options.Verbosity)
137 Printf("PreferSmall: %d\n", PreferSmall);
138 PrintStats("READ ", 0);
139 std::vector<Unit> NewCorpus;
140 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
143 Corpus.begin(), Corpus.end(),
144 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
145 Unit &U = CurrentUnit;
146 for (const auto &C : Corpus) {
147 for (size_t First = 0; First < 1; First++) {
149 size_t Last = std::min(First + Options.MaxLen, C.size());
150 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
151 if (Options.OnlyASCII)
153 size_t NewCoverage = RunOne(U);
155 MaxCov = NewCoverage;
156 NewCorpus.push_back(U);
157 if (Options.Verbosity >= 2)
158 Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
163 for (auto &X : Corpus)
164 UnitHashesAddedToCorpus.insert(Hash(X));
165 PrintStats("INITED", MaxCov);
168 size_t Fuzzer::RunOne(const Unit &U) {
169 UnitStartTime = system_clock::now();
171 size_t Res = RunOneMaximizeTotalCoverage(U);
172 auto UnitStopTime = system_clock::now();
174 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
175 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
176 TimeOfUnit >= Options.ReportSlowUnits) {
177 TimeOfLongestUnitInSeconds = TimeOfUnit;
178 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
179 WriteUnitToFileWithPrefix(U, "slow-unit-");
184 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
185 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
187 if (Options.OnlyASCII)
189 ReportNewCoverage(RunOne(U), U);
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) {
208 if (Options.Tokens.empty()) {
209 Res = USF.TargetFunction(U.data(), U.size());
211 auto T = SubstituteTokens(U);
212 Res = USF.TargetFunction(T.data(), T.size());
217 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
218 size_t NumCounters = __sanitizer_get_number_of_counters();
219 if (Options.UseCounters) {
220 CounterBitmap.resize(NumCounters);
221 __sanitizer_update_counter_bitset_and_clear_counters(0);
223 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
225 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
226 size_t NumNewBits = 0;
227 if (Options.UseCounters)
228 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
229 CounterBitmap.data());
231 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
232 PrintStats("pulse ", NewCoverage);
234 if (NewCoverage > OldCoverage || NumNewBits)
239 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
240 if (Options.OutputCorpus.empty()) return;
241 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
242 WriteToFile(U, Path);
243 if (Options.Verbosity >= 2)
244 Printf("Written to %s\n", Path.c_str());
245 assert(!Options.OnlyASCII || IsASCII(U));
248 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
249 if (!Options.SaveArtifacts)
251 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
252 WriteToFile(U, Path);
253 Printf("artifact_prefix='%s'; Test unit written to %s\n",
254 Options.ArtifactPrefix.c_str(), Path.c_str());
255 if (U.size() <= kMaxUnitSizeToPrint) {
257 PrintFileAsBase64(Path);
261 void Fuzzer::SaveCorpus() {
262 if (Options.OutputCorpus.empty()) return;
263 for (const auto &U : Corpus)
264 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
265 if (Options.Verbosity)
266 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
267 Options.OutputCorpus.c_str());
270 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
271 if (!NewCoverage) return;
273 UnitHashesAddedToCorpus.insert(Hash(U));
274 PrintStats("NEW ", NewCoverage, "");
275 if (Options.Verbosity) {
276 Printf(" L: %zd", U.size());
279 PrintUnitInASCIIOrTokens(U, "\t");
284 WriteToOutputCorpus(U);
285 if (Options.ExitOnFirst)
289 void Fuzzer::MutateAndTestOne(Unit *U) {
290 for (int i = 0; i < Options.MutateDepth; i++) {
291 StartTraceRecording();
292 size_t Size = U->size();
293 U->resize(Options.MaxLen);
294 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
295 assert(NewSize > 0 && "Mutator returned empty unit");
296 assert(NewSize <= (size_t)Options.MaxLen &&
297 "Mutator return overisized unit");
299 RunOneAndUpdateCorpus(*U);
300 size_t NumTraceBasedMutations = StopTraceRecording();
302 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
304 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
306 for (size_t w = 0; w < TBMWidth; w++) {
308 for (size_t d = 0; d < TBMDepth; d++) {
309 TotalNumberOfExecutedTraceBasedMutations++;
310 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
311 RunOneAndUpdateCorpus(*U);
317 void Fuzzer::Loop() {
318 for (auto &U: Options.Dictionary)
319 USF.GetMD().AddWordToDictionary(U.data(), U.size());
322 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
324 RereadOutputCorpus();
325 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
327 if (Options.MaxTotalTimeSec > 0 &&
328 secondsSinceProcessStartUp() >
329 static_cast<size_t>(Options.MaxTotalTimeSec))
331 CurrentUnit = Corpus[J1];
332 // Optionally, cross with another unit.
333 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
334 size_t J2 = USF.GetRand()(Corpus.size());
335 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
336 assert(!Corpus[J2].empty());
337 CurrentUnit.resize(Options.MaxLen);
338 size_t NewSize = USF.CrossOver(
339 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
340 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
341 assert(NewSize > 0 && "CrossOver returned empty unit");
342 assert(NewSize <= (size_t)Options.MaxLen &&
343 "CrossOver returned overisized unit");
344 CurrentUnit.resize(NewSize);
347 // Perform several mutations and runs.
348 MutateAndTestOne(&CurrentUnit);
353 void Fuzzer::SyncCorpus() {
354 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
355 auto Now = system_clock::now();
356 if (duration_cast<seconds>(Now - LastExternalSync).count() <
359 LastExternalSync = Now;
360 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
363 } // namespace fuzzer