blob: d3c32626a3bb3c0bb4672912570bd7b3bce87411 [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" {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000017// Re-declare some of the sanitizer functions as "weak" so that
18// libFuzzer can be linked w/o the sanitizers and sanitizer-coveragte
19// (in which case it will complain at start-up time).
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000020__attribute__((weak)) void __sanitizer_print_stack_trace();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +000021__attribute__((weak)) void __sanitizer_reset_coverage();
Kostya Serebryany94660b32015-10-23 18:37:58 +000022__attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000023__attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
24__attribute__((weak))
25void __sanitizer_set_death_callback(void (*callback)(void));
26__attribute__((weak)) size_t __sanitizer_get_number_of_counters();
27__attribute__((weak))
28uintptr_t __sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000029}
30
Aaron Ballmanef116982015-01-29 16:58:29 +000031namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000032static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000033
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000034static void MissingWeakApiFunction(const char *FnName) {
35 Printf("ERROR: %s is not defined. Exiting.\n"
36 "Did you use -fsanitize-coverage=... to build your code?\n", FnName);
37 exit(1);
38}
39
40#define CHECK_WEAK_API_FUNCTION(fn) \
41 do { \
42 if (!fn) \
43 MissingWeakApiFunction(#fn); \
44 } while (false)
45
Kostya Serebryany52a788e2015-03-31 20:13:20 +000046// Only one Fuzzer per process.
47static Fuzzer *F;
48
Kostya Serebryanyf3424592015-05-22 22:35:31 +000049Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
50 : USF(USF), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000051 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000052 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000053 assert(!F);
54 F = this;
55}
Aaron Ballmanef116982015-01-29 16:58:29 +000056
57void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000058 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000059 __sanitizer_set_death_callback(StaticDeathCallback);
60}
61
Kostya Serebryanyb3602562015-10-22 21:48:09 +000062void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
63 PrintASCII(U, PrintAfter);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000064}
65
66void Fuzzer::StaticDeathCallback() {
67 assert(F);
68 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000069}
70
71void Fuzzer::DeathCallback() {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000072 Printf("DEATH:\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000073 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
74 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, "crash-");
Aaron Ballmanef116982015-01-29 16:58:29 +000078}
79
Kostya Serebryany52a788e2015-03-31 20:13:20 +000080void Fuzzer::StaticAlarmCallback() {
81 assert(F);
82 F->AlarmCallback();
83}
84
Aaron Ballmanef116982015-01-29 16:58:29 +000085void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +000086 assert(Options.UnitTimeoutSec > 0);
Aaron Ballmanef116982015-01-29 16:58:29 +000087 size_t Seconds =
88 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Kostya Serebryany490bbd62015-05-19 22:12:57 +000089 if (Seconds == 0) return;
90 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000091 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +000092 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000093 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +000094 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
95 Options.UnitTimeoutSec);
Kostya Serebryanye95022a2015-10-09 04:03:14 +000096 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
Kostya Serebryany1165efd2015-07-31 22:07:17 +000097 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +000098 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000099 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000100 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000101 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
102 Seconds);
103 if (__sanitizer_print_stack_trace)
104 __sanitizer_print_stack_trace();
105 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000106 exit(1);
Aaron Ballmanef116982015-01-29 16:58:29 +0000107 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000108}
109
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000110void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000111 if (!Options.Verbosity) return;
112 size_t Seconds = secondsSinceProcessStartUp();
113 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000114 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000115 if (LastRecordedBlockCoverage)
116 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000117 if (auto TB = TotalBits())
118 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000119 if (LastRecordedCallerCalleeCoverage)
120 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000121 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000122 if (TotalNumberOfExecutedTraceBasedMutations)
123 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
124 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000125}
126
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000127void Fuzzer::RereadOutputCorpus() {
128 if (Options.OutputCorpus.empty()) return;
129 std::vector<Unit> AdditionalCorpus;
130 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
131 &EpochOfLastReadOfOutputCorpus);
132 if (Corpus.empty()) {
133 Corpus = AdditionalCorpus;
134 return;
135 }
136 if (!Options.Reload) return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000137 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000138 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000139 for (auto &X : AdditionalCorpus) {
140 if (X.size() > (size_t)Options.MaxLen)
141 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000142 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000143 CurrentUnit.clear();
144 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000145 if (RunOne(CurrentUnit)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000146 Corpus.push_back(X);
147 if (Options.Verbosity >= 1)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000148 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000149 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000150 }
151 }
152}
153
Aaron Ballmanef116982015-01-29 16:58:29 +0000154void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000155 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
156 (Options.PreferSmallDuringInitialShuffle == -1 &&
157 USF.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000158 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000159 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000160 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000161 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000162 if (Options.ShuffleAtStartUp) {
163 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
164 if (PreferSmall)
165 std::stable_sort(
166 Corpus.begin(), Corpus.end(),
167 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
168 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000169 Unit &U = CurrentUnit;
170 for (const auto &C : Corpus) {
171 for (size_t First = 0; First < 1; First++) {
172 U.clear();
173 size_t Last = std::min(First + Options.MaxLen, C.size());
174 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000175 if (Options.OnlyASCII)
176 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000177 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000178 NewCorpus.push_back(U);
179 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000180 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000181 }
182 }
183 }
184 Corpus = NewCorpus;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000185 for (auto &X : Corpus)
186 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000187 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000188}
189
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000190bool Fuzzer::RunOne(const Unit &U) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000191 UnitStartTime = system_clock::now();
192 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000193
194 PrepareCoverageBeforeRun();
195 ExecuteCallback(U);
196 bool Res = CheckCoverageAfterRun();
197
Kostya Serebryany16901a92015-03-30 23:04:35 +0000198 auto UnitStopTime = system_clock::now();
199 auto TimeOfUnit =
200 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Kostya Serebryanyb8d0da12015-11-05 01:19:42 +0000201 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1))
202 && secondsSinceProcessStartUp() >= 2
203 && Options.Verbosity)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000204 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000205 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
206 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000207 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000208 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000209 WriteUnitToFileWithPrefix(U, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000210 }
211 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000212}
213
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000214void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000215 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
216 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000217 if (Options.OnlyASCII)
218 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000219 if (RunOne(U))
220 ReportNewCoverage(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000221}
222
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000223void Fuzzer::ExecuteCallback(const Unit &U) {
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000224 int Res = USF.TargetFunction(U.data(), U.size());
225 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000226 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000227}
228
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000229size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000230 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000231 return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
232}
233
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000234size_t Fuzzer::RecordCallerCalleeCoverage() {
235 if (!Options.UseIndirCalls)
236 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000237 if (!__sanitizer_get_total_unique_caller_callee_pairs)
238 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000239 return LastRecordedCallerCalleeCoverage =
240 __sanitizer_get_total_unique_caller_callee_pairs();
241}
242
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000243void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000244 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000245 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000246 CounterBitmap.resize(NumCounters);
247 __sanitizer_update_counter_bitset_and_clear_counters(0);
248 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000249 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000250 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000251}
252
253bool Fuzzer::CheckCoverageAfterRun() {
254 size_t OldCoverage = LastRecordedBlockCoverage;
255 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000256 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
257 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000258 size_t NumNewBits = 0;
259 if (Options.UseCounters)
260 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
261 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000262 return NewCoverage > OldCoverage ||
263 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000264}
265
266void Fuzzer::WriteToOutputCorpus(const Unit &U) {
267 if (Options.OutputCorpus.empty()) return;
268 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
269 WriteToFile(U, Path);
270 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000271 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000272 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000273}
274
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000275void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000276 if (!Options.SaveArtifacts)
277 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000278 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Aaron Ballmanef116982015-01-29 16:58:29 +0000279 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000280 Printf("artifact_prefix='%s'; Test unit written to %s\n",
281 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany1165efd2015-07-31 22:07:17 +0000282 if (U.size() <= kMaxUnitSizeToPrint) {
283 Printf("Base64: ");
284 PrintFileAsBase64(Path);
285 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000286}
287
288void Fuzzer::SaveCorpus() {
289 if (Options.OutputCorpus.empty()) return;
290 for (const auto &U : Corpus)
291 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
292 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000293 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
294 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000295}
296
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000297void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
298 if (!Options.PrintNEW)
299 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000300 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000301 if (Options.Verbosity) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000302 Printf(" L: %zd", U.size());
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000303 if (U.size() < 30) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000304 Printf(" ");
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000305 PrintUnitInASCII(U, "\t");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000306 Print(U);
Aaron Ballmanef116982015-01-29 16:58:29 +0000307 }
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000308 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000309 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000310}
311
312void Fuzzer::ReportNewCoverage(const Unit &U) {
313 Corpus.push_back(U);
314 UnitHashesAddedToCorpus.insert(Hash(U));
315 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000316 WriteToOutputCorpus(U);
317 if (Options.ExitOnFirst)
318 exit(0);
Aaron Ballmanef116982015-01-29 16:58:29 +0000319}
320
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000321void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
322 if (Corpora.size() <= 1) {
323 Printf("Merge requires two or more corpus dirs\n");
324 return;
325 }
326 auto InitialCorpusDir = Corpora[0];
327 ReadDir(InitialCorpusDir, nullptr);
328 Printf("Merge: running the initial corpus '%s' of %d units\n",
329 InitialCorpusDir.c_str(), Corpus.size());
330 for (auto &U : Corpus)
331 RunOne(U);
332
333 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
334
335 size_t NumTried = 0;
336 size_t NumMerged = 0;
337 for (auto &C : ExtraCorpora) {
338 Corpus.clear();
339 ReadDir(C, nullptr);
340 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
341 Corpus.size());
342 for (auto &U : Corpus) {
343 NumTried++;
344 if (RunOne(U)) {
345 WriteToOutputCorpus(U);
346 NumMerged++;
347 }
348 }
349 }
350 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
351}
352
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000353void Fuzzer::MutateAndTestOne(Unit *U) {
354 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000355 StartTraceRecording();
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000356 size_t Size = U->size();
357 U->resize(Options.MaxLen);
358 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000359 assert(NewSize > 0 && "Mutator returned empty unit");
360 assert(NewSize <= (size_t)Options.MaxLen &&
361 "Mutator return overisized unit");
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000362 U->resize(NewSize);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000363 RunOneAndUpdateCorpus(*U);
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000364 size_t NumTraceBasedMutations = StopTraceRecording();
Kostya Serebryany12c78372015-08-12 01:55:37 +0000365 size_t TBMWidth =
366 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
367 size_t TBMDepth =
368 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
369 Unit BackUp = *U;
370 for (size_t w = 0; w < TBMWidth; w++) {
371 *U = BackUp;
372 for (size_t d = 0; d < TBMDepth; d++) {
373 TotalNumberOfExecutedTraceBasedMutations++;
374 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
375 RunOneAndUpdateCorpus(*U);
376 }
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000377 }
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000378 }
379}
380
Kostya Serebryanye6926212015-11-04 23:22:25 +0000381// Returns an index of random unit from the corpus to mutate.
382// Hypothesis: units added to the corpus last are more likely to be interesting.
383// This function gives more wieght to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000384size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000385 size_t N = Corpus.size();
386 size_t Total = (N + 1) * N / 2;
387 size_t R = USF.GetRand()(Total);
388 size_t IdxBeg = 0, IdxEnd = N;
389 // Binary search.
390 while (IdxEnd - IdxBeg >= 2) {
391 size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
392 if (R > (Idx + 1) * Idx / 2)
393 IdxBeg = Idx;
394 else
395 IdxEnd = Idx;
396 }
397 assert(IdxBeg < N);
398 return IdxBeg;
399}
400
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000401// Experimental search heuristic: drilling.
402// - Read, shuffle, execute and minimize the corpus.
403// - Choose one random unit.
404// - Reset the coverage.
405// - Start fuzzing as if the chosen unit was the only element of the corpus.
406// - When done, reset the coverage again.
407// - Merge the newly created corpus into the original one.
408void Fuzzer::Drill() {
409 // The corpus is already read, shuffled, and minimized.
410 assert(!Corpus.empty());
411 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000412
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000413 Unit U = ChooseUnitToMutate();
414
415 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
416 __sanitizer_reset_coverage();
417
418 std::vector<Unit> SavedCorpus;
419 SavedCorpus.swap(Corpus);
420 Corpus.push_back(U);
421 assert(Corpus.size() == 1);
422 RunOne(U);
423 PrintStats("DRILL ");
424 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
425 SavedOutputCorpusPath.swap(Options.OutputCorpus);
426 Loop();
427
428 __sanitizer_reset_coverage();
429
430 PrintStats("REINIT");
431 SavedOutputCorpusPath.swap(Options.OutputCorpus);
432 for (auto &U : SavedCorpus)
433 RunOne(U);
434 PrintStats("MERGE ");
435 Options.PrintNEW = true;
436 size_t NumMerged = 0;
437 for (auto &U : Corpus) {
438 if (RunOne(U)) {
439 PrintStatusForNewUnit(U);
440 NumMerged++;
441 WriteToOutputCorpus(U);
442 }
443 }
444 PrintStats("MERGED");
445 if (NumMerged && Options.Verbosity)
446 Printf("Drilling discovered %zd new units\n", NumMerged);
447}
448
449void Fuzzer::Loop() {
Kostya Serebryany468ed782015-09-08 17:30:35 +0000450 while (true) {
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000451 size_t J1 = ChooseUnitIdxToMutate();;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000452 SyncCorpus();
453 RereadOutputCorpus();
454 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
455 return;
456 if (Options.MaxTotalTimeSec > 0 &&
457 secondsSinceProcessStartUp() >
458 static_cast<size_t>(Options.MaxTotalTimeSec))
459 return;
460 CurrentUnit = Corpus[J1];
461 // Optionally, cross with another unit.
462 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000463 size_t J2 = ChooseUnitIdxToMutate();
Kostya Serebryanye6926212015-11-04 23:22:25 +0000464 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
465 assert(!Corpus[J2].empty());
466 CurrentUnit.resize(Options.MaxLen);
467 size_t NewSize = USF.CrossOver(
468 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
469 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
470 assert(NewSize > 0 && "CrossOver returned empty unit");
471 assert(NewSize <= (size_t)Options.MaxLen &&
472 "CrossOver returned overisized unit");
473 CurrentUnit.resize(NewSize);
Aaron Ballmanef116982015-01-29 16:58:29 +0000474 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000475 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000476 // Perform several mutations and runs.
477 MutateAndTestOne(&CurrentUnit);
Aaron Ballmanef116982015-01-29 16:58:29 +0000478 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000479}
480
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000481void Fuzzer::SyncCorpus() {
482 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
483 auto Now = system_clock::now();
484 if (duration_cast<seconds>(Now - LastExternalSync).count() <
485 Options.SyncTimeout)
486 return;
487 LastExternalSync = Now;
488 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
489}
490
Aaron Ballmanef116982015-01-29 16:58:29 +0000491} // namespace fuzzer