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