blob: dfa6cf38b1fa63298d987e498c05630ddd4ba9d0 [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));
162}
163
alekseyshl9f6a9f22017-10-23 23:24:33 +0000164Fuzzer::~Fuzzer() {}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000165
166void Fuzzer::AllocateCurrentUnitData() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000167 if (CurrentUnitData || MaxInputLen == 0)
168 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000169 CurrentUnitData = new uint8_t[MaxInputLen];
170}
171
172void Fuzzer::StaticDeathCallback() {
173 assert(F);
174 F->DeathCallback();
175}
176
177void Fuzzer::DumpCurrentUnit(const char *Prefix) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000178 if (!CurrentUnitData)
179 return; // Happens when running individual inputs.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000180 MD.PrintMutationSequence();
181 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
182 size_t UnitSize = CurrentUnitSize;
183 if (UnitSize <= kMaxUnitSizeToPrint) {
184 PrintHexArray(CurrentUnitData, UnitSize, "\n");
185 PrintASCII(CurrentUnitData, UnitSize, "\n");
186 }
187 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
188 Prefix);
189}
190
191NO_SANITIZE_MEMORY
192void Fuzzer::DeathCallback() {
193 DumpCurrentUnit("crash-");
194 PrintFinalStats();
195}
196
197void Fuzzer::StaticAlarmCallback() {
198 assert(F);
199 F->AlarmCallback();
200}
201
202void Fuzzer::StaticCrashSignalCallback() {
203 assert(F);
204 F->CrashCallback();
205}
206
207void Fuzzer::StaticExitCallback() {
208 assert(F);
209 F->ExitCallback();
210}
211
212void Fuzzer::StaticInterruptCallback() {
213 assert(F);
214 F->InterruptCallback();
215}
216
kcc1239a992017-11-09 20:30:19 +0000217void Fuzzer::StaticGracefulExitCallback() {
218 assert(F);
219 F->GracefulExitRequested = true;
220 Printf("INFO: signal received, trying to exit gracefully\n");
221}
222
george.karpenkov29efa6d2017-08-21 23:25:50 +0000223void Fuzzer::StaticFileSizeExceedCallback() {
224 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
225 exit(1);
226}
227
228void Fuzzer::CrashCallback() {
morehousef7b44452018-05-02 02:55:28 +0000229 if (EF->__sanitizer_acquire_crash_state)
230 EF->__sanitizer_acquire_crash_state();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000231 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000232 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000233 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
234 " Combine libFuzzer with AddressSanitizer or similar for better "
235 "crash reports.\n");
236 Printf("SUMMARY: libFuzzer: deadly signal\n");
237 DumpCurrentUnit("crash-");
238 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000239 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000240}
241
242void Fuzzer::ExitCallback() {
243 if (!RunningCB)
244 return; // This exit did not come from the user callback
morehouse5a4566a2018-05-01 21:01:53 +0000245 if (EF->__sanitizer_acquire_crash_state &&
246 !EF->__sanitizer_acquire_crash_state())
247 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000248 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000249 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000250 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
251 DumpCurrentUnit("crash-");
252 PrintFinalStats();
253 _Exit(Options.ErrorExitCode);
254}
255
kcc1239a992017-11-09 20:30:19 +0000256void Fuzzer::MaybeExitGracefully() {
257 if (!GracefulExitRequested) return;
258 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
259 PrintFinalStats();
260 _Exit(0);
261}
262
george.karpenkov29efa6d2017-08-21 23:25:50 +0000263void Fuzzer::InterruptCallback() {
264 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
265 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000266 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000267}
268
269NO_SANITIZE_MEMORY
270void Fuzzer::AlarmCallback() {
271 assert(Options.UnitTimeoutSec > 0);
272 // In Windows Alarm callback is executed by a different thread.
273#if !LIBFUZZER_WINDOWS
alekseyshl9f6a9f22017-10-23 23:24:33 +0000274 if (!InFuzzingThread())
275 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000276#endif
277 if (!RunningCB)
278 return; // We have not started running units yet.
279 size_t Seconds =
280 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
281 if (Seconds == 0)
282 return;
283 if (Options.Verbosity >= 2)
284 Printf("AlarmCallback %zd\n", Seconds);
285 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000286 if (EF->__sanitizer_acquire_crash_state &&
287 !EF->__sanitizer_acquire_crash_state())
288 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000289 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
290 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
291 Options.UnitTimeoutSec);
292 DumpCurrentUnit("timeout-");
293 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
294 Seconds);
morehousebd67cc22018-05-08 23:45:05 +0000295 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000296 Printf("SUMMARY: libFuzzer: timeout\n");
297 PrintFinalStats();
298 _Exit(Options.TimeoutExitCode); // Stop right now.
299 }
300}
301
302void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000303 if (EF->__sanitizer_acquire_crash_state &&
304 !EF->__sanitizer_acquire_crash_state())
305 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000306 Printf(
307 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
308 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
309 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000310 PrintMemoryProfile();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000311 DumpCurrentUnit("oom-");
312 Printf("SUMMARY: libFuzzer: out-of-memory\n");
313 PrintFinalStats();
314 _Exit(Options.ErrorExitCode); // Stop right now.
315}
316
317void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
318 size_t ExecPerSec = execPerSec();
319 if (!Options.Verbosity)
320 return;
321 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
322 if (size_t N = TPC.GetTotalPCCoverage())
323 Printf(" cov: %zd", N);
324 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000325 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000326 if (!Corpus.empty()) {
327 Printf(" corp: %zd", Corpus.NumActiveUnits());
328 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000329 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000330 Printf("/%zdb", N);
331 else if (N < (1 << 24))
332 Printf("/%zdKb", N >> 10);
333 else
334 Printf("/%zdMb", N >> 20);
335 }
336 }
morehousea6c692c2018-02-22 19:00:17 +0000337 if (TmpMaxMutationLen)
338 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000339 if (Units)
340 Printf(" units: %zd", Units);
341
342 Printf(" exec/s: %zd", ExecPerSec);
343 Printf(" rss: %zdMb", GetPeakRSSMb());
344 Printf("%s", End);
345}
346
347void Fuzzer::PrintFinalStats() {
348 if (Options.PrintCoverage)
349 TPC.PrintCoverage();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000350 if (Options.PrintCorpusStats)
351 Corpus.PrintStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000352 if (!Options.PrintFinalStats)
353 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000354 size_t ExecPerSec = execPerSec();
355 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
356 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
357 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
358 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
359 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
360}
361
362void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
363 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
364 assert(MaxInputLen);
365 this->MaxInputLen = MaxInputLen;
366 this->MaxMutationLen = MaxInputLen;
367 AllocateCurrentUnitData();
368 Printf("INFO: -max_len is not provided; "
369 "libFuzzer will not generate inputs larger than %zd bytes\n",
370 MaxInputLen);
371}
372
373void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
374 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
375 this->MaxMutationLen = MaxMutationLen;
376}
377
378void Fuzzer::CheckExitOnSrcPosOrItem() {
379 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000380 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000381 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000382 if (!PCsSet->insert(PC).second)
383 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000384 std::string Descr = DescribePC("%F %L", PC + 1);
385 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
386 Printf("INFO: found line matching '%s', exiting.\n",
387 Options.ExitOnSrcPos.c_str());
388 _Exit(0);
389 }
390 };
391 TPC.ForEachObservedPC(HandlePC);
392 }
393 if (!Options.ExitOnItem.empty()) {
394 if (Corpus.HasUnit(Options.ExitOnItem)) {
395 Printf("INFO: found item with checksum '%s', exiting.\n",
396 Options.ExitOnItem.c_str());
397 _Exit(0);
398 }
399 }
400}
401
402void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000403 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
404 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000405 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000406 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
407 &EpochOfLastReadOfOutputCorpus, MaxSize,
408 /*ExitOnError*/ false);
409 if (Options.Verbosity >= 2)
410 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
411 bool Reloaded = false;
412 for (auto &U : AdditionalCorpus) {
413 if (U.size() > MaxSize)
414 U.resize(MaxSize);
415 if (!Corpus.HasUnit(U)) {
416 if (RunOne(U.data(), U.size())) {
417 CheckExitOnSrcPosOrItem();
418 Reloaded = true;
419 }
420 }
421 }
422 if (Reloaded)
423 PrintStats("RELOAD");
424}
425
george.karpenkov29efa6d2017-08-21 23:25:50 +0000426void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
427 auto TimeOfUnit =
428 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
429 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
430 secondsSinceProcessStartUp() >= 2)
431 PrintStats("pulse ");
432 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
433 TimeOfUnit >= Options.ReportSlowUnits) {
434 TimeOfLongestUnitInSeconds = TimeOfUnit;
435 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
436 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
437 }
438}
439
440bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000441 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000442 if (!Size)
443 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000444
445 ExecuteCallback(Data, Size);
446
447 UniqFeatureSetTmp.clear();
448 size_t FoundUniqFeaturesOfII = 0;
449 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
450 TPC.CollectFeatures([&](size_t Feature) {
kcc1f5638d2017-12-08 22:21:42 +0000451 if (Options.UseFeatureFrequency)
452 Corpus.UpdateFeatureFrequency(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000453 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
454 UniqFeatureSetTmp.push_back(Feature);
455 if (Options.ReduceInputs && II)
456 if (std::binary_search(II->UniqFeatureSet.begin(),
457 II->UniqFeatureSet.end(), Feature))
458 FoundUniqFeaturesOfII++;
459 });
kccb6836be2017-12-01 19:18:38 +0000460 if (FoundUniqFeatures)
461 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000462 PrintPulseAndReportSlowInput(Data, Size);
463 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
464 if (NumNewFeatures) {
465 TPC.UpdateObservedPCs();
466 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
467 UniqFeatureSetTmp);
468 return true;
469 }
470 if (II && FoundUniqFeaturesOfII &&
471 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
472 II->U.size() > Size) {
473 Corpus.Replace(II, {Data, Data + Size});
474 return true;
475 }
476 return false;
477}
478
479size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
480 assert(InFuzzingThread());
481 *Data = CurrentUnitData;
482 return CurrentUnitSize;
483}
484
485void Fuzzer::CrashOnOverwrittenData() {
486 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
487 GetPid());
488 DumpCurrentUnit("crash-");
489 Printf("SUMMARY: libFuzzer: out-of-memory\n");
490 _Exit(Options.ErrorExitCode); // Stop right now.
491}
492
493// Compare two arrays, but not all bytes if the arrays are large.
494static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
495 const size_t Limit = 64;
496 if (Size <= 64)
497 return !memcmp(A, B, Size);
498 // Compare first and last Limit/2 bytes.
499 return !memcmp(A, B, Limit / 2) &&
500 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
501}
502
503void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
504 TPC.RecordInitialStack();
505 TotalNumberOfRuns++;
506 assert(InFuzzingThread());
507 if (SMR.IsClient())
508 SMR.WriteByteArray(Data, Size);
509 // We copy the contents of Unit into a separate heap buffer
510 // so that we reliably find buffer overflows in it.
511 uint8_t *DataCopy = new uint8_t[Size];
512 memcpy(DataCopy, Data, Size);
513 if (CurrentUnitData && CurrentUnitData != Data)
514 memcpy(CurrentUnitData, Data, Size);
515 CurrentUnitSize = Size;
516 AllocTracer.Start(Options.TraceMalloc);
517 UnitStartTime = system_clock::now();
518 TPC.ResetMaps();
519 RunningCB = true;
520 int Res = CB(DataCopy, Size);
521 RunningCB = false;
522 UnitStopTime = system_clock::now();
523 (void)Res;
524 assert(Res == 0);
525 HasMoreMallocsThanFrees = AllocTracer.Stop();
526 if (!LooseMemeq(DataCopy, Data, Size))
527 CrashOnOverwrittenData();
528 CurrentUnitSize = 0;
529 delete[] DataCopy;
530}
531
532void Fuzzer::WriteToOutputCorpus(const Unit &U) {
533 if (Options.OnlyASCII)
534 assert(IsASCII(U));
535 if (Options.OutputCorpus.empty())
536 return;
537 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
538 WriteToFile(U, Path);
539 if (Options.Verbosity >= 2)
540 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
541}
542
543void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
544 if (!Options.SaveArtifacts)
545 return;
546 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
547 if (!Options.ExactArtifactPath.empty())
548 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
549 WriteToFile(U, Path);
550 Printf("artifact_prefix='%s'; Test unit written to %s\n",
551 Options.ArtifactPrefix.c_str(), Path.c_str());
552 if (U.size() <= kMaxUnitSizeToPrint)
553 Printf("Base64: %s\n", Base64(U).c_str());
554}
555
556void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
557 if (!Options.PrintNEW)
558 return;
559 PrintStats(Text, "");
560 if (Options.Verbosity) {
561 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
562 MD.PrintMutationSequence();
563 Printf("\n");
564 }
565}
566
567void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
568 II->NumSuccessfullMutations++;
569 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000570 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000571 WriteToOutputCorpus(U);
572 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000573 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000574 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000575}
576
577// Tries detecting a memory leak on the particular input that we have just
578// executed before calling this function.
579void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
580 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000581 if (!HasMoreMallocsThanFrees)
582 return; // mallocs==frees, a leak is unlikely.
583 if (!Options.DetectLeaks)
584 return;
dor1s38279cb2017-09-12 02:01:54 +0000585 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000586 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
587 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000588 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
589 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000590 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000591 // Run the target once again, but with lsan disabled so that if there is
592 // a real leak we do not report it twice.
593 EF->__lsan_disable();
594 ExecuteCallback(Data, Size);
595 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000596 if (!HasMoreMallocsThanFrees)
597 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000598 if (NumberOfLeakDetectionAttempts++ > 1000) {
599 Options.DetectLeaks = false;
600 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
601 " Most likely the target function accumulates allocated\n"
602 " memory in a global state w/o actually leaking it.\n"
603 " You may try running this binary with -trace_malloc=[12]"
604 " to get a trace of mallocs and frees.\n"
605 " If LeakSanitizer is enabled in this process it will still\n"
606 " run on the process shutdown.\n");
607 return;
608 }
609 // Now perform the actual lsan pass. This is expensive and we must ensure
610 // we don't call it too often.
611 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
612 if (DuringInitialCorpusExecution)
613 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
614 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
615 CurrentUnitSize = Size;
616 DumpCurrentUnit("leak-");
617 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000618 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000619 }
620}
621
622void Fuzzer::MutateAndTestOne() {
623 MD.StartMutationSequence();
624
625 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
kcc20fc0672017-10-11 01:44:26 +0000626 if (Options.UseFeatureFrequency)
627 Corpus.UpdateFeatureFrequencyScore(&II);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000628 const auto &U = II.U;
629 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
630 assert(CurrentUnitData);
631 size_t Size = U.size();
632 assert(Size <= MaxInputLen && "Oversized Unit");
633 memcpy(CurrentUnitData, U.data(), Size);
634
635 assert(MaxMutationLen > 0);
636
637 size_t CurrentMaxMutationLen =
638 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
639 assert(CurrentMaxMutationLen > 0);
640
641 for (int i = 0; i < Options.MutateDepth; i++) {
642 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
643 break;
kcc1239a992017-11-09 20:30:19 +0000644 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000645 size_t NewSize = 0;
646 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
647 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000648 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000649 Size = NewSize;
650 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000651
kccb6836be2017-12-01 19:18:38 +0000652 bool FoundUniqFeatures = false;
653 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
654 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000655 TryDetectingAMemoryLeak(CurrentUnitData, Size,
656 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000657 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000658 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000659 break; // We will mutate this input more in the next rounds.
660 }
661 if (Options.ReduceDepth && !FoundUniqFeatures)
662 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000663 }
664}
665
alekseyshld995b552017-10-23 22:04:30 +0000666void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000667 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000668 return;
alekseyshld995b552017-10-23 22:04:30 +0000669 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000670 LastAllocatorPurgeAttemptTime)
671 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000672 return;
alekseyshld995b552017-10-23 22:04:30 +0000673
674 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000675 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000676 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000677
678 LastAllocatorPurgeAttemptTime = system_clock::now();
679}
680
kcc2e93b3f2017-08-29 02:05:01 +0000681void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
682 const size_t kMaxSaneLen = 1 << 20;
683 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000684 Vector<SizedFile> SizedFiles;
685 size_t MaxSize = 0;
686 size_t MinSize = -1;
687 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000688 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000689 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000690 GetSizedFilesFromDir(Dir, &SizedFiles);
691 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
692 Dir.c_str());
693 LastNumFiles = SizedFiles.size();
694 }
695 for (auto &File : SizedFiles) {
696 MaxSize = Max(File.Size, MaxSize);
697 MinSize = Min(File.Size, MinSize);
698 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000699 }
kccdc00cd32017-08-29 20:51:24 +0000700 if (Options.MaxLen == 0)
701 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
702 assert(MaxInputLen > 0);
703
kcc2cd9f092017-10-13 01:12:23 +0000704 // Test the callback with empty input and never try it again.
705 uint8_t dummy = 0;
706 ExecuteCallback(&dummy, 0);
707
kccdc00cd32017-08-29 20:51:24 +0000708 if (SizedFiles.empty()) {
709 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
710 Unit U({'\n'}); // Valid ASCII input.
711 RunOne(U.data(), U.size());
712 } else {
713 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
714 " rss: %zdMb\n",
715 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
716 if (Options.ShuffleAtStartUp)
717 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
718
kcc7f5f2222017-09-12 21:58:07 +0000719 if (Options.PreferSmall) {
720 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
721 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
722 }
kccdc00cd32017-08-29 20:51:24 +0000723
724 // Load and execute inputs one by one.
725 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000726 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000727 assert(U.size() <= MaxInputLen);
728 RunOne(U.data(), U.size());
729 CheckExitOnSrcPosOrItem();
730 TryDetectingAMemoryLeak(U.data(), U.size(),
731 /*DuringInitialCorpusExecution*/ true);
732 }
kcc2e93b3f2017-08-29 02:05:01 +0000733 }
734
kccdc00cd32017-08-29 20:51:24 +0000735 PrintStats("INITED");
736 if (Corpus.empty()) {
737 Printf("ERROR: no interesting inputs were found. "
738 "Is the code instrumented for coverage? Exiting.\n");
739 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000740 }
kcc2e93b3f2017-08-29 02:05:01 +0000741}
742
743void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
744 ReadAndExecuteSeedCorpora(CorpusDirs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000745 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000746 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000747 system_clock::time_point LastCorpusReload = system_clock::now();
748 if (Options.DoCrossOver)
749 MD.SetCorpus(&Corpus);
750 while (true) {
751 auto Now = system_clock::now();
752 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
753 Options.ReloadIntervalSec) {
754 RereadOutputCorpus(MaxInputLen);
755 LastCorpusReload = system_clock::now();
756 }
757 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
758 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000759 if (TimedOut())
760 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000761
762 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000763 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000764 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000765 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000766 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000767 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000768 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000769 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000770 }
771 } else {
772 TmpMaxMutationLen = MaxMutationLen;
773 }
774
775 // Perform several mutations and runs.
776 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000777
778 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000779 }
780
781 PrintStats("DONE ", "\n");
782 MD.PrintRecommendedDictionary();
783}
784
785void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000786 if (U.size() <= 1)
787 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000788 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
789 MD.StartMutationSequence();
790 memcpy(CurrentUnitData, U.data(), U.size());
791 for (int i = 0; i < Options.MutateDepth; i++) {
792 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
793 assert(NewSize > 0 && NewSize <= MaxMutationLen);
794 ExecuteCallback(CurrentUnitData, NewSize);
795 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
796 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
797 /*DuringInitialCorpusExecution*/ false);
798 }
799 }
800}
801
802void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
803 if (SMR.IsServer()) {
804 SMR.WriteByteArray(Data, Size);
805 } else if (SMR.IsClient()) {
806 SMR.PostClient();
807 SMR.WaitServer();
808 size_t OtherSize = SMR.ReadByteArraySize();
809 uint8_t *OtherData = SMR.GetByteArray();
810 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
811 size_t i = 0;
812 for (i = 0; i < Min(Size, OtherSize); i++)
813 if (Data[i] != OtherData[i])
814 break;
815 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000816 "offset %zd\n",
817 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000818 DumpCurrentUnit("mismatch-");
819 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
820 PrintFinalStats();
821 _Exit(Options.ErrorExitCode);
822 }
823 }
824}
825
826} // namespace fuzzer
827
828extern "C" {
829
phosek966475e2018-01-17 20:39:14 +0000830__attribute__((visibility("default"))) size_t
831LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000832 assert(fuzzer::F);
833 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
834}
835
836// Experimental
phosek966475e2018-01-17 20:39:14 +0000837__attribute__((visibility("default"))) void
838LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000839 assert(fuzzer::F);
840 fuzzer::F->AnnounceOutput(Data, Size);
841}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000842} // extern "C"