[libFuzzer] more refactoring the code that checks the coverage. NFC
[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::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
39   PrintASCII(U, PrintAfter);
40 }
41
42 void Fuzzer::StaticDeathCallback() {
43   assert(F);
44   F->DeathCallback();
45 }
46
47 void Fuzzer::DeathCallback() {
48   Printf("DEATH:\n");
49   if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
50     Print(CurrentUnit, "\n");
51     PrintUnitInASCII(CurrentUnit, "\n");
52   }
53   WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
54 }
55
56 void Fuzzer::StaticAlarmCallback() {
57   assert(F);
58   F->AlarmCallback();
59 }
60
61 void Fuzzer::AlarmCallback() {
62   assert(Options.UnitTimeoutSec > 0);
63   size_t Seconds =
64       duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
65   if (Seconds == 0) return;
66   if (Options.Verbosity >= 2)
67     Printf("AlarmCallback %zd\n", Seconds);
68   if (Seconds >= (size_t)Options.UnitTimeoutSec) {
69     Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
70     Printf("       and the timeout value is %d (use -timeout=N to change)\n",
71            Options.UnitTimeoutSec);
72     if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
73       Print(CurrentUnit, "\n");
74       PrintUnitInASCII(CurrentUnit, "\n");
75     }
76     WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
77     Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
78            Seconds);
79     if (__sanitizer_print_stack_trace)
80       __sanitizer_print_stack_trace();
81     Printf("SUMMARY: libFuzzer: timeout\n");
82     exit(1);
83   }
84 }
85
86 void Fuzzer::PrintStats(const char *Where, const char *End) {
87   if (!Options.Verbosity) return;
88   size_t Seconds = secondsSinceProcessStartUp();
89   size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
90   Printf("#%zd\t%s", TotalNumberOfRuns, Where);
91   if (LastRecordedBlockCoverage)
92     Printf(" cov: %zd", LastRecordedBlockCoverage);
93   if (auto TB = TotalBits())
94     Printf(" bits: %zd", TB);
95   Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
96   if (TotalNumberOfExecutedTraceBasedMutations)
97     Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
98   Printf("%s", End);
99 }
100
101 void Fuzzer::RereadOutputCorpus() {
102   if (Options.OutputCorpus.empty()) return;
103   std::vector<Unit> AdditionalCorpus;
104   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
105                          &EpochOfLastReadOfOutputCorpus);
106   if (Corpus.empty()) {
107     Corpus = AdditionalCorpus;
108     return;
109   }
110   if (!Options.Reload) return;
111   if (Options.Verbosity >= 2)
112     Printf("Reload: read %zd new units.\n",  AdditionalCorpus.size());
113   for (auto &X : AdditionalCorpus) {
114     if (X.size() > (size_t)Options.MaxLen)
115       X.resize(Options.MaxLen);
116     if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
117       CurrentUnit.clear();
118       CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
119       if (RunOne(CurrentUnit)) {
120         Corpus.push_back(X);
121         if (Options.Verbosity >= 1)
122           PrintStats("RELOAD");
123       }
124     }
125   }
126 }
127
128 void Fuzzer::ShuffleAndMinimize() {
129   bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
130                       (Options.PreferSmallDuringInitialShuffle == -1 &&
131                        USF.GetRand().RandBool()));
132   if (Options.Verbosity)
133     Printf("PreferSmall: %d\n", PreferSmall);
134   PrintStats("READ  ");
135   std::vector<Unit> NewCorpus;
136   if (Options.ShuffleAtStartUp) {
137     std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
138     if (PreferSmall)
139       std::stable_sort(
140           Corpus.begin(), Corpus.end(),
141           [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
142   }
143   Unit &U = CurrentUnit;
144   for (const auto &C : Corpus) {
145     for (size_t First = 0; First < 1; First++) {
146       U.clear();
147       size_t Last = std::min(First + Options.MaxLen, C.size());
148       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
149       if (Options.OnlyASCII)
150         ToASCII(U);
151       if (RunOne(U)) {
152         NewCorpus.push_back(U);
153         if (Options.Verbosity >= 2)
154           Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
155       }
156     }
157   }
158   Corpus = NewCorpus;
159   for (auto &X : Corpus)
160     UnitHashesAddedToCorpus.insert(Hash(X));
161   PrintStats("INITED");
162 }
163
164 bool Fuzzer::RunOne(const Unit &U) {
165   UnitStartTime = system_clock::now();
166   TotalNumberOfRuns++;
167
168   PrepareCoverageBeforeRun();
169   ExecuteCallback(U);
170   bool Res = CheckCoverageAfterRun();
171
172   auto UnitStopTime = system_clock::now();
173   auto TimeOfUnit =
174       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
175   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
176     PrintStats("pulse ");
177   if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
178       TimeOfUnit >= Options.ReportSlowUnits) {
179     TimeOfLongestUnitInSeconds = TimeOfUnit;
180     Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
181     WriteUnitToFileWithPrefix(U, "slow-unit-");
182   }
183   return Res;
184 }
185
186 void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
187   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
188     return;
189   if (Options.OnlyASCII)
190     ToASCII(U);
191   if (RunOne(U))
192     ReportNewCoverage(U);
193 }
194
195 void Fuzzer::ExecuteCallback(const Unit &U) {
196   int Res = USF.TargetFunction(U.data(), U.size());
197   (void)Res;
198   assert(Res == 0);
199 }
200
201 size_t Fuzzer::RecordBlockCoverage() {
202   return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
203 }
204
205 void Fuzzer::PrepareCoverageBeforeRun() {
206   if (Options.UseCounters) {
207     size_t NumCounters = __sanitizer_get_number_of_counters();
208     CounterBitmap.resize(NumCounters);
209     __sanitizer_update_counter_bitset_and_clear_counters(0);
210   }
211   RecordBlockCoverage();
212 }
213
214 bool Fuzzer::CheckCoverageAfterRun() {
215   size_t OldCoverage = LastRecordedBlockCoverage;
216   size_t NewCoverage = RecordBlockCoverage();
217   size_t NumNewBits = 0;
218   if (Options.UseCounters)
219     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
220         CounterBitmap.data());
221   return NewCoverage > OldCoverage || NumNewBits;
222 }
223
224 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
225   if (Options.OutputCorpus.empty()) return;
226   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
227   WriteToFile(U, Path);
228   if (Options.Verbosity >= 2)
229     Printf("Written to %s\n", Path.c_str());
230   assert(!Options.OnlyASCII || IsASCII(U));
231 }
232
233 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
234   if (!Options.SaveArtifacts)
235     return;
236   std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
237   WriteToFile(U, Path);
238   Printf("artifact_prefix='%s'; Test unit written to %s\n",
239          Options.ArtifactPrefix.c_str(), Path.c_str());
240   if (U.size() <= kMaxUnitSizeToPrint) {
241     Printf("Base64: ");
242     PrintFileAsBase64(Path);
243   }
244 }
245
246 void Fuzzer::SaveCorpus() {
247   if (Options.OutputCorpus.empty()) return;
248   for (const auto &U : Corpus)
249     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
250   if (Options.Verbosity)
251     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
252            Options.OutputCorpus.c_str());
253 }
254
255 void Fuzzer::ReportNewCoverage(const Unit &U) {
256   Corpus.push_back(U);
257   UnitHashesAddedToCorpus.insert(Hash(U));
258   PrintStats("NEW   ", "");
259   if (Options.Verbosity) {
260     Printf(" L: %zd", U.size());
261     if (U.size() < 30) {
262       Printf(" ");
263       PrintUnitInASCII(U, "\t");
264       Print(U);
265     }
266     Printf("\n");
267   }
268   WriteToOutputCorpus(U);
269   if (Options.ExitOnFirst)
270     exit(0);
271 }
272
273 void Fuzzer::MutateAndTestOne(Unit *U) {
274   for (int i = 0; i < Options.MutateDepth; i++) {
275     StartTraceRecording();
276     size_t Size = U->size();
277     U->resize(Options.MaxLen);
278     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
279     assert(NewSize > 0 && "Mutator returned empty unit");
280     assert(NewSize <= (size_t)Options.MaxLen &&
281            "Mutator return overisized unit");
282     U->resize(NewSize);
283     RunOneAndUpdateCorpus(*U);
284     size_t NumTraceBasedMutations = StopTraceRecording();
285     size_t TBMWidth =
286         std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
287     size_t TBMDepth =
288         std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
289     Unit BackUp = *U;
290     for (size_t w = 0; w < TBMWidth; w++) {
291       *U = BackUp;
292       for (size_t d = 0; d < TBMDepth; d++) {
293         TotalNumberOfExecutedTraceBasedMutations++;
294         ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
295         RunOneAndUpdateCorpus(*U);
296       }
297     }
298   }
299 }
300
301 void Fuzzer::Loop() {
302   for (auto &U: Options.Dictionary)
303     USF.GetMD().AddWordToDictionary(U.data(), U.size());
304
305   while (true) {
306     for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
307       SyncCorpus();
308       RereadOutputCorpus();
309       if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
310         return;
311       if (Options.MaxTotalTimeSec > 0 &&
312           secondsSinceProcessStartUp() >
313               static_cast<size_t>(Options.MaxTotalTimeSec))
314         return;
315       CurrentUnit = Corpus[J1];
316       // Optionally, cross with another unit.
317       if (Options.DoCrossOver && USF.GetRand().RandBool()) {
318         size_t J2 = USF.GetRand()(Corpus.size());
319         if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
320           assert(!Corpus[J2].empty());
321           CurrentUnit.resize(Options.MaxLen);
322           size_t NewSize = USF.CrossOver(
323               Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
324               Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
325           assert(NewSize > 0 && "CrossOver returned empty unit");
326           assert(NewSize <= (size_t)Options.MaxLen &&
327                  "CrossOver returned overisized unit");
328           CurrentUnit.resize(NewSize);
329         }
330       }
331       // Perform several mutations and runs.
332       MutateAndTestOne(&CurrentUnit);
333     }
334   }
335 }
336
337 void Fuzzer::SyncCorpus() {
338   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
339   auto Now = system_clock::now();
340   if (duration_cast<seconds>(Now - LastExternalSync).count() <
341       Options.SyncTimeout)
342     return;
343   LastExternalSync = Now;
344   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
345 }
346
347 }  // namespace fuzzer