blob: a84c2348b535dd0e412ba858590a6a9c499061c9 [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)
Ivan Krasindf919102016-01-22 22:28:27 +000018#if __has_include(<sanitizer / coverage_interface.h>)
19#include <sanitizer/coverage_interface.h>
20#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000021#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();
Ivan Krasindf919102016-01-22 22:28:27 +000031__attribute__((weak)) void
32__sanitizer_set_death_callback(void (*callback)(void));
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000033__attribute__((weak)) size_t __sanitizer_get_number_of_counters();
Ivan Krasindf919102016-01-22 22:28:27 +000034__attribute__((weak)) uintptr_t
35__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"
Ivan Krasindf919102016-01-22 22:28:27 +000045 "Did you use -fsanitize-coverage=... to build your code?\n",
46 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000047 exit(1);
48}
49
50#define CHECK_WEAK_API_FUNCTION(fn) \
51 do { \
52 if (!fn) \
53 MissingWeakApiFunction(#fn); \
54 } while (false)
55
Kostya Serebryany52a788e2015-03-31 20:13:20 +000056// Only one Fuzzer per process.
57static Fuzzer *F;
58
Kostya Serebryanyf3424592015-05-22 22:35:31 +000059Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
Ivan Krasindf919102016-01-22 22:28:27 +000060 : Generator(USF.GetRand().Rand()), USF(USF), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000061 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000062 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000063 assert(!F);
64 F = this;
65}
Aaron Ballmanef116982015-01-29 16:58:29 +000066
67void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000068 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000069 __sanitizer_set_death_callback(StaticDeathCallback);
70}
71
Kostya Serebryany52a788e2015-03-31 20:13:20 +000072void Fuzzer::StaticDeathCallback() {
73 assert(F);
74 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000075}
76
77void Fuzzer::DeathCallback() {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000078 Printf("DEATH:\n");
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000079 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
80 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
81 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000082 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000083 WriteUnitToFileWithPrefix(
84 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, "crash-");
Aaron Ballmanef116982015-01-29 16:58:29 +000085}
86
Kostya Serebryany52a788e2015-03-31 20:13:20 +000087void Fuzzer::StaticAlarmCallback() {
88 assert(F);
89 F->AlarmCallback();
90}
91
Aaron Ballmanef116982015-01-29 16:58:29 +000092void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +000093 assert(Options.UnitTimeoutSec > 0);
Aaron Ballmanef116982015-01-29 16:58:29 +000094 size_t Seconds =
95 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +000096 if (Seconds == 0)
97 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +000098 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000099 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000100 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000101 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000102 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
103 Options.UnitTimeoutSec);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000104 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
105 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
106 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000107 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000108 WriteUnitToFileWithPrefix(
109 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, "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() {
Ivan Krasindf919102016-01-22 22:28:27 +0000151 if (Options.OutputCorpus.empty())
152 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000153 std::vector<Unit> AdditionalCorpus;
154 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
155 &EpochOfLastReadOfOutputCorpus);
156 if (Corpus.empty()) {
157 Corpus = AdditionalCorpus;
158 return;
159 }
Ivan Krasindf919102016-01-22 22:28:27 +0000160 if (!Options.Reload)
161 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000162 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000163 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000164 for (auto &X : AdditionalCorpus) {
165 if (X.size() > (size_t)Options.MaxLen)
166 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000167 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000168 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000169 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000170 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000171 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000172 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000173 }
174 }
175}
176
Aaron Ballmanef116982015-01-29 16:58:29 +0000177void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000178 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
179 (Options.PreferSmallDuringInitialShuffle == -1 &&
180 USF.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000181 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000182 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000183 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000184 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000185 if (Options.ShuffleAtStartUp) {
186 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
187 if (PreferSmall)
188 std::stable_sort(
189 Corpus.begin(), Corpus.end(),
190 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
191 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000192 Unit U;
Aaron Ballmanef116982015-01-29 16:58:29 +0000193 for (const auto &C : Corpus) {
194 for (size_t First = 0; First < 1; First++) {
195 U.clear();
196 size_t Last = std::min(First + Options.MaxLen, C.size());
197 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000198 if (Options.OnlyASCII)
199 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000200 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000201 NewCorpus.push_back(U);
202 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000203 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000204 }
205 }
206 }
207 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000208 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000209 for (auto &X : Corpus)
210 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000211 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000212}
213
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000214bool Fuzzer::RunOne(const Unit &U) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000215 UnitStartTime = system_clock::now();
216 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000217
218 PrepareCoverageBeforeRun();
219 ExecuteCallback(U);
220 bool Res = CheckCoverageAfterRun();
221
Kostya Serebryany16901a92015-03-30 23:04:35 +0000222 auto UnitStopTime = system_clock::now();
223 auto TimeOfUnit =
224 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000225 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
226 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000227 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000228 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
229 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000230 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000231 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000232 WriteUnitToFileWithPrefix(U, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000233 }
234 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000235}
236
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000237void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000238 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
239 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000240 if (Options.OnlyASCII)
241 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000242 if (RunOne(U))
243 ReportNewCoverage(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000244}
245
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000246void Fuzzer::ExecuteCallback(const Unit &U) {
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000247 // We copy the contents of Unit into a separate heap buffer
248 // so that we reliably find buffer overflows in it.
249 std::unique_ptr<uint8_t[]> Data(new uint8_t[U.size()]);
250 memcpy(Data.get(), U.data(), U.size());
251 AssignTaintLabels(Data.get(), U.size());
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000252 CurrentUnitData = Data.get();
253 CurrentUnitSize = U.size();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000254 int Res = USF.TargetFunction(Data.get(), U.size());
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000255 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000256 assert(Res == 0);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000257 CurrentUnitData = nullptr;
258 CurrentUnitSize = 0;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000259}
260
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000261size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000262 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000263 uintptr_t PrevCoverage = LastRecordedBlockCoverage;
264 LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
265
266 if (PrevCoverage == LastRecordedBlockCoverage || !Options.PrintNewCovPcs)
267 return LastRecordedBlockCoverage;
268
269 uintptr_t PrevBufferLen = LastCoveragePcBufferLen;
270 uintptr_t *CoverageBuf;
271 LastCoveragePcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
272 assert(CoverageBuf);
273 for (size_t i = PrevBufferLen; i < LastCoveragePcBufferLen; ++i) {
Mike Aizatskye313f8f2016-01-21 00:02:09 +0000274 Printf("%p\n", CoverageBuf[i]);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000275 }
276
277 return LastRecordedBlockCoverage;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000278}
279
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000280size_t Fuzzer::RecordCallerCalleeCoverage() {
281 if (!Options.UseIndirCalls)
282 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000283 if (!__sanitizer_get_total_unique_caller_callee_pairs)
284 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000285 return LastRecordedCallerCalleeCoverage =
286 __sanitizer_get_total_unique_caller_callee_pairs();
287}
288
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000289void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000290 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000291 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000292 CounterBitmap.resize(NumCounters);
293 __sanitizer_update_counter_bitset_and_clear_counters(0);
294 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000295 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000296 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000297}
298
299bool Fuzzer::CheckCoverageAfterRun() {
300 size_t OldCoverage = LastRecordedBlockCoverage;
301 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000302 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
303 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000304 size_t NumNewBits = 0;
305 if (Options.UseCounters)
306 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
307 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000308 return NewCoverage > OldCoverage ||
309 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000310}
311
312void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Ivan Krasindf919102016-01-22 22:28:27 +0000313 if (Options.OutputCorpus.empty())
314 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000315 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
316 WriteToFile(U, Path);
317 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000318 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000319 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000320}
321
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000322void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000323 if (!Options.SaveArtifacts)
324 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000325 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000326 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000327 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000328 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000329 Printf("artifact_prefix='%s'; Test unit written to %s\n",
330 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000331 if (U.size() <= kMaxUnitSizeToPrint)
332 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000333}
334
335void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000336 if (Options.OutputCorpus.empty())
337 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000338 for (const auto &U : Corpus)
339 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
340 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000341 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
342 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000343}
344
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000345void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
346 if (!Options.PrintNEW)
347 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000348 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000349 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000350 Printf(" L: %zd ", U.size());
Kostya Serebryany4b358742016-01-14 02:36:44 +0000351 USF.GetMD().PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000352 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000353 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000354}
355
356void Fuzzer::ReportNewCoverage(const Unit &U) {
357 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000358 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000359 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany4b358742016-01-14 02:36:44 +0000360 USF.GetMD().RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000361 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000362 WriteToOutputCorpus(U);
363 if (Options.ExitOnFirst)
364 exit(0);
Aaron Ballmanef116982015-01-29 16:58:29 +0000365}
366
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000367void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
368 if (Corpora.size() <= 1) {
369 Printf("Merge requires two or more corpus dirs\n");
370 return;
371 }
372 auto InitialCorpusDir = Corpora[0];
373 ReadDir(InitialCorpusDir, nullptr);
374 Printf("Merge: running the initial corpus '%s' of %d units\n",
375 InitialCorpusDir.c_str(), Corpus.size());
376 for (auto &U : Corpus)
377 RunOne(U);
378
379 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
380
381 size_t NumTried = 0;
382 size_t NumMerged = 0;
383 for (auto &C : ExtraCorpora) {
384 Corpus.clear();
385 ReadDir(C, nullptr);
386 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
387 Corpus.size());
388 for (auto &U : Corpus) {
389 NumTried++;
390 if (RunOne(U)) {
391 WriteToOutputCorpus(U);
392 NumMerged++;
393 }
394 }
395 }
396 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
397}
398
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000399void Fuzzer::MutateAndTestOne() {
Kostya Serebryany4b358742016-01-14 02:36:44 +0000400 USF.GetMD().StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000401
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000402 auto U = ChooseUnitToMutate();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000403
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000404 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000405 size_t Size = U.size();
406 U.resize(Options.MaxLen);
407 size_t NewSize = USF.Mutate(U.data(), Size, U.size());
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000408 assert(NewSize > 0 && "Mutator returned empty unit");
409 assert(NewSize <= (size_t)Options.MaxLen &&
410 "Mutator return overisized unit");
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000411 U.resize(NewSize);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000412 if (i == 0)
413 StartTraceRecording();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000414 RunOneAndUpdateCorpus(U);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000415 StopTraceRecording();
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000416 }
417}
418
Kostya Serebryanye6926212015-11-04 23:22:25 +0000419// Returns an index of random unit from the corpus to mutate.
420// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000421// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000422size_t Fuzzer::ChooseUnitIdxToMutate() {
Ivan Krasindf919102016-01-22 22:28:27 +0000423 size_t Idx = static_cast<size_t>(CorpusDistribution(Generator));
424 assert(Idx < Corpus.size());
425 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000426}
427
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000428// Experimental search heuristic: drilling.
429// - Read, shuffle, execute and minimize the corpus.
430// - Choose one random unit.
431// - Reset the coverage.
432// - Start fuzzing as if the chosen unit was the only element of the corpus.
433// - When done, reset the coverage again.
434// - Merge the newly created corpus into the original one.
435void Fuzzer::Drill() {
436 // The corpus is already read, shuffled, and minimized.
437 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000438 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000439
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000440 Unit U = ChooseUnitToMutate();
441
442 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
443 __sanitizer_reset_coverage();
444
445 std::vector<Unit> SavedCorpus;
446 SavedCorpus.swap(Corpus);
447 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000448 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000449 assert(Corpus.size() == 1);
450 RunOne(U);
451 PrintStats("DRILL ");
452 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
453 SavedOutputCorpusPath.swap(Options.OutputCorpus);
454 Loop();
455
456 __sanitizer_reset_coverage();
457
458 PrintStats("REINIT");
459 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000460 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000461 RunOne(U);
462 PrintStats("MERGE ");
463 Options.PrintNEW = true;
464 size_t NumMerged = 0;
465 for (auto &U : Corpus) {
466 if (RunOne(U)) {
467 PrintStatusForNewUnit(U);
468 NumMerged++;
469 WriteToOutputCorpus(U);
470 }
471 }
472 PrintStats("MERGED");
473 if (NumMerged && Options.Verbosity)
474 Printf("Drilling discovered %zd new units\n", NumMerged);
475}
476
477void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000478 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000479 if (Options.DoCrossOver)
Kostya Serebryany628bc3e2016-01-16 00:04:36 +0000480 USF.GetMD().SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000481 while (true) {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000482 SyncCorpus();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000483 auto Now = system_clock::now();
484 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
485 RereadOutputCorpus();
486 LastCorpusReload = Now;
487 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000488 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000489 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000490 if (Options.MaxTotalTimeSec > 0 &&
491 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000492 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000493 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000494 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000495 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000496 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000497
498 PrintStats("DONE ", "\n");
Kostya Serebryany4b358742016-01-14 02:36:44 +0000499 USF.GetMD().PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000500}
501
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000502void Fuzzer::SyncCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000503 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty())
504 return;
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000505 auto Now = system_clock::now();
506 if (duration_cast<seconds>(Now - LastExternalSync).count() <
507 Options.SyncTimeout)
508 return;
509 LastExternalSync = Now;
510 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
511}
512
Ivan Krasindf919102016-01-22 22:28:27 +0000513void Fuzzer::UpdateCorpusDistribution() {
514 size_t N = Corpus.size();
515 std::vector<double> Intervals(N + 1);
516 std::vector<double> Weights(N);
517 std::iota(Intervals.begin(), Intervals.end(), 0);
518 std::iota(Weights.begin(), Weights.end(), 1);
519 CorpusDistribution = std::piecewise_constant_distribution<double>(
520 Intervals.begin(), Intervals.end(), Weights.begin());
521}
522
523} // namespace fuzzer