blob: 54e748fb796fcb02c5fa7e29cfa500ca6b7c3a32 [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;
Aaron Ballmanef116982015-01-29 16:58:29 +000036
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000037thread_local bool Fuzzer::IsMyThread;
38
Dan Liew1873a492016-06-07 23:32:50 +000039static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000040 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000041 "Did you use -fsanitize-coverage=... to build your code?\n",
42 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000043 exit(1);
44}
45
Dan Liew1873a492016-06-07 23:32:50 +000046#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000047 do { \
Dan Liew1873a492016-06-07 23:32:50 +000048 if (!(EF->fn)) \
49 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000050 } while (false)
51
Kostya Serebryany52a788e2015-03-31 20:13:20 +000052// Only one Fuzzer per process.
53static Fuzzer *F;
54
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000055void Fuzzer::ResetEdgeCoverage() {
56 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
57 EF->__sanitizer_reset_coverage();
58}
59
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000060void Fuzzer::ResetCounters() {
61 if (Options.UseCounters) {
62 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
63 }
64 if (EF->__sanitizer_get_coverage_pc_buffer_pos)
65 PcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
66}
67
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000068void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
69 if (Options.UseCounters) {
70 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
71 C->CounterBitmap.resize(NumCounters);
72 }
73}
74
75// Records data to a maximum coverage tracker. Returns true if additional
76// coverage was discovered.
77bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
78 bool Res = false;
79
Kostya Serebryanya5277d52016-09-15 01:30:18 +000080 TPC.FinalizeTrace();
81
Kostya Serebryanya00b2432016-09-14 02:13:06 +000082 uint64_t NewBlockCoverage =
83 EF->__sanitizer_get_total_unique_coverage() + TPC.GetTotalCoverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000084 if (NewBlockCoverage > C->BlockCoverage) {
85 Res = true;
86 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000087 }
88
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000089 if (Options.UseIndirCalls &&
90 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
91 uint64_t NewCallerCalleeCoverage =
92 EF->__sanitizer_get_total_unique_caller_callee_pairs();
93 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000094 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000095 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000096 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000097 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000098
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000099 if (Options.UseCounters) {
100 uint64_t CounterDelta =
101 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000102 C->CounterBitmap.data()) +
103 TPC.UpdateCounterMap(&C->TPCMap);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000104 if (CounterDelta > 0) {
105 Res = true;
106 C->CounterBitmapBits += CounterDelta;
107 }
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000108
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000109 }
110
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000111 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
112 if (NewVPMapBits > C->VPMapBits) {
113 Res = true;
114 C->VPMapBits = NewVPMapBits;
115 }
116
117 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
118 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000119 if (NewPcBufferPos > PcBufferPos) {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000120 Res = true;
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000121 PcBufferPos = NewPcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000122 }
123
124 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
125 Printf("ERROR: PC buffer overflow\n");
126 _Exit(1);
127 }
128 }
129
130 return Res;
131}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000132
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000133// Leak detection is expensive, so we first check if there were more mallocs
134// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
135struct MallocFreeTracer {
136 void Start() {
137 Mallocs = 0;
138 Frees = 0;
139 }
140 // Returns true if there were more mallocs than frees.
141 bool Stop() { return Mallocs > Frees; }
142 std::atomic<size_t> Mallocs;
143 std::atomic<size_t> Frees;
144};
145
146static MallocFreeTracer AllocTracer;
147
148void MallocHook(const volatile void *ptr, size_t size) {
149 AllocTracer.Mallocs++;
150}
151void FreeHook(const volatile void *ptr) {
152 AllocTracer.Frees++;
153}
154
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000155Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000156 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000157 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000158 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000159 assert(!F);
160 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000161 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000162 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000163 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
164 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000165 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000166
167 if (Options.PrintNewCovPcs) {
168 PcBufferLen = 1 << 24;
169 PcBuffer = new uintptr_t[PcBufferLen];
170 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
171 }
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000172}
Aaron Ballmanef116982015-01-29 16:58:29 +0000173
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000174Fuzzer::~Fuzzer() { }
175
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000176void Fuzzer::LazyAllocateCurrentUnitData() {
177 if (CurrentUnitData || Options.MaxLen == 0) return;
178 CurrentUnitData = new uint8_t[Options.MaxLen];
179}
180
Aaron Ballmanef116982015-01-29 16:58:29 +0000181void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000182 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
183 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000184}
185
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000186void Fuzzer::StaticDeathCallback() {
187 assert(F);
188 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000189}
190
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000191static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000192 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000193 Printf(
194 "***\n"
195 "***\n"
196 "***\n"
197 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
198 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
199 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
200 "*** Future versions may have crash-resistant merge, stay tuned.\n"
201 "***\n"
202 "***\n"
203 "***\n");
204}
205
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000206void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000207 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000208 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000209 MD.PrintMutationSequence();
210 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000211 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000212 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000213 PrintHexArray(CurrentUnitData, UnitSize, "\n");
214 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000215 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000216 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
217 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000218}
219
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000220NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000221void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000222 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000223 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000224}
225
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000226void Fuzzer::StaticAlarmCallback() {
227 assert(F);
228 F->AlarmCallback();
229}
230
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000231void Fuzzer::StaticCrashSignalCallback() {
232 assert(F);
233 F->CrashCallback();
234}
235
236void Fuzzer::StaticInterruptCallback() {
237 assert(F);
238 F->InterruptCallback();
239}
240
241void Fuzzer::CrashCallback() {
242 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000243 if (EF->__sanitizer_print_stack_trace)
244 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000245 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
246 " Combine libFuzzer with AddressSanitizer or similar for better "
247 "crash reports.\n");
248 Printf("SUMMARY: libFuzzer: deadly signal\n");
249 DumpCurrentUnit("crash-");
250 PrintFinalStats();
251 exit(Options.ErrorExitCode);
252}
253
254void Fuzzer::InterruptCallback() {
255 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
256 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000257 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000258}
259
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000260NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000261void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000262 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000263 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000264 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000265 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000266 size_t Seconds =
267 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000268 if (Seconds == 0)
269 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000270 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000271 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000272 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000273 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000274 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
275 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000276 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000277 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
278 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000279 if (EF->__sanitizer_print_stack_trace)
280 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000281 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000282 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000283 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000284 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000285}
286
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000287void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000288 Printf(
289 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
290 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000291 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000292 if (EF->__sanitizer_print_memory_profile)
293 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000294 DumpCurrentUnit("oom-");
295 Printf("SUMMARY: libFuzzer: out-of-memory\n");
296 PrintFinalStats();
297 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000298}
299
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000300void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000301 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000302 if (Options.OutputCSV) {
303 static bool csvHeaderPrinted = false;
304 if (!csvHeaderPrinted) {
305 csvHeaderPrinted = true;
306 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
307 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000308 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000309 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
310 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000311 }
312
313 if (!Options.Verbosity)
314 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000315 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000316 if (MaxCoverage.BlockCoverage)
317 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000318 if (MaxCoverage.VPMapBits)
319 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000320 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000321 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000322 if (MaxCoverage.CallerCalleeCoverage)
323 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000324 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000325 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000326}
327
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000328void Fuzzer::PrintFinalStats() {
329 if (!Options.PrintFinalStats) return;
330 size_t ExecPerSec = execPerSec();
331 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
332 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
333 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
334 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
335 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
336}
337
Kostya Serebryany64d24572016-03-12 01:57:04 +0000338size_t Fuzzer::MaxUnitSizeInCorpus() const {
339 size_t Res = 0;
340 for (auto &X : Corpus)
341 Res = std::max(Res, X.size());
342 return Res;
343}
344
345void Fuzzer::SetMaxLen(size_t MaxLen) {
346 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
347 assert(MaxLen);
348 Options.MaxLen = MaxLen;
349 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
350}
351
352
353void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000354 if (Options.OutputCorpus.empty())
355 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000356 std::vector<Unit> AdditionalCorpus;
357 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000358 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000359 if (Corpus.empty()) {
360 Corpus = AdditionalCorpus;
361 return;
362 }
Ivan Krasindf919102016-01-22 22:28:27 +0000363 if (!Options.Reload)
364 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000365 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000366 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000367 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000368 if (X.size() > MaxSize)
369 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000370 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000371 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000372 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000373 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000374 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000375 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000376 }
377 }
378}
379
Kostya Serebryany945761b2016-03-18 00:23:29 +0000380void Fuzzer::ShuffleCorpus(UnitVector *V) {
381 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
382 if (Options.PreferSmall)
383 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
384 return A.size() < B.size();
385 });
386}
387
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000388// Tries random prefixes of corpus items.
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000389void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000390 std::vector<double> Fractions = {0.25, 0.5, 0.75, 1.0};
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000391
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000392 size_t TruncInputs = 0;
393 for (double Fraction : Fractions) {
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000394 for (const auto &U : Corpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000395 uint64_t S = MD.GetRand()(U.size() * Fraction);
396 if (!S || !RunOne(U.data(), S))
397 continue;
398 TruncInputs++;
399 Unit U1(U.begin(), U.begin() + S);
400 NewCorpus->push_back(U1);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000401 }
402 }
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000403 if (TruncInputs)
404 Printf("\tINFO TRUNC %zd units added to in-memory corpus\n", TruncInputs);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000405}
406
Aaron Ballmanef116982015-01-29 16:58:29 +0000407void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000408 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000409 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000410 if (Options.ShuffleAtStartUp)
411 ShuffleCorpus(&Corpus);
412
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000413 if (Options.TruncateUnits) {
414 ResetCoverage();
415 TruncateUnits(&NewCorpus);
416 ResetCoverage();
417 }
418
Kostya Serebryany945761b2016-03-18 00:23:29 +0000419 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000420 bool NewCoverage = RunOne(U);
421 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000422 NewCorpus.push_back(U);
423 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000424 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000425 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000426 TryDetectingAMemoryLeak(U.data(), U.size(),
427 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000428 }
429 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000430 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000431 for (auto &X : Corpus)
432 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000433 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000434 if (Corpus.empty()) {
435 Printf("ERROR: no interesting inputs were found. "
436 "Is the code instrumented for coverage? Exiting.\n");
437 exit(1);
438 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000439}
440
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000441bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000442 PrevPcBufferPos = PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000443 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000444
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000445 return Res;
446}
447
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000448bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000449 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000450
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000451 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000452 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000453
Kostya Serebryany16901a92015-03-30 23:04:35 +0000454 auto UnitStopTime = system_clock::now();
455 auto TimeOfUnit =
456 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000457 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
458 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000459 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000460 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
461 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000462 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000463 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000464 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000465 }
466 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000467}
468
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000469void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000470 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
471 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000472 if (RunOne(Data, Size))
473 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000474}
475
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000476size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000477 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000478 *Data = CurrentUnitData;
479 return CurrentUnitSize;
480}
481
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000482void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000483 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000484 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000485 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000486 // We copy the contents of Unit into a separate heap buffer
487 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000488 uint8_t *DataCopy = new uint8_t[Size];
489 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000490 if (CurrentUnitData && CurrentUnitData != Data)
491 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000492 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000493 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000494 AllocTracer.Start();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000495 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000496 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000497 (void)Res;
498 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000499 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000500 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000501 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000502}
503
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000504std::string Fuzzer::Coverage::DebugString() const {
505 std::string Result =
506 std::string("Coverage{") + "BlockCoverage=" +
507 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
508 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanya00b2432016-09-14 02:13:06 +0000509 std::to_string(CounterBitmapBits) +
510 " VPMapBits " + std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000511 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000512}
513
514void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000515 if (Options.OnlyASCII)
516 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000517 if (Options.OutputCorpus.empty())
518 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000519 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
520 WriteToFile(U, Path);
521 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000522 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000523}
524
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000525void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000526 if (!Options.SaveArtifacts)
527 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000528 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000529 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000530 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000531 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000532 Printf("artifact_prefix='%s'; Test unit written to %s\n",
533 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000534 if (U.size() <= kMaxUnitSizeToPrint)
535 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000536}
537
538void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000539 if (Options.OutputCorpus.empty())
540 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000541 for (const auto &U : Corpus)
542 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
543 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000544 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
545 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000546}
547
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000548void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
549 if (!Options.PrintNEW)
550 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000551 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000552 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000553 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000554 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000555 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000556 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000557}
558
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000559void Fuzzer::PrintNewPCs() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000560 if (Options.PrintNewCovPcs && PrevPcBufferPos != PcBufferPos) {
561 int NumPrinted = 0;
562 for (size_t I = PrevPcBufferPos; I < PcBufferPos; ++I) {
563 if (NumPrinted++ > 30) break; // Don't print too many new PCs.
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000564 if (EF->__sanitizer_symbolize_pc) {
565 char PcDescr[1024];
566 EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PcBuffer[I]),
567 "%p %F %L", PcDescr, sizeof(PcDescr));
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000568 PcDescr[sizeof(PcDescr) - 1] = 0; // Just in case.
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000569 Printf("\tNEW_PC: %s\n", PcDescr);
570 } else {
571 Printf("\tNEW_PC: %p\n", PcBuffer[I]);
572 }
573 }
574 }
575}
576
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000577void Fuzzer::ReportNewCoverage(const Unit &U) {
578 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000579 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000580 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000581 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000582 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000583 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000584 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000585 PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000586}
587
Kostya Serebryany945761b2016-03-18 00:23:29 +0000588// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
589// We do it by actually executing the units, sometimes more than once,
590// because we may be using different coverage-like signals and the only
591// common thing between them is that we can say "this unit found new stuff".
592UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
593 const UnitVector &Extra) {
594 UnitVector Res = Extra;
595 size_t OldSize = Res.size();
596 for (int Iter = 0; Iter < 10; Iter++) {
597 ShuffleCorpus(&Res);
598 ResetCoverage();
599
600 for (auto &U : Initial)
601 RunOne(U);
602
603 Corpus.clear();
604 for (auto &U : Res)
605 if (RunOne(U))
606 Corpus.push_back(U);
607
608 char Stat[7] = "MIN ";
609 Stat[3] = '0' + Iter;
610 PrintStats(Stat);
611
612 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000613 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000614 Res.swap(Corpus);
615
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000616 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000617 break;
618 OldSize = NewSize;
619 }
620 return Res;
621}
622
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000623void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
624 if (Corpora.size() <= 1) {
625 Printf("Merge requires two or more corpus dirs\n");
626 return;
627 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000628 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000629 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
630
Kostya Serebryany945761b2016-03-18 00:23:29 +0000631 assert(Options.MaxLen > 0);
632 UnitVector Initial, Extra;
633 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
634 for (auto &C : ExtraCorpora)
635 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
636
637 if (!Initial.empty()) {
638 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
639 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000640 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000641
642 Printf("=== Merging extra %zd units\n", Extra.size());
643 auto Res = FindExtraUnits(Initial, Extra);
644
645 for (auto &U: Res)
646 WriteToOutputCorpus(U);
647
648 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000649}
650
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000651// Tries detecting a memory leak on the particular input that we have just
652// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000653void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
654 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000655 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
656 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000657 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
658 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000659 return; // No lsan.
660 // Run the target once again, but with lsan disabled so that if there is
661 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000662 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000663 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000664 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000665 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000666 if (NumberOfLeakDetectionAttempts++ > 1000) {
667 Options.DetectLeaks = false;
668 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
669 " Most likely the target function accumulates allocated\n"
670 " memory in a global state w/o actually leaking it.\n"
671 " If LeakSanitizer is enabled in this process it will still\n"
672 " run on the process shutdown.\n");
673 return;
674 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000675 // Now perform the actual lsan pass. This is expensive and we must ensure
676 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000677 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000678 if (DuringInitialCorpusExecution)
679 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
680 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000681 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000682 DumpCurrentUnit("leak-");
683 PrintFinalStats();
684 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
685 }
686}
687
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000688void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000689 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000690 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000691
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000692 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000693 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000694 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000695 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000696 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000697 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000698
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000699 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000700 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000701 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000702 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000703 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000704 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000705 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000706 if (i == 0)
707 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000708 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000709 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000710 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000711 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000712 }
713}
714
Kostya Serebryanye6926212015-11-04 23:22:25 +0000715// Returns an index of random unit from the corpus to mutate.
716// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000717// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000718size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000719 size_t Idx =
720 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000721 assert(Idx < Corpus.size());
722 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000723}
724
Kostya Serebryany945761b2016-03-18 00:23:29 +0000725void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000726 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000727 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000728 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000729}
730
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000731// Experimental search heuristic: drilling.
732// - Read, shuffle, execute and minimize the corpus.
733// - Choose one random unit.
734// - Reset the coverage.
735// - Start fuzzing as if the chosen unit was the only element of the corpus.
736// - When done, reset the coverage again.
737// - Merge the newly created corpus into the original one.
738void Fuzzer::Drill() {
739 // The corpus is already read, shuffled, and minimized.
740 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000741 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000742
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000743 Unit U = ChooseUnitToMutate();
744
Kostya Serebryany945761b2016-03-18 00:23:29 +0000745 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000746
747 std::vector<Unit> SavedCorpus;
748 SavedCorpus.swap(Corpus);
749 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000750 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000751 assert(Corpus.size() == 1);
752 RunOne(U);
753 PrintStats("DRILL ");
754 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
755 SavedOutputCorpusPath.swap(Options.OutputCorpus);
756 Loop();
757
Kostya Serebryany945761b2016-03-18 00:23:29 +0000758 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000759
760 PrintStats("REINIT");
761 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000762 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000763 RunOne(U);
764 PrintStats("MERGE ");
765 Options.PrintNEW = true;
766 size_t NumMerged = 0;
767 for (auto &U : Corpus) {
768 if (RunOne(U)) {
769 PrintStatusForNewUnit(U);
770 NumMerged++;
771 WriteToOutputCorpus(U);
772 }
773 }
774 PrintStats("MERGED");
775 if (NumMerged && Options.Verbosity)
776 Printf("Drilling discovered %zd new units\n", NumMerged);
777}
778
779void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000780 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000781 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000782 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000783 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000784 auto Now = system_clock::now();
785 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000786 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000787 LastCorpusReload = Now;
788 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000789 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000790 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000791 if (Options.MaxTotalTimeSec > 0 &&
792 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000793 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000794 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000795 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000796 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000797 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000798
799 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000800 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000801}
802
Ivan Krasindf919102016-01-22 22:28:27 +0000803void Fuzzer::UpdateCorpusDistribution() {
804 size_t N = Corpus.size();
805 std::vector<double> Intervals(N + 1);
806 std::vector<double> Weights(N);
807 std::iota(Intervals.begin(), Intervals.end(), 0);
808 std::iota(Weights.begin(), Weights.end(), 1);
809 CorpusDistribution = std::piecewise_constant_distribution<double>(
810 Intervals.begin(), Intervals.end(), Weights.begin());
811}
812
813} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000814
815extern "C" {
816
817size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
818 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000819 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000820}
821} // extern "C"