output_csv libfuzzer option
[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 // Re-declare some of the sanitizer functions as "weak" so that
18 // libFuzzer can be linked w/o the sanitizers and sanitizer-coveragte
19 // (in which case it will complain at start-up time).
20 __attribute__((weak)) void __sanitizer_print_stack_trace();
21 __attribute__((weak)) void __sanitizer_reset_coverage();
22 __attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
23 __attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
24 __attribute__((weak))
25 void __sanitizer_set_death_callback(void (*callback)(void));
26 __attribute__((weak)) size_t __sanitizer_get_number_of_counters();
27 __attribute__((weak))
28 uintptr_t __sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
29 }
30
31 namespace fuzzer {
32 static const size_t kMaxUnitSizeToPrint = 256;
33
34 static void MissingWeakApiFunction(const char *FnName) {
35   Printf("ERROR: %s is not defined. Exiting.\n"
36          "Did you use -fsanitize-coverage=... to build your code?\n", FnName);
37   exit(1);
38 }
39
40 #define CHECK_WEAK_API_FUNCTION(fn)                                            \
41   do {                                                                         \
42     if (!fn)                                                                   \
43       MissingWeakApiFunction(#fn);                                             \
44   } while (false)
45
46 // Only one Fuzzer per process.
47 static Fuzzer *F;
48
49 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
50     : USF(USF), Options(Options) {
51   SetDeathCallback();
52   InitializeTraceState();
53   assert(!F);
54   F = this;
55 }
56
57 void Fuzzer::SetDeathCallback() {
58   CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
59   __sanitizer_set_death_callback(StaticDeathCallback);
60 }
61
62 void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
63   PrintASCII(U, PrintAfter);
64 }
65
66 void Fuzzer::StaticDeathCallback() {
67   assert(F);
68   F->DeathCallback();
69 }
70
71 void Fuzzer::DeathCallback() {
72   Printf("DEATH:\n");
73   if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
74     Print(CurrentUnit, "\n");
75     PrintUnitInASCII(CurrentUnit, "\n");
76   }
77   WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
78 }
79
80 void Fuzzer::StaticAlarmCallback() {
81   assert(F);
82   F->AlarmCallback();
83 }
84
85 void Fuzzer::AlarmCallback() {
86   assert(Options.UnitTimeoutSec > 0);
87   size_t Seconds =
88       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
89   if (Seconds == 0) return;
90   if (Options.Verbosity >= 2)
91     Printf("AlarmCallback %zd\n", Seconds);
92   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
93     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
94     Printf("       and the timeout value is %d (use -timeout=N to change)\n",
95            Options.UnitTimeoutSec);
96     if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
97       Print(CurrentUnit, "\n");
98       PrintUnitInASCII(CurrentUnit, "\n");
99     }
100     WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
101     Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
102            Seconds);
103     if (__sanitizer_print_stack_trace)
104       __sanitizer_print_stack_trace();
105     Printf("SUMMARY: libFuzzer: timeout\n");
106     exit(1);
107   }
108 }
109
110 void Fuzzer::PrintStats(const char *Where, const char *End) {
111   size_t Seconds = secondsSinceProcessStartUp();
112   size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
113
114   if (Options.OutputCSV) {
115     static bool csvHeaderPrinted = false;
116     if (!csvHeaderPrinted) {
117       csvHeaderPrinted = true;
118       Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
119     }
120     Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
121            LastRecordedBlockCoverage, TotalBits(),
122            LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
123            TotalNumberOfExecutedTraceBasedMutations, Where);
124   }
125
126   if (!Options.Verbosity)
127     return;
128   Printf("#%zd\t%s", TotalNumberOfRuns, Where);
129   if (LastRecordedBlockCoverage)
130     Printf(" cov: %zd", LastRecordedBlockCoverage);
131   if (auto TB = TotalBits())
132     Printf(" bits: %zd", TB);
133   if (LastRecordedCallerCalleeCoverage)
134     Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
135   Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
136   if (TotalNumberOfExecutedTraceBasedMutations)
137     Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
138   Printf("%s", End);
139 }
140
141 void Fuzzer::RereadOutputCorpus() {
142   if (Options.OutputCorpus.empty()) return;
143   std::vector<Unit> AdditionalCorpus;
144   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
145                          &EpochOfLastReadOfOutputCorpus);
146   if (Corpus.empty()) {
147     Corpus = AdditionalCorpus;
148     return;
149   }
150   if (!Options.Reload) return;
151   if (Options.Verbosity >= 2)
152     Printf("Reload: read %zd new units.\n",  AdditionalCorpus.size());
153   for (auto &X : AdditionalCorpus) {
154     if (X.size() > (size_t)Options.MaxLen)
155       X.resize(Options.MaxLen);
156     if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
157       CurrentUnit.clear();
158       CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
159       if (RunOne(CurrentUnit)) {
160         Corpus.push_back(X);
161         PrintStats("RELOAD");
162       }
163     }
164   }
165 }
166
167 void Fuzzer::ShuffleAndMinimize() {
168   bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
169                       (Options.PreferSmallDuringInitialShuffle == -1 &&
170                        USF.GetRand().RandBool()));
171   if (Options.Verbosity)
172     Printf("PreferSmall: %d\n", PreferSmall);
173   PrintStats("READ  ");
174   std::vector<Unit> NewCorpus;
175   if (Options.ShuffleAtStartUp) {
176     std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
177     if (PreferSmall)
178       std::stable_sort(
179           Corpus.begin(), Corpus.end(),
180           [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
181   }
182   Unit &U = CurrentUnit;
183   for (const auto &C : Corpus) {
184     for (size_t First = 0; First < 1; First++) {
185       U.clear();
186       size_t Last = std::min(First + Options.MaxLen, C.size());
187       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
188       if (Options.OnlyASCII)
189         ToASCII(U);
190       if (RunOne(U)) {
191         NewCorpus.push_back(U);
192         if (Options.Verbosity >= 2)
193           Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
194       }
195     }
196   }
197   Corpus = NewCorpus;
198   for (auto &X : Corpus)
199     UnitHashesAddedToCorpus.insert(Hash(X));
200   PrintStats("INITED");
201 }
202
203 bool Fuzzer::RunOne(const Unit &U) {
204   UnitStartTime = system_clock::now();
205   TotalNumberOfRuns++;
206
207   PrepareCoverageBeforeRun();
208   ExecuteCallback(U);
209   bool Res = CheckCoverageAfterRun();
210
211   auto UnitStopTime = system_clock::now();
212   auto TimeOfUnit =
213       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
214   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
215       secondsSinceProcessStartUp() >= 2)
216     PrintStats("pulse ");
217   if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
218       TimeOfUnit >= Options.ReportSlowUnits) {
219     TimeOfLongestUnitInSeconds = TimeOfUnit;
220     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
221     WriteUnitToFileWithPrefix(U, "slow-unit-");
222   }
223   return Res;
224 }
225
226 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
227   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
228     return;
229   if (Options.OnlyASCII)
230     ToASCII(U);
231   if (RunOne(U))
232     ReportNewCoverage(U);
233 }
234
235 void Fuzzer::ExecuteCallback(const Unit &U) {
236   int Res = USF.TargetFunction(U.data(), U.size());
237   (void)Res;
238   assert(Res == 0);
239 }
240
241 size_t Fuzzer::RecordBlockCoverage() {
242   CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
243   return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
244 }
245
246 size_t Fuzzer::RecordCallerCalleeCoverage() {
247   if (!Options.UseIndirCalls)
248     return 0;
249   if (!__sanitizer_get_total_unique_caller_callee_pairs)
250     return 0;
251   return LastRecordedCallerCalleeCoverage =
252              __sanitizer_get_total_unique_caller_callee_pairs();
253 }
254
255 void Fuzzer::PrepareCoverageBeforeRun() {
256   if (Options.UseCounters) {
257     size_t NumCounters = __sanitizer_get_number_of_counters();
258     CounterBitmap.resize(NumCounters);
259     __sanitizer_update_counter_bitset_and_clear_counters(0);
260   }
261   RecordBlockCoverage();
262   RecordCallerCalleeCoverage();
263 }
264
265 bool Fuzzer::CheckCoverageAfterRun() {
266   size_t OldCoverage = LastRecordedBlockCoverage;
267   size_t NewCoverage = RecordBlockCoverage();
268   size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
269   size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
270   size_t NumNewBits = 0;
271   if (Options.UseCounters)
272     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
273         CounterBitmap.data());
274   return NewCoverage > OldCoverage ||
275          NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
276 }
277
278 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
279   if (Options.OutputCorpus.empty()) return;
280   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
281   WriteToFile(U, Path);
282   if (Options.Verbosity >= 2)
283     Printf("Written to %s\n", Path.c_str());
284   assert(!Options.OnlyASCII || IsASCII(U));
285 }
286
287 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
288   if (!Options.SaveArtifacts)
289     return;
290   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
291   WriteToFile(U, Path);
292   Printf("artifact_prefix='%s'; Test unit written to %s\n",
293          Options.ArtifactPrefix.c_str(), Path.c_str());
294   if (U.size() <= kMaxUnitSizeToPrint) {
295     Printf("Base64: ");
296     PrintFileAsBase64(Path);
297   }
298 }
299
300 void Fuzzer::SaveCorpus() {
301   if (Options.OutputCorpus.empty()) return;
302   for (const auto &U : Corpus)
303     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
304   if (Options.Verbosity)
305     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
306            Options.OutputCorpus.c_str());
307 }
308
309 void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
310   if (!Options.PrintNEW)
311     return;
312   PrintStats("NEW   ", "");
313   if (Options.Verbosity) {
314     Printf(" L: %zd", U.size());
315     if (U.size() < 30) {
316       Printf(" ");
317       PrintUnitInASCII(U, "\t");
318       Print(U);
319     }
320     Printf("\n");
321   }
322 }
323
324 void Fuzzer::ReportNewCoverage(const Unit &U) {
325   Corpus.push_back(U);
326   UnitHashesAddedToCorpus.insert(Hash(U));
327   PrintStatusForNewUnit(U);
328   WriteToOutputCorpus(U);
329   if (Options.ExitOnFirst)
330     exit(0);
331 }
332
333 void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
334   if (Corpora.size() <= 1) {
335     Printf("Merge requires two or more corpus dirs\n");
336     return;
337   }
338   auto InitialCorpusDir = Corpora[0];
339   ReadDir(InitialCorpusDir, nullptr);
340   Printf("Merge: running the initial corpus '%s' of %d units\n",
341          InitialCorpusDir.c_str(), Corpus.size());
342   for (auto &U : Corpus)
343     RunOne(U);
344
345   std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
346
347   size_t NumTried = 0;
348   size_t NumMerged = 0;
349   for (auto &C : ExtraCorpora) {
350     Corpus.clear();
351     ReadDir(C, nullptr);
352     Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
353            Corpus.size());
354     for (auto &U : Corpus) {
355       NumTried++;
356       if (RunOne(U)) {
357         WriteToOutputCorpus(U);
358         NumMerged++;
359       }
360     }
361   }
362   Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
363 }
364
365 void Fuzzer::MutateAndTestOne(Unit *U) {
366   for (int i = 0; i < Options.MutateDepth; i++) {
367     StartTraceRecording();
368     size_t Size = U->size();
369     U->resize(Options.MaxLen);
370     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
371     assert(NewSize > 0 && "Mutator returned empty unit");
372     assert(NewSize <= (size_t)Options.MaxLen &&
373            "Mutator return overisized unit");
374     U->resize(NewSize);
375     RunOneAndUpdateCorpus(*U);
376     size_t NumTraceBasedMutations = StopTraceRecording();
377     size_t TBMWidth =
378         std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
379     size_t TBMDepth =
380         std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
381     Unit BackUp = *U;
382     for (size_t w = 0; w < TBMWidth; w++) {
383       *U = BackUp;
384       for (size_t d = 0; d < TBMDepth; d++) {
385         TotalNumberOfExecutedTraceBasedMutations++;
386         ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
387         RunOneAndUpdateCorpus(*U);
388       }
389     }
390   }
391 }
392
393 // Returns an index of random unit from the corpus to mutate.
394 // Hypothesis: units added to the corpus last are more likely to be interesting.
395 // This function gives more wieght to the more recent units.
396 size_t Fuzzer::ChooseUnitIdxToMutate() {
397     size_t N = Corpus.size();
398     size_t Total = (N + 1) * N / 2;
399     size_t R = USF.GetRand()(Total);
400     size_t IdxBeg = 0, IdxEnd = N;
401     // Binary search.
402     while (IdxEnd - IdxBeg >= 2) {
403       size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
404       if (R > (Idx + 1) * Idx / 2)
405         IdxBeg = Idx;
406       else
407         IdxEnd = Idx;
408     }
409     assert(IdxBeg < N);
410     return IdxBeg;
411 }
412
413 // Experimental search heuristic: drilling.
414 // - Read, shuffle, execute and minimize the corpus.
415 // - Choose one random unit.
416 // - Reset the coverage.
417 // - Start fuzzing as if the chosen unit was the only element of the corpus.
418 // - When done, reset the coverage again.
419 // - Merge the newly created corpus into the original one.
420 void Fuzzer::Drill() {
421   // The corpus is already read, shuffled, and minimized.
422   assert(!Corpus.empty());
423   Options.PrintNEW = false;  // Don't print NEW status lines when drilling.
424
425   Unit U = ChooseUnitToMutate();
426
427   CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
428   __sanitizer_reset_coverage();
429
430   std::vector<Unit> SavedCorpus;
431   SavedCorpus.swap(Corpus);
432   Corpus.push_back(U);
433   assert(Corpus.size() == 1);
434   RunOne(U);
435   PrintStats("DRILL ");
436   std::string SavedOutputCorpusPath; // Don't write new units while drilling.
437   SavedOutputCorpusPath.swap(Options.OutputCorpus);
438   Loop();
439
440   __sanitizer_reset_coverage();
441
442   PrintStats("REINIT");
443   SavedOutputCorpusPath.swap(Options.OutputCorpus);
444   for (auto &U : SavedCorpus)
445     RunOne(U);
446   PrintStats("MERGE ");
447   Options.PrintNEW = true;
448   size_t NumMerged = 0;
449   for (auto &U : Corpus) {
450     if (RunOne(U)) {
451       PrintStatusForNewUnit(U);
452       NumMerged++;
453       WriteToOutputCorpus(U);
454     }
455   }
456   PrintStats("MERGED");
457   if (NumMerged && Options.Verbosity)
458     Printf("Drilling discovered %zd new units\n", NumMerged);
459 }
460
461 void Fuzzer::Loop() {
462   while (true) {
463     size_t J1 = ChooseUnitIdxToMutate();;
464     SyncCorpus();
465     RereadOutputCorpus();
466     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
467       break;
468     if (Options.MaxTotalTimeSec > 0 &&
469         secondsSinceProcessStartUp() >
470         static_cast<size_t>(Options.MaxTotalTimeSec))
471       break;
472     CurrentUnit = Corpus[J1];
473     // Optionally, cross with another unit.
474     if (Options.DoCrossOver && USF.GetRand().RandBool()) {
475       size_t J2 = ChooseUnitIdxToMutate();
476       if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
477         assert(!Corpus[J2].empty());
478         CurrentUnit.resize(Options.MaxLen);
479         size_t NewSize = USF.CrossOver(
480             Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
481             Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
482         assert(NewSize > 0 && "CrossOver returned empty unit");
483         assert(NewSize <= (size_t)Options.MaxLen &&
484                "CrossOver returned overisized unit");
485         CurrentUnit.resize(NewSize);
486       }
487     }
488     // Perform several mutations and runs.
489     MutateAndTestOne(&CurrentUnit);
490   }
491
492   PrintStats("DONE  ", "\n");
493 }
494
495 void Fuzzer::SyncCorpus() {
496   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
497   auto Now = system_clock::now();
498   if (duration_cast<seconds>(Now - LastExternalSync).count() <
499       Options.SyncTimeout)
500     return;
501   LastExternalSync = Now;
502   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
503 }
504
505 }  // namespace fuzzer