blob: 017ea03eaf7fe0a4d080b74768fade1a83045c4f [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
80 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
81 if (NewBlockCoverage > C->BlockCoverage) {
82 Res = true;
83 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000084 }
85
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000086 if (Options.UseIndirCalls &&
87 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
88 uint64_t NewCallerCalleeCoverage =
89 EF->__sanitizer_get_total_unique_caller_callee_pairs();
90 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000091 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000092 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000093 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000094 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000095
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000096 if (Options.UseCounters) {
97 uint64_t CounterDelta =
98 EF->__sanitizer_update_counter_bitset_and_clear_counters(
99 C->CounterBitmap.data());
100 if (CounterDelta > 0) {
101 Res = true;
102 C->CounterBitmapBits += CounterDelta;
103 }
104 }
105
106 size_t NewPCMapBits = PCMapMergeFromCurrent(C->PCMap);
107 if (NewPCMapBits > C->PCMapBits) {
108 Res = true;
109 C->PCMapBits = NewPCMapBits;
110 }
111
112 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
113 if (NewVPMapBits > C->VPMapBits) {
114 Res = true;
115 C->VPMapBits = NewVPMapBits;
116 }
117
118 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
119 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000120 if (NewPcBufferPos > PcBufferPos) {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000121 Res = true;
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000122 PcBufferPos = NewPcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000123 }
124
125 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
126 Printf("ERROR: PC buffer overflow\n");
127 _Exit(1);
128 }
129 }
130
131 return Res;
132}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000133
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000134// Leak detection is expensive, so we first check if there were more mallocs
135// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
136struct MallocFreeTracer {
137 void Start() {
138 Mallocs = 0;
139 Frees = 0;
140 }
141 // Returns true if there were more mallocs than frees.
142 bool Stop() { return Mallocs > Frees; }
143 std::atomic<size_t> Mallocs;
144 std::atomic<size_t> Frees;
145};
146
147static MallocFreeTracer AllocTracer;
148
149void MallocHook(const volatile void *ptr, size_t size) {
150 AllocTracer.Mallocs++;
151}
152void FreeHook(const volatile void *ptr) {
153 AllocTracer.Frees++;
154}
155
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000156Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000157 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000158 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000159 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000160 assert(!F);
161 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000162 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000163 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000164 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
165 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000166
167 if (Options.PrintNewCovPcs) {
168 PcBufferLen = 1 << 24;
169 PcBuffer = new uintptr_t[PcBufferLen];
170 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
171 }
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000172}
Aaron Ballmanef116982015-01-29 16:58:29 +0000173
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000174Fuzzer::~Fuzzer() { }
175
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000176void Fuzzer::LazyAllocateCurrentUnitData() {
177 if (CurrentUnitData || Options.MaxLen == 0) return;
178 CurrentUnitData = new uint8_t[Options.MaxLen];
179}
180
Aaron Ballmanef116982015-01-29 16:58:29 +0000181void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000182 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
183 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000184}
185
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000186void Fuzzer::StaticDeathCallback() {
187 assert(F);
188 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000189}
190
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000191void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany311cc832016-05-28 04:19:46 +0000192 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000193 MD.PrintMutationSequence();
194 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000195 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000196 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000197 PrintHexArray(CurrentUnitData, UnitSize, "\n");
198 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000199 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000200 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
201 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000202}
203
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000204NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000205void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000206 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000207 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000208}
209
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000210void Fuzzer::StaticAlarmCallback() {
211 assert(F);
212 F->AlarmCallback();
213}
214
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000215void Fuzzer::StaticCrashSignalCallback() {
216 assert(F);
217 F->CrashCallback();
218}
219
220void Fuzzer::StaticInterruptCallback() {
221 assert(F);
222 F->InterruptCallback();
223}
224
225void Fuzzer::CrashCallback() {
226 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000227 if (EF->__sanitizer_print_stack_trace)
228 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000229 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
230 " Combine libFuzzer with AddressSanitizer or similar for better "
231 "crash reports.\n");
232 Printf("SUMMARY: libFuzzer: deadly signal\n");
233 DumpCurrentUnit("crash-");
234 PrintFinalStats();
235 exit(Options.ErrorExitCode);
236}
237
238void Fuzzer::InterruptCallback() {
239 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
240 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000241 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000242}
243
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000244NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000245void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000246 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000247 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000248 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000249 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000250 size_t Seconds =
251 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000252 if (Seconds == 0)
253 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000254 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000255 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000256 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000257 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000258 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
259 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000260 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000261 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
262 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000263 if (EF->__sanitizer_print_stack_trace)
264 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000265 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000266 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000267 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000268 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000269}
270
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000271void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000272 Printf(
273 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
274 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000275 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000276 if (EF->__sanitizer_print_memory_profile)
277 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000278 DumpCurrentUnit("oom-");
279 Printf("SUMMARY: libFuzzer: out-of-memory\n");
280 PrintFinalStats();
281 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000282}
283
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000284void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000285 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000286 if (Options.OutputCSV) {
287 static bool csvHeaderPrinted = false;
288 if (!csvHeaderPrinted) {
289 csvHeaderPrinted = true;
290 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
291 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000292 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000293 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
294 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000295 }
296
297 if (!Options.Verbosity)
298 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000299 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000300 if (MaxCoverage.BlockCoverage)
301 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyc98ef712016-08-16 17:37:13 +0000302 if (MaxCoverage.PCMapBits)
303 Printf(" path: %zd", MaxCoverage.PCMapBits);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000304 if (MaxCoverage.VPMapBits)
305 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000306 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000307 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000308 if (MaxCoverage.CallerCalleeCoverage)
309 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000310 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000311 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000312}
313
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000314void Fuzzer::PrintFinalStats() {
315 if (!Options.PrintFinalStats) return;
316 size_t ExecPerSec = execPerSec();
317 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
318 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
319 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
320 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
321 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
322}
323
Kostya Serebryany64d24572016-03-12 01:57:04 +0000324size_t Fuzzer::MaxUnitSizeInCorpus() const {
325 size_t Res = 0;
326 for (auto &X : Corpus)
327 Res = std::max(Res, X.size());
328 return Res;
329}
330
331void Fuzzer::SetMaxLen(size_t MaxLen) {
332 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
333 assert(MaxLen);
334 Options.MaxLen = MaxLen;
335 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
336}
337
338
339void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000340 if (Options.OutputCorpus.empty())
341 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000342 std::vector<Unit> AdditionalCorpus;
343 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000344 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000345 if (Corpus.empty()) {
346 Corpus = AdditionalCorpus;
347 return;
348 }
Ivan Krasindf919102016-01-22 22:28:27 +0000349 if (!Options.Reload)
350 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000351 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000352 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000353 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000354 if (X.size() > MaxSize)
355 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000356 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000357 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000358 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000359 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000360 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000361 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000362 }
363 }
364}
365
Kostya Serebryany945761b2016-03-18 00:23:29 +0000366void Fuzzer::ShuffleCorpus(UnitVector *V) {
367 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
368 if (Options.PreferSmall)
369 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
370 return A.size() < B.size();
371 });
372}
373
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000374// Tries random prefixes of corpus items.
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000375void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000376 std::vector<double> Fractions = {0.25, 0.5, 0.75, 1.0};
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000377
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000378 size_t TruncInputs = 0;
379 for (double Fraction : Fractions) {
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000380 for (const auto &U : Corpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000381 uint64_t S = MD.GetRand()(U.size() * Fraction);
382 if (!S || !RunOne(U.data(), S))
383 continue;
384 TruncInputs++;
385 Unit U1(U.begin(), U.begin() + S);
386 NewCorpus->push_back(U1);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000387 }
388 }
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000389 if (TruncInputs)
390 Printf("\tINFO TRUNC %zd units added to in-memory corpus\n", TruncInputs);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000391}
392
Aaron Ballmanef116982015-01-29 16:58:29 +0000393void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000394 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000395 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000396 if (Options.ShuffleAtStartUp)
397 ShuffleCorpus(&Corpus);
398
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000399 if (Options.TruncateUnits) {
400 ResetCoverage();
401 TruncateUnits(&NewCorpus);
402 ResetCoverage();
403 }
404
Kostya Serebryany945761b2016-03-18 00:23:29 +0000405 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000406 bool NewCoverage = RunOne(U);
407 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000408 NewCorpus.push_back(U);
409 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000410 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000411 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000412 TryDetectingAMemoryLeak(U.data(), U.size(),
413 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000414 }
415 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000416 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000417 for (auto &X : Corpus)
418 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000419 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000420 if (Corpus.empty()) {
421 Printf("ERROR: no interesting inputs were found. "
422 "Is the code instrumented for coverage? Exiting.\n");
423 exit(1);
424 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000425}
426
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000427bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000428 PrevPcBufferPos = PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000429 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000430
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000431 return Res;
432}
433
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000434bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000435 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000436
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000437 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000438 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000439
Kostya Serebryany16901a92015-03-30 23:04:35 +0000440 auto UnitStopTime = system_clock::now();
441 auto TimeOfUnit =
442 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000443 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
444 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000445 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000446 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
447 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000448 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000449 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000450 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000451 }
452 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000453}
454
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000455void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000456 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
457 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000458 if (RunOne(Data, Size))
459 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000460}
461
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000462size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000463 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000464 *Data = CurrentUnitData;
465 return CurrentUnitSize;
466}
467
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000468void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000469 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000470 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000471 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000472 // We copy the contents of Unit into a separate heap buffer
473 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000474 uint8_t *DataCopy = new uint8_t[Size];
475 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000476 if (CurrentUnitData && CurrentUnitData != Data)
477 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000478 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000479 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000480 AllocTracer.Start();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000481 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000482 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000483 (void)Res;
484 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000485 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000486 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000487 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000488}
489
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000490std::string Fuzzer::Coverage::DebugString() const {
491 std::string Result =
492 std::string("Coverage{") + "BlockCoverage=" +
493 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
494 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000495 std::to_string(CounterBitmapBits) + " PCMapBits=" +
496 std::to_string(PCMapBits) + " VPMapBits " +
497 std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000498 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000499}
500
501void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000502 if (Options.OnlyASCII)
503 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000504 if (Options.OutputCorpus.empty())
505 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000506 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
507 WriteToFile(U, Path);
508 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000509 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000510}
511
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000512void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000513 if (!Options.SaveArtifacts)
514 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000515 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000516 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000517 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000518 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000519 Printf("artifact_prefix='%s'; Test unit written to %s\n",
520 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000521 if (U.size() <= kMaxUnitSizeToPrint)
522 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000523}
524
525void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000526 if (Options.OutputCorpus.empty())
527 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000528 for (const auto &U : Corpus)
529 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
530 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000531 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
532 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000533}
534
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000535void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
536 if (!Options.PrintNEW)
537 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000538 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000539 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000540 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000541 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000542 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000543 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000544}
545
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000546void Fuzzer::PrintNewPCs() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000547 if (Options.PrintNewCovPcs && PrevPcBufferPos != PcBufferPos) {
548 int NumPrinted = 0;
549 for (size_t I = PrevPcBufferPos; I < PcBufferPos; ++I) {
550 if (NumPrinted++ > 30) break; // Don't print too many new PCs.
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000551 if (EF->__sanitizer_symbolize_pc) {
552 char PcDescr[1024];
553 EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PcBuffer[I]),
554 "%p %F %L", PcDescr, sizeof(PcDescr));
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000555 PcDescr[sizeof(PcDescr) - 1] = 0; // Just in case.
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000556 Printf("\tNEW_PC: %s\n", PcDescr);
557 } else {
558 Printf("\tNEW_PC: %p\n", PcBuffer[I]);
559 }
560 }
561 }
562}
563
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000564void Fuzzer::ReportNewCoverage(const Unit &U) {
565 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000566 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000567 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000568 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000569 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000570 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000571 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000572 PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000573}
574
Kostya Serebryany945761b2016-03-18 00:23:29 +0000575// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
576// We do it by actually executing the units, sometimes more than once,
577// because we may be using different coverage-like signals and the only
578// common thing between them is that we can say "this unit found new stuff".
579UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
580 const UnitVector &Extra) {
581 UnitVector Res = Extra;
582 size_t OldSize = Res.size();
583 for (int Iter = 0; Iter < 10; Iter++) {
584 ShuffleCorpus(&Res);
585 ResetCoverage();
586
587 for (auto &U : Initial)
588 RunOne(U);
589
590 Corpus.clear();
591 for (auto &U : Res)
592 if (RunOne(U))
593 Corpus.push_back(U);
594
595 char Stat[7] = "MIN ";
596 Stat[3] = '0' + Iter;
597 PrintStats(Stat);
598
599 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000600 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000601 Res.swap(Corpus);
602
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000603 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000604 break;
605 OldSize = NewSize;
606 }
607 return Res;
608}
609
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000610void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
611 if (Corpora.size() <= 1) {
612 Printf("Merge requires two or more corpus dirs\n");
613 return;
614 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000615 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
616
Kostya Serebryany945761b2016-03-18 00:23:29 +0000617 assert(Options.MaxLen > 0);
618 UnitVector Initial, Extra;
619 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
620 for (auto &C : ExtraCorpora)
621 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
622
623 if (!Initial.empty()) {
624 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
625 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000626 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000627
628 Printf("=== Merging extra %zd units\n", Extra.size());
629 auto Res = FindExtraUnits(Initial, Extra);
630
631 for (auto &U: Res)
632 WriteToOutputCorpus(U);
633
634 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000635}
636
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000637// Tries detecting a memory leak on the particular input that we have just
638// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000639void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
640 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000641 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
642 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000643 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
644 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000645 return; // No lsan.
646 // Run the target once again, but with lsan disabled so that if there is
647 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000648 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000649 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000650 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000651 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000652 if (NumberOfLeakDetectionAttempts++ > 1000) {
653 Options.DetectLeaks = false;
654 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
655 " Most likely the target function accumulates allocated\n"
656 " memory in a global state w/o actually leaking it.\n"
657 " If LeakSanitizer is enabled in this process it will still\n"
658 " run on the process shutdown.\n");
659 return;
660 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000661 // Now perform the actual lsan pass. This is expensive and we must ensure
662 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000663 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000664 if (DuringInitialCorpusExecution)
665 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
666 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000667 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000668 DumpCurrentUnit("leak-");
669 PrintFinalStats();
670 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
671 }
672}
673
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000674void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000675 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000676 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000677
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000678 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000679 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000680 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000681 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000682 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000683 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000684
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000685 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000686 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000687 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000688 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000689 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000690 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000691 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000692 if (i == 0)
693 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000694 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000695 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000696 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000697 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000698 }
699}
700
Kostya Serebryanye6926212015-11-04 23:22:25 +0000701// Returns an index of random unit from the corpus to mutate.
702// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000703// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000704size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000705 size_t Idx =
706 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000707 assert(Idx < Corpus.size());
708 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000709}
710
Kostya Serebryany945761b2016-03-18 00:23:29 +0000711void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000712 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000713 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000714 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000715}
716
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000717// Experimental search heuristic: drilling.
718// - Read, shuffle, execute and minimize the corpus.
719// - Choose one random unit.
720// - Reset the coverage.
721// - Start fuzzing as if the chosen unit was the only element of the corpus.
722// - When done, reset the coverage again.
723// - Merge the newly created corpus into the original one.
724void Fuzzer::Drill() {
725 // The corpus is already read, shuffled, and minimized.
726 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000727 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000728
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000729 Unit U = ChooseUnitToMutate();
730
Kostya Serebryany945761b2016-03-18 00:23:29 +0000731 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000732
733 std::vector<Unit> SavedCorpus;
734 SavedCorpus.swap(Corpus);
735 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000736 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000737 assert(Corpus.size() == 1);
738 RunOne(U);
739 PrintStats("DRILL ");
740 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
741 SavedOutputCorpusPath.swap(Options.OutputCorpus);
742 Loop();
743
Kostya Serebryany945761b2016-03-18 00:23:29 +0000744 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000745
746 PrintStats("REINIT");
747 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000748 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000749 RunOne(U);
750 PrintStats("MERGE ");
751 Options.PrintNEW = true;
752 size_t NumMerged = 0;
753 for (auto &U : Corpus) {
754 if (RunOne(U)) {
755 PrintStatusForNewUnit(U);
756 NumMerged++;
757 WriteToOutputCorpus(U);
758 }
759 }
760 PrintStats("MERGED");
761 if (NumMerged && Options.Verbosity)
762 Printf("Drilling discovered %zd new units\n", NumMerged);
763}
764
765void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000766 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000767 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000768 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000769 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000770 auto Now = system_clock::now();
771 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000772 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000773 LastCorpusReload = Now;
774 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000775 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000776 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000777 if (Options.MaxTotalTimeSec > 0 &&
778 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000779 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000780 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000781 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000782 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000783 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000784
785 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000786 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000787}
788
Ivan Krasindf919102016-01-22 22:28:27 +0000789void Fuzzer::UpdateCorpusDistribution() {
790 size_t N = Corpus.size();
791 std::vector<double> Intervals(N + 1);
792 std::vector<double> Weights(N);
793 std::iota(Intervals.begin(), Intervals.end(), 0);
794 std::iota(Weights.begin(), Weights.end(), 1);
795 CorpusDistribution = std::piecewise_constant_distribution<double>(
796 Intervals.begin(), Intervals.end(), Weights.begin());
797}
798
799} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000800
801extern "C" {
802
803size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
804 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000805 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000806}
807} // extern "C"