[lib/Fuzzer] use -fsanitize-coverage=trace-cmp when building LLVM with LLVM_USE_SANIT...
[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   InitializeDFSan();
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 (UnitsAddedAfterInitialLoad.insert(X).second) {
103       Corpus.push_back(X);
104       CurrentUnit.clear();
105       CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
106       size_t NewCoverage = RunOne(CurrentUnit);
107       if (NewCoverage && Options.Verbosity >= 1)
108         PrintStats("RELOAD", NewCoverage);
109     }
110   }
111 }
112
113 void Fuzzer::ShuffleAndMinimize() {
114   size_t MaxCov = 0;
115   bool PreferSmall =
116       (Options.PreferSmallDuringInitialShuffle == 1 ||
117        (Options.PreferSmallDuringInitialShuffle == -1 && rand() % 2));
118   if (Options.Verbosity)
119     std::cerr << "PreferSmall: " << PreferSmall << "\n";
120   PrintStats("READ  ", 0);
121   std::vector<Unit> NewCorpus;
122   std::random_shuffle(Corpus.begin(), Corpus.end());
123   if (PreferSmall)
124     std::stable_sort(
125         Corpus.begin(), Corpus.end(),
126         [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
127   Unit &U = CurrentUnit;
128   for (const auto &C : Corpus) {
129     for (size_t First = 0; First < 1; First++) {
130       U.clear();
131       size_t Last = std::min(First + Options.MaxLen, C.size());
132       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
133       size_t NewCoverage = RunOne(U);
134       if (NewCoverage) {
135         MaxCov = NewCoverage;
136         NewCorpus.push_back(U);
137         if (Options.Verbosity >= 2)
138           std::cerr << "NEW0: " << NewCoverage
139                     << " L " << U.size()
140                     << "\n";
141       }
142     }
143   }
144   Corpus = NewCorpus;
145   PrintStats("INITED", MaxCov);
146 }
147
148 size_t Fuzzer::RunOne(const Unit &U) {
149   UnitStartTime = system_clock::now();
150   TotalNumberOfRuns++;
151   size_t Res = 0;
152   if (Options.UseFullCoverageSet)
153     Res = RunOneMaximizeFullCoverageSet(U);
154   else if (Options.UseCoveragePairs)
155     Res = RunOneMaximizeCoveragePairs(U);
156   else
157     Res = RunOneMaximizeTotalCoverage(U);
158   auto UnitStopTime = system_clock::now();
159   auto TimeOfUnit =
160       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
161   if (TimeOfUnit > TimeOfLongestUnitInSeconds) {
162     TimeOfLongestUnitInSeconds = TimeOfUnit;
163     std::cerr << "Longest unit: " << TimeOfLongestUnitInSeconds
164               << " s:\n";
165     Print(U, "\n");
166   }
167   return Res;
168 }
169
170 void Fuzzer::RunOneAndUpdateCorpus(const Unit &U) {
171   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
172     return;
173   ReportNewCoverage(RunOne(U), U);
174 }
175
176 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
177   uintptr_t Res = 0;
178   for (uintptr_t i = 0; i < NumPCs; i++) {
179     Res = (Res + PCs[i]) * 7;
180   }
181   return Res;
182 }
183
184 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
185   Unit Res;
186   for (auto Idx : U) {
187     if (Idx < Options.Tokens.size()) {
188       std::string Token = Options.Tokens[Idx];
189       Res.insert(Res.end(), Token.begin(), Token.end());
190     } else {
191       Res.push_back(' ');
192     }
193   }
194   // FIXME: Apply DFSan labels.
195   return Res;
196 }
197
198 void Fuzzer::ExecuteCallback(const Unit &U) {
199   if (Options.Tokens.empty()) {
200     Callback(U.data(), U.size());
201   } else {
202     auto T = SubstituteTokens(U);
203     Callback(T.data(), T.size());
204   }
205 }
206
207 // Experimental. Does not yet scale.
208 // Fuly reset the current coverage state, run a single unit,
209 // collect all coverage pairs and return non-zero if a new pair is observed.
210 size_t Fuzzer::RunOneMaximizeCoveragePairs(const Unit &U) {
211   __sanitizer_reset_coverage();
212   ExecuteCallback(U);
213   uintptr_t *PCs;
214   uintptr_t NumPCs = __sanitizer_get_coverage_guards(&PCs);
215   bool HasNewPairs = false;
216   for (uintptr_t i = 0; i < NumPCs; i++) {
217     if (!PCs[i]) continue;
218     for (uintptr_t j = 0; j < NumPCs; j++) {
219       if (!PCs[j]) continue;
220       uint64_t Pair = (i << 32) | j;
221       HasNewPairs |= CoveragePairs.insert(Pair).second;
222     }
223   }
224   if (HasNewPairs)
225     return CoveragePairs.size();
226   return 0;
227 }
228
229 // Experimental.
230 // Fuly reset the current coverage state, run a single unit,
231 // compute a hash function from the full coverage set,
232 // return non-zero if the hash value is new.
233 // This produces tons of new units and as is it's only suitable for small tests,
234 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
235 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
236   __sanitizer_reset_coverage();
237   ExecuteCallback(U);
238   uintptr_t *PCs;
239   uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
240   if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
241     return FullCoverageSets.size();
242   return 0;
243 }
244
245 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
246   size_t NumCounters = __sanitizer_get_number_of_counters();
247   if (Options.UseCounters) {
248     CounterBitmap.resize(NumCounters);
249     __sanitizer_update_counter_bitset_and_clear_counters(0);
250   }
251   size_t OldCoverage = __sanitizer_get_total_unique_coverage();
252   ExecuteCallback(U);
253   size_t NewCoverage = __sanitizer_get_total_unique_coverage();
254   size_t NumNewBits = 0;
255   if (Options.UseCounters)
256     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
257         CounterBitmap.data());
258
259   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
260     PrintStats("pulse ", NewCoverage);
261
262   if (NewCoverage > OldCoverage || NumNewBits)
263     return NewCoverage;
264   return 0;
265 }
266
267 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
268   if (Options.OutputCorpus.empty()) return;
269   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
270   WriteToFile(U, Path);
271   if (Options.Verbosity >= 2)
272     std::cerr << "Written to " << Path << std::endl;
273 }
274
275 void Fuzzer::WriteToCrash(const Unit &U, const char *Prefix) {
276   std::string Path = Prefix + Hash(U);
277   WriteToFile(U, Path);
278   std::cerr << "CRASHED; file written to " << Path << std::endl;
279   std::cerr << "Base64: ";
280   PrintFileAsBase64(Path);
281 }
282
283 void Fuzzer::SaveCorpus() {
284   if (Options.OutputCorpus.empty()) return;
285   for (const auto &U : Corpus)
286     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
287   if (Options.Verbosity)
288     std::cerr << "Written corpus of " << Corpus.size() << " files to "
289               << Options.OutputCorpus << "\n";
290 }
291
292 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
293   if (!NewCoverage) return;
294   Corpus.push_back(U);
295   UnitsAddedAfterInitialLoad.insert(U);
296   PrintStats("NEW   ", NewCoverage, "");
297   if (Options.Verbosity) {
298     std::cerr << " L: " << U.size();
299     if (U.size() < 30) {
300       std::cerr << " ";
301       PrintUnitInASCIIOrTokens(U, "\t");
302       Print(U);
303     }
304     std::cerr << "\n";
305   }
306   WriteToOutputCorpus(U);
307   if (Options.ExitOnFirst)
308     exit(0);
309 }
310
311 void Fuzzer::MutateAndTestOne(Unit *U) {
312   for (int i = 0; i < Options.MutateDepth; i++) {
313     StartTraceRecording();
314     Mutate(U, Options.MaxLen);
315     RunOneAndUpdateCorpus(*U);
316     size_t NumTraceBasedMutations = StopTraceRecording();
317     for (size_t j = 0; j < NumTraceBasedMutations; j++) {
318         ApplyTraceBasedMutation(j, U);
319         RunOneAndUpdateCorpus(*U);
320     }
321   }
322 }
323
324 void Fuzzer::Loop(size_t NumIterations) {
325   for (size_t i = 1; i <= NumIterations; i++) {
326     for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
327       RereadOutputCorpus();
328       if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
329         return;
330       // First, simply mutate the unit w/o doing crosses.
331       CurrentUnit = Corpus[J1];
332       MutateAndTestOne(&CurrentUnit);
333       // Now, cross with others.
334       if (Options.DoCrossOver) {
335         for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
336           CurrentUnit.clear();
337           CrossOver(Corpus[J1], Corpus[J2], &CurrentUnit, Options.MaxLen);
338           MutateAndTestOne(&CurrentUnit);
339         }
340       }
341     }
342   }
343 }
344
345 }  // namespace fuzzer