[libFuzzer] actually make the dictionaries work (+docs)
[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",
85          TotalNumberOfRuns, Where, Cov, TotalBits(), Corpus.size(), ExecPerSec);
86   if (TotalNumberOfExecutedTraceBasedMutations)
87     Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
88   Printf("%s", End);
89 }
90
91 void Fuzzer::RereadOutputCorpus() {
92   if (Options.OutputCorpus.empty()) return;
93   std::vector<Unit> AdditionalCorpus;
94   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
95                          &EpochOfLastReadOfOutputCorpus);
96   if (Corpus.empty()) {
97     Corpus = AdditionalCorpus;
98     return;
99   }
100   if (!Options.Reload) return;
101   if (Options.Verbosity >= 2)
102     Printf("Reload: read %zd new units.\n",  AdditionalCorpus.size());
103   for (auto &X : AdditionalCorpus) {
104     if (X.size() > (size_t)Options.MaxLen)
105       X.resize(Options.MaxLen);
106     if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
107       CurrentUnit.clear();
108       CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
109       size_t NewCoverage = RunOne(CurrentUnit);
110       if (NewCoverage) {
111         Corpus.push_back(X);
112         if (Options.Verbosity >= 1)
113           PrintStats("RELOAD", NewCoverage);
114       }
115     }
116   }
117 }
118
119 void Fuzzer::ShuffleAndMinimize() {
120   size_t MaxCov = 0;
121   bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
122                       (Options.PreferSmallDuringInitialShuffle == -1 &&
123                        USF.GetRand().RandBool()));
124   if (Options.Verbosity)
125     Printf("PreferSmall: %d\n", PreferSmall);
126   PrintStats("READ  ", 0);
127   std::vector<Unit> NewCorpus;
128   std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
129   if (PreferSmall)
130     std::stable_sort(
131         Corpus.begin(), Corpus.end(),
132         [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
133   Unit &U = CurrentUnit;
134   for (const auto &C : Corpus) {
135     for (size_t First = 0; First < 1; First++) {
136       U.clear();
137       size_t Last = std::min(First + Options.MaxLen, C.size());
138       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
139       if (Options.OnlyASCII)
140         ToASCII(U);
141       size_t NewCoverage = RunOne(U);
142       if (NewCoverage) {
143         MaxCov = NewCoverage;
144         NewCorpus.push_back(U);
145         if (Options.Verbosity >= 2)
146           Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
147       }
148     }
149   }
150   Corpus = NewCorpus;
151   for (auto &X : Corpus)
152     UnitHashesAddedToCorpus.insert(Hash(X));
153   PrintStats("INITED", MaxCov);
154 }
155
156 size_t Fuzzer::RunOne(const Unit &U) {
157   UnitStartTime = system_clock::now();
158   TotalNumberOfRuns++;
159   size_t Res = 0;
160   if (Options.UseFullCoverageSet)
161     Res = RunOneMaximizeFullCoverageSet(U);
162   else
163     Res = RunOneMaximizeTotalCoverage(U);
164   auto UnitStopTime = system_clock::now();
165   auto TimeOfUnit =
166       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
167   if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
168       TimeOfUnit >= Options.ReportSlowUnits) {
169     TimeOfLongestUnitInSeconds = TimeOfUnit;
170     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
171     if (U.size() <= kMaxUnitSizeToPrint)
172       Print(U, "\n");
173     WriteUnitToFileWithPrefix(U, "slow-unit-");
174   }
175   return Res;
176 }
177
178 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
179   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
180     return;
181   if (Options.OnlyASCII)
182     ToASCII(U);
183   ReportNewCoverage(RunOne(U), U);
184 }
185
186 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
187   uintptr_t Res = 0;
188   for (uintptr_t i = 0; i < NumPCs; i++) {
189     Res = (Res + PCs[i]) * 7;
190   }
191   return Res;
192 }
193
194 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
195   Unit Res;
196   for (auto Idx : U) {
197     if (Idx < Options.Tokens.size()) {
198       std::string Token = Options.Tokens[Idx];
199       Res.insert(Res.end(), Token.begin(), Token.end());
200     } else {
201       Res.push_back(' ');
202     }
203   }
204   // FIXME: Apply DFSan labels.
205   return Res;
206 }
207
208 void Fuzzer::ExecuteCallback(const Unit &U) {
209   if (Options.Tokens.empty()) {
210     USF.TargetFunction(U.data(), U.size());
211   } else {
212     auto T = SubstituteTokens(U);
213     USF.TargetFunction(T.data(), T.size());
214   }
215 }
216
217 // Experimental.
218 // Fuly reset the current coverage state, run a single unit,
219 // compute a hash function from the full coverage set,
220 // return non-zero if the hash value is new.
221 // This produces tons of new units and as is it's only suitable for small tests,
222 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
223 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
224   __sanitizer_reset_coverage();
225   ExecuteCallback(U);
226   uintptr_t *PCs;
227   uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
228   if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
229     return FullCoverageSets.size();
230   return 0;
231 }
232
233 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
234   size_t NumCounters = __sanitizer_get_number_of_counters();
235   if (Options.UseCounters) {
236     CounterBitmap.resize(NumCounters);
237     __sanitizer_update_counter_bitset_and_clear_counters(0);
238   }
239   size_t OldCoverage = __sanitizer_get_total_unique_coverage();
240   ExecuteCallback(U);
241   size_t NewCoverage = __sanitizer_get_total_unique_coverage();
242   size_t NumNewBits = 0;
243   if (Options.UseCounters)
244     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
245         CounterBitmap.data());
246
247   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
248     PrintStats("pulse ", NewCoverage);
249
250   if (NewCoverage > OldCoverage || NumNewBits)
251     return NewCoverage;
252   return 0;
253 }
254
255 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
256   if (Options.OutputCorpus.empty()) return;
257   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
258   WriteToFile(U, Path);
259   if (Options.Verbosity >= 2)
260     Printf("Written to %s\n", Path.c_str());
261   assert(!Options.OnlyASCII || IsASCII(U));
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     size_t TBMWidth =
315         std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
316     size_t TBMDepth =
317         std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
318     Unit BackUp = *U;
319     for (size_t w = 0; w < TBMWidth; w++) {
320       *U = BackUp;
321       for (size_t d = 0; d < TBMDepth; d++) {
322         TotalNumberOfExecutedTraceBasedMutations++;
323         ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
324         RunOneAndUpdateCorpus(*U);
325       }
326     }
327   }
328 }
329
330 void Fuzzer::Loop(size_t NumIterations) {
331   for (auto &U: Options.Dictionary)
332     USF.GetMD().AddWordToDictionary(U.data(), U.size());
333
334   for (size_t i = 1; i <= NumIterations; i++) {
335     for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
336       SyncCorpus();
337       RereadOutputCorpus();
338       if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
339         return;
340       // First, simply mutate the unit w/o doing crosses.
341       CurrentUnit = Corpus[J1];
342       MutateAndTestOne(&CurrentUnit);
343       // Now, cross with others.
344       if (Options.DoCrossOver && !Corpus[J1].empty()) {
345         for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
346           CurrentUnit.resize(Options.MaxLen);
347           size_t NewSize = USF.CrossOver(
348               Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
349               Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
350           assert(NewSize > 0 && "CrossOver returned empty unit");
351           assert(NewSize <= (size_t)Options.MaxLen &&
352                  "CrossOver return overisized unit");
353           CurrentUnit.resize(NewSize);
354           MutateAndTestOne(&CurrentUnit);
355         }
356       }
357     }
358   }
359 }
360
361 void Fuzzer::SyncCorpus() {
362   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
363   auto Now = system_clock::now();
364   if (duration_cast<seconds>(Now - LastExternalSync).count() <
365       Options.SyncTimeout)
366     return;
367   LastExternalSync = Now;
368   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
369 }
370
371 }  // namespace fuzzer