blob: b68185ba3b57763056bb1c7d815299dc41a5994e [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"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000013#include "FuzzerMutate.h"
14#include "FuzzerTracePC.h"
15#include "FuzzerRandom.h"
16
Aaron Ballmanef116982015-01-29 16:58:29 +000017#include <algorithm>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000018#include <cstring>
19#include <memory>
Aaron Ballmanef116982015-01-29 16:58:29 +000020
Kostya Serebryany2a48c242015-11-13 01:54:40 +000021#if defined(__has_include)
Ivan Krasindf919102016-01-22 22:28:27 +000022#if __has_include(<sanitizer / coverage_interface.h>)
23#include <sanitizer/coverage_interface.h>
24#endif
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000025#if __has_include(<sanitizer / lsan_interface.h>)
26#include <sanitizer/lsan_interface.h>
27#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000028#endif
29
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000030#define NO_SANITIZE_MEMORY
31#if defined(__has_feature)
32#if __has_feature(memory_sanitizer)
33#undef NO_SANITIZE_MEMORY
34#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
35#endif
36#endif
37
Aaron Ballmanef116982015-01-29 16:58:29 +000038namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000039static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000040
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000041thread_local bool Fuzzer::IsMyThread;
42
Dan Liew1873a492016-06-07 23:32:50 +000043static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000044 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000045 "Did you use -fsanitize-coverage=... to build your code?\n",
46 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000047 exit(1);
48}
49
Dan Liew1873a492016-06-07 23:32:50 +000050#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000051 do { \
Dan Liew1873a492016-06-07 23:32:50 +000052 if (!(EF->fn)) \
53 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000054 } while (false)
55
Kostya Serebryany52a788e2015-03-31 20:13:20 +000056// Only one Fuzzer per process.
57static Fuzzer *F;
58
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000059void Fuzzer::ResetEdgeCoverage() {
60 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
61 EF->__sanitizer_reset_coverage();
62}
63
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000064void Fuzzer::ResetCounters() {
65 if (Options.UseCounters) {
66 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
67 }
68 if (EF->__sanitizer_get_coverage_pc_buffer_pos)
69 PcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryany53501782016-09-15 04:36:45 +000070 TPC.GetNewPCsAndFlush();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000071}
72
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000073void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
74 if (Options.UseCounters) {
75 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
76 C->CounterBitmap.resize(NumCounters);
77 }
78}
79
80// Records data to a maximum coverage tracker. Returns true if additional
81// coverage was discovered.
82bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
83 bool Res = false;
84
Kostya Serebryanya5277d52016-09-15 01:30:18 +000085 TPC.FinalizeTrace();
86
Kostya Serebryanya00b2432016-09-14 02:13:06 +000087 uint64_t NewBlockCoverage =
88 EF->__sanitizer_get_total_unique_coverage() + TPC.GetTotalCoverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000089 if (NewBlockCoverage > C->BlockCoverage) {
90 Res = true;
91 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000092 }
93
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000094 if (Options.UseIndirCalls &&
95 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
96 uint64_t NewCallerCalleeCoverage =
97 EF->__sanitizer_get_total_unique_caller_callee_pairs();
98 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000099 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000100 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000101 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000102 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000103
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000104 if (Options.UseCounters) {
105 uint64_t CounterDelta =
106 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000107 C->CounterBitmap.data()) +
108 TPC.UpdateCounterMap(&C->TPCMap);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000109 if (CounterDelta > 0) {
110 Res = true;
111 C->CounterBitmapBits += CounterDelta;
112 }
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000113
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000114 }
115
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000116 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
117 if (NewVPMapBits > C->VPMapBits) {
118 Res = true;
119 C->VPMapBits = NewVPMapBits;
120 }
121
122 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
123 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000124 if (NewPcBufferPos > PcBufferPos) {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000125 Res = true;
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000126 PcBufferPos = NewPcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000127 }
128
129 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
130 Printf("ERROR: PC buffer overflow\n");
131 _Exit(1);
132 }
133 }
134
135 return Res;
136}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000137
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000138// Leak detection is expensive, so we first check if there were more mallocs
139// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
140struct MallocFreeTracer {
141 void Start() {
142 Mallocs = 0;
143 Frees = 0;
144 }
145 // Returns true if there were more mallocs than frees.
146 bool Stop() { return Mallocs > Frees; }
147 std::atomic<size_t> Mallocs;
148 std::atomic<size_t> Frees;
149};
150
151static MallocFreeTracer AllocTracer;
152
153void MallocHook(const volatile void *ptr, size_t size) {
154 AllocTracer.Mallocs++;
155}
156void FreeHook(const volatile void *ptr) {
157 AllocTracer.Frees++;
158}
159
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000160Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000161 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000162 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000163 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000164 assert(!F);
165 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000166 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000167 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000168 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
169 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000170 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000171
172 if (Options.PrintNewCovPcs) {
173 PcBufferLen = 1 << 24;
174 PcBuffer = new uintptr_t[PcBufferLen];
175 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
176 }
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000177 if (Options.Verbosity)
178 TPC.PrintModuleInfo();
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000179 if (!Options.OutputCorpus.empty() && Options.Reload)
180 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000181}
Aaron Ballmanef116982015-01-29 16:58:29 +0000182
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000183Fuzzer::~Fuzzer() { }
184
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000185void Fuzzer::LazyAllocateCurrentUnitData() {
186 if (CurrentUnitData || Options.MaxLen == 0) return;
187 CurrentUnitData = new uint8_t[Options.MaxLen];
188}
189
Aaron Ballmanef116982015-01-29 16:58:29 +0000190void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000191 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
192 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000193}
194
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000195void Fuzzer::StaticDeathCallback() {
196 assert(F);
197 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000198}
199
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000200static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000201 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000202 Printf(
203 "***\n"
204 "***\n"
205 "***\n"
206 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
207 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
208 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
209 "*** Future versions may have crash-resistant merge, stay tuned.\n"
210 "***\n"
211 "***\n"
212 "***\n");
213}
214
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000215void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000216 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000217 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000218 MD.PrintMutationSequence();
219 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000220 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000221 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000222 PrintHexArray(CurrentUnitData, UnitSize, "\n");
223 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000224 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000225 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
226 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000227}
228
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000229NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000230void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000231 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000232 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000233}
234
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000235void Fuzzer::StaticAlarmCallback() {
236 assert(F);
237 F->AlarmCallback();
238}
239
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000240void Fuzzer::StaticCrashSignalCallback() {
241 assert(F);
242 F->CrashCallback();
243}
244
245void Fuzzer::StaticInterruptCallback() {
246 assert(F);
247 F->InterruptCallback();
248}
249
250void Fuzzer::CrashCallback() {
251 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000252 if (EF->__sanitizer_print_stack_trace)
253 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000254 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
255 " Combine libFuzzer with AddressSanitizer or similar for better "
256 "crash reports.\n");
257 Printf("SUMMARY: libFuzzer: deadly signal\n");
258 DumpCurrentUnit("crash-");
259 PrintFinalStats();
260 exit(Options.ErrorExitCode);
261}
262
263void Fuzzer::InterruptCallback() {
264 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
265 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000266 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000267}
268
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000269NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000270void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000271 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000272 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000273 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000274 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000275 size_t Seconds =
276 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000277 if (Seconds == 0)
278 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000279 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000280 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000281 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000282 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000283 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
284 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000285 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000286 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
287 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000288 if (EF->__sanitizer_print_stack_trace)
289 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000290 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000291 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000292 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000293 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000294}
295
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000296void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000297 Printf(
298 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
299 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000300 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000301 if (EF->__sanitizer_print_memory_profile)
302 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000303 DumpCurrentUnit("oom-");
304 Printf("SUMMARY: libFuzzer: out-of-memory\n");
305 PrintFinalStats();
306 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000307}
308
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000309void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000310 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000311 if (Options.OutputCSV) {
312 static bool csvHeaderPrinted = false;
313 if (!csvHeaderPrinted) {
314 csvHeaderPrinted = true;
315 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
316 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000317 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000318 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
319 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000320 }
321
322 if (!Options.Verbosity)
323 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000324 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000325 if (MaxCoverage.BlockCoverage)
326 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000327 if (MaxCoverage.VPMapBits)
328 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000329 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000330 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000331 if (MaxCoverage.CallerCalleeCoverage)
332 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000333 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000334 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000335}
336
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000337void Fuzzer::PrintFinalStats() {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000338 if (Options.PrintCoverage)
339 TPC.PrintCoverage();
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000340 if (!Options.PrintFinalStats) return;
341 size_t ExecPerSec = execPerSec();
342 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
343 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
344 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
345 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
346 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
347}
348
Kostya Serebryany64d24572016-03-12 01:57:04 +0000349void Fuzzer::SetMaxLen(size_t MaxLen) {
350 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
351 assert(MaxLen);
352 Options.MaxLen = MaxLen;
353 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
354}
355
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000356void Fuzzer::ReadDir(const std::string &Path, long *Epoch, size_t MaxSize) {
357 Printf("Loading corpus: %s\n", Path.c_str());
358 std::vector<Unit> V;
359 ReadDirToVectorOfUnits(Path.c_str(), &V, Epoch, MaxSize);
360 for (auto &U : V)
361 Corpus.push_back(U);
362}
Kostya Serebryany64d24572016-03-12 01:57:04 +0000363
364void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000365 if (Options.OutputCorpus.empty() || !Options.Reload) return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000366 std::vector<Unit> AdditionalCorpus;
367 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000368 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000369 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000370 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000371 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000372 if (X.size() > MaxSize)
373 X.resize(MaxSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000374 if (!Corpus.HasUnit(X)) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000375 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000376 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000377 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000378 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000379 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000380 }
381 }
382}
383
Kostya Serebryany945761b2016-03-18 00:23:29 +0000384void Fuzzer::ShuffleCorpus(UnitVector *V) {
385 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
386 if (Options.PreferSmall)
387 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
388 return A.size() < B.size();
389 });
390}
391
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000392void Fuzzer::ShuffleAndMinimize(UnitVector *InitialCorpus) {
393 Printf("#0\tREAD units: %zd\n", InitialCorpus->size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000394 if (Options.ShuffleAtStartUp)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000395 ShuffleCorpus(InitialCorpus);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000396
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000397 for (const auto &U : *InitialCorpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000398 bool NewCoverage = RunOne(U);
399 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000400 Corpus.push_back(U);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000401 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000402 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000403 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000404 TryDetectingAMemoryLeak(U.data(), U.size(),
405 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000406 }
Ivan Krasindf919102016-01-22 22:28:27 +0000407 UpdateCorpusDistribution();
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000408 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000409 if (Corpus.empty()) {
410 Printf("ERROR: no interesting inputs were found. "
411 "Is the code instrumented for coverage? Exiting.\n");
412 exit(1);
413 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000414}
415
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000416bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000417 PrevPcBufferPos = PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000418 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000419
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000420 return Res;
421}
422
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000423bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000424 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000425
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000426 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000427 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000428
Kostya Serebryany16901a92015-03-30 23:04:35 +0000429 auto UnitStopTime = system_clock::now();
430 auto TimeOfUnit =
431 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000432 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
433 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000434 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000435 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
436 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000437 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000438 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000439 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000440 }
441 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000442}
443
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000444void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000445 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
446 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000447 if (RunOne(Data, Size))
448 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000449}
450
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000451size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000452 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000453 *Data = CurrentUnitData;
454 return CurrentUnitSize;
455}
456
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000457void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000458 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000459 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000460 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000461 // We copy the contents of Unit into a separate heap buffer
462 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000463 uint8_t *DataCopy = new uint8_t[Size];
464 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000465 if (CurrentUnitData && CurrentUnitData != Data)
466 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000467 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000468 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000469 AllocTracer.Start();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000470 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000471 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000472 (void)Res;
473 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000474 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000475 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000476 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000477}
478
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000479std::string Fuzzer::Coverage::DebugString() const {
480 std::string Result =
481 std::string("Coverage{") + "BlockCoverage=" +
482 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
483 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanya00b2432016-09-14 02:13:06 +0000484 std::to_string(CounterBitmapBits) +
485 " VPMapBits " + std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000486 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000487}
488
489void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000490 if (Options.OnlyASCII)
491 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000492 if (Options.OutputCorpus.empty())
493 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000494 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
495 WriteToFile(U, Path);
496 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000497 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000498}
499
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000500void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000501 if (!Options.SaveArtifacts)
502 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000503 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000504 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000505 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000506 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000507 Printf("artifact_prefix='%s'; Test unit written to %s\n",
508 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000509 if (U.size() <= kMaxUnitSizeToPrint)
510 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000511}
512
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000513void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
514 if (!Options.PrintNEW)
515 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000516 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000517 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000518 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000519 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000520 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000521 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000522}
523
Kostya Serebryany53501782016-09-15 04:36:45 +0000524void Fuzzer::PrintOneNewPC(uintptr_t PC) {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000525 PrintPC("\tNEW_PC: %p %F %L\n",
526 "\tNEW_PC: %p\n", PC);
Kostya Serebryany53501782016-09-15 04:36:45 +0000527}
528
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000529void Fuzzer::PrintNewPCs() {
Kostya Serebryany53501782016-09-15 04:36:45 +0000530 if (!Options.PrintNewCovPcs) return;
531 if (PrevPcBufferPos != PcBufferPos) {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000532 int NumPrinted = 0;
533 for (size_t I = PrevPcBufferPos; I < PcBufferPos; ++I) {
534 if (NumPrinted++ > 30) break; // Don't print too many new PCs.
Kostya Serebryany53501782016-09-15 04:36:45 +0000535 PrintOneNewPC(PcBuffer[I]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000536 }
537 }
Kostya Serebryany53501782016-09-15 04:36:45 +0000538 uintptr_t *PCs;
539 if (size_t NumNewPCs = TPC.GetNewPCsAndFlush(&PCs))
540 for (size_t i = 0; i < NumNewPCs; i++)
541 PrintOneNewPC(PCs[i]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000542}
543
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000544void Fuzzer::ReportNewCoverage(const Unit &U) {
545 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000546 UpdateCorpusDistribution();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000547 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000548 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000549 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000550 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000551 PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000552}
553
Kostya Serebryany945761b2016-03-18 00:23:29 +0000554// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
555// We do it by actually executing the units, sometimes more than once,
556// because we may be using different coverage-like signals and the only
557// common thing between them is that we can say "this unit found new stuff".
558UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
559 const UnitVector &Extra) {
560 UnitVector Res = Extra;
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000561 UnitVector Tmp;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000562 size_t OldSize = Res.size();
563 for (int Iter = 0; Iter < 10; Iter++) {
564 ShuffleCorpus(&Res);
565 ResetCoverage();
566
567 for (auto &U : Initial)
568 RunOne(U);
569
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000570 Tmp.clear();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000571 for (auto &U : Res)
572 if (RunOne(U))
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000573 Tmp.push_back(U);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000574
575 char Stat[7] = "MIN ";
576 Stat[3] = '0' + Iter;
577 PrintStats(Stat);
578
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000579 size_t NewSize = Tmp.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000580 assert(NewSize <= OldSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000581 Res.swap(Tmp);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000582
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000583 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000584 break;
585 OldSize = NewSize;
586 }
587 return Res;
588}
589
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000590void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
591 if (Corpora.size() <= 1) {
592 Printf("Merge requires two or more corpus dirs\n");
593 return;
594 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000595 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000596 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
597
Kostya Serebryany945761b2016-03-18 00:23:29 +0000598 assert(Options.MaxLen > 0);
599 UnitVector Initial, Extra;
600 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
601 for (auto &C : ExtraCorpora)
602 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
603
604 if (!Initial.empty()) {
605 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
606 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000607 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000608
609 Printf("=== Merging extra %zd units\n", Extra.size());
610 auto Res = FindExtraUnits(Initial, Extra);
611
612 for (auto &U: Res)
613 WriteToOutputCorpus(U);
614
615 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000616}
617
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000618// Tries detecting a memory leak on the particular input that we have just
619// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000620void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
621 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000622 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
623 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000624 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
625 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000626 return; // No lsan.
627 // Run the target once again, but with lsan disabled so that if there is
628 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000629 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000630 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000631 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000632 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000633 if (NumberOfLeakDetectionAttempts++ > 1000) {
634 Options.DetectLeaks = false;
635 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
636 " Most likely the target function accumulates allocated\n"
637 " memory in a global state w/o actually leaking it.\n"
638 " If LeakSanitizer is enabled in this process it will still\n"
639 " run on the process shutdown.\n");
640 return;
641 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000642 // Now perform the actual lsan pass. This is expensive and we must ensure
643 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000644 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000645 if (DuringInitialCorpusExecution)
646 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
647 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000648 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000649 DumpCurrentUnit("leak-");
650 PrintFinalStats();
651 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
652 }
653}
654
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000655void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000656 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000657 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000658
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000659 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000660 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000661 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000662 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000663 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000664 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000665
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000666 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000667 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000668 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000669 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000670 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000671 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000672 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000673 if (i == 0)
674 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000675 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000676 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000677 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000678 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000679 }
680}
681
Kostya Serebryanye6926212015-11-04 23:22:25 +0000682// Returns an index of random unit from the corpus to mutate.
683// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000684// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000685size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000686 size_t Idx =
687 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000688 assert(Idx < Corpus.size());
689 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000690}
691
Kostya Serebryany945761b2016-03-18 00:23:29 +0000692void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000693 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000694 MaxCoverage.Reset();
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000695 TPC.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000696 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000697}
698
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000699void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000700 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000701 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000702 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000703 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000704 auto Now = system_clock::now();
705 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000706 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000707 LastCorpusReload = Now;
708 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000709 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000710 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000711 if (Options.MaxTotalTimeSec > 0 &&
712 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000713 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000714 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000715 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000716 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000717 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000718
719 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000720 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000721}
722
Ivan Krasindf919102016-01-22 22:28:27 +0000723void Fuzzer::UpdateCorpusDistribution() {
724 size_t N = Corpus.size();
725 std::vector<double> Intervals(N + 1);
726 std::vector<double> Weights(N);
727 std::iota(Intervals.begin(), Intervals.end(), 0);
728 std::iota(Weights.begin(), Weights.end(), 1);
729 CorpusDistribution = std::piecewise_constant_distribution<double>(
730 Intervals.begin(), Intervals.end(), Weights.begin());
731}
732
733} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000734
735extern "C" {
736
737size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
738 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000739 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000740}
741} // extern "C"