blob: 3838cdde1d9186a230cd29017e25cf00e184e446 [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
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000162void Fuzzer::LazyAllocateCurrentUnitData() {
163 if (CurrentUnitData || Options.MaxLen == 0) return;
164 CurrentUnitData = new uint8_t[Options.MaxLen];
165}
166
Aaron Ballmanef116982015-01-29 16:58:29 +0000167void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000168 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000169 __sanitizer_set_death_callback(StaticDeathCallback);
170}
171
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000172void Fuzzer::StaticDeathCallback() {
173 assert(F);
174 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000175}
176
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000177void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000178 const uint8_t *UnitData;
179 size_t UnitSize = GetCurrentUnitNoThreadCheck(&UnitData);
180 if (UnitSize <= kMaxUnitSizeToPrint) {
181 PrintHexArray(UnitData, UnitSize, "\n");
182 PrintASCII(UnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000183 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000184 WriteUnitToFileWithPrefix(
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000185 {UnitData, UnitData + UnitSize}, Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000186}
187
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000188NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000189void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000190 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000191 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000192}
193
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000194void Fuzzer::StaticAlarmCallback() {
195 assert(F);
196 F->AlarmCallback();
197}
198
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000199void Fuzzer::StaticCrashSignalCallback() {
200 assert(F);
201 F->CrashCallback();
202}
203
204void Fuzzer::StaticInterruptCallback() {
205 assert(F);
206 F->InterruptCallback();
207}
208
209void Fuzzer::CrashCallback() {
210 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
211 if (__sanitizer_print_stack_trace)
212 __sanitizer_print_stack_trace();
213 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
214 " Combine libFuzzer with AddressSanitizer or similar for better "
215 "crash reports.\n");
216 Printf("SUMMARY: libFuzzer: deadly signal\n");
217 DumpCurrentUnit("crash-");
218 PrintFinalStats();
219 exit(Options.ErrorExitCode);
220}
221
222void Fuzzer::InterruptCallback() {
223 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
224 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000225 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000226}
227
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000228NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000229void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000230 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000231 if (!InFuzzingThread()) return;
232 const uint8_t *UnitData;
233 size_t UnitSize = GetCurrentUnitInFuzzingThead(&UnitData);
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000234 if (InOOMState) {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000235 Printf(
236 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
237 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000238 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n");
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000239 if (UnitSize && UnitData) {
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000240 DumpCurrentUnit("oom-");
241 if (__sanitizer_print_stack_trace)
242 __sanitizer_print_stack_trace();
243 }
244 Printf("SUMMARY: libFuzzer: out-of-memory\n");
245 PrintFinalStats();
246 _Exit(Options.ErrorExitCode); // Stop right now.
247 }
248
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000249 if (!UnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000250 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000251 size_t Seconds =
252 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000253 if (Seconds == 0)
254 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000255 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000256 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000257 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000258 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000259 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
260 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000261 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000262 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
263 Seconds);
264 if (__sanitizer_print_stack_trace)
265 __sanitizer_print_stack_trace();
266 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000267 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000268 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000269 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000270}
271
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000272void Fuzzer::RssLimitCallback() {
273 InOOMState = true;
274 SignalToMainThread();
275 SleepSeconds(5);
276 Printf("Signal to main thread failed (non-linux?). Exiting.\n");
277 _Exit(Options.ErrorExitCode);
278 return;
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000279}
280
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000281void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000282 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000283 if (Options.OutputCSV) {
284 static bool csvHeaderPrinted = false;
285 if (!csvHeaderPrinted) {
286 csvHeaderPrinted = true;
287 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
288 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000289 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000290 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
291 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000292 }
293
294 if (!Options.Verbosity)
295 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000296 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000297 if (MaxCoverage.BlockCoverage)
298 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
299 if (MaxCoverage.PcMapBits)
300 Printf(" path: %zd", MaxCoverage.PcMapBits);
301 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000302 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000303 if (MaxCoverage.CallerCalleeCoverage)
304 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000305 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000306 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000307}
308
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000309void Fuzzer::PrintFinalStats() {
310 if (!Options.PrintFinalStats) return;
311 size_t ExecPerSec = execPerSec();
312 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
313 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
314 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
315 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
316 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
317}
318
Kostya Serebryany64d24572016-03-12 01:57:04 +0000319size_t Fuzzer::MaxUnitSizeInCorpus() const {
320 size_t Res = 0;
321 for (auto &X : Corpus)
322 Res = std::max(Res, X.size());
323 return Res;
324}
325
326void Fuzzer::SetMaxLen(size_t MaxLen) {
327 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
328 assert(MaxLen);
329 Options.MaxLen = MaxLen;
330 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
331}
332
333
334void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000335 if (Options.OutputCorpus.empty())
336 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000337 std::vector<Unit> AdditionalCorpus;
338 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000339 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000340 if (Corpus.empty()) {
341 Corpus = AdditionalCorpus;
342 return;
343 }
Ivan Krasindf919102016-01-22 22:28:27 +0000344 if (!Options.Reload)
345 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000346 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000347 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000348 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000349 if (X.size() > MaxSize)
350 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000351 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000352 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000353 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000354 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000355 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000356 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000357 }
358 }
359}
360
Kostya Serebryany945761b2016-03-18 00:23:29 +0000361void Fuzzer::ShuffleCorpus(UnitVector *V) {
362 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
363 if (Options.PreferSmall)
364 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
365 return A.size() < B.size();
366 });
367}
368
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000369// Tries random prefixes of corpus items.
370// Prefix length is chosen according to exponential distribution
371// to sample short lengths much more heavily.
372void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
373 size_t MaxCorpusLen = 0;
374 for (const auto &U : Corpus)
375 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
376
377 if (MaxCorpusLen <= 1)
378 return;
379
380 // 50% of exponential distribution is Log[2]/lambda.
381 // Choose lambda so that median is MaxCorpusLen / 2.
382 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
383 std::exponential_distribution<> Dist(Lambda);
384 std::vector<double> Sizes;
385 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
386 Sizes.reserve(TruncatePoints);
387 for (size_t I = 0; I < TruncatePoints; ++I) {
388 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
389 }
390 std::sort(Sizes.begin(), Sizes.end());
391
392 for (size_t S : Sizes) {
393 for (const auto &U : Corpus) {
394 if (S < U.size() && RunOne(U.data(), S)) {
395 Unit U1(U.begin(), U.begin() + S);
396 NewCorpus->push_back(U1);
397 WriteToOutputCorpus(U1);
398 PrintStatusForNewUnit(U1);
399 }
400 }
401 }
402 PrintStats("TRUNC ");
403}
404
Aaron Ballmanef116982015-01-29 16:58:29 +0000405void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000406 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000407 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000408 if (Options.ShuffleAtStartUp)
409 ShuffleCorpus(&Corpus);
410
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000411 if (Options.TruncateUnits) {
412 ResetCoverage();
413 TruncateUnits(&NewCorpus);
414 ResetCoverage();
415 }
416
Kostya Serebryany945761b2016-03-18 00:23:29 +0000417 for (const auto &U : Corpus) {
418 if (RunOne(U)) {
419 NewCorpus.push_back(U);
420 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000421 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000422 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000423 TryDetectingAMemoryLeak(U.data(), U.size(),
424 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000425 }
426 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000427 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000428 for (auto &X : Corpus)
429 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000430 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000431}
432
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000433bool Fuzzer::UpdateMaxCoverage() {
434 uintptr_t PrevBufferLen = MaxCoverage.PcBufferLen;
435 bool Res = CoverageController::RecordMax(Options, &MaxCoverage);
436
437 if (Options.PrintNewCovPcs && PrevBufferLen != MaxCoverage.PcBufferLen) {
438 uintptr_t *CoverageBuf;
439 __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
440 assert(CoverageBuf);
441 for (size_t I = PrevBufferLen; I < MaxCoverage.PcBufferLen; ++I) {
442 Printf("%p\n", CoverageBuf[I]);
443 }
444 }
445
446 return Res;
447}
448
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000449bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000450 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000451
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000452 // TODO(aizatsky): this Reset call seems to be not needed.
453 CoverageController::ResetCounters(Options);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000454 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000455 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000456
Kostya Serebryany16901a92015-03-30 23:04:35 +0000457 auto UnitStopTime = system_clock::now();
458 auto TimeOfUnit =
459 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000460 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
461 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000462 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000463 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
464 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000465 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000466 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000467 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000468 }
469 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000470}
471
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000472void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000473 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
474 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000475 if (RunOne(Data, Size))
476 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000477}
478
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000479// Leak detection is expensive, so we first check if there were more mallocs
480// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
481struct MallocFreeTracer {
482 void Start() {
483 Mallocs = 0;
484 Frees = 0;
485 }
486 // Returns true if there were more mallocs than frees.
487 bool Stop() { return Mallocs > Frees; }
488 size_t Mallocs;
489 size_t Frees;
490};
491
492static thread_local MallocFreeTracer AllocTracer;
493
Dan Liew3868e462016-05-19 22:00:33 +0000494// FIXME: The hooks only count on Linux because
495// on Mac OSX calls to malloc are intercepted before
496// thread local storage is initialised leading to
497// crashes when accessing ``AllocTracer``.
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000498extern "C" {
Dan Liew3868e462016-05-19 22:00:33 +0000499void __sanitizer_malloc_hook(void *ptr, size_t size) {
500 if (!LIBFUZZER_APPLE)
501 AllocTracer.Mallocs++;
502}
503void __sanitizer_free_hook(void *ptr) {
504 if (!LIBFUZZER_APPLE)
505 AllocTracer.Frees++;
506}
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000507} // extern "C"
508
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000509void Fuzzer::SetCurrentUnit(size_t Size) {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000510 assert(InFuzzingThread());
511 CurrentUnitSize = Size;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000512}
513
514size_t Fuzzer::GetCurrentUnitNoThreadCheck(const uint8_t **Data) const {
515 *Data = CurrentUnitData;
516 return CurrentUnitSize;
517}
518
519size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
520 assert(InFuzzingThread());
521 return GetCurrentUnitNoThreadCheck(Data);
522}
523
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000524void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000525 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000526 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000527 // We copy the contents of Unit into a separate heap buffer
528 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000529 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
530 memcpy(DataCopy.get(), Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000531 if (CurrentUnitData && CurrentUnitData != Data)
532 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000533 AssignTaintLabels(DataCopy.get(), Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000534 SetCurrentUnit(Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000535 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000536 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000537 (void)Res;
538 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000539 SetCurrentUnit(0);
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000540 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000541}
542
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000543std::string Fuzzer::Coverage::DebugString() const {
544 std::string Result =
545 std::string("Coverage{") + "BlockCoverage=" +
546 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
547 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
548 std::to_string(CounterBitmapBits) + " PcMapBits=" +
549 std::to_string(PcMapBits) + "}";
550 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000551}
552
553void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000554 if (Options.OnlyASCII)
555 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000556 if (Options.OutputCorpus.empty())
557 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000558 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
559 WriteToFile(U, Path);
560 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000561 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000562}
563
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000564void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000565 if (!Options.SaveArtifacts)
566 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000567 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000568 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000569 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000570 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000571 Printf("artifact_prefix='%s'; Test unit written to %s\n",
572 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000573 if (U.size() <= kMaxUnitSizeToPrint)
574 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000575}
576
577void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000578 if (Options.OutputCorpus.empty())
579 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000580 for (const auto &U : Corpus)
581 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
582 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000583 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
584 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000585}
586
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000587void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
588 if (!Options.PrintNEW)
589 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000590 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000591 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000592 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000593 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000594 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000595 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000596}
597
598void Fuzzer::ReportNewCoverage(const Unit &U) {
599 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000600 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000601 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000602 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000603 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000604 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000605 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000606}
607
Kostya Serebryany945761b2016-03-18 00:23:29 +0000608// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
609// We do it by actually executing the units, sometimes more than once,
610// because we may be using different coverage-like signals and the only
611// common thing between them is that we can say "this unit found new stuff".
612UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
613 const UnitVector &Extra) {
614 UnitVector Res = Extra;
615 size_t OldSize = Res.size();
616 for (int Iter = 0; Iter < 10; Iter++) {
617 ShuffleCorpus(&Res);
618 ResetCoverage();
619
620 for (auto &U : Initial)
621 RunOne(U);
622
623 Corpus.clear();
624 for (auto &U : Res)
625 if (RunOne(U))
626 Corpus.push_back(U);
627
628 char Stat[7] = "MIN ";
629 Stat[3] = '0' + Iter;
630 PrintStats(Stat);
631
632 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000633 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000634 Res.swap(Corpus);
635
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000636 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000637 break;
638 OldSize = NewSize;
639 }
640 return Res;
641}
642
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000643void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
644 if (Corpora.size() <= 1) {
645 Printf("Merge requires two or more corpus dirs\n");
646 return;
647 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000648 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
649
Kostya Serebryany945761b2016-03-18 00:23:29 +0000650 assert(Options.MaxLen > 0);
651 UnitVector Initial, Extra;
652 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
653 for (auto &C : ExtraCorpora)
654 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
655
656 if (!Initial.empty()) {
657 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
658 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000659 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000660
661 Printf("=== Merging extra %zd units\n", Extra.size());
662 auto Res = FindExtraUnits(Initial, Extra);
663
664 for (auto &U: Res)
665 WriteToOutputCorpus(U);
666
667 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000668}
669
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000670// Tries detecting a memory leak on the particular input that we have just
671// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000672void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
673 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000674 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
675 if (!Options.DetectLeaks) return;
676 if (!&__lsan_enable || !&__lsan_disable || !__lsan_do_recoverable_leak_check)
677 return; // No lsan.
678 // Run the target once again, but with lsan disabled so that if there is
679 // a real leak we do not report it twice.
680 __lsan_disable();
681 RunOneAndUpdateCorpus(Data, Size);
682 __lsan_enable();
683 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000684 if (NumberOfLeakDetectionAttempts++ > 1000) {
685 Options.DetectLeaks = false;
686 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
687 " Most likely the target function accumulates allocated\n"
688 " memory in a global state w/o actually leaking it.\n"
689 " If LeakSanitizer is enabled in this process it will still\n"
690 " run on the process shutdown.\n");
691 return;
692 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000693 // Now perform the actual lsan pass. This is expensive and we must ensure
694 // we don't call it too often.
695 if (__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000696 if (DuringInitialCorpusExecution)
697 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
698 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000699 SetCurrentUnit(Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000700 DumpCurrentUnit("leak-");
701 PrintFinalStats();
702 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
703 }
704}
705
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000706void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000707 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000708 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000709
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000710 auto &U = ChooseUnitToMutate();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000711 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000712 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000713 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000714 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000715
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000716 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000717 size_t NewSize = 0;
718 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000719 NewSize = LLVMFuzzerCustomMutator(CurrentUnitData, Size,
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000720 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000721 else
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000722 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000723 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000724 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000725 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000726 Size = NewSize;
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000727 if (Options.OnlyASCII)
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000728 ToASCII(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000729 if (i == 0)
730 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000731 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000732 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000733 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000734 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000735 }
736}
737
Kostya Serebryanye6926212015-11-04 23:22:25 +0000738// Returns an index of random unit from the corpus to mutate.
739// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000740// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000741size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000742 size_t Idx =
743 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000744 assert(Idx < Corpus.size());
745 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000746}
747
Kostya Serebryany945761b2016-03-18 00:23:29 +0000748void Fuzzer::ResetCoverage() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000749 CoverageController::Reset();
750 MaxCoverage.Reset();
751 CoverageController::Prepare(Options, &MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000752}
753
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000754// Experimental search heuristic: drilling.
755// - Read, shuffle, execute and minimize the corpus.
756// - Choose one random unit.
757// - Reset the coverage.
758// - Start fuzzing as if the chosen unit was the only element of the corpus.
759// - When done, reset the coverage again.
760// - Merge the newly created corpus into the original one.
761void Fuzzer::Drill() {
762 // The corpus is already read, shuffled, and minimized.
763 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000764 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000765
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000766 Unit U = ChooseUnitToMutate();
767
Kostya Serebryany945761b2016-03-18 00:23:29 +0000768 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000769
770 std::vector<Unit> SavedCorpus;
771 SavedCorpus.swap(Corpus);
772 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000773 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000774 assert(Corpus.size() == 1);
775 RunOne(U);
776 PrintStats("DRILL ");
777 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
778 SavedOutputCorpusPath.swap(Options.OutputCorpus);
779 Loop();
780
Kostya Serebryany945761b2016-03-18 00:23:29 +0000781 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000782
783 PrintStats("REINIT");
784 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000785 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000786 RunOne(U);
787 PrintStats("MERGE ");
788 Options.PrintNEW = true;
789 size_t NumMerged = 0;
790 for (auto &U : Corpus) {
791 if (RunOne(U)) {
792 PrintStatusForNewUnit(U);
793 NumMerged++;
794 WriteToOutputCorpus(U);
795 }
796 }
797 PrintStats("MERGED");
798 if (NumMerged && Options.Verbosity)
799 Printf("Drilling discovered %zd new units\n", NumMerged);
800}
801
802void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000803 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000804 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000805 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000806 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000807 auto Now = system_clock::now();
808 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000809 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000810 LastCorpusReload = Now;
811 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000812 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000813 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000814 if (Options.MaxTotalTimeSec > 0 &&
815 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000816 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000817 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000818 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000819 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000820 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000821
822 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000823 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000824}
825
Ivan Krasindf919102016-01-22 22:28:27 +0000826void Fuzzer::UpdateCorpusDistribution() {
827 size_t N = Corpus.size();
828 std::vector<double> Intervals(N + 1);
829 std::vector<double> Weights(N);
830 std::iota(Intervals.begin(), Intervals.end(), 0);
831 std::iota(Weights.begin(), Weights.end(), 1);
832 CorpusDistribution = std::piecewise_constant_distribution<double>(
833 Intervals.begin(), Intervals.end(), Weights.begin());
834}
835
836} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000837
838extern "C" {
839
840size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
841 assert(fuzzer::F);
842 return fuzzer::F->GetMD().Mutate(Data, Size, MaxSize);
843}
844} // extern "C"