blob: ed8a1fb44de460ee945cf0e725d56e033217fc51 [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() {
180 if (!CurrentUnitSize) return;
181 Printf("DEATH:\n");
182 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000183 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000184}
185
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000186void Fuzzer::StaticAlarmCallback() {
187 assert(F);
188 F->AlarmCallback();
189}
190
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000191void Fuzzer::StaticCrashSignalCallback() {
192 assert(F);
193 F->CrashCallback();
194}
195
196void Fuzzer::StaticInterruptCallback() {
197 assert(F);
198 F->InterruptCallback();
199}
200
201void Fuzzer::CrashCallback() {
202 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
203 if (__sanitizer_print_stack_trace)
204 __sanitizer_print_stack_trace();
205 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
206 " Combine libFuzzer with AddressSanitizer or similar for better "
207 "crash reports.\n");
208 Printf("SUMMARY: libFuzzer: deadly signal\n");
209 DumpCurrentUnit("crash-");
210 PrintFinalStats();
211 exit(Options.ErrorExitCode);
212}
213
214void Fuzzer::InterruptCallback() {
215 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
216 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000217 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000218}
219
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000220NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000221void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000222 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000223 if (InOOMState) {
224 Printf("==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
225 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
226 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n");
227 if (CurrentUnitSize && CurrentUnitData) {
228 DumpCurrentUnit("oom-");
229 if (__sanitizer_print_stack_trace)
230 __sanitizer_print_stack_trace();
231 }
232 Printf("SUMMARY: libFuzzer: out-of-memory\n");
233 PrintFinalStats();
234 _Exit(Options.ErrorExitCode); // Stop right now.
235 }
236
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000237 if (!CurrentUnitSize)
238 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000239 size_t Seconds =
240 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000241 if (Seconds == 0)
242 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000243 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000244 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000245 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000246 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000247 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
248 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000249 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000250 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
251 Seconds);
252 if (__sanitizer_print_stack_trace)
253 __sanitizer_print_stack_trace();
254 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000255 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000256 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000257 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000258}
259
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000260void Fuzzer::RssLimitCallback() {
261 InOOMState = true;
262 SignalToMainThread();
263 SleepSeconds(5);
264 Printf("Signal to main thread failed (non-linux?). Exiting.\n");
265 _Exit(Options.ErrorExitCode);
266 return;
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000267}
268
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000269void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000270 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000271 if (Options.OutputCSV) {
272 static bool csvHeaderPrinted = false;
273 if (!csvHeaderPrinted) {
274 csvHeaderPrinted = true;
275 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
276 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000277 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000278 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
279 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000280 }
281
282 if (!Options.Verbosity)
283 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000284 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000285 if (MaxCoverage.BlockCoverage)
286 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
287 if (MaxCoverage.PcMapBits)
288 Printf(" path: %zd", MaxCoverage.PcMapBits);
289 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000290 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000291 if (MaxCoverage.CallerCalleeCoverage)
292 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000293 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000294 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000295}
296
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000297void Fuzzer::PrintFinalStats() {
298 if (!Options.PrintFinalStats) return;
299 size_t ExecPerSec = execPerSec();
300 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
301 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
302 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
303 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
304 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
305}
306
Kostya Serebryany64d24572016-03-12 01:57:04 +0000307size_t Fuzzer::MaxUnitSizeInCorpus() const {
308 size_t Res = 0;
309 for (auto &X : Corpus)
310 Res = std::max(Res, X.size());
311 return Res;
312}
313
314void Fuzzer::SetMaxLen(size_t MaxLen) {
315 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
316 assert(MaxLen);
317 Options.MaxLen = MaxLen;
318 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
319}
320
321
322void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000323 if (Options.OutputCorpus.empty())
324 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000325 std::vector<Unit> AdditionalCorpus;
326 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000327 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000328 if (Corpus.empty()) {
329 Corpus = AdditionalCorpus;
330 return;
331 }
Ivan Krasindf919102016-01-22 22:28:27 +0000332 if (!Options.Reload)
333 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000334 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000335 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000336 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000337 if (X.size() > MaxSize)
338 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000339 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000340 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000341 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000342 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000343 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000344 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000345 }
346 }
347}
348
Kostya Serebryany945761b2016-03-18 00:23:29 +0000349void Fuzzer::ShuffleCorpus(UnitVector *V) {
350 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
351 if (Options.PreferSmall)
352 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
353 return A.size() < B.size();
354 });
355}
356
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000357// Tries random prefixes of corpus items.
358// Prefix length is chosen according to exponential distribution
359// to sample short lengths much more heavily.
360void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
361 size_t MaxCorpusLen = 0;
362 for (const auto &U : Corpus)
363 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
364
365 if (MaxCorpusLen <= 1)
366 return;
367
368 // 50% of exponential distribution is Log[2]/lambda.
369 // Choose lambda so that median is MaxCorpusLen / 2.
370 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
371 std::exponential_distribution<> Dist(Lambda);
372 std::vector<double> Sizes;
373 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
374 Sizes.reserve(TruncatePoints);
375 for (size_t I = 0; I < TruncatePoints; ++I) {
376 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
377 }
378 std::sort(Sizes.begin(), Sizes.end());
379
380 for (size_t S : Sizes) {
381 for (const auto &U : Corpus) {
382 if (S < U.size() && RunOne(U.data(), S)) {
383 Unit U1(U.begin(), U.begin() + S);
384 NewCorpus->push_back(U1);
385 WriteToOutputCorpus(U1);
386 PrintStatusForNewUnit(U1);
387 }
388 }
389 }
390 PrintStats("TRUNC ");
391}
392
Aaron Ballmanef116982015-01-29 16:58:29 +0000393void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000394 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000395 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000396 if (Options.ShuffleAtStartUp)
397 ShuffleCorpus(&Corpus);
398
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000399 if (Options.TruncateUnits) {
400 ResetCoverage();
401 TruncateUnits(&NewCorpus);
402 ResetCoverage();
403 }
404
Kostya Serebryany945761b2016-03-18 00:23:29 +0000405 for (const auto &U : Corpus) {
406 if (RunOne(U)) {
407 NewCorpus.push_back(U);
408 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000409 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000410 }
411 }
412 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000413 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000414 for (auto &X : Corpus)
415 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000416 PrintStats("INITED");
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000417 CheckForMemoryLeaks();
Aaron Ballmanef116982015-01-29 16:58:29 +0000418}
419
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000420bool Fuzzer::UpdateMaxCoverage() {
421 uintptr_t PrevBufferLen = MaxCoverage.PcBufferLen;
422 bool Res = CoverageController::RecordMax(Options, &MaxCoverage);
423
424 if (Options.PrintNewCovPcs && PrevBufferLen != MaxCoverage.PcBufferLen) {
425 uintptr_t *CoverageBuf;
426 __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
427 assert(CoverageBuf);
428 for (size_t I = PrevBufferLen; I < MaxCoverage.PcBufferLen; ++I) {
429 Printf("%p\n", CoverageBuf[I]);
430 }
431 }
432
433 return Res;
434}
435
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000436bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000437 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000438
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000439 // TODO(aizatsky): this Reset call seems to be not needed.
440 CoverageController::ResetCounters(Options);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000441 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000442 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000443
Kostya Serebryany16901a92015-03-30 23:04:35 +0000444 auto UnitStopTime = system_clock::now();
445 auto TimeOfUnit =
446 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000447 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
448 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000449 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000450 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
451 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000452 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000453 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000454 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000455 }
456 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000457}
458
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000459void Fuzzer::RunOneAndUpdateCorpus(uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000460 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
461 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000462 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000463 ToASCII(Data, Size);
464 if (RunOne(Data, Size))
465 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000466}
467
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000468// Leak detection is expensive, so we first check if there were more mallocs
469// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
470struct MallocFreeTracer {
471 void Start() {
472 Mallocs = 0;
473 Frees = 0;
474 }
475 // Returns true if there were more mallocs than frees.
476 bool Stop() { return Mallocs > Frees; }
477 size_t Mallocs;
478 size_t Frees;
479};
480
481static thread_local MallocFreeTracer AllocTracer;
482
Dan Liew3868e462016-05-19 22:00:33 +0000483// FIXME: The hooks only count on Linux because
484// on Mac OSX calls to malloc are intercepted before
485// thread local storage is initialised leading to
486// crashes when accessing ``AllocTracer``.
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000487extern "C" {
Dan Liew3868e462016-05-19 22:00:33 +0000488void __sanitizer_malloc_hook(void *ptr, size_t size) {
489 if (!LIBFUZZER_APPLE)
490 AllocTracer.Mallocs++;
491}
492void __sanitizer_free_hook(void *ptr) {
493 if (!LIBFUZZER_APPLE)
494 AllocTracer.Frees++;
495}
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000496} // extern "C"
497
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000498void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000499 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000500 // We copy the contents of Unit into a separate heap buffer
501 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000502 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
503 memcpy(DataCopy.get(), Data, Size);
504 AssignTaintLabels(DataCopy.get(), Size);
505 CurrentUnitData = DataCopy.get();
506 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000507 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000508 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000509 (void)Res;
510 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000511 CurrentUnitSize = 0;
512 CurrentUnitData = nullptr;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000513 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000514}
515
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000516std::string Fuzzer::Coverage::DebugString() const {
517 std::string Result =
518 std::string("Coverage{") + "BlockCoverage=" +
519 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
520 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
521 std::to_string(CounterBitmapBits) + " PcMapBits=" +
522 std::to_string(PcMapBits) + "}";
523 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000524}
525
526void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Ivan Krasindf919102016-01-22 22:28:27 +0000527 if (Options.OutputCorpus.empty())
528 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000529 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
530 WriteToFile(U, Path);
531 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000532 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000533 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000534}
535
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000536void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000537 if (!Options.SaveArtifacts)
538 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000539 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000540 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000541 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000542 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000543 Printf("artifact_prefix='%s'; Test unit written to %s\n",
544 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000545 if (U.size() <= kMaxUnitSizeToPrint)
546 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000547}
548
549void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000550 if (Options.OutputCorpus.empty())
551 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000552 for (const auto &U : Corpus)
553 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
554 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000555 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
556 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000557}
558
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000559void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
560 if (!Options.PrintNEW)
561 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000562 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000563 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000564 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000565 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000566 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000567 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000568}
569
570void Fuzzer::ReportNewCoverage(const Unit &U) {
571 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000572 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000573 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000574 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000575 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000576 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000577 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000578}
579
Kostya Serebryany945761b2016-03-18 00:23:29 +0000580// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
581// We do it by actually executing the units, sometimes more than once,
582// because we may be using different coverage-like signals and the only
583// common thing between them is that we can say "this unit found new stuff".
584UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
585 const UnitVector &Extra) {
586 UnitVector Res = Extra;
587 size_t OldSize = Res.size();
588 for (int Iter = 0; Iter < 10; Iter++) {
589 ShuffleCorpus(&Res);
590 ResetCoverage();
591
592 for (auto &U : Initial)
593 RunOne(U);
594
595 Corpus.clear();
596 for (auto &U : Res)
597 if (RunOne(U))
598 Corpus.push_back(U);
599
600 char Stat[7] = "MIN ";
601 Stat[3] = '0' + Iter;
602 PrintStats(Stat);
603
604 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000605 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000606 Res.swap(Corpus);
607
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000608 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000609 break;
610 OldSize = NewSize;
611 }
612 return Res;
613}
614
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000615void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
616 if (Corpora.size() <= 1) {
617 Printf("Merge requires two or more corpus dirs\n");
618 return;
619 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000620 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
621
Kostya Serebryany945761b2016-03-18 00:23:29 +0000622 assert(Options.MaxLen > 0);
623 UnitVector Initial, Extra;
624 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
625 for (auto &C : ExtraCorpora)
626 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
627
628 if (!Initial.empty()) {
629 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
630 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000631 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000632
633 Printf("=== Merging extra %zd units\n", Extra.size());
634 auto Res = FindExtraUnits(Initial, Extra);
635
636 for (auto &U: Res)
637 WriteToOutputCorpus(U);
638
639 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000640}
641
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000642// Tries to call lsan, and if there are leaks exits. We call this right after
643// the initial corpus was read because if there are leaky inputs in the corpus
644// further fuzzing will likely hit OOMs.
645void Fuzzer::CheckForMemoryLeaks() {
646 if (!Options.DetectLeaks) return;
647 if (!__lsan_do_recoverable_leak_check)
648 return;
649 if (__lsan_do_recoverable_leak_check()) {
650 Printf("==%d== ERROR: libFuzzer: initial corpus triggers memory leaks.\n"
651 "Exiting now. Use -detect_leaks=0 to disable leak detection here.\n"
652 "LeakSanitizer will still check for leaks at the process exit.\n",
653 GetPid());
654 PrintFinalStats();
655 _Exit(Options.ErrorExitCode);
656 }
657}
658
659// Tries detecting a memory leak on the particular input that we have just
660// executed before calling this function.
661void Fuzzer::TryDetectingAMemoryLeak(uint8_t *Data, size_t Size) {
662 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
663 if (!Options.DetectLeaks) return;
664 if (!&__lsan_enable || !&__lsan_disable || !__lsan_do_recoverable_leak_check)
665 return; // No lsan.
666 // Run the target once again, but with lsan disabled so that if there is
667 // a real leak we do not report it twice.
668 __lsan_disable();
669 RunOneAndUpdateCorpus(Data, Size);
670 __lsan_enable();
671 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000672 if (NumberOfLeakDetectionAttempts++ > 1000) {
673 Options.DetectLeaks = false;
674 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
675 " Most likely the target function accumulates allocated\n"
676 " memory in a global state w/o actually leaking it.\n"
677 " If LeakSanitizer is enabled in this process it will still\n"
678 " run on the process shutdown.\n");
679 return;
680 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000681 // Now perform the actual lsan pass. This is expensive and we must ensure
682 // we don't call it too often.
683 if (__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
684 CurrentUnitData = Data;
685 CurrentUnitSize = Size;
686 DumpCurrentUnit("leak-");
687 PrintFinalStats();
688 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
689 }
690}
691
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000692void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000693 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000694
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000695 auto &U = ChooseUnitToMutate();
696 MutateInPlaceHere.resize(Options.MaxLen);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000697 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000698 assert(Size <= Options.MaxLen && "Oversized Unit");
699 memcpy(MutateInPlaceHere.data(), U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000700
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000701 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000702 size_t NewSize = 0;
703 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000704 NewSize = LLVMFuzzerCustomMutator(MutateInPlaceHere.data(), Size,
705 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000706 else
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000707 NewSize = MD.Mutate(MutateInPlaceHere.data(), Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000708 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000709 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000710 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000711 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000712 if (i == 0)
713 StartTraceRecording();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000714 RunOneAndUpdateCorpus(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000715 StopTraceRecording();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000716 TryDetectingAMemoryLeak(MutateInPlaceHere.data(), Size);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000717 }
718}
719
Kostya Serebryanye6926212015-11-04 23:22:25 +0000720// Returns an index of random unit from the corpus to mutate.
721// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000722// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000723size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000724 size_t Idx =
725 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000726 assert(Idx < Corpus.size());
727 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000728}
729
Kostya Serebryany945761b2016-03-18 00:23:29 +0000730void Fuzzer::ResetCoverage() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000731 CoverageController::Reset();
732 MaxCoverage.Reset();
733 CoverageController::Prepare(Options, &MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000734}
735
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000736// Experimental search heuristic: drilling.
737// - Read, shuffle, execute and minimize the corpus.
738// - Choose one random unit.
739// - Reset the coverage.
740// - Start fuzzing as if the chosen unit was the only element of the corpus.
741// - When done, reset the coverage again.
742// - Merge the newly created corpus into the original one.
743void Fuzzer::Drill() {
744 // The corpus is already read, shuffled, and minimized.
745 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000746 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000747
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000748 Unit U = ChooseUnitToMutate();
749
Kostya Serebryany945761b2016-03-18 00:23:29 +0000750 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000751
752 std::vector<Unit> SavedCorpus;
753 SavedCorpus.swap(Corpus);
754 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000755 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000756 assert(Corpus.size() == 1);
757 RunOne(U);
758 PrintStats("DRILL ");
759 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
760 SavedOutputCorpusPath.swap(Options.OutputCorpus);
761 Loop();
762
Kostya Serebryany945761b2016-03-18 00:23:29 +0000763 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000764
765 PrintStats("REINIT");
766 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000767 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000768 RunOne(U);
769 PrintStats("MERGE ");
770 Options.PrintNEW = true;
771 size_t NumMerged = 0;
772 for (auto &U : Corpus) {
773 if (RunOne(U)) {
774 PrintStatusForNewUnit(U);
775 NumMerged++;
776 WriteToOutputCorpus(U);
777 }
778 }
779 PrintStats("MERGED");
780 if (NumMerged && Options.Verbosity)
781 Printf("Drilling discovered %zd new units\n", NumMerged);
782}
783
784void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000785 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000786 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000787 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000788 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000789 auto Now = system_clock::now();
790 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000791 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000792 LastCorpusReload = Now;
793 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000794 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000795 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000796 if (Options.MaxTotalTimeSec > 0 &&
797 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000798 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000799 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000800 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000801 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000802 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000803
804 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000805 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000806}
807
Ivan Krasindf919102016-01-22 22:28:27 +0000808void Fuzzer::UpdateCorpusDistribution() {
809 size_t N = Corpus.size();
810 std::vector<double> Intervals(N + 1);
811 std::vector<double> Weights(N);
812 std::iota(Intervals.begin(), Intervals.end(), 0);
813 std::iota(Weights.begin(), Weights.end(), 1);
814 CorpusDistribution = std::piecewise_constant_distribution<double>(
815 Intervals.begin(), Intervals.end(), Weights.begin());
816}
817
818} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000819
820extern "C" {
821
822size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
823 assert(fuzzer::F);
824 return fuzzer::F->GetMD().Mutate(Data, Size, MaxSize);
825}
826} // extern "C"