blob: da59da662db67bbff1dec6cce91e540486bcd177 [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +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 "FuzzerCorpus.h"
13#include "FuzzerIO.h"
14#include "FuzzerInternal.h"
15#include "FuzzerMutate.h"
16#include "FuzzerRandom.h"
17#include "FuzzerShmem.h"
18#include "FuzzerTracePC.h"
19#include <algorithm>
20#include <cstring>
21#include <memory>
vitalybukab3e5a2c2017-11-01 03:02:59 +000022#include <mutex>
george.karpenkov29efa6d2017-08-21 23:25:50 +000023#include <set>
24
25#if defined(__has_include)
26#if __has_include(<sanitizer / lsan_interface.h>)
27#include <sanitizer/lsan_interface.h>
28#endif
29#endif
30
31#define NO_SANITIZE_MEMORY
32#if defined(__has_feature)
33#if __has_feature(memory_sanitizer)
34#undef NO_SANITIZE_MEMORY
35#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
36#endif
37#endif
38
39namespace fuzzer {
40static const size_t kMaxUnitSizeToPrint = 256;
41
42thread_local bool Fuzzer::IsMyThread;
43
44SharedMemoryRegion SMR;
45
46// Only one Fuzzer per process.
47static Fuzzer *F;
48
49// Leak detection is expensive, so we first check if there were more mallocs
50// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
51struct MallocFreeTracer {
52 void Start(int TraceLevel) {
53 this->TraceLevel = TraceLevel;
54 if (TraceLevel)
55 Printf("MallocFreeTracer: START\n");
56 Mallocs = 0;
57 Frees = 0;
58 }
59 // Returns true if there were more mallocs than frees.
60 bool Stop() {
61 if (TraceLevel)
62 Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
63 Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
64 bool Result = Mallocs > Frees;
65 Mallocs = 0;
66 Frees = 0;
67 TraceLevel = 0;
68 return Result;
69 }
70 std::atomic<size_t> Mallocs;
71 std::atomic<size_t> Frees;
72 int TraceLevel = 0;
vitalybukae6504cf2017-11-02 04:12:10 +000073
74 std::recursive_mutex TraceMutex;
75 bool TraceDisabled = false;
george.karpenkov29efa6d2017-08-21 23:25:50 +000076};
77
78static MallocFreeTracer AllocTracer;
79
vitalybukae6504cf2017-11-02 04:12:10 +000080// Locks printing and avoids nested hooks triggered from mallocs/frees in
81// sanitizer.
82class TraceLock {
83public:
84 TraceLock() : Lock(AllocTracer.TraceMutex) {
85 AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
86 }
87 ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
88
89 bool IsDisabled() const {
90 // This is already inverted value.
91 return !AllocTracer.TraceDisabled;
92 }
93
94private:
95 std::lock_guard<std::recursive_mutex> Lock;
96};
vitalybukab3e5a2c2017-11-01 03:02:59 +000097
george.karpenkov29efa6d2017-08-21 23:25:50 +000098ATTRIBUTE_NO_SANITIZE_MEMORY
99void MallocHook(const volatile void *ptr, size_t size) {
100 size_t N = AllocTracer.Mallocs++;
101 F->HandleMalloc(size);
102 if (int TraceLevel = AllocTracer.TraceLevel) {
vitalybukae6504cf2017-11-02 04:12:10 +0000103 TraceLock Lock;
104 if (Lock.IsDisabled())
105 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000106 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
107 if (TraceLevel >= 2 && EF)
morehousebd67cc22018-05-08 23:45:05 +0000108 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000109 }
110}
111
112ATTRIBUTE_NO_SANITIZE_MEMORY
113void FreeHook(const volatile void *ptr) {
114 size_t N = AllocTracer.Frees++;
115 if (int TraceLevel = AllocTracer.TraceLevel) {
vitalybukae6504cf2017-11-02 04:12:10 +0000116 TraceLock Lock;
117 if (Lock.IsDisabled())
118 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000119 Printf("FREE[%zd] %p\n", N, ptr);
120 if (TraceLevel >= 2 && EF)
morehousebd67cc22018-05-08 23:45:05 +0000121 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000122 }
123}
124
125// Crash on a single malloc that exceeds the rss limit.
126void Fuzzer::HandleMalloc(size_t Size) {
kcc120e40b2017-12-01 22:12:04 +0000127 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000128 return;
129 Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
130 Size);
131 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000132 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000133 DumpCurrentUnit("oom-");
134 Printf("SUMMARY: libFuzzer: out-of-memory\n");
135 PrintFinalStats();
136 _Exit(Options.ErrorExitCode); // Stop right now.
137}
138
139Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
140 FuzzingOptions Options)
141 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
142 if (EF->__sanitizer_set_death_callback)
143 EF->__sanitizer_set_death_callback(StaticDeathCallback);
144 assert(!F);
145 F = this;
146 TPC.ResetMaps();
147 IsMyThread = true;
148 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
149 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
150 TPC.SetUseCounters(Options.UseCounters);
kcc3850d062018-07-03 22:33:09 +0000151 TPC.SetUseValueProfileMask(Options.UseValueProfile);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000152
153 if (Options.Verbosity)
154 TPC.PrintModuleInfo();
155 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
156 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
157 MaxInputLen = MaxMutationLen = Options.MaxLen;
158 TmpMaxMutationLen = Max(size_t(4), Corpus.MaxInputSize());
159 AllocateCurrentUnitData();
160 CurrentUnitSize = 0;
161 memset(BaseSha1, 0, sizeof(BaseSha1));
kcc3acbe072018-05-16 23:26:37 +0000162 TPC.SetFocusFunction(Options.FocusFunction);
kcc86e43882018-06-06 01:23:29 +0000163 DFT.Init(Options.DataFlowTrace, Options.FocusFunction);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000164}
165
alekseyshl9f6a9f22017-10-23 23:24:33 +0000166Fuzzer::~Fuzzer() {}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000167
168void Fuzzer::AllocateCurrentUnitData() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000169 if (CurrentUnitData || MaxInputLen == 0)
170 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000171 CurrentUnitData = new uint8_t[MaxInputLen];
172}
173
174void Fuzzer::StaticDeathCallback() {
175 assert(F);
176 F->DeathCallback();
177}
178
179void Fuzzer::DumpCurrentUnit(const char *Prefix) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000180 if (!CurrentUnitData)
181 return; // Happens when running individual inputs.
morehouse1467b792018-07-09 23:51:08 +0000182 ScopedDisableMsanInterceptorChecks S;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000183 MD.PrintMutationSequence();
184 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
185 size_t UnitSize = CurrentUnitSize;
186 if (UnitSize <= kMaxUnitSizeToPrint) {
187 PrintHexArray(CurrentUnitData, UnitSize, "\n");
188 PrintASCII(CurrentUnitData, UnitSize, "\n");
189 }
190 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
191 Prefix);
192}
193
194NO_SANITIZE_MEMORY
195void Fuzzer::DeathCallback() {
196 DumpCurrentUnit("crash-");
197 PrintFinalStats();
198}
199
200void Fuzzer::StaticAlarmCallback() {
201 assert(F);
202 F->AlarmCallback();
203}
204
205void Fuzzer::StaticCrashSignalCallback() {
206 assert(F);
207 F->CrashCallback();
208}
209
210void Fuzzer::StaticExitCallback() {
211 assert(F);
212 F->ExitCallback();
213}
214
215void Fuzzer::StaticInterruptCallback() {
216 assert(F);
217 F->InterruptCallback();
218}
219
kcc1239a992017-11-09 20:30:19 +0000220void Fuzzer::StaticGracefulExitCallback() {
221 assert(F);
222 F->GracefulExitRequested = true;
223 Printf("INFO: signal received, trying to exit gracefully\n");
224}
225
george.karpenkov29efa6d2017-08-21 23:25:50 +0000226void Fuzzer::StaticFileSizeExceedCallback() {
227 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
228 exit(1);
229}
230
231void Fuzzer::CrashCallback() {
morehousef7b44452018-05-02 02:55:28 +0000232 if (EF->__sanitizer_acquire_crash_state)
233 EF->__sanitizer_acquire_crash_state();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000234 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000235 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000236 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
237 " Combine libFuzzer with AddressSanitizer or similar for better "
238 "crash reports.\n");
239 Printf("SUMMARY: libFuzzer: deadly signal\n");
240 DumpCurrentUnit("crash-");
241 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000242 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000243}
244
245void Fuzzer::ExitCallback() {
246 if (!RunningCB)
247 return; // This exit did not come from the user callback
morehouse5a4566a2018-05-01 21:01:53 +0000248 if (EF->__sanitizer_acquire_crash_state &&
249 !EF->__sanitizer_acquire_crash_state())
250 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000251 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000252 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000253 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
254 DumpCurrentUnit("crash-");
255 PrintFinalStats();
256 _Exit(Options.ErrorExitCode);
257}
258
kcc1239a992017-11-09 20:30:19 +0000259void Fuzzer::MaybeExitGracefully() {
260 if (!GracefulExitRequested) return;
261 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
262 PrintFinalStats();
263 _Exit(0);
264}
265
george.karpenkov29efa6d2017-08-21 23:25:50 +0000266void Fuzzer::InterruptCallback() {
267 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
268 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000269 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000270}
271
272NO_SANITIZE_MEMORY
273void Fuzzer::AlarmCallback() {
274 assert(Options.UnitTimeoutSec > 0);
275 // In Windows Alarm callback is executed by a different thread.
276#if !LIBFUZZER_WINDOWS
alekseyshl9f6a9f22017-10-23 23:24:33 +0000277 if (!InFuzzingThread())
278 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000279#endif
280 if (!RunningCB)
281 return; // We have not started running units yet.
282 size_t Seconds =
283 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
284 if (Seconds == 0)
285 return;
286 if (Options.Verbosity >= 2)
287 Printf("AlarmCallback %zd\n", Seconds);
288 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000289 if (EF->__sanitizer_acquire_crash_state &&
290 !EF->__sanitizer_acquire_crash_state())
291 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000292 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
293 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
294 Options.UnitTimeoutSec);
295 DumpCurrentUnit("timeout-");
296 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
297 Seconds);
morehousebd67cc22018-05-08 23:45:05 +0000298 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000299 Printf("SUMMARY: libFuzzer: timeout\n");
300 PrintFinalStats();
301 _Exit(Options.TimeoutExitCode); // Stop right now.
302 }
303}
304
305void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000306 if (EF->__sanitizer_acquire_crash_state &&
307 !EF->__sanitizer_acquire_crash_state())
308 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000309 Printf(
310 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
311 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
312 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000313 PrintMemoryProfile();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000314 DumpCurrentUnit("oom-");
315 Printf("SUMMARY: libFuzzer: out-of-memory\n");
316 PrintFinalStats();
317 _Exit(Options.ErrorExitCode); // Stop right now.
318}
319
320void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
321 size_t ExecPerSec = execPerSec();
322 if (!Options.Verbosity)
323 return;
324 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
325 if (size_t N = TPC.GetTotalPCCoverage())
326 Printf(" cov: %zd", N);
327 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000328 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000329 if (!Corpus.empty()) {
330 Printf(" corp: %zd", Corpus.NumActiveUnits());
331 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000332 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000333 Printf("/%zdb", N);
334 else if (N < (1 << 24))
335 Printf("/%zdKb", N >> 10);
336 else
337 Printf("/%zdMb", N >> 20);
338 }
kcc3acbe072018-05-16 23:26:37 +0000339 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
340 Printf(" focus: %zd", FF);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000341 }
morehousea6c692c2018-02-22 19:00:17 +0000342 if (TmpMaxMutationLen)
343 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000344 if (Units)
345 Printf(" units: %zd", Units);
346
347 Printf(" exec/s: %zd", ExecPerSec);
348 Printf(" rss: %zdMb", GetPeakRSSMb());
349 Printf("%s", End);
350}
351
352void Fuzzer::PrintFinalStats() {
353 if (Options.PrintCoverage)
354 TPC.PrintCoverage();
dor1sf8e5f862018-07-16 14:54:23 +0000355 if (Options.PrintUnstableStats)
356 TPC.PrintUnstableStats();
kcca7dd2a92018-05-21 19:47:00 +0000357 if (Options.DumpCoverage)
358 TPC.DumpCoverage();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000359 if (Options.PrintCorpusStats)
360 Corpus.PrintStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000361 if (!Options.PrintFinalStats)
362 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000363 size_t ExecPerSec = execPerSec();
364 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
365 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
366 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
367 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
368 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
369}
370
371void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
372 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
373 assert(MaxInputLen);
374 this->MaxInputLen = MaxInputLen;
375 this->MaxMutationLen = MaxInputLen;
376 AllocateCurrentUnitData();
377 Printf("INFO: -max_len is not provided; "
378 "libFuzzer will not generate inputs larger than %zd bytes\n",
379 MaxInputLen);
380}
381
382void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
383 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
384 this->MaxMutationLen = MaxMutationLen;
385}
386
387void Fuzzer::CheckExitOnSrcPosOrItem() {
388 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000389 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000390 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000391 if (!PCsSet->insert(PC).second)
392 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000393 std::string Descr = DescribePC("%F %L", PC + 1);
394 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
395 Printf("INFO: found line matching '%s', exiting.\n",
396 Options.ExitOnSrcPos.c_str());
397 _Exit(0);
398 }
399 };
400 TPC.ForEachObservedPC(HandlePC);
401 }
402 if (!Options.ExitOnItem.empty()) {
403 if (Corpus.HasUnit(Options.ExitOnItem)) {
404 Printf("INFO: found item with checksum '%s', exiting.\n",
405 Options.ExitOnItem.c_str());
406 _Exit(0);
407 }
408 }
409}
410
411void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000412 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
413 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000414 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000415 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
416 &EpochOfLastReadOfOutputCorpus, MaxSize,
417 /*ExitOnError*/ false);
418 if (Options.Verbosity >= 2)
419 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
420 bool Reloaded = false;
421 for (auto &U : AdditionalCorpus) {
422 if (U.size() > MaxSize)
423 U.resize(MaxSize);
424 if (!Corpus.HasUnit(U)) {
425 if (RunOne(U.data(), U.size())) {
426 CheckExitOnSrcPosOrItem();
427 Reloaded = true;
428 }
429 }
430 }
431 if (Reloaded)
432 PrintStats("RELOAD");
433}
434
george.karpenkov29efa6d2017-08-21 23:25:50 +0000435void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
436 auto TimeOfUnit =
437 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
438 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
439 secondsSinceProcessStartUp() >= 2)
440 PrintStats("pulse ");
441 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
442 TimeOfUnit >= Options.ReportSlowUnits) {
443 TimeOfLongestUnitInSeconds = TimeOfUnit;
444 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
445 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
446 }
447}
448
dor1sf8e5f862018-07-16 14:54:23 +0000449void Fuzzer::CheckForUnstableCounters(const uint8_t *Data, size_t Size) {
450 auto CBSetupAndRun = [&]() {
451 ScopedEnableMsanInterceptorChecks S;
452 UnitStartTime = system_clock::now();
453 TPC.ResetMaps();
454 RunningCB = true;
455 CB(Data, Size);
456 RunningCB = false;
457 UnitStopTime = system_clock::now();
458 };
459
460 // Copy original run counters into our unstable counters
461 TPC.InitializeUnstableCounters();
462
463 // First Rerun
464 CBSetupAndRun();
465 TPC.UpdateUnstableCounters();
466
467 // Second Rerun
468 CBSetupAndRun();
469 TPC.UpdateUnstableCounters();
470}
471
george.karpenkov29efa6d2017-08-21 23:25:50 +0000472bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000473 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000474 if (!Size)
475 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000476
477 ExecuteCallback(Data, Size);
478
479 UniqFeatureSetTmp.clear();
480 size_t FoundUniqFeaturesOfII = 0;
481 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
482 TPC.CollectFeatures([&](size_t Feature) {
483 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
484 UniqFeatureSetTmp.push_back(Feature);
485 if (Options.ReduceInputs && II)
486 if (std::binary_search(II->UniqFeatureSet.begin(),
487 II->UniqFeatureSet.end(), Feature))
488 FoundUniqFeaturesOfII++;
489 });
kccb6836be2017-12-01 19:18:38 +0000490 if (FoundUniqFeatures)
491 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000492 PrintPulseAndReportSlowInput(Data, Size);
493 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
dor1sf8e5f862018-07-16 14:54:23 +0000494
495 // If print_unstable_stats, execute the same input two more times to detect
496 // unstable edges.
497 if (NumNewFeatures && Options.PrintUnstableStats)
498 CheckForUnstableCounters(Data, Size);
499
george.karpenkov29efa6d2017-08-21 23:25:50 +0000500 if (NumNewFeatures) {
501 TPC.UpdateObservedPCs();
502 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
kcc3acbe072018-05-16 23:26:37 +0000503 TPC.ObservedFocusFunction(),
kccadf188b2018-06-07 01:40:20 +0000504 UniqFeatureSetTmp, DFT);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000505 return true;
506 }
507 if (II && FoundUniqFeaturesOfII &&
kccadf188b2018-06-07 01:40:20 +0000508 II->DataFlowTraceForFocusFunction.empty() &&
george.karpenkov29efa6d2017-08-21 23:25:50 +0000509 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
510 II->U.size() > Size) {
511 Corpus.Replace(II, {Data, Data + Size});
512 return true;
513 }
514 return false;
515}
516
517size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
518 assert(InFuzzingThread());
519 *Data = CurrentUnitData;
520 return CurrentUnitSize;
521}
522
523void Fuzzer::CrashOnOverwrittenData() {
524 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
525 GetPid());
526 DumpCurrentUnit("crash-");
527 Printf("SUMMARY: libFuzzer: out-of-memory\n");
528 _Exit(Options.ErrorExitCode); // Stop right now.
529}
530
531// Compare two arrays, but not all bytes if the arrays are large.
532static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
533 const size_t Limit = 64;
534 if (Size <= 64)
535 return !memcmp(A, B, Size);
536 // Compare first and last Limit/2 bytes.
537 return !memcmp(A, B, Limit / 2) &&
538 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
539}
540
541void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
542 TPC.RecordInitialStack();
543 TotalNumberOfRuns++;
544 assert(InFuzzingThread());
545 if (SMR.IsClient())
546 SMR.WriteByteArray(Data, Size);
547 // We copy the contents of Unit into a separate heap buffer
548 // so that we reliably find buffer overflows in it.
549 uint8_t *DataCopy = new uint8_t[Size];
550 memcpy(DataCopy, Data, Size);
morehouse1467b792018-07-09 23:51:08 +0000551 if (EF->__msan_unpoison)
552 EF->__msan_unpoison(DataCopy, Size);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000553 if (CurrentUnitData && CurrentUnitData != Data)
554 memcpy(CurrentUnitData, Data, Size);
555 CurrentUnitSize = Size;
morehouse1467b792018-07-09 23:51:08 +0000556 {
557 ScopedEnableMsanInterceptorChecks S;
558 AllocTracer.Start(Options.TraceMalloc);
559 UnitStartTime = system_clock::now();
560 TPC.ResetMaps();
561 RunningCB = true;
562 int Res = CB(DataCopy, Size);
563 RunningCB = false;
564 UnitStopTime = system_clock::now();
565 (void)Res;
566 assert(Res == 0);
567 HasMoreMallocsThanFrees = AllocTracer.Stop();
568 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000569 if (!LooseMemeq(DataCopy, Data, Size))
570 CrashOnOverwrittenData();
571 CurrentUnitSize = 0;
572 delete[] DataCopy;
573}
574
575void Fuzzer::WriteToOutputCorpus(const Unit &U) {
576 if (Options.OnlyASCII)
577 assert(IsASCII(U));
578 if (Options.OutputCorpus.empty())
579 return;
580 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
581 WriteToFile(U, Path);
582 if (Options.Verbosity >= 2)
583 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
584}
585
586void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
587 if (!Options.SaveArtifacts)
588 return;
589 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
590 if (!Options.ExactArtifactPath.empty())
591 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
592 WriteToFile(U, Path);
593 Printf("artifact_prefix='%s'; Test unit written to %s\n",
594 Options.ArtifactPrefix.c_str(), Path.c_str());
595 if (U.size() <= kMaxUnitSizeToPrint)
596 Printf("Base64: %s\n", Base64(U).c_str());
597}
598
599void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
600 if (!Options.PrintNEW)
601 return;
602 PrintStats(Text, "");
603 if (Options.Verbosity) {
604 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
605 MD.PrintMutationSequence();
606 Printf("\n");
607 }
608}
609
610void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
611 II->NumSuccessfullMutations++;
612 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000613 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000614 WriteToOutputCorpus(U);
615 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000616 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000617 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000618}
619
620// Tries detecting a memory leak on the particular input that we have just
621// executed before calling this function.
622void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
623 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000624 if (!HasMoreMallocsThanFrees)
625 return; // mallocs==frees, a leak is unlikely.
626 if (!Options.DetectLeaks)
627 return;
dor1s38279cb2017-09-12 02:01:54 +0000628 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000629 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
630 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000631 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
632 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000633 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000634 // Run the target once again, but with lsan disabled so that if there is
635 // a real leak we do not report it twice.
636 EF->__lsan_disable();
637 ExecuteCallback(Data, Size);
638 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000639 if (!HasMoreMallocsThanFrees)
640 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000641 if (NumberOfLeakDetectionAttempts++ > 1000) {
642 Options.DetectLeaks = false;
643 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
644 " Most likely the target function accumulates allocated\n"
645 " memory in a global state w/o actually leaking it.\n"
646 " You may try running this binary with -trace_malloc=[12]"
647 " to get a trace of mallocs and frees.\n"
648 " If LeakSanitizer is enabled in this process it will still\n"
649 " run on the process shutdown.\n");
650 return;
651 }
652 // Now perform the actual lsan pass. This is expensive and we must ensure
653 // we don't call it too often.
654 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
655 if (DuringInitialCorpusExecution)
656 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
657 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
658 CurrentUnitSize = Size;
659 DumpCurrentUnit("leak-");
660 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000661 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000662 }
663}
664
665void Fuzzer::MutateAndTestOne() {
666 MD.StartMutationSequence();
667
668 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
669 const auto &U = II.U;
670 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
671 assert(CurrentUnitData);
672 size_t Size = U.size();
673 assert(Size <= MaxInputLen && "Oversized Unit");
674 memcpy(CurrentUnitData, U.data(), Size);
675
676 assert(MaxMutationLen > 0);
677
678 size_t CurrentMaxMutationLen =
679 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
680 assert(CurrentMaxMutationLen > 0);
681
682 for (int i = 0; i < Options.MutateDepth; i++) {
683 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
684 break;
kcc1239a992017-11-09 20:30:19 +0000685 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000686 size_t NewSize = 0;
687 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
688 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000689 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000690 Size = NewSize;
691 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000692
kccb6836be2017-12-01 19:18:38 +0000693 bool FoundUniqFeatures = false;
694 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
695 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000696 TryDetectingAMemoryLeak(CurrentUnitData, Size,
697 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000698 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000699 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000700 break; // We will mutate this input more in the next rounds.
701 }
702 if (Options.ReduceDepth && !FoundUniqFeatures)
dor1sf8e5f862018-07-16 14:54:23 +0000703 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000704 }
705}
706
alekseyshld995b552017-10-23 22:04:30 +0000707void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000708 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000709 return;
alekseyshld995b552017-10-23 22:04:30 +0000710 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000711 LastAllocatorPurgeAttemptTime)
712 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000713 return;
alekseyshld995b552017-10-23 22:04:30 +0000714
715 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000716 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000717 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000718
719 LastAllocatorPurgeAttemptTime = system_clock::now();
720}
721
kcc2e93b3f2017-08-29 02:05:01 +0000722void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
723 const size_t kMaxSaneLen = 1 << 20;
724 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000725 Vector<SizedFile> SizedFiles;
726 size_t MaxSize = 0;
727 size_t MinSize = -1;
728 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000729 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000730 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000731 GetSizedFilesFromDir(Dir, &SizedFiles);
732 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
733 Dir.c_str());
734 LastNumFiles = SizedFiles.size();
735 }
736 for (auto &File : SizedFiles) {
737 MaxSize = Max(File.Size, MaxSize);
738 MinSize = Min(File.Size, MinSize);
739 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000740 }
kccdc00cd32017-08-29 20:51:24 +0000741 if (Options.MaxLen == 0)
742 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
743 assert(MaxInputLen > 0);
744
kcc2cd9f092017-10-13 01:12:23 +0000745 // Test the callback with empty input and never try it again.
746 uint8_t dummy = 0;
747 ExecuteCallback(&dummy, 0);
748
kccdc00cd32017-08-29 20:51:24 +0000749 if (SizedFiles.empty()) {
750 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
751 Unit U({'\n'}); // Valid ASCII input.
752 RunOne(U.data(), U.size());
753 } else {
754 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
755 " rss: %zdMb\n",
756 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
757 if (Options.ShuffleAtStartUp)
758 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
759
kcc7f5f2222017-09-12 21:58:07 +0000760 if (Options.PreferSmall) {
761 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
762 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
763 }
kccdc00cd32017-08-29 20:51:24 +0000764
765 // Load and execute inputs one by one.
766 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000767 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000768 assert(U.size() <= MaxInputLen);
769 RunOne(U.data(), U.size());
770 CheckExitOnSrcPosOrItem();
771 TryDetectingAMemoryLeak(U.data(), U.size(),
772 /*DuringInitialCorpusExecution*/ true);
773 }
kcc2e93b3f2017-08-29 02:05:01 +0000774 }
775
kccdc00cd32017-08-29 20:51:24 +0000776 PrintStats("INITED");
kcc3acbe072018-05-16 23:26:37 +0000777 if (!Options.FocusFunction.empty())
778 Printf("INFO: %zd/%zd inputs touch the focus function\n",
779 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
kccadf188b2018-06-07 01:40:20 +0000780 if (!Options.DataFlowTrace.empty())
781 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
782 Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
kcc3acbe072018-05-16 23:26:37 +0000783
dor1s770a9bc2018-05-23 19:42:30 +0000784 if (Corpus.empty() && Options.MaxNumberOfRuns) {
kccdc00cd32017-08-29 20:51:24 +0000785 Printf("ERROR: no interesting inputs were found. "
786 "Is the code instrumented for coverage? Exiting.\n");
787 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000788 }
kcc2e93b3f2017-08-29 02:05:01 +0000789}
790
791void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
792 ReadAndExecuteSeedCorpora(CorpusDirs);
kccadf188b2018-06-07 01:40:20 +0000793 DFT.Clear(); // No need for DFT any more.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000794 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000795 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000796 system_clock::time_point LastCorpusReload = system_clock::now();
797 if (Options.DoCrossOver)
798 MD.SetCorpus(&Corpus);
799 while (true) {
800 auto Now = system_clock::now();
801 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
802 Options.ReloadIntervalSec) {
803 RereadOutputCorpus(MaxInputLen);
804 LastCorpusReload = system_clock::now();
805 }
806 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
807 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000808 if (TimedOut())
809 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000810
811 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000812 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000813 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000814 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000815 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000816 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000817 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000818 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000819 }
820 } else {
821 TmpMaxMutationLen = MaxMutationLen;
822 }
823
824 // Perform several mutations and runs.
825 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000826
827 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000828 }
829
830 PrintStats("DONE ", "\n");
831 MD.PrintRecommendedDictionary();
832}
833
834void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000835 if (U.size() <= 1)
836 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000837 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
838 MD.StartMutationSequence();
839 memcpy(CurrentUnitData, U.data(), U.size());
840 for (int i = 0; i < Options.MutateDepth; i++) {
841 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
842 assert(NewSize > 0 && NewSize <= MaxMutationLen);
843 ExecuteCallback(CurrentUnitData, NewSize);
844 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
845 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
846 /*DuringInitialCorpusExecution*/ false);
847 }
848 }
849}
850
851void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
852 if (SMR.IsServer()) {
853 SMR.WriteByteArray(Data, Size);
854 } else if (SMR.IsClient()) {
855 SMR.PostClient();
856 SMR.WaitServer();
857 size_t OtherSize = SMR.ReadByteArraySize();
858 uint8_t *OtherData = SMR.GetByteArray();
859 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
860 size_t i = 0;
861 for (i = 0; i < Min(Size, OtherSize); i++)
862 if (Data[i] != OtherData[i])
863 break;
864 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000865 "offset %zd\n",
866 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000867 DumpCurrentUnit("mismatch-");
868 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
869 PrintFinalStats();
870 _Exit(Options.ErrorExitCode);
871 }
872 }
873}
874
875} // namespace fuzzer
876
877extern "C" {
878
phosek966475e2018-01-17 20:39:14 +0000879__attribute__((visibility("default"))) size_t
880LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000881 assert(fuzzer::F);
882 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
883}
884
885// Experimental
phosek966475e2018-01-17 20:39:14 +0000886__attribute__((visibility("default"))) void
887LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000888 assert(fuzzer::F);
889 fuzzer::F->AnnounceOutput(Data, Size);
890}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000891} // extern "C"