blob: 82f1828064f79a2cbec6af867e315a2aa0bc9d61 [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 Serebryany22cc5e22016-02-13 02:29:38 +000038
39__attribute__((weak)) size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
40 size_t MaxSize,
41 unsigned int Seed);
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000042}
43
Aaron Ballmanef116982015-01-29 16:58:29 +000044namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000045static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000046
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000047static void MissingWeakApiFunction(const char *FnName) {
48 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000049 "Did you use -fsanitize-coverage=... to build your code?\n",
50 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000051 exit(1);
52}
53
54#define CHECK_WEAK_API_FUNCTION(fn) \
55 do { \
56 if (!fn) \
57 MissingWeakApiFunction(#fn); \
58 } while (false)
59
Kostya Serebryany52a788e2015-03-31 20:13:20 +000060// Only one Fuzzer per process.
61static Fuzzer *F;
62
Kostya Serebryany1deb0492016-02-13 06:24:18 +000063size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
64 assert(F);
65 return F->GetMD().Mutate(Data, Size, MaxSize);
66}
67
Kostya Serebryany7ec0c562016-02-13 03:25:16 +000068Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
69 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000070 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000071 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000072 assert(!F);
73 F = this;
74}
Aaron Ballmanef116982015-01-29 16:58:29 +000075
76void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000077 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000078 __sanitizer_set_death_callback(StaticDeathCallback);
79}
80
Kostya Serebryany52a788e2015-03-31 20:13:20 +000081void Fuzzer::StaticDeathCallback() {
82 assert(F);
83 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000084}
85
86void Fuzzer::DeathCallback() {
Kostya Serebryanyb92602a2016-02-04 00:02:17 +000087 if (!CurrentUnitSize) return;
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000088 Printf("DEATH:\n");
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000089 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
90 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
91 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000092 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000093 WriteUnitToFileWithPrefix(
94 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, "crash-");
Aaron Ballmanef116982015-01-29 16:58:29 +000095}
96
Kostya Serebryany52a788e2015-03-31 20:13:20 +000097void Fuzzer::StaticAlarmCallback() {
98 assert(F);
99 F->AlarmCallback();
100}
101
Aaron Ballmanef116982015-01-29 16:58:29 +0000102void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000103 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000104 if (!CurrentUnitSize)
105 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000106 size_t Seconds =
107 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000108 if (Seconds == 0)
109 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000110 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000111 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000112 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000113 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000114 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
115 Options.UnitTimeoutSec);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000116 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
117 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
118 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000119 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000120 WriteUnitToFileWithPrefix(
121 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, "timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000122 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
123 Seconds);
124 if (__sanitizer_print_stack_trace)
125 __sanitizer_print_stack_trace();
126 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany9768e7f2016-01-23 19:34:19 +0000127 if (Options.AbortOnTimeout)
128 abort();
Kostya Serebryany54a63632016-01-29 23:30:07 +0000129 exit(Options.TimeoutExitCode);
Aaron Ballmanef116982015-01-29 16:58:29 +0000130 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000131}
132
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000133void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000134 size_t Seconds = secondsSinceProcessStartUp();
135 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000136
137 if (Options.OutputCSV) {
138 static bool csvHeaderPrinted = false;
139 if (!csvHeaderPrinted) {
140 csvHeaderPrinted = true;
141 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
142 }
143 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
144 LastRecordedBlockCoverage, TotalBits(),
145 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
146 TotalNumberOfExecutedTraceBasedMutations, Where);
147 }
148
149 if (!Options.Verbosity)
150 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000151 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000152 if (LastRecordedBlockCoverage)
153 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryanyda63c1d2016-02-26 21:33:56 +0000154 if (LastRecordedPcMapSize)
155 Printf(" path: %zd", LastRecordedPcMapSize);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000156 if (auto TB = TotalBits())
157 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000158 if (LastRecordedCallerCalleeCoverage)
159 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000160 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000161 if (TotalNumberOfExecutedTraceBasedMutations)
162 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
163 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000164}
165
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000166void Fuzzer::RereadOutputCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000167 if (Options.OutputCorpus.empty())
168 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000169 std::vector<Unit> AdditionalCorpus;
170 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryanya35f7d32016-02-18 21:49:10 +0000171 &EpochOfLastReadOfOutputCorpus, Options.MaxLen);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000172 if (Corpus.empty()) {
173 Corpus = AdditionalCorpus;
174 return;
175 }
Ivan Krasindf919102016-01-22 22:28:27 +0000176 if (!Options.Reload)
177 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000178 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000179 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000180 for (auto &X : AdditionalCorpus) {
181 if (X.size() > (size_t)Options.MaxLen)
182 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000183 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000184 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000185 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000186 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000187 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000188 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000189 }
190 }
191}
192
Aaron Ballmanef116982015-01-29 16:58:29 +0000193void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000194 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
195 (Options.PreferSmallDuringInitialShuffle == -1 &&
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000196 MD.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000197 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000198 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000199 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000200 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000201 if (Options.ShuffleAtStartUp) {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000202 std::random_shuffle(Corpus.begin(), Corpus.end(), MD.GetRand());
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000203 if (PreferSmall)
204 std::stable_sort(
205 Corpus.begin(), Corpus.end(),
206 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
207 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000208 Unit U;
Aaron Ballmanef116982015-01-29 16:58:29 +0000209 for (const auto &C : Corpus) {
210 for (size_t First = 0; First < 1; First++) {
211 U.clear();
212 size_t Last = std::min(First + Options.MaxLen, C.size());
213 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000214 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000215 ToASCII(U.data(), U.size());
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000216 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000217 NewCorpus.push_back(U);
218 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000219 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000220 }
221 }
222 }
223 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000224 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000225 for (auto &X : Corpus)
226 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000227 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000228}
229
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000230bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000231 UnitStartTime = system_clock::now();
232 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000233
234 PrepareCoverageBeforeRun();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000235 ExecuteCallback(Data, Size);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000236 bool Res = CheckCoverageAfterRun();
237
Kostya Serebryany16901a92015-03-30 23:04:35 +0000238 auto UnitStopTime = system_clock::now();
239 auto TimeOfUnit =
240 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000241 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
242 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000243 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000244 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
245 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000246 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000247 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000248 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000249 }
250 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000251}
252
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000253void Fuzzer::RunOneAndUpdateCorpus(uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000254 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
255 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000256 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000257 ToASCII(Data, Size);
258 if (RunOne(Data, Size))
259 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000260}
261
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000262void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000263 // We copy the contents of Unit into a separate heap buffer
264 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000265 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
266 memcpy(DataCopy.get(), Data, Size);
267 AssignTaintLabels(DataCopy.get(), Size);
268 CurrentUnitData = DataCopy.get();
269 CurrentUnitSize = Size;
270 int Res = CB(DataCopy.get(), Size);
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000271 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000272 assert(Res == 0);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000273 CurrentUnitData = nullptr;
274 CurrentUnitSize = 0;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000275}
276
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000277size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000278 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000279 uintptr_t PrevCoverage = LastRecordedBlockCoverage;
280 LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
281
282 if (PrevCoverage == LastRecordedBlockCoverage || !Options.PrintNewCovPcs)
283 return LastRecordedBlockCoverage;
284
285 uintptr_t PrevBufferLen = LastCoveragePcBufferLen;
286 uintptr_t *CoverageBuf;
287 LastCoveragePcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
288 assert(CoverageBuf);
289 for (size_t i = PrevBufferLen; i < LastCoveragePcBufferLen; ++i) {
Mike Aizatskye313f8f2016-01-21 00:02:09 +0000290 Printf("%p\n", CoverageBuf[i]);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000291 }
292
293 return LastRecordedBlockCoverage;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000294}
295
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000296size_t Fuzzer::RecordCallerCalleeCoverage() {
297 if (!Options.UseIndirCalls)
298 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000299 if (!__sanitizer_get_total_unique_caller_callee_pairs)
300 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000301 return LastRecordedCallerCalleeCoverage =
302 __sanitizer_get_total_unique_caller_callee_pairs();
303}
304
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000305void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000306 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000307 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000308 CounterBitmap.resize(NumCounters);
309 __sanitizer_update_counter_bitset_and_clear_counters(0);
310 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000311 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000312 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000313}
314
315bool Fuzzer::CheckCoverageAfterRun() {
316 size_t OldCoverage = LastRecordedBlockCoverage;
317 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000318 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
319 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000320 size_t NumNewBits = 0;
Kostya Serebryanyda63c1d2016-02-26 21:33:56 +0000321 size_t OldPcMapSize = LastRecordedPcMapSize;
322 PcMapMergeCurrentToCombined();
323 size_t NewPcMapSize = PcMapCombinedSize();
324 LastRecordedPcMapSize = NewPcMapSize;
325 if (NewPcMapSize > OldPcMapSize)
326 return true;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000327 if (Options.UseCounters)
328 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
329 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000330 return NewCoverage > OldCoverage ||
331 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000332}
333
334void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Ivan Krasindf919102016-01-22 22:28:27 +0000335 if (Options.OutputCorpus.empty())
336 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000337 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
338 WriteToFile(U, Path);
339 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000340 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000341 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000342}
343
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000344void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000345 if (!Options.SaveArtifacts)
346 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000347 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000348 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000349 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000350 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000351 Printf("artifact_prefix='%s'; Test unit written to %s\n",
352 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000353 if (U.size() <= kMaxUnitSizeToPrint)
354 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000355}
356
357void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000358 if (Options.OutputCorpus.empty())
359 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000360 for (const auto &U : Corpus)
361 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
362 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000363 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
364 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000365}
366
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000367void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
368 if (!Options.PrintNEW)
369 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000370 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000371 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000372 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000373 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000374 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000375 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000376}
377
378void Fuzzer::ReportNewCoverage(const Unit &U) {
379 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000380 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000381 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000382 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000383 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000384 WriteToOutputCorpus(U);
385 if (Options.ExitOnFirst)
386 exit(0);
Aaron Ballmanef116982015-01-29 16:58:29 +0000387}
388
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000389void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
390 if (Corpora.size() <= 1) {
391 Printf("Merge requires two or more corpus dirs\n");
392 return;
393 }
394 auto InitialCorpusDir = Corpora[0];
Kostya Serebryanya35f7d32016-02-18 21:49:10 +0000395 ReadDir(InitialCorpusDir, nullptr, Options.MaxLen);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000396 Printf("Merge: running the initial corpus '%s' of %d units\n",
397 InitialCorpusDir.c_str(), Corpus.size());
398 for (auto &U : Corpus)
399 RunOne(U);
400
401 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
402
403 size_t NumTried = 0;
404 size_t NumMerged = 0;
405 for (auto &C : ExtraCorpora) {
406 Corpus.clear();
Kostya Serebryanya35f7d32016-02-18 21:49:10 +0000407 ReadDir(C, nullptr, Options.MaxLen);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000408 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
409 Corpus.size());
410 for (auto &U : Corpus) {
411 NumTried++;
412 if (RunOne(U)) {
413 WriteToOutputCorpus(U);
414 NumMerged++;
415 }
416 }
417 }
418 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
419}
420
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000421void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000422 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000423
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000424 auto &U = ChooseUnitToMutate();
425 MutateInPlaceHere.resize(Options.MaxLen);
426 memcpy(MutateInPlaceHere.data(), U.data(), U.size());
427 size_t Size = U.size();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000428
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000429 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000430 size_t NewSize = 0;
431 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000432 NewSize = LLVMFuzzerCustomMutator(MutateInPlaceHere.data(), Size,
433 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000434 else
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000435 NewSize = MD.Mutate(MutateInPlaceHere.data(), Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000436 assert(NewSize > 0 && "Mutator returned empty unit");
437 assert(NewSize <= (size_t)Options.MaxLen &&
438 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000439 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000440 if (i == 0)
441 StartTraceRecording();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000442 RunOneAndUpdateCorpus(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000443 StopTraceRecording();
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000444 }
445}
446
Kostya Serebryanye6926212015-11-04 23:22:25 +0000447// Returns an index of random unit from the corpus to mutate.
448// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000449// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000450size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000451 size_t Idx =
452 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000453 assert(Idx < Corpus.size());
454 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000455}
456
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000457// Experimental search heuristic: drilling.
458// - Read, shuffle, execute and minimize the corpus.
459// - Choose one random unit.
460// - Reset the coverage.
461// - Start fuzzing as if the chosen unit was the only element of the corpus.
462// - When done, reset the coverage again.
463// - Merge the newly created corpus into the original one.
464void Fuzzer::Drill() {
465 // The corpus is already read, shuffled, and minimized.
466 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000467 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000468
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000469 Unit U = ChooseUnitToMutate();
470
471 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
472 __sanitizer_reset_coverage();
473
474 std::vector<Unit> SavedCorpus;
475 SavedCorpus.swap(Corpus);
476 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000477 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000478 assert(Corpus.size() == 1);
479 RunOne(U);
480 PrintStats("DRILL ");
481 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
482 SavedOutputCorpusPath.swap(Options.OutputCorpus);
483 Loop();
484
485 __sanitizer_reset_coverage();
486
487 PrintStats("REINIT");
488 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000489 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000490 RunOne(U);
491 PrintStats("MERGE ");
492 Options.PrintNEW = true;
493 size_t NumMerged = 0;
494 for (auto &U : Corpus) {
495 if (RunOne(U)) {
496 PrintStatusForNewUnit(U);
497 NumMerged++;
498 WriteToOutputCorpus(U);
499 }
500 }
501 PrintStats("MERGED");
502 if (NumMerged && Options.Verbosity)
503 Printf("Drilling discovered %zd new units\n", NumMerged);
504}
505
506void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000507 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000508 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000509 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000510 while (true) {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000511 SyncCorpus();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000512 auto Now = system_clock::now();
513 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
514 RereadOutputCorpus();
515 LastCorpusReload = Now;
516 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000517 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000518 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000519 if (Options.MaxTotalTimeSec > 0 &&
520 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000521 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000522 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000523 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000524 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000525 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000526
527 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000528 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000529}
530
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000531void Fuzzer::SyncCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000532 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty())
533 return;
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000534 auto Now = system_clock::now();
535 if (duration_cast<seconds>(Now - LastExternalSync).count() <
536 Options.SyncTimeout)
537 return;
538 LastExternalSync = Now;
539 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
540}
541
Ivan Krasindf919102016-01-22 22:28:27 +0000542void Fuzzer::UpdateCorpusDistribution() {
543 size_t N = Corpus.size();
544 std::vector<double> Intervals(N + 1);
545 std::vector<double> Weights(N);
546 std::iota(Intervals.begin(), Intervals.end(), 0);
547 std::iota(Weights.begin(), Weights.end(), 1);
548 CorpusDistribution = std::piecewise_constant_distribution<double>(
549 Intervals.begin(), Intervals.end(), Weights.begin());
550}
551
552} // namespace fuzzer