blob: ccd1c4e11c47f11d0efa0b4fffde74b8e2efa6d6 [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
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000034extern "C" {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000035// Re-declare some of the sanitizer functions as "weak" so that
Kostya Serebryany2a48c242015-11-13 01:54:40 +000036// libFuzzer can be linked w/o the sanitizers and sanitizer-coverage
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000037// (in which case it will complain at start-up time).
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000038__attribute__((weak)) void __sanitizer_print_stack_trace();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +000039__attribute__((weak)) void __sanitizer_reset_coverage();
Kostya Serebryany94660b32015-10-23 18:37:58 +000040__attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000041__attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
Ivan Krasindf919102016-01-22 22:28:27 +000042__attribute__((weak)) void
43__sanitizer_set_death_callback(void (*callback)(void));
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000044__attribute__((weak)) size_t __sanitizer_get_number_of_counters();
Ivan Krasindf919102016-01-22 22:28:27 +000045__attribute__((weak)) uintptr_t
46__sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
Mike Aizatsky8b11f872016-01-06 00:21:22 +000047__attribute__((weak)) uintptr_t
48__sanitizer_get_coverage_pc_buffer(uintptr_t **data);
Kostya Serebryany22cc5e22016-02-13 02:29:38 +000049
50__attribute__((weak)) size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
51 size_t MaxSize,
52 unsigned int Seed);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000053__attribute__((weak)) void __sanitizer_malloc_hook(void *ptr, size_t size);
54__attribute__((weak)) void __sanitizer_free_hook(void *ptr);
55__attribute__((weak)) void __lsan_enable();
56__attribute__((weak)) void __lsan_disable();
57__attribute__((weak)) int __lsan_do_recoverable_leak_check();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000058}
59
Aaron Ballmanef116982015-01-29 16:58:29 +000060namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000061static const size_t kMaxUnitSizeToPrint = 256;
Mike Aizatskyaf432a42016-05-24 23:14:29 +000062static const size_t TruncateMaxRuns = 1000;
Aaron Ballmanef116982015-01-29 16:58:29 +000063
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000064static void MissingWeakApiFunction(const char *FnName) {
65 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000066 "Did you use -fsanitize-coverage=... to build your code?\n",
67 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000068 exit(1);
69}
70
71#define CHECK_WEAK_API_FUNCTION(fn) \
72 do { \
73 if (!fn) \
74 MissingWeakApiFunction(#fn); \
75 } while (false)
76
Kostya Serebryany52a788e2015-03-31 20:13:20 +000077// Only one Fuzzer per process.
78static Fuzzer *F;
79
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000080struct CoverageController {
81 static void Reset() {
82 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
83 __sanitizer_reset_coverage();
84 PcMapResetCurrent();
85 }
86
87 static void ResetCounters(const Fuzzer::FuzzingOptions &Options) {
88 if (Options.UseCounters) {
89 __sanitizer_update_counter_bitset_and_clear_counters(0);
90 }
91 }
92
93 static void Prepare(const Fuzzer::FuzzingOptions &Options,
94 Fuzzer::Coverage *C) {
95 if (Options.UseCounters) {
96 size_t NumCounters = __sanitizer_get_number_of_counters();
97 C->CounterBitmap.resize(NumCounters);
98 }
99 }
100
101 // Records data to a maximum coverage tracker. Returns true if additional
102 // coverage was discovered.
103 static bool RecordMax(const Fuzzer::FuzzingOptions &Options,
104 Fuzzer::Coverage *C) {
105 bool Res = false;
106
107 uint64_t NewBlockCoverage = __sanitizer_get_total_unique_coverage();
108 if (NewBlockCoverage > C->BlockCoverage) {
109 Res = true;
110 C->BlockCoverage = NewBlockCoverage;
111 }
112
113 if (Options.UseIndirCalls &&
114 __sanitizer_get_total_unique_caller_callee_pairs) {
115 uint64_t NewCallerCalleeCoverage =
116 __sanitizer_get_total_unique_caller_callee_pairs();
117 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
118 Res = true;
119 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
120 }
121 }
122
123 if (Options.UseCounters) {
124 uint64_t CounterDelta =
125 __sanitizer_update_counter_bitset_and_clear_counters(
126 C->CounterBitmap.data());
127 if (CounterDelta > 0) {
128 Res = true;
129 C->CounterBitmapBits += CounterDelta;
130 }
131 }
132
133 uint64_t NewPcMapBits = PcMapMergeInto(&C->PCMap);
134 if (NewPcMapBits > C->PcMapBits) {
135 Res = true;
136 C->PcMapBits = NewPcMapBits;
137 }
138
139 uintptr_t *CoverageBuf;
140 uint64_t NewPcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
141 if (NewPcBufferLen > C->PcBufferLen) {
142 Res = true;
143 C->PcBufferLen = NewPcBufferLen;
144 }
145
146 return Res;
147 }
148};
149
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000150Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
151 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000152 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000153 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000154 assert(!F);
155 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000156 ResetCoverage();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000157}
Aaron Ballmanef116982015-01-29 16:58:29 +0000158
159void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000160 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000161 __sanitizer_set_death_callback(StaticDeathCallback);
162}
163
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000164void Fuzzer::StaticDeathCallback() {
165 assert(F);
166 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000167}
168
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000169void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000170 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
171 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
172 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000173 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000174 WriteUnitToFileWithPrefix(
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000175 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, Prefix);
176}
177
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000178NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000179void Fuzzer::DeathCallback() {
Kostya Serebryanyff2e6ba2016-05-25 00:15:36 +0000180 if (CurrentUnitSize) {
181 Printf("DEATH:\n");
182 DumpCurrentUnit("crash-");
183 }
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000184 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000185}
186
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000187void Fuzzer::StaticAlarmCallback() {
188 assert(F);
189 F->AlarmCallback();
190}
191
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000192void Fuzzer::StaticCrashSignalCallback() {
193 assert(F);
194 F->CrashCallback();
195}
196
197void Fuzzer::StaticInterruptCallback() {
198 assert(F);
199 F->InterruptCallback();
200}
201
202void Fuzzer::CrashCallback() {
203 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
204 if (__sanitizer_print_stack_trace)
205 __sanitizer_print_stack_trace();
206 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
207 " Combine libFuzzer with AddressSanitizer or similar for better "
208 "crash reports.\n");
209 Printf("SUMMARY: libFuzzer: deadly signal\n");
210 DumpCurrentUnit("crash-");
211 PrintFinalStats();
212 exit(Options.ErrorExitCode);
213}
214
215void Fuzzer::InterruptCallback() {
216 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
217 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000218 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000219}
220
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000221NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000222void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000223 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000224 if (InOOMState) {
225 Printf("==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
226 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
227 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n");
228 if (CurrentUnitSize && CurrentUnitData) {
229 DumpCurrentUnit("oom-");
230 if (__sanitizer_print_stack_trace)
231 __sanitizer_print_stack_trace();
232 }
233 Printf("SUMMARY: libFuzzer: out-of-memory\n");
234 PrintFinalStats();
235 _Exit(Options.ErrorExitCode); // Stop right now.
236 }
237
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000238 if (!CurrentUnitSize)
239 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000240 size_t Seconds =
241 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000242 if (Seconds == 0)
243 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000244 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000245 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000246 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000247 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000248 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
249 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000250 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000251 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
252 Seconds);
253 if (__sanitizer_print_stack_trace)
254 __sanitizer_print_stack_trace();
255 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000256 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000257 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000258 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000259}
260
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000261void Fuzzer::RssLimitCallback() {
262 InOOMState = true;
263 SignalToMainThread();
264 SleepSeconds(5);
265 Printf("Signal to main thread failed (non-linux?). Exiting.\n");
266 _Exit(Options.ErrorExitCode);
267 return;
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000268}
269
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000270void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000271 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000272 if (Options.OutputCSV) {
273 static bool csvHeaderPrinted = false;
274 if (!csvHeaderPrinted) {
275 csvHeaderPrinted = true;
276 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
277 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000278 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000279 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
280 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000281 }
282
283 if (!Options.Verbosity)
284 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000285 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000286 if (MaxCoverage.BlockCoverage)
287 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
288 if (MaxCoverage.PcMapBits)
289 Printf(" path: %zd", MaxCoverage.PcMapBits);
290 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000291 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000292 if (MaxCoverage.CallerCalleeCoverage)
293 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000294 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000295 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000296}
297
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000298void Fuzzer::PrintFinalStats() {
299 if (!Options.PrintFinalStats) return;
300 size_t ExecPerSec = execPerSec();
301 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
302 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
303 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
304 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
305 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
306}
307
Kostya Serebryany64d24572016-03-12 01:57:04 +0000308size_t Fuzzer::MaxUnitSizeInCorpus() const {
309 size_t Res = 0;
310 for (auto &X : Corpus)
311 Res = std::max(Res, X.size());
312 return Res;
313}
314
315void Fuzzer::SetMaxLen(size_t MaxLen) {
316 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
317 assert(MaxLen);
318 Options.MaxLen = MaxLen;
319 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
320}
321
322
323void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000324 if (Options.OutputCorpus.empty())
325 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000326 std::vector<Unit> AdditionalCorpus;
327 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000328 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000329 if (Corpus.empty()) {
330 Corpus = AdditionalCorpus;
331 return;
332 }
Ivan Krasindf919102016-01-22 22:28:27 +0000333 if (!Options.Reload)
334 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000335 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000336 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000337 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000338 if (X.size() > MaxSize)
339 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000340 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000341 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000342 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000343 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000344 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000345 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000346 }
347 }
348}
349
Kostya Serebryany945761b2016-03-18 00:23:29 +0000350void Fuzzer::ShuffleCorpus(UnitVector *V) {
351 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
352 if (Options.PreferSmall)
353 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
354 return A.size() < B.size();
355 });
356}
357
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000358// Tries random prefixes of corpus items.
359// Prefix length is chosen according to exponential distribution
360// to sample short lengths much more heavily.
361void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
362 size_t MaxCorpusLen = 0;
363 for (const auto &U : Corpus)
364 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
365
366 if (MaxCorpusLen <= 1)
367 return;
368
369 // 50% of exponential distribution is Log[2]/lambda.
370 // Choose lambda so that median is MaxCorpusLen / 2.
371 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
372 std::exponential_distribution<> Dist(Lambda);
373 std::vector<double> Sizes;
374 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
375 Sizes.reserve(TruncatePoints);
376 for (size_t I = 0; I < TruncatePoints; ++I) {
377 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
378 }
379 std::sort(Sizes.begin(), Sizes.end());
380
381 for (size_t S : Sizes) {
382 for (const auto &U : Corpus) {
383 if (S < U.size() && RunOne(U.data(), S)) {
384 Unit U1(U.begin(), U.begin() + S);
385 NewCorpus->push_back(U1);
386 WriteToOutputCorpus(U1);
387 PrintStatusForNewUnit(U1);
388 }
389 }
390 }
391 PrintStats("TRUNC ");
392}
393
Aaron Ballmanef116982015-01-29 16:58:29 +0000394void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000395 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000396 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000397 if (Options.ShuffleAtStartUp)
398 ShuffleCorpus(&Corpus);
399
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000400 if (Options.TruncateUnits) {
401 ResetCoverage();
402 TruncateUnits(&NewCorpus);
403 ResetCoverage();
404 }
405
Kostya Serebryany945761b2016-03-18 00:23:29 +0000406 for (const auto &U : Corpus) {
407 if (RunOne(U)) {
408 NewCorpus.push_back(U);
409 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000410 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000411 }
412 }
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 Serebryany1bfd5832016-04-20 00:24:21 +0000418 CheckForMemoryLeaks();
Aaron Ballmanef116982015-01-29 16:58:29 +0000419}
420
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000421bool Fuzzer::UpdateMaxCoverage() {
422 uintptr_t PrevBufferLen = MaxCoverage.PcBufferLen;
423 bool Res = CoverageController::RecordMax(Options, &MaxCoverage);
424
425 if (Options.PrintNewCovPcs && PrevBufferLen != MaxCoverage.PcBufferLen) {
426 uintptr_t *CoverageBuf;
427 __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
428 assert(CoverageBuf);
429 for (size_t I = PrevBufferLen; I < MaxCoverage.PcBufferLen; ++I) {
430 Printf("%p\n", CoverageBuf[I]);
431 }
432 }
433
434 return Res;
435}
436
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000437bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000438 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000439
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000440 // TODO(aizatsky): this Reset call seems to be not needed.
441 CoverageController::ResetCounters(Options);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000442 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000443 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000444
Kostya Serebryany16901a92015-03-30 23:04:35 +0000445 auto UnitStopTime = system_clock::now();
446 auto TimeOfUnit =
447 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000448 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
449 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000450 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000451 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
452 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000453 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000454 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000455 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000456 }
457 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000458}
459
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000460void Fuzzer::RunOneAndUpdateCorpus(uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000461 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
462 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000463 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000464 ToASCII(Data, Size);
465 if (RunOne(Data, Size))
466 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000467}
468
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000469// Leak detection is expensive, so we first check if there were more mallocs
470// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
471struct MallocFreeTracer {
472 void Start() {
473 Mallocs = 0;
474 Frees = 0;
475 }
476 // Returns true if there were more mallocs than frees.
477 bool Stop() { return Mallocs > Frees; }
478 size_t Mallocs;
479 size_t Frees;
480};
481
482static thread_local MallocFreeTracer AllocTracer;
483
Dan Liew3868e462016-05-19 22:00:33 +0000484// FIXME: The hooks only count on Linux because
485// on Mac OSX calls to malloc are intercepted before
486// thread local storage is initialised leading to
487// crashes when accessing ``AllocTracer``.
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000488extern "C" {
Dan Liew3868e462016-05-19 22:00:33 +0000489void __sanitizer_malloc_hook(void *ptr, size_t size) {
490 if (!LIBFUZZER_APPLE)
491 AllocTracer.Mallocs++;
492}
493void __sanitizer_free_hook(void *ptr) {
494 if (!LIBFUZZER_APPLE)
495 AllocTracer.Frees++;
496}
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000497} // extern "C"
498
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000499void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000500 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000501 // We copy the contents of Unit into a separate heap buffer
502 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000503 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
504 memcpy(DataCopy.get(), Data, Size);
505 AssignTaintLabels(DataCopy.get(), Size);
506 CurrentUnitData = DataCopy.get();
507 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000508 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000509 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000510 (void)Res;
511 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000512 CurrentUnitSize = 0;
513 CurrentUnitData = nullptr;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000514 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000515}
516
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000517std::string Fuzzer::Coverage::DebugString() const {
518 std::string Result =
519 std::string("Coverage{") + "BlockCoverage=" +
520 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
521 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
522 std::to_string(CounterBitmapBits) + " PcMapBits=" +
523 std::to_string(PcMapBits) + "}";
524 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000525}
526
527void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Ivan Krasindf919102016-01-22 22:28:27 +0000528 if (Options.OutputCorpus.empty())
529 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000530 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
531 WriteToFile(U, Path);
532 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000533 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000534 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000535}
536
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000537void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000538 if (!Options.SaveArtifacts)
539 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000540 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000541 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000542 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000543 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000544 Printf("artifact_prefix='%s'; Test unit written to %s\n",
545 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000546 if (U.size() <= kMaxUnitSizeToPrint)
547 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000548}
549
550void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000551 if (Options.OutputCorpus.empty())
552 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000553 for (const auto &U : Corpus)
554 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
555 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000556 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
557 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000558}
559
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000560void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
561 if (!Options.PrintNEW)
562 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000563 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000564 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000565 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000566 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000567 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000568 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000569}
570
571void Fuzzer::ReportNewCoverage(const Unit &U) {
572 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000573 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000574 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000575 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000576 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000577 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000578 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000579}
580
Kostya Serebryany945761b2016-03-18 00:23:29 +0000581// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
582// We do it by actually executing the units, sometimes more than once,
583// because we may be using different coverage-like signals and the only
584// common thing between them is that we can say "this unit found new stuff".
585UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
586 const UnitVector &Extra) {
587 UnitVector Res = Extra;
588 size_t OldSize = Res.size();
589 for (int Iter = 0; Iter < 10; Iter++) {
590 ShuffleCorpus(&Res);
591 ResetCoverage();
592
593 for (auto &U : Initial)
594 RunOne(U);
595
596 Corpus.clear();
597 for (auto &U : Res)
598 if (RunOne(U))
599 Corpus.push_back(U);
600
601 char Stat[7] = "MIN ";
602 Stat[3] = '0' + Iter;
603 PrintStats(Stat);
604
605 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000606 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000607 Res.swap(Corpus);
608
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000609 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000610 break;
611 OldSize = NewSize;
612 }
613 return Res;
614}
615
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000616void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
617 if (Corpora.size() <= 1) {
618 Printf("Merge requires two or more corpus dirs\n");
619 return;
620 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000621 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
622
Kostya Serebryany945761b2016-03-18 00:23:29 +0000623 assert(Options.MaxLen > 0);
624 UnitVector Initial, Extra;
625 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
626 for (auto &C : ExtraCorpora)
627 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
628
629 if (!Initial.empty()) {
630 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
631 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000632 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000633
634 Printf("=== Merging extra %zd units\n", Extra.size());
635 auto Res = FindExtraUnits(Initial, Extra);
636
637 for (auto &U: Res)
638 WriteToOutputCorpus(U);
639
640 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000641}
642
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000643// Tries to call lsan, and if there are leaks exits. We call this right after
644// the initial corpus was read because if there are leaky inputs in the corpus
645// further fuzzing will likely hit OOMs.
646void Fuzzer::CheckForMemoryLeaks() {
647 if (!Options.DetectLeaks) return;
648 if (!__lsan_do_recoverable_leak_check)
649 return;
650 if (__lsan_do_recoverable_leak_check()) {
651 Printf("==%d== ERROR: libFuzzer: initial corpus triggers memory leaks.\n"
652 "Exiting now. Use -detect_leaks=0 to disable leak detection here.\n"
653 "LeakSanitizer will still check for leaks at the process exit.\n",
654 GetPid());
655 PrintFinalStats();
656 _Exit(Options.ErrorExitCode);
657 }
658}
659
660// Tries detecting a memory leak on the particular input that we have just
661// executed before calling this function.
662void Fuzzer::TryDetectingAMemoryLeak(uint8_t *Data, size_t Size) {
663 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
664 if (!Options.DetectLeaks) return;
665 if (!&__lsan_enable || !&__lsan_disable || !__lsan_do_recoverable_leak_check)
666 return; // No lsan.
667 // Run the target once again, but with lsan disabled so that if there is
668 // a real leak we do not report it twice.
669 __lsan_disable();
670 RunOneAndUpdateCorpus(Data, Size);
671 __lsan_enable();
672 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000673 if (NumberOfLeakDetectionAttempts++ > 1000) {
674 Options.DetectLeaks = false;
675 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
676 " Most likely the target function accumulates allocated\n"
677 " memory in a global state w/o actually leaking it.\n"
678 " If LeakSanitizer is enabled in this process it will still\n"
679 " run on the process shutdown.\n");
680 return;
681 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000682 // Now perform the actual lsan pass. This is expensive and we must ensure
683 // we don't call it too often.
684 if (__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
685 CurrentUnitData = Data;
686 CurrentUnitSize = Size;
687 DumpCurrentUnit("leak-");
688 PrintFinalStats();
689 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
690 }
691}
692
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000693void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000694 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000695
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000696 auto &U = ChooseUnitToMutate();
697 MutateInPlaceHere.resize(Options.MaxLen);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000698 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000699 assert(Size <= Options.MaxLen && "Oversized Unit");
700 memcpy(MutateInPlaceHere.data(), U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000701
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000702 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000703 size_t NewSize = 0;
704 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000705 NewSize = LLVMFuzzerCustomMutator(MutateInPlaceHere.data(), Size,
706 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000707 else
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000708 NewSize = MD.Mutate(MutateInPlaceHere.data(), Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000709 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000710 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000711 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000712 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000713 if (i == 0)
714 StartTraceRecording();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000715 RunOneAndUpdateCorpus(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000716 StopTraceRecording();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000717 TryDetectingAMemoryLeak(MutateInPlaceHere.data(), Size);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000718 }
719}
720
Kostya Serebryanye6926212015-11-04 23:22:25 +0000721// Returns an index of random unit from the corpus to mutate.
722// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000723// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000724size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000725 size_t Idx =
726 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000727 assert(Idx < Corpus.size());
728 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000729}
730
Kostya Serebryany945761b2016-03-18 00:23:29 +0000731void Fuzzer::ResetCoverage() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000732 CoverageController::Reset();
733 MaxCoverage.Reset();
734 CoverageController::Prepare(Options, &MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000735}
736
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000737// Experimental search heuristic: drilling.
738// - Read, shuffle, execute and minimize the corpus.
739// - Choose one random unit.
740// - Reset the coverage.
741// - Start fuzzing as if the chosen unit was the only element of the corpus.
742// - When done, reset the coverage again.
743// - Merge the newly created corpus into the original one.
744void Fuzzer::Drill() {
745 // The corpus is already read, shuffled, and minimized.
746 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000747 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000748
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000749 Unit U = ChooseUnitToMutate();
750
Kostya Serebryany945761b2016-03-18 00:23:29 +0000751 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000752
753 std::vector<Unit> SavedCorpus;
754 SavedCorpus.swap(Corpus);
755 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000756 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000757 assert(Corpus.size() == 1);
758 RunOne(U);
759 PrintStats("DRILL ");
760 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
761 SavedOutputCorpusPath.swap(Options.OutputCorpus);
762 Loop();
763
Kostya Serebryany945761b2016-03-18 00:23:29 +0000764 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000765
766 PrintStats("REINIT");
767 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000768 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000769 RunOne(U);
770 PrintStats("MERGE ");
771 Options.PrintNEW = true;
772 size_t NumMerged = 0;
773 for (auto &U : Corpus) {
774 if (RunOne(U)) {
775 PrintStatusForNewUnit(U);
776 NumMerged++;
777 WriteToOutputCorpus(U);
778 }
779 }
780 PrintStats("MERGED");
781 if (NumMerged && Options.Verbosity)
782 Printf("Drilling discovered %zd new units\n", NumMerged);
783}
784
785void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000786 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000787 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000788 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000789 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000790 auto Now = system_clock::now();
791 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000792 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000793 LastCorpusReload = Now;
794 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000795 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000796 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000797 if (Options.MaxTotalTimeSec > 0 &&
798 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000799 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000800 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000801 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000802 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000803 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000804
805 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000806 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000807}
808
Ivan Krasindf919102016-01-22 22:28:27 +0000809void Fuzzer::UpdateCorpusDistribution() {
810 size_t N = Corpus.size();
811 std::vector<double> Intervals(N + 1);
812 std::vector<double> Weights(N);
813 std::iota(Intervals.begin(), Intervals.end(), 0);
814 std::iota(Weights.begin(), Weights.end(), 1);
815 CorpusDistribution = std::piecewise_constant_distribution<double>(
816 Intervals.begin(), Intervals.end(), Weights.begin());
817}
818
819} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000820
821extern "C" {
822
823size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
824 assert(fuzzer::F);
825 return fuzzer::F->GetMD().Mutate(Data, Size, MaxSize);
826}
827} // extern "C"