Debian Codegraph @

tools/fuzzing/libfuzzer/FuzzerLoop.cpp

raw
1 //===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 // Fuzzer's main loop.
9 //===----------------------------------------------------------------------===//
10
11 #include "FuzzerCorpus.h"
12 #include "FuzzerIO.h"
13 #include "FuzzerInternal.h"
14 #include "FuzzerMutate.h"
15 #include "FuzzerPlatform.h"
16 #include "FuzzerRandom.h"
17 #include "FuzzerTracePC.h"
18 #include <algorithm>
19 #include <cstring>
20 #include <memory>
21 #include <mutex>
22 #include <set>
23
24 #if defined(__has_include)
25 #if __has_include(<sanitizer / lsan_interface.h>)
26 #include <sanitizer/lsan_interface.h>
27 #endif
28 #endif
29
30 #define NO_SANITIZE_MEMORY
31 #if defined(__has_feature)
32 #if __has_feature(memory_sanitizer)
33 #undef NO_SANITIZE_MEMORY
34 #define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
35 #endif
36 #endif
37
38 namespace fuzzer {
39 static const size_t kMaxUnitSizeToPrint = 256;
40
41 thread_local bool Fuzzer::IsMyThread;
42
43 bool RunningUserCallback = false;
44
45 // Only one Fuzzer per process.
46 static Fuzzer *F;
47
48 // Leak detection is expensive, so we first check if there were more mallocs
49 // than frees (using the sanitizer malloc hooks) and only then try to call lsan.
50 struct MallocFreeTracer {
51 void Start(int TraceLevel) {
52 this->TraceLevel = TraceLevel;
53 if (TraceLevel)
54 Printf("MallocFreeTracer: START\n");
55 Mallocs = 0;
56 Frees = 0;
57 }
58 // Returns true if there were more mallocs than frees.
59 bool Stop() {
60 if (TraceLevel)
61 Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
62 Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
63 bool Result = Mallocs > Frees;
64 Mallocs = 0;
65 Frees = 0;
66 TraceLevel = 0;
67 return Result;
68 }
69 std::atomic<size_t> Mallocs;
70 std::atomic<size_t> Frees;
71 int TraceLevel = 0;
72
73 std::recursive_mutex TraceMutex;
74 bool TraceDisabled = false;
75 };
76
77 static MallocFreeTracer AllocTracer;
78
79 // Locks printing and avoids nested hooks triggered from mallocs/frees in
80 // sanitizer.
81 class TraceLock {
82 public:
83 TraceLock() : Lock(AllocTracer.TraceMutex) {
84 AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
85 }
86 ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
87
88 bool IsDisabled() const {
89 // This is already inverted value.
90 return !AllocTracer.TraceDisabled;
91 }
92
93 private:
94 std::lock_guard<std::recursive_mutex> Lock;
95 };
96
97 ATTRIBUTE_NO_SANITIZE_MEMORY
98 void MallocHook(const volatile void *ptr, size_t size) {
99 size_t N = AllocTracer.Mallocs++;
100 F->HandleMalloc(size);
101 if (int TraceLevel = AllocTracer.TraceLevel) {
102 TraceLock Lock;
103 if (Lock.IsDisabled())
104 return;
105 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
106 if (TraceLevel >= 2 && EF)
107 PrintStackTrace();
108 }
109 }
110
111 ATTRIBUTE_NO_SANITIZE_MEMORY
112 void FreeHook(const volatile void *ptr) {
113 size_t N = AllocTracer.Frees++;
114 if (int TraceLevel = AllocTracer.TraceLevel) {
115 TraceLock Lock;
116 if (Lock.IsDisabled())
117 return;
118 Printf("FREE[%zd] %p\n", N, ptr);
119 if (TraceLevel >= 2 && EF)
120 PrintStackTrace();
121 }
122 }
123
124 // Crash on a single malloc that exceeds the rss limit.
125 void Fuzzer::HandleMalloc(size_t Size) {
126 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
127 return;
128 Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
129 Size);
130 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
131 PrintStackTrace();
132 DumpCurrentUnit("oom-");
133 Printf("SUMMARY: libFuzzer: out-of-memory\n");
134 PrintFinalStats();
135 _Exit(Options.OOMExitCode); // Stop right now.
136 }
137
138 Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
139 FuzzingOptions Options)
140 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
141 if (EF->__sanitizer_set_death_callback)
142 EF->__sanitizer_set_death_callback(StaticDeathCallback);
143 assert(!F);
144 F = this;
145 TPC.ResetMaps();
146 IsMyThread = true;
147 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
148 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
149 TPC.SetUseCounters(Options.UseCounters);
150 TPC.SetUseValueProfileMask(Options.UseValueProfile);
151
152 if (Options.Verbosity)
153 TPC.PrintModuleInfo();
154 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
155 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
156 MaxInputLen = MaxMutationLen = Options.MaxLen;
157 TmpMaxMutationLen = 0; // Will be set once we load the corpus.
158 AllocateCurrentUnitData();
159 CurrentUnitSize = 0;
160 memset(BaseSha1, 0, sizeof(BaseSha1));
161 }
162
163 Fuzzer::~Fuzzer() {}
164
165 void Fuzzer::AllocateCurrentUnitData() {
166 if (CurrentUnitData || MaxInputLen == 0)
167 return;
168 CurrentUnitData = new uint8_t[MaxInputLen];
169 }
170
171 void Fuzzer::StaticDeathCallback() {
172 assert(F);
173 F->DeathCallback();
174 }
175
176 void Fuzzer::DumpCurrentUnit(const char *Prefix) {
177 if (!CurrentUnitData)
178 return; // Happens when running individual inputs.
179 ScopedDisableMsanInterceptorChecks S;
180 MD.PrintMutationSequence();
181 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
182 size_t UnitSize = CurrentUnitSize;
183 if (UnitSize <= kMaxUnitSizeToPrint) {
184 PrintHexArray(CurrentUnitData, UnitSize, "\n");
185 PrintASCII(CurrentUnitData, UnitSize, "\n");
186 }
187 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
188 Prefix);
189 }
190
191 NO_SANITIZE_MEMORY
192 void Fuzzer::DeathCallback() {
193 DumpCurrentUnit("crash-");
194 PrintFinalStats();
195 }
196
197 void Fuzzer::StaticAlarmCallback() {
198 assert(F);
199 F->AlarmCallback();
200 }
201
202 void Fuzzer::StaticCrashSignalCallback() {
203 assert(F);
204 F->CrashCallback();
205 }
206
207 void Fuzzer::StaticExitCallback() {
208 assert(F);
209 F->ExitCallback();
210 }
211
212 void Fuzzer::StaticInterruptCallback() {
213 assert(F);
214 F->InterruptCallback();
215 }
216
217 void Fuzzer::StaticGracefulExitCallback() {
218 assert(F);
219 F->GracefulExitRequested = true;
220 Printf("INFO: signal received, trying to exit gracefully\n");
221 }
222
223 void Fuzzer::StaticFileSizeExceedCallback() {
224 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
225 exit(1);
226 }
227
228 void Fuzzer::CrashCallback() {
229 if (EF->__sanitizer_acquire_crash_state &&
230 !EF->__sanitizer_acquire_crash_state())
231 return;
232 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
233 PrintStackTrace();
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();
240 _Exit(Options.ErrorExitCode); // Stop right now.
241 }
242
243 void Fuzzer::ExitCallback() {
244 if (!RunningUserCallback)
245 return; // This exit did not come from the user callback
246 if (EF->__sanitizer_acquire_crash_state &&
247 !EF->__sanitizer_acquire_crash_state())
248 return;
249 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
250 PrintStackTrace();
251 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
252 DumpCurrentUnit("crash-");
253 PrintFinalStats();
254 _Exit(Options.ErrorExitCode);
255 }
256
257 bool Fuzzer::MaybeExitGracefully() {
258 if (!F->GracefulExitRequested) return false;
259 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
260 RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
261 F->PrintFinalStats();
262 return true;
263 }
264
265 void Fuzzer::GracefullyExit() {
266 F->GracefulExitRequested = true;
267 }
268
269 bool Fuzzer::isGracefulExitRequested() {
270 return F->GracefulExitRequested;
271 }
272
273 void Fuzzer::InterruptCallback() {
274 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
275 PrintFinalStats();
276 ScopedDisableMsanInterceptorChecks S; // RmDirRecursive may call opendir().
277 RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
278 // Stop right now, don't perform any at-exit actions.
279 _Exit(Options.InterruptExitCode);
280 }
281
282 NO_SANITIZE_MEMORY
283 void Fuzzer::AlarmCallback() {
284 assert(Options.UnitTimeoutSec > 0);
285 // In Windows and Fuchsia, Alarm callback is executed by a different thread.
286 // NetBSD's current behavior needs this change too.
287 #if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD && !LIBFUZZER_FUCHSIA
288 if (!InFuzzingThread())
289 return;
290 #endif
291 if (!RunningUserCallback)
292 return; // We have not started running units yet.
293 size_t Seconds =
294 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
295 if (Seconds == 0)
296 return;
297 if (Options.Verbosity >= 2)
298 Printf("AlarmCallback %zd\n", Seconds);
299 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
300 if (EF->__sanitizer_acquire_crash_state &&
301 !EF->__sanitizer_acquire_crash_state())
302 return;
303 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
304 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
305 Options.UnitTimeoutSec);
306 DumpCurrentUnit("timeout-");
307 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
308 Seconds);
309 PrintStackTrace();
310 Printf("SUMMARY: libFuzzer: timeout\n");
311 PrintFinalStats();
312 _Exit(Options.TimeoutExitCode); // Stop right now.
313 }
314 }
315
316 void Fuzzer::RssLimitCallback() {
317 if (EF->__sanitizer_acquire_crash_state &&
318 !EF->__sanitizer_acquire_crash_state())
319 return;
320 Printf(
321 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
322 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
323 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
324 PrintMemoryProfile();
325 DumpCurrentUnit("oom-");
326 Printf("SUMMARY: libFuzzer: out-of-memory\n");
327 PrintFinalStats();
328 _Exit(Options.OOMExitCode); // Stop right now.
329 }
330
331 void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units,
332 size_t Features) {
333 size_t ExecPerSec = execPerSec();
334 if (!Options.Verbosity)
335 return;
336 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
337 if (size_t N = TPC.GetTotalPCCoverage())
338 Printf(" cov: %zd", N);
339 if (size_t N = Features ? Features : Corpus.NumFeatures())
340 Printf(" ft: %zd", N);
341 if (!Corpus.empty()) {
342 Printf(" corp: %zd", Corpus.NumActiveUnits());
343 if (size_t N = Corpus.SizeInBytes()) {
344 if (N < (1 << 14))
345 Printf("/%zdb", N);
346 else if (N < (1 << 24))
347 Printf("/%zdKb", N >> 10);
348 else
349 Printf("/%zdMb", N >> 20);
350 }
351 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
352 Printf(" focus: %zd", FF);
353 }
354 if (TmpMaxMutationLen)
355 Printf(" lim: %zd", TmpMaxMutationLen);
356 if (Units)
357 Printf(" units: %zd", Units);
358
359 Printf(" exec/s: %zd", ExecPerSec);
360 Printf(" rss: %zdMb", GetPeakRSSMb());
361 Printf("%s", End);
362 }
363
364 void Fuzzer::PrintFinalStats() {
365 if (Options.PrintCoverage)
366 TPC.PrintCoverage();
367 if (Options.PrintCorpusStats)
368 Corpus.PrintStats();
369 if (!Options.PrintFinalStats)
370 return;
371 size_t ExecPerSec = execPerSec();
372 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
373 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
374 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
375 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
376 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
377 }
378
379 void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
380 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
381 assert(MaxInputLen);
382 this->MaxInputLen = MaxInputLen;
383 this->MaxMutationLen = MaxInputLen;
384 AllocateCurrentUnitData();
385 Printf("INFO: -max_len is not provided; "
386 "libFuzzer will not generate inputs larger than %zd bytes\n",
387 MaxInputLen);
388 }
389
390 void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
391 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
392 this->MaxMutationLen = MaxMutationLen;
393 }
394
395 void Fuzzer::CheckExitOnSrcPosOrItem() {
396 if (!Options.ExitOnSrcPos.empty()) {
397 static auto *PCsSet = new Set<uintptr_t>;
398 auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
399 if (!PCsSet->insert(TE->PC).second)
400 return;
401 std::string Descr = DescribePC("%F %L", TE->PC + 1);
402 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
403 Printf("INFO: found line matching '%s', exiting.\n",
404 Options.ExitOnSrcPos.c_str());
405 _Exit(0);
406 }
407 };
408 TPC.ForEachObservedPC(HandlePC);
409 }
410 if (!Options.ExitOnItem.empty()) {
411 if (Corpus.HasUnit(Options.ExitOnItem)) {
412 Printf("INFO: found item with checksum '%s', exiting.\n",
413 Options.ExitOnItem.c_str());
414 _Exit(0);
415 }
416 }
417 }
418
419 void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
420 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
421 return;
422 Vector<Unit> AdditionalCorpus;
423 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
424 &EpochOfLastReadOfOutputCorpus, MaxSize,
425 /*ExitOnError*/ false);
426 if (Options.Verbosity >= 2)
427 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
428 bool Reloaded = false;
429 for (auto &U : AdditionalCorpus) {
430 if (U.size() > MaxSize)
431 U.resize(MaxSize);
432 if (!Corpus.HasUnit(U)) {
433 if (RunOne(U.data(), U.size())) {
434 CheckExitOnSrcPosOrItem();
435 Reloaded = true;
436 }
437 }
438 }
439 if (Reloaded)
440 PrintStats("RELOAD");
441 }
442
443 void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
444 auto TimeOfUnit =
445 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
446 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
447 secondsSinceProcessStartUp() >= 2)
448 PrintStats("pulse ");
449 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
450 TimeOfUnit >= Options.ReportSlowUnits) {
451 TimeOfLongestUnitInSeconds = TimeOfUnit;
452 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
453 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
454 }
455 }
456
457 static void WriteFeatureSetToFile(const std::string &FeaturesDir,
458 const std::string &FileName,
459 const Vector<uint32_t> &FeatureSet) {
460 if (FeaturesDir.empty() || FeatureSet.empty()) return;
461 WriteToFile(reinterpret_cast<const uint8_t *>(FeatureSet.data()),
462 FeatureSet.size() * sizeof(FeatureSet[0]),
463 DirPlusFile(FeaturesDir, FileName));
464 }
465
466 static void RenameFeatureSetFile(const std::string &FeaturesDir,
467 const std::string &OldFile,
468 const std::string &NewFile) {
469 if (FeaturesDir.empty()) return;
470 RenameFile(DirPlusFile(FeaturesDir, OldFile),
471 DirPlusFile(FeaturesDir, NewFile));
472 }
473
474 bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
475 InputInfo *II, bool *FoundUniqFeatures) {
476 if (!Size)
477 return false;
478
479 if (ExecuteCallback(Data, Size)) {
480 return false;
481 }
482
483 UniqFeatureSetTmp.clear();
484 size_t FoundUniqFeaturesOfII = 0;
485 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
486 TPC.CollectFeatures([&](size_t Feature) {
487 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
488 UniqFeatureSetTmp.push_back(Feature);
489 if (Options.Entropic)
490 Corpus.UpdateFeatureFrequency(II, Feature);
491 if (Options.ReduceInputs && II)
492 if (std::binary_search(II->UniqFeatureSet.begin(),
493 II->UniqFeatureSet.end(), Feature))
494 FoundUniqFeaturesOfII++;
495 });
496 if (FoundUniqFeatures)
497 *FoundUniqFeatures = FoundUniqFeaturesOfII;
498 PrintPulseAndReportSlowInput(Data, Size);
499 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
500 if (NumNewFeatures) {
501 TPC.UpdateObservedPCs();
502 auto NewII = Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures,
503 MayDeleteFile, TPC.ObservedFocusFunction(),
504 UniqFeatureSetTmp, DFT, II);
505 WriteFeatureSetToFile(Options.FeaturesDir, Sha1ToString(NewII->Sha1),
506 NewII->UniqFeatureSet);
507 return true;
508 }
509 if (II && FoundUniqFeaturesOfII &&
510 II->DataFlowTraceForFocusFunction.empty() &&
511 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
512 II->U.size() > Size) {
513 auto OldFeaturesFile = Sha1ToString(II->Sha1);
514 Corpus.Replace(II, {Data, Data + Size});
515 RenameFeatureSetFile(Options.FeaturesDir, OldFeaturesFile,
516 Sha1ToString(II->Sha1));
517 return true;
518 }
519 return false;
520 }
521
522 size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
523 assert(InFuzzingThread());
524 *Data = CurrentUnitData;
525 return CurrentUnitSize;
526 }
527
528 void Fuzzer::CrashOnOverwrittenData() {
529 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites its const input\n",
530 GetPid());
531 PrintStackTrace();
532 Printf("SUMMARY: libFuzzer: overwrites-const-input\n");
533 DumpCurrentUnit("crash-");
534 PrintFinalStats();
535 _Exit(Options.ErrorExitCode); // Stop right now.
536 }
537
538 // Compare two arrays, but not all bytes if the arrays are large.
539 static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
540 const size_t Limit = 64;
541 if (Size <= 64)
542 return !memcmp(A, B, Size);
543 // Compare first and last Limit/2 bytes.
544 return !memcmp(A, B, Limit / 2) &&
545 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
546 }
547
548 int Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
549 TPC.RecordInitialStack();
550 TotalNumberOfRuns++;
551 assert(InFuzzingThread());
552 // We copy the contents of Unit into a separate heap buffer
553 // so that we reliably find buffer overflows in it.
554 uint8_t *DataCopy = new uint8_t[Size];
555 memcpy(DataCopy, Data, Size);
556 if (EF->__msan_unpoison)
557 EF->__msan_unpoison(DataCopy, Size);
558 if (EF->__msan_unpoison_param)
559 EF->__msan_unpoison_param(2);
560 if (CurrentUnitData && CurrentUnitData != Data)
561 memcpy(CurrentUnitData, Data, Size);
562 CurrentUnitSize = Size;
563 int Res = 0;
564 {
565 ScopedEnableMsanInterceptorChecks S;
566 AllocTracer.Start(Options.TraceMalloc);
567 UnitStartTime = system_clock::now();
568 TPC.ResetMaps();
569 RunningUserCallback = true;
570 Res = CB(DataCopy, Size);
571 RunningUserCallback = false;
572 UnitStopTime = system_clock::now();
573 HasMoreMallocsThanFrees = AllocTracer.Stop();
574 }
575 if (!LooseMemeq(DataCopy, Data, Size))
576 CrashOnOverwrittenData();
577 CurrentUnitSize = 0;
578 delete[] DataCopy;
579 return Res;
580 }
581
582 std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
583 if (Options.OnlyASCII)
584 assert(IsASCII(U));
585 if (Options.OutputCorpus.empty())
586 return "";
587 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
588 WriteToFile(U, Path);
589 if (Options.Verbosity >= 2)
590 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
591 return Path;
592 }
593
594 void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
595 if (!Options.SaveArtifacts)
596 return;
597 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
598 if (!Options.ExactArtifactPath.empty())
599 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
600 WriteToFile(U, Path);
601 Printf("artifact_prefix='%s'; Test unit written to %s\n",
602 Options.ArtifactPrefix.c_str(), Path.c_str());
603 if (U.size() <= kMaxUnitSizeToPrint)
604 Printf("Base64: %s\n", Base64(U).c_str());
605 }
606
607 void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
608 if (!Options.PrintNEW)
609 return;
610 PrintStats(Text, "");
611 if (Options.Verbosity) {
612 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
613 MD.PrintMutationSequence();
614 Printf("\n");
615 }
616 }
617
618 void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
619 II->NumSuccessfullMutations++;
620 MD.RecordSuccessfulMutationSequence();
621 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
622 WriteToOutputCorpus(U);
623 NumberOfNewUnitsAdded++;
624 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
625 LastCorpusUpdateRun = TotalNumberOfRuns;
626 }
627
628 // Tries detecting a memory leak on the particular input that we have just
629 // executed before calling this function.
630 void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
631 bool DuringInitialCorpusExecution) {
632 if (!HasMoreMallocsThanFrees)
633 return; // mallocs==frees, a leak is unlikely.
634 if (!Options.DetectLeaks)
635 return;
636 if (!DuringInitialCorpusExecution &&
637 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
638 return;
639 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
640 !(EF->__lsan_do_recoverable_leak_check))
641 return; // No lsan.
642 // Run the target once again, but with lsan disabled so that if there is
643 // a real leak we do not report it twice.
644 EF->__lsan_disable();
645 ExecuteCallback(Data, Size);
646 EF->__lsan_enable();
647 if (!HasMoreMallocsThanFrees)
648 return; // a leak is unlikely.
649 if (NumberOfLeakDetectionAttempts++ > 1000) {
650 Options.DetectLeaks = false;
651 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
652 " Most likely the target function accumulates allocated\n"
653 " memory in a global state w/o actually leaking it.\n"
654 " You may try running this binary with -trace_malloc=[12]"
655 " to get a trace of mallocs and frees.\n"
656 " If LeakSanitizer is enabled in this process it will still\n"
657 " run on the process shutdown.\n");
658 return;
659 }
660 // Now perform the actual lsan pass. This is expensive and we must ensure
661 // we don't call it too often.
662 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
663 if (DuringInitialCorpusExecution)
664 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
665 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
666 CurrentUnitSize = Size;
667 DumpCurrentUnit("leak-");
668 PrintFinalStats();
669 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
670 }
671 }
672
673 bool Fuzzer::MutateAndTestOne() {
674 MD.StartMutationSequence();
675
676 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
677 if (Options.DoCrossOver)
678 MD.SetCrossOverWith(&Corpus.ChooseUnitToMutate(MD.GetRand()).U);
679 const auto &U = II.U;
680 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
681 assert(CurrentUnitData);
682 size_t Size = U.size();
683 assert(Size <= MaxInputLen && "Oversized Unit");
684 memcpy(CurrentUnitData, U.data(), Size);
685
686 assert(MaxMutationLen > 0);
687
688 size_t CurrentMaxMutationLen =
689 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
690 assert(CurrentMaxMutationLen > 0);
691
692 for (int i = 0; i < Options.MutateDepth; i++) {
693 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
694 break;
695 if (MaybeExitGracefully()) return true;
696 size_t NewSize = 0;
697 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
698 Size <= CurrentMaxMutationLen)
699 NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
700 II.DataFlowTraceForFocusFunction);
701
702 // If MutateWithMask either failed or wasn't called, call default Mutate.
703 if (!NewSize)
704 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
705
706 if (!NewSize)
707 continue;
708
709 assert(NewSize > 0 && "Mutator returned empty unit");
710 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
711 Size = NewSize;
712 II.NumExecutedMutations++;
713 Corpus.IncrementNumExecutedMutations();
714
715 bool FoundUniqFeatures = false;
716 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
717 &FoundUniqFeatures);
718 TryDetectingAMemoryLeak(CurrentUnitData, Size,
719 /*DuringInitialCorpusExecution*/ false);
720 if (NewCov) {
721 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
722 break; // We will mutate this input more in the next rounds.
723 }
724 if (Options.ReduceDepth && !FoundUniqFeatures)
725 break;
726 }
727
728 II.NeedsEnergyUpdate = true;
729 return false;
730 }
731
732 void Fuzzer::PurgeAllocator() {
733 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
734 return;
735 if (duration_cast<seconds>(system_clock::now() -
736 LastAllocatorPurgeAttemptTime)
737 .count() < Options.PurgeAllocatorIntervalSec)
738 return;
739
740 if (Options.RssLimitMb <= 0 ||
741 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
742 EF->__sanitizer_purge_allocator();
743
744 LastAllocatorPurgeAttemptTime = system_clock::now();
745 }
746
747 int Fuzzer::ReadAndExecuteSeedCorpora(Vector<SizedFile> &CorporaFiles) {
748 const size_t kMaxSaneLen = 1 << 20;
749 const size_t kMinDefaultLen = 4096;
750 size_t MaxSize = 0;
751 size_t MinSize = -1;
752 size_t TotalSize = 0;
753 for (auto &File : CorporaFiles) {
754 MaxSize = Max(File.Size, MaxSize);
755 MinSize = Min(File.Size, MinSize);
756 TotalSize += File.Size;
757 }
758 if (Options.MaxLen == 0)
759 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
760 assert(MaxInputLen > 0);
761
762 // Test the callback with empty input and never try it again.
763 uint8_t dummy = 0;
764 ExecuteCallback(&dummy, 0);
765
766 if (CorporaFiles.empty()) {
767 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
768 Unit U({'\n'}); // Valid ASCII input.
769 RunOne(U.data(), U.size());
770 } else {
771 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
772 " rss: %zdMb\n",
773 CorporaFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
774 if (Options.ShuffleAtStartUp)
775 std::shuffle(CorporaFiles.begin(), CorporaFiles.end(), MD.GetRand());
776
777 if (Options.PreferSmall) {
778 std::stable_sort(CorporaFiles.begin(), CorporaFiles.end());
779 assert(CorporaFiles.front().Size <= CorporaFiles.back().Size);
780 }
781
782 // Load and execute inputs one by one.
783 for (auto &SF : CorporaFiles) {
784 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
785 assert(U.size() <= MaxInputLen);
786 RunOne(U.data(), U.size());
787 CheckExitOnSrcPosOrItem();
788 TryDetectingAMemoryLeak(U.data(), U.size(),
789 /*DuringInitialCorpusExecution*/ true);
790 }
791 }
792
793 PrintStats("INITED");
794 if (!Options.FocusFunction.empty()) {
795 Printf("INFO: %zd/%zd inputs touch the focus function\n",
796 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
797 if (!Options.DataFlowTrace.empty())
798 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
799 Corpus.NumInputsWithDataFlowTrace(),
800 Corpus.NumInputsThatTouchFocusFunction());
801 }
802
803 if (Corpus.empty() && Options.MaxNumberOfRuns) {
804 Printf("ERROR: no interesting inputs were found. "
805 "Is the code instrumented for coverage? Exiting.\n");
806 return 1;
807 }
808 return 0;
809 }
810
811 int Fuzzer::Loop(Vector<SizedFile> &CorporaFiles) {
812 auto FocusFunctionOrAuto = Options.FocusFunction;
813 int Res = DFT.Init(Options.DataFlowTrace, &FocusFunctionOrAuto, CorporaFiles,
814 MD.GetRand());
815 if (Res != 0)
816 return Res;
817 Res = TPC.SetFocusFunction(FocusFunctionOrAuto);
818 if (Res != 0)
819 return Res;
820 Res = ReadAndExecuteSeedCorpora(CorporaFiles);
821 if (Res != 0)
822 return Res;
823 DFT.Clear(); // No need for DFT any more.
824 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
825 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
826 system_clock::time_point LastCorpusReload = system_clock::now();
827
828 TmpMaxMutationLen =
829 Min(MaxMutationLen, Max(size_t(4), Corpus.MaxInputSize()));
830
831 while (true) {
832 auto Now = system_clock::now();
833 if (!Options.StopFile.empty() &&
834 !FileToVector(Options.StopFile, 1, false).empty())
835 break;
836 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
837 Options.ReloadIntervalSec) {
838 RereadOutputCorpus(MaxInputLen);
839 LastCorpusReload = system_clock::now();
840 }
841 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
842 break;
843 if (TimedOut())
844 break;
845
846 // Update TmpMaxMutationLen
847 if (Options.LenControl) {
848 if (TmpMaxMutationLen < MaxMutationLen &&
849 TotalNumberOfRuns - LastCorpusUpdateRun >
850 Options.LenControl * Log(TmpMaxMutationLen)) {
851 TmpMaxMutationLen =
852 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
853 LastCorpusUpdateRun = TotalNumberOfRuns;
854 }
855 } else {
856 TmpMaxMutationLen = MaxMutationLen;
857 }
858
859 // Perform several mutations and runs.
860 if (MutateAndTestOne())
861 return 0;
862
863 PurgeAllocator();
864 }
865
866 PrintStats("DONE ", "\n");
867 MD.PrintRecommendedDictionary();
868 return 0;
869 }
870
871 void Fuzzer::MinimizeCrashLoop(const Unit &U) {
872 if (U.size() <= 1)
873 return;
874 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
875 MD.StartMutationSequence();
876 memcpy(CurrentUnitData, U.data(), U.size());
877 for (int i = 0; i < Options.MutateDepth; i++) {
878 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
879 assert(NewSize <= MaxMutationLen);
880 if (!NewSize)
881 continue;
882 ExecuteCallback(CurrentUnitData, NewSize);
883 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
884 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
885 /*DuringInitialCorpusExecution*/ false);
886 }
887 }
888 }
889
890 } // namespace fuzzer
891
892 extern "C" {
893
894 ATTRIBUTE_INTERFACE size_t
895 LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
896 assert(fuzzer::F);
897 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
898 }
899
900 } // extern "C"