blob: 7a26370b3d462e7734f2493e3bb68d15163fc360 [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)
108 EF->__sanitizer_print_stack_trace();
109 }
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)
121 EF->__sanitizer_print_stack_trace();
122 }
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");
132 if (EF->__sanitizer_print_stack_trace)
133 EF->__sanitizer_print_stack_trace();
134 DumpCurrentUnit("oom-");
135 Printf("SUMMARY: libFuzzer: out-of-memory\n");
136 PrintFinalStats();
137 _Exit(Options.ErrorExitCode); // Stop right now.
138}
139
140Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
141 FuzzingOptions Options)
142 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
143 if (EF->__sanitizer_set_death_callback)
144 EF->__sanitizer_set_death_callback(StaticDeathCallback);
145 assert(!F);
146 F = this;
147 TPC.ResetMaps();
148 IsMyThread = true;
149 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
150 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
151 TPC.SetUseCounters(Options.UseCounters);
152 TPC.SetUseValueProfile(Options.UseValueProfile);
dor1s06fb50c2017-10-05 22:41:03 +0000153 TPC.SetUseClangCoverage(Options.UseClangCoverage);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000154
155 if (Options.Verbosity)
156 TPC.PrintModuleInfo();
157 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
158 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
159 MaxInputLen = MaxMutationLen = Options.MaxLen;
160 TmpMaxMutationLen = Max(size_t(4), Corpus.MaxInputSize());
161 AllocateCurrentUnitData();
162 CurrentUnitSize = 0;
163 memset(BaseSha1, 0, sizeof(BaseSha1));
164}
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.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000182 MD.PrintMutationSequence();
183 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
184 size_t UnitSize = CurrentUnitSize;
185 if (UnitSize <= kMaxUnitSizeToPrint) {
186 PrintHexArray(CurrentUnitData, UnitSize, "\n");
187 PrintASCII(CurrentUnitData, UnitSize, "\n");
188 }
189 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
190 Prefix);
191}
192
193NO_SANITIZE_MEMORY
194void Fuzzer::DeathCallback() {
195 DumpCurrentUnit("crash-");
196 PrintFinalStats();
197}
198
199void Fuzzer::StaticAlarmCallback() {
200 assert(F);
201 F->AlarmCallback();
202}
203
204void Fuzzer::StaticCrashSignalCallback() {
205 assert(F);
206 F->CrashCallback();
207}
208
209void Fuzzer::StaticExitCallback() {
210 assert(F);
211 F->ExitCallback();
212}
213
214void Fuzzer::StaticInterruptCallback() {
215 assert(F);
216 F->InterruptCallback();
217}
218
kcc1239a992017-11-09 20:30:19 +0000219void Fuzzer::StaticGracefulExitCallback() {
220 assert(F);
221 F->GracefulExitRequested = true;
222 Printf("INFO: signal received, trying to exit gracefully\n");
223}
224
george.karpenkov29efa6d2017-08-21 23:25:50 +0000225void Fuzzer::StaticFileSizeExceedCallback() {
226 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
227 exit(1);
228}
229
230void Fuzzer::CrashCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000231 if (EF->__sanitizer_acquire_crash_state &&
232 !EF->__sanitizer_acquire_crash_state())
233 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000234 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
235 if (EF->__sanitizer_print_stack_trace)
236 EF->__sanitizer_print_stack_trace();
237 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
238 " Combine libFuzzer with AddressSanitizer or similar for better "
239 "crash reports.\n");
240 Printf("SUMMARY: libFuzzer: deadly signal\n");
241 DumpCurrentUnit("crash-");
242 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000243 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000244}
245
246void Fuzzer::ExitCallback() {
247 if (!RunningCB)
248 return; // This exit did not come from the user callback
morehouse5a4566a2018-05-01 21:01:53 +0000249 if (EF->__sanitizer_acquire_crash_state &&
250 !EF->__sanitizer_acquire_crash_state())
251 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000252 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
253 if (EF->__sanitizer_print_stack_trace)
254 EF->__sanitizer_print_stack_trace();
255 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
256 DumpCurrentUnit("crash-");
257 PrintFinalStats();
258 _Exit(Options.ErrorExitCode);
259}
260
kcc1239a992017-11-09 20:30:19 +0000261void Fuzzer::MaybeExitGracefully() {
262 if (!GracefulExitRequested) return;
263 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
264 PrintFinalStats();
265 _Exit(0);
266}
267
george.karpenkov29efa6d2017-08-21 23:25:50 +0000268void Fuzzer::InterruptCallback() {
269 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
270 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000271 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000272}
273
274NO_SANITIZE_MEMORY
275void Fuzzer::AlarmCallback() {
276 assert(Options.UnitTimeoutSec > 0);
277 // In Windows Alarm callback is executed by a different thread.
278#if !LIBFUZZER_WINDOWS
alekseyshl9f6a9f22017-10-23 23:24:33 +0000279 if (!InFuzzingThread())
280 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000281#endif
282 if (!RunningCB)
283 return; // We have not started running units yet.
284 size_t Seconds =
285 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
286 if (Seconds == 0)
287 return;
288 if (Options.Verbosity >= 2)
289 Printf("AlarmCallback %zd\n", Seconds);
290 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000291 if (EF->__sanitizer_acquire_crash_state &&
292 !EF->__sanitizer_acquire_crash_state())
293 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000294 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
295 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
296 Options.UnitTimeoutSec);
297 DumpCurrentUnit("timeout-");
298 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
299 Seconds);
300 if (EF->__sanitizer_print_stack_trace)
301 EF->__sanitizer_print_stack_trace();
302 Printf("SUMMARY: libFuzzer: timeout\n");
303 PrintFinalStats();
304 _Exit(Options.TimeoutExitCode); // Stop right now.
305 }
306}
307
308void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000309 if (EF->__sanitizer_acquire_crash_state &&
310 !EF->__sanitizer_acquire_crash_state())
311 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000312 Printf(
313 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
314 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
315 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
316 if (EF->__sanitizer_print_memory_profile)
317 EF->__sanitizer_print_memory_profile(95, 8);
318 DumpCurrentUnit("oom-");
319 Printf("SUMMARY: libFuzzer: out-of-memory\n");
320 PrintFinalStats();
321 _Exit(Options.ErrorExitCode); // Stop right now.
322}
323
324void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
325 size_t ExecPerSec = execPerSec();
326 if (!Options.Verbosity)
327 return;
328 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
329 if (size_t N = TPC.GetTotalPCCoverage())
330 Printf(" cov: %zd", N);
331 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000332 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000333 if (!Corpus.empty()) {
334 Printf(" corp: %zd", Corpus.NumActiveUnits());
335 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000336 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000337 Printf("/%zdb", N);
338 else if (N < (1 << 24))
339 Printf("/%zdKb", N >> 10);
340 else
341 Printf("/%zdMb", N >> 20);
342 }
343 }
morehousea6c692c2018-02-22 19:00:17 +0000344 if (TmpMaxMutationLen)
345 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000346 if (Units)
347 Printf(" units: %zd", Units);
348
349 Printf(" exec/s: %zd", ExecPerSec);
350 Printf(" rss: %zdMb", GetPeakRSSMb());
351 Printf("%s", End);
352}
353
354void Fuzzer::PrintFinalStats() {
355 if (Options.PrintCoverage)
356 TPC.PrintCoverage();
357 if (Options.DumpCoverage)
358 TPC.DumpCoverage();
359 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
449bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000450 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000451 if (!Size)
452 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000453
454 ExecuteCallback(Data, Size);
455
456 UniqFeatureSetTmp.clear();
457 size_t FoundUniqFeaturesOfII = 0;
458 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
459 TPC.CollectFeatures([&](size_t Feature) {
kcc1f5638d2017-12-08 22:21:42 +0000460 if (Options.UseFeatureFrequency)
461 Corpus.UpdateFeatureFrequency(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000462 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
463 UniqFeatureSetTmp.push_back(Feature);
464 if (Options.ReduceInputs && II)
465 if (std::binary_search(II->UniqFeatureSet.begin(),
466 II->UniqFeatureSet.end(), Feature))
467 FoundUniqFeaturesOfII++;
468 });
kccb6836be2017-12-01 19:18:38 +0000469 if (FoundUniqFeatures)
470 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000471 PrintPulseAndReportSlowInput(Data, Size);
472 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
473 if (NumNewFeatures) {
474 TPC.UpdateObservedPCs();
475 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
476 UniqFeatureSetTmp);
477 return true;
478 }
479 if (II && FoundUniqFeaturesOfII &&
480 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
481 II->U.size() > Size) {
482 Corpus.Replace(II, {Data, Data + Size});
483 return true;
484 }
485 return false;
486}
487
488size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
489 assert(InFuzzingThread());
490 *Data = CurrentUnitData;
491 return CurrentUnitSize;
492}
493
494void Fuzzer::CrashOnOverwrittenData() {
495 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
496 GetPid());
497 DumpCurrentUnit("crash-");
498 Printf("SUMMARY: libFuzzer: out-of-memory\n");
499 _Exit(Options.ErrorExitCode); // Stop right now.
500}
501
502// Compare two arrays, but not all bytes if the arrays are large.
503static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
504 const size_t Limit = 64;
505 if (Size <= 64)
506 return !memcmp(A, B, Size);
507 // Compare first and last Limit/2 bytes.
508 return !memcmp(A, B, Limit / 2) &&
509 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
510}
511
512void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
513 TPC.RecordInitialStack();
514 TotalNumberOfRuns++;
515 assert(InFuzzingThread());
516 if (SMR.IsClient())
517 SMR.WriteByteArray(Data, Size);
518 // We copy the contents of Unit into a separate heap buffer
519 // so that we reliably find buffer overflows in it.
520 uint8_t *DataCopy = new uint8_t[Size];
521 memcpy(DataCopy, Data, Size);
522 if (CurrentUnitData && CurrentUnitData != Data)
523 memcpy(CurrentUnitData, Data, Size);
524 CurrentUnitSize = Size;
525 AllocTracer.Start(Options.TraceMalloc);
526 UnitStartTime = system_clock::now();
527 TPC.ResetMaps();
528 RunningCB = true;
529 int Res = CB(DataCopy, Size);
530 RunningCB = false;
531 UnitStopTime = system_clock::now();
532 (void)Res;
533 assert(Res == 0);
534 HasMoreMallocsThanFrees = AllocTracer.Stop();
535 if (!LooseMemeq(DataCopy, Data, Size))
536 CrashOnOverwrittenData();
537 CurrentUnitSize = 0;
538 delete[] DataCopy;
539}
540
541void Fuzzer::WriteToOutputCorpus(const Unit &U) {
542 if (Options.OnlyASCII)
543 assert(IsASCII(U));
544 if (Options.OutputCorpus.empty())
545 return;
546 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
547 WriteToFile(U, Path);
548 if (Options.Verbosity >= 2)
549 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
550}
551
552void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
553 if (!Options.SaveArtifacts)
554 return;
555 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
556 if (!Options.ExactArtifactPath.empty())
557 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
558 WriteToFile(U, Path);
559 Printf("artifact_prefix='%s'; Test unit written to %s\n",
560 Options.ArtifactPrefix.c_str(), Path.c_str());
561 if (U.size() <= kMaxUnitSizeToPrint)
562 Printf("Base64: %s\n", Base64(U).c_str());
563}
564
565void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
566 if (!Options.PrintNEW)
567 return;
568 PrintStats(Text, "");
569 if (Options.Verbosity) {
570 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
571 MD.PrintMutationSequence();
572 Printf("\n");
573 }
574}
575
576void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
577 II->NumSuccessfullMutations++;
578 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000579 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000580 WriteToOutputCorpus(U);
581 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000582 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000583 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000584}
585
586// Tries detecting a memory leak on the particular input that we have just
587// executed before calling this function.
588void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
589 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000590 if (!HasMoreMallocsThanFrees)
591 return; // mallocs==frees, a leak is unlikely.
592 if (!Options.DetectLeaks)
593 return;
dor1s38279cb2017-09-12 02:01:54 +0000594 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000595 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
596 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000597 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
598 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000599 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000600 // Run the target once again, but with lsan disabled so that if there is
601 // a real leak we do not report it twice.
602 EF->__lsan_disable();
603 ExecuteCallback(Data, Size);
604 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000605 if (!HasMoreMallocsThanFrees)
606 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000607 if (NumberOfLeakDetectionAttempts++ > 1000) {
608 Options.DetectLeaks = false;
609 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
610 " Most likely the target function accumulates allocated\n"
611 " memory in a global state w/o actually leaking it.\n"
612 " You may try running this binary with -trace_malloc=[12]"
613 " to get a trace of mallocs and frees.\n"
614 " If LeakSanitizer is enabled in this process it will still\n"
615 " run on the process shutdown.\n");
616 return;
617 }
618 // Now perform the actual lsan pass. This is expensive and we must ensure
619 // we don't call it too often.
620 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
621 if (DuringInitialCorpusExecution)
622 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
623 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
624 CurrentUnitSize = Size;
625 DumpCurrentUnit("leak-");
626 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000627 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000628 }
629}
630
631void Fuzzer::MutateAndTestOne() {
632 MD.StartMutationSequence();
633
634 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
kcc20fc0672017-10-11 01:44:26 +0000635 if (Options.UseFeatureFrequency)
636 Corpus.UpdateFeatureFrequencyScore(&II);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000637 const auto &U = II.U;
638 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
639 assert(CurrentUnitData);
640 size_t Size = U.size();
641 assert(Size <= MaxInputLen && "Oversized Unit");
642 memcpy(CurrentUnitData, U.data(), Size);
643
644 assert(MaxMutationLen > 0);
645
646 size_t CurrentMaxMutationLen =
647 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
648 assert(CurrentMaxMutationLen > 0);
649
650 for (int i = 0; i < Options.MutateDepth; i++) {
651 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
652 break;
kcc1239a992017-11-09 20:30:19 +0000653 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000654 size_t NewSize = 0;
655 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
656 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000657 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000658 Size = NewSize;
659 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000660
kccb6836be2017-12-01 19:18:38 +0000661 bool FoundUniqFeatures = false;
662 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
663 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000664 TryDetectingAMemoryLeak(CurrentUnitData, Size,
665 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000666 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000667 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000668 break; // We will mutate this input more in the next rounds.
669 }
670 if (Options.ReduceDepth && !FoundUniqFeatures)
671 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000672 }
673}
674
alekseyshld995b552017-10-23 22:04:30 +0000675void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000676 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000677 return;
alekseyshld995b552017-10-23 22:04:30 +0000678 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000679 LastAllocatorPurgeAttemptTime)
680 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000681 return;
alekseyshld995b552017-10-23 22:04:30 +0000682
683 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000684 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000685 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000686
687 LastAllocatorPurgeAttemptTime = system_clock::now();
688}
689
kcc2e93b3f2017-08-29 02:05:01 +0000690void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
691 const size_t kMaxSaneLen = 1 << 20;
692 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000693 Vector<SizedFile> SizedFiles;
694 size_t MaxSize = 0;
695 size_t MinSize = -1;
696 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000697 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000698 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000699 GetSizedFilesFromDir(Dir, &SizedFiles);
700 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
701 Dir.c_str());
702 LastNumFiles = SizedFiles.size();
703 }
704 for (auto &File : SizedFiles) {
705 MaxSize = Max(File.Size, MaxSize);
706 MinSize = Min(File.Size, MinSize);
707 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000708 }
kccdc00cd32017-08-29 20:51:24 +0000709 if (Options.MaxLen == 0)
710 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
711 assert(MaxInputLen > 0);
712
kcc2cd9f092017-10-13 01:12:23 +0000713 // Test the callback with empty input and never try it again.
714 uint8_t dummy = 0;
715 ExecuteCallback(&dummy, 0);
716
kccdc00cd32017-08-29 20:51:24 +0000717 if (SizedFiles.empty()) {
718 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
719 Unit U({'\n'}); // Valid ASCII input.
720 RunOne(U.data(), U.size());
721 } else {
722 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
723 " rss: %zdMb\n",
724 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
725 if (Options.ShuffleAtStartUp)
726 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
727
kcc7f5f2222017-09-12 21:58:07 +0000728 if (Options.PreferSmall) {
729 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
730 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
731 }
kccdc00cd32017-08-29 20:51:24 +0000732
733 // Load and execute inputs one by one.
734 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000735 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000736 assert(U.size() <= MaxInputLen);
737 RunOne(U.data(), U.size());
738 CheckExitOnSrcPosOrItem();
739 TryDetectingAMemoryLeak(U.data(), U.size(),
740 /*DuringInitialCorpusExecution*/ true);
741 }
kcc2e93b3f2017-08-29 02:05:01 +0000742 }
743
kccdc00cd32017-08-29 20:51:24 +0000744 PrintStats("INITED");
745 if (Corpus.empty()) {
746 Printf("ERROR: no interesting inputs were found. "
747 "Is the code instrumented for coverage? Exiting.\n");
748 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000749 }
kcc2e93b3f2017-08-29 02:05:01 +0000750}
751
752void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
753 ReadAndExecuteSeedCorpora(CorpusDirs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000754 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000755 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000756 system_clock::time_point LastCorpusReload = system_clock::now();
757 if (Options.DoCrossOver)
758 MD.SetCorpus(&Corpus);
759 while (true) {
760 auto Now = system_clock::now();
761 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
762 Options.ReloadIntervalSec) {
763 RereadOutputCorpus(MaxInputLen);
764 LastCorpusReload = system_clock::now();
765 }
766 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
767 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000768 if (TimedOut())
769 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000770
771 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000772 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000773 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000774 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000775 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000776 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000777 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000778 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000779 }
780 } else {
781 TmpMaxMutationLen = MaxMutationLen;
782 }
783
784 // Perform several mutations and runs.
785 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000786
787 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000788 }
789
790 PrintStats("DONE ", "\n");
791 MD.PrintRecommendedDictionary();
792}
793
794void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000795 if (U.size() <= 1)
796 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000797 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
798 MD.StartMutationSequence();
799 memcpy(CurrentUnitData, U.data(), U.size());
800 for (int i = 0; i < Options.MutateDepth; i++) {
801 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
802 assert(NewSize > 0 && NewSize <= MaxMutationLen);
803 ExecuteCallback(CurrentUnitData, NewSize);
804 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
805 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
806 /*DuringInitialCorpusExecution*/ false);
807 }
808 }
809}
810
811void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
812 if (SMR.IsServer()) {
813 SMR.WriteByteArray(Data, Size);
814 } else if (SMR.IsClient()) {
815 SMR.PostClient();
816 SMR.WaitServer();
817 size_t OtherSize = SMR.ReadByteArraySize();
818 uint8_t *OtherData = SMR.GetByteArray();
819 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
820 size_t i = 0;
821 for (i = 0; i < Min(Size, OtherSize); i++)
822 if (Data[i] != OtherData[i])
823 break;
824 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000825 "offset %zd\n",
826 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000827 DumpCurrentUnit("mismatch-");
828 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
829 PrintFinalStats();
830 _Exit(Options.ErrorExitCode);
831 }
832 }
833}
834
835} // namespace fuzzer
836
837extern "C" {
838
phosek966475e2018-01-17 20:39:14 +0000839__attribute__((visibility("default"))) size_t
840LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000841 assert(fuzzer::F);
842 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
843}
844
845// Experimental
phosek966475e2018-01-17 20:39:14 +0000846__attribute__((visibility("default"))) void
847LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000848 assert(fuzzer::F);
849 fuzzer::F->AnnounceOutput(Data, Size);
850}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000851} // extern "C"