blob: 9c19ba913205c75fd3cd96b9e03d99af7c522616 [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);
151 TPC.SetUseValueProfile(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);
George Karpenkov10ab2ac2017-08-21 23:25:50163}
164
Alex Shlyapnikov5ded0702017-10-23 23:24:33165Fuzzer::~Fuzzer() {}
George Karpenkov10ab2ac2017-08-21 23:25:50166
167void Fuzzer::AllocateCurrentUnitData() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33168 if (CurrentUnitData || MaxInputLen == 0)
169 return;
George Karpenkov10ab2ac2017-08-21 23:25:50170 CurrentUnitData = new uint8_t[MaxInputLen];
171}
172
173void Fuzzer::StaticDeathCallback() {
174 assert(F);
175 F->DeathCallback();
176}
177
178void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33179 if (!CurrentUnitData)
180 return; // Happens when running individual inputs.
George Karpenkov10ab2ac2017-08-21 23:25:50181 MD.PrintMutationSequence();
182 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
183 size_t UnitSize = CurrentUnitSize;
184 if (UnitSize <= kMaxUnitSizeToPrint) {
185 PrintHexArray(CurrentUnitData, UnitSize, "\n");
186 PrintASCII(CurrentUnitData, UnitSize, "\n");
187 }
188 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
189 Prefix);
190}
191
192NO_SANITIZE_MEMORY
193void Fuzzer::DeathCallback() {
194 DumpCurrentUnit("crash-");
195 PrintFinalStats();
196}
197
198void Fuzzer::StaticAlarmCallback() {
199 assert(F);
200 F->AlarmCallback();
201}
202
203void Fuzzer::StaticCrashSignalCallback() {
204 assert(F);
205 F->CrashCallback();
206}
207
208void Fuzzer::StaticExitCallback() {
209 assert(F);
210 F->ExitCallback();
211}
212
213void Fuzzer::StaticInterruptCallback() {
214 assert(F);
215 F->InterruptCallback();
216}
217
Kostya Serebryanya2ca2dc2017-11-09 20:30:19218void Fuzzer::StaticGracefulExitCallback() {
219 assert(F);
220 F->GracefulExitRequested = true;
221 Printf("INFO: signal received, trying to exit gracefully\n");
222}
223
George Karpenkov10ab2ac2017-08-21 23:25:50224void Fuzzer::StaticFileSizeExceedCallback() {
225 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
226 exit(1);
227}
228
229void Fuzzer::CrashCallback() {
Matt Morehouse7764a042018-05-02 02:55:28230 if (EF->__sanitizer_acquire_crash_state)
231 EF->__sanitizer_acquire_crash_state();
George Karpenkov10ab2ac2017-08-21 23:25:50232 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
Matt Morehouse14cf71a2018-05-08 23:45:05233 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50234 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
Matt Morehouse52fd1692018-05-01 21:01:53246 if (EF->__sanitizer_acquire_crash_state &&
247 !EF->__sanitizer_acquire_crash_state())
248 return;
George Karpenkov10ab2ac2017-08-21 23:25:50249 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
Matt Morehouse14cf71a2018-05-08 23:45:05250 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50251 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
252 DumpCurrentUnit("crash-");
253 PrintFinalStats();
254 _Exit(Options.ErrorExitCode);
255}
256
Kostya Serebryanya2ca2dc2017-11-09 20:30:19257void Fuzzer::MaybeExitGracefully() {
258 if (!GracefulExitRequested) return;
259 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
260 PrintFinalStats();
261 _Exit(0);
262}
263
George Karpenkov10ab2ac2017-08-21 23:25:50264void Fuzzer::InterruptCallback() {
265 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
266 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33267 _Exit(0); // Stop right now, don't perform any at-exit actions.
George Karpenkov10ab2ac2017-08-21 23:25:50268}
269
270NO_SANITIZE_MEMORY
271void Fuzzer::AlarmCallback() {
272 assert(Options.UnitTimeoutSec > 0);
273 // In Windows Alarm callback is executed by a different thread.
274#if !LIBFUZZER_WINDOWS
Alex Shlyapnikov5ded0702017-10-23 23:24:33275 if (!InFuzzingThread())
276 return;
George Karpenkov10ab2ac2017-08-21 23:25:50277#endif
278 if (!RunningCB)
279 return; // We have not started running units yet.
280 size_t Seconds =
281 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
282 if (Seconds == 0)
283 return;
284 if (Options.Verbosity >= 2)
285 Printf("AlarmCallback %zd\n", Seconds);
286 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Matt Morehouse52fd1692018-05-01 21:01:53287 if (EF->__sanitizer_acquire_crash_state &&
288 !EF->__sanitizer_acquire_crash_state())
289 return;
George Karpenkov10ab2ac2017-08-21 23:25:50290 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
291 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
292 Options.UnitTimeoutSec);
293 DumpCurrentUnit("timeout-");
294 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
295 Seconds);
Matt Morehouse14cf71a2018-05-08 23:45:05296 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50297 Printf("SUMMARY: libFuzzer: timeout\n");
298 PrintFinalStats();
299 _Exit(Options.TimeoutExitCode); // Stop right now.
300 }
301}
302
303void Fuzzer::RssLimitCallback() {
Matt Morehouse52fd1692018-05-01 21:01:53304 if (EF->__sanitizer_acquire_crash_state &&
305 !EF->__sanitizer_acquire_crash_state())
306 return;
George Karpenkov10ab2ac2017-08-21 23:25:50307 Printf(
308 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
309 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
310 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Matt Morehouse14cf71a2018-05-08 23:45:05311 PrintMemoryProfile();
George Karpenkov10ab2ac2017-08-21 23:25:50312 DumpCurrentUnit("oom-");
313 Printf("SUMMARY: libFuzzer: out-of-memory\n");
314 PrintFinalStats();
315 _Exit(Options.ErrorExitCode); // Stop right now.
316}
317
318void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
319 size_t ExecPerSec = execPerSec();
320 if (!Options.Verbosity)
321 return;
322 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
323 if (size_t N = TPC.GetTotalPCCoverage())
324 Printf(" cov: %zd", N);
325 if (size_t N = Corpus.NumFeatures())
Alex Shlyapnikov5ded0702017-10-23 23:24:33326 Printf(" ft: %zd", N);
George Karpenkov10ab2ac2017-08-21 23:25:50327 if (!Corpus.empty()) {
328 Printf(" corp: %zd", Corpus.NumActiveUnits());
329 if (size_t N = Corpus.SizeInBytes()) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33330 if (N < (1 << 14))
George Karpenkov10ab2ac2017-08-21 23:25:50331 Printf("/%zdb", N);
332 else if (N < (1 << 24))
333 Printf("/%zdKb", N >> 10);
334 else
335 Printf("/%zdMb", N >> 20);
336 }
Kostya Serebryanye9c6f062018-05-16 23:26:37337 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
338 Printf(" focus: %zd", FF);
George Karpenkov10ab2ac2017-08-21 23:25:50339 }
Matt Morehouseddf352b2018-02-22 19:00:17340 if (TmpMaxMutationLen)
341 Printf(" lim: %zd", TmpMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50342 if (Units)
343 Printf(" units: %zd", Units);
344
345 Printf(" exec/s: %zd", ExecPerSec);
346 Printf(" rss: %zdMb", GetPeakRSSMb());
347 Printf("%s", End);
348}
349
350void Fuzzer::PrintFinalStats() {
351 if (Options.PrintCoverage)
352 TPC.PrintCoverage();
Kostya Serebryany69c2b712018-05-21 19:47:00353 if (Options.DumpCoverage)
354 TPC.DumpCoverage();
George Karpenkov10ab2ac2017-08-21 23:25:50355 if (Options.PrintCorpusStats)
356 Corpus.PrintStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33357 if (!Options.PrintFinalStats)
358 return;
George Karpenkov10ab2ac2017-08-21 23:25:50359 size_t ExecPerSec = execPerSec();
360 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
361 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
362 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
363 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
364 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
365}
366
367void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
368 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
369 assert(MaxInputLen);
370 this->MaxInputLen = MaxInputLen;
371 this->MaxMutationLen = MaxInputLen;
372 AllocateCurrentUnitData();
373 Printf("INFO: -max_len is not provided; "
374 "libFuzzer will not generate inputs larger than %zd bytes\n",
375 MaxInputLen);
376}
377
378void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
379 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
380 this->MaxMutationLen = MaxMutationLen;
381}
382
383void Fuzzer::CheckExitOnSrcPosOrItem() {
384 if (!Options.ExitOnSrcPos.empty()) {
George Karpenkovbebcbfb2017-08-27 23:20:09385 static auto *PCsSet = new Set<uintptr_t>;
George Karpenkov10ab2ac2017-08-21 23:25:50386 auto HandlePC = [&](uintptr_t PC) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33387 if (!PCsSet->insert(PC).second)
388 return;
George Karpenkov10ab2ac2017-08-21 23:25:50389 std::string Descr = DescribePC("%F %L", PC + 1);
390 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
391 Printf("INFO: found line matching '%s', exiting.\n",
392 Options.ExitOnSrcPos.c_str());
393 _Exit(0);
394 }
395 };
396 TPC.ForEachObservedPC(HandlePC);
397 }
398 if (!Options.ExitOnItem.empty()) {
399 if (Corpus.HasUnit(Options.ExitOnItem)) {
400 Printf("INFO: found item with checksum '%s', exiting.\n",
401 Options.ExitOnItem.c_str());
402 _Exit(0);
403 }
404 }
405}
406
407void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33408 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
409 return;
George Karpenkovbebcbfb2017-08-27 23:20:09410 Vector<Unit> AdditionalCorpus;
George Karpenkov10ab2ac2017-08-21 23:25:50411 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
412 &EpochOfLastReadOfOutputCorpus, MaxSize,
413 /*ExitOnError*/ false);
414 if (Options.Verbosity >= 2)
415 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
416 bool Reloaded = false;
417 for (auto &U : AdditionalCorpus) {
418 if (U.size() > MaxSize)
419 U.resize(MaxSize);
420 if (!Corpus.HasUnit(U)) {
421 if (RunOne(U.data(), U.size())) {
422 CheckExitOnSrcPosOrItem();
423 Reloaded = true;
424 }
425 }
426 }
427 if (Reloaded)
428 PrintStats("RELOAD");
429}
430
George Karpenkov10ab2ac2017-08-21 23:25:50431void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
432 auto TimeOfUnit =
433 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
434 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
435 secondsSinceProcessStartUp() >= 2)
436 PrintStats("pulse ");
437 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
438 TimeOfUnit >= Options.ReportSlowUnits) {
439 TimeOfLongestUnitInSeconds = TimeOfUnit;
440 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
441 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
442 }
443}
444
445bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
Kostya Serebryanyad05ee02017-12-01 19:18:38446 InputInfo *II, bool *FoundUniqFeatures) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33447 if (!Size)
448 return false;
George Karpenkov10ab2ac2017-08-21 23:25:50449
450 ExecuteCallback(Data, Size);
451
452 UniqFeatureSetTmp.clear();
453 size_t FoundUniqFeaturesOfII = 0;
454 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
455 TPC.CollectFeatures([&](size_t Feature) {
Kostya Serebryany2659c632017-12-08 22:21:42456 if (Options.UseFeatureFrequency)
457 Corpus.UpdateFeatureFrequency(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(),
George Karpenkov10ab2ac2017-08-21 23:25:50473 UniqFeatureSetTmp);
474 return true;
475 }
476 if (II && FoundUniqFeaturesOfII &&
477 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
478 II->U.size() > Size) {
479 Corpus.Replace(II, {Data, Data + Size});
480 return true;
481 }
482 return false;
483}
484
485size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
486 assert(InFuzzingThread());
487 *Data = CurrentUnitData;
488 return CurrentUnitSize;
489}
490
491void Fuzzer::CrashOnOverwrittenData() {
492 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
493 GetPid());
494 DumpCurrentUnit("crash-");
495 Printf("SUMMARY: libFuzzer: out-of-memory\n");
496 _Exit(Options.ErrorExitCode); // Stop right now.
497}
498
499// Compare two arrays, but not all bytes if the arrays are large.
500static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
501 const size_t Limit = 64;
502 if (Size <= 64)
503 return !memcmp(A, B, Size);
504 // Compare first and last Limit/2 bytes.
505 return !memcmp(A, B, Limit / 2) &&
506 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
507}
508
509void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
510 TPC.RecordInitialStack();
511 TotalNumberOfRuns++;
512 assert(InFuzzingThread());
513 if (SMR.IsClient())
514 SMR.WriteByteArray(Data, Size);
515 // We copy the contents of Unit into a separate heap buffer
516 // so that we reliably find buffer overflows in it.
517 uint8_t *DataCopy = new uint8_t[Size];
518 memcpy(DataCopy, Data, Size);
519 if (CurrentUnitData && CurrentUnitData != Data)
520 memcpy(CurrentUnitData, Data, Size);
521 CurrentUnitSize = Size;
522 AllocTracer.Start(Options.TraceMalloc);
523 UnitStartTime = system_clock::now();
524 TPC.ResetMaps();
525 RunningCB = true;
526 int Res = CB(DataCopy, Size);
527 RunningCB = false;
528 UnitStopTime = system_clock::now();
529 (void)Res;
530 assert(Res == 0);
531 HasMoreMallocsThanFrees = AllocTracer.Stop();
532 if (!LooseMemeq(DataCopy, Data, Size))
533 CrashOnOverwrittenData();
534 CurrentUnitSize = 0;
535 delete[] DataCopy;
536}
537
538void Fuzzer::WriteToOutputCorpus(const Unit &U) {
539 if (Options.OnlyASCII)
540 assert(IsASCII(U));
541 if (Options.OutputCorpus.empty())
542 return;
543 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
544 WriteToFile(U, Path);
545 if (Options.Verbosity >= 2)
546 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
547}
548
549void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
550 if (!Options.SaveArtifacts)
551 return;
552 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
553 if (!Options.ExactArtifactPath.empty())
554 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
555 WriteToFile(U, Path);
556 Printf("artifact_prefix='%s'; Test unit written to %s\n",
557 Options.ArtifactPrefix.c_str(), Path.c_str());
558 if (U.size() <= kMaxUnitSizeToPrint)
559 Printf("Base64: %s\n", Base64(U).c_str());
560}
561
562void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
563 if (!Options.PrintNEW)
564 return;
565 PrintStats(Text, "");
566 if (Options.Verbosity) {
567 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
568 MD.PrintMutationSequence();
569 Printf("\n");
570 }
571}
572
573void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
574 II->NumSuccessfullMutations++;
575 MD.RecordSuccessfulMutationSequence();
Alex Shlyapnikov5ded0702017-10-23 23:24:33576 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
George Karpenkov10ab2ac2017-08-21 23:25:50577 WriteToOutputCorpus(U);
578 NumberOfNewUnitsAdded++;
Alex Shlyapnikov5ded0702017-10-23 23:24:33579 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50580 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50581}
582
583// Tries detecting a memory leak on the particular input that we have just
584// executed before calling this function.
585void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
586 bool DuringInitialCorpusExecution) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33587 if (!HasMoreMallocsThanFrees)
588 return; // mallocs==frees, a leak is unlikely.
589 if (!Options.DetectLeaks)
590 return;
Max Moroz3f26dac2017-09-12 02:01:54591 if (!DuringInitialCorpusExecution &&
Alex Shlyapnikov5ded0702017-10-23 23:24:33592 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
593 return;
George Karpenkov10ab2ac2017-08-21 23:25:50594 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
595 !(EF->__lsan_do_recoverable_leak_check))
Alex Shlyapnikov5ded0702017-10-23 23:24:33596 return; // No lsan.
George Karpenkov10ab2ac2017-08-21 23:25:50597 // Run the target once again, but with lsan disabled so that if there is
598 // a real leak we do not report it twice.
599 EF->__lsan_disable();
600 ExecuteCallback(Data, Size);
601 EF->__lsan_enable();
Alex Shlyapnikov5ded0702017-10-23 23:24:33602 if (!HasMoreMallocsThanFrees)
603 return; // a leak is unlikely.
George Karpenkov10ab2ac2017-08-21 23:25:50604 if (NumberOfLeakDetectionAttempts++ > 1000) {
605 Options.DetectLeaks = false;
606 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
607 " Most likely the target function accumulates allocated\n"
608 " memory in a global state w/o actually leaking it.\n"
609 " You may try running this binary with -trace_malloc=[12]"
610 " to get a trace of mallocs and frees.\n"
611 " If LeakSanitizer is enabled in this process it will still\n"
612 " run on the process shutdown.\n");
613 return;
614 }
615 // Now perform the actual lsan pass. This is expensive and we must ensure
616 // we don't call it too often.
617 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
618 if (DuringInitialCorpusExecution)
619 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
620 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
621 CurrentUnitSize = Size;
622 DumpCurrentUnit("leak-");
623 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33624 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
George Karpenkov10ab2ac2017-08-21 23:25:50625 }
626}
627
628void Fuzzer::MutateAndTestOne() {
629 MD.StartMutationSequence();
630
631 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany4083d542017-10-11 01:44:26632 if (Options.UseFeatureFrequency)
633 Corpus.UpdateFeatureFrequencyScore(&II);
George Karpenkov10ab2ac2017-08-21 23:25:50634 const auto &U = II.U;
635 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
636 assert(CurrentUnitData);
637 size_t Size = U.size();
638 assert(Size <= MaxInputLen && "Oversized Unit");
639 memcpy(CurrentUnitData, U.data(), Size);
640
641 assert(MaxMutationLen > 0);
642
643 size_t CurrentMaxMutationLen =
644 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
645 assert(CurrentMaxMutationLen > 0);
646
647 for (int i = 0; i < Options.MutateDepth; i++) {
648 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
649 break;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19650 MaybeExitGracefully();
George Karpenkov10ab2ac2017-08-21 23:25:50651 size_t NewSize = 0;
652 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
653 assert(NewSize > 0 && "Mutator returned empty unit");
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30654 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
George Karpenkov10ab2ac2017-08-21 23:25:50655 Size = NewSize;
656 II.NumExecutedMutations++;
George Karpenkov10ab2ac2017-08-21 23:25:50657
Kostya Serebryanyad05ee02017-12-01 19:18:38658 bool FoundUniqFeatures = false;
659 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
660 &FoundUniqFeatures);
George Karpenkov10ab2ac2017-08-21 23:25:50661 TryDetectingAMemoryLeak(CurrentUnitData, Size,
662 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryanyad05ee02017-12-01 19:18:38663 if (NewCov) {
Matt Morehouse947838c2017-11-09 20:44:08664 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryanyad05ee02017-12-01 19:18:38665 break; // We will mutate this input more in the next rounds.
666 }
667 if (Options.ReduceDepth && !FoundUniqFeatures)
668 break;
George Karpenkov10ab2ac2017-08-21 23:25:50669 }
670}
671
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30672void Fuzzer::PurgeAllocator() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33673 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30674 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30675 if (duration_cast<seconds>(system_clock::now() -
Alex Shlyapnikov5ded0702017-10-23 23:24:33676 LastAllocatorPurgeAttemptTime)
677 .count() < Options.PurgeAllocatorIntervalSec)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30678 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30679
680 if (Options.RssLimitMb <= 0 ||
Alex Shlyapnikov5ded0702017-10-23 23:24:33681 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30682 EF->__sanitizer_purge_allocator();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30683
684 LastAllocatorPurgeAttemptTime = system_clock::now();
685}
686
Kostya Serebryany3a8e3c82017-08-29 02:05:01687void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
688 const size_t kMaxSaneLen = 1 << 20;
689 const size_t kMinDefaultLen = 4096;
Kostya Serebryany4faeb872017-08-29 20:51:24690 Vector<SizedFile> SizedFiles;
691 size_t MaxSize = 0;
692 size_t MinSize = -1;
693 size_t TotalSize = 0;
Kostya Serebryany93679be2017-09-12 21:58:07694 size_t LastNumFiles = 0;
Kostya Serebryany4faeb872017-08-29 20:51:24695 for (auto &Dir : CorpusDirs) {
Kostya Serebryany93679be2017-09-12 21:58:07696 GetSizedFilesFromDir(Dir, &SizedFiles);
697 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
698 Dir.c_str());
699 LastNumFiles = SizedFiles.size();
700 }
701 for (auto &File : SizedFiles) {
702 MaxSize = Max(File.Size, MaxSize);
703 MinSize = Min(File.Size, MinSize);
704 TotalSize += File.Size;
Kostya Serebryany3a8e3c82017-08-29 02:05:01705 }
Kostya Serebryany4faeb872017-08-29 20:51:24706 if (Options.MaxLen == 0)
707 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
708 assert(MaxInputLen > 0);
709
Kostya Serebryany51823d32017-10-13 01:12:23710 // Test the callback with empty input and never try it again.
711 uint8_t dummy = 0;
712 ExecuteCallback(&dummy, 0);
713
Kostya Serebryany4faeb872017-08-29 20:51:24714 if (SizedFiles.empty()) {
715 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
716 Unit U({'\n'}); // Valid ASCII input.
717 RunOne(U.data(), U.size());
718 } else {
719 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
720 " rss: %zdMb\n",
721 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
722 if (Options.ShuffleAtStartUp)
723 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
724
Kostya Serebryany93679be2017-09-12 21:58:07725 if (Options.PreferSmall) {
726 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
727 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
728 }
Kostya Serebryany4faeb872017-08-29 20:51:24729
730 // Load and execute inputs one by one.
731 for (auto &SF : SizedFiles) {
Kostya Serebryany082e9a72017-08-31 19:17:15732 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
Kostya Serebryany4faeb872017-08-29 20:51:24733 assert(U.size() <= MaxInputLen);
734 RunOne(U.data(), U.size());
735 CheckExitOnSrcPosOrItem();
736 TryDetectingAMemoryLeak(U.data(), U.size(),
737 /*DuringInitialCorpusExecution*/ true);
738 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01739 }
740
Kostya Serebryany4faeb872017-08-29 20:51:24741 PrintStats("INITED");
Kostya Serebryanye9c6f062018-05-16 23:26:37742 if (!Options.FocusFunction.empty())
743 Printf("INFO: %zd/%zd inputs touch the focus function\n",
744 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
745
Max Morozfe974412018-05-23 19:42:30746 if (Corpus.empty() && Options.MaxNumberOfRuns) {
Kostya Serebryany4faeb872017-08-29 20:51:24747 Printf("ERROR: no interesting inputs were found. "
748 "Is the code instrumented for coverage? Exiting.\n");
749 exit(1);
Kostya Serebryany3a8e3c82017-08-29 02:05:01750 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01751}
752
753void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
754 ReadAndExecuteSeedCorpora(CorpusDirs);
George Karpenkov10ab2ac2017-08-21 23:25:50755 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryany2eef8162017-08-25 20:09:25756 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
George Karpenkov10ab2ac2017-08-21 23:25:50757 system_clock::time_point LastCorpusReload = system_clock::now();
758 if (Options.DoCrossOver)
759 MD.SetCorpus(&Corpus);
760 while (true) {
761 auto Now = system_clock::now();
762 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
763 Options.ReloadIntervalSec) {
764 RereadOutputCorpus(MaxInputLen);
765 LastCorpusReload = system_clock::now();
766 }
767 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
768 break;
Alex Shlyapnikov5ded0702017-10-23 23:24:33769 if (TimedOut())
770 break;
George Karpenkov10ab2ac2017-08-21 23:25:50771
772 // Update TmpMaxMutationLen
Matt Morehouse36c89b32018-02-13 20:52:15773 if (Options.LenControl) {
George Karpenkov10ab2ac2017-08-21 23:25:50774 if (TmpMaxMutationLen < MaxMutationLen &&
Kostya Serebryanye9ed2322017-12-12 23:11:28775 TotalNumberOfRuns - LastCorpusUpdateRun >
Matt Morehouse36c89b32018-02-13 20:52:15776 Options.LenControl * Log(TmpMaxMutationLen)) {
George Karpenkov10ab2ac2017-08-21 23:25:50777 TmpMaxMutationLen =
Kostya Serebryanye9ed2322017-12-12 23:11:28778 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
Kostya Serebryanye9ed2322017-12-12 23:11:28779 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50780 }
781 } else {
782 TmpMaxMutationLen = MaxMutationLen;
783 }
784
785 // Perform several mutations and runs.
786 MutateAndTestOne();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30787
788 PurgeAllocator();
George Karpenkov10ab2ac2017-08-21 23:25:50789 }
790
791 PrintStats("DONE ", "\n");
792 MD.PrintRecommendedDictionary();
793}
794
795void Fuzzer::MinimizeCrashLoop(const Unit &U) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33796 if (U.size() <= 1)
797 return;
George Karpenkov10ab2ac2017-08-21 23:25:50798 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
799 MD.StartMutationSequence();
800 memcpy(CurrentUnitData, U.data(), U.size());
801 for (int i = 0; i < Options.MutateDepth; i++) {
802 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
803 assert(NewSize > 0 && NewSize <= MaxMutationLen);
804 ExecuteCallback(CurrentUnitData, NewSize);
805 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
806 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
807 /*DuringInitialCorpusExecution*/ false);
808 }
809 }
810}
811
812void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
813 if (SMR.IsServer()) {
814 SMR.WriteByteArray(Data, Size);
815 } else if (SMR.IsClient()) {
816 SMR.PostClient();
817 SMR.WaitServer();
818 size_t OtherSize = SMR.ReadByteArraySize();
819 uint8_t *OtherData = SMR.GetByteArray();
820 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
821 size_t i = 0;
822 for (i = 0; i < Min(Size, OtherSize); i++)
823 if (Data[i] != OtherData[i])
824 break;
825 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
Alex Shlyapnikov5ded0702017-10-23 23:24:33826 "offset %zd\n",
827 GetPid(), Size, OtherSize, i);
George Karpenkov10ab2ac2017-08-21 23:25:50828 DumpCurrentUnit("mismatch-");
829 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
830 PrintFinalStats();
831 _Exit(Options.ErrorExitCode);
832 }
833 }
834}
835
836} // namespace fuzzer
837
838extern "C" {
839
Petr Hosekeac2b472018-01-17 20:39:14840__attribute__((visibility("default"))) size_t
841LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
George Karpenkov10ab2ac2017-08-21 23:25:50842 assert(fuzzer::F);
843 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
844}
845
846// Experimental
Petr Hosekeac2b472018-01-17 20:39:14847__attribute__((visibility("default"))) void
848LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
George Karpenkov10ab2ac2017-08-21 23:25:50849 assert(fuzzer::F);
850 fuzzer::F->AnnounceOutput(Data, Size);
851}
Alex Shlyapnikov5ded0702017-10-23 23:24:33852} // extern "C"