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