blob: 64c567d83f7a93eaa44a2a6b465febfd0d24564a [file] [log] [blame]
Aaron Ballmanef116982015-01-29 16:58:29 +00001//===- 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"
Kostya Serebryany4b96ce92015-02-03 19:42:05 +000013#include <sanitizer/coverage_interface.h>
Aaron Ballmanef116982015-01-29 16:58:29 +000014#include <algorithm>
Aaron Ballmanef116982015-01-29 16:58:29 +000015
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000016extern "C" {
17__attribute__((weak)) void __sanitizer_print_stack_trace();
Kostya Serebryany94660b32015-10-23 18:37:58 +000018__attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000019}
20
Aaron Ballmanef116982015-01-29 16:58:29 +000021namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000022static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000023
Kostya Serebryany52a788e2015-03-31 20:13:20 +000024// Only one Fuzzer per process.
25static Fuzzer *F;
26
Kostya Serebryanyf3424592015-05-22 22:35:31 +000027Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
28 : USF(USF), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000029 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000030 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000031 assert(!F);
32 F = this;
33}
Aaron Ballmanef116982015-01-29 16:58:29 +000034
35void Fuzzer::SetDeathCallback() {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000036 __sanitizer_set_death_callback(StaticDeathCallback);
37}
38
Kostya Serebryanyb3602562015-10-22 21:48:09 +000039void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
40 PrintASCII(U, PrintAfter);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000041}
42
43void Fuzzer::StaticDeathCallback() {
44 assert(F);
45 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000046}
47
48void Fuzzer::DeathCallback() {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000049 Printf("DEATH:\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000050 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
51 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +000052 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000053 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +000054 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
Aaron Ballmanef116982015-01-29 16:58:29 +000055}
56
Kostya Serebryany52a788e2015-03-31 20:13:20 +000057void Fuzzer::StaticAlarmCallback() {
58 assert(F);
59 F->AlarmCallback();
60}
61
Aaron Ballmanef116982015-01-29 16:58:29 +000062void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +000063 assert(Options.UnitTimeoutSec > 0);
Aaron Ballmanef116982015-01-29 16:58:29 +000064 size_t Seconds =
65 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Kostya Serebryany490bbd62015-05-19 22:12:57 +000066 if (Seconds == 0) return;
67 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000068 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +000069 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000070 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +000071 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
72 Options.UnitTimeoutSec);
Kostya Serebryanye95022a2015-10-09 04:03:14 +000073 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
Kostya Serebryany1165efd2015-07-31 22:07:17 +000074 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +000075 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000076 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +000077 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000078 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");
Kostya Serebryany490bbd62015-05-19 22:12:57 +000083 exit(1);
Aaron Ballmanef116982015-01-29 16:58:29 +000084 }
Aaron Ballmanef116982015-01-29 16:58:29 +000085}
86
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +000087void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany03db8b92015-03-30 22:44:03 +000088 if (!Options.Verbosity) return;
89 size_t Seconds = secondsSinceProcessStartUp();
90 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
Kostya Serebryany007c9b22015-10-22 22:50:47 +000091 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +000092 if (LastRecordedBlockCoverage)
93 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +000094 if (auto TB = TotalBits())
95 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +000096 if (LastRecordedCallerCalleeCoverage)
97 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +000098 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +000099 if (TotalNumberOfExecutedTraceBasedMutations)
100 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
101 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000102}
103
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000104void 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;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000114 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000115 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000116 for (auto &X : AdditionalCorpus) {
117 if (X.size() > (size_t)Options.MaxLen)
118 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000119 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000120 CurrentUnit.clear();
121 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000122 if (RunOne(CurrentUnit)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000123 Corpus.push_back(X);
124 if (Options.Verbosity >= 1)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000125 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000126 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000127 }
128 }
129}
130
Aaron Ballmanef116982015-01-29 16:58:29 +0000131void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000132 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
133 (Options.PreferSmallDuringInitialShuffle == -1 &&
134 USF.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000135 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000136 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000137 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000138 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000139 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 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000146 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);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000152 if (Options.OnlyASCII)
153 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000154 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000155 NewCorpus.push_back(U);
156 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000157 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000158 }
159 }
160 }
161 Corpus = NewCorpus;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000162 for (auto &X : Corpus)
163 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000164 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000165}
166
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000167bool Fuzzer::RunOne(const Unit &U) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000168 UnitStartTime = system_clock::now();
169 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000170
171 PrepareCoverageBeforeRun();
172 ExecuteCallback(U);
173 bool Res = CheckCoverageAfterRun();
174
Kostya Serebryany16901a92015-03-30 23:04:35 +0000175 auto UnitStopTime = system_clock::now();
176 auto TimeOfUnit =
177 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000178 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000179 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000180 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
181 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000182 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000183 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000184 WriteUnitToFileWithPrefix(U, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000185 }
186 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000187}
188
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000189void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000190 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
191 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000192 if (Options.OnlyASCII)
193 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000194 if (RunOne(U))
195 ReportNewCoverage(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000196}
197
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000198void Fuzzer::ExecuteCallback(const Unit &U) {
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000199 int Res = USF.TargetFunction(U.data(), U.size());
200 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000201 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000202}
203
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000204size_t Fuzzer::RecordBlockCoverage() {
205 return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
206}
207
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000208size_t Fuzzer::RecordCallerCalleeCoverage() {
209 if (!Options.UseIndirCalls)
210 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000211 if (!__sanitizer_get_total_unique_caller_callee_pairs)
212 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000213 return LastRecordedCallerCalleeCoverage =
214 __sanitizer_get_total_unique_caller_callee_pairs();
215}
216
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000217void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000218 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000219 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000220 CounterBitmap.resize(NumCounters);
221 __sanitizer_update_counter_bitset_and_clear_counters(0);
222 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000223 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000224 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000225}
226
227bool Fuzzer::CheckCoverageAfterRun() {
228 size_t OldCoverage = LastRecordedBlockCoverage;
229 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000230 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
231 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000232 size_t NumNewBits = 0;
233 if (Options.UseCounters)
234 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
235 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000236 return NewCoverage > OldCoverage ||
237 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000238}
239
240void 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)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000245 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000246 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000247}
248
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000249void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000250 if (!Options.SaveArtifacts)
251 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000252 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Aaron Ballmanef116982015-01-29 16:58:29 +0000253 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000254 Printf("artifact_prefix='%s'; Test unit written to %s\n",
255 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany1165efd2015-07-31 22:07:17 +0000256 if (U.size() <= kMaxUnitSizeToPrint) {
257 Printf("Base64: ");
258 PrintFileAsBase64(Path);
259 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000260}
261
262void 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)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000267 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
268 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000269}
270
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000271void Fuzzer::ReportNewCoverage(const Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000272 Corpus.push_back(U);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000273 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000274 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000275 if (Options.Verbosity) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000276 Printf(" L: %zd", U.size());
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000277 if (U.size() < 30) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000278 Printf(" ");
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000279 PrintUnitInASCII(U, "\t");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000280 Print(U);
Aaron Ballmanef116982015-01-29 16:58:29 +0000281 }
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000282 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000283 }
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000284 WriteToOutputCorpus(U);
285 if (Options.ExitOnFirst)
286 exit(0);
Aaron Ballmanef116982015-01-29 16:58:29 +0000287}
288
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000289void 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
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000321void Fuzzer::MutateAndTestOne(Unit *U) {
322 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000323 StartTraceRecording();
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000324 size_t Size = U->size();
325 U->resize(Options.MaxLen);
326 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000327 assert(NewSize > 0 && "Mutator returned empty unit");
328 assert(NewSize <= (size_t)Options.MaxLen &&
329 "Mutator return overisized unit");
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000330 U->resize(NewSize);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000331 RunOneAndUpdateCorpus(*U);
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000332 size_t NumTraceBasedMutations = StopTraceRecording();
Kostya Serebryany12c78372015-08-12 01:55:37 +0000333 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 }
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000345 }
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000346 }
347}
348
Kostya Serebryanye6926212015-11-04 23:22:25 +0000349// 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.
352size_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
Kostya Serebryany468ed782015-09-08 17:30:35 +0000369void Fuzzer::Loop() {
Kostya Serebryany7d211662015-09-04 00:12:11 +0000370 for (auto &U: Options.Dictionary)
371 USF.GetMD().AddWordToDictionary(U.data(), U.size());
372
Kostya Serebryany468ed782015-09-08 17:30:35 +0000373 while (true) {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000374 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);
Aaron Ballmanef116982015-01-29 16:58:29 +0000397 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000398 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000399 // Perform several mutations and runs.
400 MutateAndTestOne(&CurrentUnit);
Aaron Ballmanef116982015-01-29 16:58:29 +0000401 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000402}
403
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000404void 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
Aaron Ballmanef116982015-01-29 16:58:29 +0000414} // namespace fuzzer