blob: 4d2b6973fbfa009b88c49fe4ad6aeb243586dee2 [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
60void Fuzzer::ResetCounters() {
61 if (Options.UseCounters) {
62 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
63 }
64}
65
66void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
67 if (Options.UseCounters) {
68 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
69 C->CounterBitmap.resize(NumCounters);
70 }
71}
72
73// Records data to a maximum coverage tracker. Returns true if additional
74// coverage was discovered.
75bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
76 bool Res = false;
77
78 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
79 if (NewBlockCoverage > C->BlockCoverage) {
80 Res = true;
81 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000082 }
83
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000084 if (Options.UseIndirCalls &&
85 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
86 uint64_t NewCallerCalleeCoverage =
87 EF->__sanitizer_get_total_unique_caller_callee_pairs();
88 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000089 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000090 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000091 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000092 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000093
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000094 if (Options.UseCounters) {
95 uint64_t CounterDelta =
96 EF->__sanitizer_update_counter_bitset_and_clear_counters(
97 C->CounterBitmap.data());
98 if (CounterDelta > 0) {
99 Res = true;
100 C->CounterBitmapBits += CounterDelta;
101 }
102 }
103
104 size_t NewPCMapBits = PCMapMergeFromCurrent(C->PCMap);
105 if (NewPCMapBits > C->PCMapBits) {
106 Res = true;
107 C->PCMapBits = NewPCMapBits;
108 }
109
110 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
111 if (NewVPMapBits > C->VPMapBits) {
112 Res = true;
113 C->VPMapBits = NewVPMapBits;
114 }
115
116 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
117 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
118 if (NewPcBufferPos > C->PcBufferPos) {
119 Res = true;
120 C->PcBufferPos = NewPcBufferPos;
121 }
122
123 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
124 Printf("ERROR: PC buffer overflow\n");
125 _Exit(1);
126 }
127 }
128
129 return Res;
130}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000131
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000132// Leak detection is expensive, so we first check if there were more mallocs
133// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
134struct MallocFreeTracer {
135 void Start() {
136 Mallocs = 0;
137 Frees = 0;
138 }
139 // Returns true if there were more mallocs than frees.
140 bool Stop() { return Mallocs > Frees; }
141 std::atomic<size_t> Mallocs;
142 std::atomic<size_t> Frees;
143};
144
145static MallocFreeTracer AllocTracer;
146
147void MallocHook(const volatile void *ptr, size_t size) {
148 AllocTracer.Mallocs++;
149}
150void FreeHook(const volatile void *ptr) {
151 AllocTracer.Frees++;
152}
153
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000154Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000155 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000156 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000157 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000158 assert(!F);
159 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000160 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000161 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000162 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
163 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000164
165 if (Options.PrintNewCovPcs) {
166 PcBufferLen = 1 << 24;
167 PcBuffer = new uintptr_t[PcBufferLen];
168 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
169 }
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000170}
Aaron Ballmanef116982015-01-29 16:58:29 +0000171
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000172Fuzzer::~Fuzzer() { }
173
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000174void Fuzzer::LazyAllocateCurrentUnitData() {
175 if (CurrentUnitData || Options.MaxLen == 0) return;
176 CurrentUnitData = new uint8_t[Options.MaxLen];
177}
178
Aaron Ballmanef116982015-01-29 16:58:29 +0000179void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000180 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
181 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000182}
183
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000184void Fuzzer::StaticDeathCallback() {
185 assert(F);
186 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000187}
188
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000189void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany311cc832016-05-28 04:19:46 +0000190 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000191 MD.PrintMutationSequence();
192 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000193 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000194 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000195 PrintHexArray(CurrentUnitData, UnitSize, "\n");
196 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000197 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000198 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
199 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000200}
201
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000202NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000203void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000204 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000205 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000206}
207
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000208void Fuzzer::StaticAlarmCallback() {
209 assert(F);
210 F->AlarmCallback();
211}
212
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000213void Fuzzer::StaticCrashSignalCallback() {
214 assert(F);
215 F->CrashCallback();
216}
217
218void Fuzzer::StaticInterruptCallback() {
219 assert(F);
220 F->InterruptCallback();
221}
222
223void Fuzzer::CrashCallback() {
224 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000225 if (EF->__sanitizer_print_stack_trace)
226 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000227 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
228 " Combine libFuzzer with AddressSanitizer or similar for better "
229 "crash reports.\n");
230 Printf("SUMMARY: libFuzzer: deadly signal\n");
231 DumpCurrentUnit("crash-");
232 PrintFinalStats();
233 exit(Options.ErrorExitCode);
234}
235
236void Fuzzer::InterruptCallback() {
237 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
238 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000239 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000240}
241
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000242NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000243void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000244 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000245 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000246 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000247 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000248 size_t Seconds =
249 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000250 if (Seconds == 0)
251 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000252 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000253 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000254 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000255 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000256 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
257 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000258 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000259 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
260 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000261 if (EF->__sanitizer_print_stack_trace)
262 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000263 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000264 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000265 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000266 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000267}
268
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000269void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000270 Printf(
271 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
272 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000273 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000274 if (EF->__sanitizer_print_memory_profile)
275 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000276 DumpCurrentUnit("oom-");
277 Printf("SUMMARY: libFuzzer: out-of-memory\n");
278 PrintFinalStats();
279 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000280}
281
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000282void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000283 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000284 if (Options.OutputCSV) {
285 static bool csvHeaderPrinted = false;
286 if (!csvHeaderPrinted) {
287 csvHeaderPrinted = true;
288 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
289 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000290 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000291 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
292 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000293 }
294
295 if (!Options.Verbosity)
296 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000297 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000298 if (MaxCoverage.BlockCoverage)
299 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyc98ef712016-08-16 17:37:13 +0000300 if (MaxCoverage.PCMapBits)
301 Printf(" path: %zd", MaxCoverage.PCMapBits);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000302 if (MaxCoverage.VPMapBits)
303 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000304 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000305 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000306 if (MaxCoverage.CallerCalleeCoverage)
307 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000308 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000309 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000310}
311
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000312void Fuzzer::PrintFinalStats() {
313 if (!Options.PrintFinalStats) return;
314 size_t ExecPerSec = execPerSec();
315 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
316 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
317 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
318 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
319 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
320}
321
Kostya Serebryany64d24572016-03-12 01:57:04 +0000322size_t Fuzzer::MaxUnitSizeInCorpus() const {
323 size_t Res = 0;
324 for (auto &X : Corpus)
325 Res = std::max(Res, X.size());
326 return Res;
327}
328
329void Fuzzer::SetMaxLen(size_t MaxLen) {
330 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
331 assert(MaxLen);
332 Options.MaxLen = MaxLen;
333 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
334}
335
336
337void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000338 if (Options.OutputCorpus.empty())
339 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000340 std::vector<Unit> AdditionalCorpus;
341 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000342 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000343 if (Corpus.empty()) {
344 Corpus = AdditionalCorpus;
345 return;
346 }
Ivan Krasindf919102016-01-22 22:28:27 +0000347 if (!Options.Reload)
348 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000349 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000350 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000351 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000352 if (X.size() > MaxSize)
353 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000354 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000355 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000356 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000357 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000358 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000359 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000360 }
361 }
362}
363
Kostya Serebryany945761b2016-03-18 00:23:29 +0000364void Fuzzer::ShuffleCorpus(UnitVector *V) {
365 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
366 if (Options.PreferSmall)
367 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
368 return A.size() < B.size();
369 });
370}
371
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000372// Tries random prefixes of corpus items.
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000373void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000374 std::vector<double> Fractions = {0.25, 0.5, 0.75, 1.0};
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000375
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000376 size_t TruncInputs = 0;
377 for (double Fraction : Fractions) {
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000378 for (const auto &U : Corpus) {
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000379 uint64_t S = MD.GetRand()(U.size() * Fraction);
380 if (!S || !RunOne(U.data(), S))
381 continue;
382 TruncInputs++;
383 Unit U1(U.begin(), U.begin() + S);
384 NewCorpus->push_back(U1);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000385 }
386 }
Mike Aizatskyb077d3f2016-08-30 20:49:07 +0000387 if (TruncInputs)
388 Printf("\tINFO TRUNC %zd units added to in-memory corpus\n", TruncInputs);
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000389}
390
Aaron Ballmanef116982015-01-29 16:58:29 +0000391void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000392 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000393 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000394 if (Options.ShuffleAtStartUp)
395 ShuffleCorpus(&Corpus);
396
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000397 if (Options.TruncateUnits) {
398 ResetCoverage();
399 TruncateUnits(&NewCorpus);
400 ResetCoverage();
401 }
402
Kostya Serebryany945761b2016-03-18 00:23:29 +0000403 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000404 bool NewCoverage = RunOne(U);
405 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000406 NewCorpus.push_back(U);
407 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000408 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000409 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000410 TryDetectingAMemoryLeak(U.data(), U.size(),
411 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000412 }
413 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000414 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000415 for (auto &X : Corpus)
416 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000417 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000418 if (Corpus.empty()) {
419 Printf("ERROR: no interesting inputs were found. "
420 "Is the code instrumented for coverage? Exiting.\n");
421 exit(1);
422 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000423}
424
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000425bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000426 PrevPcBufferPos = MaxCoverage.PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000427 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000428
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000429 return Res;
430}
431
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000432bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000433 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000434
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000435 // TODO(aizatsky): this Reset call seems to be not needed.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000436 ResetCounters();
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 Serebryanyf67357c2016-08-25 01:25:03 +0000481 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000482 (void)Res;
483 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000484 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000485 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000486 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000487}
488
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000489std::string Fuzzer::Coverage::DebugString() const {
490 std::string Result =
491 std::string("Coverage{") + "BlockCoverage=" +
492 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
493 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000494 std::to_string(CounterBitmapBits) + " PCMapBits=" +
495 std::to_string(PCMapBits) + " VPMapBits " +
496 std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000497 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000498}
499
500void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000501 if (Options.OnlyASCII)
502 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000503 if (Options.OutputCorpus.empty())
504 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000505 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
506 WriteToFile(U, Path);
507 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000508 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000509}
510
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000511void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000512 if (!Options.SaveArtifacts)
513 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000514 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000515 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000516 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000517 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000518 Printf("artifact_prefix='%s'; Test unit written to %s\n",
519 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000520 if (U.size() <= kMaxUnitSizeToPrint)
521 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000522}
523
524void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000525 if (Options.OutputCorpus.empty())
526 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000527 for (const auto &U : Corpus)
528 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
529 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000530 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
531 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000532}
533
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000534void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
535 if (!Options.PrintNEW)
536 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000537 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000538 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000539 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000540 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000541 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000542 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000543}
544
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000545void Fuzzer::PrintNewPCs() {
546 if (Options.PrintNewCovPcs && PrevPcBufferPos != MaxCoverage.PcBufferPos) {
547 for (size_t I = PrevPcBufferPos; I < MaxCoverage.PcBufferPos; ++I) {
548 if (EF->__sanitizer_symbolize_pc) {
549 char PcDescr[1024];
550 EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PcBuffer[I]),
551 "%p %F %L", PcDescr, sizeof(PcDescr));
552 Printf("\tNEW_PC: %s\n", PcDescr);
553 } else {
554 Printf("\tNEW_PC: %p\n", PcBuffer[I]);
555 }
556 }
557 }
558}
559
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000560void Fuzzer::ReportNewCoverage(const Unit &U) {
561 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000562 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000563 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000564 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000565 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000566 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000567 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000568 PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000569}
570
Kostya Serebryany945761b2016-03-18 00:23:29 +0000571// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
572// We do it by actually executing the units, sometimes more than once,
573// because we may be using different coverage-like signals and the only
574// common thing between them is that we can say "this unit found new stuff".
575UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
576 const UnitVector &Extra) {
577 UnitVector Res = Extra;
578 size_t OldSize = Res.size();
579 for (int Iter = 0; Iter < 10; Iter++) {
580 ShuffleCorpus(&Res);
581 ResetCoverage();
582
583 for (auto &U : Initial)
584 RunOne(U);
585
586 Corpus.clear();
587 for (auto &U : Res)
588 if (RunOne(U))
589 Corpus.push_back(U);
590
591 char Stat[7] = "MIN ";
592 Stat[3] = '0' + Iter;
593 PrintStats(Stat);
594
595 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000596 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000597 Res.swap(Corpus);
598
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000599 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000600 break;
601 OldSize = NewSize;
602 }
603 return Res;
604}
605
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000606void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
607 if (Corpora.size() <= 1) {
608 Printf("Merge requires two or more corpus dirs\n");
609 return;
610 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000611 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
612
Kostya Serebryany945761b2016-03-18 00:23:29 +0000613 assert(Options.MaxLen > 0);
614 UnitVector Initial, Extra;
615 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
616 for (auto &C : ExtraCorpora)
617 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
618
619 if (!Initial.empty()) {
620 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
621 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000622 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000623
624 Printf("=== Merging extra %zd units\n", Extra.size());
625 auto Res = FindExtraUnits(Initial, Extra);
626
627 for (auto &U: Res)
628 WriteToOutputCorpus(U);
629
630 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000631}
632
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000633// Tries detecting a memory leak on the particular input that we have just
634// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000635void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
636 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000637 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
638 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000639 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
640 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000641 return; // No lsan.
642 // Run the target once again, but with lsan disabled so that if there is
643 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000644 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000645 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000646 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000647 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000648 if (NumberOfLeakDetectionAttempts++ > 1000) {
649 Options.DetectLeaks = false;
650 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
651 " Most likely the target function accumulates allocated\n"
652 " memory in a global state w/o actually leaking it.\n"
653 " If LeakSanitizer is enabled in this process it will still\n"
654 " run on the process shutdown.\n");
655 return;
656 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000657 // Now perform the actual lsan pass. This is expensive and we must ensure
658 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000659 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000660 if (DuringInitialCorpusExecution)
661 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
662 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000663 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000664 DumpCurrentUnit("leak-");
665 PrintFinalStats();
666 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
667 }
668}
669
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000670void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000671 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000672 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000673
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000674 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000675 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000676 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000677 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000678 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000679 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000680
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000681 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000682 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000683 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000684 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000685 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000686 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000687 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000688 if (i == 0)
689 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000690 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000691 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000692 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000693 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000694 }
695}
696
Kostya Serebryanye6926212015-11-04 23:22:25 +0000697// Returns an index of random unit from the corpus to mutate.
698// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000699// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000700size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000701 size_t Idx =
702 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000703 assert(Idx < Corpus.size());
704 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000705}
706
Kostya Serebryany945761b2016-03-18 00:23:29 +0000707void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000708 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000709 MaxCoverage.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000710 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000711}
712
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000713// Experimental search heuristic: drilling.
714// - Read, shuffle, execute and minimize the corpus.
715// - Choose one random unit.
716// - Reset the coverage.
717// - Start fuzzing as if the chosen unit was the only element of the corpus.
718// - When done, reset the coverage again.
719// - Merge the newly created corpus into the original one.
720void Fuzzer::Drill() {
721 // The corpus is already read, shuffled, and minimized.
722 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000723 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000724
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000725 Unit U = ChooseUnitToMutate();
726
Kostya Serebryany945761b2016-03-18 00:23:29 +0000727 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000728
729 std::vector<Unit> SavedCorpus;
730 SavedCorpus.swap(Corpus);
731 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000732 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000733 assert(Corpus.size() == 1);
734 RunOne(U);
735 PrintStats("DRILL ");
736 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
737 SavedOutputCorpusPath.swap(Options.OutputCorpus);
738 Loop();
739
Kostya Serebryany945761b2016-03-18 00:23:29 +0000740 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000741
742 PrintStats("REINIT");
743 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000744 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000745 RunOne(U);
746 PrintStats("MERGE ");
747 Options.PrintNEW = true;
748 size_t NumMerged = 0;
749 for (auto &U : Corpus) {
750 if (RunOne(U)) {
751 PrintStatusForNewUnit(U);
752 NumMerged++;
753 WriteToOutputCorpus(U);
754 }
755 }
756 PrintStats("MERGED");
757 if (NumMerged && Options.Verbosity)
758 Printf("Drilling discovered %zd new units\n", NumMerged);
759}
760
761void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000762 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000763 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000764 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000765 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000766 auto Now = system_clock::now();
767 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000768 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000769 LastCorpusReload = Now;
770 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000771 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000772 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000773 if (Options.MaxTotalTimeSec > 0 &&
774 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000775 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000776 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000777 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000778 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000779 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000780
781 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000782 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000783}
784
Ivan Krasindf919102016-01-22 22:28:27 +0000785void Fuzzer::UpdateCorpusDistribution() {
786 size_t N = Corpus.size();
787 std::vector<double> Intervals(N + 1);
788 std::vector<double> Weights(N);
789 std::iota(Intervals.begin(), Intervals.end(), 0);
790 std::iota(Weights.begin(), Weights.end(), 1);
791 CorpusDistribution = std::piecewise_constant_distribution<double>(
792 Intervals.begin(), Intervals.end(), Weights.begin());
793}
794
795} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000796
797extern "C" {
798
799size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
800 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000801 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000802}
803} // extern "C"