5e8e2e4aae34a12c4fe34a91c9d5be0361a6ebdf
[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 namespace fuzzer {
17 static const size_t kMaxUnitSizeToPrint = 4096;
18
19 // Only one Fuzzer per process.
20 static Fuzzer *F;
21
22 Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
23     : USF(USF), Options(Options) {
24   SetDeathCallback();
25   InitializeTraceState();
26   assert(!F);
27   F = this;
28 }
29
30 void Fuzzer::SetDeathCallback() {
31   __sanitizer_set_death_callback(StaticDeathCallback);
32 }
33
34 void Fuzzer::PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter) {
35   if (Options.Tokens.empty()) {
36     PrintASCII(U, PrintAfter);
37   } else {
38     auto T = SubstituteTokens(U);
39     T.push_back(0);
40     Printf("%s%s", T.data(), PrintAfter);
41   }
42 }
43
44 void Fuzzer::StaticDeathCallback() {
45   assert(F);
46   F->DeathCallback();
47 }
48
49 void Fuzzer::DeathCallback() {
50   Printf("DEATH:\n");
51   Print(CurrentUnit, "\n");
52   PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
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     PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
75     WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
76     exit(1);
77   }
78 }
79
80 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
81   if (!Options.Verbosity) return;
82   size_t Seconds = secondsSinceProcessStartUp();
83   size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
84   Printf("#%zd\t%s cov %zd bits %zd units %zd exec/s %zd %s", TotalNumberOfRuns,
85          Where, Cov, TotalBits(), Corpus.size(), ExecPerSec, End);
86 }
87
88 void Fuzzer::RereadOutputCorpus() {
89   if (Options.OutputCorpus.empty()) return;
90   std::vector<Unit> AdditionalCorpus;
91   ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
92                          &EpochOfLastReadOfOutputCorpus);
93   if (Corpus.empty()) {
94     Corpus = AdditionalCorpus;
95     return;
96   }
97   if (!Options.Reload) return;
98   if (Options.Verbosity >= 2)
99     Printf("Reload: read %zd new units.\n",  AdditionalCorpus.size());
100   for (auto &X : AdditionalCorpus) {
101     if (X.size() > (size_t)Options.MaxLen)
102       X.resize(Options.MaxLen);
103     if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
104       CurrentUnit.clear();
105       CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
106       size_t NewCoverage = RunOne(CurrentUnit);
107       if (NewCoverage) {
108         Corpus.push_back(X);
109         if (Options.Verbosity >= 1)
110           PrintStats("RELOAD", NewCoverage);
111       }
112     }
113   }
114 }
115
116 void Fuzzer::ShuffleAndMinimize() {
117   size_t MaxCov = 0;
118   bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
119                       (Options.PreferSmallDuringInitialShuffle == -1 &&
120                        USF.GetRand().RandBool()));
121   if (Options.Verbosity)
122     Printf("PreferSmall: %d\n", PreferSmall);
123   PrintStats("READ  ", 0);
124   std::vector<Unit> NewCorpus;
125   std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
126   if (PreferSmall)
127     std::stable_sort(
128         Corpus.begin(), Corpus.end(),
129         [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
130   Unit &U = CurrentUnit;
131   for (const auto &C : Corpus) {
132     for (size_t First = 0; First < 1; First++) {
133       U.clear();
134       size_t Last = std::min(First + Options.MaxLen, C.size());
135       U.insert(U.begin(), C.begin() + First, C.begin() + Last);
136       size_t NewCoverage = RunOne(U);
137       if (NewCoverage) {
138         MaxCov = NewCoverage;
139         NewCorpus.push_back(U);
140         if (Options.Verbosity >= 2)
141           Printf("NEW0: %zd L %zd\n", NewCoverage, U.size());
142       }
143     }
144   }
145   Corpus = NewCorpus;
146   for (auto &X : Corpus)
147     UnitHashesAddedToCorpus.insert(Hash(X));
148   PrintStats("INITED", MaxCov);
149 }
150
151 size_t Fuzzer::RunOne(const Unit &U) {
152   UnitStartTime = system_clock::now();
153   TotalNumberOfRuns++;
154   size_t Res = 0;
155   if (Options.UseFullCoverageSet)
156     Res = RunOneMaximizeFullCoverageSet(U);
157   else
158     Res = RunOneMaximizeTotalCoverage(U);
159   auto UnitStopTime = system_clock::now();
160   auto TimeOfUnit =
161       duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
162   if (TimeOfUnit > TimeOfLongestUnitInSeconds) {
163     TimeOfLongestUnitInSeconds = TimeOfUnit;
164     Printf("Longest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
165     if (U.size() <= kMaxUnitSizeToPrint)
166       Print(U, "\n");
167     WriteUnitToFileWithPrefix(U, "long-running-unit-");
168   }
169   return Res;
170 }
171
172 void Fuzzer::RunOneAndUpdateCorpus(const Unit &U) {
173   if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
174     return;
175   ReportNewCoverage(RunOne(U), U);
176 }
177
178 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
179   uintptr_t Res = 0;
180   for (uintptr_t i = 0; i < NumPCs; i++) {
181     Res = (Res + PCs[i]) * 7;
182   }
183   return Res;
184 }
185
186 Unit Fuzzer::SubstituteTokens(const Unit &U) const {
187   Unit Res;
188   for (auto Idx : U) {
189     if (Idx < Options.Tokens.size()) {
190       std::string Token = Options.Tokens[Idx];
191       Res.insert(Res.end(), Token.begin(), Token.end());
192     } else {
193       Res.push_back(' ');
194     }
195   }
196   // FIXME: Apply DFSan labels.
197   return Res;
198 }
199
200 void Fuzzer::ExecuteCallback(const Unit &U) {
201   if (Options.Tokens.empty()) {
202     USF.TargetFunction(U.data(), U.size());
203   } else {
204     auto T = SubstituteTokens(U);
205     USF.TargetFunction(T.data(), T.size());
206   }
207 }
208
209 // Experimental.
210 // Fuly reset the current coverage state, run a single unit,
211 // compute a hash function from the full coverage set,
212 // return non-zero if the hash value is new.
213 // This produces tons of new units and as is it's only suitable for small tests,
214 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
215 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
216   __sanitizer_reset_coverage();
217   ExecuteCallback(U);
218   uintptr_t *PCs;
219   uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
220   if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
221     return FullCoverageSets.size();
222   return 0;
223 }
224
225 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
226   size_t NumCounters = __sanitizer_get_number_of_counters();
227   if (Options.UseCounters) {
228     CounterBitmap.resize(NumCounters);
229     __sanitizer_update_counter_bitset_and_clear_counters(0);
230   }
231   size_t OldCoverage = __sanitizer_get_total_unique_coverage();
232   ExecuteCallback(U);
233   size_t NewCoverage = __sanitizer_get_total_unique_coverage();
234   size_t NumNewBits = 0;
235   if (Options.UseCounters)
236     NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
237         CounterBitmap.data());
238
239   if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
240     PrintStats("pulse ", NewCoverage);
241
242   if (NewCoverage > OldCoverage || NumNewBits)
243     return NewCoverage;
244   return 0;
245 }
246
247 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
248   if (Options.OutputCorpus.empty()) return;
249   std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
250   WriteToFile(U, Path);
251   if (Options.Verbosity >= 2)
252     Printf("Written to %s\n", Path.c_str());
253 }
254
255 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
256   std::string Path = Prefix + Hash(U);
257   WriteToFile(U, Path);
258   Printf("Test unit written to %s\n", Path.c_str());
259   if (U.size() <= kMaxUnitSizeToPrint) {
260     Printf("Base64: ");
261     PrintFileAsBase64(Path);
262   }
263 }
264
265 void Fuzzer::SaveCorpus() {
266   if (Options.OutputCorpus.empty()) return;
267   for (const auto &U : Corpus)
268     WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
269   if (Options.Verbosity)
270     Printf("Written corpus of %zd files to %s\n", Corpus.size(),
271            Options.OutputCorpus.c_str());
272 }
273
274 void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
275   if (!NewCoverage) return;
276   Corpus.push_back(U);
277   UnitHashesAddedToCorpus.insert(Hash(U));
278   PrintStats("NEW   ", NewCoverage, "");
279   if (Options.Verbosity) {
280     Printf(" L: %zd", U.size());
281     if (U.size() < 30) {
282       Printf(" ");
283       PrintUnitInASCIIOrTokens(U, "\t");
284       Print(U);
285     }
286     Printf("\n");
287   }
288   WriteToOutputCorpus(U);
289   if (Options.ExitOnFirst)
290     exit(0);
291 }
292
293 void Fuzzer::MutateAndTestOne(Unit *U) {
294   for (int i = 0; i < Options.MutateDepth; i++) {
295     StartTraceRecording();
296     size_t Size = U->size();
297     U->resize(Options.MaxLen);
298     size_t NewSize = USF.Mutate(U->data(), Size, U->size());
299     assert(NewSize > 0 && "Mutator returned empty unit");
300     assert(NewSize <= (size_t)Options.MaxLen &&
301            "Mutator return overisized unit");
302     U->resize(NewSize);
303     RunOneAndUpdateCorpus(*U);
304     size_t NumTraceBasedMutations = StopTraceRecording();
305     for (size_t j = 0; j < NumTraceBasedMutations; j++) {
306       ApplyTraceBasedMutation(j, U);
307       RunOneAndUpdateCorpus(*U);
308     }
309   }
310 }
311
312 void Fuzzer::Loop(size_t NumIterations) {
313   for (size_t i = 1; i <= NumIterations; i++) {
314     for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
315       SyncCorpus();
316       RereadOutputCorpus();
317       if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
318         return;
319       // First, simply mutate the unit w/o doing crosses.
320       CurrentUnit = Corpus[J1];
321       MutateAndTestOne(&CurrentUnit);
322       // Now, cross with others.
323       if (Options.DoCrossOver && !Corpus[J1].empty()) {
324         for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
325           CurrentUnit.resize(Options.MaxLen);
326           size_t NewSize = USF.CrossOver(
327               Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
328               Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
329           assert(NewSize > 0 && "CrossOver returned empty unit");
330           assert(NewSize <= (size_t)Options.MaxLen &&
331                  "CrossOver return overisized unit");
332           CurrentUnit.resize(NewSize);
333           MutateAndTestOne(&CurrentUnit);
334         }
335       }
336     }
337   }
338 }
339
340 void Fuzzer::SyncCorpus() {
341   if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
342   auto Now = system_clock::now();
343   if (duration_cast<seconds>(Now - LastExternalSync).count() <
344       Options.SyncTimeout)
345     return;
346   LastExternalSync = Now;
347   ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
348 }
349
350 }  // namespace fuzzer