blob: 1a2276fd19bb28321521c838e1a7e12981d34819 [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);
kcc3850d062018-07-03 22:33:09 +0000151 TPC.SetUseValueProfileMask(Options.UseValueProfile);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000152
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();
morehousecfe1f442018-07-09 20:17:52 +0000358 if (Options.PrintMutationStats)
359 MD.PrintMutationStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000360 if (!Options.PrintFinalStats)
361 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000362 size_t ExecPerSec = execPerSec();
363 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
364 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
365 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
366 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
367 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
368}
369
370void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
371 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
372 assert(MaxInputLen);
373 this->MaxInputLen = MaxInputLen;
374 this->MaxMutationLen = MaxInputLen;
375 AllocateCurrentUnitData();
376 Printf("INFO: -max_len is not provided; "
377 "libFuzzer will not generate inputs larger than %zd bytes\n",
378 MaxInputLen);
379}
380
381void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
382 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
383 this->MaxMutationLen = MaxMutationLen;
384}
385
386void Fuzzer::CheckExitOnSrcPosOrItem() {
387 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000388 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000389 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000390 if (!PCsSet->insert(PC).second)
391 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000392 std::string Descr = DescribePC("%F %L", PC + 1);
393 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
394 Printf("INFO: found line matching '%s', exiting.\n",
395 Options.ExitOnSrcPos.c_str());
396 _Exit(0);
397 }
398 };
399 TPC.ForEachObservedPC(HandlePC);
400 }
401 if (!Options.ExitOnItem.empty()) {
402 if (Corpus.HasUnit(Options.ExitOnItem)) {
403 Printf("INFO: found item with checksum '%s', exiting.\n",
404 Options.ExitOnItem.c_str());
405 _Exit(0);
406 }
407 }
408}
409
410void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000411 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
412 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000413 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000414 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
415 &EpochOfLastReadOfOutputCorpus, MaxSize,
416 /*ExitOnError*/ false);
417 if (Options.Verbosity >= 2)
418 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
419 bool Reloaded = false;
420 for (auto &U : AdditionalCorpus) {
421 if (U.size() > MaxSize)
422 U.resize(MaxSize);
423 if (!Corpus.HasUnit(U)) {
424 if (RunOne(U.data(), U.size())) {
425 CheckExitOnSrcPosOrItem();
426 Reloaded = true;
427 }
428 }
429 }
430 if (Reloaded)
431 PrintStats("RELOAD");
432}
433
george.karpenkov29efa6d2017-08-21 23:25:50 +0000434void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
435 auto TimeOfUnit =
436 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
437 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
438 secondsSinceProcessStartUp() >= 2)
439 PrintStats("pulse ");
440 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
441 TimeOfUnit >= Options.ReportSlowUnits) {
442 TimeOfLongestUnitInSeconds = TimeOfUnit;
443 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
444 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
445 }
446}
447
448bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000449 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000450 if (!Size)
451 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000452
453 ExecuteCallback(Data, Size);
454
455 UniqFeatureSetTmp.clear();
456 size_t FoundUniqFeaturesOfII = 0;
457 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
458 TPC.CollectFeatures([&](size_t Feature) {
459 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
460 UniqFeatureSetTmp.push_back(Feature);
461 if (Options.ReduceInputs && II)
462 if (std::binary_search(II->UniqFeatureSet.begin(),
463 II->UniqFeatureSet.end(), Feature))
464 FoundUniqFeaturesOfII++;
465 });
kccb6836be2017-12-01 19:18:38 +0000466 if (FoundUniqFeatures)
467 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000468 PrintPulseAndReportSlowInput(Data, Size);
469 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
470 if (NumNewFeatures) {
471 TPC.UpdateObservedPCs();
472 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
kcc3acbe072018-05-16 23:26:37 +0000473 TPC.ObservedFocusFunction(),
kccadf188b2018-06-07 01:40:20 +0000474 UniqFeatureSetTmp, DFT);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000475 return true;
476 }
477 if (II && FoundUniqFeaturesOfII &&
kccadf188b2018-06-07 01:40:20 +0000478 II->DataFlowTraceForFocusFunction.empty() &&
george.karpenkov29efa6d2017-08-21 23:25:50 +0000479 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
480 II->U.size() > Size) {
481 Corpus.Replace(II, {Data, Data + Size});
482 return true;
483 }
484 return false;
485}
486
487size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
488 assert(InFuzzingThread());
489 *Data = CurrentUnitData;
490 return CurrentUnitSize;
491}
492
493void Fuzzer::CrashOnOverwrittenData() {
494 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
495 GetPid());
496 DumpCurrentUnit("crash-");
497 Printf("SUMMARY: libFuzzer: out-of-memory\n");
498 _Exit(Options.ErrorExitCode); // Stop right now.
499}
500
501// Compare two arrays, but not all bytes if the arrays are large.
502static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
503 const size_t Limit = 64;
504 if (Size <= 64)
505 return !memcmp(A, B, Size);
506 // Compare first and last Limit/2 bytes.
507 return !memcmp(A, B, Limit / 2) &&
508 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
509}
510
511void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
512 TPC.RecordInitialStack();
513 TotalNumberOfRuns++;
514 assert(InFuzzingThread());
515 if (SMR.IsClient())
516 SMR.WriteByteArray(Data, Size);
517 // We copy the contents of Unit into a separate heap buffer
518 // so that we reliably find buffer overflows in it.
519 uint8_t *DataCopy = new uint8_t[Size];
520 memcpy(DataCopy, Data, Size);
521 if (CurrentUnitData && CurrentUnitData != Data)
522 memcpy(CurrentUnitData, Data, Size);
523 CurrentUnitSize = Size;
524 AllocTracer.Start(Options.TraceMalloc);
525 UnitStartTime = system_clock::now();
526 TPC.ResetMaps();
527 RunningCB = true;
528 int Res = CB(DataCopy, Size);
529 RunningCB = false;
530 UnitStopTime = system_clock::now();
531 (void)Res;
532 assert(Res == 0);
533 HasMoreMallocsThanFrees = AllocTracer.Stop();
534 if (!LooseMemeq(DataCopy, Data, Size))
535 CrashOnOverwrittenData();
536 CurrentUnitSize = 0;
537 delete[] DataCopy;
538}
539
540void Fuzzer::WriteToOutputCorpus(const Unit &U) {
541 if (Options.OnlyASCII)
542 assert(IsASCII(U));
543 if (Options.OutputCorpus.empty())
544 return;
545 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
546 WriteToFile(U, Path);
547 if (Options.Verbosity >= 2)
548 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
549}
550
551void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
552 if (!Options.SaveArtifacts)
553 return;
554 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
555 if (!Options.ExactArtifactPath.empty())
556 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
557 WriteToFile(U, Path);
558 Printf("artifact_prefix='%s'; Test unit written to %s\n",
559 Options.ArtifactPrefix.c_str(), Path.c_str());
560 if (U.size() <= kMaxUnitSizeToPrint)
561 Printf("Base64: %s\n", Base64(U).c_str());
562}
563
564void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
565 if (!Options.PrintNEW)
566 return;
567 PrintStats(Text, "");
568 if (Options.Verbosity) {
569 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
570 MD.PrintMutationSequence();
571 Printf("\n");
572 }
573}
574
575void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
576 II->NumSuccessfullMutations++;
577 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000578 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000579 WriteToOutputCorpus(U);
580 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000581 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000582 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000583}
584
585// Tries detecting a memory leak on the particular input that we have just
586// executed before calling this function.
587void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
588 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000589 if (!HasMoreMallocsThanFrees)
590 return; // mallocs==frees, a leak is unlikely.
591 if (!Options.DetectLeaks)
592 return;
dor1s38279cb2017-09-12 02:01:54 +0000593 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000594 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
595 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000596 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
597 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000598 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000599 // Run the target once again, but with lsan disabled so that if there is
600 // a real leak we do not report it twice.
601 EF->__lsan_disable();
602 ExecuteCallback(Data, Size);
603 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000604 if (!HasMoreMallocsThanFrees)
605 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000606 if (NumberOfLeakDetectionAttempts++ > 1000) {
607 Options.DetectLeaks = false;
608 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
609 " Most likely the target function accumulates allocated\n"
610 " memory in a global state w/o actually leaking it.\n"
611 " You may try running this binary with -trace_malloc=[12]"
612 " to get a trace of mallocs and frees.\n"
613 " If LeakSanitizer is enabled in this process it will still\n"
614 " run on the process shutdown.\n");
615 return;
616 }
617 // Now perform the actual lsan pass. This is expensive and we must ensure
618 // we don't call it too often.
619 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
620 if (DuringInitialCorpusExecution)
621 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
622 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
623 CurrentUnitSize = Size;
624 DumpCurrentUnit("leak-");
625 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000626 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000627 }
628}
629
630void Fuzzer::MutateAndTestOne() {
631 MD.StartMutationSequence();
632
633 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
634 const auto &U = II.U;
635 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
636 assert(CurrentUnitData);
637 size_t Size = U.size();
638 assert(Size <= MaxInputLen && "Oversized Unit");
639 memcpy(CurrentUnitData, U.data(), Size);
640
641 assert(MaxMutationLen > 0);
642
643 size_t CurrentMaxMutationLen =
644 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
645 assert(CurrentMaxMutationLen > 0);
646
647 for (int i = 0; i < Options.MutateDepth; i++) {
648 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
649 break;
kcc1239a992017-11-09 20:30:19 +0000650 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000651 size_t NewSize = 0;
652 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
653 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000654 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000655 Size = NewSize;
656 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000657
kccb6836be2017-12-01 19:18:38 +0000658 bool FoundUniqFeatures = false;
659 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
660 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000661 TryDetectingAMemoryLeak(CurrentUnitData, Size,
662 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000663 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000664 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000665 break; // We will mutate this input more in the next rounds.
666 }
667 if (Options.ReduceDepth && !FoundUniqFeatures)
668 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000669 }
670}
671
alekseyshld995b552017-10-23 22:04:30 +0000672void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000673 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000674 return;
alekseyshld995b552017-10-23 22:04:30 +0000675 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000676 LastAllocatorPurgeAttemptTime)
677 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000678 return;
alekseyshld995b552017-10-23 22:04:30 +0000679
680 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000681 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000682 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000683
684 LastAllocatorPurgeAttemptTime = system_clock::now();
685}
686
kcc2e93b3f2017-08-29 02:05:01 +0000687void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
688 const size_t kMaxSaneLen = 1 << 20;
689 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000690 Vector<SizedFile> SizedFiles;
691 size_t MaxSize = 0;
692 size_t MinSize = -1;
693 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000694 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000695 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000696 GetSizedFilesFromDir(Dir, &SizedFiles);
697 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
698 Dir.c_str());
699 LastNumFiles = SizedFiles.size();
700 }
701 for (auto &File : SizedFiles) {
702 MaxSize = Max(File.Size, MaxSize);
703 MinSize = Min(File.Size, MinSize);
704 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000705 }
kccdc00cd32017-08-29 20:51:24 +0000706 if (Options.MaxLen == 0)
707 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
708 assert(MaxInputLen > 0);
709
kcc2cd9f092017-10-13 01:12:23 +0000710 // Test the callback with empty input and never try it again.
711 uint8_t dummy = 0;
712 ExecuteCallback(&dummy, 0);
713
kccdc00cd32017-08-29 20:51:24 +0000714 if (SizedFiles.empty()) {
715 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
716 Unit U({'\n'}); // Valid ASCII input.
717 RunOne(U.data(), U.size());
718 } else {
719 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
720 " rss: %zdMb\n",
721 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
722 if (Options.ShuffleAtStartUp)
723 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
724
kcc7f5f2222017-09-12 21:58:07 +0000725 if (Options.PreferSmall) {
726 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
727 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
728 }
kccdc00cd32017-08-29 20:51:24 +0000729
730 // Load and execute inputs one by one.
731 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000732 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000733 assert(U.size() <= MaxInputLen);
734 RunOne(U.data(), U.size());
735 CheckExitOnSrcPosOrItem();
736 TryDetectingAMemoryLeak(U.data(), U.size(),
737 /*DuringInitialCorpusExecution*/ true);
738 }
kcc2e93b3f2017-08-29 02:05:01 +0000739 }
740
kccdc00cd32017-08-29 20:51:24 +0000741 PrintStats("INITED");
kcc3acbe072018-05-16 23:26:37 +0000742 if (!Options.FocusFunction.empty())
743 Printf("INFO: %zd/%zd inputs touch the focus function\n",
744 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
kccadf188b2018-06-07 01:40:20 +0000745 if (!Options.DataFlowTrace.empty())
746 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
747 Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
kcc3acbe072018-05-16 23:26:37 +0000748
dor1s770a9bc2018-05-23 19:42:30 +0000749 if (Corpus.empty() && Options.MaxNumberOfRuns) {
kccdc00cd32017-08-29 20:51:24 +0000750 Printf("ERROR: no interesting inputs were found. "
751 "Is the code instrumented for coverage? Exiting.\n");
752 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000753 }
kcc2e93b3f2017-08-29 02:05:01 +0000754}
755
756void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
757 ReadAndExecuteSeedCorpora(CorpusDirs);
kccadf188b2018-06-07 01:40:20 +0000758 DFT.Clear(); // No need for DFT any more.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000759 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000760 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000761 system_clock::time_point LastCorpusReload = system_clock::now();
762 if (Options.DoCrossOver)
763 MD.SetCorpus(&Corpus);
764 while (true) {
765 auto Now = system_clock::now();
766 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
767 Options.ReloadIntervalSec) {
768 RereadOutputCorpus(MaxInputLen);
769 LastCorpusReload = system_clock::now();
770 }
771 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
772 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000773 if (TimedOut())
774 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000775
776 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000777 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000778 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000779 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000780 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000781 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000782 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000783 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000784 }
785 } else {
786 TmpMaxMutationLen = MaxMutationLen;
787 }
788
789 // Perform several mutations and runs.
790 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000791
792 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000793 }
794
795 PrintStats("DONE ", "\n");
796 MD.PrintRecommendedDictionary();
797}
798
799void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000800 if (U.size() <= 1)
801 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000802 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
803 MD.StartMutationSequence();
804 memcpy(CurrentUnitData, U.data(), U.size());
805 for (int i = 0; i < Options.MutateDepth; i++) {
806 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
807 assert(NewSize > 0 && NewSize <= MaxMutationLen);
808 ExecuteCallback(CurrentUnitData, NewSize);
809 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
810 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
811 /*DuringInitialCorpusExecution*/ false);
812 }
813 }
814}
815
816void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
817 if (SMR.IsServer()) {
818 SMR.WriteByteArray(Data, Size);
819 } else if (SMR.IsClient()) {
820 SMR.PostClient();
821 SMR.WaitServer();
822 size_t OtherSize = SMR.ReadByteArraySize();
823 uint8_t *OtherData = SMR.GetByteArray();
824 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
825 size_t i = 0;
826 for (i = 0; i < Min(Size, OtherSize); i++)
827 if (Data[i] != OtherData[i])
828 break;
829 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000830 "offset %zd\n",
831 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000832 DumpCurrentUnit("mismatch-");
833 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
834 PrintFinalStats();
835 _Exit(Options.ErrorExitCode);
836 }
837 }
838}
839
840} // namespace fuzzer
841
842extern "C" {
843
phosek966475e2018-01-17 20:39:14 +0000844__attribute__((visibility("default"))) size_t
845LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000846 assert(fuzzer::F);
847 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
848}
849
850// Experimental
phosek966475e2018-01-17 20:39:14 +0000851__attribute__((visibility("default"))) void
852LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000853 assert(fuzzer::F);
854 fuzzer::F->AnnounceOutput(Data, Size);
855}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000856} // extern "C"