blob: 6cc220d9789c3c4b937f846ef74cba24f8927577 [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() {
Matt Morehouse7764a042018-05-02 02:55:28231 if (EF->__sanitizer_acquire_crash_state)
232 EF->__sanitizer_acquire_crash_state();
George Karpenkov10ab2ac2017-08-21 23:25:50233 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
234 if (EF->__sanitizer_print_stack_trace)
235 EF->__sanitizer_print_stack_trace();
236 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());
252 if (EF->__sanitizer_print_stack_trace)
253 EF->__sanitizer_print_stack_trace();
254 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
255 DumpCurrentUnit("crash-");
256 PrintFinalStats();
257 _Exit(Options.ErrorExitCode);
258}
259
Kostya Serebryanya2ca2dc2017-11-09 20:30:19260void Fuzzer::MaybeExitGracefully() {
261 if (!GracefulExitRequested) return;
262 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
263 PrintFinalStats();
264 _Exit(0);
265}
266
George Karpenkov10ab2ac2017-08-21 23:25:50267void Fuzzer::InterruptCallback() {
268 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
269 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33270 _Exit(0); // Stop right now, don't perform any at-exit actions.
George Karpenkov10ab2ac2017-08-21 23:25:50271}
272
273NO_SANITIZE_MEMORY
274void Fuzzer::AlarmCallback() {
275 assert(Options.UnitTimeoutSec > 0);
276 // In Windows Alarm callback is executed by a different thread.
277#if !LIBFUZZER_WINDOWS
Alex Shlyapnikov5ded0702017-10-23 23:24:33278 if (!InFuzzingThread())
279 return;
George Karpenkov10ab2ac2017-08-21 23:25:50280#endif
281 if (!RunningCB)
282 return; // We have not started running units yet.
283 size_t Seconds =
284 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
285 if (Seconds == 0)
286 return;
287 if (Options.Verbosity >= 2)
288 Printf("AlarmCallback %zd\n", Seconds);
289 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Matt Morehouse52fd1692018-05-01 21:01:53290 if (EF->__sanitizer_acquire_crash_state &&
291 !EF->__sanitizer_acquire_crash_state())
292 return;
George Karpenkov10ab2ac2017-08-21 23:25:50293 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
294 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
295 Options.UnitTimeoutSec);
296 DumpCurrentUnit("timeout-");
297 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
298 Seconds);
299 if (EF->__sanitizer_print_stack_trace)
300 EF->__sanitizer_print_stack_trace();
301 Printf("SUMMARY: libFuzzer: timeout\n");
302 PrintFinalStats();
303 _Exit(Options.TimeoutExitCode); // Stop right now.
304 }
305}
306
307void Fuzzer::RssLimitCallback() {
Matt Morehouse52fd1692018-05-01 21:01:53308 if (EF->__sanitizer_acquire_crash_state &&
309 !EF->__sanitizer_acquire_crash_state())
310 return;
George Karpenkov10ab2ac2017-08-21 23:25:50311 Printf(
312 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
313 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
314 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
315 if (EF->__sanitizer_print_memory_profile)
316 EF->__sanitizer_print_memory_profile(95, 8);
317 DumpCurrentUnit("oom-");
318 Printf("SUMMARY: libFuzzer: out-of-memory\n");
319 PrintFinalStats();
320 _Exit(Options.ErrorExitCode); // Stop right now.
321}
322
323void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
324 size_t ExecPerSec = execPerSec();
325 if (!Options.Verbosity)
326 return;
327 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
328 if (size_t N = TPC.GetTotalPCCoverage())
329 Printf(" cov: %zd", N);
330 if (size_t N = Corpus.NumFeatures())
Alex Shlyapnikov5ded0702017-10-23 23:24:33331 Printf(" ft: %zd", N);
George Karpenkov10ab2ac2017-08-21 23:25:50332 if (!Corpus.empty()) {
333 Printf(" corp: %zd", Corpus.NumActiveUnits());
334 if (size_t N = Corpus.SizeInBytes()) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33335 if (N < (1 << 14))
George Karpenkov10ab2ac2017-08-21 23:25:50336 Printf("/%zdb", N);
337 else if (N < (1 << 24))
338 Printf("/%zdKb", N >> 10);
339 else
340 Printf("/%zdMb", N >> 20);
341 }
342 }
Matt Morehouseddf352b2018-02-22 19:00:17343 if (TmpMaxMutationLen)
344 Printf(" lim: %zd", TmpMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50345 if (Units)
346 Printf(" units: %zd", Units);
347
348 Printf(" exec/s: %zd", ExecPerSec);
349 Printf(" rss: %zdMb", GetPeakRSSMb());
350 Printf("%s", End);
351}
352
353void Fuzzer::PrintFinalStats() {
354 if (Options.PrintCoverage)
355 TPC.PrintCoverage();
356 if (Options.DumpCoverage)
357 TPC.DumpCoverage();
358 if (Options.PrintCorpusStats)
359 Corpus.PrintStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33360 if (!Options.PrintFinalStats)
361 return;
George Karpenkov10ab2ac2017-08-21 23:25:50362 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 Karpenkovbebcbfb2017-08-27 23:20:09388 static auto *PCsSet = new Set<uintptr_t>;
George Karpenkov10ab2ac2017-08-21 23:25:50389 auto HandlePC = [&](uintptr_t PC) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33390 if (!PCsSet->insert(PC).second)
391 return;
George Karpenkov10ab2ac2017-08-21 23:25:50392 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) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33411 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
412 return;
George Karpenkovbebcbfb2017-08-27 23:20:09413 Vector<Unit> AdditionalCorpus;
George Karpenkov10ab2ac2017-08-21 23:25:50414 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 Karpenkov10ab2ac2017-08-21 23:25:50434void 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,
Kostya Serebryanyad05ee02017-12-01 19:18:38449 InputInfo *II, bool *FoundUniqFeatures) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33450 if (!Size)
451 return false;
George Karpenkov10ab2ac2017-08-21 23:25:50452
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) {
Kostya Serebryany2659c632017-12-08 22:21:42459 if (Options.UseFeatureFrequency)
460 Corpus.UpdateFeatureFrequency(Feature);
George Karpenkov10ab2ac2017-08-21 23:25:50461 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
462 UniqFeatureSetTmp.push_back(Feature);
463 if (Options.ReduceInputs && II)
464 if (std::binary_search(II->UniqFeatureSet.begin(),
465 II->UniqFeatureSet.end(), Feature))
466 FoundUniqFeaturesOfII++;
467 });
Kostya Serebryanyad05ee02017-12-01 19:18:38468 if (FoundUniqFeatures)
469 *FoundUniqFeatures = FoundUniqFeaturesOfII;
George Karpenkov10ab2ac2017-08-21 23:25:50470 PrintPulseAndReportSlowInput(Data, Size);
471 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
472 if (NumNewFeatures) {
473 TPC.UpdateObservedPCs();
474 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
475 UniqFeatureSetTmp);
476 return true;
477 }
478 if (II && FoundUniqFeaturesOfII &&
479 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();
Alex Shlyapnikov5ded0702017-10-23 23:24:33578 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
George Karpenkov10ab2ac2017-08-21 23:25:50579 WriteToOutputCorpus(U);
580 NumberOfNewUnitsAdded++;
Alex Shlyapnikov5ded0702017-10-23 23:24:33581 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50582 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50583}
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) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33589 if (!HasMoreMallocsThanFrees)
590 return; // mallocs==frees, a leak is unlikely.
591 if (!Options.DetectLeaks)
592 return;
Max Moroz3f26dac2017-09-12 02:01:54593 if (!DuringInitialCorpusExecution &&
Alex Shlyapnikov5ded0702017-10-23 23:24:33594 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
595 return;
George Karpenkov10ab2ac2017-08-21 23:25:50596 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
597 !(EF->__lsan_do_recoverable_leak_check))
Alex Shlyapnikov5ded0702017-10-23 23:24:33598 return; // No lsan.
George Karpenkov10ab2ac2017-08-21 23:25:50599 // 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();
Alex Shlyapnikov5ded0702017-10-23 23:24:33604 if (!HasMoreMallocsThanFrees)
605 return; // a leak is unlikely.
George Karpenkov10ab2ac2017-08-21 23:25:50606 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();
Alex Shlyapnikov5ded0702017-10-23 23:24:33626 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
George Karpenkov10ab2ac2017-08-21 23:25:50627 }
628}
629
630void Fuzzer::MutateAndTestOne() {
631 MD.StartMutationSequence();
632
633 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany4083d542017-10-11 01:44:26634 if (Options.UseFeatureFrequency)
635 Corpus.UpdateFeatureFrequencyScore(&II);
George Karpenkov10ab2ac2017-08-21 23:25:50636 const auto &U = II.U;
637 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
638 assert(CurrentUnitData);
639 size_t Size = U.size();
640 assert(Size <= MaxInputLen && "Oversized Unit");
641 memcpy(CurrentUnitData, U.data(), Size);
642
643 assert(MaxMutationLen > 0);
644
645 size_t CurrentMaxMutationLen =
646 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
647 assert(CurrentMaxMutationLen > 0);
648
649 for (int i = 0; i < Options.MutateDepth; i++) {
650 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
651 break;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19652 MaybeExitGracefully();
George Karpenkov10ab2ac2017-08-21 23:25:50653 size_t NewSize = 0;
654 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
655 assert(NewSize > 0 && "Mutator returned empty unit");
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30656 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
George Karpenkov10ab2ac2017-08-21 23:25:50657 Size = NewSize;
658 II.NumExecutedMutations++;
George Karpenkov10ab2ac2017-08-21 23:25:50659
Kostya Serebryanyad05ee02017-12-01 19:18:38660 bool FoundUniqFeatures = false;
661 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
662 &FoundUniqFeatures);
George Karpenkov10ab2ac2017-08-21 23:25:50663 TryDetectingAMemoryLeak(CurrentUnitData, Size,
664 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryanyad05ee02017-12-01 19:18:38665 if (NewCov) {
Matt Morehouse947838c2017-11-09 20:44:08666 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryanyad05ee02017-12-01 19:18:38667 break; // We will mutate this input more in the next rounds.
668 }
669 if (Options.ReduceDepth && !FoundUniqFeatures)
670 break;
George Karpenkov10ab2ac2017-08-21 23:25:50671 }
672}
673
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30674void Fuzzer::PurgeAllocator() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33675 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30676 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30677 if (duration_cast<seconds>(system_clock::now() -
Alex Shlyapnikov5ded0702017-10-23 23:24:33678 LastAllocatorPurgeAttemptTime)
679 .count() < Options.PurgeAllocatorIntervalSec)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30680 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30681
682 if (Options.RssLimitMb <= 0 ||
Alex Shlyapnikov5ded0702017-10-23 23:24:33683 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30684 EF->__sanitizer_purge_allocator();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30685
686 LastAllocatorPurgeAttemptTime = system_clock::now();
687}
688
Kostya Serebryany3a8e3c82017-08-29 02:05:01689void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
690 const size_t kMaxSaneLen = 1 << 20;
691 const size_t kMinDefaultLen = 4096;
Kostya Serebryany4faeb872017-08-29 20:51:24692 Vector<SizedFile> SizedFiles;
693 size_t MaxSize = 0;
694 size_t MinSize = -1;
695 size_t TotalSize = 0;
Kostya Serebryany93679be2017-09-12 21:58:07696 size_t LastNumFiles = 0;
Kostya Serebryany4faeb872017-08-29 20:51:24697 for (auto &Dir : CorpusDirs) {
Kostya Serebryany93679be2017-09-12 21:58:07698 GetSizedFilesFromDir(Dir, &SizedFiles);
699 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
700 Dir.c_str());
701 LastNumFiles = SizedFiles.size();
702 }
703 for (auto &File : SizedFiles) {
704 MaxSize = Max(File.Size, MaxSize);
705 MinSize = Min(File.Size, MinSize);
706 TotalSize += File.Size;
Kostya Serebryany3a8e3c82017-08-29 02:05:01707 }
Kostya Serebryany4faeb872017-08-29 20:51:24708 if (Options.MaxLen == 0)
709 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
710 assert(MaxInputLen > 0);
711
Kostya Serebryany51823d32017-10-13 01:12:23712 // Test the callback with empty input and never try it again.
713 uint8_t dummy = 0;
714 ExecuteCallback(&dummy, 0);
715
Kostya Serebryany4faeb872017-08-29 20:51:24716 if (SizedFiles.empty()) {
717 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
718 Unit U({'\n'}); // Valid ASCII input.
719 RunOne(U.data(), U.size());
720 } else {
721 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
722 " rss: %zdMb\n",
723 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
724 if (Options.ShuffleAtStartUp)
725 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
726
Kostya Serebryany93679be2017-09-12 21:58:07727 if (Options.PreferSmall) {
728 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
729 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
730 }
Kostya Serebryany4faeb872017-08-29 20:51:24731
732 // Load and execute inputs one by one.
733 for (auto &SF : SizedFiles) {
Kostya Serebryany082e9a72017-08-31 19:17:15734 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
Kostya Serebryany4faeb872017-08-29 20:51:24735 assert(U.size() <= MaxInputLen);
736 RunOne(U.data(), U.size());
737 CheckExitOnSrcPosOrItem();
738 TryDetectingAMemoryLeak(U.data(), U.size(),
739 /*DuringInitialCorpusExecution*/ true);
740 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01741 }
742
Kostya Serebryany4faeb872017-08-29 20:51:24743 PrintStats("INITED");
744 if (Corpus.empty()) {
745 Printf("ERROR: no interesting inputs were found. "
746 "Is the code instrumented for coverage? Exiting.\n");
747 exit(1);
Kostya Serebryany3a8e3c82017-08-29 02:05:01748 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01749}
750
751void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
752 ReadAndExecuteSeedCorpora(CorpusDirs);
George Karpenkov10ab2ac2017-08-21 23:25:50753 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryany2eef8162017-08-25 20:09:25754 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
George Karpenkov10ab2ac2017-08-21 23:25:50755 system_clock::time_point LastCorpusReload = system_clock::now();
756 if (Options.DoCrossOver)
757 MD.SetCorpus(&Corpus);
758 while (true) {
759 auto Now = system_clock::now();
760 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
761 Options.ReloadIntervalSec) {
762 RereadOutputCorpus(MaxInputLen);
763 LastCorpusReload = system_clock::now();
764 }
765 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
766 break;
Alex Shlyapnikov5ded0702017-10-23 23:24:33767 if (TimedOut())
768 break;
George Karpenkov10ab2ac2017-08-21 23:25:50769
770 // Update TmpMaxMutationLen
Matt Morehouse36c89b32018-02-13 20:52:15771 if (Options.LenControl) {
George Karpenkov10ab2ac2017-08-21 23:25:50772 if (TmpMaxMutationLen < MaxMutationLen &&
Kostya Serebryanye9ed2322017-12-12 23:11:28773 TotalNumberOfRuns - LastCorpusUpdateRun >
Matt Morehouse36c89b32018-02-13 20:52:15774 Options.LenControl * Log(TmpMaxMutationLen)) {
George Karpenkov10ab2ac2017-08-21 23:25:50775 TmpMaxMutationLen =
Kostya Serebryanye9ed2322017-12-12 23:11:28776 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
Kostya Serebryanye9ed2322017-12-12 23:11:28777 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50778 }
779 } else {
780 TmpMaxMutationLen = MaxMutationLen;
781 }
782
783 // Perform several mutations and runs.
784 MutateAndTestOne();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30785
786 PurgeAllocator();
George Karpenkov10ab2ac2017-08-21 23:25:50787 }
788
789 PrintStats("DONE ", "\n");
790 MD.PrintRecommendedDictionary();
791}
792
793void Fuzzer::MinimizeCrashLoop(const Unit &U) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33794 if (U.size() <= 1)
795 return;
George Karpenkov10ab2ac2017-08-21 23:25:50796 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
797 MD.StartMutationSequence();
798 memcpy(CurrentUnitData, U.data(), U.size());
799 for (int i = 0; i < Options.MutateDepth; i++) {
800 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
801 assert(NewSize > 0 && NewSize <= MaxMutationLen);
802 ExecuteCallback(CurrentUnitData, NewSize);
803 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
804 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
805 /*DuringInitialCorpusExecution*/ false);
806 }
807 }
808}
809
810void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
811 if (SMR.IsServer()) {
812 SMR.WriteByteArray(Data, Size);
813 } else if (SMR.IsClient()) {
814 SMR.PostClient();
815 SMR.WaitServer();
816 size_t OtherSize = SMR.ReadByteArraySize();
817 uint8_t *OtherData = SMR.GetByteArray();
818 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
819 size_t i = 0;
820 for (i = 0; i < Min(Size, OtherSize); i++)
821 if (Data[i] != OtherData[i])
822 break;
823 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
Alex Shlyapnikov5ded0702017-10-23 23:24:33824 "offset %zd\n",
825 GetPid(), Size, OtherSize, i);
George Karpenkov10ab2ac2017-08-21 23:25:50826 DumpCurrentUnit("mismatch-");
827 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
828 PrintFinalStats();
829 _Exit(Options.ErrorExitCode);
830 }
831 }
832}
833
834} // namespace fuzzer
835
836extern "C" {
837
Petr Hosekeac2b472018-01-17 20:39:14838__attribute__((visibility("default"))) size_t
839LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
George Karpenkov10ab2ac2017-08-21 23:25:50840 assert(fuzzer::F);
841 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
842}
843
844// Experimental
Petr Hosekeac2b472018-01-17 20:39:14845__attribute__((visibility("default"))) void
846LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
George Karpenkov10ab2ac2017-08-21 23:25:50847 assert(fuzzer::F);
848 fuzzer::F->AnnounceOutput(Data, Size);
849}
Alex Shlyapnikov5ded0702017-10-23 23:24:33850} // extern "C"