blob: 4bf5c7802460c6c8dcc4de2a9918bcc71a5120d8 [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);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000163}
164
alekseyshl9f6a9f22017-10-23 23:24:33 +0000165Fuzzer::~Fuzzer() {}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000166
167void Fuzzer::AllocateCurrentUnitData() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000168 if (CurrentUnitData || MaxInputLen == 0)
169 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000170 CurrentUnitData = new uint8_t[MaxInputLen];
171}
172
173void Fuzzer::StaticDeathCallback() {
174 assert(F);
175 F->DeathCallback();
176}
177
178void Fuzzer::DumpCurrentUnit(const char *Prefix) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000179 if (!CurrentUnitData)
180 return; // Happens when running individual inputs.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000181 MD.PrintMutationSequence();
182 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
183 size_t UnitSize = CurrentUnitSize;
184 if (UnitSize <= kMaxUnitSizeToPrint) {
185 PrintHexArray(CurrentUnitData, UnitSize, "\n");
186 PrintASCII(CurrentUnitData, UnitSize, "\n");
187 }
188 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
189 Prefix);
190}
191
192NO_SANITIZE_MEMORY
193void Fuzzer::DeathCallback() {
194 DumpCurrentUnit("crash-");
195 PrintFinalStats();
196}
197
198void Fuzzer::StaticAlarmCallback() {
199 assert(F);
200 F->AlarmCallback();
201}
202
203void Fuzzer::StaticCrashSignalCallback() {
204 assert(F);
205 F->CrashCallback();
206}
207
208void Fuzzer::StaticExitCallback() {
209 assert(F);
210 F->ExitCallback();
211}
212
213void Fuzzer::StaticInterruptCallback() {
214 assert(F);
215 F->InterruptCallback();
216}
217
kcc1239a992017-11-09 20:30:19 +0000218void Fuzzer::StaticGracefulExitCallback() {
219 assert(F);
220 F->GracefulExitRequested = true;
221 Printf("INFO: signal received, trying to exit gracefully\n");
222}
223
george.karpenkov29efa6d2017-08-21 23:25:50 +0000224void Fuzzer::StaticFileSizeExceedCallback() {
225 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
226 exit(1);
227}
228
229void Fuzzer::CrashCallback() {
morehousef7b44452018-05-02 02:55:28 +0000230 if (EF->__sanitizer_acquire_crash_state)
231 EF->__sanitizer_acquire_crash_state();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000232 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000233 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000234 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
235 " Combine libFuzzer with AddressSanitizer or similar for better "
236 "crash reports.\n");
237 Printf("SUMMARY: libFuzzer: deadly signal\n");
238 DumpCurrentUnit("crash-");
239 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000240 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000241}
242
243void Fuzzer::ExitCallback() {
244 if (!RunningCB)
245 return; // This exit did not come from the user callback
morehouse5a4566a2018-05-01 21:01:53 +0000246 if (EF->__sanitizer_acquire_crash_state &&
247 !EF->__sanitizer_acquire_crash_state())
248 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000249 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000250 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000251 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
252 DumpCurrentUnit("crash-");
253 PrintFinalStats();
254 _Exit(Options.ErrorExitCode);
255}
256
kcc1239a992017-11-09 20:30:19 +0000257void Fuzzer::MaybeExitGracefully() {
258 if (!GracefulExitRequested) return;
259 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
260 PrintFinalStats();
261 _Exit(0);
262}
263
george.karpenkov29efa6d2017-08-21 23:25:50 +0000264void Fuzzer::InterruptCallback() {
265 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
266 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000267 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000268}
269
270NO_SANITIZE_MEMORY
271void Fuzzer::AlarmCallback() {
272 assert(Options.UnitTimeoutSec > 0);
273 // In Windows Alarm callback is executed by a different thread.
274#if !LIBFUZZER_WINDOWS
alekseyshl9f6a9f22017-10-23 23:24:33 +0000275 if (!InFuzzingThread())
276 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000277#endif
278 if (!RunningCB)
279 return; // We have not started running units yet.
280 size_t Seconds =
281 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
282 if (Seconds == 0)
283 return;
284 if (Options.Verbosity >= 2)
285 Printf("AlarmCallback %zd\n", Seconds);
286 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000287 if (EF->__sanitizer_acquire_crash_state &&
288 !EF->__sanitizer_acquire_crash_state())
289 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000290 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
291 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
292 Options.UnitTimeoutSec);
293 DumpCurrentUnit("timeout-");
294 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
295 Seconds);
morehousebd67cc22018-05-08 23:45:05 +0000296 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000297 Printf("SUMMARY: libFuzzer: timeout\n");
298 PrintFinalStats();
299 _Exit(Options.TimeoutExitCode); // Stop right now.
300 }
301}
302
303void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000304 if (EF->__sanitizer_acquire_crash_state &&
305 !EF->__sanitizer_acquire_crash_state())
306 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000307 Printf(
308 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
309 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
310 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000311 PrintMemoryProfile();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000312 DumpCurrentUnit("oom-");
313 Printf("SUMMARY: libFuzzer: out-of-memory\n");
314 PrintFinalStats();
315 _Exit(Options.ErrorExitCode); // Stop right now.
316}
317
318void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
319 size_t ExecPerSec = execPerSec();
320 if (!Options.Verbosity)
321 return;
322 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
323 if (size_t N = TPC.GetTotalPCCoverage())
324 Printf(" cov: %zd", N);
325 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000326 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000327 if (!Corpus.empty()) {
328 Printf(" corp: %zd", Corpus.NumActiveUnits());
329 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000330 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000331 Printf("/%zdb", N);
332 else if (N < (1 << 24))
333 Printf("/%zdKb", N >> 10);
334 else
335 Printf("/%zdMb", N >> 20);
336 }
kcc3acbe072018-05-16 23:26:37 +0000337 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
338 Printf(" focus: %zd", FF);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000339 }
morehousea6c692c2018-02-22 19:00:17 +0000340 if (TmpMaxMutationLen)
341 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000342 if (Units)
343 Printf(" units: %zd", Units);
344
345 Printf(" exec/s: %zd", ExecPerSec);
346 Printf(" rss: %zdMb", GetPeakRSSMb());
347 Printf("%s", End);
348}
349
350void Fuzzer::PrintFinalStats() {
351 if (Options.PrintCoverage)
352 TPC.PrintCoverage();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000353 if (Options.PrintCorpusStats)
354 Corpus.PrintStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000355 if (!Options.PrintFinalStats)
356 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000357 size_t ExecPerSec = execPerSec();
358 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
359 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
360 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
361 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
362 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
363}
364
365void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
366 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
367 assert(MaxInputLen);
368 this->MaxInputLen = MaxInputLen;
369 this->MaxMutationLen = MaxInputLen;
370 AllocateCurrentUnitData();
371 Printf("INFO: -max_len is not provided; "
372 "libFuzzer will not generate inputs larger than %zd bytes\n",
373 MaxInputLen);
374}
375
376void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
377 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
378 this->MaxMutationLen = MaxMutationLen;
379}
380
381void Fuzzer::CheckExitOnSrcPosOrItem() {
382 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000383 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000384 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000385 if (!PCsSet->insert(PC).second)
386 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000387 std::string Descr = DescribePC("%F %L", PC + 1);
388 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
389 Printf("INFO: found line matching '%s', exiting.\n",
390 Options.ExitOnSrcPos.c_str());
391 _Exit(0);
392 }
393 };
394 TPC.ForEachObservedPC(HandlePC);
395 }
396 if (!Options.ExitOnItem.empty()) {
397 if (Corpus.HasUnit(Options.ExitOnItem)) {
398 Printf("INFO: found item with checksum '%s', exiting.\n",
399 Options.ExitOnItem.c_str());
400 _Exit(0);
401 }
402 }
403}
404
405void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000406 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
407 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000408 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000409 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
410 &EpochOfLastReadOfOutputCorpus, MaxSize,
411 /*ExitOnError*/ false);
412 if (Options.Verbosity >= 2)
413 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
414 bool Reloaded = false;
415 for (auto &U : AdditionalCorpus) {
416 if (U.size() > MaxSize)
417 U.resize(MaxSize);
418 if (!Corpus.HasUnit(U)) {
419 if (RunOne(U.data(), U.size())) {
420 CheckExitOnSrcPosOrItem();
421 Reloaded = true;
422 }
423 }
424 }
425 if (Reloaded)
426 PrintStats("RELOAD");
427}
428
george.karpenkov29efa6d2017-08-21 23:25:50 +0000429void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
430 auto TimeOfUnit =
431 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
432 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
433 secondsSinceProcessStartUp() >= 2)
434 PrintStats("pulse ");
435 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
436 TimeOfUnit >= Options.ReportSlowUnits) {
437 TimeOfLongestUnitInSeconds = TimeOfUnit;
438 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
439 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
440 }
441}
442
443bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000444 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000445 if (!Size)
446 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000447
448 ExecuteCallback(Data, Size);
449
450 UniqFeatureSetTmp.clear();
451 size_t FoundUniqFeaturesOfII = 0;
452 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
453 TPC.CollectFeatures([&](size_t Feature) {
kcc1f5638d2017-12-08 22:21:42 +0000454 if (Options.UseFeatureFrequency)
455 Corpus.UpdateFeatureFrequency(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000456 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
457 UniqFeatureSetTmp.push_back(Feature);
458 if (Options.ReduceInputs && II)
459 if (std::binary_search(II->UniqFeatureSet.begin(),
460 II->UniqFeatureSet.end(), Feature))
461 FoundUniqFeaturesOfII++;
462 });
kccb6836be2017-12-01 19:18:38 +0000463 if (FoundUniqFeatures)
464 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000465 PrintPulseAndReportSlowInput(Data, Size);
466 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
467 if (NumNewFeatures) {
468 TPC.UpdateObservedPCs();
469 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
kcc3acbe072018-05-16 23:26:37 +0000470 TPC.ObservedFocusFunction(),
george.karpenkov29efa6d2017-08-21 23:25:50 +0000471 UniqFeatureSetTmp);
472 return true;
473 }
474 if (II && FoundUniqFeaturesOfII &&
475 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
476 II->U.size() > Size) {
477 Corpus.Replace(II, {Data, Data + Size});
478 return true;
479 }
480 return false;
481}
482
483size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
484 assert(InFuzzingThread());
485 *Data = CurrentUnitData;
486 return CurrentUnitSize;
487}
488
489void Fuzzer::CrashOnOverwrittenData() {
490 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
491 GetPid());
492 DumpCurrentUnit("crash-");
493 Printf("SUMMARY: libFuzzer: out-of-memory\n");
494 _Exit(Options.ErrorExitCode); // Stop right now.
495}
496
497// Compare two arrays, but not all bytes if the arrays are large.
498static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
499 const size_t Limit = 64;
500 if (Size <= 64)
501 return !memcmp(A, B, Size);
502 // Compare first and last Limit/2 bytes.
503 return !memcmp(A, B, Limit / 2) &&
504 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
505}
506
507void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
508 TPC.RecordInitialStack();
509 TotalNumberOfRuns++;
510 assert(InFuzzingThread());
511 if (SMR.IsClient())
512 SMR.WriteByteArray(Data, Size);
513 // We copy the contents of Unit into a separate heap buffer
514 // so that we reliably find buffer overflows in it.
515 uint8_t *DataCopy = new uint8_t[Size];
516 memcpy(DataCopy, Data, Size);
517 if (CurrentUnitData && CurrentUnitData != Data)
518 memcpy(CurrentUnitData, Data, Size);
519 CurrentUnitSize = Size;
520 AllocTracer.Start(Options.TraceMalloc);
521 UnitStartTime = system_clock::now();
522 TPC.ResetMaps();
523 RunningCB = true;
524 int Res = CB(DataCopy, Size);
525 RunningCB = false;
526 UnitStopTime = system_clock::now();
527 (void)Res;
528 assert(Res == 0);
529 HasMoreMallocsThanFrees = AllocTracer.Stop();
530 if (!LooseMemeq(DataCopy, Data, Size))
531 CrashOnOverwrittenData();
532 CurrentUnitSize = 0;
533 delete[] DataCopy;
534}
535
536void Fuzzer::WriteToOutputCorpus(const Unit &U) {
537 if (Options.OnlyASCII)
538 assert(IsASCII(U));
539 if (Options.OutputCorpus.empty())
540 return;
541 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
542 WriteToFile(U, Path);
543 if (Options.Verbosity >= 2)
544 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
545}
546
547void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
548 if (!Options.SaveArtifacts)
549 return;
550 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
551 if (!Options.ExactArtifactPath.empty())
552 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
553 WriteToFile(U, Path);
554 Printf("artifact_prefix='%s'; Test unit written to %s\n",
555 Options.ArtifactPrefix.c_str(), Path.c_str());
556 if (U.size() <= kMaxUnitSizeToPrint)
557 Printf("Base64: %s\n", Base64(U).c_str());
558}
559
560void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
561 if (!Options.PrintNEW)
562 return;
563 PrintStats(Text, "");
564 if (Options.Verbosity) {
565 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
566 MD.PrintMutationSequence();
567 Printf("\n");
568 }
569}
570
571void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
572 II->NumSuccessfullMutations++;
573 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000574 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000575 WriteToOutputCorpus(U);
576 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000577 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000578 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000579}
580
581// Tries detecting a memory leak on the particular input that we have just
582// executed before calling this function.
583void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
584 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000585 if (!HasMoreMallocsThanFrees)
586 return; // mallocs==frees, a leak is unlikely.
587 if (!Options.DetectLeaks)
588 return;
dor1s38279cb2017-09-12 02:01:54 +0000589 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000590 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
591 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000592 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
593 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000594 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000595 // Run the target once again, but with lsan disabled so that if there is
596 // a real leak we do not report it twice.
597 EF->__lsan_disable();
598 ExecuteCallback(Data, Size);
599 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000600 if (!HasMoreMallocsThanFrees)
601 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000602 if (NumberOfLeakDetectionAttempts++ > 1000) {
603 Options.DetectLeaks = false;
604 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
605 " Most likely the target function accumulates allocated\n"
606 " memory in a global state w/o actually leaking it.\n"
607 " You may try running this binary with -trace_malloc=[12]"
608 " to get a trace of mallocs and frees.\n"
609 " If LeakSanitizer is enabled in this process it will still\n"
610 " run on the process shutdown.\n");
611 return;
612 }
613 // Now perform the actual lsan pass. This is expensive and we must ensure
614 // we don't call it too often.
615 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
616 if (DuringInitialCorpusExecution)
617 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
618 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
619 CurrentUnitSize = Size;
620 DumpCurrentUnit("leak-");
621 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000622 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000623 }
624}
625
626void Fuzzer::MutateAndTestOne() {
627 MD.StartMutationSequence();
628
629 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
kcc20fc0672017-10-11 01:44:26 +0000630 if (Options.UseFeatureFrequency)
631 Corpus.UpdateFeatureFrequencyScore(&II);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000632 const auto &U = II.U;
633 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
634 assert(CurrentUnitData);
635 size_t Size = U.size();
636 assert(Size <= MaxInputLen && "Oversized Unit");
637 memcpy(CurrentUnitData, U.data(), Size);
638
639 assert(MaxMutationLen > 0);
640
641 size_t CurrentMaxMutationLen =
642 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
643 assert(CurrentMaxMutationLen > 0);
644
645 for (int i = 0; i < Options.MutateDepth; i++) {
646 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
647 break;
kcc1239a992017-11-09 20:30:19 +0000648 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000649 size_t NewSize = 0;
650 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
651 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000652 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000653 Size = NewSize;
654 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000655
kccb6836be2017-12-01 19:18:38 +0000656 bool FoundUniqFeatures = false;
657 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
658 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000659 TryDetectingAMemoryLeak(CurrentUnitData, Size,
660 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000661 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000662 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000663 break; // We will mutate this input more in the next rounds.
664 }
665 if (Options.ReduceDepth && !FoundUniqFeatures)
666 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000667 }
668}
669
alekseyshld995b552017-10-23 22:04:30 +0000670void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000671 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000672 return;
alekseyshld995b552017-10-23 22:04:30 +0000673 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000674 LastAllocatorPurgeAttemptTime)
675 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000676 return;
alekseyshld995b552017-10-23 22:04:30 +0000677
678 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000679 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000680 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000681
682 LastAllocatorPurgeAttemptTime = system_clock::now();
683}
684
kcc2e93b3f2017-08-29 02:05:01 +0000685void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
686 const size_t kMaxSaneLen = 1 << 20;
687 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000688 Vector<SizedFile> SizedFiles;
689 size_t MaxSize = 0;
690 size_t MinSize = -1;
691 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000692 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000693 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000694 GetSizedFilesFromDir(Dir, &SizedFiles);
695 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
696 Dir.c_str());
697 LastNumFiles = SizedFiles.size();
698 }
699 for (auto &File : SizedFiles) {
700 MaxSize = Max(File.Size, MaxSize);
701 MinSize = Min(File.Size, MinSize);
702 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000703 }
kccdc00cd32017-08-29 20:51:24 +0000704 if (Options.MaxLen == 0)
705 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
706 assert(MaxInputLen > 0);
707
kcc2cd9f092017-10-13 01:12:23 +0000708 // Test the callback with empty input and never try it again.
709 uint8_t dummy = 0;
710 ExecuteCallback(&dummy, 0);
711
kccdc00cd32017-08-29 20:51:24 +0000712 if (SizedFiles.empty()) {
713 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
714 Unit U({'\n'}); // Valid ASCII input.
715 RunOne(U.data(), U.size());
716 } else {
717 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
718 " rss: %zdMb\n",
719 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
720 if (Options.ShuffleAtStartUp)
721 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
722
kcc7f5f2222017-09-12 21:58:07 +0000723 if (Options.PreferSmall) {
724 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
725 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
726 }
kccdc00cd32017-08-29 20:51:24 +0000727
728 // Load and execute inputs one by one.
729 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000730 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000731 assert(U.size() <= MaxInputLen);
732 RunOne(U.data(), U.size());
733 CheckExitOnSrcPosOrItem();
734 TryDetectingAMemoryLeak(U.data(), U.size(),
735 /*DuringInitialCorpusExecution*/ true);
736 }
kcc2e93b3f2017-08-29 02:05:01 +0000737 }
738
kccdc00cd32017-08-29 20:51:24 +0000739 PrintStats("INITED");
kcc3acbe072018-05-16 23:26:37 +0000740 if (!Options.FocusFunction.empty())
741 Printf("INFO: %zd/%zd inputs touch the focus function\n",
742 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
743
kccdc00cd32017-08-29 20:51:24 +0000744 if (Corpus.empty()) {
745 Printf("ERROR: no interesting inputs were found. "
746 "Is the code instrumented for coverage? Exiting.\n");
747 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000748 }
kcc2e93b3f2017-08-29 02:05:01 +0000749}
750
751void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
752 ReadAndExecuteSeedCorpora(CorpusDirs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000753 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000754 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000755 system_clock::time_point LastCorpusReload = system_clock::now();
756 if (Options.DoCrossOver)
757 MD.SetCorpus(&Corpus);
758 while (true) {
759 auto Now = system_clock::now();
760 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
761 Options.ReloadIntervalSec) {
762 RereadOutputCorpus(MaxInputLen);
763 LastCorpusReload = system_clock::now();
764 }
765 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
766 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000767 if (TimedOut())
768 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000769
770 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000771 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000772 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000773 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000774 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000775 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000776 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000777 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000778 }
779 } else {
780 TmpMaxMutationLen = MaxMutationLen;
781 }
782
783 // Perform several mutations and runs.
784 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000785
786 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000787 }
788
789 PrintStats("DONE ", "\n");
790 MD.PrintRecommendedDictionary();
791}
792
793void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000794 if (U.size() <= 1)
795 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000796 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
797 MD.StartMutationSequence();
798 memcpy(CurrentUnitData, U.data(), U.size());
799 for (int i = 0; i < Options.MutateDepth; i++) {
800 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
801 assert(NewSize > 0 && NewSize <= MaxMutationLen);
802 ExecuteCallback(CurrentUnitData, NewSize);
803 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
804 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
805 /*DuringInitialCorpusExecution*/ false);
806 }
807 }
808}
809
810void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
811 if (SMR.IsServer()) {
812 SMR.WriteByteArray(Data, Size);
813 } else if (SMR.IsClient()) {
814 SMR.PostClient();
815 SMR.WaitServer();
816 size_t OtherSize = SMR.ReadByteArraySize();
817 uint8_t *OtherData = SMR.GetByteArray();
818 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
819 size_t i = 0;
820 for (i = 0; i < Min(Size, OtherSize); i++)
821 if (Data[i] != OtherData[i])
822 break;
823 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000824 "offset %zd\n",
825 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000826 DumpCurrentUnit("mismatch-");
827 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
828 PrintFinalStats();
829 _Exit(Options.ErrorExitCode);
830 }
831 }
832}
833
834} // namespace fuzzer
835
836extern "C" {
837
phosek966475e2018-01-17 20:39:14 +0000838__attribute__((visibility("default"))) size_t
839LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000840 assert(fuzzer::F);
841 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
842}
843
844// Experimental
phosek966475e2018-01-17 20:39:14 +0000845__attribute__((visibility("default"))) void
846LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000847 assert(fuzzer::F);
848 fuzzer::F->AnnounceOutput(Data, Size);
849}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000850} // extern "C"