blob: ccc05c8b128103680d226f9fb3747fa8e3805e3a [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"
Aaron Ballmanef116982015-01-29 16:58:29 +000013#include <algorithm>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000014#include <cstring>
15#include <memory>
Aaron Ballmanef116982015-01-29 16:58:29 +000016
Kostya Serebryany2a48c242015-11-13 01:54:40 +000017#if defined(__has_include)
18# if __has_include(<sanitizer/coverage_interface.h>)
19# include <sanitizer/coverage_interface.h>
20# endif
21#endif
22
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000023extern "C" {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000024// Re-declare some of the sanitizer functions as "weak" so that
Kostya Serebryany2a48c242015-11-13 01:54:40 +000025// libFuzzer can be linked w/o the sanitizers and sanitizer-coverage
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000026// (in which case it will complain at start-up time).
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000027__attribute__((weak)) void __sanitizer_print_stack_trace();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +000028__attribute__((weak)) void __sanitizer_reset_coverage();
Kostya Serebryany94660b32015-10-23 18:37:58 +000029__attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000030__attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
31__attribute__((weak))
32void __sanitizer_set_death_callback(void (*callback)(void));
33__attribute__((weak)) size_t __sanitizer_get_number_of_counters();
34__attribute__((weak))
35uintptr_t __sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
Mike Aizatsky8b11f872016-01-06 00:21:22 +000036__attribute__((weak)) uintptr_t
37__sanitizer_get_coverage_pc_buffer(uintptr_t **data);
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000038}
39
Aaron Ballmanef116982015-01-29 16:58:29 +000040namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000041static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000042
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000043static void MissingWeakApiFunction(const char *FnName) {
44 Printf("ERROR: %s is not defined. Exiting.\n"
45 "Did you use -fsanitize-coverage=... to build your code?\n", FnName);
46 exit(1);
47}
48
49#define CHECK_WEAK_API_FUNCTION(fn) \
50 do { \
51 if (!fn) \
52 MissingWeakApiFunction(#fn); \
53 } while (false)
54
Kostya Serebryany52a788e2015-03-31 20:13:20 +000055// Only one Fuzzer per process.
56static Fuzzer *F;
57
Kostya Serebryanyf3424592015-05-22 22:35:31 +000058Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
59 : USF(USF), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000060 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000061 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000062 assert(!F);
63 F = this;
64}
Aaron Ballmanef116982015-01-29 16:58:29 +000065
66void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000067 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000068 __sanitizer_set_death_callback(StaticDeathCallback);
69}
70
Kostya Serebryanyb3602562015-10-22 21:48:09 +000071void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
72 PrintASCII(U, PrintAfter);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000073}
74
75void Fuzzer::StaticDeathCallback() {
76 assert(F);
77 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000078}
79
80void Fuzzer::DeathCallback() {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000081 Printf("DEATH:\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000082 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
83 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +000084 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000085 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +000086 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
Aaron Ballmanef116982015-01-29 16:58:29 +000087}
88
Kostya Serebryany52a788e2015-03-31 20:13:20 +000089void Fuzzer::StaticAlarmCallback() {
90 assert(F);
91 F->AlarmCallback();
92}
93
Aaron Ballmanef116982015-01-29 16:58:29 +000094void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +000095 assert(Options.UnitTimeoutSec > 0);
Aaron Ballmanef116982015-01-29 16:58:29 +000096 size_t Seconds =
97 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Kostya Serebryany490bbd62015-05-19 22:12:57 +000098 if (Seconds == 0) return;
99 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000100 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000101 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000102 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000103 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
104 Options.UnitTimeoutSec);
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000105 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
Kostya Serebryany1165efd2015-07-31 22:07:17 +0000106 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000107 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000108 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000109 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000110 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
111 Seconds);
112 if (__sanitizer_print_stack_trace)
113 __sanitizer_print_stack_trace();
114 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000115 exit(1);
Aaron Ballmanef116982015-01-29 16:58:29 +0000116 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000117}
118
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000119void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000120 size_t Seconds = secondsSinceProcessStartUp();
121 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000122
123 if (Options.OutputCSV) {
124 static bool csvHeaderPrinted = false;
125 if (!csvHeaderPrinted) {
126 csvHeaderPrinted = true;
127 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
128 }
129 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
130 LastRecordedBlockCoverage, TotalBits(),
131 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
132 TotalNumberOfExecutedTraceBasedMutations, Where);
133 }
134
135 if (!Options.Verbosity)
136 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000137 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000138 if (LastRecordedBlockCoverage)
139 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000140 if (auto TB = TotalBits())
141 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000142 if (LastRecordedCallerCalleeCoverage)
143 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000144 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000145 if (TotalNumberOfExecutedTraceBasedMutations)
146 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
147 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000148}
149
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000150void Fuzzer::RereadOutputCorpus() {
151 if (Options.OutputCorpus.empty()) return;
152 std::vector<Unit> AdditionalCorpus;
153 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
154 &EpochOfLastReadOfOutputCorpus);
155 if (Corpus.empty()) {
156 Corpus = AdditionalCorpus;
157 return;
158 }
159 if (!Options.Reload) return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000160 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000161 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000162 for (auto &X : AdditionalCorpus) {
163 if (X.size() > (size_t)Options.MaxLen)
164 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000165 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000166 CurrentUnit.clear();
167 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000168 if (RunOne(CurrentUnit)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000169 Corpus.push_back(X);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000170 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000171 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000172 }
173 }
174}
175
Aaron Ballmanef116982015-01-29 16:58:29 +0000176void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000177 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
178 (Options.PreferSmallDuringInitialShuffle == -1 &&
179 USF.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000180 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000181 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000182 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000183 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000184 if (Options.ShuffleAtStartUp) {
185 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
186 if (PreferSmall)
187 std::stable_sort(
188 Corpus.begin(), Corpus.end(),
189 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
190 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000191 Unit &U = CurrentUnit;
192 for (const auto &C : Corpus) {
193 for (size_t First = 0; First < 1; First++) {
194 U.clear();
195 size_t Last = std::min(First + Options.MaxLen, C.size());
196 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000197 if (Options.OnlyASCII)
198 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000199 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000200 NewCorpus.push_back(U);
201 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000202 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000203 }
204 }
205 }
206 Corpus = NewCorpus;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000207 for (auto &X : Corpus)
208 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000209 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000210}
211
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000212bool Fuzzer::RunOne(const Unit &U) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000213 UnitStartTime = system_clock::now();
214 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000215
216 PrepareCoverageBeforeRun();
217 ExecuteCallback(U);
218 bool Res = CheckCoverageAfterRun();
219
Kostya Serebryany16901a92015-03-30 23:04:35 +0000220 auto UnitStopTime = system_clock::now();
221 auto TimeOfUnit =
222 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000223 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
224 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000225 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000226 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
227 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000228 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000229 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000230 WriteUnitToFileWithPrefix(U, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000231 }
232 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000233}
234
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000235void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000236 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
237 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000238 if (Options.OnlyASCII)
239 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000240 if (RunOne(U))
241 ReportNewCoverage(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000242}
243
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000244void Fuzzer::ExecuteCallback(const Unit &U) {
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000245 // We copy the contents of Unit into a separate heap buffer
246 // so that we reliably find buffer overflows in it.
247 std::unique_ptr<uint8_t[]> Data(new uint8_t[U.size()]);
248 memcpy(Data.get(), U.data(), U.size());
249 AssignTaintLabels(Data.get(), U.size());
250 int Res = USF.TargetFunction(Data.get(), U.size());
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000251 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000252 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000253}
254
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000255size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000256 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000257 uintptr_t PrevCoverage = LastRecordedBlockCoverage;
258 LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
259
260 if (PrevCoverage == LastRecordedBlockCoverage || !Options.PrintNewCovPcs)
261 return LastRecordedBlockCoverage;
262
263 uintptr_t PrevBufferLen = LastCoveragePcBufferLen;
264 uintptr_t *CoverageBuf;
265 LastCoveragePcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
266 assert(CoverageBuf);
267 for (size_t i = PrevBufferLen; i < LastCoveragePcBufferLen; ++i) {
268 Printf("0x%x\n", CoverageBuf[i]);
269 }
270
271 return LastRecordedBlockCoverage;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000272}
273
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000274size_t Fuzzer::RecordCallerCalleeCoverage() {
275 if (!Options.UseIndirCalls)
276 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000277 if (!__sanitizer_get_total_unique_caller_callee_pairs)
278 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000279 return LastRecordedCallerCalleeCoverage =
280 __sanitizer_get_total_unique_caller_callee_pairs();
281}
282
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000283void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000284 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000285 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000286 CounterBitmap.resize(NumCounters);
287 __sanitizer_update_counter_bitset_and_clear_counters(0);
288 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000289 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000290 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000291}
292
293bool Fuzzer::CheckCoverageAfterRun() {
294 size_t OldCoverage = LastRecordedBlockCoverage;
295 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000296 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
297 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000298 size_t NumNewBits = 0;
299 if (Options.UseCounters)
300 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
301 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000302 return NewCoverage > OldCoverage ||
303 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000304}
305
306void Fuzzer::WriteToOutputCorpus(const Unit &U) {
307 if (Options.OutputCorpus.empty()) return;
308 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
309 WriteToFile(U, Path);
310 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000311 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000312 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000313}
314
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000315void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000316 if (!Options.SaveArtifacts)
317 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000318 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000319 if (!Options.ExactArtifactPath.empty())
320 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000321 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000322 Printf("artifact_prefix='%s'; Test unit written to %s\n",
323 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000324 if (U.size() <= kMaxUnitSizeToPrint)
325 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000326}
327
328void Fuzzer::SaveCorpus() {
329 if (Options.OutputCorpus.empty()) return;
330 for (const auto &U : Corpus)
331 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
332 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000333 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
334 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000335}
336
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000337void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
338 if (!Options.PrintNEW)
339 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000340 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000341 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000342 Printf(" L: %zd ", U.size());
343 USF.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000344 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000345 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000346}
347
348void Fuzzer::ReportNewCoverage(const Unit &U) {
349 Corpus.push_back(U);
350 UnitHashesAddedToCorpus.insert(Hash(U));
351 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000352 WriteToOutputCorpus(U);
353 if (Options.ExitOnFirst)
354 exit(0);
Aaron Ballmanef116982015-01-29 16:58:29 +0000355}
356
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000357void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
358 if (Corpora.size() <= 1) {
359 Printf("Merge requires two or more corpus dirs\n");
360 return;
361 }
362 auto InitialCorpusDir = Corpora[0];
363 ReadDir(InitialCorpusDir, nullptr);
364 Printf("Merge: running the initial corpus '%s' of %d units\n",
365 InitialCorpusDir.c_str(), Corpus.size());
366 for (auto &U : Corpus)
367 RunOne(U);
368
369 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
370
371 size_t NumTried = 0;
372 size_t NumMerged = 0;
373 for (auto &C : ExtraCorpora) {
374 Corpus.clear();
375 ReadDir(C, nullptr);
376 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
377 Corpus.size());
378 for (auto &U : Corpus) {
379 NumTried++;
380 if (RunOne(U)) {
381 WriteToOutputCorpus(U);
382 NumMerged++;
383 }
384 }
385 }
386 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
387}
388
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000389void Fuzzer::MutateAndTestOne() {
390 auto &U = CurrentUnit;
391 USF.StartMutationSequence();
392
393 U = ChooseUnitToMutate();
394
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000395 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000396 size_t Size = U.size();
397 U.resize(Options.MaxLen);
398 size_t NewSize = USF.Mutate(U.data(), Size, U.size());
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000399 assert(NewSize > 0 && "Mutator returned empty unit");
400 assert(NewSize <= (size_t)Options.MaxLen &&
401 "Mutator return overisized unit");
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000402 U.resize(NewSize);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000403 if (i == 0)
404 StartTraceRecording();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000405 RunOneAndUpdateCorpus(U);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000406 StopTraceRecording();
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000407 }
408}
409
Kostya Serebryanye6926212015-11-04 23:22:25 +0000410// Returns an index of random unit from the corpus to mutate.
411// Hypothesis: units added to the corpus last are more likely to be interesting.
412// This function gives more wieght to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000413size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000414 size_t N = Corpus.size();
415 size_t Total = (N + 1) * N / 2;
416 size_t R = USF.GetRand()(Total);
417 size_t IdxBeg = 0, IdxEnd = N;
418 // Binary search.
419 while (IdxEnd - IdxBeg >= 2) {
420 size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
421 if (R > (Idx + 1) * Idx / 2)
422 IdxBeg = Idx;
423 else
424 IdxEnd = Idx;
425 }
426 assert(IdxBeg < N);
427 return IdxBeg;
428}
429
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000430// Experimental search heuristic: drilling.
431// - Read, shuffle, execute and minimize the corpus.
432// - Choose one random unit.
433// - Reset the coverage.
434// - Start fuzzing as if the chosen unit was the only element of the corpus.
435// - When done, reset the coverage again.
436// - Merge the newly created corpus into the original one.
437void Fuzzer::Drill() {
438 // The corpus is already read, shuffled, and minimized.
439 assert(!Corpus.empty());
440 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000441
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000442 Unit U = ChooseUnitToMutate();
443
444 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
445 __sanitizer_reset_coverage();
446
447 std::vector<Unit> SavedCorpus;
448 SavedCorpus.swap(Corpus);
449 Corpus.push_back(U);
450 assert(Corpus.size() == 1);
451 RunOne(U);
452 PrintStats("DRILL ");
453 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
454 SavedOutputCorpusPath.swap(Options.OutputCorpus);
455 Loop();
456
457 __sanitizer_reset_coverage();
458
459 PrintStats("REINIT");
460 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany72fdb322016-01-13 01:58:27 +0000461 for (auto &U : SavedCorpus) {
462 CurrentUnit = U;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000463 RunOne(U);
Kostya Serebryany72fdb322016-01-13 01:58:27 +0000464 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000465 PrintStats("MERGE ");
466 Options.PrintNEW = true;
467 size_t NumMerged = 0;
468 for (auto &U : Corpus) {
Kostya Serebryany72fdb322016-01-13 01:58:27 +0000469 CurrentUnit = U;
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000470 if (RunOne(U)) {
471 PrintStatusForNewUnit(U);
472 NumMerged++;
473 WriteToOutputCorpus(U);
474 }
475 }
476 PrintStats("MERGED");
477 if (NumMerged && Options.Verbosity)
478 Printf("Drilling discovered %zd new units\n", NumMerged);
479}
480
481void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000482 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000483 if (Options.DoCrossOver)
484 USF.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000485 while (true) {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000486 SyncCorpus();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000487 auto Now = system_clock::now();
488 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
489 RereadOutputCorpus();
490 LastCorpusReload = Now;
491 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000492 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000493 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000494 if (Options.MaxTotalTimeSec > 0 &&
495 secondsSinceProcessStartUp() >
496 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000497 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000498 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000499 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000500 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000501
502 PrintStats("DONE ", "\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000503}
504
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000505void Fuzzer::SyncCorpus() {
506 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
507 auto Now = system_clock::now();
508 if (duration_cast<seconds>(Now - LastExternalSync).count() <
509 Options.SyncTimeout)
510 return;
511 LastExternalSync = Now;
512 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
513}
514
Aaron Ballmanef116982015-01-29 16:58:29 +0000515} // namespace fuzzer