blob: db8868c68387484acaf3f3cac9e64a232a32eaed [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 Serebryany1bfd5832016-04-20 00:24:21 +000021#if __has_include(<sanitizer / lsan_interface.h>)
22#include <sanitizer/lsan_interface.h>
23#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000024#endif
25
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000026#define NO_SANITIZE_MEMORY
27#if defined(__has_feature)
28#if __has_feature(memory_sanitizer)
29#undef NO_SANITIZE_MEMORY
30#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
31#endif
32#endif
33
Aaron Ballmanef116982015-01-29 16:58:29 +000034namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000035static const size_t kMaxUnitSizeToPrint = 256;
Mike Aizatskyaf432a42016-05-24 23:14:29 +000036static const size_t TruncateMaxRuns = 1000;
Aaron Ballmanef116982015-01-29 16:58:29 +000037
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000038thread_local bool Fuzzer::IsMyThread;
39
Dan Liew1873a492016-06-07 23:32:50 +000040static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000041 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000042 "Did you use -fsanitize-coverage=... to build your code?\n",
43 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000044 exit(1);
45}
46
Dan Liew1873a492016-06-07 23:32:50 +000047#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000048 do { \
Dan Liew1873a492016-06-07 23:32:50 +000049 if (!(EF->fn)) \
50 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000051 } while (false)
52
Kostya Serebryany52a788e2015-03-31 20:13:20 +000053// Only one Fuzzer per process.
54static Fuzzer *F;
55
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000056// Only one CoverageController per process should be created.
57class CoverageController {
58 public:
59 explicit CoverageController(const FuzzingOptions &Options)
60 : Options(Options) {
61 if (Options.PrintNewCovPcs) {
62 PcBufferLen = 1 << 24;
63 PcBuffer = new uintptr_t[PcBufferLen];
64 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
65 }
66 }
67
68 uintptr_t* pc_buffer() const { return PcBuffer; }
69
70 void Reset() {
Dan Liew1873a492016-06-07 23:32:50 +000071 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
72 EF->__sanitizer_reset_coverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000073 PcMapResetCurrent();
74 }
75
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000076 void ResetCounters() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000077 if (Options.UseCounters) {
Dan Liew1873a492016-06-07 23:32:50 +000078 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000079 }
80 }
81
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000082 void Prepare(Fuzzer::Coverage *C) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000083 if (Options.UseCounters) {
Dan Liew1873a492016-06-07 23:32:50 +000084 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000085 C->CounterBitmap.resize(NumCounters);
86 }
87 }
88
89 // Records data to a maximum coverage tracker. Returns true if additional
90 // coverage was discovered.
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000091 bool RecordMax(Fuzzer::Coverage *C) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000092 bool Res = false;
93
Dan Liew1873a492016-06-07 23:32:50 +000094 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000095 if (NewBlockCoverage > C->BlockCoverage) {
96 Res = true;
97 C->BlockCoverage = NewBlockCoverage;
98 }
99
100 if (Options.UseIndirCalls &&
Dan Liew1873a492016-06-07 23:32:50 +0000101 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000102 uint64_t NewCallerCalleeCoverage =
Dan Liew1873a492016-06-07 23:32:50 +0000103 EF->__sanitizer_get_total_unique_caller_callee_pairs();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000104 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
105 Res = true;
106 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
107 }
108 }
109
110 if (Options.UseCounters) {
111 uint64_t CounterDelta =
Dan Liew1873a492016-06-07 23:32:50 +0000112 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000113 C->CounterBitmap.data());
114 if (CounterDelta > 0) {
115 Res = true;
116 C->CounterBitmapBits += CounterDelta;
117 }
118 }
119
120 uint64_t NewPcMapBits = PcMapMergeInto(&C->PCMap);
121 if (NewPcMapBits > C->PcMapBits) {
122 Res = true;
123 C->PcMapBits = NewPcMapBits;
124 }
125
Kostya Serebryany728447b2016-08-06 21:28:56 +0000126 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
127 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
128 if (NewPcBufferPos > C->PcBufferPos) {
129 Res = true;
130 C->PcBufferPos = NewPcBufferPos;
131 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000132
Kostya Serebryany728447b2016-08-06 21:28:56 +0000133 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
134 Printf("ERROR: PC buffer overflow\n");
135 _Exit(1);
136 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000137 }
138
139 return Res;
140 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000141
142 private:
143 const FuzzingOptions Options;
144 uintptr_t* PcBuffer = nullptr;
145 size_t PcBufferLen = 0;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000146};
147
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000148// Leak detection is expensive, so we first check if there were more mallocs
149// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
150struct MallocFreeTracer {
151 void Start() {
152 Mallocs = 0;
153 Frees = 0;
154 }
155 // Returns true if there were more mallocs than frees.
156 bool Stop() { return Mallocs > Frees; }
157 std::atomic<size_t> Mallocs;
158 std::atomic<size_t> Frees;
159};
160
161static MallocFreeTracer AllocTracer;
162
163void MallocHook(const volatile void *ptr, size_t size) {
164 AllocTracer.Mallocs++;
165}
166void FreeHook(const volatile void *ptr) {
167 AllocTracer.Frees++;
168}
169
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000170Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000171 : CB(CB), MD(MD), Options(Options),
172 CController(new CoverageController(Options)) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000173 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000174 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000175 assert(!F);
176 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000177 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000178 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000179 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
180 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000181}
Aaron Ballmanef116982015-01-29 16:58:29 +0000182
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000183Fuzzer::~Fuzzer() { }
184
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000185void Fuzzer::LazyAllocateCurrentUnitData() {
186 if (CurrentUnitData || Options.MaxLen == 0) return;
187 CurrentUnitData = new uint8_t[Options.MaxLen];
188}
189
Aaron Ballmanef116982015-01-29 16:58:29 +0000190void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000191 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
192 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000193}
194
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000195void Fuzzer::StaticDeathCallback() {
196 assert(F);
197 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000198}
199
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000200void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany311cc832016-05-28 04:19:46 +0000201 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000202 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000203 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000204 PrintHexArray(CurrentUnitData, UnitSize, "\n");
205 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000206 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000207 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
208 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000209}
210
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000211NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000212void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000213 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000214 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000215}
216
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000217void Fuzzer::StaticAlarmCallback() {
218 assert(F);
219 F->AlarmCallback();
220}
221
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000222void Fuzzer::StaticCrashSignalCallback() {
223 assert(F);
224 F->CrashCallback();
225}
226
227void Fuzzer::StaticInterruptCallback() {
228 assert(F);
229 F->InterruptCallback();
230}
231
232void Fuzzer::CrashCallback() {
233 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000234 if (EF->__sanitizer_print_stack_trace)
235 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000236 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
237 " Combine libFuzzer with AddressSanitizer or similar for better "
238 "crash reports.\n");
239 Printf("SUMMARY: libFuzzer: deadly signal\n");
240 DumpCurrentUnit("crash-");
241 PrintFinalStats();
242 exit(Options.ErrorExitCode);
243}
244
245void Fuzzer::InterruptCallback() {
246 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
247 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000248 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000249}
250
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000251NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000252void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000253 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000254 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000255 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000256 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000257 size_t Seconds =
258 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000259 if (Seconds == 0)
260 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000261 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000262 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000263 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000264 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000265 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
266 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000267 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000268 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
269 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000270 if (EF->__sanitizer_print_stack_trace)
271 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000272 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000273 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000274 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000275 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000276}
277
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000278void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000279 Printf(
280 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
281 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000282 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000283 if (EF->__sanitizer_print_memory_profile)
284 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000285 DumpCurrentUnit("oom-");
286 Printf("SUMMARY: libFuzzer: out-of-memory\n");
287 PrintFinalStats();
288 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000289}
290
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000291void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000292 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000293 if (Options.OutputCSV) {
294 static bool csvHeaderPrinted = false;
295 if (!csvHeaderPrinted) {
296 csvHeaderPrinted = true;
297 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
298 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000299 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000300 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
301 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000302 }
303
304 if (!Options.Verbosity)
305 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000306 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000307 if (MaxCoverage.BlockCoverage)
308 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
309 if (MaxCoverage.PcMapBits)
310 Printf(" path: %zd", MaxCoverage.PcMapBits);
311 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000312 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000313 if (MaxCoverage.CallerCalleeCoverage)
314 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000315 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000316 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000317}
318
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000319void Fuzzer::PrintFinalStats() {
320 if (!Options.PrintFinalStats) return;
321 size_t ExecPerSec = execPerSec();
322 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
323 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
324 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
325 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
326 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
327}
328
Kostya Serebryany64d24572016-03-12 01:57:04 +0000329size_t Fuzzer::MaxUnitSizeInCorpus() const {
330 size_t Res = 0;
331 for (auto &X : Corpus)
332 Res = std::max(Res, X.size());
333 return Res;
334}
335
336void Fuzzer::SetMaxLen(size_t MaxLen) {
337 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
338 assert(MaxLen);
339 Options.MaxLen = MaxLen;
340 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
341}
342
343
344void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000345 if (Options.OutputCorpus.empty())
346 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000347 std::vector<Unit> AdditionalCorpus;
348 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000349 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000350 if (Corpus.empty()) {
351 Corpus = AdditionalCorpus;
352 return;
353 }
Ivan Krasindf919102016-01-22 22:28:27 +0000354 if (!Options.Reload)
355 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000356 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000357 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000358 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000359 if (X.size() > MaxSize)
360 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000361 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000362 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000363 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000364 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000365 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000366 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000367 }
368 }
369}
370
Kostya Serebryany945761b2016-03-18 00:23:29 +0000371void Fuzzer::ShuffleCorpus(UnitVector *V) {
372 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
373 if (Options.PreferSmall)
374 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
375 return A.size() < B.size();
376 });
377}
378
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000379// Tries random prefixes of corpus items.
380// Prefix length is chosen according to exponential distribution
381// to sample short lengths much more heavily.
382void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
383 size_t MaxCorpusLen = 0;
384 for (const auto &U : Corpus)
385 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
386
387 if (MaxCorpusLen <= 1)
388 return;
389
390 // 50% of exponential distribution is Log[2]/lambda.
391 // Choose lambda so that median is MaxCorpusLen / 2.
392 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
393 std::exponential_distribution<> Dist(Lambda);
394 std::vector<double> Sizes;
395 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
396 Sizes.reserve(TruncatePoints);
397 for (size_t I = 0; I < TruncatePoints; ++I) {
398 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
399 }
400 std::sort(Sizes.begin(), Sizes.end());
401
402 for (size_t S : Sizes) {
403 for (const auto &U : Corpus) {
404 if (S < U.size() && RunOne(U.data(), S)) {
405 Unit U1(U.begin(), U.begin() + S);
406 NewCorpus->push_back(U1);
407 WriteToOutputCorpus(U1);
408 PrintStatusForNewUnit(U1);
409 }
410 }
411 }
412 PrintStats("TRUNC ");
413}
414
Aaron Ballmanef116982015-01-29 16:58:29 +0000415void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000416 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000417 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000418 if (Options.ShuffleAtStartUp)
419 ShuffleCorpus(&Corpus);
420
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000421 if (Options.TruncateUnits) {
422 ResetCoverage();
423 TruncateUnits(&NewCorpus);
424 ResetCoverage();
425 }
426
Kostya Serebryany945761b2016-03-18 00:23:29 +0000427 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000428 bool NewCoverage = RunOne(U);
429 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000430 NewCorpus.push_back(U);
431 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000432 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000433 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000434 TryDetectingAMemoryLeak(U.data(), U.size(),
435 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000436 }
437 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000438 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000439 for (auto &X : Corpus)
440 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000441 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000442 if (Corpus.empty()) {
443 Printf("ERROR: no interesting inputs were found. "
444 "Is the code instrumented for coverage? Exiting.\n");
445 exit(1);
446 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000447}
448
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000449bool Fuzzer::UpdateMaxCoverage() {
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000450 uintptr_t PrevPcBufferPos = MaxCoverage.PcBufferPos;
451 bool Res = CController->RecordMax(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000452
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000453 if (Options.PrintNewCovPcs && PrevPcBufferPos != MaxCoverage.PcBufferPos) {
454 uintptr_t* PcBuffer = CController->pc_buffer();
455 for (size_t I = PrevPcBufferPos; I < MaxCoverage.PcBufferPos; ++I) {
456 Printf("%p\n", PcBuffer[I]);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000457 }
458 }
459
460 return Res;
461}
462
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000463bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000464 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000465
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000466 // TODO(aizatsky): this Reset call seems to be not needed.
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000467 CController->ResetCounters();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000468 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000469 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000470
Kostya Serebryany16901a92015-03-30 23:04:35 +0000471 auto UnitStopTime = system_clock::now();
472 auto TimeOfUnit =
473 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000474 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
475 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000476 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000477 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
478 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000479 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000480 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000481 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000482 }
483 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000484}
485
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000486void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000487 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
488 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000489 if (RunOne(Data, Size))
490 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000491}
492
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000493size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000494 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000495 *Data = CurrentUnitData;
496 return CurrentUnitSize;
497}
498
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000499void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000500 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000501 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000502 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000503 // We copy the contents of Unit into a separate heap buffer
504 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000505 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
506 memcpy(DataCopy.get(), Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000507 if (CurrentUnitData && CurrentUnitData != Data)
508 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000509 AssignTaintLabels(DataCopy.get(), Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000510 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000511 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000512 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000513 (void)Res;
514 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000515 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000516 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000517}
518
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000519std::string Fuzzer::Coverage::DebugString() const {
520 std::string Result =
521 std::string("Coverage{") + "BlockCoverage=" +
522 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
523 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
524 std::to_string(CounterBitmapBits) + " PcMapBits=" +
525 std::to_string(PcMapBits) + "}";
526 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000527}
528
529void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000530 if (Options.OnlyASCII)
531 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000532 if (Options.OutputCorpus.empty())
533 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000534 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
535 WriteToFile(U, Path);
536 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000537 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000538}
539
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000540void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000541 if (!Options.SaveArtifacts)
542 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000543 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000544 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000545 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000546 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000547 Printf("artifact_prefix='%s'; Test unit written to %s\n",
548 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000549 if (U.size() <= kMaxUnitSizeToPrint)
550 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000551}
552
553void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000554 if (Options.OutputCorpus.empty())
555 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000556 for (const auto &U : Corpus)
557 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
558 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000559 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
560 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000561}
562
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000563void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
564 if (!Options.PrintNEW)
565 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000566 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000567 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000568 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000569 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000570 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000571 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000572}
573
574void Fuzzer::ReportNewCoverage(const Unit &U) {
575 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000576 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000577 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000578 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000579 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000580 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000581 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000582}
583
Kostya Serebryany945761b2016-03-18 00:23:29 +0000584// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
585// We do it by actually executing the units, sometimes more than once,
586// because we may be using different coverage-like signals and the only
587// common thing between them is that we can say "this unit found new stuff".
588UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
589 const UnitVector &Extra) {
590 UnitVector Res = Extra;
591 size_t OldSize = Res.size();
592 for (int Iter = 0; Iter < 10; Iter++) {
593 ShuffleCorpus(&Res);
594 ResetCoverage();
595
596 for (auto &U : Initial)
597 RunOne(U);
598
599 Corpus.clear();
600 for (auto &U : Res)
601 if (RunOne(U))
602 Corpus.push_back(U);
603
604 char Stat[7] = "MIN ";
605 Stat[3] = '0' + Iter;
606 PrintStats(Stat);
607
608 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000609 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000610 Res.swap(Corpus);
611
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000612 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000613 break;
614 OldSize = NewSize;
615 }
616 return Res;
617}
618
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000619void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
620 if (Corpora.size() <= 1) {
621 Printf("Merge requires two or more corpus dirs\n");
622 return;
623 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000624 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
625
Kostya Serebryany945761b2016-03-18 00:23:29 +0000626 assert(Options.MaxLen > 0);
627 UnitVector Initial, Extra;
628 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
629 for (auto &C : ExtraCorpora)
630 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
631
632 if (!Initial.empty()) {
633 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
634 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000635 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000636
637 Printf("=== Merging extra %zd units\n", Extra.size());
638 auto Res = FindExtraUnits(Initial, Extra);
639
640 for (auto &U: Res)
641 WriteToOutputCorpus(U);
642
643 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000644}
645
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000646// Tries detecting a memory leak on the particular input that we have just
647// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000648void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
649 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000650 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
651 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000652 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
653 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000654 return; // No lsan.
655 // Run the target once again, but with lsan disabled so that if there is
656 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000657 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000658 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000659 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000660 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000661 if (NumberOfLeakDetectionAttempts++ > 1000) {
662 Options.DetectLeaks = false;
663 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
664 " Most likely the target function accumulates allocated\n"
665 " memory in a global state w/o actually leaking it.\n"
666 " If LeakSanitizer is enabled in this process it will still\n"
667 " run on the process shutdown.\n");
668 return;
669 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000670 // Now perform the actual lsan pass. This is expensive and we must ensure
671 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000672 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000673 if (DuringInitialCorpusExecution)
674 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
675 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000676 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000677 DumpCurrentUnit("leak-");
678 PrintFinalStats();
679 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
680 }
681}
682
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000683void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000684 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000685 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000686
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000687 auto &U = ChooseUnitToMutate();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000688 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000689 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000690 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000691 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000692
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000693 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000694 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000695 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000696 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000697 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000698 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000699 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000700 if (i == 0)
701 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000702 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000703 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000704 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000705 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000706 }
707}
708
Kostya Serebryanye6926212015-11-04 23:22:25 +0000709// Returns an index of random unit from the corpus to mutate.
710// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000711// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000712size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000713 size_t Idx =
714 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000715 assert(Idx < Corpus.size());
716 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000717}
718
Kostya Serebryany945761b2016-03-18 00:23:29 +0000719void Fuzzer::ResetCoverage() {
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000720 CController->Reset();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000721 MaxCoverage.Reset();
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000722 CController->Prepare(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000723}
724
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000725// Experimental search heuristic: drilling.
726// - Read, shuffle, execute and minimize the corpus.
727// - Choose one random unit.
728// - Reset the coverage.
729// - Start fuzzing as if the chosen unit was the only element of the corpus.
730// - When done, reset the coverage again.
731// - Merge the newly created corpus into the original one.
732void Fuzzer::Drill() {
733 // The corpus is already read, shuffled, and minimized.
734 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000735 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000736
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000737 Unit U = ChooseUnitToMutate();
738
Kostya Serebryany945761b2016-03-18 00:23:29 +0000739 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000740
741 std::vector<Unit> SavedCorpus;
742 SavedCorpus.swap(Corpus);
743 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000744 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000745 assert(Corpus.size() == 1);
746 RunOne(U);
747 PrintStats("DRILL ");
748 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
749 SavedOutputCorpusPath.swap(Options.OutputCorpus);
750 Loop();
751
Kostya Serebryany945761b2016-03-18 00:23:29 +0000752 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000753
754 PrintStats("REINIT");
755 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000756 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000757 RunOne(U);
758 PrintStats("MERGE ");
759 Options.PrintNEW = true;
760 size_t NumMerged = 0;
761 for (auto &U : Corpus) {
762 if (RunOne(U)) {
763 PrintStatusForNewUnit(U);
764 NumMerged++;
765 WriteToOutputCorpus(U);
766 }
767 }
768 PrintStats("MERGED");
769 if (NumMerged && Options.Verbosity)
770 Printf("Drilling discovered %zd new units\n", NumMerged);
771}
772
773void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000774 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000775 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000776 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000777 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000778 auto Now = system_clock::now();
779 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000780 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000781 LastCorpusReload = Now;
782 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000783 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000784 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000785 if (Options.MaxTotalTimeSec > 0 &&
786 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000787 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000788 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000789 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000790 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000791 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000792
793 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000794 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000795}
796
Ivan Krasindf919102016-01-22 22:28:27 +0000797void Fuzzer::UpdateCorpusDistribution() {
798 size_t N = Corpus.size();
799 std::vector<double> Intervals(N + 1);
800 std::vector<double> Weights(N);
801 std::iota(Intervals.begin(), Intervals.end(), 0);
802 std::iota(Weights.begin(), Weights.end(), 1);
803 CorpusDistribution = std::piecewise_constant_distribution<double>(
804 Intervals.begin(), Intervals.end(), Weights.begin());
805}
806
807} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000808
809extern "C" {
810
811size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
812 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000813 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000814}
815} // extern "C"