blob: 51cb8703c26d9977fc895505e62378a72545acd7 [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
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000056struct CoverageController {
57 static void Reset() {
Dan Liew1873a492016-06-07 23:32:50 +000058 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
59 EF->__sanitizer_reset_coverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000060 PcMapResetCurrent();
61 }
62
63 static void ResetCounters(const Fuzzer::FuzzingOptions &Options) {
64 if (Options.UseCounters) {
Dan Liew1873a492016-06-07 23:32:50 +000065 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000066 }
67 }
68
69 static void Prepare(const Fuzzer::FuzzingOptions &Options,
70 Fuzzer::Coverage *C) {
71 if (Options.UseCounters) {
Dan Liew1873a492016-06-07 23:32:50 +000072 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000073 C->CounterBitmap.resize(NumCounters);
74 }
75 }
76
77 // Records data to a maximum coverage tracker. Returns true if additional
78 // coverage was discovered.
79 static bool RecordMax(const Fuzzer::FuzzingOptions &Options,
80 Fuzzer::Coverage *C) {
81 bool Res = false;
82
Dan Liew1873a492016-06-07 23:32:50 +000083 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000084 if (NewBlockCoverage > C->BlockCoverage) {
85 Res = true;
86 C->BlockCoverage = NewBlockCoverage;
87 }
88
89 if (Options.UseIndirCalls &&
Dan Liew1873a492016-06-07 23:32:50 +000090 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000091 uint64_t NewCallerCalleeCoverage =
Dan Liew1873a492016-06-07 23:32:50 +000092 EF->__sanitizer_get_total_unique_caller_callee_pairs();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000093 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
94 Res = true;
95 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
96 }
97 }
98
99 if (Options.UseCounters) {
100 uint64_t CounterDelta =
Dan Liew1873a492016-06-07 23:32:50 +0000101 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000102 C->CounterBitmap.data());
103 if (CounterDelta > 0) {
104 Res = true;
105 C->CounterBitmapBits += CounterDelta;
106 }
107 }
108
109 uint64_t NewPcMapBits = PcMapMergeInto(&C->PCMap);
110 if (NewPcMapBits > C->PcMapBits) {
111 Res = true;
112 C->PcMapBits = NewPcMapBits;
113 }
114
115 uintptr_t *CoverageBuf;
Dan Liew1873a492016-06-07 23:32:50 +0000116 uint64_t NewPcBufferLen =
117 EF->__sanitizer_get_coverage_pc_buffer(&CoverageBuf);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000118 if (NewPcBufferLen > C->PcBufferLen) {
119 Res = true;
120 C->PcBufferLen = NewPcBufferLen;
121 }
122
123 return Res;
124 }
125};
126
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000127// Leak detection is expensive, so we first check if there were more mallocs
128// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
129struct MallocFreeTracer {
130 void Start() {
131 Mallocs = 0;
132 Frees = 0;
133 }
134 // Returns true if there were more mallocs than frees.
135 bool Stop() { return Mallocs > Frees; }
136 std::atomic<size_t> Mallocs;
137 std::atomic<size_t> Frees;
138};
139
140static MallocFreeTracer AllocTracer;
141
142void MallocHook(const volatile void *ptr, size_t size) {
143 AllocTracer.Mallocs++;
144}
145void FreeHook(const volatile void *ptr) {
146 AllocTracer.Frees++;
147}
148
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000149Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
150 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000151 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000152 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000153 assert(!F);
154 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000155 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000156 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000157 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
158 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000159}
Aaron Ballmanef116982015-01-29 16:58:29 +0000160
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000161void Fuzzer::LazyAllocateCurrentUnitData() {
162 if (CurrentUnitData || Options.MaxLen == 0) return;
163 CurrentUnitData = new uint8_t[Options.MaxLen];
164}
165
Aaron Ballmanef116982015-01-29 16:58:29 +0000166void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000167 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
168 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000169}
170
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000171void Fuzzer::StaticDeathCallback() {
172 assert(F);
173 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000174}
175
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000176void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany311cc832016-05-28 04:19:46 +0000177 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000178 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000179 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000180 PrintHexArray(CurrentUnitData, UnitSize, "\n");
181 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000182 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000183 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
184 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000185}
186
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000187NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000188void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000189 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000190 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000191}
192
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000193void Fuzzer::StaticAlarmCallback() {
194 assert(F);
195 F->AlarmCallback();
196}
197
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000198void Fuzzer::StaticCrashSignalCallback() {
199 assert(F);
200 F->CrashCallback();
201}
202
203void Fuzzer::StaticInterruptCallback() {
204 assert(F);
205 F->InterruptCallback();
206}
207
208void Fuzzer::CrashCallback() {
209 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000210 if (EF->__sanitizer_print_stack_trace)
211 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000212 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
213 " Combine libFuzzer with AddressSanitizer or similar for better "
214 "crash reports.\n");
215 Printf("SUMMARY: libFuzzer: deadly signal\n");
216 DumpCurrentUnit("crash-");
217 PrintFinalStats();
218 exit(Options.ErrorExitCode);
219}
220
221void Fuzzer::InterruptCallback() {
222 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
223 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000224 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000225}
226
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000227NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000228void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000229 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000230 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000231 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000232 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000233 size_t Seconds =
234 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000235 if (Seconds == 0)
236 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000237 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000238 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000239 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000240 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000241 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
242 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000243 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000244 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
245 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000246 if (EF->__sanitizer_print_stack_trace)
247 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000248 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000249 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000250 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000251 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000252}
253
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000254void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000255 Printf(
256 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
257 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000258 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000259 if (EF->__sanitizer_print_memory_profile)
260 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000261 DumpCurrentUnit("oom-");
262 Printf("SUMMARY: libFuzzer: out-of-memory\n");
263 PrintFinalStats();
264 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000265}
266
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000267void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000268 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000269 if (Options.OutputCSV) {
270 static bool csvHeaderPrinted = false;
271 if (!csvHeaderPrinted) {
272 csvHeaderPrinted = true;
273 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
274 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000275 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000276 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
277 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000278 }
279
280 if (!Options.Verbosity)
281 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000282 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000283 if (MaxCoverage.BlockCoverage)
284 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
285 if (MaxCoverage.PcMapBits)
286 Printf(" path: %zd", MaxCoverage.PcMapBits);
287 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000288 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000289 if (MaxCoverage.CallerCalleeCoverage)
290 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000291 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000292 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000293}
294
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000295void Fuzzer::PrintFinalStats() {
296 if (!Options.PrintFinalStats) return;
297 size_t ExecPerSec = execPerSec();
298 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
299 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
300 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
301 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
302 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
303}
304
Kostya Serebryany64d24572016-03-12 01:57:04 +0000305size_t Fuzzer::MaxUnitSizeInCorpus() const {
306 size_t Res = 0;
307 for (auto &X : Corpus)
308 Res = std::max(Res, X.size());
309 return Res;
310}
311
312void Fuzzer::SetMaxLen(size_t MaxLen) {
313 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
314 assert(MaxLen);
315 Options.MaxLen = MaxLen;
316 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
317}
318
319
320void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000321 if (Options.OutputCorpus.empty())
322 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000323 std::vector<Unit> AdditionalCorpus;
324 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000325 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000326 if (Corpus.empty()) {
327 Corpus = AdditionalCorpus;
328 return;
329 }
Ivan Krasindf919102016-01-22 22:28:27 +0000330 if (!Options.Reload)
331 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000332 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000333 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000334 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000335 if (X.size() > MaxSize)
336 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000337 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000338 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000339 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000340 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000341 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000342 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000343 }
344 }
345}
346
Kostya Serebryany945761b2016-03-18 00:23:29 +0000347void Fuzzer::ShuffleCorpus(UnitVector *V) {
348 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
349 if (Options.PreferSmall)
350 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
351 return A.size() < B.size();
352 });
353}
354
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000355// Tries random prefixes of corpus items.
356// Prefix length is chosen according to exponential distribution
357// to sample short lengths much more heavily.
358void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
359 size_t MaxCorpusLen = 0;
360 for (const auto &U : Corpus)
361 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
362
363 if (MaxCorpusLen <= 1)
364 return;
365
366 // 50% of exponential distribution is Log[2]/lambda.
367 // Choose lambda so that median is MaxCorpusLen / 2.
368 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
369 std::exponential_distribution<> Dist(Lambda);
370 std::vector<double> Sizes;
371 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
372 Sizes.reserve(TruncatePoints);
373 for (size_t I = 0; I < TruncatePoints; ++I) {
374 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
375 }
376 std::sort(Sizes.begin(), Sizes.end());
377
378 for (size_t S : Sizes) {
379 for (const auto &U : Corpus) {
380 if (S < U.size() && RunOne(U.data(), S)) {
381 Unit U1(U.begin(), U.begin() + S);
382 NewCorpus->push_back(U1);
383 WriteToOutputCorpus(U1);
384 PrintStatusForNewUnit(U1);
385 }
386 }
387 }
388 PrintStats("TRUNC ");
389}
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() {
426 uintptr_t PrevBufferLen = MaxCoverage.PcBufferLen;
427 bool Res = CoverageController::RecordMax(Options, &MaxCoverage);
428
429 if (Options.PrintNewCovPcs && PrevBufferLen != MaxCoverage.PcBufferLen) {
430 uintptr_t *CoverageBuf;
Dan Liew1873a492016-06-07 23:32:50 +0000431 EF->__sanitizer_get_coverage_pc_buffer(&CoverageBuf);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000432 assert(CoverageBuf);
433 for (size_t I = PrevBufferLen; I < MaxCoverage.PcBufferLen; ++I) {
434 Printf("%p\n", CoverageBuf[I]);
435 }
436 }
437
438 return Res;
439}
440
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000441bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000442 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000443
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000444 // TODO(aizatsky): this Reset call seems to be not needed.
445 CoverageController::ResetCounters(Options);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000446 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000447 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000448
Kostya Serebryany16901a92015-03-30 23:04:35 +0000449 auto UnitStopTime = system_clock::now();
450 auto TimeOfUnit =
451 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000452 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
453 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000454 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000455 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
456 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000457 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000458 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000459 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000460 }
461 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000462}
463
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000464void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000465 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
466 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000467 if (RunOne(Data, Size))
468 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000469}
470
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000471size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000472 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000473 *Data = CurrentUnitData;
474 return CurrentUnitSize;
475}
476
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000477void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000478 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000479 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000480 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000481 // We copy the contents of Unit into a separate heap buffer
482 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000483 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
484 memcpy(DataCopy.get(), Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000485 if (CurrentUnitData && CurrentUnitData != Data)
486 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000487 AssignTaintLabels(DataCopy.get(), Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000488 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000489 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000490 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000491 (void)Res;
492 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000493 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000494 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000495}
496
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000497std::string Fuzzer::Coverage::DebugString() const {
498 std::string Result =
499 std::string("Coverage{") + "BlockCoverage=" +
500 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
501 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
502 std::to_string(CounterBitmapBits) + " PcMapBits=" +
503 std::to_string(PcMapBits) + "}";
504 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000505}
506
507void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000508 if (Options.OnlyASCII)
509 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000510 if (Options.OutputCorpus.empty())
511 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000512 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
513 WriteToFile(U, Path);
514 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000515 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000516}
517
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000518void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000519 if (!Options.SaveArtifacts)
520 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000521 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000522 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000523 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000524 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000525 Printf("artifact_prefix='%s'; Test unit written to %s\n",
526 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000527 if (U.size() <= kMaxUnitSizeToPrint)
528 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000529}
530
531void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000532 if (Options.OutputCorpus.empty())
533 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000534 for (const auto &U : Corpus)
535 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
536 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000537 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
538 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000539}
540
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000541void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
542 if (!Options.PrintNEW)
543 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000544 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000545 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000546 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000547 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000548 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000549 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000550}
551
552void Fuzzer::ReportNewCoverage(const Unit &U) {
553 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000554 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000555 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000556 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000557 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000558 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000559 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000560}
561
Kostya Serebryany945761b2016-03-18 00:23:29 +0000562// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
563// We do it by actually executing the units, sometimes more than once,
564// because we may be using different coverage-like signals and the only
565// common thing between them is that we can say "this unit found new stuff".
566UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
567 const UnitVector &Extra) {
568 UnitVector Res = Extra;
569 size_t OldSize = Res.size();
570 for (int Iter = 0; Iter < 10; Iter++) {
571 ShuffleCorpus(&Res);
572 ResetCoverage();
573
574 for (auto &U : Initial)
575 RunOne(U);
576
577 Corpus.clear();
578 for (auto &U : Res)
579 if (RunOne(U))
580 Corpus.push_back(U);
581
582 char Stat[7] = "MIN ";
583 Stat[3] = '0' + Iter;
584 PrintStats(Stat);
585
586 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000587 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000588 Res.swap(Corpus);
589
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000590 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000591 break;
592 OldSize = NewSize;
593 }
594 return Res;
595}
596
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000597void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
598 if (Corpora.size() <= 1) {
599 Printf("Merge requires two or more corpus dirs\n");
600 return;
601 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000602 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
603
Kostya Serebryany945761b2016-03-18 00:23:29 +0000604 assert(Options.MaxLen > 0);
605 UnitVector Initial, Extra;
606 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
607 for (auto &C : ExtraCorpora)
608 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
609
610 if (!Initial.empty()) {
611 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
612 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000613 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000614
615 Printf("=== Merging extra %zd units\n", Extra.size());
616 auto Res = FindExtraUnits(Initial, Extra);
617
618 for (auto &U: Res)
619 WriteToOutputCorpus(U);
620
621 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000622}
623
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000624// Tries detecting a memory leak on the particular input that we have just
625// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000626void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
627 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000628 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
629 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000630 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
631 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000632 return; // No lsan.
633 // Run the target once again, but with lsan disabled so that if there is
634 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000635 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000636 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000637 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000638 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000639 if (NumberOfLeakDetectionAttempts++ > 1000) {
640 Options.DetectLeaks = false;
641 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
642 " Most likely the target function accumulates allocated\n"
643 " memory in a global state w/o actually leaking it.\n"
644 " If LeakSanitizer is enabled in this process it will still\n"
645 " run on the process shutdown.\n");
646 return;
647 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000648 // Now perform the actual lsan pass. This is expensive and we must ensure
649 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000650 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000651 if (DuringInitialCorpusExecution)
652 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
653 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000654 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000655 DumpCurrentUnit("leak-");
656 PrintFinalStats();
657 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
658 }
659}
660
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000661void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000662 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000663 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000664
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000665 auto &U = ChooseUnitToMutate();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000666 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000667 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000668 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000669 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000670
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000671 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000672 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000673 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000674 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000675 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000676 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000677 Size = NewSize;
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000678 if (Options.OnlyASCII)
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000679 ToASCII(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000680 if (i == 0)
681 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000682 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000683 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000684 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000685 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000686 }
687}
688
Kostya Serebryanye6926212015-11-04 23:22:25 +0000689// Returns an index of random unit from the corpus to mutate.
690// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000691// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000692size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000693 size_t Idx =
694 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000695 assert(Idx < Corpus.size());
696 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000697}
698
Kostya Serebryany945761b2016-03-18 00:23:29 +0000699void Fuzzer::ResetCoverage() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000700 CoverageController::Reset();
701 MaxCoverage.Reset();
702 CoverageController::Prepare(Options, &MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000703}
704
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000705// Experimental search heuristic: drilling.
706// - Read, shuffle, execute and minimize the corpus.
707// - Choose one random unit.
708// - Reset the coverage.
709// - Start fuzzing as if the chosen unit was the only element of the corpus.
710// - When done, reset the coverage again.
711// - Merge the newly created corpus into the original one.
712void Fuzzer::Drill() {
713 // The corpus is already read, shuffled, and minimized.
714 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000715 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000716
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000717 Unit U = ChooseUnitToMutate();
718
Kostya Serebryany945761b2016-03-18 00:23:29 +0000719 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000720
721 std::vector<Unit> SavedCorpus;
722 SavedCorpus.swap(Corpus);
723 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000724 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000725 assert(Corpus.size() == 1);
726 RunOne(U);
727 PrintStats("DRILL ");
728 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
729 SavedOutputCorpusPath.swap(Options.OutputCorpus);
730 Loop();
731
Kostya Serebryany945761b2016-03-18 00:23:29 +0000732 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000733
734 PrintStats("REINIT");
735 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000736 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000737 RunOne(U);
738 PrintStats("MERGE ");
739 Options.PrintNEW = true;
740 size_t NumMerged = 0;
741 for (auto &U : Corpus) {
742 if (RunOne(U)) {
743 PrintStatusForNewUnit(U);
744 NumMerged++;
745 WriteToOutputCorpus(U);
746 }
747 }
748 PrintStats("MERGED");
749 if (NumMerged && Options.Verbosity)
750 Printf("Drilling discovered %zd new units\n", NumMerged);
751}
752
753void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000754 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000755 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000756 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000757 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000758 auto Now = system_clock::now();
759 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000760 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000761 LastCorpusReload = Now;
762 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000763 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000764 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000765 if (Options.MaxTotalTimeSec > 0 &&
766 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000767 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000768 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000769 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000770 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000771 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000772
773 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000774 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000775}
776
Ivan Krasindf919102016-01-22 22:28:27 +0000777void Fuzzer::UpdateCorpusDistribution() {
778 size_t N = Corpus.size();
779 std::vector<double> Intervals(N + 1);
780 std::vector<double> Weights(N);
781 std::iota(Intervals.begin(), Intervals.end(), 0);
782 std::iota(Weights.begin(), Weights.end(), 1);
783 CorpusDistribution = std::piecewise_constant_distribution<double>(
784 Intervals.begin(), Intervals.end(), Weights.begin());
785}
786
787} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000788
789extern "C" {
790
791size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
792 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000793 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000794}
795} // extern "C"