blob: f5852cb4c7a9f783896b6975f41ae3418804b311 [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"
Aaron Ballmanef116982015-01-29 16:58:29 +000013#include <algorithm>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000014#include <cstring>
15#include <memory>
Aaron Ballmanef116982015-01-29 16:58:29 +000016
Kostya Serebryany2a48c242015-11-13 01:54:40 +000017#if defined(__has_include)
Ivan Krasindf919102016-01-22 22:28:27 +000018#if __has_include(<sanitizer / coverage_interface.h>)
19#include <sanitizer/coverage_interface.h>
20#endif
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000021#if __has_include(<sanitizer / lsan_interface.h>)
22#include <sanitizer/lsan_interface.h>
23#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000024#endif
25
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000026#define NO_SANITIZE_MEMORY
27#if defined(__has_feature)
28#if __has_feature(memory_sanitizer)
29#undef NO_SANITIZE_MEMORY
30#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
31#endif
32#endif
33
Aaron Ballmanef116982015-01-29 16:58:29 +000034namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000035static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000036
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000037thread_local bool Fuzzer::IsMyThread;
38
Dan Liew1873a492016-06-07 23:32:50 +000039static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000040 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000041 "Did you use -fsanitize-coverage=... to build your code?\n",
42 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000043 exit(1);
44}
45
Dan Liew1873a492016-06-07 23:32:50 +000046#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000047 do { \
Dan Liew1873a492016-06-07 23:32:50 +000048 if (!(EF->fn)) \
49 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000050 } while (false)
51
Kostya Serebryany52a788e2015-03-31 20:13:20 +000052// Only one Fuzzer per process.
53static Fuzzer *F;
54
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000055void Fuzzer::ResetEdgeCoverage() {
56 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
57 EF->__sanitizer_reset_coverage();
58}
59
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000060void Fuzzer::ResetCounters() {
61 if (Options.UseCounters) {
62 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
63 }
64 if (EF->__sanitizer_get_coverage_pc_buffer_pos)
65 PcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
66}
67
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000068void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
69 if (Options.UseCounters) {
70 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
71 C->CounterBitmap.resize(NumCounters);
72 }
73}
74
75// Records data to a maximum coverage tracker. Returns true if additional
76// coverage was discovered.
77bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
78 bool Res = false;
79
Kostya Serebryanya00b2432016-09-14 02:13:06 +000080 uint64_t NewBlockCoverage =
81 EF->__sanitizer_get_total_unique_coverage() + TPC.GetTotalCoverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000082 if (NewBlockCoverage > C->BlockCoverage) {
83 Res = true;
84 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000085 }
86
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000087 if (Options.UseIndirCalls &&
88 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
89 uint64_t NewCallerCalleeCoverage =
90 EF->__sanitizer_get_total_unique_caller_callee_pairs();
91 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000092 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000093 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000094 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000095 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000096
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000097 if (Options.UseCounters) {
98 uint64_t CounterDelta =
99 EF->__sanitizer_update_counter_bitset_and_clear_counters(
100 C->CounterBitmap.data());
101 if (CounterDelta > 0) {
102 Res = true;
103 C->CounterBitmapBits += CounterDelta;
104 }
105 }
106
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000107 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
108 if (NewVPMapBits > C->VPMapBits) {
109 Res = true;
110 C->VPMapBits = NewVPMapBits;
111 }
112
113 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
114 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000115 if (NewPcBufferPos > PcBufferPos) {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000116 Res = true;
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000117 PcBufferPos = NewPcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000118 }
119
120 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
121 Printf("ERROR: PC buffer overflow\n");
122 _Exit(1);
123 }
124 }
125
126 return Res;
127}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000128
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000129// Leak detection is expensive, so we first check if there were more mallocs
130// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
131struct MallocFreeTracer {
132 void Start() {
133 Mallocs = 0;
134 Frees = 0;
135 }
136 // Returns true if there were more mallocs than frees.
137 bool Stop() { return Mallocs > Frees; }
138 std::atomic<size_t> Mallocs;
139 std::atomic<size_t> Frees;
140};
141
142static MallocFreeTracer AllocTracer;
143
144void MallocHook(const volatile void *ptr, size_t size) {
145 AllocTracer.Mallocs++;
146}
147void FreeHook(const volatile void *ptr) {
148 AllocTracer.Frees++;
149}
150
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000151Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000152 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000153 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000154 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000155 assert(!F);
156 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000157 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000158 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000159 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
160 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000161
162 if (Options.PrintNewCovPcs) {
163 PcBufferLen = 1 << 24;
164 PcBuffer = new uintptr_t[PcBufferLen];
165 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
166 }
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000167}
Aaron Ballmanef116982015-01-29 16:58:29 +0000168
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000169Fuzzer::~Fuzzer() { }
170
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000171void Fuzzer::LazyAllocateCurrentUnitData() {
172 if (CurrentUnitData || Options.MaxLen == 0) return;
173 CurrentUnitData = new uint8_t[Options.MaxLen];
174}
175
Aaron Ballmanef116982015-01-29 16:58:29 +0000176void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000177 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
178 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000179}
180
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000181void Fuzzer::StaticDeathCallback() {
182 assert(F);
183 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000184}
185
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000186static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000187 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000188 Printf(
189 "***\n"
190 "***\n"
191 "***\n"
192 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
193 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
194 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
195 "*** Future versions may have crash-resistant merge, stay tuned.\n"
196 "***\n"
197 "***\n"
198 "***\n");
199}
200
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000201void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000202 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000203 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000204 MD.PrintMutationSequence();
205 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000206 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000207 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000208 PrintHexArray(CurrentUnitData, UnitSize, "\n");
209 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000210 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000211 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
212 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000213}
214
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000215NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000216void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000217 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000218 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000219}
220
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000221void Fuzzer::StaticAlarmCallback() {
222 assert(F);
223 F->AlarmCallback();
224}
225
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000226void Fuzzer::StaticCrashSignalCallback() {
227 assert(F);
228 F->CrashCallback();
229}
230
231void Fuzzer::StaticInterruptCallback() {
232 assert(F);
233 F->InterruptCallback();
234}
235
236void Fuzzer::CrashCallback() {
237 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000238 if (EF->__sanitizer_print_stack_trace)
239 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000240 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
241 " Combine libFuzzer with AddressSanitizer or similar for better "
242 "crash reports.\n");
243 Printf("SUMMARY: libFuzzer: deadly signal\n");
244 DumpCurrentUnit("crash-");
245 PrintFinalStats();
246 exit(Options.ErrorExitCode);
247}
248
249void Fuzzer::InterruptCallback() {
250 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
251 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000252 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000253}
254
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000255NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000256void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000257 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000258 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000259 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000260 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000261 size_t Seconds =
262 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000263 if (Seconds == 0)
264 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000265 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000266 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000267 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000268 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000269 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
270 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000271 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000272 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
273 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000274 if (EF->__sanitizer_print_stack_trace)
275 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000276 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000277 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000278 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000279 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000280}
281
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000282void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000283 Printf(
284 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
285 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000286 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000287 if (EF->__sanitizer_print_memory_profile)
288 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000289 DumpCurrentUnit("oom-");
290 Printf("SUMMARY: libFuzzer: out-of-memory\n");
291 PrintFinalStats();
292 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000293}
294
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000295void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000296 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000297 if (Options.OutputCSV) {
298 static bool csvHeaderPrinted = false;
299 if (!csvHeaderPrinted) {
300 csvHeaderPrinted = true;
301 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
302 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000303 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000304 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
305 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000306 }
307
308 if (!Options.Verbosity)
309 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000310 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000311 if (MaxCoverage.BlockCoverage)
312 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000313 if (MaxCoverage.VPMapBits)
314 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000315 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000316 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000317 if (MaxCoverage.CallerCalleeCoverage)
318 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000319 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000320 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000321}
322
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000323void Fuzzer::PrintFinalStats() {
324 if (!Options.PrintFinalStats) return;
325 size_t ExecPerSec = execPerSec();
326 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
327 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
328 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
329 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
330 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
331}
332
Kostya Serebryany64d24572016-03-12 01:57:04 +0000333size_t Fuzzer::MaxUnitSizeInCorpus() const {
334 size_t Res = 0;
335 for (auto &X : Corpus)
336 Res = std::max(Res, X.size());
337 return Res;
338}
339
340void Fuzzer::SetMaxLen(size_t MaxLen) {
341 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
342 assert(MaxLen);
343 Options.MaxLen = MaxLen;
344 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
345}
346
347
348void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000349 if (Options.OutputCorpus.empty())
350 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000351 std::vector<Unit> AdditionalCorpus;
352 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000353 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000354 if (Corpus.empty()) {
355 Corpus = AdditionalCorpus;
356 return;
357 }
Ivan Krasindf919102016-01-22 22:28:27 +0000358 if (!Options.Reload)
359 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000360 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000361 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000362 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000363 if (X.size() > MaxSize)
364 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000365 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000366 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000367 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000368 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000369 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000370 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000371 }
372 }
373}
374
Kostya Serebryany945761b2016-03-18 00:23:29 +0000375void Fuzzer::ShuffleCorpus(UnitVector *V) {
376 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
377 if (Options.PreferSmall)
378 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
379 return A.size() < B.size();
380 });
381}
382
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000383// Tries random prefixes of corpus items.
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000384void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000385 std::vector<double> Fractions = {0.25, 0.5, 0.75, 1.0};
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000386
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000387 size_t TruncInputs = 0;
388 for (double Fraction : Fractions) {
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000389 for (const auto &U : Corpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000390 uint64_t S = MD.GetRand()(U.size() * Fraction);
391 if (!S || !RunOne(U.data(), S))
392 continue;
393 TruncInputs++;
394 Unit U1(U.begin(), U.begin() + S);
395 NewCorpus->push_back(U1);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000396 }
397 }
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000398 if (TruncInputs)
399 Printf("\tINFO TRUNC %zd units added to in-memory corpus\n", TruncInputs);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000400}
401
Aaron Ballmanef116982015-01-29 16:58:29 +0000402void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000403 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000404 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000405 if (Options.ShuffleAtStartUp)
406 ShuffleCorpus(&Corpus);
407
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000408 if (Options.TruncateUnits) {
409 ResetCoverage();
410 TruncateUnits(&NewCorpus);
411 ResetCoverage();
412 }
413
Kostya Serebryany945761b2016-03-18 00:23:29 +0000414 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000415 bool NewCoverage = RunOne(U);
416 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000417 NewCorpus.push_back(U);
418 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000419 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000420 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000421 TryDetectingAMemoryLeak(U.data(), U.size(),
422 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000423 }
424 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000425 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000426 for (auto &X : Corpus)
427 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000428 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000429 if (Corpus.empty()) {
430 Printf("ERROR: no interesting inputs were found. "
431 "Is the code instrumented for coverage? Exiting.\n");
432 exit(1);
433 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000434}
435
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000436bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000437 PrevPcBufferPos = PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000438 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000439
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000440 return Res;
441}
442
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000443bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000444 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000445
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000446 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000447 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000448
Kostya Serebryany16901a92015-03-30 23:04:35 +0000449 auto UnitStopTime = system_clock::now();
450 auto TimeOfUnit =
451 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000452 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
453 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000454 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000455 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
456 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000457 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000458 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000459 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000460 }
461 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000462}
463
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000464void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000465 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
466 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000467 if (RunOne(Data, Size))
468 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000469}
470
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000471size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000472 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000473 *Data = CurrentUnitData;
474 return CurrentUnitSize;
475}
476
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000477void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000478 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000479 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000480 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000481 // We copy the contents of Unit into a separate heap buffer
482 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000483 uint8_t *DataCopy = new uint8_t[Size];
484 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000485 if (CurrentUnitData && CurrentUnitData != Data)
486 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000487 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000488 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000489 AllocTracer.Start();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000490 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000491 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000492 (void)Res;
493 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000494 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000495 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000496 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000497}
498
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000499std::string Fuzzer::Coverage::DebugString() const {
500 std::string Result =
501 std::string("Coverage{") + "BlockCoverage=" +
502 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
503 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanya00b2432016-09-14 02:13:06 +0000504 std::to_string(CounterBitmapBits) +
505 " VPMapBits " + std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000506 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000507}
508
509void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000510 if (Options.OnlyASCII)
511 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000512 if (Options.OutputCorpus.empty())
513 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000514 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
515 WriteToFile(U, Path);
516 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000517 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000518}
519
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000520void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000521 if (!Options.SaveArtifacts)
522 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000523 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000524 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000525 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000526 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000527 Printf("artifact_prefix='%s'; Test unit written to %s\n",
528 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000529 if (U.size() <= kMaxUnitSizeToPrint)
530 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000531}
532
533void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000534 if (Options.OutputCorpus.empty())
535 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000536 for (const auto &U : Corpus)
537 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
538 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000539 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
540 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000541}
542
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000543void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
544 if (!Options.PrintNEW)
545 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000546 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000547 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000548 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000549 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000550 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000551 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000552}
553
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000554void Fuzzer::PrintNewPCs() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000555 if (Options.PrintNewCovPcs && PrevPcBufferPos != PcBufferPos) {
556 int NumPrinted = 0;
557 for (size_t I = PrevPcBufferPos; I < PcBufferPos; ++I) {
558 if (NumPrinted++ > 30) break; // Don't print too many new PCs.
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000559 if (EF->__sanitizer_symbolize_pc) {
560 char PcDescr[1024];
561 EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PcBuffer[I]),
562 "%p %F %L", PcDescr, sizeof(PcDescr));
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000563 PcDescr[sizeof(PcDescr) - 1] = 0; // Just in case.
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000564 Printf("\tNEW_PC: %s\n", PcDescr);
565 } else {
566 Printf("\tNEW_PC: %p\n", PcBuffer[I]);
567 }
568 }
569 }
570}
571
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000572void Fuzzer::ReportNewCoverage(const Unit &U) {
573 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000574 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000575 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000576 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000577 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000578 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000579 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000580 PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000581}
582
Kostya Serebryany945761b2016-03-18 00:23:29 +0000583// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
584// We do it by actually executing the units, sometimes more than once,
585// because we may be using different coverage-like signals and the only
586// common thing between them is that we can say "this unit found new stuff".
587UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
588 const UnitVector &Extra) {
589 UnitVector Res = Extra;
590 size_t OldSize = Res.size();
591 for (int Iter = 0; Iter < 10; Iter++) {
592 ShuffleCorpus(&Res);
593 ResetCoverage();
594
595 for (auto &U : Initial)
596 RunOne(U);
597
598 Corpus.clear();
599 for (auto &U : Res)
600 if (RunOne(U))
601 Corpus.push_back(U);
602
603 char Stat[7] = "MIN ";
604 Stat[3] = '0' + Iter;
605 PrintStats(Stat);
606
607 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000608 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000609 Res.swap(Corpus);
610
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000611 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000612 break;
613 OldSize = NewSize;
614 }
615 return Res;
616}
617
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000618void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
619 if (Corpora.size() <= 1) {
620 Printf("Merge requires two or more corpus dirs\n");
621 return;
622 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000623 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000624 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
625
Kostya Serebryany945761b2016-03-18 00:23:29 +0000626 assert(Options.MaxLen > 0);
627 UnitVector Initial, Extra;
628 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
629 for (auto &C : ExtraCorpora)
630 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
631
632 if (!Initial.empty()) {
633 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
634 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000635 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000636
637 Printf("=== Merging extra %zd units\n", Extra.size());
638 auto Res = FindExtraUnits(Initial, Extra);
639
640 for (auto &U: Res)
641 WriteToOutputCorpus(U);
642
643 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000644}
645
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000646// Tries detecting a memory leak on the particular input that we have just
647// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000648void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
649 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000650 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
651 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000652 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
653 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000654 return; // No lsan.
655 // Run the target once again, but with lsan disabled so that if there is
656 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000657 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000658 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000659 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000660 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000661 if (NumberOfLeakDetectionAttempts++ > 1000) {
662 Options.DetectLeaks = false;
663 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
664 " Most likely the target function accumulates allocated\n"
665 " memory in a global state w/o actually leaking it.\n"
666 " If LeakSanitizer is enabled in this process it will still\n"
667 " run on the process shutdown.\n");
668 return;
669 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000670 // Now perform the actual lsan pass. This is expensive and we must ensure
671 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000672 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000673 if (DuringInitialCorpusExecution)
674 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
675 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000676 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000677 DumpCurrentUnit("leak-");
678 PrintFinalStats();
679 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
680 }
681}
682
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000683void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000684 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000685 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000686
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000687 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000688 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000689 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000690 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000691 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000692 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000693
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000694 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000695 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000696 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000697 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000698 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000699 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000700 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000701 if (i == 0)
702 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000703 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000704 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000705 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000706 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000707 }
708}
709
Kostya Serebryanye6926212015-11-04 23:22:25 +0000710// Returns an index of random unit from the corpus to mutate.
711// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000712// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000713size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000714 size_t Idx =
715 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000716 assert(Idx < Corpus.size());
717 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000718}
719
Kostya Serebryany945761b2016-03-18 00:23:29 +0000720void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000721 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000722 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000723 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000724}
725
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000726// Experimental search heuristic: drilling.
727// - Read, shuffle, execute and minimize the corpus.
728// - Choose one random unit.
729// - Reset the coverage.
730// - Start fuzzing as if the chosen unit was the only element of the corpus.
731// - When done, reset the coverage again.
732// - Merge the newly created corpus into the original one.
733void Fuzzer::Drill() {
734 // The corpus is already read, shuffled, and minimized.
735 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000736 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000737
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000738 Unit U = ChooseUnitToMutate();
739
Kostya Serebryany945761b2016-03-18 00:23:29 +0000740 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000741
742 std::vector<Unit> SavedCorpus;
743 SavedCorpus.swap(Corpus);
744 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000745 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000746 assert(Corpus.size() == 1);
747 RunOne(U);
748 PrintStats("DRILL ");
749 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
750 SavedOutputCorpusPath.swap(Options.OutputCorpus);
751 Loop();
752
Kostya Serebryany945761b2016-03-18 00:23:29 +0000753 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000754
755 PrintStats("REINIT");
756 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000757 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000758 RunOne(U);
759 PrintStats("MERGE ");
760 Options.PrintNEW = true;
761 size_t NumMerged = 0;
762 for (auto &U : Corpus) {
763 if (RunOne(U)) {
764 PrintStatusForNewUnit(U);
765 NumMerged++;
766 WriteToOutputCorpus(U);
767 }
768 }
769 PrintStats("MERGED");
770 if (NumMerged && Options.Verbosity)
771 Printf("Drilling discovered %zd new units\n", NumMerged);
772}
773
774void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000775 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000776 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000777 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000778 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000779 auto Now = system_clock::now();
780 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000781 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000782 LastCorpusReload = Now;
783 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000784 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000785 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000786 if (Options.MaxTotalTimeSec > 0 &&
787 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000788 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000789 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000790 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000791 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000792 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000793
794 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000795 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000796}
797
Ivan Krasindf919102016-01-22 22:28:27 +0000798void Fuzzer::UpdateCorpusDistribution() {
799 size_t N = Corpus.size();
800 std::vector<double> Intervals(N + 1);
801 std::vector<double> Weights(N);
802 std::iota(Intervals.begin(), Intervals.end(), 0);
803 std::iota(Weights.begin(), Weights.end(), 1);
804 CorpusDistribution = std::piecewise_constant_distribution<double>(
805 Intervals.begin(), Intervals.end(), Weights.begin());
806}
807
808} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000809
810extern "C" {
811
812size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
813 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000814 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000815}
816} // extern "C"