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