blob: 5cfbad4c3274d0df0df6a770cbe8a34125ed762c [file] [log] [blame]
Aaron Ballmanef116982015-01-29 16:58:29 +00001//===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// Fuzzer's main loop.
10//===----------------------------------------------------------------------===//
11
12#include "FuzzerInternal.h"
Aaron Ballmanef116982015-01-29 16:58:29 +000013#include <algorithm>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000014#include <cstring>
15#include <memory>
Aaron Ballmanef116982015-01-29 16:58:29 +000016
Kostya Serebryany2a48c242015-11-13 01:54:40 +000017#if defined(__has_include)
Ivan Krasindf919102016-01-22 22:28:27 +000018#if __has_include(<sanitizer / coverage_interface.h>)
19#include <sanitizer/coverage_interface.h>
20#endif
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000021#if __has_include(<sanitizer / lsan_interface.h>)
22#include <sanitizer/lsan_interface.h>
23#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000024#endif
25
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000026#define NO_SANITIZE_MEMORY
27#if defined(__has_feature)
28#if __has_feature(memory_sanitizer)
29#undef NO_SANITIZE_MEMORY
30#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
31#endif
32#endif
33
Aaron Ballmanef116982015-01-29 16:58:29 +000034namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000035static const size_t kMaxUnitSizeToPrint = 256;
Mike Aizatskyaf432a42016-05-24 23:14:29 +000036static const size_t TruncateMaxRuns = 1000;
Aaron Ballmanef116982015-01-29 16:58:29 +000037
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000038thread_local bool Fuzzer::IsMyThread;
39
Dan Liew1873a492016-06-07 23:32:50 +000040static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000041 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000042 "Did you use -fsanitize-coverage=... to build your code?\n",
43 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000044 exit(1);
45}
46
Dan Liew1873a492016-06-07 23:32:50 +000047#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000048 do { \
Dan Liew1873a492016-06-07 23:32:50 +000049 if (!(EF->fn)) \
50 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000051 } while (false)
52
Kostya Serebryany52a788e2015-03-31 20:13:20 +000053// Only one Fuzzer per process.
54static Fuzzer *F;
55
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000056struct CoverageController {
57 static void Reset() {
Dan Liew1873a492016-06-07 23:32:50 +000058 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
59 EF->__sanitizer_reset_coverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000060 PcMapResetCurrent();
61 }
62
63 static void ResetCounters(const Fuzzer::FuzzingOptions &Options) {
64 if (Options.UseCounters) {
Dan Liew1873a492016-06-07 23:32:50 +000065 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000066 }
67 }
68
69 static void Prepare(const Fuzzer::FuzzingOptions &Options,
70 Fuzzer::Coverage *C) {
71 if (Options.UseCounters) {
Dan Liew1873a492016-06-07 23:32:50 +000072 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000073 C->CounterBitmap.resize(NumCounters);
74 }
75 }
76
77 // Records data to a maximum coverage tracker. Returns true if additional
78 // coverage was discovered.
79 static bool RecordMax(const Fuzzer::FuzzingOptions &Options,
80 Fuzzer::Coverage *C) {
81 bool Res = false;
82
Dan Liew1873a492016-06-07 23:32:50 +000083 uint64_t NewBlockCoverage = EF->__sanitizer_get_total_unique_coverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000084 if (NewBlockCoverage > C->BlockCoverage) {
85 Res = true;
86 C->BlockCoverage = NewBlockCoverage;
87 }
88
89 if (Options.UseIndirCalls &&
Dan Liew1873a492016-06-07 23:32:50 +000090 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000091 uint64_t NewCallerCalleeCoverage =
Dan Liew1873a492016-06-07 23:32:50 +000092 EF->__sanitizer_get_total_unique_caller_callee_pairs();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000093 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
94 Res = true;
95 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
96 }
97 }
98
99 if (Options.UseCounters) {
100 uint64_t CounterDelta =
Dan Liew1873a492016-06-07 23:32:50 +0000101 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000102 C->CounterBitmap.data());
103 if (CounterDelta > 0) {
104 Res = true;
105 C->CounterBitmapBits += CounterDelta;
106 }
107 }
108
109 uint64_t NewPcMapBits = PcMapMergeInto(&C->PCMap);
110 if (NewPcMapBits > C->PcMapBits) {
111 Res = true;
112 C->PcMapBits = NewPcMapBits;
113 }
114
115 uintptr_t *CoverageBuf;
Dan Liew1873a492016-06-07 23:32:50 +0000116 uint64_t NewPcBufferLen =
117 EF->__sanitizer_get_coverage_pc_buffer(&CoverageBuf);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000118 if (NewPcBufferLen > C->PcBufferLen) {
119 Res = true;
120 C->PcBufferLen = NewPcBufferLen;
121 }
122
123 return Res;
124 }
125};
126
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000127Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
128 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000129 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000130 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000131 assert(!F);
132 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000133 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000134 IsMyThread = true;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000135}
Aaron Ballmanef116982015-01-29 16:58:29 +0000136
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000137void Fuzzer::LazyAllocateCurrentUnitData() {
138 if (CurrentUnitData || Options.MaxLen == 0) return;
139 CurrentUnitData = new uint8_t[Options.MaxLen];
140}
141
Aaron Ballmanef116982015-01-29 16:58:29 +0000142void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000143 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
144 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000145}
146
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000147void Fuzzer::StaticDeathCallback() {
148 assert(F);
149 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000150}
151
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000152void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany311cc832016-05-28 04:19:46 +0000153 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000154 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000155 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000156 PrintHexArray(CurrentUnitData, UnitSize, "\n");
157 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000158 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000159 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
160 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000161}
162
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000163NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000164void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000165 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000166 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000167}
168
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000169void Fuzzer::StaticAlarmCallback() {
170 assert(F);
171 F->AlarmCallback();
172}
173
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000174void Fuzzer::StaticCrashSignalCallback() {
175 assert(F);
176 F->CrashCallback();
177}
178
179void Fuzzer::StaticInterruptCallback() {
180 assert(F);
181 F->InterruptCallback();
182}
183
184void Fuzzer::CrashCallback() {
185 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000186 if (EF->__sanitizer_print_stack_trace)
187 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000188 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
189 " Combine libFuzzer with AddressSanitizer or similar for better "
190 "crash reports.\n");
191 Printf("SUMMARY: libFuzzer: deadly signal\n");
192 DumpCurrentUnit("crash-");
193 PrintFinalStats();
194 exit(Options.ErrorExitCode);
195}
196
197void Fuzzer::InterruptCallback() {
198 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
199 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000200 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000201}
202
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000203NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000204void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000205 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000206 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000207 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000208 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000209 size_t Seconds =
210 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000211 if (Seconds == 0)
212 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000213 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000214 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000215 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000216 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000217 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
218 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000219 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000220 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
221 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000222 if (EF->__sanitizer_print_stack_trace)
223 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000224 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000225 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000226 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000227 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000228}
229
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000230void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000231 Printf(
232 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
233 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000234 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000235 if (EF->__sanitizer_print_memory_profile)
236 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000237 DumpCurrentUnit("oom-");
238 Printf("SUMMARY: libFuzzer: out-of-memory\n");
239 PrintFinalStats();
240 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000241}
242
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000243void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000244 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000245 if (Options.OutputCSV) {
246 static bool csvHeaderPrinted = false;
247 if (!csvHeaderPrinted) {
248 csvHeaderPrinted = true;
249 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
250 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000251 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000252 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
253 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000254 }
255
256 if (!Options.Verbosity)
257 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000258 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000259 if (MaxCoverage.BlockCoverage)
260 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
261 if (MaxCoverage.PcMapBits)
262 Printf(" path: %zd", MaxCoverage.PcMapBits);
263 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000264 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000265 if (MaxCoverage.CallerCalleeCoverage)
266 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000267 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000268 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000269}
270
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000271void Fuzzer::PrintFinalStats() {
272 if (!Options.PrintFinalStats) return;
273 size_t ExecPerSec = execPerSec();
274 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
275 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
276 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
277 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
278 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
279}
280
Kostya Serebryany64d24572016-03-12 01:57:04 +0000281size_t Fuzzer::MaxUnitSizeInCorpus() const {
282 size_t Res = 0;
283 for (auto &X : Corpus)
284 Res = std::max(Res, X.size());
285 return Res;
286}
287
288void Fuzzer::SetMaxLen(size_t MaxLen) {
289 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
290 assert(MaxLen);
291 Options.MaxLen = MaxLen;
292 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
293}
294
295
296void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000297 if (Options.OutputCorpus.empty())
298 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000299 std::vector<Unit> AdditionalCorpus;
300 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000301 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000302 if (Corpus.empty()) {
303 Corpus = AdditionalCorpus;
304 return;
305 }
Ivan Krasindf919102016-01-22 22:28:27 +0000306 if (!Options.Reload)
307 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000308 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000309 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000310 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000311 if (X.size() > MaxSize)
312 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000313 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000314 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000315 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000316 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000317 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000318 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000319 }
320 }
321}
322
Kostya Serebryany945761b2016-03-18 00:23:29 +0000323void Fuzzer::ShuffleCorpus(UnitVector *V) {
324 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
325 if (Options.PreferSmall)
326 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
327 return A.size() < B.size();
328 });
329}
330
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000331// Tries random prefixes of corpus items.
332// Prefix length is chosen according to exponential distribution
333// to sample short lengths much more heavily.
334void Fuzzer::TruncateUnits(std::vector<Unit> *NewCorpus) {
335 size_t MaxCorpusLen = 0;
336 for (const auto &U : Corpus)
337 MaxCorpusLen = std::max(MaxCorpusLen, U.size());
338
339 if (MaxCorpusLen <= 1)
340 return;
341
342 // 50% of exponential distribution is Log[2]/lambda.
343 // Choose lambda so that median is MaxCorpusLen / 2.
344 double Lambda = 2.0 * log(2.0) / static_cast<double>(MaxCorpusLen);
345 std::exponential_distribution<> Dist(Lambda);
346 std::vector<double> Sizes;
347 size_t TruncatePoints = std::max(1ul, TruncateMaxRuns / Corpus.size());
348 Sizes.reserve(TruncatePoints);
349 for (size_t I = 0; I < TruncatePoints; ++I) {
350 Sizes.push_back(Dist(MD.GetRand().Get_mt19937()) + 1);
351 }
352 std::sort(Sizes.begin(), Sizes.end());
353
354 for (size_t S : Sizes) {
355 for (const auto &U : Corpus) {
356 if (S < U.size() && RunOne(U.data(), S)) {
357 Unit U1(U.begin(), U.begin() + S);
358 NewCorpus->push_back(U1);
359 WriteToOutputCorpus(U1);
360 PrintStatusForNewUnit(U1);
361 }
362 }
363 }
364 PrintStats("TRUNC ");
365}
366
Aaron Ballmanef116982015-01-29 16:58:29 +0000367void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000368 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000369 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000370 if (Options.ShuffleAtStartUp)
371 ShuffleCorpus(&Corpus);
372
Mike Aizatskyaf432a42016-05-24 23:14:29 +0000373 if (Options.TruncateUnits) {
374 ResetCoverage();
375 TruncateUnits(&NewCorpus);
376 ResetCoverage();
377 }
378
Kostya Serebryany945761b2016-03-18 00:23:29 +0000379 for (const auto &U : Corpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000380 bool NewCoverage = RunOne(U);
381 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany945761b2016-03-18 00:23:29 +0000382 NewCorpus.push_back(U);
383 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000384 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000385 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000386 TryDetectingAMemoryLeak(U.data(), U.size(),
387 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000388 }
389 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000390 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000391 for (auto &X : Corpus)
392 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000393 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000394}
395
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000396bool Fuzzer::UpdateMaxCoverage() {
397 uintptr_t PrevBufferLen = MaxCoverage.PcBufferLen;
398 bool Res = CoverageController::RecordMax(Options, &MaxCoverage);
399
400 if (Options.PrintNewCovPcs && PrevBufferLen != MaxCoverage.PcBufferLen) {
401 uintptr_t *CoverageBuf;
Dan Liew1873a492016-06-07 23:32:50 +0000402 EF->__sanitizer_get_coverage_pc_buffer(&CoverageBuf);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000403 assert(CoverageBuf);
404 for (size_t I = PrevBufferLen; I < MaxCoverage.PcBufferLen; ++I) {
405 Printf("%p\n", CoverageBuf[I]);
406 }
407 }
408
409 return Res;
410}
411
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000412bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000413 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000414
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000415 // TODO(aizatsky): this Reset call seems to be not needed.
416 CoverageController::ResetCounters(Options);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000417 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000418 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000419
Kostya Serebryany16901a92015-03-30 23:04:35 +0000420 auto UnitStopTime = system_clock::now();
421 auto TimeOfUnit =
422 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000423 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
424 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000425 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000426 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
427 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000428 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000429 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000430 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000431 }
432 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000433}
434
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000435void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000436 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
437 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000438 if (RunOne(Data, Size))
439 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000440}
441
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000442// Leak detection is expensive, so we first check if there were more mallocs
443// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
444struct MallocFreeTracer {
445 void Start() {
446 Mallocs = 0;
447 Frees = 0;
448 }
449 // Returns true if there were more mallocs than frees.
450 bool Stop() { return Mallocs > Frees; }
451 size_t Mallocs;
452 size_t Frees;
453};
454
455static thread_local MallocFreeTracer AllocTracer;
456
Dan Liew3868e462016-05-19 22:00:33 +0000457// FIXME: The hooks only count on Linux because
458// on Mac OSX calls to malloc are intercepted before
459// thread local storage is initialised leading to
460// crashes when accessing ``AllocTracer``.
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000461extern "C" {
Dan Liew3868e462016-05-19 22:00:33 +0000462void __sanitizer_malloc_hook(void *ptr, size_t size) {
463 if (!LIBFUZZER_APPLE)
464 AllocTracer.Mallocs++;
465}
466void __sanitizer_free_hook(void *ptr) {
467 if (!LIBFUZZER_APPLE)
468 AllocTracer.Frees++;
469}
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000470} // extern "C"
471
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000472size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000473 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000474 *Data = CurrentUnitData;
475 return CurrentUnitSize;
476}
477
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000478void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000479 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000480 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000481 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000482 // We copy the contents of Unit into a separate heap buffer
483 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000484 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
485 memcpy(DataCopy.get(), Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000486 if (CurrentUnitData && CurrentUnitData != Data)
487 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000488 AssignTaintLabels(DataCopy.get(), Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000489 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000490 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000491 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000492 (void)Res;
493 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000494 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000495 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000496}
497
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000498std::string Fuzzer::Coverage::DebugString() const {
499 std::string Result =
500 std::string("Coverage{") + "BlockCoverage=" +
501 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
502 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
503 std::to_string(CounterBitmapBits) + " PcMapBits=" +
504 std::to_string(PcMapBits) + "}";
505 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000506}
507
508void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000509 if (Options.OnlyASCII)
510 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000511 if (Options.OutputCorpus.empty())
512 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000513 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
514 WriteToFile(U, Path);
515 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000516 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000517}
518
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000519void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000520 if (!Options.SaveArtifacts)
521 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000522 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000523 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000524 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000525 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000526 Printf("artifact_prefix='%s'; Test unit written to %s\n",
527 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000528 if (U.size() <= kMaxUnitSizeToPrint)
529 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000530}
531
532void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000533 if (Options.OutputCorpus.empty())
534 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000535 for (const auto &U : Corpus)
536 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
537 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000538 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
539 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000540}
541
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000542void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
543 if (!Options.PrintNEW)
544 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000545 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000546 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000547 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000548 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000549 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000550 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000551}
552
553void Fuzzer::ReportNewCoverage(const Unit &U) {
554 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000555 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000556 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000557 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000558 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000559 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000560 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000561}
562
Kostya Serebryany945761b2016-03-18 00:23:29 +0000563// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
564// We do it by actually executing the units, sometimes more than once,
565// because we may be using different coverage-like signals and the only
566// common thing between them is that we can say "this unit found new stuff".
567UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
568 const UnitVector &Extra) {
569 UnitVector Res = Extra;
570 size_t OldSize = Res.size();
571 for (int Iter = 0; Iter < 10; Iter++) {
572 ShuffleCorpus(&Res);
573 ResetCoverage();
574
575 for (auto &U : Initial)
576 RunOne(U);
577
578 Corpus.clear();
579 for (auto &U : Res)
580 if (RunOne(U))
581 Corpus.push_back(U);
582
583 char Stat[7] = "MIN ";
584 Stat[3] = '0' + Iter;
585 PrintStats(Stat);
586
587 size_t NewSize = Corpus.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000588 assert(NewSize <= OldSize);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000589 Res.swap(Corpus);
590
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000591 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000592 break;
593 OldSize = NewSize;
594 }
595 return Res;
596}
597
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000598void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
599 if (Corpora.size() <= 1) {
600 Printf("Merge requires two or more corpus dirs\n");
601 return;
602 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000603 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
604
Kostya Serebryany945761b2016-03-18 00:23:29 +0000605 assert(Options.MaxLen > 0);
606 UnitVector Initial, Extra;
607 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
608 for (auto &C : ExtraCorpora)
609 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
610
611 if (!Initial.empty()) {
612 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
613 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000614 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000615
616 Printf("=== Merging extra %zd units\n", Extra.size());
617 auto Res = FindExtraUnits(Initial, Extra);
618
619 for (auto &U: Res)
620 WriteToOutputCorpus(U);
621
622 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000623}
624
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000625// Tries detecting a memory leak on the particular input that we have just
626// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000627void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
628 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000629 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
630 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000631 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
632 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000633 return; // No lsan.
634 // Run the target once again, but with lsan disabled so that if there is
635 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000636 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000637 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000638 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000639 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000640 if (NumberOfLeakDetectionAttempts++ > 1000) {
641 Options.DetectLeaks = false;
642 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
643 " Most likely the target function accumulates allocated\n"
644 " memory in a global state w/o actually leaking it.\n"
645 " If LeakSanitizer is enabled in this process it will still\n"
646 " run on the process shutdown.\n");
647 return;
648 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000649 // Now perform the actual lsan pass. This is expensive and we must ensure
650 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000651 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000652 if (DuringInitialCorpusExecution)
653 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
654 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000655 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000656 DumpCurrentUnit("leak-");
657 PrintFinalStats();
658 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
659 }
660}
661
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000662void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000663 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000664 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000665
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000666 auto &U = ChooseUnitToMutate();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000667 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000668 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000669 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000670 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000671
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000672 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000673 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000674 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000675 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000676 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000677 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000678 Size = NewSize;
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000679 if (Options.OnlyASCII)
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000680 ToASCII(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000681 if (i == 0)
682 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000683 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000684 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000685 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000686 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000687 }
688}
689
Kostya Serebryanye6926212015-11-04 23:22:25 +0000690// Returns an index of random unit from the corpus to mutate.
691// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000692// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000693size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000694 size_t Idx =
695 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000696 assert(Idx < Corpus.size());
697 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000698}
699
Kostya Serebryany945761b2016-03-18 00:23:29 +0000700void Fuzzer::ResetCoverage() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000701 CoverageController::Reset();
702 MaxCoverage.Reset();
703 CoverageController::Prepare(Options, &MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000704}
705
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000706// Experimental search heuristic: drilling.
707// - Read, shuffle, execute and minimize the corpus.
708// - Choose one random unit.
709// - Reset the coverage.
710// - Start fuzzing as if the chosen unit was the only element of the corpus.
711// - When done, reset the coverage again.
712// - Merge the newly created corpus into the original one.
713void Fuzzer::Drill() {
714 // The corpus is already read, shuffled, and minimized.
715 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000716 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000717
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000718 Unit U = ChooseUnitToMutate();
719
Kostya Serebryany945761b2016-03-18 00:23:29 +0000720 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000721
722 std::vector<Unit> SavedCorpus;
723 SavedCorpus.swap(Corpus);
724 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000725 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000726 assert(Corpus.size() == 1);
727 RunOne(U);
728 PrintStats("DRILL ");
729 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
730 SavedOutputCorpusPath.swap(Options.OutputCorpus);
731 Loop();
732
Kostya Serebryany945761b2016-03-18 00:23:29 +0000733 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000734
735 PrintStats("REINIT");
736 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000737 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000738 RunOne(U);
739 PrintStats("MERGE ");
740 Options.PrintNEW = true;
741 size_t NumMerged = 0;
742 for (auto &U : Corpus) {
743 if (RunOne(U)) {
744 PrintStatusForNewUnit(U);
745 NumMerged++;
746 WriteToOutputCorpus(U);
747 }
748 }
749 PrintStats("MERGED");
750 if (NumMerged && Options.Verbosity)
751 Printf("Drilling discovered %zd new units\n", NumMerged);
752}
753
754void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000755 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000756 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000757 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000758 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000759 auto Now = system_clock::now();
760 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000761 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000762 LastCorpusReload = Now;
763 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000764 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000765 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000766 if (Options.MaxTotalTimeSec > 0 &&
767 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000768 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000769 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000770 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000771 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000772 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000773
774 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000775 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000776}
777
Ivan Krasindf919102016-01-22 22:28:27 +0000778void Fuzzer::UpdateCorpusDistribution() {
779 size_t N = Corpus.size();
780 std::vector<double> Intervals(N + 1);
781 std::vector<double> Weights(N);
782 std::iota(Intervals.begin(), Intervals.end(), 0);
783 std::iota(Weights.begin(), Weights.end(), 1);
784 CorpusDistribution = std::piecewise_constant_distribution<double>(
785 Intervals.begin(), Intervals.end(), Weights.begin());
786}
787
788} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000789
790extern "C" {
791
792size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
793 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000794 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000795}
796} // extern "C"