blob: 00dac2274f6fd2dce2cf880a11c77b36010aa5e9 [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
Kostya Serebryany29bb6642016-09-21 22:42:17 +000012#include "FuzzerCorpus.h"
Zachary Turner24a148b2016-11-30 19:06:14 +000013#include "FuzzerInternal.h"
14#include "FuzzerIO.h"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000015#include "FuzzerMutate.h"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000016#include "FuzzerRandom.h"
Zachary Turner24a148b2016-11-30 19:06:14 +000017#include "FuzzerTracePC.h"
Aaron Ballmanef116982015-01-29 16:58:29 +000018#include <algorithm>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000019#include <cstring>
20#include <memory>
Zachary Turner24a148b2016-11-30 19:06:14 +000021#include <set>
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
Kostya Serebryany3a4e2dd2016-12-16 22:45:25 +0000140ATTRIBUTE_NO_SANITIZE_MEMORY
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000141void MallocHook(const volatile void *ptr, size_t size) {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000142 size_t N = AllocTracer.Mallocs++;
Kostya Serebryany05f77912016-11-30 22:39:35 +0000143 F->HandleMalloc(size);
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000144 if (int TraceLevel = AllocTracer.TraceLevel) {
145 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
146 if (TraceLevel >= 2 && EF)
147 EF->__sanitizer_print_stack_trace();
148 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000149}
Kostya Serebryany3a4e2dd2016-12-16 22:45:25 +0000150
151ATTRIBUTE_NO_SANITIZE_MEMORY
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000152void FreeHook(const volatile void *ptr) {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000153 size_t N = AllocTracer.Frees++;
154 if (int TraceLevel = AllocTracer.TraceLevel) {
Kostya Serebryany03813742016-10-13 22:24:10 +0000155 Printf("FREE[%zd] %p\n", N, ptr);
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000156 if (TraceLevel >= 2 && EF)
157 EF->__sanitizer_print_stack_trace();
158 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000159}
160
Kostya Serebryany05f77912016-11-30 22:39:35 +0000161// Crash on a single malloc that exceeds the rss limit.
162void Fuzzer::HandleMalloc(size_t Size) {
Kostya Serebryanydc6b8ca2016-12-01 17:56:15 +0000163 if (!Options.RssLimitMb || (Size >> 20) < (size_t)Options.RssLimitMb)
Kostya Serebryany05f77912016-11-30 22:39:35 +0000164 return;
165 Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
166 Size);
167 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
168 if (EF->__sanitizer_print_stack_trace)
169 EF->__sanitizer_print_stack_trace();
170 DumpCurrentUnit("oom-");
171 Printf("SUMMARY: libFuzzer: out-of-memory\n");
172 PrintFinalStats();
173 _Exit(Options.ErrorExitCode); // Stop right now.
174}
175
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000176Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
177 FuzzingOptions Options)
178 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000179 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000180 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000181 assert(!F);
182 F = this;
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000183 TPC.ResetMaps();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000184 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000185 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000186 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
187 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000188 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000189 TPC.SetUseValueProfile(Options.UseValueProfile);
Kostya Serebryanya5b2e542016-10-26 00:20:51 +0000190 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000191
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000192 if (Options.Verbosity)
193 TPC.PrintModuleInfo();
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000194 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000195 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000196 MaxInputLen = MaxMutationLen = Options.MaxLen;
197 AllocateCurrentUnitData();
Kostya Serebryanyfe1094b2016-12-05 23:35:22 +0000198 CurrentUnitSize = 0;
199 memset(BaseSha1, 0, sizeof(BaseSha1));
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000200}
Aaron Ballmanef116982015-01-29 16:58:29 +0000201
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000202Fuzzer::~Fuzzer() { }
203
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000204void Fuzzer::AllocateCurrentUnitData() {
205 if (CurrentUnitData || MaxInputLen == 0) return;
206 CurrentUnitData = new uint8_t[MaxInputLen];
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000207}
208
Aaron Ballmanef116982015-01-29 16:58:29 +0000209void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000210 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
211 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000212}
213
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000214void Fuzzer::StaticDeathCallback() {
215 assert(F);
216 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000217}
218
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000219static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000220 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000221 Printf(
222 "***\n"
223 "***\n"
224 "***\n"
225 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
226 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
227 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
228 "*** Future versions may have crash-resistant merge, stay tuned.\n"
229 "***\n"
230 "***\n"
231 "***\n");
232}
233
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000234void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000235 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000236 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000237 MD.PrintMutationSequence();
238 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000239 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000240 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000241 PrintHexArray(CurrentUnitData, UnitSize, "\n");
242 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000243 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000244 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
245 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000246}
247
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000248NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000249void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000250 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000251 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000252}
253
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000254void Fuzzer::StaticAlarmCallback() {
255 assert(F);
256 F->AlarmCallback();
257}
258
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000259void Fuzzer::StaticCrashSignalCallback() {
260 assert(F);
261 F->CrashCallback();
262}
263
264void Fuzzer::StaticInterruptCallback() {
265 assert(F);
266 F->InterruptCallback();
267}
268
269void Fuzzer::CrashCallback() {
Marcos Pividori463f8bd2016-12-13 17:45:44 +0000270 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000271 if (EF->__sanitizer_print_stack_trace)
272 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000273 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
274 " Combine libFuzzer with AddressSanitizer or similar for better "
275 "crash reports.\n");
276 Printf("SUMMARY: libFuzzer: deadly signal\n");
277 DumpCurrentUnit("crash-");
278 PrintFinalStats();
279 exit(Options.ErrorExitCode);
280}
281
282void Fuzzer::InterruptCallback() {
Marcos Pividori463f8bd2016-12-13 17:45:44 +0000283 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000284 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000285 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000286}
287
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000288NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000289void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000290 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000291 if (!InFuzzingThread()) return;
Marcos Pividori64d41472016-12-13 17:46:25 +0000292 if (!RunningCB)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000293 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000294 size_t Seconds =
295 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000296 if (Seconds == 0)
297 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000298 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000299 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000300 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000301 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000302 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
303 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000304 DumpCurrentUnit("timeout-");
Marcos Pividori463f8bd2016-12-13 17:45:44 +0000305 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000306 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000307 if (EF->__sanitizer_print_stack_trace)
308 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000309 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000310 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000311 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000312 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000313}
314
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000315void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000316 Printf(
Marcos Pividori463f8bd2016-12-13 17:45:44 +0000317 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000318 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000319 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000320 if (EF->__sanitizer_print_memory_profile)
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000321 EF->__sanitizer_print_memory_profile(95);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000322 DumpCurrentUnit("oom-");
323 Printf("SUMMARY: libFuzzer: out-of-memory\n");
324 PrintFinalStats();
325 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000326}
327
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000328void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000329 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000330 if (Options.OutputCSV) {
331 static bool csvHeaderPrinted = false;
332 if (!csvHeaderPrinted) {
333 csvHeaderPrinted = true;
334 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
335 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000336 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000337 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
338 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000339 }
340
341 if (!Options.Verbosity)
342 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000343 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000344 if (MaxCoverage.BlockCoverage)
345 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000346 if (size_t N = MaxCoverage.VPMap.GetNumBitsSinceLastMerge())
347 Printf(" vp: %zd", N);
Kostya Serebryany87a598e2016-09-23 01:20:07 +0000348 if (size_t N = TPC.GetTotalPCCoverage())
349 Printf(" cov: %zd", N);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000350 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000351 Printf(" bits: %zd", TB);
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000352 if (size_t N = Corpus.NumFeatures())
353 Printf( " ft: %zd", N);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000354 if (MaxCoverage.CallerCalleeCoverage)
355 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Reid Klecknerac2a2a82016-10-21 16:26:27 +0000356 if (!Corpus.empty()) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000357 Printf(" corp: %zd", Corpus.NumActiveUnits());
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000358 if (size_t N = Corpus.SizeInBytes()) {
359 if (N < (1<<14))
360 Printf("/%zdb", N);
361 else if (N < (1 << 24))
362 Printf("/%zdKb", N >> 10);
363 else
364 Printf("/%zdMb", N >> 20);
365 }
366 }
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000367 if (Units)
368 Printf(" units: %zd", Units);
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000369
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000370 Printf(" exec/s: %zd", ExecPerSec);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000371 Printf(" rss: %zdMb", GetPeakRSSMb());
Kostya Serebryany12c78372015-08-12 01:55:37 +0000372 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000373}
374
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000375void Fuzzer::PrintFinalStats() {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000376 if (Options.PrintCoverage)
377 TPC.PrintCoverage();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000378 if (Options.PrintCorpusStats)
379 Corpus.PrintStats();
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000380 if (!Options.PrintFinalStats) return;
381 size_t ExecPerSec = execPerSec();
382 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
383 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
384 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
385 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
386 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
387}
388
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000389void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
390 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
391 assert(MaxInputLen);
392 this->MaxInputLen = MaxInputLen;
393 this->MaxMutationLen = MaxInputLen;
394 AllocateCurrentUnitData();
395 Printf("INFO: -max_len is not provided, using %zd\n", MaxInputLen);
396}
397
398void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
399 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
400 this->MaxMutationLen = MaxMutationLen;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000401}
402
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000403void Fuzzer::CheckExitOnSrcPosOrItem() {
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000404 if (!Options.ExitOnSrcPos.empty()) {
Kostya Serebryany2fabeca2016-10-26 18:52:04 +0000405 static auto *PCsSet = new std::set<uintptr_t>;
Kostya Serebryany06b87572016-10-26 00:42:52 +0000406 for (size_t i = 1, N = TPC.GetNumPCs(); i < N; i++) {
407 uintptr_t PC = TPC.GetPC(i);
408 if (!PC) continue;
Kostya Serebryany2fabeca2016-10-26 18:52:04 +0000409 if (!PCsSet->insert(PC).second) continue;
Kostya Serebryany06b87572016-10-26 00:42:52 +0000410 std::string Descr = DescribePC("%L", PC);
411 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
412 Printf("INFO: found line matching '%s', exiting.\n",
413 Options.ExitOnSrcPos.c_str());
414 _Exit(0);
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000415 }
416 }
417 }
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000418 if (!Options.ExitOnItem.empty()) {
419 if (Corpus.HasUnit(Options.ExitOnItem)) {
420 Printf("INFO: found item with checksum '%s', exiting.\n",
421 Options.ExitOnItem.c_str());
422 _Exit(0);
423 }
424 }
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000425}
426
Kostya Serebryany64d24572016-03-12 01:57:04 +0000427void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000428 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec) return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000429 std::vector<Unit> AdditionalCorpus;
430 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000431 &EpochOfLastReadOfOutputCorpus, MaxSize,
432 /*ExitOnError*/ false);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000433 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000434 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000435 bool Reloaded = false;
Kostya Serebryany90f8f362016-09-30 23:29:27 +0000436 for (auto &U : AdditionalCorpus) {
437 if (U.size() > MaxSize)
438 U.resize(MaxSize);
439 if (!Corpus.HasUnit(U)) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000440 if (size_t NumFeatures = RunOne(U)) {
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000441 CheckExitOnSrcPosOrItem();
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000442 Corpus.AddToCorpus(U, NumFeatures);
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000443 Reloaded = true;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000444 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000445 }
446 }
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000447 if (Reloaded)
448 PrintStats("RELOAD");
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000449}
450
Kostya Serebryany945761b2016-03-18 00:23:29 +0000451void Fuzzer::ShuffleCorpus(UnitVector *V) {
452 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
453 if (Options.PreferSmall)
454 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
455 return A.size() < B.size();
456 });
457}
458
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000459void Fuzzer::ShuffleAndMinimize(UnitVector *InitialCorpus) {
460 Printf("#0\tREAD units: %zd\n", InitialCorpus->size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000461 if (Options.ShuffleAtStartUp)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000462 ShuffleCorpus(InitialCorpus);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000463
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000464 // Test the callback with empty input and never try it again.
465 uint8_t dummy;
466 ExecuteCallback(&dummy, 0);
467
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000468 for (const auto &U : *InitialCorpus) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000469 if (size_t NumFeatures = RunOne(U)) {
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000470 CheckExitOnSrcPosOrItem();
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000471 Corpus.AddToCorpus(U, NumFeatures);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000472 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000473 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000474 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000475 TryDetectingAMemoryLeak(U.data(), U.size(),
476 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000477 }
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000478 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000479 if (Corpus.empty()) {
480 Printf("ERROR: no interesting inputs were found. "
481 "Is the code instrumented for coverage? Exiting.\n");
482 exit(1);
483 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000484}
485
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000486size_t Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
487 if (!Size) return 0;
Aaron Ballmanef116982015-01-29 16:58:29 +0000488 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000489
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000490 ExecuteCallback(Data, Size);
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000491
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000492 size_t Res = 0;
Kostya Serebryanyfe1094b2016-12-05 23:35:22 +0000493 if (size_t NumFeatures = TPC.CollectFeatures([&](size_t Feature) -> bool {
494 return Corpus.AddFeature(Feature, Size, Options.Shrink);
495 }))
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000496 Res = NumFeatures;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000497
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000498 if (!TPC.UsingTracePcGuard()) {
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000499 if (TPC.UpdateValueProfileMap(&MaxCoverage.VPMap))
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000500 Res = 1;
501 if (!Res && RecordMaxCoverage(&MaxCoverage))
502 Res = 1;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000503 }
504
Kostya Serebryany16901a92015-03-30 23:04:35 +0000505 auto TimeOfUnit =
506 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000507 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
508 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000509 PrintStats("pulse ");
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000510 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000511 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000512 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000513 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000514 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000515 }
516 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000517}
518
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000519size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000520 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000521 *Data = CurrentUnitData;
522 return CurrentUnitSize;
523}
524
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000525void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000526 assert(InFuzzingThread());
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000527 // We copy the contents of Unit into a separate heap buffer
528 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000529 uint8_t *DataCopy = new uint8_t[Size];
530 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000531 if (CurrentUnitData && CurrentUnitData != Data)
532 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000533 CurrentUnitSize = Size;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000534 AllocTracer.Start(Options.TraceMalloc);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000535 UnitStartTime = system_clock::now();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000536 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000537 TPC.ResetMaps();
Marcos Pividori64d41472016-12-13 17:46:25 +0000538 RunningCB = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000539 int Res = CB(DataCopy, Size);
Marcos Pividori64d41472016-12-13 17:46:25 +0000540 RunningCB = false;
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000541 UnitStopTime = system_clock::now();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000542 (void)Res;
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000543 assert(Res == 0);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000544 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000545 CurrentUnitSize = 0;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000546 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000547}
548
Aaron Ballmanef116982015-01-29 16:58:29 +0000549void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000550 if (Options.OnlyASCII)
551 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000552 if (Options.OutputCorpus.empty())
553 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000554 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
555 WriteToFile(U, Path);
556 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000557 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000558}
559
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000560void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000561 if (!Options.SaveArtifacts)
562 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000563 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000564 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000565 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000566 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000567 Printf("artifact_prefix='%s'; Test unit written to %s\n",
568 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000569 if (U.size() <= kMaxUnitSizeToPrint)
570 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000571}
572
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000573void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
574 if (!Options.PrintNEW)
575 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000576 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000577 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000578 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000579 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000580 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000581 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000582}
583
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000584void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
585 II->NumSuccessfullMutations++;
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000586 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000587 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000588 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000589 NumberOfNewUnitsAdded++;
Kostya Serebryanya5b2e542016-10-26 00:20:51 +0000590 TPC.PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000591}
592
Kostya Serebryany945761b2016-03-18 00:23:29 +0000593// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
594// We do it by actually executing the units, sometimes more than once,
595// because we may be using different coverage-like signals and the only
596// common thing between them is that we can say "this unit found new stuff".
597UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
598 const UnitVector &Extra) {
599 UnitVector Res = Extra;
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000600 UnitVector Tmp;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000601 size_t OldSize = Res.size();
602 for (int Iter = 0; Iter < 10; Iter++) {
603 ShuffleCorpus(&Res);
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000604 TPC.ResetMaps();
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000605 Corpus.ResetFeatureSet();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000606 ResetCoverage();
607
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000608 for (auto &U : Initial) {
609 TPC.ResetMaps();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000610 RunOne(U);
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000611 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000612
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000613 Tmp.clear();
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000614 for (auto &U : Res) {
615 TPC.ResetMaps();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000616 if (RunOne(U))
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000617 Tmp.push_back(U);
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000618 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000619
620 char Stat[7] = "MIN ";
621 Stat[3] = '0' + Iter;
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000622 PrintStats(Stat, "\n", Tmp.size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000623
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000624 size_t NewSize = Tmp.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000625 assert(NewSize <= OldSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000626 Res.swap(Tmp);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000627
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000628 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000629 break;
630 OldSize = NewSize;
631 }
632 return Res;
633}
634
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000635void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
636 if (Corpora.size() <= 1) {
637 Printf("Merge requires two or more corpus dirs\n");
638 return;
639 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000640 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000641 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
642
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000643 assert(MaxInputLen > 0);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000644 UnitVector Initial, Extra;
Kostya Serebryanyd4be8892016-12-12 20:39:35 +0000645 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, MaxInputLen,
646 true);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000647 for (auto &C : ExtraCorpora)
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000648 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, MaxInputLen, true);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000649
650 if (!Initial.empty()) {
651 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
652 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000653 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000654
655 Printf("=== Merging extra %zd units\n", Extra.size());
656 auto Res = FindExtraUnits(Initial, Extra);
657
658 for (auto &U: Res)
659 WriteToOutputCorpus(U);
660
661 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000662}
663
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000664// Tries detecting a memory leak on the particular input that we have just
665// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000666void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
667 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000668 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
669 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000670 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
671 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000672 return; // No lsan.
673 // Run the target once again, but with lsan disabled so that if there is
674 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000675 EF->__lsan_disable();
Kostya Serebryany3b564e92016-10-05 23:31:01 +0000676 ExecuteCallback(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000677 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000678 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000679 if (NumberOfLeakDetectionAttempts++ > 1000) {
680 Options.DetectLeaks = false;
681 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
682 " Most likely the target function accumulates allocated\n"
683 " memory in a global state w/o actually leaking it.\n"
Kostya Serebryany03813742016-10-13 22:24:10 +0000684 " You may try running this binary with -trace_malloc=[12]"
685 " to get a trace of mallocs and frees.\n"
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000686 " If LeakSanitizer is enabled in this process it will still\n"
687 " run on the process shutdown.\n");
688 return;
689 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000690 // Now perform the actual lsan pass. This is expensive and we must ensure
691 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000692 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000693 if (DuringInitialCorpusExecution)
694 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
695 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000696 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000697 DumpCurrentUnit("leak-");
698 PrintFinalStats();
699 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
700 }
701}
702
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000703void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000704 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000705
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000706 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany20801e12016-09-21 21:41:48 +0000707 const auto &U = II.U;
708 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000709 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000710 size_t Size = U.size();
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000711 assert(Size <= MaxInputLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000712 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000713
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000714 assert(MaxMutationLen > 0);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000715
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000716 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000717 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
718 break;
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000719 size_t NewSize = 0;
Daniel Jasperfa1030e2016-12-17 12:27:49 +0000720 NewSize = MD.Mutate(CurrentUnitData, Size, MaxMutationLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000721 assert(NewSize > 0 && "Mutator returned empty unit");
Daniel Jasperfa1030e2016-12-17 12:27:49 +0000722 assert(NewSize <= MaxMutationLen && "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000723 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000724 if (i == 0)
725 StartTraceRecording();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000726 II.NumExecutedMutations++;
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000727 if (size_t NumFeatures = RunOne(CurrentUnitData, Size)) {
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000728 Corpus.AddToCorpus({CurrentUnitData, CurrentUnitData + Size}, NumFeatures,
729 /*MayDeleteFile=*/true);
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000730 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000731 CheckExitOnSrcPosOrItem();
Kostya Serebryany90f8f362016-09-30 23:29:27 +0000732 }
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000733 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000734 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000735 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000736 }
737}
738
Kostya Serebryany945761b2016-03-18 00:23:29 +0000739void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000740 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000741 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000742 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000743}
744
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000745void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000746 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000747 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000748 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000749 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000750 auto Now = system_clock::now();
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000751 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
752 Options.ReloadIntervalSec) {
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000753 RereadOutputCorpus(MaxInputLen);
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000754 LastCorpusReload = system_clock::now();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000755 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000756 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000757 break;
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000758 if (TimedOut()) break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000759 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000760 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000761 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000762
763 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000764 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000765}
766
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000767void Fuzzer::MinimizeCrashLoop(const Unit &U) {
768 if (U.size() <= 2) return;
769 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
770 MD.StartMutationSequence();
771 memcpy(CurrentUnitData, U.data(), U.size());
772 for (int i = 0; i < Options.MutateDepth; i++) {
773 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
774 assert(NewSize > 0 && NewSize <= MaxMutationLen);
775 RunOne(CurrentUnitData, NewSize);
776 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
777 /*DuringInitialCorpusExecution*/ false);
778 }
779 }
780}
781
Ivan Krasindf919102016-01-22 22:28:27 +0000782} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000783
784extern "C" {
785
786size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
787 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000788 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000789}
790} // extern "C"