blob: f4771e1df293190957dd4664a5ecd47ff8554fa5 [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) {
127 if (!Options.RssLimitMb || (Size >> 20) < (size_t)Options.RssLimitMb)
128 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
219void Fuzzer::StaticFileSizeExceedCallback() {
220 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
221 exit(1);
222}
223
224void Fuzzer::CrashCallback() {
225 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
226 if (EF->__sanitizer_print_stack_trace)
227 EF->__sanitizer_print_stack_trace();
228 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
229 " Combine libFuzzer with AddressSanitizer or similar for better "
230 "crash reports.\n");
231 Printf("SUMMARY: libFuzzer: deadly signal\n");
232 DumpCurrentUnit("crash-");
233 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000234 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000235}
236
237void Fuzzer::ExitCallback() {
238 if (!RunningCB)
239 return; // This exit did not come from the user callback
240 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
241 if (EF->__sanitizer_print_stack_trace)
242 EF->__sanitizer_print_stack_trace();
243 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
244 DumpCurrentUnit("crash-");
245 PrintFinalStats();
246 _Exit(Options.ErrorExitCode);
247}
248
george.karpenkov29efa6d2017-08-21 23:25:50 +0000249void Fuzzer::InterruptCallback() {
250 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
251 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000252 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000253}
254
255NO_SANITIZE_MEMORY
256void Fuzzer::AlarmCallback() {
257 assert(Options.UnitTimeoutSec > 0);
258 // In Windows Alarm callback is executed by a different thread.
259#if !LIBFUZZER_WINDOWS
alekseyshl9f6a9f22017-10-23 23:24:33 +0000260 if (!InFuzzingThread())
261 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000262#endif
263 if (!RunningCB)
264 return; // We have not started running units yet.
265 size_t Seconds =
266 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
267 if (Seconds == 0)
268 return;
269 if (Options.Verbosity >= 2)
270 Printf("AlarmCallback %zd\n", Seconds);
271 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
272 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
273 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
274 Options.UnitTimeoutSec);
275 DumpCurrentUnit("timeout-");
276 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
277 Seconds);
278 if (EF->__sanitizer_print_stack_trace)
279 EF->__sanitizer_print_stack_trace();
280 Printf("SUMMARY: libFuzzer: timeout\n");
281 PrintFinalStats();
282 _Exit(Options.TimeoutExitCode); // Stop right now.
283 }
284}
285
286void Fuzzer::RssLimitCallback() {
287 Printf(
288 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
289 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
290 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
291 if (EF->__sanitizer_print_memory_profile)
292 EF->__sanitizer_print_memory_profile(95, 8);
293 DumpCurrentUnit("oom-");
294 Printf("SUMMARY: libFuzzer: out-of-memory\n");
295 PrintFinalStats();
296 _Exit(Options.ErrorExitCode); // Stop right now.
297}
298
299void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
300 size_t ExecPerSec = execPerSec();
301 if (!Options.Verbosity)
302 return;
303 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
304 if (size_t N = TPC.GetTotalPCCoverage())
305 Printf(" cov: %zd", N);
306 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000307 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000308 if (!Corpus.empty()) {
309 Printf(" corp: %zd", Corpus.NumActiveUnits());
310 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000311 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000312 Printf("/%zdb", N);
313 else if (N < (1 << 24))
314 Printf("/%zdKb", N >> 10);
315 else
316 Printf("/%zdMb", N >> 20);
317 }
318 }
319 if (Units)
320 Printf(" units: %zd", Units);
321
322 Printf(" exec/s: %zd", ExecPerSec);
323 Printf(" rss: %zdMb", GetPeakRSSMb());
324 Printf("%s", End);
325}
326
327void Fuzzer::PrintFinalStats() {
328 if (Options.PrintCoverage)
329 TPC.PrintCoverage();
330 if (Options.DumpCoverage)
331 TPC.DumpCoverage();
332 if (Options.PrintCorpusStats)
333 Corpus.PrintStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000334 if (!Options.PrintFinalStats)
335 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000336 size_t ExecPerSec = execPerSec();
337 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
338 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
339 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
340 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
341 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
342}
343
344void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
345 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
346 assert(MaxInputLen);
347 this->MaxInputLen = MaxInputLen;
348 this->MaxMutationLen = MaxInputLen;
349 AllocateCurrentUnitData();
350 Printf("INFO: -max_len is not provided; "
351 "libFuzzer will not generate inputs larger than %zd bytes\n",
352 MaxInputLen);
353}
354
355void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
356 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
357 this->MaxMutationLen = MaxMutationLen;
358}
359
360void Fuzzer::CheckExitOnSrcPosOrItem() {
361 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000362 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000363 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000364 if (!PCsSet->insert(PC).second)
365 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000366 std::string Descr = DescribePC("%F %L", PC + 1);
367 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
368 Printf("INFO: found line matching '%s', exiting.\n",
369 Options.ExitOnSrcPos.c_str());
370 _Exit(0);
371 }
372 };
373 TPC.ForEachObservedPC(HandlePC);
374 }
375 if (!Options.ExitOnItem.empty()) {
376 if (Corpus.HasUnit(Options.ExitOnItem)) {
377 Printf("INFO: found item with checksum '%s', exiting.\n",
378 Options.ExitOnItem.c_str());
379 _Exit(0);
380 }
381 }
382}
383
384void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000385 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
386 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000387 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000388 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
389 &EpochOfLastReadOfOutputCorpus, MaxSize,
390 /*ExitOnError*/ false);
391 if (Options.Verbosity >= 2)
392 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
393 bool Reloaded = false;
394 for (auto &U : AdditionalCorpus) {
395 if (U.size() > MaxSize)
396 U.resize(MaxSize);
397 if (!Corpus.HasUnit(U)) {
398 if (RunOne(U.data(), U.size())) {
399 CheckExitOnSrcPosOrItem();
400 Reloaded = true;
401 }
402 }
403 }
404 if (Reloaded)
405 PrintStats("RELOAD");
406}
407
george.karpenkov29efa6d2017-08-21 23:25:50 +0000408void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
409 auto TimeOfUnit =
410 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
411 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
412 secondsSinceProcessStartUp() >= 2)
413 PrintStats("pulse ");
414 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
415 TimeOfUnit >= Options.ReportSlowUnits) {
416 TimeOfLongestUnitInSeconds = TimeOfUnit;
417 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
418 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
419 }
420}
421
422bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
423 InputInfo *II) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000424 if (!Size)
425 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000426
427 ExecuteCallback(Data, Size);
428
429 UniqFeatureSetTmp.clear();
430 size_t FoundUniqFeaturesOfII = 0;
431 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
432 TPC.CollectFeatures([&](size_t Feature) {
kcc20fc0672017-10-11 01:44:26 +0000433 Corpus.UpdateFeatureFrequency(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000434 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
435 UniqFeatureSetTmp.push_back(Feature);
436 if (Options.ReduceInputs && II)
437 if (std::binary_search(II->UniqFeatureSet.begin(),
438 II->UniqFeatureSet.end(), Feature))
439 FoundUniqFeaturesOfII++;
440 });
441 PrintPulseAndReportSlowInput(Data, Size);
442 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
443 if (NumNewFeatures) {
444 TPC.UpdateObservedPCs();
445 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
446 UniqFeatureSetTmp);
447 return true;
448 }
449 if (II && FoundUniqFeaturesOfII &&
450 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
451 II->U.size() > Size) {
452 Corpus.Replace(II, {Data, Data + Size});
453 return true;
454 }
455 return false;
456}
457
458size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
459 assert(InFuzzingThread());
460 *Data = CurrentUnitData;
461 return CurrentUnitSize;
462}
463
464void Fuzzer::CrashOnOverwrittenData() {
465 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
466 GetPid());
467 DumpCurrentUnit("crash-");
468 Printf("SUMMARY: libFuzzer: out-of-memory\n");
469 _Exit(Options.ErrorExitCode); // Stop right now.
470}
471
472// Compare two arrays, but not all bytes if the arrays are large.
473static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
474 const size_t Limit = 64;
475 if (Size <= 64)
476 return !memcmp(A, B, Size);
477 // Compare first and last Limit/2 bytes.
478 return !memcmp(A, B, Limit / 2) &&
479 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
480}
481
482void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
483 TPC.RecordInitialStack();
484 TotalNumberOfRuns++;
485 assert(InFuzzingThread());
486 if (SMR.IsClient())
487 SMR.WriteByteArray(Data, Size);
488 // We copy the contents of Unit into a separate heap buffer
489 // so that we reliably find buffer overflows in it.
490 uint8_t *DataCopy = new uint8_t[Size];
491 memcpy(DataCopy, Data, Size);
492 if (CurrentUnitData && CurrentUnitData != Data)
493 memcpy(CurrentUnitData, Data, Size);
494 CurrentUnitSize = Size;
495 AllocTracer.Start(Options.TraceMalloc);
496 UnitStartTime = system_clock::now();
497 TPC.ResetMaps();
498 RunningCB = true;
499 int Res = CB(DataCopy, Size);
500 RunningCB = false;
501 UnitStopTime = system_clock::now();
502 (void)Res;
503 assert(Res == 0);
504 HasMoreMallocsThanFrees = AllocTracer.Stop();
505 if (!LooseMemeq(DataCopy, Data, Size))
506 CrashOnOverwrittenData();
507 CurrentUnitSize = 0;
508 delete[] DataCopy;
509}
510
511void Fuzzer::WriteToOutputCorpus(const Unit &U) {
512 if (Options.OnlyASCII)
513 assert(IsASCII(U));
514 if (Options.OutputCorpus.empty())
515 return;
516 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
517 WriteToFile(U, Path);
518 if (Options.Verbosity >= 2)
519 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
520}
521
522void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
523 if (!Options.SaveArtifacts)
524 return;
525 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
526 if (!Options.ExactArtifactPath.empty())
527 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
528 WriteToFile(U, Path);
529 Printf("artifact_prefix='%s'; Test unit written to %s\n",
530 Options.ArtifactPrefix.c_str(), Path.c_str());
531 if (U.size() <= kMaxUnitSizeToPrint)
532 Printf("Base64: %s\n", Base64(U).c_str());
533}
534
535void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
536 if (!Options.PrintNEW)
537 return;
538 PrintStats(Text, "");
539 if (Options.Verbosity) {
540 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
541 MD.PrintMutationSequence();
542 Printf("\n");
543 }
544}
545
546void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
547 II->NumSuccessfullMutations++;
548 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000549 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000550 WriteToOutputCorpus(U);
551 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000552 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000553 LastCorpusUpdateRun = TotalNumberOfRuns;
554 LastCorpusUpdateTime = system_clock::now();
555}
556
557// Tries detecting a memory leak on the particular input that we have just
558// executed before calling this function.
559void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
560 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000561 if (!HasMoreMallocsThanFrees)
562 return; // mallocs==frees, a leak is unlikely.
563 if (!Options.DetectLeaks)
564 return;
dor1s38279cb2017-09-12 02:01:54 +0000565 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000566 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
567 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000568 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
569 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000570 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000571 // Run the target once again, but with lsan disabled so that if there is
572 // a real leak we do not report it twice.
573 EF->__lsan_disable();
574 ExecuteCallback(Data, Size);
575 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000576 if (!HasMoreMallocsThanFrees)
577 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000578 if (NumberOfLeakDetectionAttempts++ > 1000) {
579 Options.DetectLeaks = false;
580 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
581 " Most likely the target function accumulates allocated\n"
582 " memory in a global state w/o actually leaking it.\n"
583 " You may try running this binary with -trace_malloc=[12]"
584 " to get a trace of mallocs and frees.\n"
585 " If LeakSanitizer is enabled in this process it will still\n"
586 " run on the process shutdown.\n");
587 return;
588 }
589 // Now perform the actual lsan pass. This is expensive and we must ensure
590 // we don't call it too often.
591 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
592 if (DuringInitialCorpusExecution)
593 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
594 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
595 CurrentUnitSize = Size;
596 DumpCurrentUnit("leak-");
597 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000598 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000599 }
600}
601
602void Fuzzer::MutateAndTestOne() {
603 MD.StartMutationSequence();
604
605 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
kcc20fc0672017-10-11 01:44:26 +0000606 if (Options.UseFeatureFrequency)
607 Corpus.UpdateFeatureFrequencyScore(&II);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000608 const auto &U = II.U;
609 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
610 assert(CurrentUnitData);
611 size_t Size = U.size();
612 assert(Size <= MaxInputLen && "Oversized Unit");
613 memcpy(CurrentUnitData, U.data(), Size);
614
615 assert(MaxMutationLen > 0);
616
617 size_t CurrentMaxMutationLen =
618 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
619 assert(CurrentMaxMutationLen > 0);
620
621 for (int i = 0; i < Options.MutateDepth; i++) {
622 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
623 break;
624 size_t NewSize = 0;
625 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
626 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000627 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000628 Size = NewSize;
629 II.NumExecutedMutations++;
630 if (RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II))
631 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
632
633 TryDetectingAMemoryLeak(CurrentUnitData, Size,
634 /*DuringInitialCorpusExecution*/ false);
635 }
636}
637
alekseyshld995b552017-10-23 22:04:30 +0000638void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000639 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000640 return;
alekseyshld995b552017-10-23 22:04:30 +0000641 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000642 LastAllocatorPurgeAttemptTime)
643 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000644 return;
alekseyshld995b552017-10-23 22:04:30 +0000645
646 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000647 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000648 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000649
650 LastAllocatorPurgeAttemptTime = system_clock::now();
651}
652
kcc2e93b3f2017-08-29 02:05:01 +0000653void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
654 const size_t kMaxSaneLen = 1 << 20;
655 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000656 Vector<SizedFile> SizedFiles;
657 size_t MaxSize = 0;
658 size_t MinSize = -1;
659 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000660 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000661 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000662 GetSizedFilesFromDir(Dir, &SizedFiles);
663 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
664 Dir.c_str());
665 LastNumFiles = SizedFiles.size();
666 }
667 for (auto &File : SizedFiles) {
668 MaxSize = Max(File.Size, MaxSize);
669 MinSize = Min(File.Size, MinSize);
670 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000671 }
kccdc00cd32017-08-29 20:51:24 +0000672 if (Options.MaxLen == 0)
673 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
674 assert(MaxInputLen > 0);
675
kcc2cd9f092017-10-13 01:12:23 +0000676 // Test the callback with empty input and never try it again.
677 uint8_t dummy = 0;
678 ExecuteCallback(&dummy, 0);
679
kccdc00cd32017-08-29 20:51:24 +0000680 if (SizedFiles.empty()) {
681 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
682 Unit U({'\n'}); // Valid ASCII input.
683 RunOne(U.data(), U.size());
684 } else {
685 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
686 " rss: %zdMb\n",
687 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
688 if (Options.ShuffleAtStartUp)
689 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
690
kcc7f5f2222017-09-12 21:58:07 +0000691 if (Options.PreferSmall) {
692 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
693 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
694 }
kccdc00cd32017-08-29 20:51:24 +0000695
696 // Load and execute inputs one by one.
697 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000698 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000699 assert(U.size() <= MaxInputLen);
700 RunOne(U.data(), U.size());
701 CheckExitOnSrcPosOrItem();
702 TryDetectingAMemoryLeak(U.data(), U.size(),
703 /*DuringInitialCorpusExecution*/ true);
704 }
kcc2e93b3f2017-08-29 02:05:01 +0000705 }
706
kccdc00cd32017-08-29 20:51:24 +0000707 PrintStats("INITED");
708 if (Corpus.empty()) {
709 Printf("ERROR: no interesting inputs were found. "
710 "Is the code instrumented for coverage? Exiting.\n");
711 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000712 }
kcc2e93b3f2017-08-29 02:05:01 +0000713}
714
715void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
716 ReadAndExecuteSeedCorpora(CorpusDirs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000717 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000718 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000719 system_clock::time_point LastCorpusReload = system_clock::now();
720 if (Options.DoCrossOver)
721 MD.SetCorpus(&Corpus);
722 while (true) {
723 auto Now = system_clock::now();
724 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
725 Options.ReloadIntervalSec) {
726 RereadOutputCorpus(MaxInputLen);
727 LastCorpusReload = system_clock::now();
728 }
729 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
730 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000731 if (TimedOut())
732 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000733
734 // Update TmpMaxMutationLen
735 if (Options.ExperimentalLenControl) {
736 if (TmpMaxMutationLen < MaxMutationLen &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000737 (TotalNumberOfRuns - LastCorpusUpdateRun > 1000 &&
738 duration_cast<seconds>(Now - LastCorpusUpdateTime).count() >= 1)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000739 LastCorpusUpdateRun = TotalNumberOfRuns;
740 LastCorpusUpdateTime = Now;
741 TmpMaxMutationLen =
742 Min(MaxMutationLen,
743 TmpMaxMutationLen + Max(size_t(4), TmpMaxMutationLen / 8));
744 if (TmpMaxMutationLen <= MaxMutationLen)
745 Printf("#%zd\tTEMP_MAX_LEN: %zd\n", TotalNumberOfRuns,
746 TmpMaxMutationLen);
747 }
748 } else {
749 TmpMaxMutationLen = MaxMutationLen;
750 }
751
752 // Perform several mutations and runs.
753 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000754
755 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000756 }
757
758 PrintStats("DONE ", "\n");
759 MD.PrintRecommendedDictionary();
760}
761
762void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000763 if (U.size() <= 1)
764 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000765 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
766 MD.StartMutationSequence();
767 memcpy(CurrentUnitData, U.data(), U.size());
768 for (int i = 0; i < Options.MutateDepth; i++) {
769 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
770 assert(NewSize > 0 && NewSize <= MaxMutationLen);
771 ExecuteCallback(CurrentUnitData, NewSize);
772 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
773 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
774 /*DuringInitialCorpusExecution*/ false);
775 }
776 }
777}
778
779void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
780 if (SMR.IsServer()) {
781 SMR.WriteByteArray(Data, Size);
782 } else if (SMR.IsClient()) {
783 SMR.PostClient();
784 SMR.WaitServer();
785 size_t OtherSize = SMR.ReadByteArraySize();
786 uint8_t *OtherData = SMR.GetByteArray();
787 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
788 size_t i = 0;
789 for (i = 0; i < Min(Size, OtherSize); i++)
790 if (Data[i] != OtherData[i])
791 break;
792 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000793 "offset %zd\n",
794 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000795 DumpCurrentUnit("mismatch-");
796 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
797 PrintFinalStats();
798 _Exit(Options.ErrorExitCode);
799 }
800 }
801}
802
803} // namespace fuzzer
804
805extern "C" {
806
807size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
808 assert(fuzzer::F);
809 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
810}
811
812// Experimental
813void LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
814 assert(fuzzer::F);
815 fuzzer::F->AnnounceOutput(Data, Size);
816}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000817} // extern "C"