AMDGPU/SI: Refactor VOP[12C] tablegen definitions
[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))
179       && secondsSinceProcessStartUp() >= 2
180       && Options.Verbosity)
181     PrintStats("pulse ");
182   if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
183       TimeOfUnit >= Options.ReportSlowUnits) {
184     TimeOfLongestUnitInSeconds = TimeOfUnit;
185     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
186     WriteUnitToFileWithPrefix(U, "slow-unit-");
187   }
188   return Res;
189 }
190
191 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
192   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
193     return;
194   if (Options.OnlyASCII)
195     ToASCII(U);
196   if (RunOne(U))
197     ReportNewCoverage(U);
198 }
199
200 void Fuzzer::ExecuteCallback(const Unit &U) {
201   int Res = USF.TargetFunction(U.data(), U.size());
202   (void)Res;
203   assert(Res == 0);
204 }
205
206 size_t Fuzzer::RecordBlockCoverage() {
207   return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
208 }
209
210 size_t Fuzzer::RecordCallerCalleeCoverage() {
211   if (!Options.UseIndirCalls)
212     return 0;
213   if (!__sanitizer_get_total_unique_caller_callee_pairs)
214     return 0;
215   return LastRecordedCallerCalleeCoverage =
216              __sanitizer_get_total_unique_caller_callee_pairs();
217 }
218
219 void Fuzzer::PrepareCoverageBeforeRun() {
220   if (Options.UseCounters) {
221     size_t NumCounters = __sanitizer_get_number_of_counters();
222     CounterBitmap.resize(NumCounters);
223     __sanitizer_update_counter_bitset_and_clear_counters(0);
224   }
225   RecordBlockCoverage();
226   RecordCallerCalleeCoverage();
227 }
228
229 bool Fuzzer::CheckCoverageAfterRun() {
230   size_t OldCoverage = LastRecordedBlockCoverage;
231   size_t NewCoverage = RecordBlockCoverage();
232   size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
233   size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
234   size_t NumNewBits = 0;
235   if (Options.UseCounters)
236     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
237         CounterBitmap.data());
238   return NewCoverage > OldCoverage ||
239          NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
240 }
241
242 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
243   if (Options.OutputCorpus.empty()) return;
244   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
245   WriteToFile(U, Path);
246   if (Options.Verbosity >= 2)
247     Printf("Written to %s\n", Path.c_str());
248   assert(!Options.OnlyASCII || IsASCII(U));
249 }
250
251 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
252   if (!Options.SaveArtifacts)
253     return;
254   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
255   WriteToFile(U, Path);
256   Printf("artifact_prefix='%s'; Test unit written to %s\n",
257          Options.ArtifactPrefix.c_str(), Path.c_str());
258   if (U.size() <= kMaxUnitSizeToPrint) {
259     Printf("Base64: ");
260     PrintFileAsBase64(Path);
261   }
262 }
263
264 void Fuzzer::SaveCorpus() {
265   if (Options.OutputCorpus.empty()) return;
266   for (const auto &U : Corpus)
267     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
268   if (Options.Verbosity)
269     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
270            Options.OutputCorpus.c_str());
271 }
272
273 void Fuzzer::ReportNewCoverage(const Unit &U) {
274   Corpus.push_back(U);
275   UnitHashesAddedToCorpus.insert(Hash(U));
276   PrintStats("NEW   ", "");
277   if (Options.Verbosity) {
278     Printf(" L: %zd", U.size());
279     if (U.size() < 30) {
280       Printf(" ");
281       PrintUnitInASCII(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::Merge(const std::vector<std::string> &Corpora) {
292   if (Corpora.size() <= 1) {
293     Printf("Merge requires two or more corpus dirs\n");
294     return;
295   }
296   auto InitialCorpusDir = Corpora[0];
297   ReadDir(InitialCorpusDir, nullptr);
298   Printf("Merge: running the initial corpus '%s' of %d units\n",
299          InitialCorpusDir.c_str(), Corpus.size());
300   for (auto &U : Corpus)
301     RunOne(U);
302
303   std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
304
305   size_t NumTried = 0;
306   size_t NumMerged = 0;
307   for (auto &C : ExtraCorpora) {
308     Corpus.clear();
309     ReadDir(C, nullptr);
310     Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
311            Corpus.size());
312     for (auto &U : Corpus) {
313       NumTried++;
314       if (RunOne(U)) {
315         WriteToOutputCorpus(U);
316         NumMerged++;
317       }
318     }
319   }
320   Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
321 }
322
323 void Fuzzer::MutateAndTestOne(Unit *U) {
324   for (int i = 0; i < Options.MutateDepth; i++) {
325     StartTraceRecording();
326     size_t Size = U->size();
327     U->resize(Options.MaxLen);
328     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
329     assert(NewSize > 0 && "Mutator returned empty unit");
330     assert(NewSize <= (size_t)Options.MaxLen &&
331            "Mutator return overisized unit");
332     U->resize(NewSize);
333     RunOneAndUpdateCorpus(*U);
334     size_t NumTraceBasedMutations = StopTraceRecording();
335     size_t TBMWidth =
336         std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
337     size_t TBMDepth =
338         std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
339     Unit BackUp = *U;
340     for (size_t w = 0; w < TBMWidth; w++) {
341       *U = BackUp;
342       for (size_t d = 0; d < TBMDepth; d++) {
343         TotalNumberOfExecutedTraceBasedMutations++;
344         ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
345         RunOneAndUpdateCorpus(*U);
346       }
347     }
348   }
349 }
350
351 // Returns an index of random unit from the corpus to mutate.
352 // Hypothesis: units added to the corpus last are more likely to be interesting.
353 // This function gives more wieght to the more recent units.
354 size_t Fuzzer::ChooseUnitToMutate() {
355     size_t N = Corpus.size();
356     size_t Total = (N + 1) * N / 2;
357     size_t R = USF.GetRand()(Total);
358     size_t IdxBeg = 0, IdxEnd = N;
359     // Binary search.
360     while (IdxEnd - IdxBeg >= 2) {
361       size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
362       if (R > (Idx + 1) * Idx / 2)
363         IdxBeg = Idx;
364       else
365         IdxEnd = Idx;
366     }
367     assert(IdxBeg < N);
368     return IdxBeg;
369 }
370
371 void Fuzzer::Loop() {
372   for (auto &U: Options.Dictionary)
373     USF.GetMD().AddWordToDictionary(U.data(), U.size());
374
375   while (true) {
376     size_t J1 = ChooseUnitToMutate();;
377     SyncCorpus();
378     RereadOutputCorpus();
379     if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
380       return;
381     if (Options.MaxTotalTimeSec > 0 &&
382         secondsSinceProcessStartUp() >
383         static_cast<size_t>(Options.MaxTotalTimeSec))
384       return;
385     CurrentUnit = Corpus[J1];
386     // Optionally, cross with another unit.
387     if (Options.DoCrossOver && USF.GetRand().RandBool()) {
388       size_t J2 = ChooseUnitToMutate();
389       if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
390         assert(!Corpus[J2].empty());
391         CurrentUnit.resize(Options.MaxLen);
392         size_t NewSize = USF.CrossOver(
393             Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
394             Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
395         assert(NewSize > 0 && "CrossOver returned empty unit");
396         assert(NewSize <= (size_t)Options.MaxLen &&
397                "CrossOver returned overisized unit");
398         CurrentUnit.resize(NewSize);
399       }
400     }
401     // Perform several mutations and runs.
402     MutateAndTestOne(&CurrentUnit);
403   }
404 }
405
406 void Fuzzer::SyncCorpus() {
407   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
408   auto Now = system_clock::now();
409   if (duration_cast<seconds>(Now - LastExternalSync).count() <
410       Options.SyncTimeout)
411     return;
412   LastExternalSync = Now;
413   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
414 }
415
416 }  // namespace fuzzer