[libFuzzer] add -shuffle flag
[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 extern "C" {
17 __attribute__((weak)) void __sanitizer_print_stack_trace();
18 }
19
20 namespace fuzzer {
21 static const size_t kMaxUnitSizeToPrint = 256;
22
23 // Only one Fuzzer per process.
24 static Fuzzer *F;
25
26 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
27     : USF(USF), Options(Options) {
28   SetDeathCallback();
29   InitializeTraceState();
30   assert(!F);
31   F = this;
32 }
33
34 void Fuzzer::SetDeathCallback() {
35   __sanitizer_set_death_callback(StaticDeathCallback);
36 }
37
38 void Fuzzer::PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter) {
39   if (Options.Tokens.empty()) {
40     PrintASCII(U, PrintAfter);
41   } else {
42     auto T = SubstituteTokens(U);
43     T.push_back(0);
44     Printf("%s%s", T.data(), PrintAfter);
45   }
46 }
47
48 void Fuzzer::StaticDeathCallback() {
49   assert(F);
50   F->DeathCallback();
51 }
52
53 void Fuzzer::DeathCallback() {
54   Printf("DEATH:\n");
55   if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
56     Print(CurrentUnit, "\n");
57     PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
58   }
59   WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
60 }
61
62 void Fuzzer::StaticAlarmCallback() {
63   assert(F);
64   F->AlarmCallback();
65 }
66
67 void Fuzzer::AlarmCallback() {
68   assert(Options.UnitTimeoutSec > 0);
69   size_t Seconds =
70       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
71   if (Seconds == 0) return;
72   if (Options.Verbosity >= 2)
73     Printf("AlarmCallback %zd\n", Seconds);
74   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
75     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
76     Printf("       and the timeout value is %d (use -timeout=N to change)\n",
77            Options.UnitTimeoutSec);
78     if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
79       Print(CurrentUnit, "\n");
80       PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
81     }
82     WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
83     Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
84            Seconds);
85     if (__sanitizer_print_stack_trace)
86       __sanitizer_print_stack_trace();
87     Printf("SUMMARY: libFuzzer: timeout\n");
88     exit(1);
89   }
90 }
91
92 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
93   if (!Options.Verbosity) return;
94   size_t Seconds = secondsSinceProcessStartUp();
95   size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
96   Printf("#%zd\t%s cov: %zd bits: %zd units: %zd exec/s: %zd",
97          TotalNumberOfRuns, Where, Cov, TotalBits(), Corpus.size(), ExecPerSec);
98   if (TotalNumberOfExecutedTraceBasedMutations)
99     Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
100   Printf("%s", End);
101 }
102
103 void Fuzzer::RereadOutputCorpus() {
104   if (Options.OutputCorpus.empty()) return;
105   std::vector<Unit> AdditionalCorpus;
106   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
107                          &EpochOfLastReadOfOutputCorpus);
108   if (Corpus.empty()) {
109     Corpus = AdditionalCorpus;
110     return;
111   }
112   if (!Options.Reload) return;
113   if (Options.Verbosity >= 2)
114     Printf("Reload: read %zd new units.\n",  AdditionalCorpus.size());
115   for (auto &X : AdditionalCorpus) {
116     if (X.size() > (size_t)Options.MaxLen)
117       X.resize(Options.MaxLen);
118     if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
119       CurrentUnit.clear();
120       CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
121       size_t NewCoverage = RunOne(CurrentUnit);
122       if (NewCoverage) {
123         Corpus.push_back(X);
124         if (Options.Verbosity >= 1)
125           PrintStats("RELOAD", NewCoverage);
126       }
127     }
128   }
129 }
130
131 void Fuzzer::ShuffleAndMinimize() {
132   size_t MaxCov = 0;
133   bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
134                       (Options.PreferSmallDuringInitialShuffle == -1 &&
135                        USF.GetRand().RandBool()));
136   if (Options.Verbosity)
137     Printf("PreferSmall: %d\n", PreferSmall);
138   PrintStats("READ  ", 0);
139   std::vector<Unit> NewCorpus;
140   if (Options.ShuffleAtStartUp) {
141     std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
142     if (PreferSmall)
143       std::stable_sort(
144           Corpus.begin(), Corpus.end(),
145           [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
146   }
147   Unit &U = CurrentUnit;
148   for (const auto &C : Corpus) {
149     for (size_t First = 0; First < 1; First++) {
150       U.clear();
151       size_t Last = std::min(First + Options.MaxLen, C.size());
152       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
153       if (Options.OnlyASCII)
154         ToASCII(U);
155       size_t NewCoverage = RunOne(U);
156       if (NewCoverage) {
157         MaxCov = NewCoverage;
158         NewCorpus.push_back(U);
159         if (Options.Verbosity >= 2)
160           Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
161       }
162     }
163   }
164   Corpus = NewCorpus;
165   for (auto &X : Corpus)
166     UnitHashesAddedToCorpus.insert(Hash(X));
167   PrintStats("INITED", MaxCov);
168 }
169
170 size_t Fuzzer::RunOne(const Unit &U) {
171   UnitStartTime = system_clock::now();
172   TotalNumberOfRuns++;
173   size_t Res = RunOneMaximizeTotalCoverage(U);
174   auto UnitStopTime = system_clock::now();
175   auto TimeOfUnit =
176       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
177   if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
178       TimeOfUnit >= Options.ReportSlowUnits) {
179     TimeOfLongestUnitInSeconds = TimeOfUnit;
180     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
181     WriteUnitToFileWithPrefix(U, "slow-unit-");
182   }
183   return Res;
184 }
185
186 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
187   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
188     return;
189   if (Options.OnlyASCII)
190     ToASCII(U);
191   ReportNewCoverage(RunOne(U), U);
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   int Res = 0;
210   if (Options.Tokens.empty()) {
211     Res = USF.TargetFunction(U.data(), U.size());
212   } else {
213     auto T = SubstituteTokens(U);
214     Res = USF.TargetFunction(T.data(), T.size());
215   }
216   assert(Res == 0);
217 }
218
219 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
220   size_t NumCounters = __sanitizer_get_number_of_counters();
221   if (Options.UseCounters) {
222     CounterBitmap.resize(NumCounters);
223     __sanitizer_update_counter_bitset_and_clear_counters(0);
224   }
225   size_t OldCoverage = __sanitizer_get_total_unique_coverage();
226   ExecuteCallback(U);
227   size_t NewCoverage = __sanitizer_get_total_unique_coverage();
228   size_t NumNewBits = 0;
229   if (Options.UseCounters)
230     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
231         CounterBitmap.data());
232
233   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
234     PrintStats("pulse ", NewCoverage);
235
236   if (NewCoverage > OldCoverage || NumNewBits)
237     return NewCoverage;
238   return 0;
239 }
240
241 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
242   if (Options.OutputCorpus.empty()) return;
243   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
244   WriteToFile(U, Path);
245   if (Options.Verbosity >= 2)
246     Printf("Written to %s\n", Path.c_str());
247   assert(!Options.OnlyASCII || IsASCII(U));
248 }
249
250 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
251   if (!Options.SaveArtifacts)
252     return;
253   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
254   WriteToFile(U, Path);
255   Printf("artifact_prefix='%s'; Test unit written to %s\n",
256          Options.ArtifactPrefix.c_str(), Path.c_str());
257   if (U.size() <= kMaxUnitSizeToPrint) {
258     Printf("Base64: ");
259     PrintFileAsBase64(Path);
260   }
261 }
262
263 void Fuzzer::SaveCorpus() {
264   if (Options.OutputCorpus.empty()) return;
265   for (const auto &U : Corpus)
266     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
267   if (Options.Verbosity)
268     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
269            Options.OutputCorpus.c_str());
270 }
271
272 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
273   if (!NewCoverage) return;
274   Corpus.push_back(U);
275   UnitHashesAddedToCorpus.insert(Hash(U));
276   PrintStats("NEW   ", NewCoverage, "");
277   if (Options.Verbosity) {
278     Printf(" L: %zd", U.size());
279     if (U.size() < 30) {
280       Printf(" ");
281       PrintUnitInASCIIOrTokens(U, "\t");
282       Print(U);
283     }
284     Printf("\n");
285   }
286   WriteToOutputCorpus(U);
287   if (Options.ExitOnFirst)
288     exit(0);
289 }
290
291 void Fuzzer::MutateAndTestOne(Unit *U) {
292   for (int i = 0; i < Options.MutateDepth; i++) {
293     StartTraceRecording();
294     size_t Size = U->size();
295     U->resize(Options.MaxLen);
296     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
297     assert(NewSize > 0 && "Mutator returned empty unit");
298     assert(NewSize <= (size_t)Options.MaxLen &&
299            "Mutator return overisized unit");
300     U->resize(NewSize);
301     RunOneAndUpdateCorpus(*U);
302     size_t NumTraceBasedMutations = StopTraceRecording();
303     size_t TBMWidth =
304         std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
305     size_t TBMDepth =
306         std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
307     Unit BackUp = *U;
308     for (size_t w = 0; w < TBMWidth; w++) {
309       *U = BackUp;
310       for (size_t d = 0; d < TBMDepth; d++) {
311         TotalNumberOfExecutedTraceBasedMutations++;
312         ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
313         RunOneAndUpdateCorpus(*U);
314       }
315     }
316   }
317 }
318
319 void Fuzzer::Loop() {
320   for (auto &U: Options.Dictionary)
321     USF.GetMD().AddWordToDictionary(U.data(), U.size());
322
323   while (true) {
324     for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
325       SyncCorpus();
326       RereadOutputCorpus();
327       if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
328         return;
329       if (Options.MaxTotalTimeSec > 0 &&
330           secondsSinceProcessStartUp() >
331               static_cast<size_t>(Options.MaxTotalTimeSec))
332         return;
333       CurrentUnit = Corpus[J1];
334       // Optionally, cross with another unit.
335       if (Options.DoCrossOver && USF.GetRand().RandBool()) {
336         size_t J2 = USF.GetRand()(Corpus.size());
337         if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
338           assert(!Corpus[J2].empty());
339           CurrentUnit.resize(Options.MaxLen);
340           size_t NewSize = USF.CrossOver(
341               Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
342               Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
343           assert(NewSize > 0 && "CrossOver returned empty unit");
344           assert(NewSize <= (size_t)Options.MaxLen &&
345                  "CrossOver returned overisized unit");
346           CurrentUnit.resize(NewSize);
347         }
348       }
349       // Perform several mutations and runs.
350       MutateAndTestOne(&CurrentUnit);
351     }
352   }
353 }
354
355 void Fuzzer::SyncCorpus() {
356   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
357   auto Now = system_clock::now();
358   if (duration_cast<seconds>(Now - LastExternalSync).count() <
359       Options.SyncTimeout)
360     return;
361   LastExternalSync = Now;
362   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
363 }
364
365 }  // namespace fuzzer