[libFuzzer] when choosing the next unit to mutate, give some preference to the most...
[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 __attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
19 }
20
21 namespace fuzzer {
22 static const size_t kMaxUnitSizeToPrint = 256;
23
24 // Only one Fuzzer per process.
25 static Fuzzer *F;
26
27 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
28     : USF(USF), Options(Options) {
29   SetDeathCallback();
30   InitializeTraceState();
31   assert(!F);
32   F = this;
33 }
34
35 void Fuzzer::SetDeathCallback() {
36   __sanitizer_set_death_callback(StaticDeathCallback);
37 }
38
39 void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
40   PrintASCII(U, PrintAfter);
41 }
42
43 void Fuzzer::StaticDeathCallback() {
44   assert(F);
45   F->DeathCallback();
46 }
47
48 void Fuzzer::DeathCallback() {
49   Printf("DEATH:\n");
50   if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
51     Print(CurrentUnit, "\n");
52     PrintUnitInASCII(CurrentUnit, "\n");
53   }
54   WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
55 }
56
57 void Fuzzer::StaticAlarmCallback() {
58   assert(F);
59   F->AlarmCallback();
60 }
61
62 void Fuzzer::AlarmCallback() {
63   assert(Options.UnitTimeoutSec > 0);
64   size_t Seconds =
65       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
66   if (Seconds == 0) return;
67   if (Options.Verbosity >= 2)
68     Printf("AlarmCallback %zd\n", Seconds);
69   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
70     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
71     Printf("       and the timeout value is %d (use -timeout=N to change)\n",
72            Options.UnitTimeoutSec);
73     if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
74       Print(CurrentUnit, "\n");
75       PrintUnitInASCII(CurrentUnit, "\n");
76     }
77     WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
78     Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
79            Seconds);
80     if (__sanitizer_print_stack_trace)
81       __sanitizer_print_stack_trace();
82     Printf("SUMMARY: libFuzzer: timeout\n");
83     exit(1);
84   }
85 }
86
87 void Fuzzer::PrintStats(const char *Where, const char *End) {
88   if (!Options.Verbosity) return;
89   size_t Seconds = secondsSinceProcessStartUp();
90   size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
91   Printf("#%zd\t%s", TotalNumberOfRuns, Where);
92   if (LastRecordedBlockCoverage)
93     Printf(" cov: %zd", LastRecordedBlockCoverage);
94   if (auto TB = TotalBits())
95     Printf(" bits: %zd", TB);
96   if (LastRecordedCallerCalleeCoverage)
97     Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
98   Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
99   if (TotalNumberOfExecutedTraceBasedMutations)
100     Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
101   Printf("%s", End);
102 }
103
104 void Fuzzer::RereadOutputCorpus() {
105   if (Options.OutputCorpus.empty()) return;
106   std::vector<Unit> AdditionalCorpus;
107   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
108                          &EpochOfLastReadOfOutputCorpus);
109   if (Corpus.empty()) {
110     Corpus = AdditionalCorpus;
111     return;
112   }
113   if (!Options.Reload) return;
114   if (Options.Verbosity >= 2)
115     Printf("Reload: read %zd new units.\n",  AdditionalCorpus.size());
116   for (auto &X : AdditionalCorpus) {
117     if (X.size() > (size_t)Options.MaxLen)
118       X.resize(Options.MaxLen);
119     if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
120       CurrentUnit.clear();
121       CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
122       if (RunOne(CurrentUnit)) {
123         Corpus.push_back(X);
124         if (Options.Verbosity >= 1)
125           PrintStats("RELOAD");
126       }
127     }
128   }
129 }
130
131 void Fuzzer::ShuffleAndMinimize() {
132   bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
133                       (Options.PreferSmallDuringInitialShuffle == -1 &&
134                        USF.GetRand().RandBool()));
135   if (Options.Verbosity)
136     Printf("PreferSmall: %d\n", PreferSmall);
137   PrintStats("READ  ");
138   std::vector<Unit> NewCorpus;
139   if (Options.ShuffleAtStartUp) {
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   }
146   Unit &U = CurrentUnit;
147   for (const auto &C : Corpus) {
148     for (size_t First = 0; First < 1; First++) {
149       U.clear();
150       size_t Last = std::min(First + Options.MaxLen, C.size());
151       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
152       if (Options.OnlyASCII)
153         ToASCII(U);
154       if (RunOne(U)) {
155         NewCorpus.push_back(U);
156         if (Options.Verbosity >= 2)
157           Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
158       }
159     }
160   }
161   Corpus = NewCorpus;
162   for (auto &X : Corpus)
163     UnitHashesAddedToCorpus.insert(Hash(X));
164   PrintStats("INITED");
165 }
166
167 bool Fuzzer::RunOne(const Unit &U) {
168   UnitStartTime = system_clock::now();
169   TotalNumberOfRuns++;
170
171   PrepareCoverageBeforeRun();
172   ExecuteCallback(U);
173   bool Res = CheckCoverageAfterRun();
174
175   auto UnitStopTime = system_clock::now();
176   auto TimeOfUnit =
177       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
178   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
179     PrintStats("pulse ");
180   if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
181       TimeOfUnit >= Options.ReportSlowUnits) {
182     TimeOfLongestUnitInSeconds = TimeOfUnit;
183     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
184     WriteUnitToFileWithPrefix(U, "slow-unit-");
185   }
186   return Res;
187 }
188
189 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
190   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
191     return;
192   if (Options.OnlyASCII)
193     ToASCII(U);
194   if (RunOne(U))
195     ReportNewCoverage(U);
196 }
197
198 void Fuzzer::ExecuteCallback(const Unit &U) {
199   int Res = USF.TargetFunction(U.data(), U.size());
200   (void)Res;
201   assert(Res == 0);
202 }
203
204 size_t Fuzzer::RecordBlockCoverage() {
205   return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
206 }
207
208 size_t Fuzzer::RecordCallerCalleeCoverage() {
209   if (!Options.UseIndirCalls)
210     return 0;
211   if (!__sanitizer_get_total_unique_caller_callee_pairs)
212     return 0;
213   return LastRecordedCallerCalleeCoverage =
214              __sanitizer_get_total_unique_caller_callee_pairs();
215 }
216
217 void Fuzzer::PrepareCoverageBeforeRun() {
218   if (Options.UseCounters) {
219     size_t NumCounters = __sanitizer_get_number_of_counters();
220     CounterBitmap.resize(NumCounters);
221     __sanitizer_update_counter_bitset_and_clear_counters(0);
222   }
223   RecordBlockCoverage();
224   RecordCallerCalleeCoverage();
225 }
226
227 bool Fuzzer::CheckCoverageAfterRun() {
228   size_t OldCoverage = LastRecordedBlockCoverage;
229   size_t NewCoverage = RecordBlockCoverage();
230   size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
231   size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
232   size_t NumNewBits = 0;
233   if (Options.UseCounters)
234     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
235         CounterBitmap.data());
236   return NewCoverage > OldCoverage ||
237          NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
238 }
239
240 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
241   if (Options.OutputCorpus.empty()) return;
242   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
243   WriteToFile(U, Path);
244   if (Options.Verbosity >= 2)
245     Printf("Written to %s\n", Path.c_str());
246   assert(!Options.OnlyASCII || IsASCII(U));
247 }
248
249 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
250   if (!Options.SaveArtifacts)
251     return;
252   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
253   WriteToFile(U, Path);
254   Printf("artifact_prefix='%s'; Test unit written to %s\n",
255          Options.ArtifactPrefix.c_str(), Path.c_str());
256   if (U.size() <= kMaxUnitSizeToPrint) {
257     Printf("Base64: ");
258     PrintFileAsBase64(Path);
259   }
260 }
261
262 void Fuzzer::SaveCorpus() {
263   if (Options.OutputCorpus.empty()) return;
264   for (const auto &U : Corpus)
265     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
266   if (Options.Verbosity)
267     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
268            Options.OutputCorpus.c_str());
269 }
270
271 void Fuzzer::ReportNewCoverage(const Unit &U) {
272   Corpus.push_back(U);
273   UnitHashesAddedToCorpus.insert(Hash(U));
274   PrintStats("NEW   ", "");
275   if (Options.Verbosity) {
276     Printf(" L: %zd", U.size());
277     if (U.size() < 30) {
278       Printf(" ");
279       PrintUnitInASCII(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::Merge(const std::vector<std::string> &Corpora) {
290   if (Corpora.size() <= 1) {
291     Printf("Merge requires two or more corpus dirs\n");
292     return;
293   }
294   auto InitialCorpusDir = Corpora[0];
295   ReadDir(InitialCorpusDir, nullptr);
296   Printf("Merge: running the initial corpus '%s' of %d units\n",
297          InitialCorpusDir.c_str(), Corpus.size());
298   for (auto &U : Corpus)
299     RunOne(U);
300
301   std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
302
303   size_t NumTried = 0;
304   size_t NumMerged = 0;
305   for (auto &C : ExtraCorpora) {
306     Corpus.clear();
307     ReadDir(C, nullptr);
308     Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
309            Corpus.size());
310     for (auto &U : Corpus) {
311       NumTried++;
312       if (RunOne(U)) {
313         WriteToOutputCorpus(U);
314         NumMerged++;
315       }
316     }
317   }
318   Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
319 }
320
321 void Fuzzer::MutateAndTestOne(Unit *U) {
322   for (int i = 0; i < Options.MutateDepth; i++) {
323     StartTraceRecording();
324     size_t Size = U->size();
325     U->resize(Options.MaxLen);
326     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
327     assert(NewSize > 0 && "Mutator returned empty unit");
328     assert(NewSize <= (size_t)Options.MaxLen &&
329            "Mutator return overisized unit");
330     U->resize(NewSize);
331     RunOneAndUpdateCorpus(*U);
332     size_t NumTraceBasedMutations = StopTraceRecording();
333     size_t TBMWidth =
334         std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
335     size_t TBMDepth =
336         std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
337     Unit BackUp = *U;
338     for (size_t w = 0; w < TBMWidth; w++) {
339       *U = BackUp;
340       for (size_t d = 0; d < TBMDepth; d++) {
341         TotalNumberOfExecutedTraceBasedMutations++;
342         ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
343         RunOneAndUpdateCorpus(*U);
344       }
345     }
346   }
347 }
348
349 // Returns an index of random unit from the corpus to mutate.
350 // Hypothesis: units added to the corpus last are more likely to be interesting.
351 // This function gives more wieght to the more recent units.
352 size_t Fuzzer::ChooseUnitToMutate() {
353     size_t N = Corpus.size();
354     size_t Total = (N + 1) * N / 2;
355     size_t R = USF.GetRand()(Total);
356     size_t IdxBeg = 0, IdxEnd = N;
357     // Binary search.
358     while (IdxEnd - IdxBeg >= 2) {
359       size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
360       if (R > (Idx + 1) * Idx / 2)
361         IdxBeg = Idx;
362       else
363         IdxEnd = Idx;
364     }
365     assert(IdxBeg < N);
366     return IdxBeg;
367 }
368
369 void Fuzzer::Loop() {
370   for (auto &U: Options.Dictionary)
371     USF.GetMD().AddWordToDictionary(U.data(), U.size());
372
373   while (true) {
374     size_t J1 = ChooseUnitToMutate();;
375     SyncCorpus();
376     RereadOutputCorpus();
377     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
378       return;
379     if (Options.MaxTotalTimeSec > 0 &&
380         secondsSinceProcessStartUp() >
381         static_cast<size_t>(Options.MaxTotalTimeSec))
382       return;
383     CurrentUnit = Corpus[J1];
384     // Optionally, cross with another unit.
385     if (Options.DoCrossOver && USF.GetRand().RandBool()) {
386       size_t J2 = ChooseUnitToMutate();
387       if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
388         assert(!Corpus[J2].empty());
389         CurrentUnit.resize(Options.MaxLen);
390         size_t NewSize = USF.CrossOver(
391             Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
392             Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
393         assert(NewSize > 0 && "CrossOver returned empty unit");
394         assert(NewSize <= (size_t)Options.MaxLen &&
395                "CrossOver returned overisized unit");
396         CurrentUnit.resize(NewSize);
397       }
398     }
399     // Perform several mutations and runs.
400     MutateAndTestOne(&CurrentUnit);
401   }
402 }
403
404 void Fuzzer::SyncCorpus() {
405   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
406   auto Now = system_clock::now();
407   if (duration_cast<seconds>(Now - LastExternalSync).count() <
408       Options.SyncTimeout)
409     return;
410   LastExternalSync = Now;
411   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
412 }
413
414 }  // namespace fuzzer