blob: 7366f69ffca8f0458bda47ea8d2d7bd349413562 [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)
108 EF->__sanitizer_print_stack_trace();
109 }
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)
121 EF->__sanitizer_print_stack_trace();
122 }
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");
132 if (EF->__sanitizer_print_stack_trace)
133 EF->__sanitizer_print_stack_trace();
134 DumpCurrentUnit("oom-");
135 Printf("SUMMARY: libFuzzer: out-of-memory\n");
136 PrintFinalStats();
137 _Exit(Options.ErrorExitCode); // Stop right now.
138}
139
140Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
141 FuzzingOptions Options)
142 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
143 if (EF->__sanitizer_set_death_callback)
144 EF->__sanitizer_set_death_callback(StaticDeathCallback);
145 assert(!F);
146 F = this;
147 TPC.ResetMaps();
148 IsMyThread = true;
149 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
150 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
151 TPC.SetUseCounters(Options.UseCounters);
152 TPC.SetUseValueProfile(Options.UseValueProfile);
Max Moroz330496c2017-10-05 22:41:03153 TPC.SetUseClangCoverage(Options.UseClangCoverage);
George Karpenkov10ab2ac2017-08-21 23:25:50154
155 if (Options.Verbosity)
156 TPC.PrintModuleInfo();
157 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
158 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
159 MaxInputLen = MaxMutationLen = Options.MaxLen;
160 TmpMaxMutationLen = Max(size_t(4), Corpus.MaxInputSize());
161 AllocateCurrentUnitData();
162 CurrentUnitSize = 0;
163 memset(BaseSha1, 0, sizeof(BaseSha1));
164}
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.
George Karpenkov10ab2ac2017-08-21 23:25:50182 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
Kostya Serebryanya2ca2dc2017-11-09 20:30:19219void Fuzzer::StaticGracefulExitCallback() {
220 assert(F);
221 F->GracefulExitRequested = true;
222 Printf("INFO: signal received, trying to exit gracefully\n");
223}
224
George Karpenkov10ab2ac2017-08-21 23:25:50225void Fuzzer::StaticFileSizeExceedCallback() {
226 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
227 exit(1);
228}
229
230void Fuzzer::CrashCallback() {
231 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
232 if (EF->__sanitizer_print_stack_trace)
233 EF->__sanitizer_print_stack_trace();
234 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();
Alex Shlyapnikov5ded0702017-10-23 23:24:33240 _Exit(Options.ErrorExitCode); // Stop right now.
George Karpenkov10ab2ac2017-08-21 23:25:50241}
242
243void Fuzzer::ExitCallback() {
244 if (!RunningCB)
245 return; // This exit did not come from the user callback
246 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
247 if (EF->__sanitizer_print_stack_trace)
248 EF->__sanitizer_print_stack_trace();
249 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
250 DumpCurrentUnit("crash-");
251 PrintFinalStats();
252 _Exit(Options.ErrorExitCode);
253}
254
Kostya Serebryanya2ca2dc2017-11-09 20:30:19255void Fuzzer::MaybeExitGracefully() {
256 if (!GracefulExitRequested) return;
257 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
258 PrintFinalStats();
259 _Exit(0);
260}
261
George Karpenkov10ab2ac2017-08-21 23:25:50262void Fuzzer::InterruptCallback() {
263 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
264 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33265 _Exit(0); // Stop right now, don't perform any at-exit actions.
George Karpenkov10ab2ac2017-08-21 23:25:50266}
267
268NO_SANITIZE_MEMORY
269void Fuzzer::AlarmCallback() {
270 assert(Options.UnitTimeoutSec > 0);
271 // In Windows Alarm callback is executed by a different thread.
272#if !LIBFUZZER_WINDOWS
Alex Shlyapnikov5ded0702017-10-23 23:24:33273 if (!InFuzzingThread())
274 return;
George Karpenkov10ab2ac2017-08-21 23:25:50275#endif
276 if (!RunningCB)
277 return; // We have not started running units yet.
278 size_t Seconds =
279 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
280 if (Seconds == 0)
281 return;
282 if (Options.Verbosity >= 2)
283 Printf("AlarmCallback %zd\n", Seconds);
284 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
285 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
286 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
287 Options.UnitTimeoutSec);
288 DumpCurrentUnit("timeout-");
289 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
290 Seconds);
291 if (EF->__sanitizer_print_stack_trace)
292 EF->__sanitizer_print_stack_trace();
293 Printf("SUMMARY: libFuzzer: timeout\n");
294 PrintFinalStats();
295 _Exit(Options.TimeoutExitCode); // Stop right now.
296 }
297}
298
299void Fuzzer::RssLimitCallback() {
300 Printf(
301 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
302 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
303 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
304 if (EF->__sanitizer_print_memory_profile)
305 EF->__sanitizer_print_memory_profile(95, 8);
306 DumpCurrentUnit("oom-");
307 Printf("SUMMARY: libFuzzer: out-of-memory\n");
308 PrintFinalStats();
309 _Exit(Options.ErrorExitCode); // Stop right now.
310}
311
312void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
313 size_t ExecPerSec = execPerSec();
314 if (!Options.Verbosity)
315 return;
316 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
317 if (size_t N = TPC.GetTotalPCCoverage())
318 Printf(" cov: %zd", N);
319 if (size_t N = Corpus.NumFeatures())
Alex Shlyapnikov5ded0702017-10-23 23:24:33320 Printf(" ft: %zd", N);
George Karpenkov10ab2ac2017-08-21 23:25:50321 if (!Corpus.empty()) {
322 Printf(" corp: %zd", Corpus.NumActiveUnits());
323 if (size_t N = Corpus.SizeInBytes()) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33324 if (N < (1 << 14))
George Karpenkov10ab2ac2017-08-21 23:25:50325 Printf("/%zdb", N);
326 else if (N < (1 << 24))
327 Printf("/%zdKb", N >> 10);
328 else
329 Printf("/%zdMb", N >> 20);
330 }
331 }
332 if (Units)
333 Printf(" units: %zd", Units);
334
335 Printf(" exec/s: %zd", ExecPerSec);
336 Printf(" rss: %zdMb", GetPeakRSSMb());
337 Printf("%s", End);
338}
339
340void Fuzzer::PrintFinalStats() {
341 if (Options.PrintCoverage)
342 TPC.PrintCoverage();
343 if (Options.DumpCoverage)
344 TPC.DumpCoverage();
345 if (Options.PrintCorpusStats)
346 Corpus.PrintStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33347 if (!Options.PrintFinalStats)
348 return;
George Karpenkov10ab2ac2017-08-21 23:25:50349 size_t ExecPerSec = execPerSec();
350 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
351 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
352 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
353 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
354 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
355}
356
357void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
358 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
359 assert(MaxInputLen);
360 this->MaxInputLen = MaxInputLen;
361 this->MaxMutationLen = MaxInputLen;
362 AllocateCurrentUnitData();
363 Printf("INFO: -max_len is not provided; "
364 "libFuzzer will not generate inputs larger than %zd bytes\n",
365 MaxInputLen);
366}
367
368void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
369 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
370 this->MaxMutationLen = MaxMutationLen;
371}
372
373void Fuzzer::CheckExitOnSrcPosOrItem() {
374 if (!Options.ExitOnSrcPos.empty()) {
George Karpenkovbebcbfb2017-08-27 23:20:09375 static auto *PCsSet = new Set<uintptr_t>;
George Karpenkov10ab2ac2017-08-21 23:25:50376 auto HandlePC = [&](uintptr_t PC) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33377 if (!PCsSet->insert(PC).second)
378 return;
George Karpenkov10ab2ac2017-08-21 23:25:50379 std::string Descr = DescribePC("%F %L", PC + 1);
380 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
381 Printf("INFO: found line matching '%s', exiting.\n",
382 Options.ExitOnSrcPos.c_str());
383 _Exit(0);
384 }
385 };
386 TPC.ForEachObservedPC(HandlePC);
387 }
388 if (!Options.ExitOnItem.empty()) {
389 if (Corpus.HasUnit(Options.ExitOnItem)) {
390 Printf("INFO: found item with checksum '%s', exiting.\n",
391 Options.ExitOnItem.c_str());
392 _Exit(0);
393 }
394 }
395}
396
397void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33398 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
399 return;
George Karpenkovbebcbfb2017-08-27 23:20:09400 Vector<Unit> AdditionalCorpus;
George Karpenkov10ab2ac2017-08-21 23:25:50401 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
402 &EpochOfLastReadOfOutputCorpus, MaxSize,
403 /*ExitOnError*/ false);
404 if (Options.Verbosity >= 2)
405 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
406 bool Reloaded = false;
407 for (auto &U : AdditionalCorpus) {
408 if (U.size() > MaxSize)
409 U.resize(MaxSize);
410 if (!Corpus.HasUnit(U)) {
411 if (RunOne(U.data(), U.size())) {
412 CheckExitOnSrcPosOrItem();
413 Reloaded = true;
414 }
415 }
416 }
417 if (Reloaded)
418 PrintStats("RELOAD");
419}
420
George Karpenkov10ab2ac2017-08-21 23:25:50421void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
422 auto TimeOfUnit =
423 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
424 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
425 secondsSinceProcessStartUp() >= 2)
426 PrintStats("pulse ");
427 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
428 TimeOfUnit >= Options.ReportSlowUnits) {
429 TimeOfLongestUnitInSeconds = TimeOfUnit;
430 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
431 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
432 }
433}
434
435bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
Kostya Serebryanyad05ee02017-12-01 19:18:38436 InputInfo *II, bool *FoundUniqFeatures) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33437 if (!Size)
438 return false;
George Karpenkov10ab2ac2017-08-21 23:25:50439
440 ExecuteCallback(Data, Size);
441
442 UniqFeatureSetTmp.clear();
443 size_t FoundUniqFeaturesOfII = 0;
444 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
445 TPC.CollectFeatures([&](size_t Feature) {
Kostya Serebryany2659c632017-12-08 22:21:42446 if (Options.UseFeatureFrequency)
447 Corpus.UpdateFeatureFrequency(Feature);
George Karpenkov10ab2ac2017-08-21 23:25:50448 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
449 UniqFeatureSetTmp.push_back(Feature);
450 if (Options.ReduceInputs && II)
451 if (std::binary_search(II->UniqFeatureSet.begin(),
452 II->UniqFeatureSet.end(), Feature))
453 FoundUniqFeaturesOfII++;
454 });
Kostya Serebryanyad05ee02017-12-01 19:18:38455 if (FoundUniqFeatures)
456 *FoundUniqFeatures = FoundUniqFeaturesOfII;
George Karpenkov10ab2ac2017-08-21 23:25:50457 PrintPulseAndReportSlowInput(Data, Size);
458 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
459 if (NumNewFeatures) {
460 TPC.UpdateObservedPCs();
461 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
462 UniqFeatureSetTmp);
463 return true;
464 }
465 if (II && FoundUniqFeaturesOfII &&
466 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
467 II->U.size() > Size) {
468 Corpus.Replace(II, {Data, Data + Size});
469 return true;
470 }
471 return false;
472}
473
474size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
475 assert(InFuzzingThread());
476 *Data = CurrentUnitData;
477 return CurrentUnitSize;
478}
479
480void Fuzzer::CrashOnOverwrittenData() {
481 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
482 GetPid());
483 DumpCurrentUnit("crash-");
484 Printf("SUMMARY: libFuzzer: out-of-memory\n");
485 _Exit(Options.ErrorExitCode); // Stop right now.
486}
487
488// Compare two arrays, but not all bytes if the arrays are large.
489static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
490 const size_t Limit = 64;
491 if (Size <= 64)
492 return !memcmp(A, B, Size);
493 // Compare first and last Limit/2 bytes.
494 return !memcmp(A, B, Limit / 2) &&
495 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
496}
497
498void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
499 TPC.RecordInitialStack();
500 TotalNumberOfRuns++;
501 assert(InFuzzingThread());
502 if (SMR.IsClient())
503 SMR.WriteByteArray(Data, Size);
504 // We copy the contents of Unit into a separate heap buffer
505 // so that we reliably find buffer overflows in it.
506 uint8_t *DataCopy = new uint8_t[Size];
507 memcpy(DataCopy, Data, Size);
508 if (CurrentUnitData && CurrentUnitData != Data)
509 memcpy(CurrentUnitData, Data, Size);
510 CurrentUnitSize = Size;
511 AllocTracer.Start(Options.TraceMalloc);
512 UnitStartTime = system_clock::now();
513 TPC.ResetMaps();
514 RunningCB = true;
515 int Res = CB(DataCopy, Size);
516 RunningCB = false;
517 UnitStopTime = system_clock::now();
518 (void)Res;
519 assert(Res == 0);
520 HasMoreMallocsThanFrees = AllocTracer.Stop();
521 if (!LooseMemeq(DataCopy, Data, Size))
522 CrashOnOverwrittenData();
523 CurrentUnitSize = 0;
524 delete[] DataCopy;
525}
526
527void Fuzzer::WriteToOutputCorpus(const Unit &U) {
528 if (Options.OnlyASCII)
529 assert(IsASCII(U));
530 if (Options.OutputCorpus.empty())
531 return;
532 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
533 WriteToFile(U, Path);
534 if (Options.Verbosity >= 2)
535 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
536}
537
538void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
539 if (!Options.SaveArtifacts)
540 return;
541 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
542 if (!Options.ExactArtifactPath.empty())
543 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
544 WriteToFile(U, Path);
545 Printf("artifact_prefix='%s'; Test unit written to %s\n",
546 Options.ArtifactPrefix.c_str(), Path.c_str());
547 if (U.size() <= kMaxUnitSizeToPrint)
548 Printf("Base64: %s\n", Base64(U).c_str());
549}
550
551void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
552 if (!Options.PrintNEW)
553 return;
554 PrintStats(Text, "");
555 if (Options.Verbosity) {
556 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
557 MD.PrintMutationSequence();
558 Printf("\n");
559 }
560}
561
562void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
563 II->NumSuccessfullMutations++;
564 MD.RecordSuccessfulMutationSequence();
Alex Shlyapnikov5ded0702017-10-23 23:24:33565 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
George Karpenkov10ab2ac2017-08-21 23:25:50566 WriteToOutputCorpus(U);
567 NumberOfNewUnitsAdded++;
Alex Shlyapnikov5ded0702017-10-23 23:24:33568 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50569 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50570}
571
572// Tries detecting a memory leak on the particular input that we have just
573// executed before calling this function.
574void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
575 bool DuringInitialCorpusExecution) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33576 if (!HasMoreMallocsThanFrees)
577 return; // mallocs==frees, a leak is unlikely.
578 if (!Options.DetectLeaks)
579 return;
Max Moroz3f26dac2017-09-12 02:01:54580 if (!DuringInitialCorpusExecution &&
Alex Shlyapnikov5ded0702017-10-23 23:24:33581 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
582 return;
George Karpenkov10ab2ac2017-08-21 23:25:50583 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
584 !(EF->__lsan_do_recoverable_leak_check))
Alex Shlyapnikov5ded0702017-10-23 23:24:33585 return; // No lsan.
George Karpenkov10ab2ac2017-08-21 23:25:50586 // Run the target once again, but with lsan disabled so that if there is
587 // a real leak we do not report it twice.
588 EF->__lsan_disable();
589 ExecuteCallback(Data, Size);
590 EF->__lsan_enable();
Alex Shlyapnikov5ded0702017-10-23 23:24:33591 if (!HasMoreMallocsThanFrees)
592 return; // a leak is unlikely.
George Karpenkov10ab2ac2017-08-21 23:25:50593 if (NumberOfLeakDetectionAttempts++ > 1000) {
594 Options.DetectLeaks = false;
595 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
596 " Most likely the target function accumulates allocated\n"
597 " memory in a global state w/o actually leaking it.\n"
598 " You may try running this binary with -trace_malloc=[12]"
599 " to get a trace of mallocs and frees.\n"
600 " If LeakSanitizer is enabled in this process it will still\n"
601 " run on the process shutdown.\n");
602 return;
603 }
604 // Now perform the actual lsan pass. This is expensive and we must ensure
605 // we don't call it too often.
606 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
607 if (DuringInitialCorpusExecution)
608 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
609 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
610 CurrentUnitSize = Size;
611 DumpCurrentUnit("leak-");
612 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33613 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
George Karpenkov10ab2ac2017-08-21 23:25:50614 }
615}
616
617void Fuzzer::MutateAndTestOne() {
618 MD.StartMutationSequence();
619
620 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany4083d542017-10-11 01:44:26621 if (Options.UseFeatureFrequency)
622 Corpus.UpdateFeatureFrequencyScore(&II);
George Karpenkov10ab2ac2017-08-21 23:25:50623 const auto &U = II.U;
624 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
625 assert(CurrentUnitData);
626 size_t Size = U.size();
627 assert(Size <= MaxInputLen && "Oversized Unit");
628 memcpy(CurrentUnitData, U.data(), Size);
629
630 assert(MaxMutationLen > 0);
631
632 size_t CurrentMaxMutationLen =
633 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
634 assert(CurrentMaxMutationLen > 0);
635
636 for (int i = 0; i < Options.MutateDepth; i++) {
637 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
638 break;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19639 MaybeExitGracefully();
George Karpenkov10ab2ac2017-08-21 23:25:50640 size_t NewSize = 0;
641 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
642 assert(NewSize > 0 && "Mutator returned empty unit");
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30643 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
George Karpenkov10ab2ac2017-08-21 23:25:50644 Size = NewSize;
645 II.NumExecutedMutations++;
George Karpenkov10ab2ac2017-08-21 23:25:50646
Kostya Serebryanyad05ee02017-12-01 19:18:38647 bool FoundUniqFeatures = false;
648 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
649 &FoundUniqFeatures);
George Karpenkov10ab2ac2017-08-21 23:25:50650 TryDetectingAMemoryLeak(CurrentUnitData, Size,
651 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryanyad05ee02017-12-01 19:18:38652 if (NewCov) {
Matt Morehouse947838c2017-11-09 20:44:08653 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryanyad05ee02017-12-01 19:18:38654 break; // We will mutate this input more in the next rounds.
655 }
656 if (Options.ReduceDepth && !FoundUniqFeatures)
657 break;
George Karpenkov10ab2ac2017-08-21 23:25:50658 }
659}
660
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30661void Fuzzer::PurgeAllocator() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33662 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30663 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30664 if (duration_cast<seconds>(system_clock::now() -
Alex Shlyapnikov5ded0702017-10-23 23:24:33665 LastAllocatorPurgeAttemptTime)
666 .count() < Options.PurgeAllocatorIntervalSec)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30667 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30668
669 if (Options.RssLimitMb <= 0 ||
Alex Shlyapnikov5ded0702017-10-23 23:24:33670 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30671 EF->__sanitizer_purge_allocator();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30672
673 LastAllocatorPurgeAttemptTime = system_clock::now();
674}
675
Kostya Serebryany3a8e3c82017-08-29 02:05:01676void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
677 const size_t kMaxSaneLen = 1 << 20;
678 const size_t kMinDefaultLen = 4096;
Kostya Serebryany4faeb872017-08-29 20:51:24679 Vector<SizedFile> SizedFiles;
680 size_t MaxSize = 0;
681 size_t MinSize = -1;
682 size_t TotalSize = 0;
Kostya Serebryany93679be2017-09-12 21:58:07683 size_t LastNumFiles = 0;
Kostya Serebryany4faeb872017-08-29 20:51:24684 for (auto &Dir : CorpusDirs) {
Kostya Serebryany93679be2017-09-12 21:58:07685 GetSizedFilesFromDir(Dir, &SizedFiles);
686 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
687 Dir.c_str());
688 LastNumFiles = SizedFiles.size();
689 }
690 for (auto &File : SizedFiles) {
691 MaxSize = Max(File.Size, MaxSize);
692 MinSize = Min(File.Size, MinSize);
693 TotalSize += File.Size;
Kostya Serebryany3a8e3c82017-08-29 02:05:01694 }
Kostya Serebryany4faeb872017-08-29 20:51:24695 if (Options.MaxLen == 0)
696 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
697 assert(MaxInputLen > 0);
698
Kostya Serebryany51823d32017-10-13 01:12:23699 // Test the callback with empty input and never try it again.
700 uint8_t dummy = 0;
701 ExecuteCallback(&dummy, 0);
702
Kostya Serebryany4faeb872017-08-29 20:51:24703 if (SizedFiles.empty()) {
704 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
705 Unit U({'\n'}); // Valid ASCII input.
706 RunOne(U.data(), U.size());
707 } else {
708 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
709 " rss: %zdMb\n",
710 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
711 if (Options.ShuffleAtStartUp)
712 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
713
Kostya Serebryany93679be2017-09-12 21:58:07714 if (Options.PreferSmall) {
715 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
716 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
717 }
Kostya Serebryany4faeb872017-08-29 20:51:24718
719 // Load and execute inputs one by one.
720 for (auto &SF : SizedFiles) {
Kostya Serebryany082e9a72017-08-31 19:17:15721 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
Kostya Serebryany4faeb872017-08-29 20:51:24722 assert(U.size() <= MaxInputLen);
723 RunOne(U.data(), U.size());
724 CheckExitOnSrcPosOrItem();
725 TryDetectingAMemoryLeak(U.data(), U.size(),
726 /*DuringInitialCorpusExecution*/ true);
727 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01728 }
729
Kostya Serebryany4faeb872017-08-29 20:51:24730 PrintStats("INITED");
731 if (Corpus.empty()) {
732 Printf("ERROR: no interesting inputs were found. "
733 "Is the code instrumented for coverage? Exiting.\n");
734 exit(1);
Kostya Serebryany3a8e3c82017-08-29 02:05:01735 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01736}
737
738void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
739 ReadAndExecuteSeedCorpora(CorpusDirs);
George Karpenkov10ab2ac2017-08-21 23:25:50740 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryany2eef8162017-08-25 20:09:25741 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
George Karpenkov10ab2ac2017-08-21 23:25:50742 system_clock::time_point LastCorpusReload = system_clock::now();
743 if (Options.DoCrossOver)
744 MD.SetCorpus(&Corpus);
745 while (true) {
746 auto Now = system_clock::now();
747 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
748 Options.ReloadIntervalSec) {
749 RereadOutputCorpus(MaxInputLen);
750 LastCorpusReload = system_clock::now();
751 }
752 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
753 break;
Alex Shlyapnikov5ded0702017-10-23 23:24:33754 if (TimedOut())
755 break;
George Karpenkov10ab2ac2017-08-21 23:25:50756
757 // Update TmpMaxMutationLen
758 if (Options.ExperimentalLenControl) {
759 if (TmpMaxMutationLen < MaxMutationLen &&
Kostya Serebryanye9ed2322017-12-12 23:11:28760 TotalNumberOfRuns - LastCorpusUpdateRun >
761 Options.ExperimentalLenControl * Log(TmpMaxMutationLen)) {
George Karpenkov10ab2ac2017-08-21 23:25:50762 TmpMaxMutationLen =
Kostya Serebryanye9ed2322017-12-12 23:11:28763 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
George Karpenkov10ab2ac2017-08-21 23:25:50764 if (TmpMaxMutationLen <= MaxMutationLen)
Kostya Serebryany2659c632017-12-08 22:21:42765 Printf("#%zd\tTEMP_MAX_LEN: %zd (%zd %zd)\n", TotalNumberOfRuns,
766 TmpMaxMutationLen, Options.ExperimentalLenControl,
767 LastCorpusUpdateRun);
Kostya Serebryanye9ed2322017-12-12 23:11:28768 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50769 }
770 } else {
771 TmpMaxMutationLen = MaxMutationLen;
772 }
773
774 // Perform several mutations and runs.
775 MutateAndTestOne();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30776
777 PurgeAllocator();
George Karpenkov10ab2ac2017-08-21 23:25:50778 }
779
780 PrintStats("DONE ", "\n");
781 MD.PrintRecommendedDictionary();
782}
783
784void Fuzzer::MinimizeCrashLoop(const Unit &U) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33785 if (U.size() <= 1)
786 return;
George Karpenkov10ab2ac2017-08-21 23:25:50787 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
788 MD.StartMutationSequence();
789 memcpy(CurrentUnitData, U.data(), U.size());
790 for (int i = 0; i < Options.MutateDepth; i++) {
791 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
792 assert(NewSize > 0 && NewSize <= MaxMutationLen);
793 ExecuteCallback(CurrentUnitData, NewSize);
794 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
795 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
796 /*DuringInitialCorpusExecution*/ false);
797 }
798 }
799}
800
801void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
802 if (SMR.IsServer()) {
803 SMR.WriteByteArray(Data, Size);
804 } else if (SMR.IsClient()) {
805 SMR.PostClient();
806 SMR.WaitServer();
807 size_t OtherSize = SMR.ReadByteArraySize();
808 uint8_t *OtherData = SMR.GetByteArray();
809 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
810 size_t i = 0;
811 for (i = 0; i < Min(Size, OtherSize); i++)
812 if (Data[i] != OtherData[i])
813 break;
814 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
Alex Shlyapnikov5ded0702017-10-23 23:24:33815 "offset %zd\n",
816 GetPid(), Size, OtherSize, i);
George Karpenkov10ab2ac2017-08-21 23:25:50817 DumpCurrentUnit("mismatch-");
818 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
819 PrintFinalStats();
820 _Exit(Options.ErrorExitCode);
821 }
822 }
823}
824
825} // namespace fuzzer
826
827extern "C" {
828
Petr Hosekeac2b472018-01-17 20:39:14829__attribute__((visibility("default"))) size_t
830LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
George Karpenkov10ab2ac2017-08-21 23:25:50831 assert(fuzzer::F);
832 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
833}
834
835// Experimental
Petr Hosekeac2b472018-01-17 20:39:14836__attribute__((visibility("default"))) void
837LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
George Karpenkov10ab2ac2017-08-21 23:25:50838 assert(fuzzer::F);
839 fuzzer::F->AnnounceOutput(Data, Size);
840}
Alex Shlyapnikov5ded0702017-10-23 23:24:33841} // extern "C"