[libFuzzer] remove experimental flag and functionality
[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 = 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 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
183   Unit Res;
184   for (auto Idx : U) {
185     if (Idx < Options.Tokens.size()) {
186       std::string Token = Options.Tokens[Idx];
187       Res.insert(Res.end(), Token.begin(), Token.end());
188     } else {
189       Res.push_back(' ');
190     }
191   }
192   // FIXME: Apply DFSan labels.
193   return Res;
194 }
195
196 void Fuzzer::ExecuteCallback(const Unit &U) {
197   if (Options.Tokens.empty()) {
198     USF.TargetFunction(U.data(), U.size());
199   } else {
200     auto T = SubstituteTokens(U);
201     USF.TargetFunction(T.data(), T.size());
202   }
203 }
204
205 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
206   size_t NumCounters = __sanitizer_get_number_of_counters();
207   if (Options.UseCounters) {
208     CounterBitmap.resize(NumCounters);
209     __sanitizer_update_counter_bitset_and_clear_counters(0);
210   }
211   size_t OldCoverage = __sanitizer_get_total_unique_coverage();
212   ExecuteCallback(U);
213   size_t NewCoverage = __sanitizer_get_total_unique_coverage();
214   size_t NumNewBits = 0;
215   if (Options.UseCounters)
216     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
217         CounterBitmap.data());
218
219   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
220     PrintStats("pulse ", NewCoverage);
221
222   if (NewCoverage > OldCoverage || NumNewBits)
223     return NewCoverage;
224   return 0;
225 }
226
227 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
228   if (Options.OutputCorpus.empty()) return;
229   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
230   WriteToFile(U, Path);
231   if (Options.Verbosity >= 2)
232     Printf("Written to %s\n", Path.c_str());
233   assert(!Options.OnlyASCII || IsASCII(U));
234 }
235
236 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
237   std::string Path = Prefix + Hash(U);
238   WriteToFile(U, Path);
239   Printf("Test unit written to %s\n", Path.c_str());
240   if (U.size() <= kMaxUnitSizeToPrint) {
241     Printf("Base64: ");
242     PrintFileAsBase64(Path);
243   }
244 }
245
246 void Fuzzer::SaveCorpus() {
247   if (Options.OutputCorpus.empty()) return;
248   for (const auto &U : Corpus)
249     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
250   if (Options.Verbosity)
251     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
252            Options.OutputCorpus.c_str());
253 }
254
255 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
256   if (!NewCoverage) return;
257   Corpus.push_back(U);
258   UnitHashesAddedToCorpus.insert(Hash(U));
259   PrintStats("NEW   ", NewCoverage, "");
260   if (Options.Verbosity) {
261     Printf(" L: %zd", U.size());
262     if (U.size() < 30) {
263       Printf(" ");
264       PrintUnitInASCIIOrTokens(U, "\t");
265       Print(U);
266     }
267     Printf("\n");
268   }
269   WriteToOutputCorpus(U);
270   if (Options.ExitOnFirst)
271     exit(0);
272 }
273
274 void Fuzzer::MutateAndTestOne(Unit *U) {
275   for (int i = 0; i < Options.MutateDepth; i++) {
276     StartTraceRecording();
277     size_t Size = U->size();
278     U->resize(Options.MaxLen);
279     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
280     assert(NewSize > 0 && "Mutator returned empty unit");
281     assert(NewSize <= (size_t)Options.MaxLen &&
282            "Mutator return overisized unit");
283     U->resize(NewSize);
284     RunOneAndUpdateCorpus(*U);
285     size_t NumTraceBasedMutations = StopTraceRecording();
286     size_t TBMWidth =
287         std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
288     size_t TBMDepth =
289         std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
290     Unit BackUp = *U;
291     for (size_t w = 0; w < TBMWidth; w++) {
292       *U = BackUp;
293       for (size_t d = 0; d < TBMDepth; d++) {
294         TotalNumberOfExecutedTraceBasedMutations++;
295         ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
296         RunOneAndUpdateCorpus(*U);
297       }
298     }
299   }
300 }
301
302 void Fuzzer::Loop() {
303   for (auto &U: Options.Dictionary)
304     USF.GetMD().AddWordToDictionary(U.data(), U.size());
305
306   while (true) {
307     for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
308       SyncCorpus();
309       RereadOutputCorpus();
310       if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
311         return;
312       if (Options.MaxTotalTimeSec > 0 &&
313           secondsSinceProcessStartUp() >
314               static_cast<size_t>(Options.MaxTotalTimeSec))
315         return;
316       CurrentUnit = Corpus[J1];
317       // Optionally, cross with another unit.
318       if (Options.DoCrossOver && USF.GetRand().RandBool()) {
319         size_t J2 = USF.GetRand()(Corpus.size());
320         if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
321           assert(!Corpus[J2].empty());
322           CurrentUnit.resize(Options.MaxLen);
323           size_t NewSize = USF.CrossOver(
324               Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
325               Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
326           assert(NewSize > 0 && "CrossOver returned empty unit");
327           assert(NewSize <= (size_t)Options.MaxLen &&
328                  "CrossOver returned overisized unit");
329           CurrentUnit.resize(NewSize);
330         }
331       }
332       // Perform several mutations and runs.
333       MutateAndTestOne(&CurrentUnit);
334     }
335   }
336 }
337
338 void Fuzzer::SyncCorpus() {
339   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
340   auto Now = system_clock::now();
341   if (duration_cast<seconds>(Now - LastExternalSync).count() <
342       Options.SyncTimeout)
343     return;
344   LastExternalSync = Now;
345   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
346 }
347
348 }  // namespace fuzzer