blob: a7e743ec6de7b660edde3522232f02db0bcbcd96 [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 Serebryany52a788e2015-03-31 20:13:20 +000071void Fuzzer::StaticDeathCallback() {
72 assert(F);
73 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000074}
75
76void Fuzzer::DeathCallback() {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000077 Printf("DEATH:\n");
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000078 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
79 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
80 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000081 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000082 WriteUnitToFileWithPrefix(
83 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, "crash-");
Aaron Ballmanef116982015-01-29 16:58:29 +000084}
85
Kostya Serebryany52a788e2015-03-31 20:13:20 +000086void Fuzzer::StaticAlarmCallback() {
87 assert(F);
88 F->AlarmCallback();
89}
90
Aaron Ballmanef116982015-01-29 16:58:29 +000091void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +000092 assert(Options.UnitTimeoutSec > 0);
Aaron Ballmanef116982015-01-29 16:58:29 +000093 size_t Seconds =
94 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Kostya Serebryany490bbd62015-05-19 22:12:57 +000095 if (Seconds == 0) return;
96 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000097 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +000098 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000099 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000100 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
101 Options.UnitTimeoutSec);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000102 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
103 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
104 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000105 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000106 WriteUnitToFileWithPrefix(
107 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, "timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000108 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
109 Seconds);
110 if (__sanitizer_print_stack_trace)
111 __sanitizer_print_stack_trace();
112 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000113 exit(1);
Aaron Ballmanef116982015-01-29 16:58:29 +0000114 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000115}
116
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000117void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000118 size_t Seconds = secondsSinceProcessStartUp();
119 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000120
121 if (Options.OutputCSV) {
122 static bool csvHeaderPrinted = false;
123 if (!csvHeaderPrinted) {
124 csvHeaderPrinted = true;
125 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
126 }
127 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
128 LastRecordedBlockCoverage, TotalBits(),
129 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
130 TotalNumberOfExecutedTraceBasedMutations, Where);
131 }
132
133 if (!Options.Verbosity)
134 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000135 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000136 if (LastRecordedBlockCoverage)
137 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000138 if (auto TB = TotalBits())
139 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000140 if (LastRecordedCallerCalleeCoverage)
141 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000142 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000143 if (TotalNumberOfExecutedTraceBasedMutations)
144 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
145 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000146}
147
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000148void Fuzzer::RereadOutputCorpus() {
149 if (Options.OutputCorpus.empty()) return;
150 std::vector<Unit> AdditionalCorpus;
151 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
152 &EpochOfLastReadOfOutputCorpus);
153 if (Corpus.empty()) {
154 Corpus = AdditionalCorpus;
155 return;
156 }
157 if (!Options.Reload) return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000158 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000159 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000160 for (auto &X : AdditionalCorpus) {
161 if (X.size() > (size_t)Options.MaxLen)
162 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000163 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000164 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000165 Corpus.push_back(X);
Ivan Krasinb008fd42016-01-22 01:32:34 +0000166 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000167 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000168 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000169 }
170 }
171}
172
Aaron Ballmanef116982015-01-29 16:58:29 +0000173void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000174 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
175 (Options.PreferSmallDuringInitialShuffle == -1 &&
176 USF.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000177 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000178 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000179 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000180 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000181 if (Options.ShuffleAtStartUp) {
182 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
183 if (PreferSmall)
184 std::stable_sort(
185 Corpus.begin(), Corpus.end(),
186 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
187 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000188 Unit U;
Aaron Ballmanef116982015-01-29 16:58:29 +0000189 for (const auto &C : Corpus) {
190 for (size_t First = 0; First < 1; First++) {
191 U.clear();
192 size_t Last = std::min(First + Options.MaxLen, C.size());
193 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000194 if (Options.OnlyASCII)
195 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000196 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000197 NewCorpus.push_back(U);
198 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000199 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000200 }
201 }
202 }
203 Corpus = NewCorpus;
Ivan Krasinb008fd42016-01-22 01:32:34 +0000204 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000205 for (auto &X : Corpus)
206 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000207 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000208}
209
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000210bool Fuzzer::RunOne(const Unit &U) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000211 UnitStartTime = system_clock::now();
212 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000213
214 PrepareCoverageBeforeRun();
215 ExecuteCallback(U);
216 bool Res = CheckCoverageAfterRun();
217
Kostya Serebryany16901a92015-03-30 23:04:35 +0000218 auto UnitStopTime = system_clock::now();
219 auto TimeOfUnit =
220 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000221 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
222 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000223 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000224 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
225 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000226 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000227 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000228 WriteUnitToFileWithPrefix(U, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000229 }
230 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000231}
232
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000233void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000234 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
235 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000236 if (Options.OnlyASCII)
237 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000238 if (RunOne(U))
239 ReportNewCoverage(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000240}
241
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000242void Fuzzer::ExecuteCallback(const Unit &U) {
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000243 // We copy the contents of Unit into a separate heap buffer
244 // so that we reliably find buffer overflows in it.
245 std::unique_ptr<uint8_t[]> Data(new uint8_t[U.size()]);
246 memcpy(Data.get(), U.data(), U.size());
247 AssignTaintLabels(Data.get(), U.size());
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000248 CurrentUnitData = Data.get();
249 CurrentUnitSize = U.size();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000250 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 Serebryany98abb2c2016-01-13 23:46:01 +0000253 CurrentUnitData = nullptr;
254 CurrentUnitSize = 0;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000255}
256
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000257size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000258 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000259 uintptr_t PrevCoverage = LastRecordedBlockCoverage;
260 LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
261
262 if (PrevCoverage == LastRecordedBlockCoverage || !Options.PrintNewCovPcs)
263 return LastRecordedBlockCoverage;
264
265 uintptr_t PrevBufferLen = LastCoveragePcBufferLen;
266 uintptr_t *CoverageBuf;
267 LastCoveragePcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
268 assert(CoverageBuf);
269 for (size_t i = PrevBufferLen; i < LastCoveragePcBufferLen; ++i) {
Mike Aizatskye313f8f2016-01-21 00:02:09 +0000270 Printf("%p\n", CoverageBuf[i]);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000271 }
272
273 return LastRecordedBlockCoverage;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000274}
275
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000276size_t Fuzzer::RecordCallerCalleeCoverage() {
277 if (!Options.UseIndirCalls)
278 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000279 if (!__sanitizer_get_total_unique_caller_callee_pairs)
280 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000281 return LastRecordedCallerCalleeCoverage =
282 __sanitizer_get_total_unique_caller_callee_pairs();
283}
284
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000285void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000286 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000287 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000288 CounterBitmap.resize(NumCounters);
289 __sanitizer_update_counter_bitset_and_clear_counters(0);
290 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000291 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000292 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000293}
294
295bool Fuzzer::CheckCoverageAfterRun() {
296 size_t OldCoverage = LastRecordedBlockCoverage;
297 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000298 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
299 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000300 size_t NumNewBits = 0;
301 if (Options.UseCounters)
302 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
303 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000304 return NewCoverage > OldCoverage ||
305 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000306}
307
308void Fuzzer::WriteToOutputCorpus(const Unit &U) {
309 if (Options.OutputCorpus.empty()) return;
310 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
311 WriteToFile(U, Path);
312 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000313 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000314 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000315}
316
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000317void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000318 if (!Options.SaveArtifacts)
319 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000320 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000321 if (!Options.ExactArtifactPath.empty())
322 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000323 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000324 Printf("artifact_prefix='%s'; Test unit written to %s\n",
325 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000326 if (U.size() <= kMaxUnitSizeToPrint)
327 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000328}
329
330void Fuzzer::SaveCorpus() {
331 if (Options.OutputCorpus.empty()) return;
332 for (const auto &U : Corpus)
333 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
334 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000335 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
336 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000337}
338
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000339void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
340 if (!Options.PrintNEW)
341 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000342 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000343 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000344 Printf(" L: %zd ", U.size());
Kostya Serebryany4b358742016-01-14 02:36:44 +0000345 USF.GetMD().PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000346 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000347 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000348}
349
350void Fuzzer::ReportNewCoverage(const Unit &U) {
351 Corpus.push_back(U);
Ivan Krasinb008fd42016-01-22 01:32:34 +0000352 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000353 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany4b358742016-01-14 02:36:44 +0000354 USF.GetMD().RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000355 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000356 WriteToOutputCorpus(U);
357 if (Options.ExitOnFirst)
358 exit(0);
Aaron Ballmanef116982015-01-29 16:58:29 +0000359}
360
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000361void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
362 if (Corpora.size() <= 1) {
363 Printf("Merge requires two or more corpus dirs\n");
364 return;
365 }
366 auto InitialCorpusDir = Corpora[0];
367 ReadDir(InitialCorpusDir, nullptr);
368 Printf("Merge: running the initial corpus '%s' of %d units\n",
369 InitialCorpusDir.c_str(), Corpus.size());
370 for (auto &U : Corpus)
371 RunOne(U);
372
373 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
374
375 size_t NumTried = 0;
376 size_t NumMerged = 0;
377 for (auto &C : ExtraCorpora) {
378 Corpus.clear();
379 ReadDir(C, nullptr);
380 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
381 Corpus.size());
382 for (auto &U : Corpus) {
383 NumTried++;
384 if (RunOne(U)) {
385 WriteToOutputCorpus(U);
386 NumMerged++;
387 }
388 }
389 }
390 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
391}
392
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000393void Fuzzer::MutateAndTestOne() {
Kostya Serebryany4b358742016-01-14 02:36:44 +0000394 USF.GetMD().StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000395
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000396 auto U = ChooseUnitToMutate();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000397
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000398 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000399 size_t Size = U.size();
400 U.resize(Options.MaxLen);
401 size_t NewSize = USF.Mutate(U.data(), Size, U.size());
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000402 assert(NewSize > 0 && "Mutator returned empty unit");
403 assert(NewSize <= (size_t)Options.MaxLen &&
404 "Mutator return overisized unit");
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000405 U.resize(NewSize);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000406 if (i == 0)
407 StartTraceRecording();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000408 RunOneAndUpdateCorpus(U);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000409 StopTraceRecording();
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000410 }
411}
412
Kostya Serebryanye6926212015-11-04 23:22:25 +0000413// Returns an index of random unit from the corpus to mutate.
414// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasinb008fd42016-01-22 01:32:34 +0000415// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000416size_t Fuzzer::ChooseUnitIdxToMutate() {
Ivan Krasinb008fd42016-01-22 01:32:34 +0000417 size_t Idx = static_cast<size_t>(CorpusDistribution(USF.GetRand()));
418 assert(Idx < Corpus.size());
419 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000420}
421
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000422// Experimental search heuristic: drilling.
423// - Read, shuffle, execute and minimize the corpus.
424// - Choose one random unit.
425// - Reset the coverage.
426// - Start fuzzing as if the chosen unit was the only element of the corpus.
427// - When done, reset the coverage again.
428// - Merge the newly created corpus into the original one.
429void Fuzzer::Drill() {
430 // The corpus is already read, shuffled, and minimized.
431 assert(!Corpus.empty());
432 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000433
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000434 Unit U = ChooseUnitToMutate();
435
436 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
437 __sanitizer_reset_coverage();
438
439 std::vector<Unit> SavedCorpus;
440 SavedCorpus.swap(Corpus);
441 Corpus.push_back(U);
Ivan Krasinb008fd42016-01-22 01:32:34 +0000442 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000443 assert(Corpus.size() == 1);
444 RunOne(U);
445 PrintStats("DRILL ");
446 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
447 SavedOutputCorpusPath.swap(Options.OutputCorpus);
448 Loop();
449
450 __sanitizer_reset_coverage();
451
452 PrintStats("REINIT");
453 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000454 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000455 RunOne(U);
456 PrintStats("MERGE ");
457 Options.PrintNEW = true;
458 size_t NumMerged = 0;
459 for (auto &U : Corpus) {
460 if (RunOne(U)) {
461 PrintStatusForNewUnit(U);
462 NumMerged++;
463 WriteToOutputCorpus(U);
464 }
465 }
466 PrintStats("MERGED");
467 if (NumMerged && Options.Verbosity)
468 Printf("Drilling discovered %zd new units\n", NumMerged);
469}
470
471void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000472 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000473 if (Options.DoCrossOver)
Kostya Serebryany628bc3e2016-01-16 00:04:36 +0000474 USF.GetMD().SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000475 while (true) {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000476 SyncCorpus();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000477 auto Now = system_clock::now();
478 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
479 RereadOutputCorpus();
480 LastCorpusReload = Now;
481 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000482 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000483 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000484 if (Options.MaxTotalTimeSec > 0 &&
485 secondsSinceProcessStartUp() >
486 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000487 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000488 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000489 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000490 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000491
492 PrintStats("DONE ", "\n");
Kostya Serebryany4b358742016-01-14 02:36:44 +0000493 USF.GetMD().PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000494}
495
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000496void Fuzzer::SyncCorpus() {
497 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
498 auto Now = system_clock::now();
499 if (duration_cast<seconds>(Now - LastExternalSync).count() <
500 Options.SyncTimeout)
501 return;
502 LastExternalSync = Now;
503 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
504}
505
Ivan Krasinb008fd42016-01-22 01:32:34 +0000506void Fuzzer::UpdateCorpusDistribution() {
507 size_t N = Corpus.size();
508 std::vector<double> Intervals(N+1);
509 std::vector<double> Weights(N);
510 std::iota(Intervals.begin(), Intervals.end(), 0);
511 std::iota(Weights.begin(), Weights.end(), 1);
512 CorpusDistribution = std::piecewise_constant_distribution<double>(
513 Intervals.begin(), Intervals.end(), Weights.begin());
514}
515
Aaron Ballmanef116982015-01-29 16:58:29 +0000516} // namespace fuzzer