blob: 7d9f397e45e678ad738a7e14b241f1c791330824 [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);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000166 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000167 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000168 }
169 }
170}
171
Aaron Ballmanef116982015-01-29 16:58:29 +0000172void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000173 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
174 (Options.PreferSmallDuringInitialShuffle == -1 &&
175 USF.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000176 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000177 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000178 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000179 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000180 if (Options.ShuffleAtStartUp) {
181 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
182 if (PreferSmall)
183 std::stable_sort(
184 Corpus.begin(), Corpus.end(),
185 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
186 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000187 Unit U;
Aaron Ballmanef116982015-01-29 16:58:29 +0000188 for (const auto &C : Corpus) {
189 for (size_t First = 0; First < 1; First++) {
190 U.clear();
191 size_t Last = std::min(First + Options.MaxLen, C.size());
192 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000193 if (Options.OnlyASCII)
194 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000195 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000196 NewCorpus.push_back(U);
197 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000198 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000199 }
200 }
201 }
202 Corpus = NewCorpus;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000203 for (auto &X : Corpus)
204 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000205 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000206}
207
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000208bool Fuzzer::RunOne(const Unit &U) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000209 UnitStartTime = system_clock::now();
210 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000211
212 PrepareCoverageBeforeRun();
213 ExecuteCallback(U);
214 bool Res = CheckCoverageAfterRun();
215
Kostya Serebryany16901a92015-03-30 23:04:35 +0000216 auto UnitStopTime = system_clock::now();
217 auto TimeOfUnit =
218 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000219 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
220 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000221 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000222 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
223 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000224 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000225 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000226 WriteUnitToFileWithPrefix(U, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000227 }
228 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000229}
230
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000231void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000232 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
233 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000234 if (Options.OnlyASCII)
235 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000236 if (RunOne(U))
237 ReportNewCoverage(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000238}
239
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000240void Fuzzer::ExecuteCallback(const Unit &U) {
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000241 // We copy the contents of Unit into a separate heap buffer
242 // so that we reliably find buffer overflows in it.
243 std::unique_ptr<uint8_t[]> Data(new uint8_t[U.size()]);
244 memcpy(Data.get(), U.data(), U.size());
245 AssignTaintLabels(Data.get(), U.size());
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000246 CurrentUnitData = Data.get();
247 CurrentUnitSize = U.size();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000248 int Res = USF.TargetFunction(Data.get(), U.size());
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000249 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000250 assert(Res == 0);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000251 CurrentUnitData = nullptr;
252 CurrentUnitSize = 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() {
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000390 USF.StartMutationSequence();
391
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000392 auto U = ChooseUnitToMutate();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000393
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000394 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000395 size_t Size = U.size();
396 U.resize(Options.MaxLen);
397 size_t NewSize = USF.Mutate(U.data(), Size, U.size());
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000398 assert(NewSize > 0 && "Mutator returned empty unit");
399 assert(NewSize <= (size_t)Options.MaxLen &&
400 "Mutator return overisized unit");
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000401 U.resize(NewSize);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000402 if (i == 0)
403 StartTraceRecording();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000404 RunOneAndUpdateCorpus(U);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000405 StopTraceRecording();
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000406 }
407}
408
Kostya Serebryanye6926212015-11-04 23:22:25 +0000409// Returns an index of random unit from the corpus to mutate.
410// Hypothesis: units added to the corpus last are more likely to be interesting.
411// This function gives more wieght to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000412size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000413 size_t N = Corpus.size();
414 size_t Total = (N + 1) * N / 2;
415 size_t R = USF.GetRand()(Total);
416 size_t IdxBeg = 0, IdxEnd = N;
417 // Binary search.
418 while (IdxEnd - IdxBeg >= 2) {
419 size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
420 if (R > (Idx + 1) * Idx / 2)
421 IdxBeg = Idx;
422 else
423 IdxEnd = Idx;
424 }
425 assert(IdxBeg < N);
426 return IdxBeg;
427}
428
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000429// Experimental search heuristic: drilling.
430// - Read, shuffle, execute and minimize the corpus.
431// - Choose one random unit.
432// - Reset the coverage.
433// - Start fuzzing as if the chosen unit was the only element of the corpus.
434// - When done, reset the coverage again.
435// - Merge the newly created corpus into the original one.
436void Fuzzer::Drill() {
437 // The corpus is already read, shuffled, and minimized.
438 assert(!Corpus.empty());
439 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000440
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000441 Unit U = ChooseUnitToMutate();
442
443 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
444 __sanitizer_reset_coverage();
445
446 std::vector<Unit> SavedCorpus;
447 SavedCorpus.swap(Corpus);
448 Corpus.push_back(U);
449 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)
480 USF.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() >
492 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");
Aaron Ballmanef116982015-01-29 16:58:29 +0000499}
500
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000501void Fuzzer::SyncCorpus() {
502 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
503 auto Now = system_clock::now();
504 if (duration_cast<seconds>(Now - LastExternalSync).count() <
505 Options.SyncTimeout)
506 return;
507 LastExternalSync = Now;
508 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
509}
510
Aaron Ballmanef116982015-01-29 16:58:29 +0000511} // namespace fuzzer