blob: 07de3c7c8b9477f1d08888b64bf59d0f735c0258 [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:
Kostya Serebryanyc98ef712016-08-16 17:37:13 +000059 explicit CoverageController(const FuzzingOptions &Options)
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000060 : 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 }
74
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000075 void ResetCounters() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000076 if (Options.UseCounters) {
Dan Liew1873a492016-06-07 23:32:50 +000077 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000078 }
79 }
80
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000081 void Prepare(Fuzzer::Coverage *C) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000082 if (Options.UseCounters) {
Dan Liew1873a492016-06-07 23:32:50 +000083 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000084 C->CounterBitmap.resize(NumCounters);
85 }
86 }
87
88 // Records data to a maximum coverage tracker. Returns true if additional
89 // coverage was discovered.
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000090 bool RecordMax(Fuzzer::Coverage *C) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000091 bool Res = false;
92
Dan Liew1873a492016-06-07 23:32:50 +000093 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000094 if (NewBlockCoverage > C->BlockCoverage) {
95 Res = true;
96 C->BlockCoverage = NewBlockCoverage;
97 }
98
99 if (Options.UseIndirCalls &&
Dan Liew1873a492016-06-07 23:32:50 +0000100 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000101 uint64_t NewCallerCalleeCoverage =
Dan Liew1873a492016-06-07 23:32:50 +0000102 EF->__sanitizer_get_total_unique_caller_callee_pairs();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000103 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
104 Res = true;
105 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
106 }
107 }
108
109 if (Options.UseCounters) {
110 uint64_t CounterDelta =
Dan Liew1873a492016-06-07 23:32:50 +0000111 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000112 C->CounterBitmap.data());
113 if (CounterDelta > 0) {
114 Res = true;
115 C->CounterBitmapBits += CounterDelta;
116 }
117 }
118
Kostya Serebryanyc98ef712016-08-16 17:37:13 +0000119 size_t NewPCMapBits = PCMapMergeFromCurrent(C->PCMap);
120 if (NewPCMapBits > C->PCMapBits) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000121 Res = true;
Kostya Serebryanyc98ef712016-08-16 17:37:13 +0000122 C->PCMapBits = NewPCMapBits;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000123 }
124
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000125 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
126 if (NewVPMapBits > C->VPMapBits) {
127 Res = true;
128 C->VPMapBits = NewVPMapBits;
129 }
130
Kostya Serebryany728447b2016-08-06 21:28:56 +0000131 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
132 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
133 if (NewPcBufferPos > C->PcBufferPos) {
134 Res = true;
135 C->PcBufferPos = NewPcBufferPos;
136 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000137
Kostya Serebryany728447b2016-08-06 21:28:56 +0000138 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
139 Printf("ERROR: PC buffer overflow\n");
140 _Exit(1);
141 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000142 }
143
144 return Res;
145 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000146
147 private:
148 const FuzzingOptions Options;
149 uintptr_t* PcBuffer = nullptr;
150 size_t PcBufferLen = 0;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000151};
152
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000153// Leak detection is expensive, so we first check if there were more mallocs
154// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
155struct MallocFreeTracer {
156 void Start() {
157 Mallocs = 0;
158 Frees = 0;
159 }
160 // Returns true if there were more mallocs than frees.
161 bool Stop() { return Mallocs > Frees; }
162 std::atomic<size_t> Mallocs;
163 std::atomic<size_t> Frees;
164};
165
166static MallocFreeTracer AllocTracer;
167
168void MallocHook(const volatile void *ptr, size_t size) {
169 AllocTracer.Mallocs++;
170}
171void FreeHook(const volatile void *ptr) {
172 AllocTracer.Frees++;
173}
174
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000175Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000176 : CB(CB), MD(MD), Options(Options),
177 CController(new CoverageController(Options)) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000178 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000179 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000180 assert(!F);
181 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000182 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000183 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000184 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
185 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000186}
Aaron Ballmanef116982015-01-29 16:58:29 +0000187
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000188Fuzzer::~Fuzzer() { }
189
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000190void Fuzzer::LazyAllocateCurrentUnitData() {
191 if (CurrentUnitData || Options.MaxLen == 0) return;
192 CurrentUnitData = new uint8_t[Options.MaxLen];
193}
194
Aaron Ballmanef116982015-01-29 16:58:29 +0000195void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000196 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
197 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000198}
199
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000200void Fuzzer::StaticDeathCallback() {
201 assert(F);
202 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000203}
204
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000205void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany311cc832016-05-28 04:19:46 +0000206 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000207 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000208 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000209 PrintHexArray(CurrentUnitData, UnitSize, "\n");
210 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000211 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000212 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
213 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000214}
215
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000216NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000217void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000218 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000219 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000220}
221
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000222void Fuzzer::StaticAlarmCallback() {
223 assert(F);
224 F->AlarmCallback();
225}
226
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000227void Fuzzer::StaticCrashSignalCallback() {
228 assert(F);
229 F->CrashCallback();
230}
231
232void Fuzzer::StaticInterruptCallback() {
233 assert(F);
234 F->InterruptCallback();
235}
236
237void Fuzzer::CrashCallback() {
238 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000239 if (EF->__sanitizer_print_stack_trace)
240 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000241 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
242 " Combine libFuzzer with AddressSanitizer or similar for better "
243 "crash reports.\n");
244 Printf("SUMMARY: libFuzzer: deadly signal\n");
245 DumpCurrentUnit("crash-");
246 PrintFinalStats();
247 exit(Options.ErrorExitCode);
248}
249
250void Fuzzer::InterruptCallback() {
251 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
252 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000253 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000254}
255
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000256NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000257void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000258 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000259 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000260 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000261 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000262 size_t Seconds =
263 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000264 if (Seconds == 0)
265 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000266 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000267 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000268 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000269 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000270 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
271 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000272 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000273 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
274 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000275 if (EF->__sanitizer_print_stack_trace)
276 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000277 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000278 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000279 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000280 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000281}
282
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000283void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000284 Printf(
285 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
286 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000287 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000288 if (EF->__sanitizer_print_memory_profile)
289 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000290 DumpCurrentUnit("oom-");
291 Printf("SUMMARY: libFuzzer: out-of-memory\n");
292 PrintFinalStats();
293 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000294}
295
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000296void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000297 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000298 if (Options.OutputCSV) {
299 static bool csvHeaderPrinted = false;
300 if (!csvHeaderPrinted) {
301 csvHeaderPrinted = true;
302 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
303 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000304 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000305 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
306 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000307 }
308
309 if (!Options.Verbosity)
310 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000311 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000312 if (MaxCoverage.BlockCoverage)
313 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyc98ef712016-08-16 17:37:13 +0000314 if (MaxCoverage.PCMapBits)
315 Printf(" path: %zd", MaxCoverage.PCMapBits);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000316 if (MaxCoverage.VPMapBits)
317 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000318 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000319 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000320 if (MaxCoverage.CallerCalleeCoverage)
321 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000322 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000323 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000324}
325
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000326void Fuzzer::PrintFinalStats() {
327 if (!Options.PrintFinalStats) return;
328 size_t ExecPerSec = execPerSec();
329 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
330 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
331 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
332 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
333 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
334}
335
Kostya Serebryany64d24572016-03-12 01:57:04 +0000336size_t Fuzzer::MaxUnitSizeInCorpus() const {
337 size_t Res = 0;
338 for (auto &X : Corpus)
339 Res = std::max(Res, X.size());
340 return Res;
341}
342
343void Fuzzer::SetMaxLen(size_t MaxLen) {
344 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
345 assert(MaxLen);
346 Options.MaxLen = MaxLen;
347 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
348}
349
350
351void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000352 if (Options.OutputCorpus.empty())
353 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000354 std::vector<Unit> AdditionalCorpus;
355 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000356 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000357 if (Corpus.empty()) {
358 Corpus = AdditionalCorpus;
359 return;
360 }
Ivan Krasindf919102016-01-22 22:28:27 +0000361 if (!Options.Reload)
362 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000363 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000364 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000365 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000366 if (X.size() > MaxSize)
367 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000368 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000369 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000370 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000371 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000372 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000373 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000374 }
375 }
376}
377
Kostya Serebryany945761b2016-03-18 00:23:29 +0000378void Fuzzer::ShuffleCorpus(UnitVector *V) {
379 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
380 if (Options.PreferSmall)
381 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
382 return A.size() < B.size();
383 });
384}
385
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000386// Tries random prefixes of corpus items.
387// Prefix length is chosen according to exponential distribution
388// to sample short lengths much more heavily.
389void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
390 size_t MaxCorpusLen = 0;
391 for (const auto &U : Corpus)
392 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
393
394 if (MaxCorpusLen <= 1)
395 return;
396
397 // 50% of exponential distribution is Log[2]/lambda.
398 // Choose lambda so that median is MaxCorpusLen / 2.
399 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
400 std::exponential_distribution<> Dist(Lambda);
401 std::vector<double> Sizes;
402 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
403 Sizes.reserve(TruncatePoints);
404 for (size_t I = 0; I < TruncatePoints; ++I) {
405 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
406 }
407 std::sort(Sizes.begin(), Sizes.end());
408
409 for (size_t S : Sizes) {
410 for (const auto &U : Corpus) {
411 if (S < U.size() && RunOne(U.data(), S)) {
412 Unit U1(U.begin(), U.begin() + S);
413 NewCorpus->push_back(U1);
414 WriteToOutputCorpus(U1);
415 PrintStatusForNewUnit(U1);
416 }
417 }
418 }
419 PrintStats("TRUNC ");
420}
421
Aaron Ballmanef116982015-01-29 16:58:29 +0000422void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000423 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000424 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000425 if (Options.ShuffleAtStartUp)
426 ShuffleCorpus(&Corpus);
427
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000428 if (Options.TruncateUnits) {
429 ResetCoverage();
430 TruncateUnits(&NewCorpus);
431 ResetCoverage();
432 }
433
Kostya Serebryany945761b2016-03-18 00:23:29 +0000434 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000435 bool NewCoverage = RunOne(U);
436 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000437 NewCorpus.push_back(U);
438 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000439 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000440 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000441 TryDetectingAMemoryLeak(U.data(), U.size(),
442 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000443 }
444 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000445 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000446 for (auto &X : Corpus)
447 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000448 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000449 if (Corpus.empty()) {
450 Printf("ERROR: no interesting inputs were found. "
451 "Is the code instrumented for coverage? Exiting.\n");
452 exit(1);
453 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000454}
455
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000456bool Fuzzer::UpdateMaxCoverage() {
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000457 uintptr_t PrevPcBufferPos = MaxCoverage.PcBufferPos;
458 bool Res = CController->RecordMax(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000459
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000460 if (Options.PrintNewCovPcs && PrevPcBufferPos != MaxCoverage.PcBufferPos) {
461 uintptr_t* PcBuffer = CController->pc_buffer();
462 for (size_t I = PrevPcBufferPos; I < MaxCoverage.PcBufferPos; ++I) {
463 Printf("%p\n", PcBuffer[I]);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000464 }
465 }
466
467 return Res;
468}
469
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000470bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000471 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000472
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000473 // TODO(aizatsky): this Reset call seems to be not needed.
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000474 CController->ResetCounters();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000475 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000476 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000477
Kostya Serebryany16901a92015-03-30 23:04:35 +0000478 auto UnitStopTime = system_clock::now();
479 auto TimeOfUnit =
480 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000481 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
482 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000483 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000484 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
485 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000486 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000487 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000488 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000489 }
490 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000491}
492
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000493void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000494 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
495 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000496 if (RunOne(Data, Size))
497 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000498}
499
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000500size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000501 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000502 *Data = CurrentUnitData;
503 return CurrentUnitSize;
504}
505
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000506void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000507 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000508 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000509 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000510 // We copy the contents of Unit into a separate heap buffer
511 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000512 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
513 memcpy(DataCopy.get(), Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000514 if (CurrentUnitData && CurrentUnitData != Data)
515 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000516 AssignTaintLabels(DataCopy.get(), Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000517 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000518 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000519 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000520 (void)Res;
521 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000522 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000523 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000524}
525
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000526std::string Fuzzer::Coverage::DebugString() const {
527 std::string Result =
528 std::string("Coverage{") + "BlockCoverage=" +
529 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
530 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000531 std::to_string(CounterBitmapBits) + " PCMapBits=" +
532 std::to_string(PCMapBits) + " VPMapBits " +
533 std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000534 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000535}
536
537void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000538 if (Options.OnlyASCII)
539 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000540 if (Options.OutputCorpus.empty())
541 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000542 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
543 WriteToFile(U, Path);
544 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000545 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000546}
547
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000548void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000549 if (!Options.SaveArtifacts)
550 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000551 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000552 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000553 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000554 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000555 Printf("artifact_prefix='%s'; Test unit written to %s\n",
556 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000557 if (U.size() <= kMaxUnitSizeToPrint)
558 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000559}
560
561void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000562 if (Options.OutputCorpus.empty())
563 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000564 for (const auto &U : Corpus)
565 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
566 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000567 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
568 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000569}
570
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000571void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
572 if (!Options.PrintNEW)
573 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000574 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000575 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000576 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000577 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000578 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000579 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000580}
581
582void Fuzzer::ReportNewCoverage(const Unit &U) {
583 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000584 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000585 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000586 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000587 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000588 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000589 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000590}
591
Kostya Serebryany945761b2016-03-18 00:23:29 +0000592// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
593// We do it by actually executing the units, sometimes more than once,
594// because we may be using different coverage-like signals and the only
595// common thing between them is that we can say "this unit found new stuff".
596UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
597 const UnitVector &Extra) {
598 UnitVector Res = Extra;
599 size_t OldSize = Res.size();
600 for (int Iter = 0; Iter < 10; Iter++) {
601 ShuffleCorpus(&Res);
602 ResetCoverage();
603
604 for (auto &U : Initial)
605 RunOne(U);
606
607 Corpus.clear();
608 for (auto &U : Res)
609 if (RunOne(U))
610 Corpus.push_back(U);
611
612 char Stat[7] = "MIN ";
613 Stat[3] = '0' + Iter;
614 PrintStats(Stat);
615
616 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000617 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000618 Res.swap(Corpus);
619
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000620 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000621 break;
622 OldSize = NewSize;
623 }
624 return Res;
625}
626
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000627void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
628 if (Corpora.size() <= 1) {
629 Printf("Merge requires two or more corpus dirs\n");
630 return;
631 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000632 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
633
Kostya Serebryany945761b2016-03-18 00:23:29 +0000634 assert(Options.MaxLen > 0);
635 UnitVector Initial, Extra;
636 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
637 for (auto &C : ExtraCorpora)
638 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
639
640 if (!Initial.empty()) {
641 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
642 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000643 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000644
645 Printf("=== Merging extra %zd units\n", Extra.size());
646 auto Res = FindExtraUnits(Initial, Extra);
647
648 for (auto &U: Res)
649 WriteToOutputCorpus(U);
650
651 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000652}
653
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000654// Tries detecting a memory leak on the particular input that we have just
655// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000656void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
657 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000658 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
659 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000660 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
661 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000662 return; // No lsan.
663 // Run the target once again, but with lsan disabled so that if there is
664 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000665 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000666 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000667 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000668 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000669 if (NumberOfLeakDetectionAttempts++ > 1000) {
670 Options.DetectLeaks = false;
671 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
672 " Most likely the target function accumulates allocated\n"
673 " memory in a global state w/o actually leaking it.\n"
674 " If LeakSanitizer is enabled in this process it will still\n"
675 " run on the process shutdown.\n");
676 return;
677 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000678 // Now perform the actual lsan pass. This is expensive and we must ensure
679 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000680 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000681 if (DuringInitialCorpusExecution)
682 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
683 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000684 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000685 DumpCurrentUnit("leak-");
686 PrintFinalStats();
687 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
688 }
689}
690
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000691void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000692 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000693 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000694
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000695 auto &U = ChooseUnitToMutate();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000696 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000697 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000698 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000699 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000700
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000701 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000702 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000703 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000704 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000705 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000706 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000707 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000708 if (i == 0)
709 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000710 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000711 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000712 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000713 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000714 }
715}
716
Kostya Serebryanye6926212015-11-04 23:22:25 +0000717// Returns an index of random unit from the corpus to mutate.
718// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000719// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000720size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000721 size_t Idx =
722 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000723 assert(Idx < Corpus.size());
724 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000725}
726
Kostya Serebryany945761b2016-03-18 00:23:29 +0000727void Fuzzer::ResetCoverage() {
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000728 CController->Reset();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000729 MaxCoverage.Reset();
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000730 CController->Prepare(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000731}
732
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000733// Experimental search heuristic: drilling.
734// - Read, shuffle, execute and minimize the corpus.
735// - Choose one random unit.
736// - Reset the coverage.
737// - Start fuzzing as if the chosen unit was the only element of the corpus.
738// - When done, reset the coverage again.
739// - Merge the newly created corpus into the original one.
740void Fuzzer::Drill() {
741 // The corpus is already read, shuffled, and minimized.
742 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000743 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000744
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000745 Unit U = ChooseUnitToMutate();
746
Kostya Serebryany945761b2016-03-18 00:23:29 +0000747 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000748
749 std::vector<Unit> SavedCorpus;
750 SavedCorpus.swap(Corpus);
751 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000752 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000753 assert(Corpus.size() == 1);
754 RunOne(U);
755 PrintStats("DRILL ");
756 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
757 SavedOutputCorpusPath.swap(Options.OutputCorpus);
758 Loop();
759
Kostya Serebryany945761b2016-03-18 00:23:29 +0000760 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000761
762 PrintStats("REINIT");
763 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000764 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000765 RunOne(U);
766 PrintStats("MERGE ");
767 Options.PrintNEW = true;
768 size_t NumMerged = 0;
769 for (auto &U : Corpus) {
770 if (RunOne(U)) {
771 PrintStatusForNewUnit(U);
772 NumMerged++;
773 WriteToOutputCorpus(U);
774 }
775 }
776 PrintStats("MERGED");
777 if (NumMerged && Options.Verbosity)
778 Printf("Drilling discovered %zd new units\n", NumMerged);
779}
780
781void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000782 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000783 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000784 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000785 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000786 auto Now = system_clock::now();
787 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000788 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000789 LastCorpusReload = Now;
790 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000791 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000792 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000793 if (Options.MaxTotalTimeSec > 0 &&
794 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000795 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000796 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000797 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000798 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000799 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000800
801 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000802 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000803}
804
Ivan Krasindf919102016-01-22 22:28:27 +0000805void Fuzzer::UpdateCorpusDistribution() {
806 size_t N = Corpus.size();
807 std::vector<double> Intervals(N + 1);
808 std::vector<double> Weights(N);
809 std::iota(Intervals.begin(), Intervals.end(), 0);
810 std::iota(Weights.begin(), Weights.end(), 1);
811 CorpusDistribution = std::piecewise_constant_distribution<double>(
812 Intervals.begin(), Intervals.end(), Weights.begin());
813}
814
815} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000816
817extern "C" {
818
819size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
820 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000821 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000822}
823} // extern "C"