blob: f96fc7416ff22cbe6d4ed0286048e36dd868ae24 [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"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000018
Aaron Ballmanef116982015-01-29 16:58:29 +000019#include <algorithm>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000020#include <cstring>
21#include <memory>
Zachary Turner24a148b2016-11-30 19:06:14 +000022#include <set>
Aaron Ballmanef116982015-01-29 16:58:29 +000023
Kostya Serebryany2a48c242015-11-13 01:54:40 +000024#if defined(__has_include)
Ivan Krasindf919102016-01-22 22:28:27 +000025#if __has_include(<sanitizer / coverage_interface.h>)
26#include <sanitizer/coverage_interface.h>
27#endif
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000028#if __has_include(<sanitizer / lsan_interface.h>)
29#include <sanitizer/lsan_interface.h>
30#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000031#endif
32
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000033#define NO_SANITIZE_MEMORY
34#if defined(__has_feature)
35#if __has_feature(memory_sanitizer)
36#undef NO_SANITIZE_MEMORY
37#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
38#endif
39#endif
40
Aaron Ballmanef116982015-01-29 16:58:29 +000041namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000042static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000043
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000044thread_local bool Fuzzer::IsMyThread;
45
Dan Liew1873a492016-06-07 23:32:50 +000046static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000047 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000048 "Did you use -fsanitize-coverage=... to build your code?\n",
49 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000050 exit(1);
51}
52
Dan Liew1873a492016-06-07 23:32:50 +000053#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000054 do { \
Dan Liew1873a492016-06-07 23:32:50 +000055 if (!(EF->fn)) \
56 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000057 } while (false)
58
Kostya Serebryany52a788e2015-03-31 20:13:20 +000059// Only one Fuzzer per process.
60static Fuzzer *F;
61
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000062void Fuzzer::ResetEdgeCoverage() {
63 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
64 EF->__sanitizer_reset_coverage();
65}
66
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000067void Fuzzer::ResetCounters() {
Kostya Serebryanyb3949ef2016-09-30 01:24:57 +000068 if (Options.UseCounters)
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000069 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000070}
71
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000072void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
73 if (Options.UseCounters) {
74 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
75 C->CounterBitmap.resize(NumCounters);
76 }
77}
78
79// Records data to a maximum coverage tracker. Returns true if additional
80// coverage was discovered.
81bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
82 bool Res = false;
83
Kostya Serebryany87a598e2016-09-23 01:20:07 +000084 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000085 if (NewBlockCoverage > C->BlockCoverage) {
86 Res = true;
87 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000088 }
89
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000090 if (Options.UseIndirCalls &&
91 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
92 uint64_t NewCallerCalleeCoverage =
93 EF->__sanitizer_get_total_unique_caller_callee_pairs();
94 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000095 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000096 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000097 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000098 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000099
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000100 if (Options.UseCounters) {
101 uint64_t CounterDelta =
102 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Kostya Serebryanyd28099d2016-09-23 00:22:46 +0000103 C->CounterBitmap.data());
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000104 if (CounterDelta > 0) {
105 Res = true;
106 C->CounterBitmapBits += CounterDelta;
107 }
108 }
109
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000110 return Res;
111}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000112
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000113// Leak detection is expensive, so we first check if there were more mallocs
114// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
115struct MallocFreeTracer {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000116 void Start(int TraceLevel) {
117 this->TraceLevel = TraceLevel;
118 if (TraceLevel)
119 Printf("MallocFreeTracer: START\n");
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000120 Mallocs = 0;
121 Frees = 0;
122 }
123 // Returns true if there were more mallocs than frees.
Kostya Serebryany03813742016-10-13 22:24:10 +0000124 bool Stop() {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000125 if (TraceLevel)
126 Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
127 Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
128 bool Result = Mallocs > Frees;
129 Mallocs = 0;
130 Frees = 0;
131 TraceLevel = 0;
132 return Result;
133 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000134 std::atomic<size_t> Mallocs;
135 std::atomic<size_t> Frees;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000136 int TraceLevel = 0;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000137};
138
139static MallocFreeTracer AllocTracer;
140
141void 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}
150void FreeHook(const volatile void *ptr) {
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000151 size_t N = AllocTracer.Frees++;
152 if (int TraceLevel = AllocTracer.TraceLevel) {
Kostya Serebryany03813742016-10-13 22:24:10 +0000153 Printf("FREE[%zd] %p\n", N, ptr);
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000154 if (TraceLevel >= 2 && EF)
155 EF->__sanitizer_print_stack_trace();
156 }
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000157}
158
Kostya Serebryany05f77912016-11-30 22:39:35 +0000159// Crash on a single malloc that exceeds the rss limit.
160void Fuzzer::HandleMalloc(size_t Size) {
Kostya Serebryanydc6b8ca2016-12-01 17:56:15 +0000161 if (!Options.RssLimitMb || (Size >> 20) < (size_t)Options.RssLimitMb)
Kostya Serebryany05f77912016-11-30 22:39:35 +0000162 return;
163 Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
164 Size);
165 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
166 if (EF->__sanitizer_print_stack_trace)
167 EF->__sanitizer_print_stack_trace();
168 DumpCurrentUnit("oom-");
169 Printf("SUMMARY: libFuzzer: out-of-memory\n");
170 PrintFinalStats();
171 _Exit(Options.ErrorExitCode); // Stop right now.
172}
173
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000174Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
175 FuzzingOptions Options)
176 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000177 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000178 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000179 assert(!F);
180 F = this;
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000181 TPC.ResetMaps();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000182 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000183 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000184 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
185 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000186 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryanyab73c692016-09-23 00:46:18 +0000187 TPC.SetUseValueProfile(Options.UseValueProfile);
Kostya Serebryanya5b2e542016-10-26 00:20:51 +0000188 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000189
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000190 if (Options.Verbosity)
191 TPC.PrintModuleInfo();
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000192 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000193 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000194 MaxInputLen = MaxMutationLen = Options.MaxLen;
195 AllocateCurrentUnitData();
Kostya Serebryanyfe1094b2016-12-05 23:35:22 +0000196 CurrentUnitSize = 0;
197 memset(BaseSha1, 0, sizeof(BaseSha1));
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000198}
Aaron Ballmanef116982015-01-29 16:58:29 +0000199
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000200Fuzzer::~Fuzzer() { }
201
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000202void Fuzzer::AllocateCurrentUnitData() {
203 if (CurrentUnitData || MaxInputLen == 0) return;
204 CurrentUnitData = new uint8_t[MaxInputLen];
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000205}
206
Aaron Ballmanef116982015-01-29 16:58:29 +0000207void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000208 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
209 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000210}
211
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000212void Fuzzer::StaticDeathCallback() {
213 assert(F);
214 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000215}
216
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000217static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000218 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000219 Printf(
220 "***\n"
221 "***\n"
222 "***\n"
223 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
224 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
225 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
226 "*** Future versions may have crash-resistant merge, stay tuned.\n"
227 "***\n"
228 "***\n"
229 "***\n");
230}
231
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000232void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000233 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000234 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000235 MD.PrintMutationSequence();
236 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000237 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000238 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000239 PrintHexArray(CurrentUnitData, UnitSize, "\n");
240 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000241 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000242 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
243 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000244}
245
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000246NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000247void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000248 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000249 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000250}
251
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000252void Fuzzer::StaticAlarmCallback() {
253 assert(F);
254 F->AlarmCallback();
255}
256
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000257void Fuzzer::StaticCrashSignalCallback() {
258 assert(F);
259 F->CrashCallback();
260}
261
262void Fuzzer::StaticInterruptCallback() {
263 assert(F);
264 F->InterruptCallback();
265}
266
267void Fuzzer::CrashCallback() {
Marcos Pividori463f8bd2016-12-13 17:45:44 +0000268 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000269 if (EF->__sanitizer_print_stack_trace)
270 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000271 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
272 " Combine libFuzzer with AddressSanitizer or similar for better "
273 "crash reports.\n");
274 Printf("SUMMARY: libFuzzer: deadly signal\n");
275 DumpCurrentUnit("crash-");
276 PrintFinalStats();
277 exit(Options.ErrorExitCode);
278}
279
280void Fuzzer::InterruptCallback() {
Marcos Pividori463f8bd2016-12-13 17:45:44 +0000281 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000282 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000283 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000284}
285
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000286NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000287void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000288 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000289 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000290 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000291 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000292 size_t Seconds =
293 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000294 if (Seconds == 0)
295 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000296 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000297 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000298 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000299 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000300 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
301 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000302 DumpCurrentUnit("timeout-");
Marcos Pividori463f8bd2016-12-13 17:45:44 +0000303 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000304 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000305 if (EF->__sanitizer_print_stack_trace)
306 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000307 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000308 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000309 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000310 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000311}
312
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000313void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000314 Printf(
Marcos Pividori463f8bd2016-12-13 17:45:44 +0000315 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000316 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000317 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000318 if (EF->__sanitizer_print_memory_profile)
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000319 EF->__sanitizer_print_memory_profile(95);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000320 DumpCurrentUnit("oom-");
321 Printf("SUMMARY: libFuzzer: out-of-memory\n");
322 PrintFinalStats();
323 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000324}
325
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000326void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000327 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000328 if (Options.OutputCSV) {
329 static bool csvHeaderPrinted = false;
330 if (!csvHeaderPrinted) {
331 csvHeaderPrinted = true;
332 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
333 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000334 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000335 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
336 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000337 }
338
339 if (!Options.Verbosity)
340 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000341 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000342 if (MaxCoverage.BlockCoverage)
343 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000344 if (size_t N = MaxCoverage.VPMap.GetNumBitsSinceLastMerge())
345 Printf(" vp: %zd", N);
Kostya Serebryany87a598e2016-09-23 01:20:07 +0000346 if (size_t N = TPC.GetTotalPCCoverage())
347 Printf(" cov: %zd", N);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000348 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000349 Printf(" bits: %zd", TB);
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000350 if (size_t N = Corpus.NumFeatures())
351 Printf( " ft: %zd", N);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000352 if (MaxCoverage.CallerCalleeCoverage)
353 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Reid Klecknerac2a2a82016-10-21 16:26:27 +0000354 if (!Corpus.empty()) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000355 Printf(" corp: %zd", Corpus.NumActiveUnits());
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000356 if (size_t N = Corpus.SizeInBytes()) {
357 if (N < (1<<14))
358 Printf("/%zdb", N);
359 else if (N < (1 << 24))
360 Printf("/%zdKb", N >> 10);
361 else
362 Printf("/%zdMb", N >> 20);
363 }
364 }
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000365 if (Units)
366 Printf(" units: %zd", Units);
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000367
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000368 Printf(" exec/s: %zd", ExecPerSec);
Kostya Serebryany936b1e72016-10-06 05:14:00 +0000369 Printf(" rss: %zdMb", GetPeakRSSMb());
Kostya Serebryany12c78372015-08-12 01:55:37 +0000370 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000371}
372
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000373void Fuzzer::PrintFinalStats() {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000374 if (Options.PrintCoverage)
375 TPC.PrintCoverage();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000376 if (Options.PrintCorpusStats)
377 Corpus.PrintStats();
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000378 if (!Options.PrintFinalStats) return;
379 size_t ExecPerSec = execPerSec();
380 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
381 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
382 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
383 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
384 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
385}
386
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000387void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
388 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
389 assert(MaxInputLen);
390 this->MaxInputLen = MaxInputLen;
391 this->MaxMutationLen = MaxInputLen;
392 AllocateCurrentUnitData();
393 Printf("INFO: -max_len is not provided, using %zd\n", MaxInputLen);
394}
395
396void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
397 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
398 this->MaxMutationLen = MaxMutationLen;
Kostya Serebryany64d24572016-03-12 01:57:04 +0000399}
400
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000401void Fuzzer::CheckExitOnSrcPosOrItem() {
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000402 if (!Options.ExitOnSrcPos.empty()) {
Kostya Serebryany2fabeca2016-10-26 18:52:04 +0000403 static auto *PCsSet = new std::set<uintptr_t>;
Kostya Serebryany06b87572016-10-26 00:42:52 +0000404 for (size_t i = 1, N = TPC.GetNumPCs(); i < N; i++) {
405 uintptr_t PC = TPC.GetPC(i);
406 if (!PC) continue;
Kostya Serebryany2fabeca2016-10-26 18:52:04 +0000407 if (!PCsSet->insert(PC).second) continue;
Kostya Serebryany06b87572016-10-26 00:42:52 +0000408 std::string Descr = DescribePC("%L", PC);
409 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
410 Printf("INFO: found line matching '%s', exiting.\n",
411 Options.ExitOnSrcPos.c_str());
412 _Exit(0);
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000413 }
414 }
415 }
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000416 if (!Options.ExitOnItem.empty()) {
417 if (Corpus.HasUnit(Options.ExitOnItem)) {
418 Printf("INFO: found item with checksum '%s', exiting.\n",
419 Options.ExitOnItem.c_str());
420 _Exit(0);
421 }
422 }
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000423}
424
Kostya Serebryany64d24572016-03-12 01:57:04 +0000425void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000426 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec) return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000427 std::vector<Unit> AdditionalCorpus;
428 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000429 &EpochOfLastReadOfOutputCorpus, MaxSize,
430 /*ExitOnError*/ false);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000431 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000432 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000433 bool Reloaded = false;
Kostya Serebryany90f8f362016-09-30 23:29:27 +0000434 for (auto &U : AdditionalCorpus) {
435 if (U.size() > MaxSize)
436 U.resize(MaxSize);
437 if (!Corpus.HasUnit(U)) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000438 if (size_t NumFeatures = RunOne(U)) {
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000439 CheckExitOnSrcPosOrItem();
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000440 Corpus.AddToCorpus(U, NumFeatures);
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000441 Reloaded = true;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000442 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000443 }
444 }
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000445 if (Reloaded)
446 PrintStats("RELOAD");
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000447}
448
Kostya Serebryany945761b2016-03-18 00:23:29 +0000449void Fuzzer::ShuffleCorpus(UnitVector *V) {
450 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
451 if (Options.PreferSmall)
452 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
453 return A.size() < B.size();
454 });
455}
456
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000457void Fuzzer::ShuffleAndMinimize(UnitVector *InitialCorpus) {
458 Printf("#0\tREAD units: %zd\n", InitialCorpus->size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000459 if (Options.ShuffleAtStartUp)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000460 ShuffleCorpus(InitialCorpus);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000461
Kostya Serebryany2455f0d2016-10-05 00:25:17 +0000462 // Test the callback with empty input and never try it again.
463 uint8_t dummy;
464 ExecuteCallback(&dummy, 0);
465
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000466 for (const auto &U : *InitialCorpus) {
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000467 if (size_t NumFeatures = RunOne(U)) {
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000468 CheckExitOnSrcPosOrItem();
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000469 Corpus.AddToCorpus(U, NumFeatures);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000470 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000471 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000472 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000473 TryDetectingAMemoryLeak(U.data(), U.size(),
474 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000475 }
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000476 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000477 if (Corpus.empty()) {
478 Printf("ERROR: no interesting inputs were found. "
479 "Is the code instrumented for coverage? Exiting.\n");
480 exit(1);
481 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000482}
483
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000484size_t Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
485 if (!Size) return 0;
Aaron Ballmanef116982015-01-29 16:58:29 +0000486 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000487
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000488 ExecuteCallback(Data, Size);
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000489
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000490 size_t Res = 0;
Kostya Serebryanyfe1094b2016-12-05 23:35:22 +0000491 if (size_t NumFeatures = TPC.CollectFeatures([&](size_t Feature) -> bool {
492 return Corpus.AddFeature(Feature, Size, Options.Shrink);
493 }))
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000494 Res = NumFeatures;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000495
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000496 if (!TPC.UsingTracePcGuard()) {
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000497 if (TPC.UpdateValueProfileMap(&MaxCoverage.VPMap))
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000498 Res = 1;
499 if (!Res && RecordMaxCoverage(&MaxCoverage))
500 Res = 1;
Kostya Serebryanyd2169222016-10-01 01:04:29 +0000501 }
502
Kostya Serebryany16901a92015-03-30 23:04:35 +0000503 auto TimeOfUnit =
504 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000505 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
506 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000507 PrintStats("pulse ");
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000508 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000509 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000510 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000511 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000512 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000513 }
514 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000515}
516
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000517size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000518 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000519 *Data = CurrentUnitData;
520 return CurrentUnitSize;
521}
522
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000523void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000524 assert(InFuzzingThread());
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000525 // We copy the contents of Unit into a separate heap buffer
526 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000527 uint8_t *DataCopy = new uint8_t[Size];
528 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000529 if (CurrentUnitData && CurrentUnitData != Data)
530 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000531 CurrentUnitSize = Size;
Kostya Serebryanya17d23e2016-10-13 19:06:46 +0000532 AllocTracer.Start(Options.TraceMalloc);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000533 UnitStartTime = system_clock::now();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000534 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000535 TPC.ResetMaps();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000536 int Res = CB(DataCopy, Size);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000537 UnitStopTime = system_clock::now();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000538 (void)Res;
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000539 assert(Res == 0);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000540 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000541 CurrentUnitSize = 0;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000542 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000543}
544
Aaron Ballmanef116982015-01-29 16:58:29 +0000545void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000546 if (Options.OnlyASCII)
547 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000548 if (Options.OutputCorpus.empty())
549 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000550 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
551 WriteToFile(U, Path);
552 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000553 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000554}
555
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000556void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000557 if (!Options.SaveArtifacts)
558 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000559 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000560 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000561 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000562 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000563 Printf("artifact_prefix='%s'; Test unit written to %s\n",
564 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000565 if (U.size() <= kMaxUnitSizeToPrint)
566 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000567}
568
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000569void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
570 if (!Options.PrintNEW)
571 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000572 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000573 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000574 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000575 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000576 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000577 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000578}
579
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000580void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
581 II->NumSuccessfullMutations++;
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000582 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000583 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000584 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000585 NumberOfNewUnitsAdded++;
Kostya Serebryanya5b2e542016-10-26 00:20:51 +0000586 TPC.PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000587}
588
Kostya Serebryany945761b2016-03-18 00:23:29 +0000589// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
590// We do it by actually executing the units, sometimes more than once,
591// because we may be using different coverage-like signals and the only
592// common thing between them is that we can say "this unit found new stuff".
593UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
594 const UnitVector &Extra) {
595 UnitVector Res = Extra;
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000596 UnitVector Tmp;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000597 size_t OldSize = Res.size();
598 for (int Iter = 0; Iter < 10; Iter++) {
599 ShuffleCorpus(&Res);
Kostya Serebryanyce1cab12016-09-23 02:18:59 +0000600 TPC.ResetMaps();
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000601 Corpus.ResetFeatureSet();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000602 ResetCoverage();
603
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000604 for (auto &U : Initial) {
605 TPC.ResetMaps();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000606 RunOne(U);
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000607 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000608
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000609 Tmp.clear();
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000610 for (auto &U : Res) {
611 TPC.ResetMaps();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000612 if (RunOne(U))
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000613 Tmp.push_back(U);
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000614 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000615
616 char Stat[7] = "MIN ";
617 Stat[3] = '0' + Iter;
Kostya Serebryany16a145f2016-09-23 01:58:51 +0000618 PrintStats(Stat, "\n", Tmp.size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000619
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000620 size_t NewSize = Tmp.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000621 assert(NewSize <= OldSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000622 Res.swap(Tmp);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000623
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000624 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000625 break;
626 OldSize = NewSize;
627 }
628 return Res;
629}
630
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000631void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
632 if (Corpora.size() <= 1) {
633 Printf("Merge requires two or more corpus dirs\n");
634 return;
635 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000636 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000637 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
638
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000639 assert(MaxInputLen > 0);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000640 UnitVector Initial, Extra;
Kostya Serebryanyd4be8892016-12-12 20:39:35 +0000641 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, MaxInputLen,
642 true);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000643 for (auto &C : ExtraCorpora)
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000644 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, MaxInputLen, true);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000645
646 if (!Initial.empty()) {
647 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
648 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000649 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000650
651 Printf("=== Merging extra %zd units\n", Extra.size());
652 auto Res = FindExtraUnits(Initial, Extra);
653
654 for (auto &U: Res)
655 WriteToOutputCorpus(U);
656
657 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000658}
659
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000660// Tries detecting a memory leak on the particular input that we have just
661// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000662void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
663 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000664 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
665 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000666 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
667 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000668 return; // No lsan.
669 // Run the target once again, but with lsan disabled so that if there is
670 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000671 EF->__lsan_disable();
Kostya Serebryany3b564e92016-10-05 23:31:01 +0000672 ExecuteCallback(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000673 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000674 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000675 if (NumberOfLeakDetectionAttempts++ > 1000) {
676 Options.DetectLeaks = false;
677 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
678 " Most likely the target function accumulates allocated\n"
679 " memory in a global state w/o actually leaking it.\n"
Kostya Serebryany03813742016-10-13 22:24:10 +0000680 " You may try running this binary with -trace_malloc=[12]"
681 " to get a trace of mallocs and frees.\n"
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000682 " If LeakSanitizer is enabled in this process it will still\n"
683 " run on the process shutdown.\n");
684 return;
685 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000686 // Now perform the actual lsan pass. This is expensive and we must ensure
687 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000688 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000689 if (DuringInitialCorpusExecution)
690 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
691 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000692 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000693 DumpCurrentUnit("leak-");
694 PrintFinalStats();
695 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
696 }
697}
698
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000699void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000700 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000701
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000702 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany20801e12016-09-21 21:41:48 +0000703 const auto &U = II.U;
704 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000705 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000706 size_t Size = U.size();
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000707 assert(Size <= MaxInputLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000708 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000709
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000710 assert(MaxMutationLen > 0);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000711
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000712 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000713 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
714 break;
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000715 size_t NewSize = 0;
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000716 NewSize = MD.Mutate(CurrentUnitData, Size, MaxMutationLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000717 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000718 assert(NewSize <= MaxMutationLen && "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000719 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000720 if (i == 0)
721 StartTraceRecording();
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000722 II.NumExecutedMutations++;
Kostya Serebryany1c73f1b2016-10-05 22:56:21 +0000723 if (size_t NumFeatures = RunOne(CurrentUnitData, Size)) {
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000724 Corpus.AddToCorpus({CurrentUnitData, CurrentUnitData + Size}, NumFeatures,
725 /*MayDeleteFile=*/true);
Kostya Serebryany29bb6642016-09-21 22:42:17 +0000726 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryany8dfed452016-10-18 18:06:05 +0000727 CheckExitOnSrcPosOrItem();
Kostya Serebryany90f8f362016-09-30 23:29:27 +0000728 }
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000729 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000730 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000731 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000732 }
733}
734
Kostya Serebryany945761b2016-03-18 00:23:29 +0000735void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000736 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000737 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000738 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000739}
740
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000741void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000742 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000743 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000744 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000745 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000746 auto Now = system_clock::now();
Kostya Serebryany9adc7c82016-10-08 22:12:14 +0000747 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
748 Options.ReloadIntervalSec) {
Kostya Serebryanybe0ed592016-09-22 23:16:36 +0000749 RereadOutputCorpus(MaxInputLen);
Kostya Serebryanyc5325ed2016-10-08 23:24:45 +0000750 LastCorpusReload = system_clock::now();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000751 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000752 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000753 break;
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000754 if (TimedOut()) break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000755 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000756 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000757 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000758
759 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000760 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000761}
762
Kostya Serebryanyf9b8e8b2016-10-15 01:00:24 +0000763void Fuzzer::MinimizeCrashLoop(const Unit &U) {
764 if (U.size() <= 2) return;
765 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
766 MD.StartMutationSequence();
767 memcpy(CurrentUnitData, U.data(), U.size());
768 for (int i = 0; i < Options.MutateDepth; i++) {
769 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
770 assert(NewSize > 0 && NewSize <= MaxMutationLen);
771 RunOne(CurrentUnitData, NewSize);
772 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
773 /*DuringInitialCorpusExecution*/ false);
774 }
775 }
776}
777
Ivan Krasindf919102016-01-22 22:28:27 +0000778} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000779
780extern "C" {
781
782size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
783 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000784 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000785}
786} // extern "C"