blob: 7cb1d4906a513076dadbe5a526ddffd9b5c037f3 [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 Serebryany52a788e2015-03-31 20:13:20 +0000173}
Aaron Ballmanef116982015-01-29 16:58:29 +0000174
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000175Fuzzer::~Fuzzer() { }
176
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000177void Fuzzer::LazyAllocateCurrentUnitData() {
178 if (CurrentUnitData || Options.MaxLen == 0) return;
179 CurrentUnitData = new uint8_t[Options.MaxLen];
180}
181
Aaron Ballmanef116982015-01-29 16:58:29 +0000182void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000183 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
184 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000185}
186
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000187void Fuzzer::StaticDeathCallback() {
188 assert(F);
189 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000190}
191
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000192static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000193 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000194 Printf(
195 "***\n"
196 "***\n"
197 "***\n"
198 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
199 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
200 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
201 "*** Future versions may have crash-resistant merge, stay tuned.\n"
202 "***\n"
203 "***\n"
204 "***\n");
205}
206
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000207void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000208 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000209 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000210 MD.PrintMutationSequence();
211 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000212 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000213 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000214 PrintHexArray(CurrentUnitData, UnitSize, "\n");
215 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000216 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000217 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
218 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000219}
220
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000221NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000222void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000223 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000224 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000225}
226
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000227void Fuzzer::StaticAlarmCallback() {
228 assert(F);
229 F->AlarmCallback();
230}
231
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000232void Fuzzer::StaticCrashSignalCallback() {
233 assert(F);
234 F->CrashCallback();
235}
236
237void Fuzzer::StaticInterruptCallback() {
238 assert(F);
239 F->InterruptCallback();
240}
241
242void Fuzzer::CrashCallback() {
243 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000244 if (EF->__sanitizer_print_stack_trace)
245 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000246 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
247 " Combine libFuzzer with AddressSanitizer or similar for better "
248 "crash reports.\n");
249 Printf("SUMMARY: libFuzzer: deadly signal\n");
250 DumpCurrentUnit("crash-");
251 PrintFinalStats();
252 exit(Options.ErrorExitCode);
253}
254
255void Fuzzer::InterruptCallback() {
256 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
257 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000258 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000259}
260
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000261NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000262void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000263 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000264 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000265 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000266 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000267 size_t Seconds =
268 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000269 if (Seconds == 0)
270 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000271 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000272 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000273 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000274 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000275 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
276 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000277 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000278 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
279 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000280 if (EF->__sanitizer_print_stack_trace)
281 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000282 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000283 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000284 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000285 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000286}
287
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000288void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000289 Printf(
290 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
291 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000292 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000293 if (EF->__sanitizer_print_memory_profile)
294 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000295 DumpCurrentUnit("oom-");
296 Printf("SUMMARY: libFuzzer: out-of-memory\n");
297 PrintFinalStats();
298 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000299}
300
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000301void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000302 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000303 if (Options.OutputCSV) {
304 static bool csvHeaderPrinted = false;
305 if (!csvHeaderPrinted) {
306 csvHeaderPrinted = true;
307 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
308 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000309 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000310 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
311 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000312 }
313
314 if (!Options.Verbosity)
315 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000316 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000317 if (MaxCoverage.BlockCoverage)
318 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000319 if (MaxCoverage.VPMapBits)
320 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000321 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000322 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000323 if (MaxCoverage.CallerCalleeCoverage)
324 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000325 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000326 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000327}
328
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000329void Fuzzer::PrintFinalStats() {
330 if (!Options.PrintFinalStats) return;
331 size_t ExecPerSec = execPerSec();
332 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
333 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
334 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
335 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
336 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
337}
338
Kostya Serebryany64d24572016-03-12 01:57:04 +0000339size_t Fuzzer::MaxUnitSizeInCorpus() const {
340 size_t Res = 0;
341 for (auto &X : Corpus)
342 Res = std::max(Res, X.size());
343 return Res;
344}
345
346void Fuzzer::SetMaxLen(size_t MaxLen) {
347 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
348 assert(MaxLen);
349 Options.MaxLen = MaxLen;
350 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
351}
352
353
354void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000355 if (Options.OutputCorpus.empty())
356 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000357 std::vector<Unit> AdditionalCorpus;
358 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000359 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000360 if (Corpus.empty()) {
361 Corpus = AdditionalCorpus;
362 return;
363 }
Ivan Krasindf919102016-01-22 22:28:27 +0000364 if (!Options.Reload)
365 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000366 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000367 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000368 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000369 if (X.size() > MaxSize)
370 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000371 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000372 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000373 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000374 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000375 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000376 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000377 }
378 }
379}
380
Kostya Serebryany945761b2016-03-18 00:23:29 +0000381void Fuzzer::ShuffleCorpus(UnitVector *V) {
382 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
383 if (Options.PreferSmall)
384 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
385 return A.size() < B.size();
386 });
387}
388
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000389// Tries random prefixes of corpus items.
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000390void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000391 std::vector<double> Fractions = {0.25, 0.5, 0.75, 1.0};
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000392
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000393 size_t TruncInputs = 0;
394 for (double Fraction : Fractions) {
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000395 for (const auto &U : Corpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000396 uint64_t S = MD.GetRand()(U.size() * Fraction);
397 if (!S || !RunOne(U.data(), S))
398 continue;
399 TruncInputs++;
400 Unit U1(U.begin(), U.begin() + S);
401 NewCorpus->push_back(U1);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000402 }
403 }
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000404 if (TruncInputs)
405 Printf("\tINFO TRUNC %zd units added to in-memory corpus\n", TruncInputs);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000406}
407
Aaron Ballmanef116982015-01-29 16:58:29 +0000408void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000409 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000410 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000411 if (Options.ShuffleAtStartUp)
412 ShuffleCorpus(&Corpus);
413
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000414 if (Options.TruncateUnits) {
415 ResetCoverage();
416 TruncateUnits(&NewCorpus);
417 ResetCoverage();
418 }
419
Kostya Serebryany945761b2016-03-18 00:23:29 +0000420 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000421 bool NewCoverage = RunOne(U);
422 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000423 NewCorpus.push_back(U);
424 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000425 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000426 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000427 TryDetectingAMemoryLeak(U.data(), U.size(),
428 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000429 }
430 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000431 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000432 for (auto &X : Corpus)
433 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000434 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000435 if (Corpus.empty()) {
436 Printf("ERROR: no interesting inputs were found. "
437 "Is the code instrumented for coverage? Exiting.\n");
438 exit(1);
439 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000440}
441
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000442bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000443 PrevPcBufferPos = PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000444 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000445
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000446 return Res;
447}
448
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000449bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000450 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000451
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000452 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000453 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000454
Kostya Serebryany16901a92015-03-30 23:04:35 +0000455 auto UnitStopTime = system_clock::now();
456 auto TimeOfUnit =
457 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000458 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
459 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000460 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000461 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
462 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000463 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000464 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000465 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000466 }
467 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000468}
469
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000470void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000471 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
472 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000473 if (RunOne(Data, Size))
474 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000475}
476
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000477size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000478 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000479 *Data = CurrentUnitData;
480 return CurrentUnitSize;
481}
482
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000483void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000484 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000485 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000486 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000487 // We copy the contents of Unit into a separate heap buffer
488 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000489 uint8_t *DataCopy = new uint8_t[Size];
490 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000491 if (CurrentUnitData && CurrentUnitData != Data)
492 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000493 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000494 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000495 AllocTracer.Start();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000496 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000497 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000498 (void)Res;
499 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000500 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000501 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000502 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000503}
504
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000505std::string Fuzzer::Coverage::DebugString() const {
506 std::string Result =
507 std::string("Coverage{") + "BlockCoverage=" +
508 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
509 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanya00b2432016-09-14 02:13:06 +0000510 std::to_string(CounterBitmapBits) +
511 " VPMapBits " + std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000512 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000513}
514
515void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000516 if (Options.OnlyASCII)
517 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000518 if (Options.OutputCorpus.empty())
519 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000520 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
521 WriteToFile(U, Path);
522 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000523 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000524}
525
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000526void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000527 if (!Options.SaveArtifacts)
528 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000529 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000530 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000531 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000532 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000533 Printf("artifact_prefix='%s'; Test unit written to %s\n",
534 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000535 if (U.size() <= kMaxUnitSizeToPrint)
536 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000537}
538
539void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000540 if (Options.OutputCorpus.empty())
541 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000542 for (const auto &U : Corpus)
543 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
544 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000545 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
546 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000547}
548
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000549void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
550 if (!Options.PrintNEW)
551 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000552 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000553 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000554 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000555 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000556 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000557 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000558}
559
Kostya Serebryany53501782016-09-15 04:36:45 +0000560void Fuzzer::PrintOneNewPC(uintptr_t PC) {
561 if (EF->__sanitizer_symbolize_pc) {
562 char PcDescr[1024];
563 EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PC),
564 "%p %F %L", PcDescr, sizeof(PcDescr));
565 PcDescr[sizeof(PcDescr) - 1] = 0; // Just in case.
566 Printf("\tNEW_PC: %s\n", PcDescr);
567 } else {
568 Printf("\tNEW_PC: %p\n", PC);
569 }
570}
571
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000572void Fuzzer::PrintNewPCs() {
Kostya Serebryany53501782016-09-15 04:36:45 +0000573 if (!Options.PrintNewCovPcs) return;
574 if (PrevPcBufferPos != PcBufferPos) {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000575 int NumPrinted = 0;
576 for (size_t I = PrevPcBufferPos; I < PcBufferPos; ++I) {
577 if (NumPrinted++ > 30) break; // Don't print too many new PCs.
Kostya Serebryany53501782016-09-15 04:36:45 +0000578 PrintOneNewPC(PcBuffer[I]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000579 }
580 }
Kostya Serebryany53501782016-09-15 04:36:45 +0000581 uintptr_t *PCs;
582 if (size_t NumNewPCs = TPC.GetNewPCsAndFlush(&PCs))
583 for (size_t i = 0; i < NumNewPCs; i++)
584 PrintOneNewPC(PCs[i]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000585}
586
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000587void Fuzzer::ReportNewCoverage(const Unit &U) {
588 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000589 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000590 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000591 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000592 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000593 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000594 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000595 PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000596}
597
Kostya Serebryany945761b2016-03-18 00:23:29 +0000598// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
599// We do it by actually executing the units, sometimes more than once,
600// because we may be using different coverage-like signals and the only
601// common thing between them is that we can say "this unit found new stuff".
602UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
603 const UnitVector &Extra) {
604 UnitVector Res = Extra;
605 size_t OldSize = Res.size();
606 for (int Iter = 0; Iter < 10; Iter++) {
607 ShuffleCorpus(&Res);
608 ResetCoverage();
609
610 for (auto &U : Initial)
611 RunOne(U);
612
613 Corpus.clear();
614 for (auto &U : Res)
615 if (RunOne(U))
616 Corpus.push_back(U);
617
618 char Stat[7] = "MIN ";
619 Stat[3] = '0' + Iter;
620 PrintStats(Stat);
621
622 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000623 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000624 Res.swap(Corpus);
625
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000626 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000627 break;
628 OldSize = NewSize;
629 }
630 return Res;
631}
632
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000633void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
634 if (Corpora.size() <= 1) {
635 Printf("Merge requires two or more corpus dirs\n");
636 return;
637 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000638 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000639 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
640
Kostya Serebryany945761b2016-03-18 00:23:29 +0000641 assert(Options.MaxLen > 0);
642 UnitVector Initial, Extra;
643 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
644 for (auto &C : ExtraCorpora)
645 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
646
647 if (!Initial.empty()) {
648 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
649 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000650 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000651
652 Printf("=== Merging extra %zd units\n", Extra.size());
653 auto Res = FindExtraUnits(Initial, Extra);
654
655 for (auto &U: Res)
656 WriteToOutputCorpus(U);
657
658 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000659}
660
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000661// Tries detecting a memory leak on the particular input that we have just
662// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000663void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
664 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000665 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
666 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000667 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
668 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000669 return; // No lsan.
670 // Run the target once again, but with lsan disabled so that if there is
671 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000672 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000673 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000674 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000675 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000676 if (NumberOfLeakDetectionAttempts++ > 1000) {
677 Options.DetectLeaks = false;
678 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
679 " Most likely the target function accumulates allocated\n"
680 " memory in a global state w/o actually leaking it.\n"
681 " If LeakSanitizer is enabled in this process it will still\n"
682 " run on the process shutdown.\n");
683 return;
684 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000685 // Now perform the actual lsan pass. This is expensive and we must ensure
686 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000687 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000688 if (DuringInitialCorpusExecution)
689 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
690 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000691 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000692 DumpCurrentUnit("leak-");
693 PrintFinalStats();
694 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
695 }
696}
697
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000698void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000699 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000700 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000701
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000702 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000703 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000704 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000705 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000706 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000707 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000708
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000709 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000710 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000711 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000712 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000713 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000714 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000715 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000716 if (i == 0)
717 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000718 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000719 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000720 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000721 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000722 }
723}
724
Kostya Serebryanye6926212015-11-04 23:22:25 +0000725// Returns an index of random unit from the corpus to mutate.
726// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000727// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000728size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000729 size_t Idx =
730 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000731 assert(Idx < Corpus.size());
732 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000733}
734
Kostya Serebryany945761b2016-03-18 00:23:29 +0000735void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000736 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000737 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000738 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000739}
740
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000741// Experimental search heuristic: drilling.
742// - Read, shuffle, execute and minimize the corpus.
743// - Choose one random unit.
744// - Reset the coverage.
745// - Start fuzzing as if the chosen unit was the only element of the corpus.
746// - When done, reset the coverage again.
747// - Merge the newly created corpus into the original one.
748void Fuzzer::Drill() {
749 // The corpus is already read, shuffled, and minimized.
750 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000751 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000752
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000753 Unit U = ChooseUnitToMutate();
754
Kostya Serebryany945761b2016-03-18 00:23:29 +0000755 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000756
757 std::vector<Unit> SavedCorpus;
758 SavedCorpus.swap(Corpus);
759 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000760 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000761 assert(Corpus.size() == 1);
762 RunOne(U);
763 PrintStats("DRILL ");
764 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
765 SavedOutputCorpusPath.swap(Options.OutputCorpus);
766 Loop();
767
Kostya Serebryany945761b2016-03-18 00:23:29 +0000768 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000769
770 PrintStats("REINIT");
771 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000772 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000773 RunOne(U);
774 PrintStats("MERGE ");
775 Options.PrintNEW = true;
776 size_t NumMerged = 0;
777 for (auto &U : Corpus) {
778 if (RunOne(U)) {
779 PrintStatusForNewUnit(U);
780 NumMerged++;
781 WriteToOutputCorpus(U);
782 }
783 }
784 PrintStats("MERGED");
785 if (NumMerged && Options.Verbosity)
786 Printf("Drilling discovered %zd new units\n", NumMerged);
787}
788
789void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000790 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000791 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000792 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000793 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000794 auto Now = system_clock::now();
795 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000796 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000797 LastCorpusReload = Now;
798 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000799 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000800 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000801 if (Options.MaxTotalTimeSec > 0 &&
802 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000803 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000804 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000805 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000806 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000807 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000808
809 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000810 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000811}
812
Ivan Krasindf919102016-01-22 22:28:27 +0000813void Fuzzer::UpdateCorpusDistribution() {
814 size_t N = Corpus.size();
815 std::vector<double> Intervals(N + 1);
816 std::vector<double> Weights(N);
817 std::iota(Intervals.begin(), Intervals.end(), 0);
818 std::iota(Weights.begin(), Weights.end(), 1);
819 CorpusDistribution = std::piecewise_constant_distribution<double>(
820 Intervals.begin(), Intervals.end(), Weights.begin());
821}
822
823} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000824
825extern "C" {
826
827size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
828 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000829 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000830}
831} // extern "C"