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
38namespace fuzzer {
39static const size_t kMaxUnitSizeToPrint = 256;
40
41thread_local bool Fuzzer::IsMyThread;
42
43bool RunningUserCallback = false;
44
45// Only one Fuzzer per process.
46static 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.
50struct MallocFreeTracer {
51 void Start(int TraceLevel) {
52 this->TraceLevel = TraceLevel;
53 if (TraceLevel)
54 Printf(Fmt: "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(Fmt: "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
77static MallocFreeTracer AllocTracer;
78
79// Locks printing and avoids nested hooks triggered from mallocs/frees in
80// sanitizer.
81class TraceLock {
82public:
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
93private:
94 std::lock_guard<std::recursive_mutex> Lock;
95};
96
97ATTRIBUTE_NO_SANITIZE_MEMORY
98void MallocHook(const volatile void *ptr, size_t size) {
99 size_t N = AllocTracer.Mallocs++;
100 F->HandleMalloc(Size: size);
101 if (int TraceLevel = AllocTracer.TraceLevel) {
102 TraceLock Lock;
103 if (Lock.IsDisabled())
104 return;
105 Printf(Fmt: "MALLOC[%zd] %p %zd\n", N, ptr, size);
106 if (TraceLevel >= 2 && EF)
107 PrintStackTrace();
108 }
109}
110
111ATTRIBUTE_NO_SANITIZE_MEMORY
112void 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(Fmt: "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.
125void Fuzzer::HandleMalloc(size_t Size) {
126 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
127 return;
128 Printf(Fmt: "==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n",
129 (int)GetPid(), Size);
130 Printf(Fmt: " To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
131 PrintStackTrace();
132 DumpCurrentUnit(Prefix: "oom-");
133 Printf(Fmt: "SUMMARY: libFuzzer: out-of-memory\n");
134 PrintFinalStats();
135 _Exit(status: Options.OOMExitCode); // Stop right now.
136}
137
138Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
139 const 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(Path: 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(s: BaseSha1, c: 0, n: sizeof(BaseSha1));
161}
162
163void Fuzzer::AllocateCurrentUnitData() {
164 if (CurrentUnitData || MaxInputLen == 0)
165 return;
166 CurrentUnitData = new uint8_t[MaxInputLen];
167}
168
169void Fuzzer::StaticDeathCallback() {
170 assert(F);
171 F->DeathCallback();
172}
173
174void Fuzzer::DumpCurrentUnit(const char *Prefix) {
175 if (!CurrentUnitData)
176 return; // Happens when running individual inputs.
177 ScopedDisableMsanInterceptorChecks S;
178 MD.PrintMutationSequence();
179 Printf(Fmt: "; base unit: %s\n", Sha1ToString(Sha1: BaseSha1).c_str());
180 size_t UnitSize = CurrentUnitSize;
181 if (UnitSize <= kMaxUnitSizeToPrint) {
182 PrintHexArray(Data: CurrentUnitData, Size: UnitSize, PrintAfter: "\n");
183 PrintASCII(Data: CurrentUnitData, Size: UnitSize, PrintAfter: "\n");
184 }
185 WriteUnitToFileWithPrefix(U: {CurrentUnitData, CurrentUnitData + UnitSize},
186 Prefix);
187}
188
189NO_SANITIZE_MEMORY
190void Fuzzer::DeathCallback() {
191 DumpCurrentUnit(Prefix: "crash-");
192 PrintFinalStats();
193}
194
195void Fuzzer::StaticAlarmCallback() {
196 assert(F);
197 F->AlarmCallback();
198}
199
200void Fuzzer::StaticCrashSignalCallback() {
201 assert(F);
202 F->CrashCallback();
203}
204
205void Fuzzer::StaticExitCallback() {
206 assert(F);
207 F->ExitCallback();
208}
209
210void Fuzzer::StaticInterruptCallback() {
211 assert(F);
212 F->InterruptCallback();
213}
214
215void Fuzzer::StaticGracefulExitCallback() {
216 assert(F);
217 F->GracefulExitRequested = true;
218 Printf(Fmt: "INFO: signal received, trying to exit gracefully\n");
219}
220
221void Fuzzer::StaticFileSizeExceedCallback() {
222 Printf(Fmt: "==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
223 exit(status: 1);
224}
225
226void Fuzzer::CrashCallback() {
227 if (EF->__sanitizer_acquire_crash_state &&
228 !EF->__sanitizer_acquire_crash_state())
229 return;
230 Printf(Fmt: "==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
231 PrintStackTrace();
232 Printf(Fmt: "NOTE: libFuzzer has rudimentary signal handlers.\n"
233 " Combine libFuzzer with AddressSanitizer or similar for better "
234 "crash reports.\n");
235 Printf(Fmt: "SUMMARY: libFuzzer: deadly signal\n");
236 DumpCurrentUnit(Prefix: "crash-");
237 PrintFinalStats();
238 _Exit(status: Options.ErrorExitCode); // Stop right now.
239}
240
241void Fuzzer::ExitCallback() {
242 if (!RunningUserCallback)
243 return; // This exit did not come from the user callback
244 if (EF->__sanitizer_acquire_crash_state &&
245 !EF->__sanitizer_acquire_crash_state())
246 return;
247 Printf(Fmt: "==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
248 PrintStackTrace();
249 Printf(Fmt: "SUMMARY: libFuzzer: fuzz target exited\n");
250 DumpCurrentUnit(Prefix: "crash-");
251 PrintFinalStats();
252 _Exit(status: Options.ErrorExitCode);
253}
254
255void Fuzzer::MaybeExitGracefully() {
256 if (!F->GracefulExitRequested) return;
257 Printf(Fmt: "==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
258 RmDirRecursive(Dir: TempPath(Prefix: "FuzzWithFork", Extension: ".dir"));
259 F->PrintFinalStats();
260 _Exit(status: 0);
261}
262
263int Fuzzer::InterruptExitCode() {
264 assert(F);
265 return F->Options.InterruptExitCode;
266}
267
268void Fuzzer::InterruptCallback() {
269 Printf(Fmt: "==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
270 PrintFinalStats();
271 ScopedDisableMsanInterceptorChecks S; // RmDirRecursive may call opendir().
272 RmDirRecursive(Dir: TempPath(Prefix: "FuzzWithFork", Extension: ".dir"));
273 // Stop right now, don't perform any at-exit actions.
274 _Exit(status: Options.InterruptExitCode);
275}
276
277NO_SANITIZE_MEMORY
278void Fuzzer::AlarmCallback() {
279 assert(Options.UnitTimeoutSec > 0);
280 // In Windows and Fuchsia, Alarm callback is executed by a different thread.
281 // NetBSD's current behavior needs this change too.
282#if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD && !LIBFUZZER_FUCHSIA
283 if (!InFuzzingThread())
284 return;
285#endif
286 if (!RunningUserCallback)
287 return; // We have not started running units yet.
288 size_t Seconds =
289 duration_cast<seconds>(fd: system_clock::now() - UnitStartTime).count();
290 if (Seconds == 0)
291 return;
292 if (Options.Verbosity >= 2)
293 Printf(Fmt: "AlarmCallback %zd\n", Seconds);
294 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
295 if (EF->__sanitizer_acquire_crash_state &&
296 !EF->__sanitizer_acquire_crash_state())
297 return;
298 Printf(Fmt: "ALARM: working on the last Unit for %zd seconds\n", Seconds);
299 Printf(Fmt: " and the timeout value is %d (use -timeout=N to change)\n",
300 Options.UnitTimeoutSec);
301 DumpCurrentUnit(Prefix: "timeout-");
302 Printf(Fmt: "==%lu== ERROR: libFuzzer: timeout after %zu seconds\n", GetPid(),
303 Seconds);
304 PrintStackTrace();
305 Printf(Fmt: "SUMMARY: libFuzzer: timeout\n");
306 PrintFinalStats();
307 _Exit(status: Options.TimeoutExitCode); // Stop right now.
308 }
309}
310
311void Fuzzer::RssLimitCallback() {
312 if (EF->__sanitizer_acquire_crash_state &&
313 !EF->__sanitizer_acquire_crash_state())
314 return;
315 Printf(Fmt: "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMB; limit: %dMB)\n",
316 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
317 Printf(Fmt: " To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
318 PrintMemoryProfile();
319 DumpCurrentUnit(Prefix: "oom-");
320 Printf(Fmt: "SUMMARY: libFuzzer: out-of-memory\n");
321 PrintFinalStats();
322 _Exit(status: Options.OOMExitCode); // Stop right now.
323}
324
325void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units,
326 size_t Features) {
327 size_t ExecPerSec = execPerSec();
328 if (!Options.Verbosity)
329 return;
330 Printf(Fmt: "#%zd\t%s", TotalNumberOfRuns, Where);
331 if (size_t N = TPC.GetTotalPCCoverage())
332 Printf(Fmt: " cov: %zd", N);
333 if (size_t N = Features ? Features : Corpus.NumFeatures())
334 Printf(Fmt: " ft: %zd", N);
335 if (!Corpus.empty()) {
336 Printf(Fmt: " corp: %zd", Corpus.NumActiveUnits());
337 if (size_t N = Corpus.SizeInBytes()) {
338 if (N < (1 << 14))
339 Printf(Fmt: "/%zdB", N);
340 else if (N < (1 << 24))
341 Printf(Fmt: "/%zdKB", N >> 10);
342 else
343 Printf(Fmt: "/%zdMB", N >> 20);
344 }
345 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
346 Printf(Fmt: " focus: %zd", FF);
347 }
348 if (TmpMaxMutationLen)
349 Printf(Fmt: " lim: %zd", TmpMaxMutationLen);
350 if (Units)
351 Printf(Fmt: " units: %zd", Units);
352
353 Printf(Fmt: " exec/s: %zd", ExecPerSec);
354 Printf(Fmt: " rss: %zdMB", GetPeakRSSMb());
355 if (Options.StaleCorpusTimeoutSec > 0)
356 Printf(Fmt: " stale: %zd", secondsSinceLastNewCorpus());
357 Printf(Fmt: "%s", End);
358}
359
360void Fuzzer::PrintFinalStats() {
361 if (Options.PrintFullCoverage)
362 TPC.PrintCoverage(/*PrintAllCounters=*/true);
363 if (Options.PrintCoverage)
364 TPC.PrintCoverage(/*PrintAllCounters=*/false);
365 if (Options.PrintCorpusStats)
366 Corpus.PrintStats();
367 if (!Options.PrintFinalStats)
368 return;
369 size_t ExecPerSec = execPerSec();
370 Printf(Fmt: "stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
371 Printf(Fmt: "stat::average_exec_per_sec: %zd\n", ExecPerSec);
372 Printf(Fmt: "stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
373 Printf(Fmt: "stat::slowest_unit_time_sec: %ld\n", TimeOfLongestUnitInSeconds);
374 Printf(Fmt: "stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
375}
376
377void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
378 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
379 assert(MaxInputLen);
380 this->MaxInputLen = MaxInputLen;
381 this->MaxMutationLen = MaxInputLen;
382 AllocateCurrentUnitData();
383 Printf(Fmt: "INFO: -max_len is not provided; "
384 "libFuzzer will not generate inputs larger than %zd bytes\n",
385 MaxInputLen);
386}
387
388void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
389 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
390 this->MaxMutationLen = MaxMutationLen;
391}
392
393void Fuzzer::CheckExitOnSrcPosOrItem() {
394 if (!Options.ExitOnSrcPos.empty()) {
395 static auto *PCsSet = new std::set<uintptr_t>;
396 auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
397 if (!PCsSet->insert(v: TE->PC).second)
398 return;
399 std::string Descr = DescribePC(SymbolizedFMT: "%F %L", PC: TE->PC + 1);
400 if (Descr.find(str: Options.ExitOnSrcPos) != std::string::npos) {
401 Printf(Fmt: "INFO: found line matching '%s', exiting.\n",
402 Options.ExitOnSrcPos.c_str());
403 _Exit(status: 0);
404 }
405 };
406 TPC.ForEachObservedPC(CB: HandlePC);
407 }
408 if (!Options.ExitOnItem.empty()) {
409 if (Corpus.HasUnit(H: Options.ExitOnItem)) {
410 Printf(Fmt: "INFO: found item with checksum '%s', exiting.\n",
411 Options.ExitOnItem.c_str());
412 _Exit(status: 0);
413 }
414 }
415}
416
417void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
418 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
419 return;
420 std::vector<Unit> AdditionalCorpus;
421 std::vector<std::string> AdditionalCorpusPaths;
422 ReadDirToVectorOfUnits(
423 Path: Options.OutputCorpus.c_str(), V: &AdditionalCorpus,
424 Epoch: &EpochOfLastReadOfOutputCorpus, MaxSize,
425 /*ExitOnError*/ false,
426 VPaths: (Options.Verbosity >= 2 ? &AdditionalCorpusPaths : nullptr));
427 if (Options.Verbosity >= 2)
428 Printf(Fmt: "Reload: read %zd new units.\n", AdditionalCorpus.size());
429 bool Reloaded = false;
430 for (size_t i = 0; i != AdditionalCorpus.size(); ++i) {
431 auto &U = AdditionalCorpus[i];
432 if (U.size() > MaxSize)
433 U.resize(new_size: MaxSize);
434 if (!Corpus.HasUnit(U)) {
435 if (RunOne(Data: U.data(), Size: U.size())) {
436 CheckExitOnSrcPosOrItem();
437 Reloaded = true;
438 if (Options.Verbosity >= 2)
439 Printf(Fmt: "Reloaded %s\n", AdditionalCorpusPaths[i].c_str());
440 }
441 }
442 }
443 if (Reloaded)
444 PrintStats(Where: "RELOAD");
445}
446
447void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
448 auto TimeOfUnit =
449 duration_cast<seconds>(fd: UnitStopTime - UnitStartTime).count();
450 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
451 secondsSinceProcessStartUp() >= 2)
452 PrintStats(Where: "pulse ");
453 auto Threshold =
454 static_cast<long>(static_cast<double>(TimeOfLongestUnitInSeconds) * 1.1);
455 if (TimeOfUnit > Threshold && TimeOfUnit >= Options.ReportSlowUnits) {
456 TimeOfLongestUnitInSeconds = TimeOfUnit;
457 Printf(Fmt: "Slowest unit: %ld s:\n", TimeOfLongestUnitInSeconds);
458 WriteUnitToFileWithPrefix(U: {Data, Data + Size}, Prefix: "slow-unit-");
459 }
460}
461
462static void WriteFeatureSetToFile(const std::string &FeaturesDir,
463 const std::string &FileName,
464 const std::vector<uint32_t> &FeatureSet) {
465 if (FeaturesDir.empty() || FeatureSet.empty()) return;
466 WriteToFile(Data: reinterpret_cast<const uint8_t *>(FeatureSet.data()),
467 Size: FeatureSet.size() * sizeof(FeatureSet[0]),
468 Path: DirPlusFile(DirPath: FeaturesDir, FileName));
469}
470
471static void RenameFeatureSetFile(const std::string &FeaturesDir,
472 const std::string &OldFile,
473 const std::string &NewFile) {
474 if (FeaturesDir.empty()) return;
475 RenameFile(OldPath: DirPlusFile(DirPath: FeaturesDir, FileName: OldFile),
476 NewPath: DirPlusFile(DirPath: FeaturesDir, FileName: NewFile));
477}
478
479static void WriteEdgeToMutationGraphFile(const std::string &MutationGraphFile,
480 const InputInfo *II,
481 const InputInfo *BaseII,
482 const std::string &MS) {
483 if (MutationGraphFile.empty())
484 return;
485
486 std::string Sha1 = Sha1ToString(Sha1: II->Sha1);
487
488 std::string OutputString;
489
490 // Add a new vertex.
491 OutputString.append(s: "\"");
492 OutputString.append(str: Sha1);
493 OutputString.append(s: "\"\n");
494
495 // Add a new edge if there is base input.
496 if (BaseII) {
497 std::string BaseSha1 = Sha1ToString(Sha1: BaseII->Sha1);
498 OutputString.append(s: "\"");
499 OutputString.append(str: BaseSha1);
500 OutputString.append(s: "\" -> \"");
501 OutputString.append(str: Sha1);
502 OutputString.append(s: "\" [label=\"");
503 OutputString.append(str: MS);
504 OutputString.append(s: "\"];\n");
505 }
506
507 AppendToFile(Data: OutputString, Path: MutationGraphFile);
508}
509
510bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
511 InputInfo *II, bool ForceAddToCorpus,
512 bool *FoundUniqFeatures) {
513 if (!Size)
514 return false;
515 // Largest input length should be INT_MAX.
516 assert(Size < std::numeric_limits<uint32_t>::max());
517
518 if(!ExecuteCallback(Data, Size)) return false;
519 auto TimeOfUnit = duration_cast<microseconds>(fd: UnitStopTime - UnitStartTime);
520
521 UniqFeatureSetTmp.clear();
522 size_t FoundUniqFeaturesOfII = 0;
523 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
524 TPC.CollectFeatures(HandleFeature: [&](uint32_t Feature) {
525 if (Corpus.AddFeature(Idx: Feature, NewSize: static_cast<uint32_t>(Size), Shrink: Options.Shrink))
526 UniqFeatureSetTmp.push_back(x: Feature);
527 if (Options.Entropic)
528 Corpus.UpdateFeatureFrequency(II, Idx: Feature);
529 if (Options.ReduceInputs && II && !II->NeverReduce)
530 if (std::binary_search(first: II->UniqFeatureSet.begin(),
531 last: II->UniqFeatureSet.end(), value: Feature))
532 FoundUniqFeaturesOfII++;
533 });
534 if (FoundUniqFeatures)
535 *FoundUniqFeatures = FoundUniqFeaturesOfII;
536 PrintPulseAndReportSlowInput(Data, Size);
537 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
538 if (NumNewFeatures || ForceAddToCorpus) {
539 TPC.UpdateObservedPCs();
540 LastNewCorpusTime = UnitStopTime;
541 auto NewII =
542 Corpus.AddToCorpus(U: {Data, Data + Size}, NumFeatures: NumNewFeatures, MayDeleteFile,
543 HasFocusFunction: TPC.ObservedFocusFunction(), NeverReduce: ForceAddToCorpus,
544 TimeOfUnit, FeatureSet: UniqFeatureSetTmp, DFT, BaseII: II);
545 WriteFeatureSetToFile(FeaturesDir: Options.FeaturesDir, FileName: Sha1ToString(Sha1: NewII->Sha1),
546 FeatureSet: NewII->UniqFeatureSet);
547 WriteEdgeToMutationGraphFile(MutationGraphFile: Options.MutationGraphFile, II: NewII, BaseII: II,
548 MS: MD.MutationSequence());
549 return true;
550 }
551 if (II && FoundUniqFeaturesOfII &&
552 II->DataFlowTraceForFocusFunction.empty() &&
553 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
554 II->U.size() > Size) {
555 auto OldFeaturesFile = Sha1ToString(Sha1: II->Sha1);
556 Corpus.Replace(II, U: {Data, Data + Size}, TimeOfUnit);
557 RenameFeatureSetFile(FeaturesDir: Options.FeaturesDir, OldFile: OldFeaturesFile,
558 NewFile: Sha1ToString(Sha1: II->Sha1));
559 return true;
560 }
561 return false;
562}
563
564void Fuzzer::TPCUpdateObservedPCs() { TPC.UpdateObservedPCs(); }
565
566size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
567 assert(InFuzzingThread());
568 *Data = CurrentUnitData;
569 return CurrentUnitSize;
570}
571
572void Fuzzer::CrashOnOverwrittenData() {
573 Printf(Fmt: "==%d== ERROR: libFuzzer: fuzz target overwrites its const input\n",
574 (int)GetPid());
575 PrintStackTrace();
576 Printf(Fmt: "SUMMARY: libFuzzer: overwrites-const-input\n");
577 DumpCurrentUnit(Prefix: "crash-");
578 PrintFinalStats();
579 _Exit(status: Options.ErrorExitCode); // Stop right now.
580}
581
582// Compare two arrays, but not all bytes if the arrays are large.
583static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
584 const size_t Limit = 64;
585 // memcmp cannot take null pointer arguments even if Size is 0.
586 if (!Size)
587 return true;
588 if (Size <= 64)
589 return !memcmp(s1: A, s2: B, n: Size);
590 // Compare first and last Limit/2 bytes.
591 return !memcmp(s1: A, s2: B, n: Limit / 2) &&
592 !memcmp(s1: A + Size - Limit / 2, s2: B + Size - Limit / 2, n: Limit / 2);
593}
594
595// This method is not inlined because it would cause a test to fail where it
596// is part of the stack unwinding. See D97975 for details.
597ATTRIBUTE_NOINLINE bool Fuzzer::ExecuteCallback(const uint8_t *Data,
598 size_t Size) {
599 TPC.RecordInitialStack();
600 TotalNumberOfRuns++;
601 assert(InFuzzingThread());
602 // We copy the contents of Unit into a separate heap buffer
603 // so that we reliably find buffer overflows in it.
604 uint8_t *DataCopy = new uint8_t[Size];
605 // memcpy cannot take null pointer arguments even if Size is 0.
606 if (Size)
607 memcpy(dest: DataCopy, src: Data, n: Size);
608 if (EF->__msan_unpoison)
609 EF->__msan_unpoison(DataCopy, Size);
610 if (EF->__msan_unpoison_param)
611 EF->__msan_unpoison_param(2);
612 if (CurrentUnitData && CurrentUnitData != Data)
613 memcpy(dest: CurrentUnitData, src: Data, n: Size);
614 CurrentUnitSize = Size;
615 int CBRes = 0;
616 {
617 ScopedEnableMsanInterceptorChecks S;
618 AllocTracer.Start(TraceLevel: Options.TraceMalloc);
619 UnitStartTime = system_clock::now();
620 TPC.ResetMaps();
621 RunningUserCallback = true;
622 CBRes = CB(DataCopy, Size);
623 RunningUserCallback = false;
624 UnitStopTime = system_clock::now();
625 assert(CBRes == 0 || CBRes == -1);
626 HasMoreMallocsThanFrees = AllocTracer.Stop();
627 }
628 if (!LooseMemeq(A: DataCopy, B: Data, Size))
629 CrashOnOverwrittenData();
630 CurrentUnitSize = 0;
631 delete[] DataCopy;
632 return CBRes == 0;
633}
634
635std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
636 if (Options.OnlyASCII)
637 assert(IsASCII(U));
638 if (Options.OutputCorpus.empty())
639 return "";
640 std::string Path = DirPlusFile(DirPath: Options.OutputCorpus, FileName: Hash(U));
641 WriteToFile(U, Path);
642 if (Options.Verbosity >= 2)
643 Printf(Fmt: "Written %zd bytes to %s\n", U.size(), Path.c_str());
644 return Path;
645}
646
647void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
648 if (!Options.SaveArtifacts)
649 return;
650 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
651 if (!Options.ExactArtifactPath.empty())
652 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
653 WriteToFile(U, Path);
654 Printf(Fmt: "artifact_prefix='%s'; Test unit written to %s\n",
655 Options.ArtifactPrefix.c_str(), Path.c_str());
656 if (U.size() <= kMaxUnitSizeToPrint)
657 Printf(Fmt: "Base64: %s\n", Base64(U).c_str());
658}
659
660void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
661 if (!Options.PrintNEW)
662 return;
663 PrintStats(Where: Text, End: "");
664 if (Options.Verbosity) {
665 Printf(Fmt: " L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
666 MD.PrintMutationSequence(Verbose: Options.Verbosity >= 2);
667 Printf(Fmt: "\n");
668 }
669}
670
671void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
672 II->NumSuccessfulMutations++;
673 MD.RecordSuccessfulMutationSequence();
674 PrintStatusForNewUnit(U, Text: II->Reduced ? "REDUCE" : "NEW ");
675 WriteToOutputCorpus(U);
676 NumberOfNewUnitsAdded++;
677 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
678 LastCorpusUpdateRun = TotalNumberOfRuns;
679}
680
681// Tries detecting a memory leak on the particular input that we have just
682// executed before calling this function.
683void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
684 bool DuringInitialCorpusExecution) {
685 if (!HasMoreMallocsThanFrees)
686 return; // mallocs==frees, a leak is unlikely.
687 if (!Options.DetectLeaks)
688 return;
689 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
690 !(EF->__lsan_do_recoverable_leak_check))
691 return; // No lsan.
692 // Run the target once again, but with lsan disabled so that if there is
693 // a real leak we do not report it twice.
694 EF->__lsan_disable();
695 ExecuteCallback(Data, Size);
696 EF->__lsan_enable();
697 // The above is a verification run, and not a fuzzing run, without the
698 // correction the number of runs would exceed -runs.
699 // See https://github.com/llvm/llvm-project/issues/66331
700 TotalNumberOfRuns--;
701 if (!HasMoreMallocsThanFrees)
702 return; // a leak is unlikely.
703 if (NumberOfLeakDetectionAttempts++ > 1000) {
704 Options.DetectLeaks = false;
705 Printf(Fmt: "INFO: libFuzzer disabled leak detection after every mutation.\n"
706 " Most likely the target function accumulates allocated\n"
707 " memory in a global state w/o actually leaking it.\n"
708 " You may try running this binary with -trace_malloc=[12]"
709 " to get a trace of mallocs and frees.\n"
710 " If LeakSanitizer is enabled in this process it will still\n"
711 " run on the process shutdown.\n");
712 return;
713 }
714 // Now perform the actual lsan pass. This is expensive and we must ensure
715 // we don't call it too often.
716 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
717 if (DuringInitialCorpusExecution)
718 Printf(Fmt: "\nINFO: a leak has been found in the initial corpus.\n\n");
719 Printf(Fmt: "INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
720 CurrentUnitSize = Size;
721 DumpCurrentUnit(Prefix: "leak-");
722 PrintFinalStats();
723 _Exit(status: Options.ErrorExitCode); // not exit() to disable lsan further on.
724 }
725}
726
727void Fuzzer::MutateAndTestOne() {
728 MD.StartMutationSequence();
729
730 auto &II = Corpus.ChooseUnitToMutate(Rand&: MD.GetRand());
731 if (Options.DoCrossOver) {
732 auto &CrossOverII = Corpus.ChooseUnitToCrossOverWith(
733 Rand&: MD.GetRand(), UniformDist: Options.CrossOverUniformDist);
734 MD.SetCrossOverWith(&CrossOverII.U);
735 }
736 const auto &U = II.U;
737 memcpy(dest: BaseSha1, src: II.Sha1, n: sizeof(BaseSha1));
738 assert(CurrentUnitData);
739 size_t Size = U.size();
740 assert(Size <= MaxInputLen && "Oversized Unit");
741 memcpy(dest: CurrentUnitData, src: U.data(), n: Size);
742
743 assert(MaxMutationLen > 0);
744
745 size_t CurrentMaxMutationLen =
746 Min(a: MaxMutationLen, b: Max(a: U.size(), b: TmpMaxMutationLen));
747 assert(CurrentMaxMutationLen > 0);
748
749 for (int i = 0; i < Options.MutateDepth; i++) {
750 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
751 break;
752 MaybeExitGracefully();
753 size_t NewSize = 0;
754 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
755 Size <= CurrentMaxMutationLen)
756 NewSize = MD.MutateWithMask(Data: CurrentUnitData, Size, MaxSize: Size,
757 Mask: II.DataFlowTraceForFocusFunction);
758
759 // If MutateWithMask either failed or wasn't called, call default Mutate.
760 if (!NewSize)
761 NewSize = MD.Mutate(Data: CurrentUnitData, Size, MaxSize: CurrentMaxMutationLen);
762 assert(NewSize > 0 && "Mutator returned empty unit");
763 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
764 Size = NewSize;
765 II.NumExecutedMutations++;
766 Corpus.IncrementNumExecutedMutations();
767
768 bool FoundUniqFeatures = false;
769 bool NewCov = RunOne(Data: CurrentUnitData, Size, /*MayDeleteFile=*/true, II: &II,
770 /*ForceAddToCorpus*/ false, FoundUniqFeatures: &FoundUniqFeatures);
771 TryDetectingAMemoryLeak(Data: CurrentUnitData, Size,
772 /*DuringInitialCorpusExecution*/ false);
773 if (NewCov) {
774 ReportNewCoverage(II: &II, U: {CurrentUnitData, CurrentUnitData + Size});
775 break; // We will mutate this input more in the next rounds.
776 }
777 if (Options.ReduceDepth && !FoundUniqFeatures)
778 break;
779 }
780
781 II.NeedsEnergyUpdate = true;
782}
783
784void Fuzzer::PurgeAllocator() {
785 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
786 return;
787 if (duration_cast<seconds>(fd: system_clock::now() -
788 LastAllocatorPurgeAttemptTime)
789 .count() < Options.PurgeAllocatorIntervalSec)
790 return;
791
792 if (Options.RssLimitMb <= 0 ||
793 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
794 EF->__sanitizer_purge_allocator();
795
796 LastAllocatorPurgeAttemptTime = system_clock::now();
797}
798
799void Fuzzer::ReadAndExecuteSeedCorpora(std::vector<SizedFile> &CorporaFiles) {
800 const size_t kMaxSaneLen = 1 << 20;
801 const size_t kMinDefaultLen = 4096;
802 size_t MaxSize = 0;
803 size_t MinSize = -1;
804 size_t TotalSize = 0;
805 for (auto &File : CorporaFiles) {
806 MaxSize = Max(a: File.Size, b: MaxSize);
807 MinSize = Min(a: File.Size, b: MinSize);
808 TotalSize += File.Size;
809 }
810 if (Options.MaxLen == 0)
811 SetMaxInputLen(std::clamp(v: MaxSize, lo: kMinDefaultLen, hi: kMaxSaneLen));
812 assert(MaxInputLen > 0);
813
814 // Test the callback with empty input and never try it again.
815 uint8_t dummy = 0;
816 ExecuteCallback(Data: &dummy, Size: 0);
817
818 if (CorporaFiles.empty()) {
819 Printf(Fmt: "INFO: A corpus is not provided, starting from an empty corpus\n");
820 Unit U({'\n'}); // Valid ASCII input.
821 RunOne(Data: U.data(), Size: U.size());
822 } else {
823 Printf(Fmt: "INFO: seed corpus: files: %zd min: %zdB max: %zdB total: %zdB"
824 " rss: %zdMB\n",
825 CorporaFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
826 if (Options.ShuffleAtStartUp)
827 std::shuffle(first: CorporaFiles.begin(), last: CorporaFiles.end(), g&: MD.GetRand());
828
829 if (Options.PreferSmall) {
830 std::stable_sort(first: CorporaFiles.begin(), last: CorporaFiles.end());
831 assert(CorporaFiles.front().Size <= CorporaFiles.back().Size);
832 }
833
834 // Load and execute inputs one by one.
835 for (auto &SF : CorporaFiles) {
836 auto U = FileToVector(Path: SF.File, MaxSize: MaxInputLen, /*ExitOnError=*/false);
837 assert(U.size() <= MaxInputLen);
838 RunOne(Data: U.data(), Size: U.size(), /*MayDeleteFile*/ false, /*II*/ nullptr,
839 /*ForceAddToCorpus*/ Options.KeepSeed,
840 /*FoundUniqFeatures*/ nullptr);
841 CheckExitOnSrcPosOrItem();
842 TryDetectingAMemoryLeak(Data: U.data(), Size: U.size(),
843 /*DuringInitialCorpusExecution*/ true);
844 }
845 }
846
847 PrintStats(Where: "INITED");
848 if (!Options.FocusFunction.empty()) {
849 Printf(Fmt: "INFO: %zd/%zd inputs touch the focus function\n",
850 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
851 if (!Options.DataFlowTrace.empty())
852 Printf(Fmt: "INFO: %zd/%zd inputs have the Data Flow Trace\n",
853 Corpus.NumInputsWithDataFlowTrace(),
854 Corpus.NumInputsThatTouchFocusFunction());
855 }
856
857 if (Corpus.empty() && Options.MaxNumberOfRuns) {
858 Printf(Fmt: "WARNING: no interesting inputs were found so far. "
859 "Is the code instrumented for coverage?\n"
860 "This may also happen if the target rejected all inputs we tried so "
861 "far\n");
862 // The remaining logic requires that the corpus is not empty,
863 // so we add one fake input to the in-memory corpus.
864 Corpus.AddToCorpus(U: {'\n'}, /*NumFeatures=*/1, /*MayDeleteFile=*/true,
865 /*HasFocusFunction=*/false, /*NeverReduce=*/false,
866 /*TimeOfUnit=*/duration_cast<microseconds>(fd: 0s), FeatureSet: {0}, DFT,
867 /*BaseII*/ nullptr);
868 }
869}
870
871void Fuzzer::Loop(std::vector<SizedFile> &CorporaFiles) {
872 auto FocusFunctionOrAuto = Options.FocusFunction;
873 DFT.Init(DirPath: Options.DataFlowTrace, FocusFunction: &FocusFunctionOrAuto, CorporaFiles,
874 Rand&: MD.GetRand());
875 TPC.SetFocusFunction(FocusFunctionOrAuto);
876 ReadAndExecuteSeedCorpora(CorporaFiles);
877 DFT.Clear(); // No need for DFT any more.
878 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
879 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
880 system_clock::time_point LastCorpusReload = LastNewCorpusTime =
881 system_clock::now();
882
883 TmpMaxMutationLen =
884 Min(a: MaxMutationLen, b: Max(a: size_t(4), b: Corpus.MaxInputSize()));
885
886 while (true) {
887 auto Now = system_clock::now();
888 if (!Options.StopFile.empty() && IsFile(Path: Options.StopFile))
889 break;
890 if (duration_cast<seconds>(fd: Now - LastCorpusReload).count() >=
891 Options.ReloadIntervalSec) {
892 RereadOutputCorpus(MaxSize: MaxInputLen);
893 LastCorpusReload = system_clock::now();
894 }
895 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
896 break;
897 if (TimedOut())
898 break;
899
900 // Update TmpMaxMutationLen
901 if (Options.LenControl) {
902 if (TmpMaxMutationLen < MaxMutationLen &&
903 TotalNumberOfRuns - LastCorpusUpdateRun >
904 Options.LenControl * Log(X: TmpMaxMutationLen)) {
905 TmpMaxMutationLen =
906 Min(a: MaxMutationLen, b: TmpMaxMutationLen + Log(X: TmpMaxMutationLen));
907 LastCorpusUpdateRun = TotalNumberOfRuns;
908 }
909 } else {
910 TmpMaxMutationLen = MaxMutationLen;
911 }
912
913 // Perform several mutations and runs.
914 MutateAndTestOne();
915
916 PurgeAllocator();
917 }
918
919 PrintStats(Where: "DONE ", End: "\n");
920 MD.PrintRecommendedDictionary();
921}
922
923void Fuzzer::MinimizeCrashLoop(const Unit &U) {
924 if (U.size() <= 1)
925 return;
926 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
927 MD.StartMutationSequence();
928 size_t Size = U.size();
929 memcpy(dest: CurrentUnitData, src: U.data(), n: Size);
930 for (int i = 0; i < Options.MutateDepth; i++) {
931 size_t NewSize = MD.Mutate(Data: CurrentUnitData, Size, MaxSize: MaxMutationLen);
932 assert(NewSize > 0 && NewSize <= MaxMutationLen);
933 ExecuteCallback(Data: CurrentUnitData, Size: NewSize);
934 PrintPulseAndReportSlowInput(Data: CurrentUnitData, Size: NewSize);
935 TryDetectingAMemoryLeak(Data: CurrentUnitData, Size: NewSize,
936 /*DuringInitialCorpusExecution*/ false);
937 Size = NewSize;
938 }
939 }
940}
941
942} // namespace fuzzer
943
944extern "C" {
945
946ATTRIBUTE_INTERFACE size_t
947LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
948 assert(fuzzer::F);
949 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
950}
951
952} // extern "C"
953