blob: a195d21d38c8e8c1729b60d9123b54b2bd37df1c [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);
151 TPC.SetUseValueProfile(Options.UseValueProfile);
152
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.
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() {
morehousef7b44452018-05-02 02:55:28 +0000231 if (EF->__sanitizer_acquire_crash_state)
232 EF->__sanitizer_acquire_crash_state();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000233 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000234 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000235 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
236 " Combine libFuzzer with AddressSanitizer or similar for better "
237 "crash reports.\n");
238 Printf("SUMMARY: libFuzzer: deadly signal\n");
239 DumpCurrentUnit("crash-");
240 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000241 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000242}
243
244void Fuzzer::ExitCallback() {
245 if (!RunningCB)
246 return; // This exit did not come from the user callback
morehouse5a4566a2018-05-01 21:01:53 +0000247 if (EF->__sanitizer_acquire_crash_state &&
248 !EF->__sanitizer_acquire_crash_state())
249 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000250 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000251 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000252 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
253 DumpCurrentUnit("crash-");
254 PrintFinalStats();
255 _Exit(Options.ErrorExitCode);
256}
257
kcc1239a992017-11-09 20:30:19 +0000258void Fuzzer::MaybeExitGracefully() {
259 if (!GracefulExitRequested) return;
260 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
261 PrintFinalStats();
262 _Exit(0);
263}
264
george.karpenkov29efa6d2017-08-21 23:25:50 +0000265void Fuzzer::InterruptCallback() {
266 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
267 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000268 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000269}
270
271NO_SANITIZE_MEMORY
272void Fuzzer::AlarmCallback() {
273 assert(Options.UnitTimeoutSec > 0);
274 // In Windows Alarm callback is executed by a different thread.
275#if !LIBFUZZER_WINDOWS
alekseyshl9f6a9f22017-10-23 23:24:33 +0000276 if (!InFuzzingThread())
277 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000278#endif
279 if (!RunningCB)
280 return; // We have not started running units yet.
281 size_t Seconds =
282 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
283 if (Seconds == 0)
284 return;
285 if (Options.Verbosity >= 2)
286 Printf("AlarmCallback %zd\n", Seconds);
287 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000288 if (EF->__sanitizer_acquire_crash_state &&
289 !EF->__sanitizer_acquire_crash_state())
290 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000291 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
292 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
293 Options.UnitTimeoutSec);
294 DumpCurrentUnit("timeout-");
295 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
296 Seconds);
morehousebd67cc22018-05-08 23:45:05 +0000297 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000298 Printf("SUMMARY: libFuzzer: timeout\n");
299 PrintFinalStats();
300 _Exit(Options.TimeoutExitCode); // Stop right now.
301 }
302}
303
304void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000305 if (EF->__sanitizer_acquire_crash_state &&
306 !EF->__sanitizer_acquire_crash_state())
307 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000308 Printf(
309 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
310 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
311 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000312 PrintMemoryProfile();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000313 DumpCurrentUnit("oom-");
314 Printf("SUMMARY: libFuzzer: out-of-memory\n");
315 PrintFinalStats();
316 _Exit(Options.ErrorExitCode); // Stop right now.
317}
318
319void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
320 size_t ExecPerSec = execPerSec();
321 if (!Options.Verbosity)
322 return;
323 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
324 if (size_t N = TPC.GetTotalPCCoverage())
325 Printf(" cov: %zd", N);
326 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000327 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000328 if (!Corpus.empty()) {
329 Printf(" corp: %zd", Corpus.NumActiveUnits());
330 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000331 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000332 Printf("/%zdb", N);
333 else if (N < (1 << 24))
334 Printf("/%zdKb", N >> 10);
335 else
336 Printf("/%zdMb", N >> 20);
337 }
kcc3acbe072018-05-16 23:26:37 +0000338 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
339 Printf(" focus: %zd", FF);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000340 }
morehousea6c692c2018-02-22 19:00:17 +0000341 if (TmpMaxMutationLen)
342 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000343 if (Units)
344 Printf(" units: %zd", Units);
345
346 Printf(" exec/s: %zd", ExecPerSec);
347 Printf(" rss: %zdMb", GetPeakRSSMb());
348 Printf("%s", End);
349}
350
351void Fuzzer::PrintFinalStats() {
352 if (Options.PrintCoverage)
353 TPC.PrintCoverage();
kcca7dd2a92018-05-21 19:47:00 +0000354 if (Options.DumpCoverage)
355 TPC.DumpCoverage();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000356 if (Options.PrintCorpusStats)
357 Corpus.PrintStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000358 if (!Options.PrintFinalStats)
359 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000360 size_t ExecPerSec = execPerSec();
361 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
362 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
363 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
364 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
365 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
366}
367
368void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
369 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
370 assert(MaxInputLen);
371 this->MaxInputLen = MaxInputLen;
372 this->MaxMutationLen = MaxInputLen;
373 AllocateCurrentUnitData();
374 Printf("INFO: -max_len is not provided; "
375 "libFuzzer will not generate inputs larger than %zd bytes\n",
376 MaxInputLen);
377}
378
379void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
380 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
381 this->MaxMutationLen = MaxMutationLen;
382}
383
384void Fuzzer::CheckExitOnSrcPosOrItem() {
385 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000386 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000387 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000388 if (!PCsSet->insert(PC).second)
389 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000390 std::string Descr = DescribePC("%F %L", PC + 1);
391 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
392 Printf("INFO: found line matching '%s', exiting.\n",
393 Options.ExitOnSrcPos.c_str());
394 _Exit(0);
395 }
396 };
397 TPC.ForEachObservedPC(HandlePC);
398 }
399 if (!Options.ExitOnItem.empty()) {
400 if (Corpus.HasUnit(Options.ExitOnItem)) {
401 Printf("INFO: found item with checksum '%s', exiting.\n",
402 Options.ExitOnItem.c_str());
403 _Exit(0);
404 }
405 }
406}
407
408void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000409 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
410 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000411 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000412 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
413 &EpochOfLastReadOfOutputCorpus, MaxSize,
414 /*ExitOnError*/ false);
415 if (Options.Verbosity >= 2)
416 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
417 bool Reloaded = false;
418 for (auto &U : AdditionalCorpus) {
419 if (U.size() > MaxSize)
420 U.resize(MaxSize);
421 if (!Corpus.HasUnit(U)) {
422 if (RunOne(U.data(), U.size())) {
423 CheckExitOnSrcPosOrItem();
424 Reloaded = true;
425 }
426 }
427 }
428 if (Reloaded)
429 PrintStats("RELOAD");
430}
431
george.karpenkov29efa6d2017-08-21 23:25:50 +0000432void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
433 auto TimeOfUnit =
434 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
435 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
436 secondsSinceProcessStartUp() >= 2)
437 PrintStats("pulse ");
438 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
439 TimeOfUnit >= Options.ReportSlowUnits) {
440 TimeOfLongestUnitInSeconds = TimeOfUnit;
441 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
442 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
443 }
444}
445
446bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000447 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000448 if (!Size)
449 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000450
451 ExecuteCallback(Data, Size);
452
453 UniqFeatureSetTmp.clear();
454 size_t FoundUniqFeaturesOfII = 0;
455 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
456 TPC.CollectFeatures([&](size_t Feature) {
457 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
458 UniqFeatureSetTmp.push_back(Feature);
459 if (Options.ReduceInputs && II)
460 if (std::binary_search(II->UniqFeatureSet.begin(),
461 II->UniqFeatureSet.end(), Feature))
462 FoundUniqFeaturesOfII++;
463 });
kccb6836be2017-12-01 19:18:38 +0000464 if (FoundUniqFeatures)
465 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000466 PrintPulseAndReportSlowInput(Data, Size);
467 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
468 if (NumNewFeatures) {
469 TPC.UpdateObservedPCs();
470 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
kcc3acbe072018-05-16 23:26:37 +0000471 TPC.ObservedFocusFunction(),
george.karpenkov29efa6d2017-08-21 23:25:50 +0000472 UniqFeatureSetTmp);
473 return true;
474 }
475 if (II && FoundUniqFeaturesOfII &&
476 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
477 II->U.size() > Size) {
478 Corpus.Replace(II, {Data, Data + Size});
479 return true;
480 }
481 return false;
482}
483
484size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
485 assert(InFuzzingThread());
486 *Data = CurrentUnitData;
487 return CurrentUnitSize;
488}
489
490void Fuzzer::CrashOnOverwrittenData() {
491 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
492 GetPid());
493 DumpCurrentUnit("crash-");
494 Printf("SUMMARY: libFuzzer: out-of-memory\n");
495 _Exit(Options.ErrorExitCode); // Stop right now.
496}
497
498// Compare two arrays, but not all bytes if the arrays are large.
499static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
500 const size_t Limit = 64;
501 if (Size <= 64)
502 return !memcmp(A, B, Size);
503 // Compare first and last Limit/2 bytes.
504 return !memcmp(A, B, Limit / 2) &&
505 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
506}
507
508void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
509 TPC.RecordInitialStack();
510 TotalNumberOfRuns++;
511 assert(InFuzzingThread());
512 if (SMR.IsClient())
513 SMR.WriteByteArray(Data, Size);
514 // We copy the contents of Unit into a separate heap buffer
515 // so that we reliably find buffer overflows in it.
516 uint8_t *DataCopy = new uint8_t[Size];
517 memcpy(DataCopy, Data, Size);
518 if (CurrentUnitData && CurrentUnitData != Data)
519 memcpy(CurrentUnitData, Data, Size);
520 CurrentUnitSize = Size;
521 AllocTracer.Start(Options.TraceMalloc);
522 UnitStartTime = system_clock::now();
523 TPC.ResetMaps();
524 RunningCB = true;
525 int Res = CB(DataCopy, Size);
526 RunningCB = false;
527 UnitStopTime = system_clock::now();
528 (void)Res;
529 assert(Res == 0);
530 HasMoreMallocsThanFrees = AllocTracer.Stop();
531 if (!LooseMemeq(DataCopy, Data, Size))
532 CrashOnOverwrittenData();
533 CurrentUnitSize = 0;
534 delete[] DataCopy;
535}
536
537void Fuzzer::WriteToOutputCorpus(const Unit &U) {
538 if (Options.OnlyASCII)
539 assert(IsASCII(U));
540 if (Options.OutputCorpus.empty())
541 return;
542 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
543 WriteToFile(U, Path);
544 if (Options.Verbosity >= 2)
545 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
546}
547
548void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
549 if (!Options.SaveArtifacts)
550 return;
551 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
552 if (!Options.ExactArtifactPath.empty())
553 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
554 WriteToFile(U, Path);
555 Printf("artifact_prefix='%s'; Test unit written to %s\n",
556 Options.ArtifactPrefix.c_str(), Path.c_str());
557 if (U.size() <= kMaxUnitSizeToPrint)
558 Printf("Base64: %s\n", Base64(U).c_str());
559}
560
561void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
562 if (!Options.PrintNEW)
563 return;
564 PrintStats(Text, "");
565 if (Options.Verbosity) {
566 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
567 MD.PrintMutationSequence();
568 Printf("\n");
569 }
570}
571
572void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
573 II->NumSuccessfullMutations++;
574 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000575 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000576 WriteToOutputCorpus(U);
577 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000578 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000579 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000580}
581
582// Tries detecting a memory leak on the particular input that we have just
583// executed before calling this function.
584void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
585 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000586 if (!HasMoreMallocsThanFrees)
587 return; // mallocs==frees, a leak is unlikely.
588 if (!Options.DetectLeaks)
589 return;
dor1s38279cb2017-09-12 02:01:54 +0000590 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000591 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
592 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000593 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
594 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000595 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000596 // Run the target once again, but with lsan disabled so that if there is
597 // a real leak we do not report it twice.
598 EF->__lsan_disable();
599 ExecuteCallback(Data, Size);
600 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000601 if (!HasMoreMallocsThanFrees)
602 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000603 if (NumberOfLeakDetectionAttempts++ > 1000) {
604 Options.DetectLeaks = false;
605 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
606 " Most likely the target function accumulates allocated\n"
607 " memory in a global state w/o actually leaking it.\n"
608 " You may try running this binary with -trace_malloc=[12]"
609 " to get a trace of mallocs and frees.\n"
610 " If LeakSanitizer is enabled in this process it will still\n"
611 " run on the process shutdown.\n");
612 return;
613 }
614 // Now perform the actual lsan pass. This is expensive and we must ensure
615 // we don't call it too often.
616 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
617 if (DuringInitialCorpusExecution)
618 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
619 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
620 CurrentUnitSize = Size;
621 DumpCurrentUnit("leak-");
622 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000623 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000624 }
625}
626
627void Fuzzer::MutateAndTestOne() {
628 MD.StartMutationSequence();
629
630 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
631 const auto &U = II.U;
632 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
633 assert(CurrentUnitData);
634 size_t Size = U.size();
635 assert(Size <= MaxInputLen && "Oversized Unit");
636 memcpy(CurrentUnitData, U.data(), Size);
637
638 assert(MaxMutationLen > 0);
639
640 size_t CurrentMaxMutationLen =
641 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
642 assert(CurrentMaxMutationLen > 0);
643
644 for (int i = 0; i < Options.MutateDepth; i++) {
645 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
646 break;
kcc1239a992017-11-09 20:30:19 +0000647 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000648 size_t NewSize = 0;
649 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
650 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000651 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000652 Size = NewSize;
653 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000654
kccb6836be2017-12-01 19:18:38 +0000655 bool FoundUniqFeatures = false;
656 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
657 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000658 TryDetectingAMemoryLeak(CurrentUnitData, Size,
659 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000660 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000661 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000662 break; // We will mutate this input more in the next rounds.
663 }
664 if (Options.ReduceDepth && !FoundUniqFeatures)
665 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000666 }
667}
668
alekseyshld995b552017-10-23 22:04:30 +0000669void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000670 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000671 return;
alekseyshld995b552017-10-23 22:04:30 +0000672 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000673 LastAllocatorPurgeAttemptTime)
674 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000675 return;
alekseyshld995b552017-10-23 22:04:30 +0000676
677 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000678 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000679 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000680
681 LastAllocatorPurgeAttemptTime = system_clock::now();
682}
683
kcc2e93b3f2017-08-29 02:05:01 +0000684void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
685 const size_t kMaxSaneLen = 1 << 20;
686 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000687 Vector<SizedFile> SizedFiles;
688 size_t MaxSize = 0;
689 size_t MinSize = -1;
690 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000691 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000692 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000693 GetSizedFilesFromDir(Dir, &SizedFiles);
694 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
695 Dir.c_str());
696 LastNumFiles = SizedFiles.size();
697 }
698 for (auto &File : SizedFiles) {
699 MaxSize = Max(File.Size, MaxSize);
700 MinSize = Min(File.Size, MinSize);
701 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000702 }
kccdc00cd32017-08-29 20:51:24 +0000703 if (Options.MaxLen == 0)
704 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
705 assert(MaxInputLen > 0);
706
kcc2cd9f092017-10-13 01:12:23 +0000707 // Test the callback with empty input and never try it again.
708 uint8_t dummy = 0;
709 ExecuteCallback(&dummy, 0);
710
kccdc00cd32017-08-29 20:51:24 +0000711 if (SizedFiles.empty()) {
712 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
713 Unit U({'\n'}); // Valid ASCII input.
714 RunOne(U.data(), U.size());
715 } else {
716 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
717 " rss: %zdMb\n",
718 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
719 if (Options.ShuffleAtStartUp)
720 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
721
kcc7f5f2222017-09-12 21:58:07 +0000722 if (Options.PreferSmall) {
723 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
724 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
725 }
kccdc00cd32017-08-29 20:51:24 +0000726
727 // Load and execute inputs one by one.
728 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000729 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000730 assert(U.size() <= MaxInputLen);
731 RunOne(U.data(), U.size());
732 CheckExitOnSrcPosOrItem();
733 TryDetectingAMemoryLeak(U.data(), U.size(),
734 /*DuringInitialCorpusExecution*/ true);
735 }
kcc2e93b3f2017-08-29 02:05:01 +0000736 }
737
kccdc00cd32017-08-29 20:51:24 +0000738 PrintStats("INITED");
kcc3acbe072018-05-16 23:26:37 +0000739 if (!Options.FocusFunction.empty())
740 Printf("INFO: %zd/%zd inputs touch the focus function\n",
741 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
742
dor1s770a9bc2018-05-23 19:42:30 +0000743 if (Corpus.empty() && Options.MaxNumberOfRuns) {
kccdc00cd32017-08-29 20:51:24 +0000744 Printf("ERROR: no interesting inputs were found. "
745 "Is the code instrumented for coverage? Exiting.\n");
746 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000747 }
kcc2e93b3f2017-08-29 02:05:01 +0000748}
749
750void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
751 ReadAndExecuteSeedCorpora(CorpusDirs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000752 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000753 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000754 system_clock::time_point LastCorpusReload = system_clock::now();
755 if (Options.DoCrossOver)
756 MD.SetCorpus(&Corpus);
757 while (true) {
758 auto Now = system_clock::now();
759 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
760 Options.ReloadIntervalSec) {
761 RereadOutputCorpus(MaxInputLen);
762 LastCorpusReload = system_clock::now();
763 }
764 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
765 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000766 if (TimedOut())
767 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000768
769 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000770 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000771 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000772 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000773 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000774 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000775 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000776 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000777 }
778 } else {
779 TmpMaxMutationLen = MaxMutationLen;
780 }
781
782 // Perform several mutations and runs.
783 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000784
785 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000786 }
787
788 PrintStats("DONE ", "\n");
789 MD.PrintRecommendedDictionary();
790}
791
792void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000793 if (U.size() <= 1)
794 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000795 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
796 MD.StartMutationSequence();
797 memcpy(CurrentUnitData, U.data(), U.size());
798 for (int i = 0; i < Options.MutateDepth; i++) {
799 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
800 assert(NewSize > 0 && NewSize <= MaxMutationLen);
801 ExecuteCallback(CurrentUnitData, NewSize);
802 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
803 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
804 /*DuringInitialCorpusExecution*/ false);
805 }
806 }
807}
808
809void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
810 if (SMR.IsServer()) {
811 SMR.WriteByteArray(Data, Size);
812 } else if (SMR.IsClient()) {
813 SMR.PostClient();
814 SMR.WaitServer();
815 size_t OtherSize = SMR.ReadByteArraySize();
816 uint8_t *OtherData = SMR.GetByteArray();
817 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
818 size_t i = 0;
819 for (i = 0; i < Min(Size, OtherSize); i++)
820 if (Data[i] != OtherData[i])
821 break;
822 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000823 "offset %zd\n",
824 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000825 DumpCurrentUnit("mismatch-");
826 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
827 PrintFinalStats();
828 _Exit(Options.ErrorExitCode);
829 }
830 }
831}
832
833} // namespace fuzzer
834
835extern "C" {
836
phosek966475e2018-01-17 20:39:14 +0000837__attribute__((visibility("default"))) size_t
838LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000839 assert(fuzzer::F);
840 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
841}
842
843// Experimental
phosek966475e2018-01-17 20:39:14 +0000844__attribute__((visibility("default"))) void
845LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000846 assert(fuzzer::F);
847 fuzzer::F->AnnounceOutput(Data, Size);
848}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000849} // extern "C"