blob: 2dcf11eb36d30e1b0e01ee83185f5fa453c4f7ea [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;
Aaron Ballmanef116982015-01-29 16:58:29 +000036
Kostya Serebryanyf26017b2016-05-26 21:32:30 +000037thread_local bool Fuzzer::IsMyThread;
38
Dan Liew1873a492016-06-07 23:32:50 +000039static void MissingExternalApiFunction(const char *FnName) {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000040 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000041 "Did you use -fsanitize-coverage=... to build your code?\n",
42 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000043 exit(1);
44}
45
Dan Liew1873a492016-06-07 23:32:50 +000046#define CHECK_EXTERNAL_FUNCTION(fn) \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000047 do { \
Dan Liew1873a492016-06-07 23:32:50 +000048 if (!(EF->fn)) \
49 MissingExternalApiFunction(#fn); \
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000050 } while (false)
51
Kostya Serebryany52a788e2015-03-31 20:13:20 +000052// Only one Fuzzer per process.
53static Fuzzer *F;
54
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000055void Fuzzer::ResetEdgeCoverage() {
56 CHECK_EXTERNAL_FUNCTION(__sanitizer_reset_coverage);
57 EF->__sanitizer_reset_coverage();
58}
59
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000060void Fuzzer::ResetCounters() {
61 if (Options.UseCounters) {
62 EF->__sanitizer_update_counter_bitset_and_clear_counters(0);
63 }
64 if (EF->__sanitizer_get_coverage_pc_buffer_pos)
65 PcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryany53501782016-09-15 04:36:45 +000066 TPC.GetNewPCsAndFlush();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +000067}
68
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000069void Fuzzer::PrepareCounters(Fuzzer::Coverage *C) {
70 if (Options.UseCounters) {
71 size_t NumCounters = EF->__sanitizer_get_number_of_counters();
72 C->CounterBitmap.resize(NumCounters);
73 }
74}
75
76// Records data to a maximum coverage tracker. Returns true if additional
77// coverage was discovered.
78bool Fuzzer::RecordMaxCoverage(Fuzzer::Coverage *C) {
79 bool Res = false;
80
Kostya Serebryanya5277d52016-09-15 01:30:18 +000081 TPC.FinalizeTrace();
82
Kostya Serebryanya00b2432016-09-14 02:13:06 +000083 uint64_t NewBlockCoverage =
84 EF->__sanitizer_get_total_unique_coverage() + TPC.GetTotalCoverage();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000085 if (NewBlockCoverage > C->BlockCoverage) {
86 Res = true;
87 C->BlockCoverage = NewBlockCoverage;
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000088 }
89
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000090 if (Options.UseIndirCalls &&
91 EF->__sanitizer_get_total_unique_caller_callee_pairs) {
92 uint64_t NewCallerCalleeCoverage =
93 EF->__sanitizer_get_total_unique_caller_callee_pairs();
94 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000095 Res = true;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +000096 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000097 }
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000098 }
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +000099
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000100 if (Options.UseCounters) {
101 uint64_t CounterDelta =
102 EF->__sanitizer_update_counter_bitset_and_clear_counters(
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000103 C->CounterBitmap.data()) +
104 TPC.UpdateCounterMap(&C->TPCMap);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000105 if (CounterDelta > 0) {
106 Res = true;
107 C->CounterBitmapBits += CounterDelta;
108 }
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000109
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000110 }
111
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000112 size_t NewVPMapBits = VPMapMergeFromCurrent(C->VPMap);
113 if (NewVPMapBits > C->VPMapBits) {
114 Res = true;
115 C->VPMapBits = NewVPMapBits;
116 }
117
118 if (EF->__sanitizer_get_coverage_pc_buffer_pos) {
119 uint64_t NewPcBufferPos = EF->__sanitizer_get_coverage_pc_buffer_pos();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000120 if (NewPcBufferPos > PcBufferPos) {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000121 Res = true;
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000122 PcBufferPos = NewPcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000123 }
124
125 if (PcBufferLen && NewPcBufferPos >= PcBufferLen) {
126 Printf("ERROR: PC buffer overflow\n");
127 _Exit(1);
128 }
129 }
130
131 return Res;
132}
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000133
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000134// Leak detection is expensive, so we first check if there were more mallocs
135// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
136struct MallocFreeTracer {
137 void Start() {
138 Mallocs = 0;
139 Frees = 0;
140 }
141 // Returns true if there were more mallocs than frees.
142 bool Stop() { return Mallocs > Frees; }
143 std::atomic<size_t> Mallocs;
144 std::atomic<size_t> Frees;
145};
146
147static MallocFreeTracer AllocTracer;
148
149void MallocHook(const volatile void *ptr, size_t size) {
150 AllocTracer.Mallocs++;
151}
152void FreeHook(const volatile void *ptr) {
153 AllocTracer.Frees++;
154}
155
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000156Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000157 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000158 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000159 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000160 assert(!F);
161 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000162 ResetCoverage();
Kostya Serebryanyf26017b2016-05-26 21:32:30 +0000163 IsMyThread = true;
Kostya Serebryanyfd6ad5b2016-06-16 20:17:41 +0000164 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
165 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
Kostya Serebryanya5277d52016-09-15 01:30:18 +0000166 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000167
168 if (Options.PrintNewCovPcs) {
169 PcBufferLen = 1 << 24;
170 PcBuffer = new uintptr_t[PcBufferLen];
171 EF->__sanitizer_set_coverage_pc_buffer(PcBuffer, PcBufferLen);
172 }
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000173 if (Options.Verbosity)
174 TPC.PrintModuleInfo();
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000175 if (!Options.OutputCorpus.empty() && Options.Reload)
176 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000177}
Aaron Ballmanef116982015-01-29 16:58:29 +0000178
Mike Aizatskyb4bbc3b2016-08-05 20:09:53 +0000179Fuzzer::~Fuzzer() { }
180
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000181void Fuzzer::LazyAllocateCurrentUnitData() {
182 if (CurrentUnitData || Options.MaxLen == 0) return;
183 CurrentUnitData = new uint8_t[Options.MaxLen];
184}
185
Aaron Ballmanef116982015-01-29 16:58:29 +0000186void Fuzzer::SetDeathCallback() {
Dan Liew1873a492016-06-07 23:32:50 +0000187 CHECK_EXTERNAL_FUNCTION(__sanitizer_set_death_callback);
188 EF->__sanitizer_set_death_callback(StaticDeathCallback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000189}
190
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000191void Fuzzer::StaticDeathCallback() {
192 assert(F);
193 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000194}
195
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000196static void WarnOnUnsuccessfullMerge(bool DoWarn) {
Kostya Serebryany8c537c52016-09-10 02:17:22 +0000197 if (!DoWarn) return;
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000198 Printf(
199 "***\n"
200 "***\n"
201 "***\n"
202 "*** NOTE: merge did not succeed due to a failure on one of the inputs.\n"
203 "*** You will need to filter out crashes from the corpus, e.g. like this:\n"
204 "*** for f in WITH_CRASHES/*; do ./fuzzer $f && cp $f NO_CRASHES; done\n"
205 "*** Future versions may have crash-resistant merge, stay tuned.\n"
206 "***\n"
207 "***\n"
208 "***\n");
209}
210
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000211void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000212 WarnOnUnsuccessfullMerge(InMergeMode);
Kostya Serebryany311cc832016-05-28 04:19:46 +0000213 if (!CurrentUnitData) return; // Happens when running individual inputs.
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000214 MD.PrintMutationSequence();
215 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000216 size_t UnitSize = CurrentUnitSize;
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000217 if (UnitSize <= kMaxUnitSizeToPrint) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000218 PrintHexArray(CurrentUnitData, UnitSize, "\n");
219 PrintASCII(CurrentUnitData, UnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000220 }
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000221 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
222 Prefix);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000223}
224
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000225NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000226void Fuzzer::DeathCallback() {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000227 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000228 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000229}
230
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000231void Fuzzer::StaticAlarmCallback() {
232 assert(F);
233 F->AlarmCallback();
234}
235
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000236void Fuzzer::StaticCrashSignalCallback() {
237 assert(F);
238 F->CrashCallback();
239}
240
241void Fuzzer::StaticInterruptCallback() {
242 assert(F);
243 F->InterruptCallback();
244}
245
246void Fuzzer::CrashCallback() {
247 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
Dan Liew1873a492016-06-07 23:32:50 +0000248 if (EF->__sanitizer_print_stack_trace)
249 EF->__sanitizer_print_stack_trace();
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000250 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
251 " Combine libFuzzer with AddressSanitizer or similar for better "
252 "crash reports.\n");
253 Printf("SUMMARY: libFuzzer: deadly signal\n");
254 DumpCurrentUnit("crash-");
255 PrintFinalStats();
256 exit(Options.ErrorExitCode);
257}
258
259void Fuzzer::InterruptCallback() {
260 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
261 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000262 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000263}
264
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000265NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000266void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000267 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000268 if (!InFuzzingThread()) return;
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000269 if (!CurrentUnitSize)
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000270 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000271 size_t Seconds =
272 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000273 if (Seconds == 0)
274 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000275 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000276 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000277 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000278 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000279 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
280 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000281 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000282 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
283 Seconds);
Dan Liew1873a492016-06-07 23:32:50 +0000284 if (EF->__sanitizer_print_stack_trace)
285 EF->__sanitizer_print_stack_trace();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000286 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000287 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000288 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000289 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000290}
291
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000292void Fuzzer::RssLimitCallback() {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000293 Printf(
294 "==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
295 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
Kostya Serebryanyf6414422016-06-02 01:33:11 +0000296 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Dan Liew1873a492016-06-07 23:32:50 +0000297 if (EF->__sanitizer_print_memory_profile)
298 EF->__sanitizer_print_memory_profile(50);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000299 DumpCurrentUnit("oom-");
300 Printf("SUMMARY: libFuzzer: out-of-memory\n");
301 PrintFinalStats();
302 _Exit(Options.ErrorExitCode); // Stop right now.
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000303}
304
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000305void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000306 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000307 if (Options.OutputCSV) {
308 static bool csvHeaderPrinted = false;
309 if (!csvHeaderPrinted) {
310 csvHeaderPrinted = true;
311 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
312 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000313 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000314 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
315 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000316 }
317
318 if (!Options.Verbosity)
319 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000320 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000321 if (MaxCoverage.BlockCoverage)
322 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +0000323 if (MaxCoverage.VPMapBits)
324 Printf(" vp: %zd", MaxCoverage.VPMapBits);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000325 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000326 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000327 if (MaxCoverage.CallerCalleeCoverage)
328 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000329 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000330 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000331}
332
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000333void Fuzzer::PrintFinalStats() {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000334 if (Options.PrintCoverage)
335 TPC.PrintCoverage();
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000336 if (!Options.PrintFinalStats) return;
337 size_t ExecPerSec = execPerSec();
338 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
339 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
340 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
341 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
342 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
343}
344
Kostya Serebryany64d24572016-03-12 01:57:04 +0000345void Fuzzer::SetMaxLen(size_t MaxLen) {
346 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
347 assert(MaxLen);
348 Options.MaxLen = MaxLen;
349 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
350}
351
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000352void Fuzzer::ReadDir(const std::string &Path, long *Epoch, size_t MaxSize) {
353 Printf("Loading corpus: %s\n", Path.c_str());
354 std::vector<Unit> V;
355 ReadDirToVectorOfUnits(Path.c_str(), &V, Epoch, MaxSize);
356 for (auto &U : V)
357 Corpus.push_back(U);
358}
Kostya Serebryany64d24572016-03-12 01:57:04 +0000359
360void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000361 if (Options.OutputCorpus.empty() || !Options.Reload) return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000362 std::vector<Unit> AdditionalCorpus;
363 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000364 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000365 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000366 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000367 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000368 if (X.size() > MaxSize)
369 X.resize(MaxSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000370 if (!Corpus.HasUnit(X)) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000371 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000372 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000373 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000374 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000375 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000376 }
377 }
378}
379
Kostya Serebryany945761b2016-03-18 00:23:29 +0000380void Fuzzer::ShuffleCorpus(UnitVector *V) {
381 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
382 if (Options.PreferSmall)
383 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
384 return A.size() < B.size();
385 });
386}
387
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000388void Fuzzer::ShuffleAndMinimize(UnitVector *InitialCorpus) {
389 Printf("#0\tREAD units: %zd\n", InitialCorpus->size());
Kostya Serebryany945761b2016-03-18 00:23:29 +0000390 if (Options.ShuffleAtStartUp)
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000391 ShuffleCorpus(InitialCorpus);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000392
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000393 for (const auto &U : *InitialCorpus) {
Mike Aizatsky1f88b122016-06-07 18:16:32 +0000394 bool NewCoverage = RunOne(U);
395 if (!Options.PruneCorpus || NewCoverage) {
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000396 Corpus.push_back(U);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000397 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000398 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000399 }
Kostya Serebryany4b923262016-05-26 20:25:49 +0000400 TryDetectingAMemoryLeak(U.data(), U.size(),
401 /*DuringInitialCorpusExecution*/ true);
Aaron Ballmanef116982015-01-29 16:58:29 +0000402 }
Ivan Krasindf919102016-01-22 22:28:27 +0000403 UpdateCorpusDistribution();
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000404 PrintStats("INITED");
Kostya Serebryany76f42522016-06-08 01:46:13 +0000405 if (Corpus.empty()) {
406 Printf("ERROR: no interesting inputs were found. "
407 "Is the code instrumented for coverage? Exiting.\n");
408 exit(1);
409 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000410}
411
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000412bool Fuzzer::UpdateMaxCoverage() {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000413 PrevPcBufferPos = PcBufferPos;
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000414 bool Res = RecordMaxCoverage(&MaxCoverage);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000415
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000416 return Res;
417}
418
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000419bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000420 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000421
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000422 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000423 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000424
Kostya Serebryany16901a92015-03-30 23:04:35 +0000425 auto UnitStopTime = system_clock::now();
426 auto TimeOfUnit =
427 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000428 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
429 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000430 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000431 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
432 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000433 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000434 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000435 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000436 }
437 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000438}
439
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000440void Fuzzer::RunOneAndUpdateCorpus(const uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000441 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
442 return;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000443 if (RunOne(Data, Size))
444 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000445}
446
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000447size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000448 assert(InFuzzingThread());
Kostya Serebryanyd8384122016-05-26 22:17:32 +0000449 *Data = CurrentUnitData;
450 return CurrentUnitSize;
451}
452
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000453void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000454 assert(InFuzzingThread());
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000455 LazyAllocateCurrentUnitData();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000456 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000457 // We copy the contents of Unit into a separate heap buffer
458 // so that we reliably find buffer overflows in it.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000459 uint8_t *DataCopy = new uint8_t[Size];
460 memcpy(DataCopy, Data, Size);
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000461 if (CurrentUnitData && CurrentUnitData != Data)
462 memcpy(CurrentUnitData, Data, Size);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000463 AssignTaintLabels(DataCopy, Size);
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000464 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000465 AllocTracer.Start();
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000466 ResetCounters(); // Reset coverage right before the callback.
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000467 int Res = CB(DataCopy, Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000468 (void)Res;
469 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000470 CurrentUnitSize = 0;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000471 assert(Res == 0);
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000472 delete[] DataCopy;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000473}
474
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000475std::string Fuzzer::Coverage::DebugString() const {
476 std::string Result =
477 std::string("Coverage{") + "BlockCoverage=" +
478 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
479 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
Kostya Serebryanya00b2432016-09-14 02:13:06 +0000480 std::to_string(CounterBitmapBits) +
481 " VPMapBits " + std::to_string(VPMapBits) + "}";
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000482 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000483}
484
485void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000486 if (Options.OnlyASCII)
487 assert(IsASCII(U));
Ivan Krasindf919102016-01-22 22:28:27 +0000488 if (Options.OutputCorpus.empty())
489 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000490 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
491 WriteToFile(U, Path);
492 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000493 Printf("Written to %s\n", Path.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000494}
495
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000496void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000497 if (!Options.SaveArtifacts)
498 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000499 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000500 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000501 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000502 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000503 Printf("artifact_prefix='%s'; Test unit written to %s\n",
504 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000505 if (U.size() <= kMaxUnitSizeToPrint)
506 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000507}
508
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000509void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
510 if (!Options.PrintNEW)
511 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000512 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000513 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000514 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000515 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000516 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000517 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000518}
519
Kostya Serebryany53501782016-09-15 04:36:45 +0000520void Fuzzer::PrintOneNewPC(uintptr_t PC) {
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000521 PrintPC("\tNEW_PC: %p %F %L\n",
522 "\tNEW_PC: %p\n", PC);
Kostya Serebryany53501782016-09-15 04:36:45 +0000523}
524
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000525void Fuzzer::PrintNewPCs() {
Kostya Serebryany53501782016-09-15 04:36:45 +0000526 if (!Options.PrintNewCovPcs) return;
527 if (PrevPcBufferPos != PcBufferPos) {
Kostya Serebryanyb76a2a52016-09-09 02:38:28 +0000528 int NumPrinted = 0;
529 for (size_t I = PrevPcBufferPos; I < PcBufferPos; ++I) {
530 if (NumPrinted++ > 30) break; // Don't print too many new PCs.
Kostya Serebryany53501782016-09-15 04:36:45 +0000531 PrintOneNewPC(PcBuffer[I]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000532 }
533 }
Kostya Serebryany53501782016-09-15 04:36:45 +0000534 uintptr_t *PCs;
535 if (size_t NumNewPCs = TPC.GetNewPCsAndFlush(&PCs))
536 for (size_t i = 0; i < NumNewPCs; i++)
537 PrintOneNewPC(PCs[i]);
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000538}
539
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000540void Fuzzer::ReportNewCoverage(const Unit &U) {
541 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000542 UpdateCorpusDistribution();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000543 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000544 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000545 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000546 NumberOfNewUnitsAdded++;
Kostya Serebryany0f0fa4f2016-08-25 22:35:08 +0000547 PrintNewPCs();
Aaron Ballmanef116982015-01-29 16:58:29 +0000548}
549
Kostya Serebryany945761b2016-03-18 00:23:29 +0000550// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
551// We do it by actually executing the units, sometimes more than once,
552// because we may be using different coverage-like signals and the only
553// common thing between them is that we can say "this unit found new stuff".
554UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
555 const UnitVector &Extra) {
556 UnitVector Res = Extra;
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000557 UnitVector Tmp;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000558 size_t OldSize = Res.size();
559 for (int Iter = 0; Iter < 10; Iter++) {
560 ShuffleCorpus(&Res);
561 ResetCoverage();
562
563 for (auto &U : Initial)
564 RunOne(U);
565
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000566 Tmp.clear();
Kostya Serebryany945761b2016-03-18 00:23:29 +0000567 for (auto &U : Res)
568 if (RunOne(U))
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000569 Tmp.push_back(U);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000570
571 char Stat[7] = "MIN ";
572 Stat[3] = '0' + Iter;
573 PrintStats(Stat);
574
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000575 size_t NewSize = Tmp.size();
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000576 assert(NewSize <= OldSize);
Kostya Serebryany09aa01a2016-09-21 01:04:43 +0000577 Res.swap(Tmp);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000578
Kostya Serebryanya0788e72016-05-13 22:11:23 +0000579 if (NewSize + 5 >= OldSize)
Kostya Serebryany945761b2016-03-18 00:23:29 +0000580 break;
581 OldSize = NewSize;
582 }
583 return Res;
584}
585
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000586void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
587 if (Corpora.size() <= 1) {
588 Printf("Merge requires two or more corpus dirs\n");
589 return;
590 }
Kostya Serebryanyb991cc12016-09-10 00:15:41 +0000591 InMergeMode = true;
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000592 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
593
Kostya Serebryany945761b2016-03-18 00:23:29 +0000594 assert(Options.MaxLen > 0);
595 UnitVector Initial, Extra;
596 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
597 for (auto &C : ExtraCorpora)
598 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
599
600 if (!Initial.empty()) {
601 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
602 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000603 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000604
605 Printf("=== Merging extra %zd units\n", Extra.size());
606 auto Res = FindExtraUnits(Initial, Extra);
607
608 for (auto &U: Res)
609 WriteToOutputCorpus(U);
610
611 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000612}
613
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000614// Tries detecting a memory leak on the particular input that we have just
615// executed before calling this function.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000616void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
617 bool DuringInitialCorpusExecution) {
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000618 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
619 if (!Options.DetectLeaks) return;
Dan Liew1873a492016-06-07 23:32:50 +0000620 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
621 !(EF->__lsan_do_recoverable_leak_check))
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000622 return; // No lsan.
623 // Run the target once again, but with lsan disabled so that if there is
624 // a real leak we do not report it twice.
Dan Liew1873a492016-06-07 23:32:50 +0000625 EF->__lsan_disable();
Kostya Serebryany47952102016-05-29 15:58:57 +0000626 RunOne(Data, Size);
Dan Liew1873a492016-06-07 23:32:50 +0000627 EF->__lsan_enable();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000628 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000629 if (NumberOfLeakDetectionAttempts++ > 1000) {
630 Options.DetectLeaks = false;
631 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
632 " Most likely the target function accumulates allocated\n"
633 " memory in a global state w/o actually leaking it.\n"
634 " If LeakSanitizer is enabled in this process it will still\n"
635 " run on the process shutdown.\n");
636 return;
637 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000638 // Now perform the actual lsan pass. This is expensive and we must ensure
639 // we don't call it too often.
Dan Liew1873a492016-06-07 23:32:50 +0000640 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
Kostya Serebryany4b923262016-05-26 20:25:49 +0000641 if (DuringInitialCorpusExecution)
642 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
643 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
Kostya Serebryany0edb5632016-05-27 00:54:15 +0000644 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000645 DumpCurrentUnit("leak-");
646 PrintFinalStats();
647 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
648 }
649}
650
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000651void Fuzzer::MutateAndTestOne() {
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000652 LazyAllocateCurrentUnitData();
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000653 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000654
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000655 auto &U = ChooseUnitToMutate();
Kostya Serebryanya9a54802016-08-17 20:45:23 +0000656 ComputeSHA1(U.data(), U.size(), BaseSha1); // Remember where we started.
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000657 assert(CurrentUnitData);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000658 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000659 assert(Size <= Options.MaxLen && "Oversized Unit");
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000660 memcpy(CurrentUnitData, U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000661
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000662 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000663 size_t NewSize = 0;
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000664 NewSize = MD.Mutate(CurrentUnitData, Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000665 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000666 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000667 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000668 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000669 if (i == 0)
670 StartTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000671 RunOneAndUpdateCorpus(CurrentUnitData, Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000672 StopTraceRecording();
Kostya Serebryany8fc3a272016-05-27 00:21:33 +0000673 TryDetectingAMemoryLeak(CurrentUnitData, Size,
Kostya Serebryany4b923262016-05-26 20:25:49 +0000674 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000675 }
676}
677
Kostya Serebryanye6926212015-11-04 23:22:25 +0000678// Returns an index of random unit from the corpus to mutate.
679// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000680// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000681size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000682 size_t Idx =
683 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000684 assert(Idx < Corpus.size());
685 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000686}
687
Kostya Serebryany945761b2016-03-18 00:23:29 +0000688void Fuzzer::ResetCoverage() {
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000689 ResetEdgeCoverage();
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000690 MaxCoverage.Reset();
Kostya Serebryany3e36ec12016-09-17 05:04:47 +0000691 TPC.Reset();
Kostya Serebryanyf67357c2016-08-25 01:25:03 +0000692 PrepareCounters(&MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000693}
694
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000695void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000696 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000697 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000698 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000699 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000700 auto Now = system_clock::now();
701 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000702 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000703 LastCorpusReload = Now;
704 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000705 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000706 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000707 if (Options.MaxTotalTimeSec > 0 &&
708 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000709 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000710 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000711 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000712 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000713 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000714
715 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000716 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000717}
718
Ivan Krasindf919102016-01-22 22:28:27 +0000719void Fuzzer::UpdateCorpusDistribution() {
720 size_t N = Corpus.size();
721 std::vector<double> Intervals(N + 1);
722 std::vector<double> Weights(N);
723 std::iota(Intervals.begin(), Intervals.end(), 0);
724 std::iota(Weights.begin(), Weights.end(), 1);
725 CorpusDistribution = std::piecewise_constant_distribution<double>(
726 Intervals.begin(), Intervals.end(), Weights.begin());
727}
728
729} // namespace fuzzer
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000730
731extern "C" {
732
733size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
734 assert(fuzzer::F);
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000735 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
Kostya Serebryany8b0d90a2016-05-13 18:04:35 +0000736}
737} // extern "C"