blob: f7d4e4ef362dda9771bfcd39fab7b9befd33b00c [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 Serebryany29bb6642016-09-21 22:42:17 +000013#include "FuzzerCorpus.h"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000014#include "FuzzerMutate.h"
15#include "FuzzerTracePC.h"
16#include "FuzzerRandom.h"
17
Aaron Ballmanef116982015-01-29 16:58:29 +000018#include <algorithm>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000019#include <cstring>
20#include <memory>
Aaron Ballmanef116982015-01-29 16:58:29 +000021
Kostya Serebryany2a48c242015-11-13 01:54:40 +000022#if defined(__has_include)
Ivan Krasindf919102016-01-22 22:28:27 +000023#if __has_include(<sanitizer / coverage_interface.h>)
24#include <sanitizer/coverage_interface.h>
25#endif
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000026#if __has_include(<sanitizer / lsan_interface.h>)
27#include <sanitizer/lsan_interface.h>
28#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000029#endif
30
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000031#define NO_SANITIZE_MEMORY
32#if defined(__has_feature)
33#if __has_feature(memory_sanitizer)
34#undef NO_SANITIZE_MEMORY
35#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
36#endif
37#endif
38
Aaron Ballmanef116982015-01-29 16:58:29 +000039namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000040static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000041
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000042thread_local bool Fuzzer::IsMyThread;
43
Dan Liew1873a492016-06-07 23:32:50 +000044static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000045 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000046 "Did you use -fsanitize-coverage=... to build your code?\n",
47 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000048 exit(1);
49}
50
Dan Liew1873a492016-06-07 23:32:50 +000051#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000052 do { \
Dan Liew1873a492016-06-07 23:32:50 +000053 if (!(EF->fn)) \
54 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000055 } while (false)
56
Kostya Serebryany52a788e2015-03-31 20:13:20 +000057// Only one Fuzzer per process.
58static Fuzzer *F;
59
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000060void Fuzzer::ResetEdgeCoverage() {
61 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
62 EF->__sanitizer_reset_coverage();
63}
64
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000065void Fuzzer::ResetCounters() {
66 if (Options.UseCounters) {
67 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
68 }
69 if (EF->__sanitizer_get_coverage_pc_buffer_pos)
70 PcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
71}
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 Serebryany87a598e2016-09-23 01:20:07 +000087 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000088 if (NewBlockCoverage > C->BlockCoverage) {
89 Res = true;
90 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000091 }
92
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000093 if (Options.UseIndirCalls &&
94 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
95 uint64_t NewCallerCalleeCoverage =
96 EF->__sanitizer_get_total_unique_caller_callee_pairs();
97 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000098 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000099 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000100 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000101 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000102
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000103 if (Options.UseCounters) {
104 uint64_t CounterDelta =
105 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000106 C->CounterBitmap.data());
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000107 if (CounterDelta > 0) {
108 Res = true;
109 C->CounterBitmapBits += CounterDelta;
110 }
111 }
112
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000113 if (TPC.UpdateCounterMap(&C->TPCMap))
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000114 Res = true;
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000115
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000116 if (TPC.UpdateValueProfileMap(&C->VPMap))
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000117 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000118
119 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
120 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000121 if (NewPcBufferPos > PcBufferPos) {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000122 Res = true;
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000123 PcBufferPos = NewPcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000124 }
125
126 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
127 Printf("ERROR: PC buffer overflow\n");
128 _Exit(1);
129 }
130 }
131
132 return Res;
133}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000134
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000135// Leak detection is expensive, so we first check if there were more mallocs
136// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
137struct MallocFreeTracer {
138 void Start() {
139 Mallocs = 0;
140 Frees = 0;
141 }
142 // Returns true if there were more mallocs than frees.
143 bool Stop() { return Mallocs > Frees; }
144 std::atomic<size_t> Mallocs;
145 std::atomic<size_t> Frees;
146};
147
148static MallocFreeTracer AllocTracer;
149
150void MallocHook(const volatile void *ptr, size_t size) {
151 AllocTracer.Mallocs++;
152}
153void FreeHook(const volatile void *ptr) {
154 AllocTracer.Frees++;
155}
156
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000157Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
158 FuzzingOptions Options)
159 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000160 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000161 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000162 assert(!F);
163 F = this;
Kostya Serebryany87a598e2016-09-23 01:20:07 +0000164 TPC.ResetTotalPCCoverage();
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000165 TPC.ResetMaps();
166 TPC.ResetGuards();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000167 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000168 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000169 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
170 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000171 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000172 TPC.SetUseValueProfile(Options.UseValueProfile);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000173
174 if (Options.PrintNewCovPcs) {
175 PcBufferLen = 1 << 24;
176 PcBuffer = new uintptr_t[PcBufferLen];
177 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
178 }
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000179 if (Options.Verbosity)
180 TPC.PrintModuleInfo();
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000181 if (!Options.OutputCorpus.empty() && Options.Reload)
182 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000183 MaxInputLen = MaxMutationLen = Options.MaxLen;
184 AllocateCurrentUnitData();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000185}
Aaron Ballmanef116982015-01-29 16:58:29 +0000186
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000187Fuzzer::~Fuzzer() { }
188
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000189void Fuzzer::AllocateCurrentUnitData() {
190 if (CurrentUnitData || MaxInputLen == 0) return;
191 CurrentUnitData = new uint8_t[MaxInputLen];
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000192}
193
Aaron Ballmanef116982015-01-29 16:58:29 +0000194void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000195 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
196 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000197}
198
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000199void Fuzzer::StaticDeathCallback() {
200 assert(F);
201 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000202}
203
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000204static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000205 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000206 Printf(
207 "***\n"
208 "***\n"
209 "***\n"
210 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
211 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
212 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
213 "*** Future versions may have crash-resistant merge, stay tuned.\n"
214 "***\n"
215 "***\n"
216 "***\n");
217}
218
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000219void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000220 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000221 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000222 MD.PrintMutationSequence();
223 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000224 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000225 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000226 PrintHexArray(CurrentUnitData, UnitSize, "\n");
227 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000228 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000229 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
230 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000231}
232
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000233NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000234void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000235 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000236 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000237}
238
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000239void Fuzzer::StaticAlarmCallback() {
240 assert(F);
241 F->AlarmCallback();
242}
243
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000244void Fuzzer::StaticCrashSignalCallback() {
245 assert(F);
246 F->CrashCallback();
247}
248
249void Fuzzer::StaticInterruptCallback() {
250 assert(F);
251 F->InterruptCallback();
252}
253
254void Fuzzer::CrashCallback() {
255 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000256 if (EF->__sanitizer_print_stack_trace)
257 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000258 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
259 " Combine libFuzzer with AddressSanitizer or similar for better "
260 "crash reports.\n");
261 Printf("SUMMARY: libFuzzer: deadly signal\n");
262 DumpCurrentUnit("crash-");
263 PrintFinalStats();
264 exit(Options.ErrorExitCode);
265}
266
267void Fuzzer::InterruptCallback() {
268 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
269 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000270 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000271}
272
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000273NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000274void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000275 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000276 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000277 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000278 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000279 size_t Seconds =
280 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000281 if (Seconds == 0)
282 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000283 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000284 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000285 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000286 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000287 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
288 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000289 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000290 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
291 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000292 if (EF->__sanitizer_print_stack_trace)
293 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000294 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000295 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000296 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000297 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000298}
299
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000300void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000301 Printf(
302 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
303 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000304 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000305 if (EF->__sanitizer_print_memory_profile)
306 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000307 DumpCurrentUnit("oom-");
308 Printf("SUMMARY: libFuzzer: out-of-memory\n");
309 PrintFinalStats();
310 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000311}
312
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000313void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000314 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000315 if (Options.OutputCSV) {
316 static bool csvHeaderPrinted = false;
317 if (!csvHeaderPrinted) {
318 csvHeaderPrinted = true;
319 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
320 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000321 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000322 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
323 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000324 }
325
326 if (!Options.Verbosity)
327 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000328 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000329 if (MaxCoverage.BlockCoverage)
330 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryany87a598e2016-09-23 01:20:07 +0000331 if (size_t N = TPC.GetTotalPCCoverage())
332 Printf(" cov: %zd", N);
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000333 if (MaxCoverage.VPMap.GetNumBitsSinceLastMerge())
334 Printf(" vp: %zd", MaxCoverage.VPMap.GetNumBitsSinceLastMerge());
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000335 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000336 Printf(" bits: %zd", TB);
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000337 if (auto TB = MaxCoverage.TPCMap.GetNumBitsSinceLastMerge())
338 Printf(" bits: %zd", MaxCoverage.TPCMap.GetNumBitsSinceLastMerge());
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000339 if (MaxCoverage.CallerCalleeCoverage)
340 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000341 if (size_t N = Corpus.size())
342 Printf(" units: %zd", N);
343 if (Units)
344 Printf(" units: %zd", Units);
345 Printf(" exec/s: %zd", ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000346 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000347}
348
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000349void Fuzzer::PrintFinalStats() {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000350 if (Options.PrintCoverage)
351 TPC.PrintCoverage();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000352 if (Options.PrintCorpusStats)
353 Corpus.PrintStats();
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000354 if (!Options.PrintFinalStats) return;
355 size_t ExecPerSec = execPerSec();
356 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
357 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
358 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
359 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
360 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
361}
362
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000363void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
364 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
365 assert(MaxInputLen);
366 this->MaxInputLen = MaxInputLen;
367 this->MaxMutationLen = MaxInputLen;
368 AllocateCurrentUnitData();
369 Printf("INFO: -max_len is not provided, using %zd\n", MaxInputLen);
370}
371
372void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
373 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
374 this->MaxMutationLen = MaxMutationLen;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000375}
376
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000377void Fuzzer::CheckExitOnSrcPos() {
378 if (!Options.ExitOnSrcPos.empty()) {
379 uintptr_t *PCIDs;
380 if (size_t NumNewPCIDs = TPC.GetNewPCIDs(&PCIDs)) {
381 for (size_t i = 0; i < NumNewPCIDs; i++) {
382 std::string Descr = DescribePC("%L", TPC.GetPCbyPCID(PCIDs[i]));
383 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
384 Printf("INFO: found line matching '%s', exiting.\n",
385 Options.ExitOnSrcPos.c_str());
386 _Exit(0);
387 }
388 }
389 }
390 }
391}
392
Kostya Serebryany0800b812016-09-23 23:51:58 +0000393void Fuzzer::AddToCorpusAndMaybeRerun(const Unit &U) {
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000394 CheckExitOnSrcPos();
Kostya Serebryany0800b812016-09-23 23:51:58 +0000395 Corpus.AddToCorpus(U);
396 if (TPC.GetTotalPCCoverage()) {
397 TPC.ResetMaps();
398 TPC.ResetGuards();
399 ExecuteCallback(U.data(), U.size());
400 TPC.FinalizeTrace();
401 TPC.UpdateFeatureSet(Corpus.size() - 1, U.size());
402 // TPC.PrintFeatureSet();
403 }
404}
405
Kostya Serebryany64d24572016-03-12 01:57:04 +0000406void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000407 if (Options.OutputCorpus.empty() || !Options.Reload) return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000408 std::vector<Unit> AdditionalCorpus;
409 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000410 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000411 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000412 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000413 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000414 if (X.size() > MaxSize)
415 X.resize(MaxSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000416 if (!Corpus.HasUnit(X)) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000417 if (RunOne(X)) {
Kostya Serebryany0800b812016-09-23 23:51:58 +0000418 AddToCorpusAndMaybeRerun(X);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000419 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000420 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000421 }
422 }
423}
424
Kostya Serebryany945761b2016-03-18 00:23:29 +0000425void Fuzzer::ShuffleCorpus(UnitVector *V) {
426 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
427 if (Options.PreferSmall)
428 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
429 return A.size() < B.size();
430 });
431}
432
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000433void Fuzzer::ShuffleAndMinimize(UnitVector *InitialCorpus) {
434 Printf("#0\tREAD units: %zd\n", InitialCorpus->size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000435 if (Options.ShuffleAtStartUp)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000436 ShuffleCorpus(InitialCorpus);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000437
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000438 for (const auto &U : *InitialCorpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000439 bool NewCoverage = RunOne(U);
440 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany0800b812016-09-23 23:51:58 +0000441 AddToCorpusAndMaybeRerun(U);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000442 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000443 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000444 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000445 TryDetectingAMemoryLeak(U.data(), U.size(),
446 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000447 }
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000448 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000449 if (Corpus.empty()) {
450 Printf("ERROR: no interesting inputs were found. "
451 "Is the code instrumented for coverage? Exiting.\n");
452 exit(1);
453 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000454}
455
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000456bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000457 PrevPcBufferPos = PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000458 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000459
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000460 return Res;
461}
462
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000463bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000464 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000465
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000466 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000467 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000468
Kostya Serebryany16901a92015-03-30 23:04:35 +0000469 auto TimeOfUnit =
470 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000471 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
472 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000473 PrintStats("pulse ");
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000474 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000475 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000476 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000477 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000478 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000479 }
480 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000481}
482
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000483size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000484 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000485 *Data = CurrentUnitData;
486 return CurrentUnitSize;
487}
488
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000489void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000490 assert(InFuzzingThread());
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000491 // We copy the contents of Unit into a separate heap buffer
492 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000493 uint8_t *DataCopy = new uint8_t[Size];
494 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000495 if (CurrentUnitData && CurrentUnitData != Data)
496 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000497 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000498 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000499 AllocTracer.Start();
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000500 UnitStartTime = system_clock::now();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000501 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000502 TPC.ResetMaps();
Kostya Serebryany0800b812016-09-23 23:51:58 +0000503 TPC.ResetGuards();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000504 int Res = CB(DataCopy, Size);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000505 UnitStopTime = system_clock::now();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000506 (void)Res;
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000507 assert(Res == 0);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000508 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000509 CurrentUnitSize = 0;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000510 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000511}
512
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000513std::string Fuzzer::Coverage::DebugString() const {
514 std::string Result =
515 std::string("Coverage{") + "BlockCoverage=" +
516 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
517 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000518 std::to_string(CounterBitmapBits) + " VPMapBits " +
519 std::to_string(VPMap.GetNumBitsSinceLastMerge()) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000520 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000521}
522
523void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000524 if (Options.OnlyASCII)
525 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000526 if (Options.OutputCorpus.empty())
527 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000528 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
529 WriteToFile(U, Path);
530 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000531 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000532}
533
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000534void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000535 if (!Options.SaveArtifacts)
536 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000537 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000538 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000539 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000540 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000541 Printf("artifact_prefix='%s'; Test unit written to %s\n",
542 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000543 if (U.size() <= kMaxUnitSizeToPrint)
544 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000545}
546
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000547void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
548 if (!Options.PrintNEW)
549 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000550 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000551 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000552 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000553 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000554 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000555 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000556}
557
Kostya Serebryany53501782016-09-15 04:36:45 +0000558void Fuzzer::PrintOneNewPC(uintptr_t PC) {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000559 PrintPC("\tNEW_PC: %p %F %L\n",
560 "\tNEW_PC: %p\n", PC);
Kostya Serebryany53501782016-09-15 04:36:45 +0000561}
562
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000563void Fuzzer::PrintNewPCs() {
Kostya Serebryany53501782016-09-15 04:36:45 +0000564 if (!Options.PrintNewCovPcs) return;
565 if (PrevPcBufferPos != PcBufferPos) {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000566 int NumPrinted = 0;
567 for (size_t I = PrevPcBufferPos; I < PcBufferPos; ++I) {
568 if (NumPrinted++ > 30) break; // Don't print too many new PCs.
Kostya Serebryany53501782016-09-15 04:36:45 +0000569 PrintOneNewPC(PcBuffer[I]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000570 }
571 }
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000572 uintptr_t *PCIDs;
573 if (size_t NumNewPCIDs = TPC.GetNewPCIDs(&PCIDs))
574 for (size_t i = 0; i < NumNewPCIDs; i++)
575 PrintOneNewPC(TPC.GetPCbyPCID(PCIDs[i]));
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000576}
577
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000578void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
579 II->NumSuccessfullMutations++;
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000580 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000581 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000582 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000583 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000584 PrintNewPCs();
Kostya Serebryany0800b812016-09-23 23:51:58 +0000585 AddToCorpusAndMaybeRerun(U);
Aaron Ballmanef116982015-01-29 16:58:29 +0000586}
587
Kostya Serebryany945761b2016-03-18 00:23:29 +0000588// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
589// We do it by actually executing the units, sometimes more than once,
590// because we may be using different coverage-like signals and the only
591// common thing between them is that we can say "this unit found new stuff".
592UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
593 const UnitVector &Extra) {
594 UnitVector Res = Extra;
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000595 UnitVector Tmp;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000596 size_t OldSize = Res.size();
597 for (int Iter = 0; Iter < 10; Iter++) {
598 ShuffleCorpus(&Res);
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000599 TPC.ResetMaps();
600 TPC.ResetGuards();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000601 ResetCoverage();
602
603 for (auto &U : Initial)
604 RunOne(U);
605
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000606 Tmp.clear();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000607 for (auto &U : Res)
608 if (RunOne(U))
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000609 Tmp.push_back(U);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000610
611 char Stat[7] = "MIN ";
612 Stat[3] = '0' + Iter;
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000613 PrintStats(Stat, "\n", Tmp.size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000614
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000615 size_t NewSize = Tmp.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000616 assert(NewSize <= OldSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000617 Res.swap(Tmp);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000618
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000619 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000620 break;
621 OldSize = NewSize;
622 }
623 return Res;
624}
625
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000626void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
627 if (Corpora.size() <= 1) {
628 Printf("Merge requires two or more corpus dirs\n");
629 return;
630 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000631 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000632 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
633
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000634 assert(MaxInputLen > 0);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000635 UnitVector Initial, Extra;
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000636 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, MaxInputLen);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000637 for (auto &C : ExtraCorpora)
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000638 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, MaxInputLen);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000639
640 if (!Initial.empty()) {
641 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
642 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000643 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000644
645 Printf("=== Merging extra %zd units\n", Extra.size());
646 auto Res = FindExtraUnits(Initial, Extra);
647
648 for (auto &U: Res)
649 WriteToOutputCorpus(U);
650
651 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000652}
653
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000654// Tries detecting a memory leak on the particular input that we have just
655// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000656void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
657 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000658 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
659 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000660 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
661 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000662 return; // No lsan.
663 // Run the target once again, but with lsan disabled so that if there is
664 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000665 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000666 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000667 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000668 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000669 if (NumberOfLeakDetectionAttempts++ > 1000) {
670 Options.DetectLeaks = false;
671 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
672 " Most likely the target function accumulates allocated\n"
673 " memory in a global state w/o actually leaking it.\n"
674 " If LeakSanitizer is enabled in this process it will still\n"
675 " run on the process shutdown.\n");
676 return;
677 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000678 // Now perform the actual lsan pass. This is expensive and we must ensure
679 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000680 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000681 if (DuringInitialCorpusExecution)
682 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
683 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000684 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000685 DumpCurrentUnit("leak-");
686 PrintFinalStats();
687 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
688 }
689}
690
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000691void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000692 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000693
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000694 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany20801e12016-09-21 21:41:48 +0000695 const auto &U = II.U;
696 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000697 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000698 size_t Size = U.size();
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000699 assert(Size <= MaxInputLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000700 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000701
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000702 assert(MaxMutationLen > 0);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000703
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000704 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000705 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
706 break;
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000707 size_t NewSize = 0;
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000708 NewSize = MD.Mutate(CurrentUnitData, Size, MaxMutationLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000709 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000710 assert(NewSize <= MaxMutationLen && "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000711 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000712 if (i == 0)
713 StartTraceRecording();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000714 II.NumExecutedMutations++;
715 if (RunOne(CurrentUnitData, Size))
716 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000717 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000718 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000719 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000720 }
721}
722
Kostya Serebryany945761b2016-03-18 00:23:29 +0000723void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000724 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000725 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000726 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000727}
728
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000729void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000730 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000731 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000732 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000733 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000734 auto Now = system_clock::now();
735 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000736 RereadOutputCorpus(MaxInputLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000737 LastCorpusReload = Now;
738 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000739 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000740 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000741 if (Options.MaxTotalTimeSec > 0 &&
742 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000743 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000744 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000745 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000746 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000747 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000748
749 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000750 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000751}
752
Ivan Krasindf919102016-01-22 22:28:27 +0000753} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000754
755extern "C" {
756
757size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
758 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000759 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000760}
761} // extern "C"