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