[lib/Fuzzer] fully get rid of std::cerr in libFuzzer
[oota-llvm.git] / lib / Fuzzer / FuzzerLoop.cpp
1 //===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // Fuzzer's main loop.
10 //===----------------------------------------------------------------------===//
11
12 #include "FuzzerInternal.h"
13 #include <sanitizer/coverage_interface.h>
14 #include <algorithm>
15
16 namespace fuzzer {
17
18 // Only one Fuzzer per process.
19 static Fuzzer *F;
20
21 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
22     : USF(USF), Options(Options) {
23   SetDeathCallback();
24   InitializeTraceState();
25   assert(!F);
26   F = this;
27 }
28
29 void Fuzzer::SetDeathCallback() {
30   __sanitizer_set_death_callback(StaticDeathCallback);
31 }
32
33 void Fuzzer::PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter) {
34   if (Options.Tokens.empty()) {
35     PrintASCII(U, PrintAfter);
36   } else {
37     auto T = SubstituteTokens(U);
38     T.push_back(0);
39     Printf("%s%s", T.data(), PrintAfter);
40   }
41 }
42
43 void Fuzzer::StaticDeathCallback() {
44   assert(F);
45   F->DeathCallback();
46 }
47
48 void Fuzzer::DeathCallback() {
49   Printf("DEATH:\n");
50   Print(CurrentUnit, "\n");
51   PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
52   WriteToCrash(CurrentUnit, "crash-");
53 }
54
55 void Fuzzer::StaticAlarmCallback() {
56   assert(F);
57   F->AlarmCallback();
58 }
59
60 void Fuzzer::AlarmCallback() {
61   assert(Options.UnitTimeoutSec > 0);
62   size_t Seconds =
63       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
64   if (Seconds == 0) return;
65   if (Options.Verbosity >= 2)
66     Printf("AlarmCallback %zd\n", Seconds);
67   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
68     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
69     Print(CurrentUnit, "\n");
70     PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
71     WriteToCrash(CurrentUnit, "timeout-");
72     exit(1);
73   }
74 }
75
76 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
77   if (!Options.Verbosity) return;
78   size_t Seconds = secondsSinceProcessStartUp();
79   size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
80   Printf("#%zd\t%s cov %zd bits %zd units %zd exec/s %zd %s", TotalNumberOfRuns,
81          Where, Cov, TotalBits(), Corpus.size(), ExecPerSec, End);
82 }
83
84 void Fuzzer::RereadOutputCorpus() {
85   if (Options.OutputCorpus.empty()) return;
86   std::vector<Unit> AdditionalCorpus;
87   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
88                          &EpochOfLastReadOfOutputCorpus);
89   if (Corpus.empty()) {
90     Corpus = AdditionalCorpus;
91     return;
92   }
93   if (!Options.Reload) return;
94   if (Options.Verbosity >= 2)
95     Printf("Reload: read %zd new units.\n",  AdditionalCorpus.size());
96   for (auto &X : AdditionalCorpus) {
97     if (X.size() > (size_t)Options.MaxLen)
98       X.resize(Options.MaxLen);
99     if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
100       CurrentUnit.clear();
101       CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
102       size_t NewCoverage = RunOne(CurrentUnit);
103       if (NewCoverage) {
104         Corpus.push_back(X);
105         if (Options.Verbosity >= 1)
106           PrintStats("RELOAD", NewCoverage);
107       }
108     }
109   }
110 }
111
112 void Fuzzer::ShuffleAndMinimize() {
113   size_t MaxCov = 0;
114   bool PreferSmall =
115       (Options.PreferSmallDuringInitialShuffle == 1 ||
116        (Options.PreferSmallDuringInitialShuffle == -1 && rand() % 2));
117   if (Options.Verbosity)
118     Printf("PreferSmall: %d\n", PreferSmall);
119   PrintStats("READ  ", 0);
120   std::vector<Unit> NewCorpus;
121   std::random_shuffle(Corpus.begin(), Corpus.end());
122   if (PreferSmall)
123     std::stable_sort(
124         Corpus.begin(), Corpus.end(),
125         [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
126   Unit &U = CurrentUnit;
127   for (const auto &C : Corpus) {
128     for (size_t First = 0; First < 1; First++) {
129       U.clear();
130       size_t Last = std::min(First + Options.MaxLen, C.size());
131       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
132       size_t NewCoverage = RunOne(U);
133       if (NewCoverage) {
134         MaxCov = NewCoverage;
135         NewCorpus.push_back(U);
136         if (Options.Verbosity >= 2)
137           Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
138       }
139     }
140   }
141   Corpus = NewCorpus;
142   for (auto &X : Corpus)
143     UnitHashesAddedToCorpus.insert(Hash(X));
144   PrintStats("INITED", MaxCov);
145 }
146
147 size_t Fuzzer::RunOne(const Unit &U) {
148   UnitStartTime = system_clock::now();
149   TotalNumberOfRuns++;
150   size_t Res = 0;
151   if (Options.UseFullCoverageSet)
152     Res = RunOneMaximizeFullCoverageSet(U);
153   else
154     Res = RunOneMaximizeTotalCoverage(U);
155   auto UnitStopTime = system_clock::now();
156   auto TimeOfUnit =
157       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
158   if (TimeOfUnit > TimeOfLongestUnitInSeconds) {
159     TimeOfLongestUnitInSeconds = TimeOfUnit;
160     Printf("Longest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
161     Print(U, "\n");
162   }
163   return Res;
164 }
165
166 void Fuzzer::RunOneAndUpdateCorpus(const Unit &U) {
167   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
168     return;
169   ReportNewCoverage(RunOne(U), U);
170 }
171
172 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
173   uintptr_t Res = 0;
174   for (uintptr_t i = 0; i < NumPCs; i++) {
175     Res = (Res + PCs[i]) * 7;
176   }
177   return Res;
178 }
179
180 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
181   Unit Res;
182   for (auto Idx : U) {
183     if (Idx < Options.Tokens.size()) {
184       std::string Token = Options.Tokens[Idx];
185       Res.insert(Res.end(), Token.begin(), Token.end());
186     } else {
187       Res.push_back(' ');
188     }
189   }
190   // FIXME: Apply DFSan labels.
191   return Res;
192 }
193
194 void Fuzzer::ExecuteCallback(const Unit &U) {
195   if (Options.Tokens.empty()) {
196     USF.TargetFunction(U.data(), U.size());
197   } else {
198     auto T = SubstituteTokens(U);
199     USF.TargetFunction(T.data(), T.size());
200   }
201 }
202
203 // Experimental.
204 // Fuly reset the current coverage state, run a single unit,
205 // compute a hash function from the full coverage set,
206 // return non-zero if the hash value is new.
207 // This produces tons of new units and as is it's only suitable for small tests,
208 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
209 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
210   __sanitizer_reset_coverage();
211   ExecuteCallback(U);
212   uintptr_t *PCs;
213   uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
214   if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
215     return FullCoverageSets.size();
216   return 0;
217 }
218
219 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
220   size_t NumCounters = __sanitizer_get_number_of_counters();
221   if (Options.UseCounters) {
222     CounterBitmap.resize(NumCounters);
223     __sanitizer_update_counter_bitset_and_clear_counters(0);
224   }
225   size_t OldCoverage = __sanitizer_get_total_unique_coverage();
226   ExecuteCallback(U);
227   size_t NewCoverage = __sanitizer_get_total_unique_coverage();
228   size_t NumNewBits = 0;
229   if (Options.UseCounters)
230     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
231         CounterBitmap.data());
232
233   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
234     PrintStats("pulse ", NewCoverage);
235
236   if (NewCoverage > OldCoverage || NumNewBits)
237     return NewCoverage;
238   return 0;
239 }
240
241 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
242   if (Options.OutputCorpus.empty()) return;
243   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
244   WriteToFile(U, Path);
245   if (Options.Verbosity >= 2)
246     Printf("Written to %s\n", Path.c_str());
247 }
248
249 void Fuzzer::WriteToCrash(const Unit &U, const char *Prefix) {
250   std::string Path = Prefix + Hash(U);
251   WriteToFile(U, Path);
252   Printf("CRASHED; file written to %s\nBase64: ", Path.c_str());
253   PrintFileAsBase64(Path);
254 }
255
256 void Fuzzer::SaveCorpus() {
257   if (Options.OutputCorpus.empty()) return;
258   for (const auto &U : Corpus)
259     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
260   if (Options.Verbosity)
261     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
262            Options.OutputCorpus.c_str());
263 }
264
265 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
266   if (!NewCoverage) return;
267   Corpus.push_back(U);
268   UnitHashesAddedToCorpus.insert(Hash(U));
269   PrintStats("NEW   ", NewCoverage, "");
270   if (Options.Verbosity) {
271     Printf(" L: %zd", U.size());
272     if (U.size() < 30) {
273       Printf(" ");
274       PrintUnitInASCIIOrTokens(U, "\t");
275       Print(U);
276     }
277     Printf("\n");
278   }
279   WriteToOutputCorpus(U);
280   if (Options.ExitOnFirst)
281     exit(0);
282 }
283
284 void Fuzzer::MutateAndTestOne(Unit *U) {
285   for (int i = 0; i < Options.MutateDepth; i++) {
286     StartTraceRecording();
287     size_t Size = U->size();
288     U->resize(Options.MaxLen);
289     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
290     assert(NewSize > 0 && NewSize <= Options.MaxLen);
291     U->resize(NewSize);
292     RunOneAndUpdateCorpus(*U);
293     size_t NumTraceBasedMutations = StopTraceRecording();
294     for (size_t j = 0; j < NumTraceBasedMutations; j++) {
295       ApplyTraceBasedMutation(j, U);
296       RunOneAndUpdateCorpus(*U);
297     }
298   }
299 }
300
301 void Fuzzer::Loop(size_t NumIterations) {
302   for (size_t i = 1; i <= NumIterations; i++) {
303     for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
304       SyncCorpus();
305       RereadOutputCorpus();
306       if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
307         return;
308       // First, simply mutate the unit w/o doing crosses.
309       CurrentUnit = Corpus[J1];
310       MutateAndTestOne(&CurrentUnit);
311       // Now, cross with others.
312       if (Options.DoCrossOver) {
313         for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
314           CurrentUnit.resize(Options.MaxLen);
315           size_t NewSize = USF.CrossOver(
316               Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
317               Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
318           assert(NewSize > 0 && NewSize <= Options.MaxLen);
319           CurrentUnit.resize(NewSize);
320           MutateAndTestOne(&CurrentUnit);
321         }
322       }
323     }
324   }
325 }
326
327 void Fuzzer::SyncCorpus() {
328   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
329   auto Now = system_clock::now();
330   if (duration_cast<seconds>(Now - LastExternalSync).count() <
331       Options.SyncTimeout)
332     return;
333   LastExternalSync = Now;
334   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
335 }
336
337 }  // namespace fuzzer