[libFuzzer] print a stack trace on timeout
[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   std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
141   if (PreferSmall)
142     std::stable_sort(
143         Corpus.begin(), Corpus.end(),
144         [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
145   Unit &U = CurrentUnit;
146   for (const auto &C : Corpus) {
147     for (size_t First = 0; First < 1; First++) {
148       U.clear();
149       size_t Last = std::min(First + Options.MaxLen, C.size());
150       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
151       if (Options.OnlyASCII)
152         ToASCII(U);
153       size_t NewCoverage = RunOne(U);
154       if (NewCoverage) {
155         MaxCov = NewCoverage;
156         NewCorpus.push_back(U);
157         if (Options.Verbosity >= 2)
158           Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
159       }
160     }
161   }
162   Corpus = NewCorpus;
163   for (auto &X : Corpus)
164     UnitHashesAddedToCorpus.insert(Hash(X));
165   PrintStats("INITED", MaxCov);
166 }
167
168 size_t Fuzzer::RunOne(const Unit &U) {
169   UnitStartTime = system_clock::now();
170   TotalNumberOfRuns++;
171   size_t Res = RunOneMaximizeTotalCoverage(U);
172   auto UnitStopTime = system_clock::now();
173   auto TimeOfUnit =
174       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
175   if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
176       TimeOfUnit >= Options.ReportSlowUnits) {
177     TimeOfLongestUnitInSeconds = TimeOfUnit;
178     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
179     WriteUnitToFileWithPrefix(U, "slow-unit-");
180   }
181   return Res;
182 }
183
184 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
185   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
186     return;
187   if (Options.OnlyASCII)
188     ToASCII(U);
189   ReportNewCoverage(RunOne(U), U);
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   int Res = 0;
208   if (Options.Tokens.empty()) {
209     Res = USF.TargetFunction(U.data(), U.size());
210   } else {
211     auto T = SubstituteTokens(U);
212     Res = USF.TargetFunction(T.data(), T.size());
213   }
214   assert(Res == 0);
215 }
216
217 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
218   size_t NumCounters = __sanitizer_get_number_of_counters();
219   if (Options.UseCounters) {
220     CounterBitmap.resize(NumCounters);
221     __sanitizer_update_counter_bitset_and_clear_counters(0);
222   }
223   size_t OldCoverage = __sanitizer_get_total_unique_coverage();
224   ExecuteCallback(U);
225   size_t NewCoverage = __sanitizer_get_total_unique_coverage();
226   size_t NumNewBits = 0;
227   if (Options.UseCounters)
228     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
229         CounterBitmap.data());
230
231   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
232     PrintStats("pulse ", NewCoverage);
233
234   if (NewCoverage > OldCoverage || NumNewBits)
235     return NewCoverage;
236   return 0;
237 }
238
239 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
240   if (Options.OutputCorpus.empty()) return;
241   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
242   WriteToFile(U, Path);
243   if (Options.Verbosity >= 2)
244     Printf("Written to %s\n", Path.c_str());
245   assert(!Options.OnlyASCII || IsASCII(U));
246 }
247
248 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
249   if (!Options.SaveArtifacts)
250     return;
251   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
252   WriteToFile(U, Path);
253   Printf("artifact_prefix='%s'; Test unit written to %s\n",
254          Options.ArtifactPrefix.c_str(), Path.c_str());
255   if (U.size() <= kMaxUnitSizeToPrint) {
256     Printf("Base64: ");
257     PrintFileAsBase64(Path);
258   }
259 }
260
261 void Fuzzer::SaveCorpus() {
262   if (Options.OutputCorpus.empty()) return;
263   for (const auto &U : Corpus)
264     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
265   if (Options.Verbosity)
266     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
267            Options.OutputCorpus.c_str());
268 }
269
270 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
271   if (!NewCoverage) return;
272   Corpus.push_back(U);
273   UnitHashesAddedToCorpus.insert(Hash(U));
274   PrintStats("NEW   ", NewCoverage, "");
275   if (Options.Verbosity) {
276     Printf(" L: %zd", U.size());
277     if (U.size() < 30) {
278       Printf(" ");
279       PrintUnitInASCIIOrTokens(U, "\t");
280       Print(U);
281     }
282     Printf("\n");
283   }
284   WriteToOutputCorpus(U);
285   if (Options.ExitOnFirst)
286     exit(0);
287 }
288
289 void Fuzzer::MutateAndTestOne(Unit *U) {
290   for (int i = 0; i < Options.MutateDepth; i++) {
291     StartTraceRecording();
292     size_t Size = U->size();
293     U->resize(Options.MaxLen);
294     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
295     assert(NewSize > 0 && "Mutator returned empty unit");
296     assert(NewSize <= (size_t)Options.MaxLen &&
297            "Mutator return overisized unit");
298     U->resize(NewSize);
299     RunOneAndUpdateCorpus(*U);
300     size_t NumTraceBasedMutations = StopTraceRecording();
301     size_t TBMWidth =
302         std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
303     size_t TBMDepth =
304         std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
305     Unit BackUp = *U;
306     for (size_t w = 0; w < TBMWidth; w++) {
307       *U = BackUp;
308       for (size_t d = 0; d < TBMDepth; d++) {
309         TotalNumberOfExecutedTraceBasedMutations++;
310         ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
311         RunOneAndUpdateCorpus(*U);
312       }
313     }
314   }
315 }
316
317 void Fuzzer::Loop() {
318   for (auto &U: Options.Dictionary)
319     USF.GetMD().AddWordToDictionary(U.data(), U.size());
320
321   while (true) {
322     for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
323       SyncCorpus();
324       RereadOutputCorpus();
325       if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
326         return;
327       if (Options.MaxTotalTimeSec > 0 &&
328           secondsSinceProcessStartUp() >
329               static_cast<size_t>(Options.MaxTotalTimeSec))
330         return;
331       CurrentUnit = Corpus[J1];
332       // Optionally, cross with another unit.
333       if (Options.DoCrossOver && USF.GetRand().RandBool()) {
334         size_t J2 = USF.GetRand()(Corpus.size());
335         if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
336           assert(!Corpus[J2].empty());
337           CurrentUnit.resize(Options.MaxLen);
338           size_t NewSize = USF.CrossOver(
339               Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
340               Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
341           assert(NewSize > 0 && "CrossOver returned empty unit");
342           assert(NewSize <= (size_t)Options.MaxLen &&
343                  "CrossOver returned overisized unit");
344           CurrentUnit.resize(NewSize);
345         }
346       }
347       // Perform several mutations and runs.
348       MutateAndTestOne(&CurrentUnit);
349     }
350   }
351 }
352
353 void Fuzzer::SyncCorpus() {
354   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
355   auto Now = system_clock::now();
356   if (duration_cast<seconds>(Now - LastExternalSync).count() <
357       Options.SyncTimeout)
358     return;
359   LastExternalSync = Now;
360   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
361 }
362
363 }  // namespace fuzzer