blob: 1e67f93a8b1f4c709dbdafa2c9e7f2fed14dce70 [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() {
Kostya Serebryanyb3949ef2016-09-30 01:24:57 +000066 if (Options.UseCounters)
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000067 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000068}
69
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000070void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
71 if (Options.UseCounters) {
72 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
73 C->CounterBitmap.resize(NumCounters);
74 }
75}
76
77// Records data to a maximum coverage tracker. Returns true if additional
78// coverage was discovered.
79bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
80 bool Res = false;
81
Kostya Serebryany87a598e2016-09-23 01:20:07 +000082 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000083 if (NewBlockCoverage > C->BlockCoverage) {
84 Res = true;
85 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000086 }
87
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000088 if (Options.UseIndirCalls &&
89 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
90 uint64_t NewCallerCalleeCoverage =
91 EF->__sanitizer_get_total_unique_caller_callee_pairs();
92 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000093 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000094 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000095 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000096 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000097
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000098 if (Options.UseCounters) {
99 uint64_t CounterDelta =
100 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000101 C->CounterBitmap.data());
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000102 if (CounterDelta > 0) {
103 Res = true;
104 C->CounterBitmapBits += CounterDelta;
105 }
106 }
107
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000108 return Res;
109}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000110
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000111// Leak detection is expensive, so we first check if there were more mallocs
112// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
113struct MallocFreeTracer {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000114 void Start(int TraceLevel) {
115 this->TraceLevel = TraceLevel;
116 if (TraceLevel)
117 Printf("MallocFreeTracer: START\n");
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000118 Mallocs = 0;
119 Frees = 0;
120 }
121 // Returns true if there were more mallocs than frees.
Kostya Serebryany03813742016-10-13 22:24:10 +0000122 bool Stop() {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000123 if (TraceLevel)
124 Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
125 Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
126 bool Result = Mallocs > Frees;
127 Mallocs = 0;
128 Frees = 0;
129 TraceLevel = 0;
130 return Result;
131 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000132 std::atomic<size_t> Mallocs;
133 std::atomic<size_t> Frees;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000134 int TraceLevel = 0;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000135};
136
137static MallocFreeTracer AllocTracer;
138
139void MallocHook(const volatile void *ptr, size_t size) {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000140 size_t N = AllocTracer.Mallocs++;
141 if (int TraceLevel = AllocTracer.TraceLevel) {
142 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
143 if (TraceLevel >= 2 && EF)
144 EF->__sanitizer_print_stack_trace();
145 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000146}
147void FreeHook(const volatile void *ptr) {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000148 size_t N = AllocTracer.Frees++;
149 if (int TraceLevel = AllocTracer.TraceLevel) {
Kostya Serebryany03813742016-10-13 22:24:10 +0000150 Printf("FREE[%zd] %p\n", N, ptr);
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000151 if (TraceLevel >= 2 && EF)
152 EF->__sanitizer_print_stack_trace();
153 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000154}
155
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000156Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
157 FuzzingOptions Options)
158 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000159 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000160 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000161 assert(!F);
162 F = this;
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000163 TPC.ResetMaps();
164 TPC.ResetGuards();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000165 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000166 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000167 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
168 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000169 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000170 TPC.SetUseValueProfile(Options.UseValueProfile);
Kostya Serebryanya5b2e542016-10-26 00:20:51 +0000171 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000172
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000173 if (Options.Verbosity)
174 TPC.PrintModuleInfo();
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000175 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000176 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000177 MaxInputLen = MaxMutationLen = Options.MaxLen;
178 AllocateCurrentUnitData();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000179}
Aaron Ballmanef116982015-01-29 16:58:29 +0000180
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000181Fuzzer::~Fuzzer() { }
182
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000183void Fuzzer::AllocateCurrentUnitData() {
184 if (CurrentUnitData || MaxInputLen == 0) return;
185 CurrentUnitData = new uint8_t[MaxInputLen];
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000186}
187
Aaron Ballmanef116982015-01-29 16:58:29 +0000188void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000189 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
190 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000191}
192
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000193void Fuzzer::StaticDeathCallback() {
194 assert(F);
195 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000196}
197
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000198static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000199 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000200 Printf(
201 "***\n"
202 "***\n"
203 "***\n"
204 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
205 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
206 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
207 "*** Future versions may have crash-resistant merge, stay tuned.\n"
208 "***\n"
209 "***\n"
210 "***\n");
211}
212
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000213void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000214 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000215 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000216 MD.PrintMutationSequence();
217 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000218 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000219 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000220 PrintHexArray(CurrentUnitData, UnitSize, "\n");
221 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000222 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000223 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
224 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000225}
226
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000227NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000228void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000229 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000230 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000231}
232
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000233void Fuzzer::StaticAlarmCallback() {
234 assert(F);
235 F->AlarmCallback();
236}
237
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000238void Fuzzer::StaticCrashSignalCallback() {
239 assert(F);
240 F->CrashCallback();
241}
242
243void Fuzzer::StaticInterruptCallback() {
244 assert(F);
245 F->InterruptCallback();
246}
247
248void Fuzzer::CrashCallback() {
249 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000250 if (EF->__sanitizer_print_stack_trace)
251 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000252 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
253 " Combine libFuzzer with AddressSanitizer or similar for better "
254 "crash reports.\n");
255 Printf("SUMMARY: libFuzzer: deadly signal\n");
256 DumpCurrentUnit("crash-");
257 PrintFinalStats();
258 exit(Options.ErrorExitCode);
259}
260
261void Fuzzer::InterruptCallback() {
262 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
263 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000264 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000265}
266
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000267NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000268void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000269 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000270 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000271 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000272 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000273 size_t Seconds =
274 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000275 if (Seconds == 0)
276 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000277 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000278 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000279 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000280 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000281 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
282 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000283 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000284 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
285 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000286 if (EF->__sanitizer_print_stack_trace)
287 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000288 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000289 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000290 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000291 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000292}
293
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000294void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000295 Printf(
296 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
297 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000298 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000299 if (EF->__sanitizer_print_memory_profile)
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000300 EF->__sanitizer_print_memory_profile(95);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000301 DumpCurrentUnit("oom-");
302 Printf("SUMMARY: libFuzzer: out-of-memory\n");
303 PrintFinalStats();
304 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000305}
306
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000307void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000308 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000309 if (Options.OutputCSV) {
310 static bool csvHeaderPrinted = false;
311 if (!csvHeaderPrinted) {
312 csvHeaderPrinted = true;
313 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
314 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000315 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000316 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
317 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000318 }
319
320 if (!Options.Verbosity)
321 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000322 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000323 if (MaxCoverage.BlockCoverage)
324 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000325 if (size_t N = MaxCoverage.VPMap.GetNumBitsSinceLastMerge())
326 Printf(" vp: %zd", N);
Kostya Serebryany87a598e2016-09-23 01:20:07 +0000327 if (size_t N = TPC.GetTotalPCCoverage())
328 Printf(" cov: %zd", N);
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);
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000331 if (size_t N = Corpus.NumFeatures())
332 Printf( " ft: %zd", N);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000333 if (MaxCoverage.CallerCalleeCoverage)
334 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Reid Klecknerac2a2a82016-10-21 16:26:27 +0000335 if (!Corpus.empty()) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000336 Printf(" corp: %zd", Corpus.NumActiveUnits());
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000337 if (size_t N = Corpus.SizeInBytes()) {
338 if (N < (1<<14))
339 Printf("/%zdb", N);
340 else if (N < (1 << 24))
341 Printf("/%zdKb", N >> 10);
342 else
343 Printf("/%zdMb", N >> 20);
344 }
345 }
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000346 if (Units)
347 Printf(" units: %zd", Units);
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000348
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000349 Printf(" exec/s: %zd", ExecPerSec);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000350 Printf(" rss: %zdMb", GetPeakRSSMb());
Kostya Serebryany12c78372015-08-12 01:55:37 +0000351 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000352}
353
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000354void Fuzzer::PrintFinalStats() {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000355 if (Options.PrintCoverage)
356 TPC.PrintCoverage();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000357 if (Options.PrintCorpusStats)
358 Corpus.PrintStats();
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000359 if (!Options.PrintFinalStats) return;
360 size_t ExecPerSec = execPerSec();
361 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
362 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
363 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
364 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
365 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
366}
367
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000368void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
369 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
370 assert(MaxInputLen);
371 this->MaxInputLen = MaxInputLen;
372 this->MaxMutationLen = MaxInputLen;
373 AllocateCurrentUnitData();
374 Printf("INFO: -max_len is not provided, using %zd\n", MaxInputLen);
375}
376
377void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
378 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
379 this->MaxMutationLen = MaxMutationLen;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000380}
381
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000382void Fuzzer::CheckExitOnSrcPosOrItem() {
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000383 if (!Options.ExitOnSrcPos.empty()) {
Kostya Serebryany06b87572016-10-26 00:42:52 +0000384 for (size_t i = 1, N = TPC.GetNumPCs(); i < N; i++) {
385 uintptr_t PC = TPC.GetPC(i);
386 if (!PC) continue;
387 std::string Descr = DescribePC("%L", PC);
388 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
389 Printf("INFO: found line matching '%s', exiting.\n",
390 Options.ExitOnSrcPos.c_str());
391 _Exit(0);
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000392 }
393 }
394 }
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000395 if (!Options.ExitOnItem.empty()) {
396 if (Corpus.HasUnit(Options.ExitOnItem)) {
397 Printf("INFO: found item with checksum '%s', exiting.\n",
398 Options.ExitOnItem.c_str());
399 _Exit(0);
400 }
401 }
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000402}
403
Kostya Serebryany64d24572016-03-12 01:57:04 +0000404void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000405 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec) return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000406 std::vector<Unit> AdditionalCorpus;
407 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000408 &EpochOfLastReadOfOutputCorpus, MaxSize,
409 /*ExitOnError*/ false);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000410 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000411 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000412 bool Reloaded = false;
Kostya Serebryany90f8f362016-09-30 23:29:27 +0000413 for (auto &U : AdditionalCorpus) {
414 if (U.size() > MaxSize)
415 U.resize(MaxSize);
416 if (!Corpus.HasUnit(U)) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000417 if (size_t NumFeatures = RunOne(U)) {
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000418 CheckExitOnSrcPosOrItem();
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000419 Corpus.AddToCorpus(U, NumFeatures);
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000420 Reloaded = true;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000421 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000422 }
423 }
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000424 if (Reloaded)
425 PrintStats("RELOAD");
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000426}
427
Kostya Serebryany945761b2016-03-18 00:23:29 +0000428void Fuzzer::ShuffleCorpus(UnitVector *V) {
429 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
430 if (Options.PreferSmall)
431 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
432 return A.size() < B.size();
433 });
434}
435
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000436void Fuzzer::ShuffleAndMinimize(UnitVector *InitialCorpus) {
437 Printf("#0\tREAD units: %zd\n", InitialCorpus->size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000438 if (Options.ShuffleAtStartUp)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000439 ShuffleCorpus(InitialCorpus);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000440
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000441 // Test the callback with empty input and never try it again.
442 uint8_t dummy;
443 ExecuteCallback(&dummy, 0);
444
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000445 for (const auto &U : *InitialCorpus) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000446 if (size_t NumFeatures = RunOne(U)) {
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000447 CheckExitOnSrcPosOrItem();
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000448 Corpus.AddToCorpus(U, NumFeatures);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000449 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000450 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000451 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000452 TryDetectingAMemoryLeak(U.data(), U.size(),
453 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000454 }
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000455 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000456 if (Corpus.empty()) {
457 Printf("ERROR: no interesting inputs were found. "
458 "Is the code instrumented for coverage? Exiting.\n");
459 exit(1);
460 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000461}
462
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000463size_t Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
464 if (!Size) return 0;
Aaron Ballmanef116982015-01-29 16:58:29 +0000465 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000466
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000467 ExecuteCallback(Data, Size);
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000468
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000469 size_t Res = 0;
470 if (size_t NumFeatures = TPC.FinalizeTrace(&Corpus, Size, Options.Shrink))
471 Res = NumFeatures;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000472
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000473 if (!TPC.UsingTracePcGuard()) {
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000474 if (TPC.UpdateValueProfileMap(&MaxCoverage.VPMap))
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000475 Res = 1;
476 if (!Res && RecordMaxCoverage(&MaxCoverage))
477 Res = 1;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000478 }
479
Kostya Serebryany16901a92015-03-30 23:04:35 +0000480 auto TimeOfUnit =
481 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000482 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
483 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000484 PrintStats("pulse ");
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000485 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000486 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000487 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000488 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000489 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000490 }
491 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000492}
493
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000494size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000495 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000496 *Data = CurrentUnitData;
497 return CurrentUnitSize;
498}
499
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000500void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000501 assert(InFuzzingThread());
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000502 // We copy the contents of Unit into a separate heap buffer
503 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000504 uint8_t *DataCopy = new uint8_t[Size];
505 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000506 if (CurrentUnitData && CurrentUnitData != Data)
507 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000508 CurrentUnitSize = Size;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000509 AllocTracer.Start(Options.TraceMalloc);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000510 UnitStartTime = system_clock::now();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000511 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000512 TPC.ResetMaps();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000513 if (Options.UseCounters)
514 TPC.ResetGuards();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000515 int Res = CB(DataCopy, Size);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000516 UnitStopTime = system_clock::now();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000517 (void)Res;
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000518 assert(Res == 0);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000519 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000520 CurrentUnitSize = 0;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000521 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000522}
523
Aaron Ballmanef116982015-01-29 16:58:29 +0000524void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000525 if (Options.OnlyASCII)
526 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000527 if (Options.OutputCorpus.empty())
528 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000529 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
530 WriteToFile(U, Path);
531 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000532 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000533}
534
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000535void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000536 if (!Options.SaveArtifacts)
537 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000538 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000539 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000540 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000541 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000542 Printf("artifact_prefix='%s'; Test unit written to %s\n",
543 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000544 if (U.size() <= kMaxUnitSizeToPrint)
545 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000546}
547
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000548void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
549 if (!Options.PrintNEW)
550 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000551 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000552 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000553 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000554 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000555 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000556 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000557}
558
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000559void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
560 II->NumSuccessfullMutations++;
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000561 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000562 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000563 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000564 NumberOfNewUnitsAdded++;
Kostya Serebryanya5b2e542016-10-26 00:20:51 +0000565 TPC.PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000566}
567
Kostya Serebryany945761b2016-03-18 00:23:29 +0000568// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
569// We do it by actually executing the units, sometimes more than once,
570// because we may be using different coverage-like signals and the only
571// common thing between them is that we can say "this unit found new stuff".
572UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
573 const UnitVector &Extra) {
574 UnitVector Res = Extra;
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000575 UnitVector Tmp;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000576 size_t OldSize = Res.size();
577 for (int Iter = 0; Iter < 10; Iter++) {
578 ShuffleCorpus(&Res);
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000579 TPC.ResetMaps();
580 TPC.ResetGuards();
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000581 Corpus.ResetFeatureSet();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000582 ResetCoverage();
583
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000584 for (auto &U : Initial) {
585 TPC.ResetMaps();
586 TPC.ResetGuards();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000587 RunOne(U);
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000588 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000589
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000590 Tmp.clear();
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000591 for (auto &U : Res) {
592 TPC.ResetMaps();
593 TPC.ResetGuards();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000594 if (RunOne(U))
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000595 Tmp.push_back(U);
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000596 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000597
598 char Stat[7] = "MIN ";
599 Stat[3] = '0' + Iter;
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000600 PrintStats(Stat, "\n", Tmp.size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000601
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000602 size_t NewSize = Tmp.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000603 assert(NewSize <= OldSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000604 Res.swap(Tmp);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000605
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000606 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000607 break;
608 OldSize = NewSize;
609 }
610 return Res;
611}
612
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000613void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
614 if (Corpora.size() <= 1) {
615 Printf("Merge requires two or more corpus dirs\n");
616 return;
617 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000618 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000619 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
620
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000621 assert(MaxInputLen > 0);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000622 UnitVector Initial, Extra;
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000623 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, MaxInputLen, true);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000624 for (auto &C : ExtraCorpora)
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000625 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, MaxInputLen, true);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000626
627 if (!Initial.empty()) {
628 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
629 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000630 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000631
632 Printf("=== Merging extra %zd units\n", Extra.size());
633 auto Res = FindExtraUnits(Initial, Extra);
634
635 for (auto &U: Res)
636 WriteToOutputCorpus(U);
637
638 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000639}
640
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000641// Tries detecting a memory leak on the particular input that we have just
642// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000643void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
644 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000645 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
646 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000647 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
648 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000649 return; // No lsan.
650 // Run the target once again, but with lsan disabled so that if there is
651 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000652 EF->__lsan_disable();
Kostya Serebryany3b564e92016-10-05 23:31:01 +0000653 ExecuteCallback(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000654 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000655 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000656 if (NumberOfLeakDetectionAttempts++ > 1000) {
657 Options.DetectLeaks = false;
658 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
659 " Most likely the target function accumulates allocated\n"
660 " memory in a global state w/o actually leaking it.\n"
Kostya Serebryany03813742016-10-13 22:24:10 +0000661 " You may try running this binary with -trace_malloc=[12]"
662 " to get a trace of mallocs and frees.\n"
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000663 " If LeakSanitizer is enabled in this process it will still\n"
664 " run on the process shutdown.\n");
665 return;
666 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000667 // Now perform the actual lsan pass. This is expensive and we must ensure
668 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000669 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000670 if (DuringInitialCorpusExecution)
671 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
672 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000673 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000674 DumpCurrentUnit("leak-");
675 PrintFinalStats();
676 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
677 }
678}
679
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000680void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000681 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000682
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000683 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany20801e12016-09-21 21:41:48 +0000684 const auto &U = II.U;
685 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000686 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000687 size_t Size = U.size();
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000688 assert(Size <= MaxInputLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000689 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000690
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000691 assert(MaxMutationLen > 0);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000692
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000693 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000694 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
695 break;
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000696 size_t NewSize = 0;
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000697 NewSize = MD.Mutate(CurrentUnitData, Size, MaxMutationLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000698 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000699 assert(NewSize <= MaxMutationLen && "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000700 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000701 if (i == 0)
702 StartTraceRecording();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000703 II.NumExecutedMutations++;
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000704 if (size_t NumFeatures = RunOne(CurrentUnitData, Size)) {
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000705 Corpus.AddToCorpus({CurrentUnitData, CurrentUnitData + Size}, NumFeatures,
706 /*MayDeleteFile=*/true);
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000707 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000708 CheckExitOnSrcPosOrItem();
Kostya Serebryany90f8f362016-09-30 23:29:27 +0000709 }
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000710 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000711 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000712 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000713 }
714}
715
Kostya Serebryany945761b2016-03-18 00:23:29 +0000716void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000717 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000718 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000719 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000720}
721
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000722void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000723 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000724 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000725 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000726 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000727 auto Now = system_clock::now();
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000728 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
729 Options.ReloadIntervalSec) {
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000730 RereadOutputCorpus(MaxInputLen);
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000731 LastCorpusReload = system_clock::now();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000732 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000733 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000734 break;
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000735 if (TimedOut()) break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000736 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000737 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000738 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000739
740 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000741 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000742}
743
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000744void Fuzzer::MinimizeCrashLoop(const Unit &U) {
745 if (U.size() <= 2) return;
746 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
747 MD.StartMutationSequence();
748 memcpy(CurrentUnitData, U.data(), U.size());
749 for (int i = 0; i < Options.MutateDepth; i++) {
750 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
751 assert(NewSize > 0 && NewSize <= MaxMutationLen);
752 RunOne(CurrentUnitData, NewSize);
753 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
754 /*DuringInitialCorpusExecution*/ false);
755 }
756 }
757}
758
Ivan Krasindf919102016-01-22 22:28:27 +0000759} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000760
761extern "C" {
762
763size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
764 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000765 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000766}
767} // extern "C"