blob: 348e7573773490632245c899ace51c6d4281fad1 [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();
Kostya Serebryany53501782016-09-15 04:36:45 +000066 TPC.GetNewPCsAndFlush();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000067}
68
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000069void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
70 if (Options.UseCounters) {
71 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
72 C->CounterBitmap.resize(NumCounters);
73 }
74}
75
76// Records data to a maximum coverage tracker. Returns true if additional
77// coverage was discovered.
78bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
79 bool Res = false;
80
Kostya Serebryanya5277d52016-09-15 01:30:18 +000081 TPC.FinalizeTrace();
82
Kostya Serebryanya00b2432016-09-14 02:13:06 +000083 uint64_t NewBlockCoverage =
84 EF->__sanitizer_get_total_unique_coverage() + TPC.GetTotalCoverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000085 if (NewBlockCoverage > C->BlockCoverage) {
86 Res = true;
87 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000088 }
89
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000090 if (Options.UseIndirCalls &&
91 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
92 uint64_t NewCallerCalleeCoverage =
93 EF->__sanitizer_get_total_unique_caller_callee_pairs();
94 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000095 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000096 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000097 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000098 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000099
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000100 if (Options.UseCounters) {
101 uint64_t CounterDelta =
102 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000103 C->CounterBitmap.data()) +
104 TPC.UpdateCounterMap(&C->TPCMap);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000105 if (CounterDelta > 0) {
106 Res = true;
107 C->CounterBitmapBits += CounterDelta;
108 }
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000109
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000110 }
111
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000112 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
113 if (NewVPMapBits > C->VPMapBits) {
114 Res = true;
115 C->VPMapBits = NewVPMapBits;
116 }
117
118 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
119 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000120 if (NewPcBufferPos > PcBufferPos) {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000121 Res = true;
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000122 PcBufferPos = NewPcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000123 }
124
125 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
126 Printf("ERROR: PC buffer overflow\n");
127 _Exit(1);
128 }
129 }
130
131 return Res;
132}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000133
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000134// Leak detection is expensive, so we first check if there were more mallocs
135// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
136struct MallocFreeTracer {
137 void Start() {
138 Mallocs = 0;
139 Frees = 0;
140 }
141 // Returns true if there were more mallocs than frees.
142 bool Stop() { return Mallocs > Frees; }
143 std::atomic<size_t> Mallocs;
144 std::atomic<size_t> Frees;
145};
146
147static MallocFreeTracer AllocTracer;
148
149void MallocHook(const volatile void *ptr, size_t size) {
150 AllocTracer.Mallocs++;
151}
152void FreeHook(const volatile void *ptr) {
153 AllocTracer.Frees++;
154}
155
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000156Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000157 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000158 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000159 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000160 assert(!F);
161 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000162 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000163 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000164 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
165 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000166 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000167
168 if (Options.PrintNewCovPcs) {
169 PcBufferLen = 1 << 24;
170 PcBuffer = new uintptr_t[PcBufferLen];
171 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
172 }
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000173 if (Options.Verbosity)
174 TPC.PrintModuleInfo();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000175}
Aaron Ballmanef116982015-01-29 16:58:29 +0000176
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000177Fuzzer::~Fuzzer() { }
178
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000179void Fuzzer::LazyAllocateCurrentUnitData() {
180 if (CurrentUnitData || Options.MaxLen == 0) return;
181 CurrentUnitData = new uint8_t[Options.MaxLen];
182}
183
Aaron Ballmanef116982015-01-29 16:58:29 +0000184void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000185 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
186 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000187}
188
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000189void Fuzzer::StaticDeathCallback() {
190 assert(F);
191 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000192}
193
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000194static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000195 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000196 Printf(
197 "***\n"
198 "***\n"
199 "***\n"
200 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
201 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
202 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
203 "*** Future versions may have crash-resistant merge, stay tuned.\n"
204 "***\n"
205 "***\n"
206 "***\n");
207}
208
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000209void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000210 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000211 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000212 MD.PrintMutationSequence();
213 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000214 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000215 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000216 PrintHexArray(CurrentUnitData, UnitSize, "\n");
217 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000218 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000219 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
220 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000221}
222
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000223NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000224void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000225 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000226 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000227}
228
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000229void Fuzzer::StaticAlarmCallback() {
230 assert(F);
231 F->AlarmCallback();
232}
233
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000234void Fuzzer::StaticCrashSignalCallback() {
235 assert(F);
236 F->CrashCallback();
237}
238
239void Fuzzer::StaticInterruptCallback() {
240 assert(F);
241 F->InterruptCallback();
242}
243
244void Fuzzer::CrashCallback() {
245 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000246 if (EF->__sanitizer_print_stack_trace)
247 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000248 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
249 " Combine libFuzzer with AddressSanitizer or similar for better "
250 "crash reports.\n");
251 Printf("SUMMARY: libFuzzer: deadly signal\n");
252 DumpCurrentUnit("crash-");
253 PrintFinalStats();
254 exit(Options.ErrorExitCode);
255}
256
257void Fuzzer::InterruptCallback() {
258 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
259 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000260 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000261}
262
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000263NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000264void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000265 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000266 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000267 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000268 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000269 size_t Seconds =
270 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000271 if (Seconds == 0)
272 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000273 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000274 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000275 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000276 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000277 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
278 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000279 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000280 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
281 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000282 if (EF->__sanitizer_print_stack_trace)
283 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000284 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000285 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000286 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000287 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000288}
289
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000290void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000291 Printf(
292 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
293 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000294 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000295 if (EF->__sanitizer_print_memory_profile)
296 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000297 DumpCurrentUnit("oom-");
298 Printf("SUMMARY: libFuzzer: out-of-memory\n");
299 PrintFinalStats();
300 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000301}
302
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000303void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000304 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000305 if (Options.OutputCSV) {
306 static bool csvHeaderPrinted = false;
307 if (!csvHeaderPrinted) {
308 csvHeaderPrinted = true;
309 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
310 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000311 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000312 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
313 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000314 }
315
316 if (!Options.Verbosity)
317 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000318 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000319 if (MaxCoverage.BlockCoverage)
320 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000321 if (MaxCoverage.VPMapBits)
322 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000323 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000324 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000325 if (MaxCoverage.CallerCalleeCoverage)
326 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000327 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000328 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000329}
330
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000331void Fuzzer::PrintFinalStats() {
332 if (!Options.PrintFinalStats) return;
333 size_t ExecPerSec = execPerSec();
334 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
335 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
336 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
337 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
338 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
339}
340
Kostya Serebryany64d24572016-03-12 01:57:04 +0000341size_t Fuzzer::MaxUnitSizeInCorpus() const {
342 size_t Res = 0;
343 for (auto &X : Corpus)
344 Res = std::max(Res, X.size());
345 return Res;
346}
347
348void Fuzzer::SetMaxLen(size_t MaxLen) {
349 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
350 assert(MaxLen);
351 Options.MaxLen = MaxLen;
352 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
353}
354
355
356void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000357 if (Options.OutputCorpus.empty())
358 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000359 std::vector<Unit> AdditionalCorpus;
360 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000361 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000362 if (Corpus.empty()) {
363 Corpus = AdditionalCorpus;
364 return;
365 }
Ivan Krasindf919102016-01-22 22:28:27 +0000366 if (!Options.Reload)
367 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000368 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000369 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000370 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000371 if (X.size() > MaxSize)
372 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000373 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000374 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000375 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000376 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000377 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000378 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000379 }
380 }
381}
382
Kostya Serebryany945761b2016-03-18 00:23:29 +0000383void Fuzzer::ShuffleCorpus(UnitVector *V) {
384 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
385 if (Options.PreferSmall)
386 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
387 return A.size() < B.size();
388 });
389}
390
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000391// Tries random prefixes of corpus items.
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000392void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000393 std::vector<double> Fractions = {0.25, 0.5, 0.75, 1.0};
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000394
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000395 size_t TruncInputs = 0;
396 for (double Fraction : Fractions) {
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000397 for (const auto &U : Corpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000398 uint64_t S = MD.GetRand()(U.size() * Fraction);
399 if (!S || !RunOne(U.data(), S))
400 continue;
401 TruncInputs++;
402 Unit U1(U.begin(), U.begin() + S);
403 NewCorpus->push_back(U1);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000404 }
405 }
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000406 if (TruncInputs)
407 Printf("\tINFO TRUNC %zd units added to in-memory corpus\n", TruncInputs);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000408}
409
Aaron Ballmanef116982015-01-29 16:58:29 +0000410void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000411 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000412 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000413 if (Options.ShuffleAtStartUp)
414 ShuffleCorpus(&Corpus);
415
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000416 if (Options.TruncateUnits) {
417 ResetCoverage();
418 TruncateUnits(&NewCorpus);
419 ResetCoverage();
420 }
421
Kostya Serebryany945761b2016-03-18 00:23:29 +0000422 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000423 bool NewCoverage = RunOne(U);
424 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000425 NewCorpus.push_back(U);
426 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000427 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000428 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000429 TryDetectingAMemoryLeak(U.data(), U.size(),
430 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000431 }
432 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000433 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000434 for (auto &X : Corpus)
435 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000436 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000437 if (Corpus.empty()) {
438 Printf("ERROR: no interesting inputs were found. "
439 "Is the code instrumented for coverage? Exiting.\n");
440 exit(1);
441 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000442}
443
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000444bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000445 PrevPcBufferPos = PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000446 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000447
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000448 return Res;
449}
450
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000451bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000452 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000453
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000454 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000455 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000456
Kostya Serebryany16901a92015-03-30 23:04:35 +0000457 auto UnitStopTime = system_clock::now();
458 auto TimeOfUnit =
459 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000460 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
461 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000462 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000463 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
464 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000465 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000466 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000467 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000468 }
469 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000470}
471
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000472void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000473 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
474 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000475 if (RunOne(Data, Size))
476 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000477}
478
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000479size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000480 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000481 *Data = CurrentUnitData;
482 return CurrentUnitSize;
483}
484
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000485void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000486 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000487 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000488 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000489 // We copy the contents of Unit into a separate heap buffer
490 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000491 uint8_t *DataCopy = new uint8_t[Size];
492 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000493 if (CurrentUnitData && CurrentUnitData != Data)
494 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000495 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000496 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000497 AllocTracer.Start();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000498 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000499 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000500 (void)Res;
501 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000502 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000503 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000504 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000505}
506
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000507std::string Fuzzer::Coverage::DebugString() const {
508 std::string Result =
509 std::string("Coverage{") + "BlockCoverage=" +
510 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
511 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanya00b2432016-09-14 02:13:06 +0000512 std::to_string(CounterBitmapBits) +
513 " VPMapBits " + std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000514 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000515}
516
517void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000518 if (Options.OnlyASCII)
519 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000520 if (Options.OutputCorpus.empty())
521 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000522 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
523 WriteToFile(U, Path);
524 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000525 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000526}
527
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000528void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000529 if (!Options.SaveArtifacts)
530 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000531 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000532 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000533 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000534 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000535 Printf("artifact_prefix='%s'; Test unit written to %s\n",
536 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000537 if (U.size() <= kMaxUnitSizeToPrint)
538 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000539}
540
541void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000542 if (Options.OutputCorpus.empty())
543 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000544 for (const auto &U : Corpus)
545 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
546 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000547 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
548 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000549}
550
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000551void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
552 if (!Options.PrintNEW)
553 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000554 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000555 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000556 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000557 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000558 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000559 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000560}
561
Kostya Serebryany53501782016-09-15 04:36:45 +0000562void Fuzzer::PrintOneNewPC(uintptr_t PC) {
563 if (EF->__sanitizer_symbolize_pc) {
564 char PcDescr[1024];
565 EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PC),
566 "%p %F %L", PcDescr, sizeof(PcDescr));
567 PcDescr[sizeof(PcDescr) - 1] = 0; // Just in case.
568 Printf("\tNEW_PC: %s\n", PcDescr);
569 } else {
570 Printf("\tNEW_PC: %p\n", PC);
571 }
572}
573
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000574void Fuzzer::PrintNewPCs() {
Kostya Serebryany53501782016-09-15 04:36:45 +0000575 if (!Options.PrintNewCovPcs) return;
576 if (PrevPcBufferPos != PcBufferPos) {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000577 int NumPrinted = 0;
578 for (size_t I = PrevPcBufferPos; I < PcBufferPos; ++I) {
579 if (NumPrinted++ > 30) break; // Don't print too many new PCs.
Kostya Serebryany53501782016-09-15 04:36:45 +0000580 PrintOneNewPC(PcBuffer[I]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000581 }
582 }
Kostya Serebryany53501782016-09-15 04:36:45 +0000583 uintptr_t *PCs;
584 if (size_t NumNewPCs = TPC.GetNewPCsAndFlush(&PCs))
585 for (size_t i = 0; i < NumNewPCs; i++)
586 PrintOneNewPC(PCs[i]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000587}
588
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000589void Fuzzer::ReportNewCoverage(const Unit &U) {
590 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000591 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000592 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000593 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000594 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000595 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000596 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000597 PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000598}
599
Kostya Serebryany945761b2016-03-18 00:23:29 +0000600// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
601// We do it by actually executing the units, sometimes more than once,
602// because we may be using different coverage-like signals and the only
603// common thing between them is that we can say "this unit found new stuff".
604UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
605 const UnitVector &Extra) {
606 UnitVector Res = Extra;
607 size_t OldSize = Res.size();
608 for (int Iter = 0; Iter < 10; Iter++) {
609 ShuffleCorpus(&Res);
610 ResetCoverage();
611
612 for (auto &U : Initial)
613 RunOne(U);
614
615 Corpus.clear();
616 for (auto &U : Res)
617 if (RunOne(U))
618 Corpus.push_back(U);
619
620 char Stat[7] = "MIN ";
621 Stat[3] = '0' + Iter;
622 PrintStats(Stat);
623
624 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000625 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000626 Res.swap(Corpus);
627
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000628 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000629 break;
630 OldSize = NewSize;
631 }
632 return Res;
633}
634
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000635void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
636 if (Corpora.size() <= 1) {
637 Printf("Merge requires two or more corpus dirs\n");
638 return;
639 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000640 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000641 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
642
Kostya Serebryany945761b2016-03-18 00:23:29 +0000643 assert(Options.MaxLen > 0);
644 UnitVector Initial, Extra;
645 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
646 for (auto &C : ExtraCorpora)
647 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
648
649 if (!Initial.empty()) {
650 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
651 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000652 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000653
654 Printf("=== Merging extra %zd units\n", Extra.size());
655 auto Res = FindExtraUnits(Initial, Extra);
656
657 for (auto &U: Res)
658 WriteToOutputCorpus(U);
659
660 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000661}
662
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000663// Tries detecting a memory leak on the particular input that we have just
664// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000665void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
666 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000667 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
668 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000669 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
670 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000671 return; // No lsan.
672 // Run the target once again, but with lsan disabled so that if there is
673 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000674 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000675 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000676 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000677 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000678 if (NumberOfLeakDetectionAttempts++ > 1000) {
679 Options.DetectLeaks = false;
680 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
681 " Most likely the target function accumulates allocated\n"
682 " memory in a global state w/o actually leaking it.\n"
683 " If LeakSanitizer is enabled in this process it will still\n"
684 " run on the process shutdown.\n");
685 return;
686 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000687 // Now perform the actual lsan pass. This is expensive and we must ensure
688 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000689 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000690 if (DuringInitialCorpusExecution)
691 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
692 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000693 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000694 DumpCurrentUnit("leak-");
695 PrintFinalStats();
696 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
697 }
698}
699
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000700void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000701 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000702 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000703
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000704 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000705 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000706 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000707 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000708 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000709 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000710
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000711 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000712 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000713 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000714 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000715 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000716 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000717 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000718 if (i == 0)
719 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000720 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000721 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000722 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000723 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000724 }
725}
726
Kostya Serebryanye6926212015-11-04 23:22:25 +0000727// Returns an index of random unit from the corpus to mutate.
728// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000729// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000730size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000731 size_t Idx =
732 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000733 assert(Idx < Corpus.size());
734 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000735}
736
Kostya Serebryany945761b2016-03-18 00:23:29 +0000737void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000738 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000739 MaxCoverage.Reset();
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000740 TPC.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000741 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000742}
743
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000744// Experimental search heuristic: drilling.
745// - Read, shuffle, execute and minimize the corpus.
746// - Choose one random unit.
747// - Reset the coverage.
748// - Start fuzzing as if the chosen unit was the only element of the corpus.
749// - When done, reset the coverage again.
750// - Merge the newly created corpus into the original one.
751void Fuzzer::Drill() {
752 // The corpus is already read, shuffled, and minimized.
753 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000754 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000755
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000756 Unit U = ChooseUnitToMutate();
757
Kostya Serebryany945761b2016-03-18 00:23:29 +0000758 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000759
760 std::vector<Unit> SavedCorpus;
761 SavedCorpus.swap(Corpus);
762 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000763 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000764 assert(Corpus.size() == 1);
765 RunOne(U);
766 PrintStats("DRILL ");
767 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
768 SavedOutputCorpusPath.swap(Options.OutputCorpus);
769 Loop();
770
Kostya Serebryany945761b2016-03-18 00:23:29 +0000771 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000772
773 PrintStats("REINIT");
774 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000775 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000776 RunOne(U);
777 PrintStats("MERGE ");
778 Options.PrintNEW = true;
779 size_t NumMerged = 0;
780 for (auto &U : Corpus) {
781 if (RunOne(U)) {
782 PrintStatusForNewUnit(U);
783 NumMerged++;
784 WriteToOutputCorpus(U);
785 }
786 }
787 PrintStats("MERGED");
788 if (NumMerged && Options.Verbosity)
789 Printf("Drilling discovered %zd new units\n", NumMerged);
790}
791
792void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000793 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000794 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000795 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000796 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000797 auto Now = system_clock::now();
798 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000799 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000800 LastCorpusReload = Now;
801 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000802 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000803 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000804 if (Options.MaxTotalTimeSec > 0 &&
805 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000806 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000807 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000808 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000809 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000810 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000811
812 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000813 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000814}
815
Ivan Krasindf919102016-01-22 22:28:27 +0000816void Fuzzer::UpdateCorpusDistribution() {
817 size_t N = Corpus.size();
818 std::vector<double> Intervals(N + 1);
819 std::vector<double> Weights(N);
820 std::iota(Intervals.begin(), Intervals.end(), 0);
821 std::iota(Weights.begin(), Weights.end(), 1);
822 CorpusDistribution = std::piecewise_constant_distribution<double>(
823 Intervals.begin(), Intervals.end(), Weights.begin());
824}
825
826} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000827
828extern "C" {
829
830size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
831 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000832 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000833}
834} // extern "C"