blob: 08b54553792f68b2598e8190a5ec0d2bd178d738 [file] [log] [blame]
George Karpenkov10ab2ac2017-08-21 23:25:501//===- 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>
Vitaly Buka7dbc1d82017-11-01 03:02:5922#include <mutex>
George Karpenkov10ab2ac2017-08-21 23:25:5023#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;
Vitaly Buka7d223242017-11-02 04:12:1073
74 std::recursive_mutex TraceMutex;
75 bool TraceDisabled = false;
George Karpenkov10ab2ac2017-08-21 23:25:5076};
77
78static MallocFreeTracer AllocTracer;
79
Vitaly Buka7d223242017-11-02 04:12:1080// 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};
Vitaly Buka7dbc1d82017-11-01 03:02:5997
George Karpenkov10ab2ac2017-08-21 23:25:5098ATTRIBUTE_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) {
Vitaly Buka7d223242017-11-02 04:12:10103 TraceLock Lock;
104 if (Lock.IsDisabled())
105 return;
George Karpenkov10ab2ac2017-08-21 23:25:50106 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
107 if (TraceLevel >= 2 && EF)
Matt Morehouse14cf71a2018-05-08 23:45:05108 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50109 }
110}
111
112ATTRIBUTE_NO_SANITIZE_MEMORY
113void FreeHook(const volatile void *ptr) {
114 size_t N = AllocTracer.Frees++;
115 if (int TraceLevel = AllocTracer.TraceLevel) {
Vitaly Buka7d223242017-11-02 04:12:10116 TraceLock Lock;
117 if (Lock.IsDisabled())
118 return;
George Karpenkov10ab2ac2017-08-21 23:25:50119 Printf("FREE[%zd] %p\n", N, ptr);
120 if (TraceLevel >= 2 && EF)
Matt Morehouse14cf71a2018-05-08 23:45:05121 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50122 }
123}
124
125// Crash on a single malloc that exceeds the rss limit.
126void Fuzzer::HandleMalloc(size_t Size) {
Kostya Serebryanyde9bafb2017-12-01 22:12:04127 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
George Karpenkov10ab2ac2017-08-21 23:25:50128 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");
Matt Morehouse14cf71a2018-05-08 23:45:05132 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50133 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);
Kostya Serebryany51ddb882018-07-03 22:33:09151 TPC.SetUseValueProfileMask(Options.UseValueProfile);
George Karpenkov10ab2ac2017-08-21 23:25:50152
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));
Kostya Serebryanye9c6f062018-05-16 23:26:37162 TPC.SetFocusFunction(Options.FocusFunction);
Kostya Serebryany1fd005f2018-06-06 01:23:29163 DFT.Init(Options.DataFlowTrace, Options.FocusFunction);
George Karpenkov10ab2ac2017-08-21 23:25:50164}
165
Alex Shlyapnikov5ded0702017-10-23 23:24:33166Fuzzer::~Fuzzer() {}
George Karpenkov10ab2ac2017-08-21 23:25:50167
168void Fuzzer::AllocateCurrentUnitData() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33169 if (CurrentUnitData || MaxInputLen == 0)
170 return;
George Karpenkov10ab2ac2017-08-21 23:25:50171 CurrentUnitData = new uint8_t[MaxInputLen];
172}
173
174void Fuzzer::StaticDeathCallback() {
175 assert(F);
176 F->DeathCallback();
177}
178
179void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33180 if (!CurrentUnitData)
181 return; // Happens when running individual inputs.
Matt Morehousea34c65e2018-07-09 23:51:08182 ScopedDisableMsanInterceptorChecks S;
George Karpenkov10ab2ac2017-08-21 23:25:50183 MD.PrintMutationSequence();
184 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
185 size_t UnitSize = CurrentUnitSize;
186 if (UnitSize <= kMaxUnitSizeToPrint) {
187 PrintHexArray(CurrentUnitData, UnitSize, "\n");
188 PrintASCII(CurrentUnitData, UnitSize, "\n");
189 }
190 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
191 Prefix);
192}
193
194NO_SANITIZE_MEMORY
195void Fuzzer::DeathCallback() {
196 DumpCurrentUnit("crash-");
197 PrintFinalStats();
198}
199
200void Fuzzer::StaticAlarmCallback() {
201 assert(F);
202 F->AlarmCallback();
203}
204
205void Fuzzer::StaticCrashSignalCallback() {
206 assert(F);
207 F->CrashCallback();
208}
209
210void Fuzzer::StaticExitCallback() {
211 assert(F);
212 F->ExitCallback();
213}
214
215void Fuzzer::StaticInterruptCallback() {
216 assert(F);
217 F->InterruptCallback();
218}
219
Kostya Serebryanya2ca2dc2017-11-09 20:30:19220void Fuzzer::StaticGracefulExitCallback() {
221 assert(F);
222 F->GracefulExitRequested = true;
223 Printf("INFO: signal received, trying to exit gracefully\n");
224}
225
George Karpenkov10ab2ac2017-08-21 23:25:50226void Fuzzer::StaticFileSizeExceedCallback() {
227 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
228 exit(1);
229}
230
231void Fuzzer::CrashCallback() {
Matt Morehouse7764a042018-05-02 02:55:28232 if (EF->__sanitizer_acquire_crash_state)
233 EF->__sanitizer_acquire_crash_state();
George Karpenkov10ab2ac2017-08-21 23:25:50234 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
Matt Morehouse14cf71a2018-05-08 23:45:05235 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50236 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
237 " Combine libFuzzer with AddressSanitizer or similar for better "
238 "crash reports.\n");
239 Printf("SUMMARY: libFuzzer: deadly signal\n");
240 DumpCurrentUnit("crash-");
241 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33242 _Exit(Options.ErrorExitCode); // Stop right now.
George Karpenkov10ab2ac2017-08-21 23:25:50243}
244
245void Fuzzer::ExitCallback() {
246 if (!RunningCB)
247 return; // This exit did not come from the user callback
Matt Morehouse52fd1692018-05-01 21:01:53248 if (EF->__sanitizer_acquire_crash_state &&
249 !EF->__sanitizer_acquire_crash_state())
250 return;
George Karpenkov10ab2ac2017-08-21 23:25:50251 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
Matt Morehouse14cf71a2018-05-08 23:45:05252 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50253 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
254 DumpCurrentUnit("crash-");
255 PrintFinalStats();
256 _Exit(Options.ErrorExitCode);
257}
258
Kostya Serebryanya2ca2dc2017-11-09 20:30:19259void Fuzzer::MaybeExitGracefully() {
260 if (!GracefulExitRequested) return;
261 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
262 PrintFinalStats();
263 _Exit(0);
264}
265
George Karpenkov10ab2ac2017-08-21 23:25:50266void Fuzzer::InterruptCallback() {
267 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
268 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33269 _Exit(0); // Stop right now, don't perform any at-exit actions.
George Karpenkov10ab2ac2017-08-21 23:25:50270}
271
272NO_SANITIZE_MEMORY
273void Fuzzer::AlarmCallback() {
274 assert(Options.UnitTimeoutSec > 0);
275 // In Windows Alarm callback is executed by a different thread.
276#if !LIBFUZZER_WINDOWS
Alex Shlyapnikov5ded0702017-10-23 23:24:33277 if (!InFuzzingThread())
278 return;
George Karpenkov10ab2ac2017-08-21 23:25:50279#endif
280 if (!RunningCB)
281 return; // We have not started running units yet.
282 size_t Seconds =
283 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
284 if (Seconds == 0)
285 return;
286 if (Options.Verbosity >= 2)
287 Printf("AlarmCallback %zd\n", Seconds);
288 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Matt Morehouse52fd1692018-05-01 21:01:53289 if (EF->__sanitizer_acquire_crash_state &&
290 !EF->__sanitizer_acquire_crash_state())
291 return;
George Karpenkov10ab2ac2017-08-21 23:25:50292 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
293 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
294 Options.UnitTimeoutSec);
295 DumpCurrentUnit("timeout-");
296 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
297 Seconds);
Matt Morehouse14cf71a2018-05-08 23:45:05298 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50299 Printf("SUMMARY: libFuzzer: timeout\n");
300 PrintFinalStats();
301 _Exit(Options.TimeoutExitCode); // Stop right now.
302 }
303}
304
305void Fuzzer::RssLimitCallback() {
Matt Morehouse52fd1692018-05-01 21:01:53306 if (EF->__sanitizer_acquire_crash_state &&
307 !EF->__sanitizer_acquire_crash_state())
308 return;
George Karpenkov10ab2ac2017-08-21 23:25:50309 Printf(
310 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
311 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
312 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Matt Morehouse14cf71a2018-05-08 23:45:05313 PrintMemoryProfile();
George Karpenkov10ab2ac2017-08-21 23:25:50314 DumpCurrentUnit("oom-");
315 Printf("SUMMARY: libFuzzer: out-of-memory\n");
316 PrintFinalStats();
317 _Exit(Options.ErrorExitCode); // Stop right now.
318}
319
320void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
321 size_t ExecPerSec = execPerSec();
322 if (!Options.Verbosity)
323 return;
324 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
325 if (size_t N = TPC.GetTotalPCCoverage())
326 Printf(" cov: %zd", N);
327 if (size_t N = Corpus.NumFeatures())
Alex Shlyapnikov5ded0702017-10-23 23:24:33328 Printf(" ft: %zd", N);
George Karpenkov10ab2ac2017-08-21 23:25:50329 if (!Corpus.empty()) {
330 Printf(" corp: %zd", Corpus.NumActiveUnits());
331 if (size_t N = Corpus.SizeInBytes()) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33332 if (N < (1 << 14))
George Karpenkov10ab2ac2017-08-21 23:25:50333 Printf("/%zdb", N);
334 else if (N < (1 << 24))
335 Printf("/%zdKb", N >> 10);
336 else
337 Printf("/%zdMb", N >> 20);
338 }
Kostya Serebryanye9c6f062018-05-16 23:26:37339 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
340 Printf(" focus: %zd", FF);
George Karpenkov10ab2ac2017-08-21 23:25:50341 }
Matt Morehouseddf352b2018-02-22 19:00:17342 if (TmpMaxMutationLen)
343 Printf(" lim: %zd", TmpMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50344 if (Units)
345 Printf(" units: %zd", Units);
346
347 Printf(" exec/s: %zd", ExecPerSec);
348 Printf(" rss: %zdMb", GetPeakRSSMb());
349 Printf("%s", End);
350}
351
352void Fuzzer::PrintFinalStats() {
353 if (Options.PrintCoverage)
354 TPC.PrintCoverage();
Kostya Serebryany69c2b712018-05-21 19:47:00355 if (Options.DumpCoverage)
356 TPC.DumpCoverage();
George Karpenkov10ab2ac2017-08-21 23:25:50357 if (Options.PrintCorpusStats)
358 Corpus.PrintStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33359 if (!Options.PrintFinalStats)
360 return;
George Karpenkov10ab2ac2017-08-21 23:25:50361 size_t ExecPerSec = execPerSec();
362 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
363 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
364 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
365 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
366 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
367}
368
369void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
370 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
371 assert(MaxInputLen);
372 this->MaxInputLen = MaxInputLen;
373 this->MaxMutationLen = MaxInputLen;
374 AllocateCurrentUnitData();
375 Printf("INFO: -max_len is not provided; "
376 "libFuzzer will not generate inputs larger than %zd bytes\n",
377 MaxInputLen);
378}
379
380void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
381 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
382 this->MaxMutationLen = MaxMutationLen;
383}
384
385void Fuzzer::CheckExitOnSrcPosOrItem() {
386 if (!Options.ExitOnSrcPos.empty()) {
George Karpenkovbebcbfb2017-08-27 23:20:09387 static auto *PCsSet = new Set<uintptr_t>;
George Karpenkov10ab2ac2017-08-21 23:25:50388 auto HandlePC = [&](uintptr_t PC) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33389 if (!PCsSet->insert(PC).second)
390 return;
George Karpenkov10ab2ac2017-08-21 23:25:50391 std::string Descr = DescribePC("%F %L", PC + 1);
392 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
393 Printf("INFO: found line matching '%s', exiting.\n",
394 Options.ExitOnSrcPos.c_str());
395 _Exit(0);
396 }
397 };
398 TPC.ForEachObservedPC(HandlePC);
399 }
400 if (!Options.ExitOnItem.empty()) {
401 if (Corpus.HasUnit(Options.ExitOnItem)) {
402 Printf("INFO: found item with checksum '%s', exiting.\n",
403 Options.ExitOnItem.c_str());
404 _Exit(0);
405 }
406 }
407}
408
409void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33410 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
411 return;
George Karpenkovbebcbfb2017-08-27 23:20:09412 Vector<Unit> AdditionalCorpus;
George Karpenkov10ab2ac2017-08-21 23:25:50413 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
414 &EpochOfLastReadOfOutputCorpus, MaxSize,
415 /*ExitOnError*/ false);
416 if (Options.Verbosity >= 2)
417 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
418 bool Reloaded = false;
419 for (auto &U : AdditionalCorpus) {
420 if (U.size() > MaxSize)
421 U.resize(MaxSize);
422 if (!Corpus.HasUnit(U)) {
423 if (RunOne(U.data(), U.size())) {
424 CheckExitOnSrcPosOrItem();
425 Reloaded = true;
426 }
427 }
428 }
429 if (Reloaded)
430 PrintStats("RELOAD");
431}
432
George Karpenkov10ab2ac2017-08-21 23:25:50433void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
434 auto TimeOfUnit =
435 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
436 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
437 secondsSinceProcessStartUp() >= 2)
438 PrintStats("pulse ");
439 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
440 TimeOfUnit >= Options.ReportSlowUnits) {
441 TimeOfLongestUnitInSeconds = TimeOfUnit;
442 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
443 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
444 }
445}
446
447bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
Kostya Serebryanyad05ee02017-12-01 19:18:38448 InputInfo *II, bool *FoundUniqFeatures) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33449 if (!Size)
450 return false;
George Karpenkov10ab2ac2017-08-21 23:25:50451
452 ExecuteCallback(Data, Size);
453
454 UniqFeatureSetTmp.clear();
455 size_t FoundUniqFeaturesOfII = 0;
456 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
457 TPC.CollectFeatures([&](size_t Feature) {
George Karpenkov10ab2ac2017-08-21 23:25:50458 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
459 UniqFeatureSetTmp.push_back(Feature);
460 if (Options.ReduceInputs && II)
461 if (std::binary_search(II->UniqFeatureSet.begin(),
462 II->UniqFeatureSet.end(), Feature))
463 FoundUniqFeaturesOfII++;
464 });
Kostya Serebryanyad05ee02017-12-01 19:18:38465 if (FoundUniqFeatures)
466 *FoundUniqFeatures = FoundUniqFeaturesOfII;
George Karpenkov10ab2ac2017-08-21 23:25:50467 PrintPulseAndReportSlowInput(Data, Size);
468 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
469 if (NumNewFeatures) {
470 TPC.UpdateObservedPCs();
471 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
Kostya Serebryanye9c6f062018-05-16 23:26:37472 TPC.ObservedFocusFunction(),
Kostya Serebryany67af9922018-06-07 01:40:20473 UniqFeatureSetTmp, DFT);
George Karpenkov10ab2ac2017-08-21 23:25:50474 return true;
475 }
476 if (II && FoundUniqFeaturesOfII &&
Kostya Serebryany67af9922018-06-07 01:40:20477 II->DataFlowTraceForFocusFunction.empty() &&
George Karpenkov10ab2ac2017-08-21 23:25:50478 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
479 II->U.size() > Size) {
480 Corpus.Replace(II, {Data, Data + Size});
481 return true;
482 }
483 return false;
484}
485
486size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
487 assert(InFuzzingThread());
488 *Data = CurrentUnitData;
489 return CurrentUnitSize;
490}
491
492void Fuzzer::CrashOnOverwrittenData() {
493 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
494 GetPid());
495 DumpCurrentUnit("crash-");
496 Printf("SUMMARY: libFuzzer: out-of-memory\n");
497 _Exit(Options.ErrorExitCode); // Stop right now.
498}
499
500// Compare two arrays, but not all bytes if the arrays are large.
501static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
502 const size_t Limit = 64;
503 if (Size <= 64)
504 return !memcmp(A, B, Size);
505 // Compare first and last Limit/2 bytes.
506 return !memcmp(A, B, Limit / 2) &&
507 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
508}
509
510void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
511 TPC.RecordInitialStack();
512 TotalNumberOfRuns++;
513 assert(InFuzzingThread());
514 if (SMR.IsClient())
515 SMR.WriteByteArray(Data, Size);
516 // We copy the contents of Unit into a separate heap buffer
517 // so that we reliably find buffer overflows in it.
518 uint8_t *DataCopy = new uint8_t[Size];
519 memcpy(DataCopy, Data, Size);
Matt Morehousea34c65e2018-07-09 23:51:08520 if (EF->__msan_unpoison)
521 EF->__msan_unpoison(DataCopy, Size);
George Karpenkov10ab2ac2017-08-21 23:25:50522 if (CurrentUnitData && CurrentUnitData != Data)
523 memcpy(CurrentUnitData, Data, Size);
524 CurrentUnitSize = Size;
Matt Morehousea34c65e2018-07-09 23:51:08525 {
526 ScopedEnableMsanInterceptorChecks S;
527 AllocTracer.Start(Options.TraceMalloc);
528 UnitStartTime = system_clock::now();
529 TPC.ResetMaps();
530 RunningCB = true;
531 int Res = CB(DataCopy, Size);
532 RunningCB = false;
533 UnitStopTime = system_clock::now();
534 (void)Res;
535 assert(Res == 0);
536 HasMoreMallocsThanFrees = AllocTracer.Stop();
537 }
George Karpenkov10ab2ac2017-08-21 23:25:50538 if (!LooseMemeq(DataCopy, Data, Size))
539 CrashOnOverwrittenData();
540 CurrentUnitSize = 0;
541 delete[] DataCopy;
542}
543
544void Fuzzer::WriteToOutputCorpus(const Unit &U) {
545 if (Options.OnlyASCII)
546 assert(IsASCII(U));
547 if (Options.OutputCorpus.empty())
548 return;
549 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
550 WriteToFile(U, Path);
551 if (Options.Verbosity >= 2)
552 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
553}
554
555void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
556 if (!Options.SaveArtifacts)
557 return;
558 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
559 if (!Options.ExactArtifactPath.empty())
560 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
561 WriteToFile(U, Path);
562 Printf("artifact_prefix='%s'; Test unit written to %s\n",
563 Options.ArtifactPrefix.c_str(), Path.c_str());
564 if (U.size() <= kMaxUnitSizeToPrint)
565 Printf("Base64: %s\n", Base64(U).c_str());
566}
567
568void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
569 if (!Options.PrintNEW)
570 return;
571 PrintStats(Text, "");
572 if (Options.Verbosity) {
573 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
574 MD.PrintMutationSequence();
575 Printf("\n");
576 }
577}
578
579void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
580 II->NumSuccessfullMutations++;
581 MD.RecordSuccessfulMutationSequence();
Alex Shlyapnikov5ded0702017-10-23 23:24:33582 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
George Karpenkov10ab2ac2017-08-21 23:25:50583 WriteToOutputCorpus(U);
584 NumberOfNewUnitsAdded++;
Alex Shlyapnikov5ded0702017-10-23 23:24:33585 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50586 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50587}
588
589// Tries detecting a memory leak on the particular input that we have just
590// executed before calling this function.
591void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
592 bool DuringInitialCorpusExecution) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33593 if (!HasMoreMallocsThanFrees)
594 return; // mallocs==frees, a leak is unlikely.
595 if (!Options.DetectLeaks)
596 return;
Max Moroz3f26dac2017-09-12 02:01:54597 if (!DuringInitialCorpusExecution &&
Alex Shlyapnikov5ded0702017-10-23 23:24:33598 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
599 return;
George Karpenkov10ab2ac2017-08-21 23:25:50600 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
601 !(EF->__lsan_do_recoverable_leak_check))
Alex Shlyapnikov5ded0702017-10-23 23:24:33602 return; // No lsan.
George Karpenkov10ab2ac2017-08-21 23:25:50603 // Run the target once again, but with lsan disabled so that if there is
604 // a real leak we do not report it twice.
605 EF->__lsan_disable();
606 ExecuteCallback(Data, Size);
607 EF->__lsan_enable();
Alex Shlyapnikov5ded0702017-10-23 23:24:33608 if (!HasMoreMallocsThanFrees)
609 return; // a leak is unlikely.
George Karpenkov10ab2ac2017-08-21 23:25:50610 if (NumberOfLeakDetectionAttempts++ > 1000) {
611 Options.DetectLeaks = false;
612 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
613 " Most likely the target function accumulates allocated\n"
614 " memory in a global state w/o actually leaking it.\n"
615 " You may try running this binary with -trace_malloc=[12]"
616 " to get a trace of mallocs and frees.\n"
617 " If LeakSanitizer is enabled in this process it will still\n"
618 " run on the process shutdown.\n");
619 return;
620 }
621 // Now perform the actual lsan pass. This is expensive and we must ensure
622 // we don't call it too often.
623 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
624 if (DuringInitialCorpusExecution)
625 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
626 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
627 CurrentUnitSize = Size;
628 DumpCurrentUnit("leak-");
629 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33630 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
George Karpenkov10ab2ac2017-08-21 23:25:50631 }
632}
633
634void Fuzzer::MutateAndTestOne() {
635 MD.StartMutationSequence();
636
637 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
George Karpenkov10ab2ac2017-08-21 23:25:50638 const auto &U = II.U;
639 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
640 assert(CurrentUnitData);
641 size_t Size = U.size();
642 assert(Size <= MaxInputLen && "Oversized Unit");
643 memcpy(CurrentUnitData, U.data(), Size);
644
645 assert(MaxMutationLen > 0);
646
647 size_t CurrentMaxMutationLen =
648 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
649 assert(CurrentMaxMutationLen > 0);
650
651 for (int i = 0; i < Options.MutateDepth; i++) {
652 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
653 break;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19654 MaybeExitGracefully();
George Karpenkov10ab2ac2017-08-21 23:25:50655 size_t NewSize = 0;
656 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
657 assert(NewSize > 0 && "Mutator returned empty unit");
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30658 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
George Karpenkov10ab2ac2017-08-21 23:25:50659 Size = NewSize;
660 II.NumExecutedMutations++;
George Karpenkov10ab2ac2017-08-21 23:25:50661
Kostya Serebryanyad05ee02017-12-01 19:18:38662 bool FoundUniqFeatures = false;
663 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
664 &FoundUniqFeatures);
George Karpenkov10ab2ac2017-08-21 23:25:50665 TryDetectingAMemoryLeak(CurrentUnitData, Size,
666 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryanyad05ee02017-12-01 19:18:38667 if (NewCov) {
Matt Morehouse947838c2017-11-09 20:44:08668 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryanyad05ee02017-12-01 19:18:38669 break; // We will mutate this input more in the next rounds.
670 }
671 if (Options.ReduceDepth && !FoundUniqFeatures)
Max Moroz1d369a52018-07-16 15:15:34672 break;
George Karpenkov10ab2ac2017-08-21 23:25:50673 }
674}
675
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30676void Fuzzer::PurgeAllocator() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33677 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30678 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30679 if (duration_cast<seconds>(system_clock::now() -
Alex Shlyapnikov5ded0702017-10-23 23:24:33680 LastAllocatorPurgeAttemptTime)
681 .count() < Options.PurgeAllocatorIntervalSec)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30682 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30683
684 if (Options.RssLimitMb <= 0 ||
Alex Shlyapnikov5ded0702017-10-23 23:24:33685 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30686 EF->__sanitizer_purge_allocator();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30687
688 LastAllocatorPurgeAttemptTime = system_clock::now();
689}
690
Kostya Serebryany3a8e3c82017-08-29 02:05:01691void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
692 const size_t kMaxSaneLen = 1 << 20;
693 const size_t kMinDefaultLen = 4096;
Kostya Serebryany4faeb872017-08-29 20:51:24694 Vector<SizedFile> SizedFiles;
695 size_t MaxSize = 0;
696 size_t MinSize = -1;
697 size_t TotalSize = 0;
Kostya Serebryany93679be2017-09-12 21:58:07698 size_t LastNumFiles = 0;
Kostya Serebryany4faeb872017-08-29 20:51:24699 for (auto &Dir : CorpusDirs) {
Kostya Serebryany93679be2017-09-12 21:58:07700 GetSizedFilesFromDir(Dir, &SizedFiles);
701 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
702 Dir.c_str());
703 LastNumFiles = SizedFiles.size();
704 }
705 for (auto &File : SizedFiles) {
706 MaxSize = Max(File.Size, MaxSize);
707 MinSize = Min(File.Size, MinSize);
708 TotalSize += File.Size;
Kostya Serebryany3a8e3c82017-08-29 02:05:01709 }
Kostya Serebryany4faeb872017-08-29 20:51:24710 if (Options.MaxLen == 0)
711 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
712 assert(MaxInputLen > 0);
713
Kostya Serebryany51823d32017-10-13 01:12:23714 // Test the callback with empty input and never try it again.
715 uint8_t dummy = 0;
716 ExecuteCallback(&dummy, 0);
717
Kostya Serebryany4faeb872017-08-29 20:51:24718 if (SizedFiles.empty()) {
719 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
720 Unit U({'\n'}); // Valid ASCII input.
721 RunOne(U.data(), U.size());
722 } else {
723 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
724 " rss: %zdMb\n",
725 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
726 if (Options.ShuffleAtStartUp)
727 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
728
Kostya Serebryany93679be2017-09-12 21:58:07729 if (Options.PreferSmall) {
730 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
731 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
732 }
Kostya Serebryany4faeb872017-08-29 20:51:24733
734 // Load and execute inputs one by one.
735 for (auto &SF : SizedFiles) {
Kostya Serebryany082e9a72017-08-31 19:17:15736 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
Kostya Serebryany4faeb872017-08-29 20:51:24737 assert(U.size() <= MaxInputLen);
738 RunOne(U.data(), U.size());
739 CheckExitOnSrcPosOrItem();
740 TryDetectingAMemoryLeak(U.data(), U.size(),
741 /*DuringInitialCorpusExecution*/ true);
742 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01743 }
744
Kostya Serebryany4faeb872017-08-29 20:51:24745 PrintStats("INITED");
Kostya Serebryanye9c6f062018-05-16 23:26:37746 if (!Options.FocusFunction.empty())
747 Printf("INFO: %zd/%zd inputs touch the focus function\n",
748 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
Kostya Serebryany67af9922018-06-07 01:40:20749 if (!Options.DataFlowTrace.empty())
750 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
751 Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
Kostya Serebryanye9c6f062018-05-16 23:26:37752
Max Morozfe974412018-05-23 19:42:30753 if (Corpus.empty() && Options.MaxNumberOfRuns) {
Kostya Serebryany4faeb872017-08-29 20:51:24754 Printf("ERROR: no interesting inputs were found. "
755 "Is the code instrumented for coverage? Exiting.\n");
756 exit(1);
Kostya Serebryany3a8e3c82017-08-29 02:05:01757 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01758}
759
760void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
761 ReadAndExecuteSeedCorpora(CorpusDirs);
Kostya Serebryany67af9922018-06-07 01:40:20762 DFT.Clear(); // No need for DFT any more.
George Karpenkov10ab2ac2017-08-21 23:25:50763 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryany2eef8162017-08-25 20:09:25764 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
George Karpenkov10ab2ac2017-08-21 23:25:50765 system_clock::time_point LastCorpusReload = system_clock::now();
766 if (Options.DoCrossOver)
767 MD.SetCorpus(&Corpus);
768 while (true) {
769 auto Now = system_clock::now();
770 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
771 Options.ReloadIntervalSec) {
772 RereadOutputCorpus(MaxInputLen);
773 LastCorpusReload = system_clock::now();
774 }
775 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
776 break;
Alex Shlyapnikov5ded0702017-10-23 23:24:33777 if (TimedOut())
778 break;
George Karpenkov10ab2ac2017-08-21 23:25:50779
780 // Update TmpMaxMutationLen
Matt Morehouse36c89b32018-02-13 20:52:15781 if (Options.LenControl) {
George Karpenkov10ab2ac2017-08-21 23:25:50782 if (TmpMaxMutationLen < MaxMutationLen &&
Kostya Serebryanye9ed2322017-12-12 23:11:28783 TotalNumberOfRuns - LastCorpusUpdateRun >
Matt Morehouse36c89b32018-02-13 20:52:15784 Options.LenControl * Log(TmpMaxMutationLen)) {
George Karpenkov10ab2ac2017-08-21 23:25:50785 TmpMaxMutationLen =
Kostya Serebryanye9ed2322017-12-12 23:11:28786 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
Kostya Serebryanye9ed2322017-12-12 23:11:28787 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50788 }
789 } else {
790 TmpMaxMutationLen = MaxMutationLen;
791 }
792
793 // Perform several mutations and runs.
794 MutateAndTestOne();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30795
796 PurgeAllocator();
George Karpenkov10ab2ac2017-08-21 23:25:50797 }
798
799 PrintStats("DONE ", "\n");
800 MD.PrintRecommendedDictionary();
801}
802
803void Fuzzer::MinimizeCrashLoop(const Unit &U) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33804 if (U.size() <= 1)
805 return;
George Karpenkov10ab2ac2017-08-21 23:25:50806 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
807 MD.StartMutationSequence();
808 memcpy(CurrentUnitData, U.data(), U.size());
809 for (int i = 0; i < Options.MutateDepth; i++) {
810 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
811 assert(NewSize > 0 && NewSize <= MaxMutationLen);
812 ExecuteCallback(CurrentUnitData, NewSize);
813 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
814 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
815 /*DuringInitialCorpusExecution*/ false);
816 }
817 }
818}
819
820void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
821 if (SMR.IsServer()) {
822 SMR.WriteByteArray(Data, Size);
823 } else if (SMR.IsClient()) {
824 SMR.PostClient();
825 SMR.WaitServer();
826 size_t OtherSize = SMR.ReadByteArraySize();
827 uint8_t *OtherData = SMR.GetByteArray();
828 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
829 size_t i = 0;
830 for (i = 0; i < Min(Size, OtherSize); i++)
831 if (Data[i] != OtherData[i])
832 break;
833 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
Alex Shlyapnikov5ded0702017-10-23 23:24:33834 "offset %zd\n",
835 GetPid(), Size, OtherSize, i);
George Karpenkov10ab2ac2017-08-21 23:25:50836 DumpCurrentUnit("mismatch-");
837 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
838 PrintFinalStats();
839 _Exit(Options.ErrorExitCode);
840 }
841 }
842}
843
844} // namespace fuzzer
845
846extern "C" {
847
Petr Hosekeac2b472018-01-17 20:39:14848__attribute__((visibility("default"))) size_t
849LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
George Karpenkov10ab2ac2017-08-21 23:25:50850 assert(fuzzer::F);
851 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
852}
853
854// Experimental
Petr Hosekeac2b472018-01-17 20:39:14855__attribute__((visibility("default"))) void
856LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
George Karpenkov10ab2ac2017-08-21 23:25:50857 assert(fuzzer::F);
858 fuzzer::F->AnnounceOutput(Data, Size);
859}
Alex Shlyapnikov5ded0702017-10-23 23:24:33860} // extern "C"