blob: 6aaa09fddc091215d3849dbb1a14d09b3d113c73 [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 Serebryanyf26017b2016-05-26 21:32:30 +000064thread_local bool Fuzzer::IsMyThread;
65
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000066static void MissingWeakApiFunction(const char *FnName) {
67 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000068 "Did you use -fsanitize-coverage=... to build your code?\n",
69 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000070 exit(1);
71}
72
73#define CHECK_WEAK_API_FUNCTION(fn) \
74 do { \
75 if (!fn) \
76 MissingWeakApiFunction(#fn); \
77 } while (false)
78
Kostya Serebryany52a788e2015-03-31 20:13:20 +000079// Only one Fuzzer per process.
80static Fuzzer *F;
81
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000082struct CoverageController {
83 static void Reset() {
84 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
85 __sanitizer_reset_coverage();
86 PcMapResetCurrent();
87 }
88
89 static void ResetCounters(const Fuzzer::FuzzingOptions &Options) {
90 if (Options.UseCounters) {
91 __sanitizer_update_counter_bitset_and_clear_counters(0);
92 }
93 }
94
95 static void Prepare(const Fuzzer::FuzzingOptions &Options,
96 Fuzzer::Coverage *C) {
97 if (Options.UseCounters) {
98 size_t NumCounters = __sanitizer_get_number_of_counters();
99 C->CounterBitmap.resize(NumCounters);
100 }
101 }
102
103 // Records data to a maximum coverage tracker. Returns true if additional
104 // coverage was discovered.
105 static bool RecordMax(const Fuzzer::FuzzingOptions &Options,
106 Fuzzer::Coverage *C) {
107 bool Res = false;
108
109 uint64_t NewBlockCoverage = __sanitizer_get_total_unique_coverage();
110 if (NewBlockCoverage > C->BlockCoverage) {
111 Res = true;
112 C->BlockCoverage = NewBlockCoverage;
113 }
114
115 if (Options.UseIndirCalls &&
116 __sanitizer_get_total_unique_caller_callee_pairs) {
117 uint64_t NewCallerCalleeCoverage =
118 __sanitizer_get_total_unique_caller_callee_pairs();
119 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
120 Res = true;
121 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
122 }
123 }
124
125 if (Options.UseCounters) {
126 uint64_t CounterDelta =
127 __sanitizer_update_counter_bitset_and_clear_counters(
128 C->CounterBitmap.data());
129 if (CounterDelta > 0) {
130 Res = true;
131 C->CounterBitmapBits += CounterDelta;
132 }
133 }
134
135 uint64_t NewPcMapBits = PcMapMergeInto(&C->PCMap);
136 if (NewPcMapBits > C->PcMapBits) {
137 Res = true;
138 C->PcMapBits = NewPcMapBits;
139 }
140
141 uintptr_t *CoverageBuf;
142 uint64_t NewPcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
143 if (NewPcBufferLen > C->PcBufferLen) {
144 Res = true;
145 C->PcBufferLen = NewPcBufferLen;
146 }
147
148 return Res;
149 }
150};
151
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000152Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
153 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000154 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000155 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000156 assert(!F);
157 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000158 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000159 IsMyThread = true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000160}
Aaron Ballmanef116982015-01-29 16:58:29 +0000161
162void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000163 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000164 __sanitizer_set_death_callback(StaticDeathCallback);
165}
166
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000167void Fuzzer::StaticDeathCallback() {
168 assert(F);
169 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000170}
171
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000172void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000173 const uint8_t *UnitData;
174 size_t UnitSize = GetCurrentUnitNoThreadCheck(&UnitData);
175 if (UnitSize <= kMaxUnitSizeToPrint) {
176 PrintHexArray(UnitData, UnitSize, "\n");
177 PrintASCII(UnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000178 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000179 WriteUnitToFileWithPrefix(
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000180 {UnitData, UnitData + UnitSize}, Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000181}
182
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000183NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000184void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000185 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000186 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000187}
188
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000189void Fuzzer::StaticAlarmCallback() {
190 assert(F);
191 F->AlarmCallback();
192}
193
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000194void Fuzzer::StaticCrashSignalCallback() {
195 assert(F);
196 F->CrashCallback();
197}
198
199void Fuzzer::StaticInterruptCallback() {
200 assert(F);
201 F->InterruptCallback();
202}
203
204void Fuzzer::CrashCallback() {
205 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
206 if (__sanitizer_print_stack_trace)
207 __sanitizer_print_stack_trace();
208 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
209 " Combine libFuzzer with AddressSanitizer or similar for better "
210 "crash reports.\n");
211 Printf("SUMMARY: libFuzzer: deadly signal\n");
212 DumpCurrentUnit("crash-");
213 PrintFinalStats();
214 exit(Options.ErrorExitCode);
215}
216
217void Fuzzer::InterruptCallback() {
218 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
219 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000220 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000221}
222
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000223NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000224void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000225 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000226 if (!InFuzzingThread()) return;
227 const uint8_t *UnitData;
228 size_t UnitSize = GetCurrentUnitInFuzzingThead(&UnitData);
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000229 if (InOOMState) {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000230 Printf(
231 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
232 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000233 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n");
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000234 if (UnitSize && UnitData) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000235 DumpCurrentUnit("oom-");
236 if (__sanitizer_print_stack_trace)
237 __sanitizer_print_stack_trace();
238 }
239 Printf("SUMMARY: libFuzzer: out-of-memory\n");
240 PrintFinalStats();
241 _Exit(Options.ErrorExitCode); // Stop right now.
242 }
243
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000244 if (!UnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000245 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000246 size_t Seconds =
247 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000248 if (Seconds == 0)
249 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000250 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000251 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000252 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000253 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000254 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
255 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000256 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000257 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
258 Seconds);
259 if (__sanitizer_print_stack_trace)
260 __sanitizer_print_stack_trace();
261 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000262 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000263 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000264 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000265}
266
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000267void Fuzzer::RssLimitCallback() {
268 InOOMState = true;
269 SignalToMainThread();
270 SleepSeconds(5);
271 Printf("Signal to main thread failed (non-linux?). Exiting.\n");
272 _Exit(Options.ErrorExitCode);
273 return;
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000274}
275
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000276void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000277 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000278 if (Options.OutputCSV) {
279 static bool csvHeaderPrinted = false;
280 if (!csvHeaderPrinted) {
281 csvHeaderPrinted = true;
282 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
283 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000284 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000285 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
286 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000287 }
288
289 if (!Options.Verbosity)
290 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000291 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000292 if (MaxCoverage.BlockCoverage)
293 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
294 if (MaxCoverage.PcMapBits)
295 Printf(" path: %zd", MaxCoverage.PcMapBits);
296 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000297 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000298 if (MaxCoverage.CallerCalleeCoverage)
299 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000300 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000301 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000302}
303
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000304void Fuzzer::PrintFinalStats() {
305 if (!Options.PrintFinalStats) return;
306 size_t ExecPerSec = execPerSec();
307 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
308 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
309 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
310 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
311 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
312}
313
Kostya Serebryany64d24572016-03-12 01:57:04 +0000314size_t Fuzzer::MaxUnitSizeInCorpus() const {
315 size_t Res = 0;
316 for (auto &X : Corpus)
317 Res = std::max(Res, X.size());
318 return Res;
319}
320
321void Fuzzer::SetMaxLen(size_t MaxLen) {
322 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
323 assert(MaxLen);
324 Options.MaxLen = MaxLen;
325 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
326}
327
328
329void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000330 if (Options.OutputCorpus.empty())
331 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000332 std::vector<Unit> AdditionalCorpus;
333 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000334 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000335 if (Corpus.empty()) {
336 Corpus = AdditionalCorpus;
337 return;
338 }
Ivan Krasindf919102016-01-22 22:28:27 +0000339 if (!Options.Reload)
340 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000341 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000342 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000343 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000344 if (X.size() > MaxSize)
345 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000346 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000347 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000348 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000349 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000350 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000351 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000352 }
353 }
354}
355
Kostya Serebryany945761b2016-03-18 00:23:29 +0000356void Fuzzer::ShuffleCorpus(UnitVector *V) {
357 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
358 if (Options.PreferSmall)
359 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
360 return A.size() < B.size();
361 });
362}
363
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000364// Tries random prefixes of corpus items.
365// Prefix length is chosen according to exponential distribution
366// to sample short lengths much more heavily.
367void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
368 size_t MaxCorpusLen = 0;
369 for (const auto &U : Corpus)
370 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
371
372 if (MaxCorpusLen <= 1)
373 return;
374
375 // 50% of exponential distribution is Log[2]/lambda.
376 // Choose lambda so that median is MaxCorpusLen / 2.
377 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
378 std::exponential_distribution<> Dist(Lambda);
379 std::vector<double> Sizes;
380 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
381 Sizes.reserve(TruncatePoints);
382 for (size_t I = 0; I < TruncatePoints; ++I) {
383 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
384 }
385 std::sort(Sizes.begin(), Sizes.end());
386
387 for (size_t S : Sizes) {
388 for (const auto &U : Corpus) {
389 if (S < U.size() && RunOne(U.data(), S)) {
390 Unit U1(U.begin(), U.begin() + S);
391 NewCorpus->push_back(U1);
392 WriteToOutputCorpus(U1);
393 PrintStatusForNewUnit(U1);
394 }
395 }
396 }
397 PrintStats("TRUNC ");
398}
399
Aaron Ballmanef116982015-01-29 16:58:29 +0000400void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000401 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000402 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000403 if (Options.ShuffleAtStartUp)
404 ShuffleCorpus(&Corpus);
405
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000406 if (Options.TruncateUnits) {
407 ResetCoverage();
408 TruncateUnits(&NewCorpus);
409 ResetCoverage();
410 }
411
Kostya Serebryany945761b2016-03-18 00:23:29 +0000412 for (const auto &U : Corpus) {
413 if (RunOne(U)) {
414 NewCorpus.push_back(U);
415 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000416 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000417 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000418 TryDetectingAMemoryLeak(U.data(), U.size(),
419 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000420 }
421 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000422 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000423 for (auto &X : Corpus)
424 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000425 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000426}
427
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000428bool Fuzzer::UpdateMaxCoverage() {
429 uintptr_t PrevBufferLen = MaxCoverage.PcBufferLen;
430 bool Res = CoverageController::RecordMax(Options, &MaxCoverage);
431
432 if (Options.PrintNewCovPcs && PrevBufferLen != MaxCoverage.PcBufferLen) {
433 uintptr_t *CoverageBuf;
434 __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
435 assert(CoverageBuf);
436 for (size_t I = PrevBufferLen; I < MaxCoverage.PcBufferLen; ++I) {
437 Printf("%p\n", CoverageBuf[I]);
438 }
439 }
440
441 return Res;
442}
443
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000444bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000445 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000446
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000447 // TODO(aizatsky): this Reset call seems to be not needed.
448 CoverageController::ResetCounters(Options);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000449 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000450 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000451
Kostya Serebryany16901a92015-03-30 23:04:35 +0000452 auto UnitStopTime = system_clock::now();
453 auto TimeOfUnit =
454 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000455 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
456 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000457 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000458 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
459 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000460 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000461 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000462 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000463 }
464 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000465}
466
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000467void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000468 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
469 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000470 if (RunOne(Data, Size))
471 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000472}
473
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000474// Leak detection is expensive, so we first check if there were more mallocs
475// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
476struct MallocFreeTracer {
477 void Start() {
478 Mallocs = 0;
479 Frees = 0;
480 }
481 // Returns true if there were more mallocs than frees.
482 bool Stop() { return Mallocs > Frees; }
483 size_t Mallocs;
484 size_t Frees;
485};
486
487static thread_local MallocFreeTracer AllocTracer;
488
Dan Liew3868e462016-05-19 22:00:33 +0000489// FIXME: The hooks only count on Linux because
490// on Mac OSX calls to malloc are intercepted before
491// thread local storage is initialised leading to
492// crashes when accessing ``AllocTracer``.
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000493extern "C" {
Dan Liew3868e462016-05-19 22:00:33 +0000494void __sanitizer_malloc_hook(void *ptr, size_t size) {
495 if (!LIBFUZZER_APPLE)
496 AllocTracer.Mallocs++;
497}
498void __sanitizer_free_hook(void *ptr) {
499 if (!LIBFUZZER_APPLE)
500 AllocTracer.Frees++;
501}
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000502} // extern "C"
503
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000504void Fuzzer::SetCurrentUnit(const uint8_t *Data, size_t Size) {
505 assert(InFuzzingThread());
506 CurrentUnitSize = Size;
507 CurrentUnitData = Data;
508}
509
510size_t Fuzzer::GetCurrentUnitNoThreadCheck(const uint8_t **Data) const {
511 *Data = CurrentUnitData;
512 return CurrentUnitSize;
513}
514
515size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
516 assert(InFuzzingThread());
517 return GetCurrentUnitNoThreadCheck(Data);
518}
519
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000520void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000521 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000522 // We copy the contents of Unit into a separate heap buffer
523 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000524 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
525 memcpy(DataCopy.get(), Data, Size);
526 AssignTaintLabels(DataCopy.get(), Size);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000527 SetCurrentUnit(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000528 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000529 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000530 (void)Res;
531 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000532 SetCurrentUnit(nullptr, 0);
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000533 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000534}
535
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000536std::string Fuzzer::Coverage::DebugString() const {
537 std::string Result =
538 std::string("Coverage{") + "BlockCoverage=" +
539 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
540 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
541 std::to_string(CounterBitmapBits) + " PcMapBits=" +
542 std::to_string(PcMapBits) + "}";
543 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000544}
545
546void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000547 if (Options.OnlyASCII)
548 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000549 if (Options.OutputCorpus.empty())
550 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000551 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
552 WriteToFile(U, Path);
553 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000554 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000555}
556
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000557void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000558 if (!Options.SaveArtifacts)
559 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000560 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000561 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000562 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000563 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000564 Printf("artifact_prefix='%s'; Test unit written to %s\n",
565 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000566 if (U.size() <= kMaxUnitSizeToPrint)
567 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000568}
569
570void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000571 if (Options.OutputCorpus.empty())
572 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000573 for (const auto &U : Corpus)
574 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
575 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000576 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
577 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000578}
579
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000580void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
581 if (!Options.PrintNEW)
582 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000583 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000584 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000585 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000586 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000587 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000588 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000589}
590
591void Fuzzer::ReportNewCoverage(const Unit &U) {
592 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000593 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000594 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000595 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000596 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000597 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000598 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000599}
600
Kostya Serebryany945761b2016-03-18 00:23:29 +0000601// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
602// We do it by actually executing the units, sometimes more than once,
603// because we may be using different coverage-like signals and the only
604// common thing between them is that we can say "this unit found new stuff".
605UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
606 const UnitVector &Extra) {
607 UnitVector Res = Extra;
608 size_t OldSize = Res.size();
609 for (int Iter = 0; Iter < 10; Iter++) {
610 ShuffleCorpus(&Res);
611 ResetCoverage();
612
613 for (auto &U : Initial)
614 RunOne(U);
615
616 Corpus.clear();
617 for (auto &U : Res)
618 if (RunOne(U))
619 Corpus.push_back(U);
620
621 char Stat[7] = "MIN ";
622 Stat[3] = '0' + Iter;
623 PrintStats(Stat);
624
625 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000626 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000627 Res.swap(Corpus);
628
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000629 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000630 break;
631 OldSize = NewSize;
632 }
633 return Res;
634}
635
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000636void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
637 if (Corpora.size() <= 1) {
638 Printf("Merge requires two or more corpus dirs\n");
639 return;
640 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000641 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
642
Kostya Serebryany945761b2016-03-18 00:23:29 +0000643 assert(Options.MaxLen > 0);
644 UnitVector Initial, Extra;
645 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
646 for (auto &C : ExtraCorpora)
647 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
648
649 if (!Initial.empty()) {
650 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
651 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000652 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000653
654 Printf("=== Merging extra %zd units\n", Extra.size());
655 auto Res = FindExtraUnits(Initial, Extra);
656
657 for (auto &U: Res)
658 WriteToOutputCorpus(U);
659
660 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000661}
662
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000663// Tries detecting a memory leak on the particular input that we have just
664// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000665void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
666 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000667 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
668 if (!Options.DetectLeaks) return;
669 if (!&__lsan_enable || !&__lsan_disable || !__lsan_do_recoverable_leak_check)
670 return; // No lsan.
671 // Run the target once again, but with lsan disabled so that if there is
672 // a real leak we do not report it twice.
673 __lsan_disable();
674 RunOneAndUpdateCorpus(Data, Size);
675 __lsan_enable();
676 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000677 if (NumberOfLeakDetectionAttempts++ > 1000) {
678 Options.DetectLeaks = false;
679 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
680 " Most likely the target function accumulates allocated\n"
681 " memory in a global state w/o actually leaking it.\n"
682 " If LeakSanitizer is enabled in this process it will still\n"
683 " run on the process shutdown.\n");
684 return;
685 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000686 // Now perform the actual lsan pass. This is expensive and we must ensure
687 // we don't call it too often.
688 if (__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000689 if (DuringInitialCorpusExecution)
690 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
691 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000692 SetCurrentUnit(Data, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000693 DumpCurrentUnit("leak-");
694 PrintFinalStats();
695 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
696 }
697}
698
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000699void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000700 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000701
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000702 auto &U = ChooseUnitToMutate();
703 MutateInPlaceHere.resize(Options.MaxLen);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000704 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000705 assert(Size <= Options.MaxLen && "Oversized Unit");
706 memcpy(MutateInPlaceHere.data(), U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000707
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000708 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000709 size_t NewSize = 0;
710 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000711 NewSize = LLVMFuzzerCustomMutator(MutateInPlaceHere.data(), Size,
712 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000713 else
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000714 NewSize = MD.Mutate(MutateInPlaceHere.data(), Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000715 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000716 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000717 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000718 Size = NewSize;
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000719 if (Options.OnlyASCII)
720 ToASCII(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000721 if (i == 0)
722 StartTraceRecording();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000723 RunOneAndUpdateCorpus(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000724 StopTraceRecording();
Kostya Serebryany4b923262016-05-26 20:25:49 +0000725 TryDetectingAMemoryLeak(MutateInPlaceHere.data(), Size,
726 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000727 }
728}
729
Kostya Serebryanye6926212015-11-04 23:22:25 +0000730// Returns an index of random unit from the corpus to mutate.
731// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000732// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000733size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000734 size_t Idx =
735 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000736 assert(Idx < Corpus.size());
737 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000738}
739
Kostya Serebryany945761b2016-03-18 00:23:29 +0000740void Fuzzer::ResetCoverage() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000741 CoverageController::Reset();
742 MaxCoverage.Reset();
743 CoverageController::Prepare(Options, &MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000744}
745
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000746// Experimental search heuristic: drilling.
747// - Read, shuffle, execute and minimize the corpus.
748// - Choose one random unit.
749// - Reset the coverage.
750// - Start fuzzing as if the chosen unit was the only element of the corpus.
751// - When done, reset the coverage again.
752// - Merge the newly created corpus into the original one.
753void Fuzzer::Drill() {
754 // The corpus is already read, shuffled, and minimized.
755 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000756 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000757
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000758 Unit U = ChooseUnitToMutate();
759
Kostya Serebryany945761b2016-03-18 00:23:29 +0000760 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000761
762 std::vector<Unit> SavedCorpus;
763 SavedCorpus.swap(Corpus);
764 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000765 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000766 assert(Corpus.size() == 1);
767 RunOne(U);
768 PrintStats("DRILL ");
769 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
770 SavedOutputCorpusPath.swap(Options.OutputCorpus);
771 Loop();
772
Kostya Serebryany945761b2016-03-18 00:23:29 +0000773 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000774
775 PrintStats("REINIT");
776 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000777 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000778 RunOne(U);
779 PrintStats("MERGE ");
780 Options.PrintNEW = true;
781 size_t NumMerged = 0;
782 for (auto &U : Corpus) {
783 if (RunOne(U)) {
784 PrintStatusForNewUnit(U);
785 NumMerged++;
786 WriteToOutputCorpus(U);
787 }
788 }
789 PrintStats("MERGED");
790 if (NumMerged && Options.Verbosity)
791 Printf("Drilling discovered %zd new units\n", NumMerged);
792}
793
794void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000795 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000796 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000797 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000798 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000799 auto Now = system_clock::now();
800 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000801 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000802 LastCorpusReload = Now;
803 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000804 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000805 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000806 if (Options.MaxTotalTimeSec > 0 &&
807 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000808 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000809 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000810 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000811 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000812 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000813
814 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000815 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000816}
817
Ivan Krasindf919102016-01-22 22:28:27 +0000818void Fuzzer::UpdateCorpusDistribution() {
819 size_t N = Corpus.size();
820 std::vector<double> Intervals(N + 1);
821 std::vector<double> Weights(N);
822 std::iota(Intervals.begin(), Intervals.end(), 0);
823 std::iota(Weights.begin(), Weights.end(), 1);
824 CorpusDistribution = std::piecewise_constant_distribution<double>(
825 Intervals.begin(), Intervals.end(), Weights.begin());
826}
827
828} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000829
830extern "C" {
831
832size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
833 assert(fuzzer::F);
834 return fuzzer::F->GetMD().Mutate(Data, Size, MaxSize);
835}
836} // extern "C"