blob: 01692ecfa5782b66f3651cd4a42e7c4f34d808d1 [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;
Mike Aizatskyaf432a42016-05-24 23:14:29 +000036static const size_t TruncateMaxRuns = 1000;
Aaron Ballmanef116982015-01-29 16:58:29 +000037
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000038thread_local bool Fuzzer::IsMyThread;
39
Dan Liew1873a492016-06-07 23:32:50 +000040static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000041 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000042 "Did you use -fsanitize-coverage=... to build your code?\n",
43 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000044 exit(1);
45}
46
Dan Liew1873a492016-06-07 23:32:50 +000047#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000048 do { \
Dan Liew1873a492016-06-07 23:32:50 +000049 if (!(EF->fn)) \
50 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000051 } while (false)
52
Kostya Serebryany52a788e2015-03-31 20:13:20 +000053// Only one Fuzzer per process.
54static Fuzzer *F;
55
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000056void Fuzzer::ResetEdgeCoverage() {
57 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
58 EF->__sanitizer_reset_coverage();
59}
60
61void Fuzzer::ResetCounters() {
62 if (Options.UseCounters) {
63 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
64 }
65}
66
67void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
68 if (Options.UseCounters) {
69 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
70 C->CounterBitmap.resize(NumCounters);
71 }
72}
73
74// Records data to a maximum coverage tracker. Returns true if additional
75// coverage was discovered.
76bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
77 bool Res = false;
78
79 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
80 if (NewBlockCoverage > C->BlockCoverage) {
81 Res = true;
82 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000083 }
84
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000085 if (Options.UseIndirCalls &&
86 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
87 uint64_t NewCallerCalleeCoverage =
88 EF->__sanitizer_get_total_unique_caller_callee_pairs();
89 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000090 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000091 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000092 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000093 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000094
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000095 if (Options.UseCounters) {
96 uint64_t CounterDelta =
97 EF->__sanitizer_update_counter_bitset_and_clear_counters(
98 C->CounterBitmap.data());
99 if (CounterDelta > 0) {
100 Res = true;
101 C->CounterBitmapBits += CounterDelta;
102 }
103 }
104
105 size_t NewPCMapBits = PCMapMergeFromCurrent(C->PCMap);
106 if (NewPCMapBits > C->PCMapBits) {
107 Res = true;
108 C->PCMapBits = NewPCMapBits;
109 }
110
111 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
112 if (NewVPMapBits > C->VPMapBits) {
113 Res = true;
114 C->VPMapBits = NewVPMapBits;
115 }
116
117 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
118 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
119 if (NewPcBufferPos > C->PcBufferPos) {
120 Res = true;
121 C->PcBufferPos = NewPcBufferPos;
122 }
123
124 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
125 Printf("ERROR: PC buffer overflow\n");
126 _Exit(1);
127 }
128 }
129
130 return Res;
131}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000132
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000133// Leak detection is expensive, so we first check if there were more mallocs
134// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
135struct MallocFreeTracer {
136 void Start() {
137 Mallocs = 0;
138 Frees = 0;
139 }
140 // Returns true if there were more mallocs than frees.
141 bool Stop() { return Mallocs > Frees; }
142 std::atomic<size_t> Mallocs;
143 std::atomic<size_t> Frees;
144};
145
146static MallocFreeTracer AllocTracer;
147
148void MallocHook(const volatile void *ptr, size_t size) {
149 AllocTracer.Mallocs++;
150}
151void FreeHook(const volatile void *ptr) {
152 AllocTracer.Frees++;
153}
154
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000155Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000156 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000157 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000158 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000159 assert(!F);
160 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000161 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000162 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000163 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
164 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000165
166 if (Options.PrintNewCovPcs) {
167 PcBufferLen = 1 << 24;
168 PcBuffer = new uintptr_t[PcBufferLen];
169 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
170 }
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000171}
Aaron Ballmanef116982015-01-29 16:58:29 +0000172
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000173Fuzzer::~Fuzzer() { }
174
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000175void Fuzzer::LazyAllocateCurrentUnitData() {
176 if (CurrentUnitData || Options.MaxLen == 0) return;
177 CurrentUnitData = new uint8_t[Options.MaxLen];
178}
179
Aaron Ballmanef116982015-01-29 16:58:29 +0000180void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000181 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
182 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000183}
184
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000185void Fuzzer::StaticDeathCallback() {
186 assert(F);
187 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000188}
189
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000190void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany311cc832016-05-28 04:19:46 +0000191 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000192 MD.PrintMutationSequence();
193 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000194 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000195 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000196 PrintHexArray(CurrentUnitData, UnitSize, "\n");
197 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000198 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000199 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
200 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000201}
202
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000203NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000204void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000205 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000206 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000207}
208
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000209void Fuzzer::StaticAlarmCallback() {
210 assert(F);
211 F->AlarmCallback();
212}
213
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000214void Fuzzer::StaticCrashSignalCallback() {
215 assert(F);
216 F->CrashCallback();
217}
218
219void Fuzzer::StaticInterruptCallback() {
220 assert(F);
221 F->InterruptCallback();
222}
223
224void Fuzzer::CrashCallback() {
225 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000226 if (EF->__sanitizer_print_stack_trace)
227 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000228 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
229 " Combine libFuzzer with AddressSanitizer or similar for better "
230 "crash reports.\n");
231 Printf("SUMMARY: libFuzzer: deadly signal\n");
232 DumpCurrentUnit("crash-");
233 PrintFinalStats();
234 exit(Options.ErrorExitCode);
235}
236
237void Fuzzer::InterruptCallback() {
238 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
239 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000240 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000241}
242
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000243NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000244void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000245 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000246 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000247 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000248 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000249 size_t Seconds =
250 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000251 if (Seconds == 0)
252 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000253 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000254 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000255 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000256 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000257 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
258 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000259 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000260 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
261 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000262 if (EF->__sanitizer_print_stack_trace)
263 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000264 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000265 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000266 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000267 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000268}
269
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000270void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000271 Printf(
272 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
273 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000274 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000275 if (EF->__sanitizer_print_memory_profile)
276 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000277 DumpCurrentUnit("oom-");
278 Printf("SUMMARY: libFuzzer: out-of-memory\n");
279 PrintFinalStats();
280 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000281}
282
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000283void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000284 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000285 if (Options.OutputCSV) {
286 static bool csvHeaderPrinted = false;
287 if (!csvHeaderPrinted) {
288 csvHeaderPrinted = true;
289 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
290 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000291 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000292 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
293 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000294 }
295
296 if (!Options.Verbosity)
297 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000298 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000299 if (MaxCoverage.BlockCoverage)
300 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyc98ef712016-08-16 17:37:13 +0000301 if (MaxCoverage.PCMapBits)
302 Printf(" path: %zd", MaxCoverage.PCMapBits);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000303 if (MaxCoverage.VPMapBits)
304 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000305 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000306 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000307 if (MaxCoverage.CallerCalleeCoverage)
308 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000309 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000310 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000311}
312
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000313void Fuzzer::PrintFinalStats() {
314 if (!Options.PrintFinalStats) return;
315 size_t ExecPerSec = execPerSec();
316 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
317 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
318 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
319 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
320 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
321}
322
Kostya Serebryany64d24572016-03-12 01:57:04 +0000323size_t Fuzzer::MaxUnitSizeInCorpus() const {
324 size_t Res = 0;
325 for (auto &X : Corpus)
326 Res = std::max(Res, X.size());
327 return Res;
328}
329
330void Fuzzer::SetMaxLen(size_t MaxLen) {
331 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
332 assert(MaxLen);
333 Options.MaxLen = MaxLen;
334 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
335}
336
337
338void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000339 if (Options.OutputCorpus.empty())
340 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000341 std::vector<Unit> AdditionalCorpus;
342 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000343 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000344 if (Corpus.empty()) {
345 Corpus = AdditionalCorpus;
346 return;
347 }
Ivan Krasindf919102016-01-22 22:28:27 +0000348 if (!Options.Reload)
349 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000350 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000351 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000352 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000353 if (X.size() > MaxSize)
354 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000355 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000356 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000357 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000358 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000359 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000360 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000361 }
362 }
363}
364
Kostya Serebryany945761b2016-03-18 00:23:29 +0000365void Fuzzer::ShuffleCorpus(UnitVector *V) {
366 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
367 if (Options.PreferSmall)
368 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
369 return A.size() < B.size();
370 });
371}
372
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000373// Tries random prefixes of corpus items.
374// Prefix length is chosen according to exponential distribution
375// to sample short lengths much more heavily.
376void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
377 size_t MaxCorpusLen = 0;
378 for (const auto &U : Corpus)
379 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
380
381 if (MaxCorpusLen <= 1)
382 return;
383
384 // 50% of exponential distribution is Log[2]/lambda.
385 // Choose lambda so that median is MaxCorpusLen / 2.
386 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
387 std::exponential_distribution<> Dist(Lambda);
388 std::vector<double> Sizes;
389 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
390 Sizes.reserve(TruncatePoints);
391 for (size_t I = 0; I < TruncatePoints; ++I) {
392 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
393 }
394 std::sort(Sizes.begin(), Sizes.end());
395
396 for (size_t S : Sizes) {
397 for (const auto &U : Corpus) {
398 if (S < U.size() && RunOne(U.data(), S)) {
399 Unit U1(U.begin(), U.begin() + S);
400 NewCorpus->push_back(U1);
401 WriteToOutputCorpus(U1);
402 PrintStatusForNewUnit(U1);
403 }
404 }
405 }
406 PrintStats("TRUNC ");
407}
408
Aaron Ballmanef116982015-01-29 16:58:29 +0000409void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000410 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000411 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000412 if (Options.ShuffleAtStartUp)
413 ShuffleCorpus(&Corpus);
414
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000415 if (Options.TruncateUnits) {
416 ResetCoverage();
417 TruncateUnits(&NewCorpus);
418 ResetCoverage();
419 }
420
Kostya Serebryany945761b2016-03-18 00:23:29 +0000421 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000422 bool NewCoverage = RunOne(U);
423 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000424 NewCorpus.push_back(U);
425 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000426 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000427 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000428 TryDetectingAMemoryLeak(U.data(), U.size(),
429 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000430 }
431 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000432 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000433 for (auto &X : Corpus)
434 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000435 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000436 if (Corpus.empty()) {
437 Printf("ERROR: no interesting inputs were found. "
438 "Is the code instrumented for coverage? Exiting.\n");
439 exit(1);
440 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000441}
442
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000443bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000444 PrevPcBufferPos = MaxCoverage.PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000445 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000446
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000447 return Res;
448}
449
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000450bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000451 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000452
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000453 // TODO(aizatsky): this Reset call seems to be not needed.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000454 ResetCounters();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000455 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000456 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000457
Kostya Serebryany16901a92015-03-30 23:04:35 +0000458 auto UnitStopTime = system_clock::now();
459 auto TimeOfUnit =
460 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000461 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
462 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000463 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000464 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
465 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000466 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000467 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000468 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000469 }
470 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000471}
472
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000473void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000474 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
475 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000476 if (RunOne(Data, Size))
477 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000478}
479
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000480size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000481 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000482 *Data = CurrentUnitData;
483 return CurrentUnitSize;
484}
485
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000486void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000487 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000488 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000489 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000490 // We copy the contents of Unit into a separate heap buffer
491 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000492 uint8_t *DataCopy = new uint8_t[Size];
493 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000494 if (CurrentUnitData && CurrentUnitData != Data)
495 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000496 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000497 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000498 AllocTracer.Start();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000499 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000500 (void)Res;
501 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000502 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000503 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000504 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000505}
506
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000507std::string Fuzzer::Coverage::DebugString() const {
508 std::string Result =
509 std::string("Coverage{") + "BlockCoverage=" +
510 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
511 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000512 std::to_string(CounterBitmapBits) + " PCMapBits=" +
513 std::to_string(PCMapBits) + " VPMapBits " +
514 std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000515 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000516}
517
518void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000519 if (Options.OnlyASCII)
520 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000521 if (Options.OutputCorpus.empty())
522 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000523 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
524 WriteToFile(U, Path);
525 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000526 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000527}
528
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000529void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000530 if (!Options.SaveArtifacts)
531 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000532 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000533 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000534 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000535 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000536 Printf("artifact_prefix='%s'; Test unit written to %s\n",
537 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000538 if (U.size() <= kMaxUnitSizeToPrint)
539 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000540}
541
542void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000543 if (Options.OutputCorpus.empty())
544 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000545 for (const auto &U : Corpus)
546 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
547 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000548 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
549 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000550}
551
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000552void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
553 if (!Options.PrintNEW)
554 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000555 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000556 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000557 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000558 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000559 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000560 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000561}
562
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000563void Fuzzer::PrintNewPCs() {
564 if (Options.PrintNewCovPcs && PrevPcBufferPos != MaxCoverage.PcBufferPos) {
565 for (size_t I = PrevPcBufferPos; I < MaxCoverage.PcBufferPos; ++I) {
566 if (EF->__sanitizer_symbolize_pc) {
567 char PcDescr[1024];
568 EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PcBuffer[I]),
569 "%p %F %L", PcDescr, sizeof(PcDescr));
570 Printf("\tNEW_PC: %s\n", PcDescr);
571 } else {
572 Printf("\tNEW_PC: %p\n", PcBuffer[I]);
573 }
574 }
575 }
576}
577
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000578void Fuzzer::ReportNewCoverage(const Unit &U) {
579 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000580 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000581 UnitHashesAddedToCorpus.insert(Hash(U));
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 Serebryany0f0fa4f2016-08-25 22:35:08 +0000586 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;
596 size_t OldSize = Res.size();
597 for (int Iter = 0; Iter < 10; Iter++) {
598 ShuffleCorpus(&Res);
599 ResetCoverage();
600
601 for (auto &U : Initial)
602 RunOne(U);
603
604 Corpus.clear();
605 for (auto &U : Res)
606 if (RunOne(U))
607 Corpus.push_back(U);
608
609 char Stat[7] = "MIN ";
610 Stat[3] = '0' + Iter;
611 PrintStats(Stat);
612
613 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000614 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000615 Res.swap(Corpus);
616
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000617 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000618 break;
619 OldSize = NewSize;
620 }
621 return Res;
622}
623
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000624void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
625 if (Corpora.size() <= 1) {
626 Printf("Merge requires two or more corpus dirs\n");
627 return;
628 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000629 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
630
Kostya Serebryany945761b2016-03-18 00:23:29 +0000631 assert(Options.MaxLen > 0);
632 UnitVector Initial, Extra;
633 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
634 for (auto &C : ExtraCorpora)
635 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
636
637 if (!Initial.empty()) {
638 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
639 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000640 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000641
642 Printf("=== Merging extra %zd units\n", Extra.size());
643 auto Res = FindExtraUnits(Initial, Extra);
644
645 for (auto &U: Res)
646 WriteToOutputCorpus(U);
647
648 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000649}
650
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000651// Tries detecting a memory leak on the particular input that we have just
652// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000653void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
654 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000655 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
656 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000657 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
658 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000659 return; // No lsan.
660 // Run the target once again, but with lsan disabled so that if there is
661 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000662 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000663 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000664 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000665 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000666 if (NumberOfLeakDetectionAttempts++ > 1000) {
667 Options.DetectLeaks = false;
668 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
669 " Most likely the target function accumulates allocated\n"
670 " memory in a global state w/o actually leaking it.\n"
671 " If LeakSanitizer is enabled in this process it will still\n"
672 " run on the process shutdown.\n");
673 return;
674 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000675 // Now perform the actual lsan pass. This is expensive and we must ensure
676 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000677 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000678 if (DuringInitialCorpusExecution)
679 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
680 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000681 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000682 DumpCurrentUnit("leak-");
683 PrintFinalStats();
684 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
685 }
686}
687
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000688void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000689 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000690 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000691
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000692 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000693 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000694 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000695 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000696 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000697 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000698
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000699 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000700 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000701 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000702 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000703 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000704 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000705 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000706 if (i == 0)
707 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000708 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000709 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000710 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000711 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000712 }
713}
714
Kostya Serebryanye6926212015-11-04 23:22:25 +0000715// Returns an index of random unit from the corpus to mutate.
716// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000717// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000718size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000719 size_t Idx =
720 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000721 assert(Idx < Corpus.size());
722 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000723}
724
Kostya Serebryany945761b2016-03-18 00:23:29 +0000725void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000726 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000727 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000728 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000729}
730
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000731// Experimental search heuristic: drilling.
732// - Read, shuffle, execute and minimize the corpus.
733// - Choose one random unit.
734// - Reset the coverage.
735// - Start fuzzing as if the chosen unit was the only element of the corpus.
736// - When done, reset the coverage again.
737// - Merge the newly created corpus into the original one.
738void Fuzzer::Drill() {
739 // The corpus is already read, shuffled, and minimized.
740 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000741 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000742
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000743 Unit U = ChooseUnitToMutate();
744
Kostya Serebryany945761b2016-03-18 00:23:29 +0000745 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000746
747 std::vector<Unit> SavedCorpus;
748 SavedCorpus.swap(Corpus);
749 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000750 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000751 assert(Corpus.size() == 1);
752 RunOne(U);
753 PrintStats("DRILL ");
754 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
755 SavedOutputCorpusPath.swap(Options.OutputCorpus);
756 Loop();
757
Kostya Serebryany945761b2016-03-18 00:23:29 +0000758 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000759
760 PrintStats("REINIT");
761 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000762 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000763 RunOne(U);
764 PrintStats("MERGE ");
765 Options.PrintNEW = true;
766 size_t NumMerged = 0;
767 for (auto &U : Corpus) {
768 if (RunOne(U)) {
769 PrintStatusForNewUnit(U);
770 NumMerged++;
771 WriteToOutputCorpus(U);
772 }
773 }
774 PrintStats("MERGED");
775 if (NumMerged && Options.Verbosity)
776 Printf("Drilling discovered %zd new units\n", NumMerged);
777}
778
779void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000780 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000781 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000782 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000783 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000784 auto Now = system_clock::now();
785 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000786 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000787 LastCorpusReload = Now;
788 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000789 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000790 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000791 if (Options.MaxTotalTimeSec > 0 &&
792 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000793 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000794 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000795 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000796 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000797 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000798
799 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000800 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000801}
802
Ivan Krasindf919102016-01-22 22:28:27 +0000803void Fuzzer::UpdateCorpusDistribution() {
804 size_t N = Corpus.size();
805 std::vector<double> Intervals(N + 1);
806 std::vector<double> Weights(N);
807 std::iota(Intervals.begin(), Intervals.end(), 0);
808 std::iota(Weights.begin(), Weights.end(), 1);
809 CorpusDistribution = std::piecewise_constant_distribution<double>(
810 Intervals.begin(), Intervals.end(), Weights.begin());
811}
812
813} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000814
815extern "C" {
816
817size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
818 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000819 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000820}
821} // extern "C"