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