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