blob: 0d2a38b6a8544b21abf7a204599e49f07e8315c0 [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>
Kostya Serebryany2fabeca2016-10-26 18:52:04 +000020#include <set>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000021#include <memory>
Aaron Ballmanef116982015-01-29 16:58:29 +000022
Kostya Serebryany2a48c242015-11-13 01:54:40 +000023#if defined(__has_include)
Ivan Krasindf919102016-01-22 22:28:27 +000024#if __has_include(<sanitizer / coverage_interface.h>)
25#include <sanitizer/coverage_interface.h>
26#endif
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000027#if __has_include(<sanitizer / lsan_interface.h>)
28#include <sanitizer/lsan_interface.h>
29#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000030#endif
31
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000032#define NO_SANITIZE_MEMORY
33#if defined(__has_feature)
34#if __has_feature(memory_sanitizer)
35#undef NO_SANITIZE_MEMORY
36#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
37#endif
38#endif
39
Aaron Ballmanef116982015-01-29 16:58:29 +000040namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000041static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000042
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000043thread_local bool Fuzzer::IsMyThread;
44
Dan Liew1873a492016-06-07 23:32:50 +000045static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000046 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000047 "Did you use -fsanitize-coverage=... to build your code?\n",
48 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000049 exit(1);
50}
51
Dan Liew1873a492016-06-07 23:32:50 +000052#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000053 do { \
Dan Liew1873a492016-06-07 23:32:50 +000054 if (!(EF->fn)) \
55 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000056 } while (false)
57
Kostya Serebryany52a788e2015-03-31 20:13:20 +000058// Only one Fuzzer per process.
59static Fuzzer *F;
60
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000061void Fuzzer::ResetEdgeCoverage() {
62 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
63 EF->__sanitizer_reset_coverage();
64}
65
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000066void Fuzzer::ResetCounters() {
Kostya Serebryanyb3949ef2016-09-30 01:24:57 +000067 if (Options.UseCounters)
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000068 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000069}
70
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000071void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
72 if (Options.UseCounters) {
73 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
74 C->CounterBitmap.resize(NumCounters);
75 }
76}
77
78// Records data to a maximum coverage tracker. Returns true if additional
79// coverage was discovered.
80bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
81 bool Res = false;
82
Kostya Serebryany87a598e2016-09-23 01:20:07 +000083 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000084 if (NewBlockCoverage > C->BlockCoverage) {
85 Res = true;
86 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000087 }
88
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000089 if (Options.UseIndirCalls &&
90 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
91 uint64_t NewCallerCalleeCoverage =
92 EF->__sanitizer_get_total_unique_caller_callee_pairs();
93 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000094 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000095 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000096 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000097 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000098
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000099 if (Options.UseCounters) {
100 uint64_t CounterDelta =
101 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000102 C->CounterBitmap.data());
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000103 if (CounterDelta > 0) {
104 Res = true;
105 C->CounterBitmapBits += CounterDelta;
106 }
107 }
108
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000109 return Res;
110}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000111
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000112// Leak detection is expensive, so we first check if there were more mallocs
113// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
114struct MallocFreeTracer {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000115 void Start(int TraceLevel) {
116 this->TraceLevel = TraceLevel;
117 if (TraceLevel)
118 Printf("MallocFreeTracer: START\n");
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000119 Mallocs = 0;
120 Frees = 0;
121 }
122 // Returns true if there were more mallocs than frees.
Kostya Serebryany03813742016-10-13 22:24:10 +0000123 bool Stop() {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000124 if (TraceLevel)
125 Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
126 Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
127 bool Result = Mallocs > Frees;
128 Mallocs = 0;
129 Frees = 0;
130 TraceLevel = 0;
131 return Result;
132 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000133 std::atomic<size_t> Mallocs;
134 std::atomic<size_t> Frees;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000135 int TraceLevel = 0;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000136};
137
138static MallocFreeTracer AllocTracer;
139
140void MallocHook(const volatile void *ptr, size_t size) {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000141 size_t N = AllocTracer.Mallocs++;
142 if (int TraceLevel = AllocTracer.TraceLevel) {
143 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
144 if (TraceLevel >= 2 && EF)
145 EF->__sanitizer_print_stack_trace();
146 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000147}
148void FreeHook(const volatile void *ptr) {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000149 size_t N = AllocTracer.Frees++;
150 if (int TraceLevel = AllocTracer.TraceLevel) {
Kostya Serebryany03813742016-10-13 22:24:10 +0000151 Printf("FREE[%zd] %p\n", N, ptr);
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000152 if (TraceLevel >= 2 && EF)
153 EF->__sanitizer_print_stack_trace();
154 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000155}
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 Serebryanyce1cab12016-09-23 02:18:59 +0000164 TPC.ResetMaps();
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 Serebryany2fabeca2016-10-26 18:52:04 +0000384 static auto *PCsSet = new std::set<uintptr_t>;
Kostya Serebryany06b87572016-10-26 00:42:52 +0000385 for (size_t i = 1, N = TPC.GetNumPCs(); i < N; i++) {
386 uintptr_t PC = TPC.GetPC(i);
387 if (!PC) continue;
Kostya Serebryany2fabeca2016-10-26 18:52:04 +0000388 if (!PCsSet->insert(PC).second) continue;
Kostya Serebryany06b87572016-10-26 00:42:52 +0000389 std::string Descr = DescribePC("%L", PC);
390 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
391 Printf("INFO: found line matching '%s', exiting.\n",
392 Options.ExitOnSrcPos.c_str());
393 _Exit(0);
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000394 }
395 }
396 }
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000397 if (!Options.ExitOnItem.empty()) {
398 if (Corpus.HasUnit(Options.ExitOnItem)) {
399 Printf("INFO: found item with checksum '%s', exiting.\n",
400 Options.ExitOnItem.c_str());
401 _Exit(0);
402 }
403 }
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000404}
405
Kostya Serebryany64d24572016-03-12 01:57:04 +0000406void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000407 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec) return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000408 std::vector<Unit> AdditionalCorpus;
409 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000410 &EpochOfLastReadOfOutputCorpus, MaxSize,
411 /*ExitOnError*/ false);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000412 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000413 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000414 bool Reloaded = false;
Kostya Serebryany90f8f362016-09-30 23:29:27 +0000415 for (auto &U : AdditionalCorpus) {
416 if (U.size() > MaxSize)
417 U.resize(MaxSize);
418 if (!Corpus.HasUnit(U)) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000419 if (size_t NumFeatures = RunOne(U)) {
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000420 CheckExitOnSrcPosOrItem();
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000421 Corpus.AddToCorpus(U, NumFeatures);
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000422 Reloaded = true;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000423 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000424 }
425 }
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000426 if (Reloaded)
427 PrintStats("RELOAD");
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000428}
429
Kostya Serebryany945761b2016-03-18 00:23:29 +0000430void Fuzzer::ShuffleCorpus(UnitVector *V) {
431 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
432 if (Options.PreferSmall)
433 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
434 return A.size() < B.size();
435 });
436}
437
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000438void Fuzzer::ShuffleAndMinimize(UnitVector *InitialCorpus) {
439 Printf("#0\tREAD units: %zd\n", InitialCorpus->size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000440 if (Options.ShuffleAtStartUp)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000441 ShuffleCorpus(InitialCorpus);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000442
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000443 // Test the callback with empty input and never try it again.
444 uint8_t dummy;
445 ExecuteCallback(&dummy, 0);
446
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000447 for (const auto &U : *InitialCorpus) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000448 if (size_t NumFeatures = RunOne(U)) {
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000449 CheckExitOnSrcPosOrItem();
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000450 Corpus.AddToCorpus(U, NumFeatures);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000451 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000452 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000453 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000454 TryDetectingAMemoryLeak(U.data(), U.size(),
455 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000456 }
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000457 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000458 if (Corpus.empty()) {
459 Printf("ERROR: no interesting inputs were found. "
460 "Is the code instrumented for coverage? Exiting.\n");
461 exit(1);
462 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000463}
464
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000465size_t Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
466 if (!Size) return 0;
Aaron Ballmanef116982015-01-29 16:58:29 +0000467 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000468
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000469 ExecuteCallback(Data, Size);
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000470
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000471 size_t Res = 0;
472 if (size_t NumFeatures = TPC.FinalizeTrace(&Corpus, Size, Options.Shrink))
473 Res = NumFeatures;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000474
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000475 if (!TPC.UsingTracePcGuard()) {
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000476 if (TPC.UpdateValueProfileMap(&MaxCoverage.VPMap))
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000477 Res = 1;
478 if (!Res && RecordMaxCoverage(&MaxCoverage))
479 Res = 1;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000480 }
481
Kostya Serebryany16901a92015-03-30 23:04:35 +0000482 auto TimeOfUnit =
483 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000484 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
485 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000486 PrintStats("pulse ");
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000487 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000488 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000489 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000490 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000491 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000492 }
493 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000494}
495
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000496size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000497 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000498 *Data = CurrentUnitData;
499 return CurrentUnitSize;
500}
501
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000502void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000503 assert(InFuzzingThread());
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000504 // We copy the contents of Unit into a separate heap buffer
505 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000506 uint8_t *DataCopy = new uint8_t[Size];
507 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000508 if (CurrentUnitData && CurrentUnitData != Data)
509 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000510 CurrentUnitSize = Size;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000511 AllocTracer.Start(Options.TraceMalloc);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000512 UnitStartTime = system_clock::now();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000513 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000514 TPC.ResetMaps();
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();
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000580 Corpus.ResetFeatureSet();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000581 ResetCoverage();
582
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000583 for (auto &U : Initial) {
584 TPC.ResetMaps();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000585 RunOne(U);
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000586 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000587
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000588 Tmp.clear();
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000589 for (auto &U : Res) {
590 TPC.ResetMaps();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000591 if (RunOne(U))
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000592 Tmp.push_back(U);
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000593 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000594
595 char Stat[7] = "MIN ";
596 Stat[3] = '0' + Iter;
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000597 PrintStats(Stat, "\n", Tmp.size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000598
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000599 size_t NewSize = Tmp.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000600 assert(NewSize <= OldSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000601 Res.swap(Tmp);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000602
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000603 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000604 break;
605 OldSize = NewSize;
606 }
607 return Res;
608}
609
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000610void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
611 if (Corpora.size() <= 1) {
612 Printf("Merge requires two or more corpus dirs\n");
613 return;
614 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000615 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000616 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
617
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000618 assert(MaxInputLen > 0);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000619 UnitVector Initial, Extra;
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000620 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, MaxInputLen, true);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000621 for (auto &C : ExtraCorpora)
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000622 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, MaxInputLen, true);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000623
624 if (!Initial.empty()) {
625 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
626 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000627 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000628
629 Printf("=== Merging extra %zd units\n", Extra.size());
630 auto Res = FindExtraUnits(Initial, Extra);
631
632 for (auto &U: Res)
633 WriteToOutputCorpus(U);
634
635 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000636}
637
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000638// Tries detecting a memory leak on the particular input that we have just
639// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000640void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
641 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000642 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
643 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000644 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
645 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000646 return; // No lsan.
647 // Run the target once again, but with lsan disabled so that if there is
648 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000649 EF->__lsan_disable();
Kostya Serebryany3b564e92016-10-05 23:31:01 +0000650 ExecuteCallback(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000651 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000652 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000653 if (NumberOfLeakDetectionAttempts++ > 1000) {
654 Options.DetectLeaks = false;
655 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
656 " Most likely the target function accumulates allocated\n"
657 " memory in a global state w/o actually leaking it.\n"
Kostya Serebryany03813742016-10-13 22:24:10 +0000658 " You may try running this binary with -trace_malloc=[12]"
659 " to get a trace of mallocs and frees.\n"
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000660 " If LeakSanitizer is enabled in this process it will still\n"
661 " run on the process shutdown.\n");
662 return;
663 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000664 // Now perform the actual lsan pass. This is expensive and we must ensure
665 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000666 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000667 if (DuringInitialCorpusExecution)
668 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
669 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000670 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000671 DumpCurrentUnit("leak-");
672 PrintFinalStats();
673 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
674 }
675}
676
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000677void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000678 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000679
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000680 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany20801e12016-09-21 21:41:48 +0000681 const auto &U = II.U;
682 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000683 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000684 size_t Size = U.size();
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000685 assert(Size <= MaxInputLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000686 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000687
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000688 assert(MaxMutationLen > 0);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000689
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000690 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000691 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
692 break;
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000693 size_t NewSize = 0;
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000694 NewSize = MD.Mutate(CurrentUnitData, Size, MaxMutationLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000695 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000696 assert(NewSize <= MaxMutationLen && "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000697 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000698 if (i == 0)
699 StartTraceRecording();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000700 II.NumExecutedMutations++;
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000701 if (size_t NumFeatures = RunOne(CurrentUnitData, Size)) {
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000702 Corpus.AddToCorpus({CurrentUnitData, CurrentUnitData + Size}, NumFeatures,
703 /*MayDeleteFile=*/true);
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000704 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000705 CheckExitOnSrcPosOrItem();
Kostya Serebryany90f8f362016-09-30 23:29:27 +0000706 }
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000707 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000708 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000709 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000710 }
711}
712
Kostya Serebryany945761b2016-03-18 00:23:29 +0000713void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000714 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000715 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000716 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000717}
718
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000719void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000720 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000721 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000722 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000723 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000724 auto Now = system_clock::now();
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000725 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
726 Options.ReloadIntervalSec) {
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000727 RereadOutputCorpus(MaxInputLen);
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000728 LastCorpusReload = system_clock::now();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000729 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000730 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000731 break;
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000732 if (TimedOut()) break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000733 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000734 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000735 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000736
737 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000738 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000739}
740
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000741void Fuzzer::MinimizeCrashLoop(const Unit &U) {
742 if (U.size() <= 2) return;
743 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
744 MD.StartMutationSequence();
745 memcpy(CurrentUnitData, U.data(), U.size());
746 for (int i = 0; i < Options.MutateDepth; i++) {
747 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
748 assert(NewSize > 0 && NewSize <= MaxMutationLen);
749 RunOne(CurrentUnitData, NewSize);
750 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
751 /*DuringInitialCorpusExecution*/ false);
752 }
753 }
754}
755
Ivan Krasindf919102016-01-22 22:28:27 +0000756} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000757
758extern "C" {
759
760size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
761 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000762 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000763}
764} // extern "C"