blob: f095757229e9ec6aee1c833cb77cbacf884c95e0 [file] [log] [blame]
George Karpenkov10ab2ac2017-08-21 23:25:501//===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:563// 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
George Karpenkov10ab2ac2017-08-21 23:25:506//
7//===----------------------------------------------------------------------===//
8// Fuzzer's main loop.
9//===----------------------------------------------------------------------===//
10
11#include "FuzzerCorpus.h"
12#include "FuzzerIO.h"
13#include "FuzzerInternal.h"
14#include "FuzzerMutate.h"
Dokyung Song750369e2020-07-14 22:25:5115#include "FuzzerPlatform.h"
George Karpenkov10ab2ac2017-08-21 23:25:5016#include "FuzzerRandom.h"
George Karpenkov10ab2ac2017-08-21 23:25:5017#include "FuzzerTracePC.h"
18#include <algorithm>
19#include <cstring>
20#include <memory>
Vitaly Buka7dbc1d82017-11-01 03:02:5921#include <mutex>
George Karpenkov10ab2ac2017-08-21 23:25:5022#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
Matt Morehouse43a22962018-07-17 16:12:0043bool RunningUserCallback = false;
44
George Karpenkov10ab2ac2017-08-21 23:25:5045// 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("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;
Vitaly Buka7d223242017-11-02 04:12:1072
73 std::recursive_mutex TraceMutex;
74 bool TraceDisabled = false;
George Karpenkov10ab2ac2017-08-21 23:25:5075};
76
77static MallocFreeTracer AllocTracer;
78
Vitaly Buka7d223242017-11-02 04:12:1079// 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};
Vitaly Buka7dbc1d82017-11-01 03:02:5996
George Karpenkov10ab2ac2017-08-21 23:25:5097ATTRIBUTE_NO_SANITIZE_MEMORY
98void MallocHook(const volatile void *ptr, size_t size) {
99 size_t N = AllocTracer.Mallocs++;
100 F->HandleMalloc(size);
101 if (int TraceLevel = AllocTracer.TraceLevel) {
Vitaly Buka7d223242017-11-02 04:12:10102 TraceLock Lock;
103 if (Lock.IsDisabled())
104 return;
George Karpenkov10ab2ac2017-08-21 23:25:50105 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
106 if (TraceLevel >= 2 && EF)
Matt Morehouse14cf71a2018-05-08 23:45:05107 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50108 }
109}
110
111ATTRIBUTE_NO_SANITIZE_MEMORY
112void FreeHook(const volatile void *ptr) {
113 size_t N = AllocTracer.Frees++;
114 if (int TraceLevel = AllocTracer.TraceLevel) {
Vitaly Buka7d223242017-11-02 04:12:10115 TraceLock Lock;
116 if (Lock.IsDisabled())
117 return;
George Karpenkov10ab2ac2017-08-21 23:25:50118 Printf("FREE[%zd] %p\n", N, ptr);
119 if (TraceLevel >= 2 && EF)
Matt Morehouse14cf71a2018-05-08 23:45:05120 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50121 }
122}
123
124// Crash on a single malloc that exceeds the rss limit.
125void Fuzzer::HandleMalloc(size_t Size) {
Kostya Serebryanyde9bafb2017-12-01 22:12:04126 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
George Karpenkov10ab2ac2017-08-21 23:25:50127 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");
Matt Morehouse14cf71a2018-05-08 23:45:05131 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50132 DumpCurrentUnit("oom-");
133 Printf("SUMMARY: libFuzzer: out-of-memory\n");
134 PrintFinalStats();
Kostya Serebryany0fda9dc2019-02-09 00:16:21135 _Exit(Options.OOMExitCode); // Stop right now.
George Karpenkov10ab2ac2017-08-21 23:25:50136}
137
138Fuzzer::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);
Kostya Serebryany51ddb882018-07-03 22:33:09150 TPC.SetUseValueProfileMask(Options.UseValueProfile);
George Karpenkov10ab2ac2017-08-21 23:25:50151
152 if (Options.Verbosity)
153 TPC.PrintModuleInfo();
154 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
155 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
156 MaxInputLen = MaxMutationLen = Options.MaxLen;
Kostya Serebryanyb6ca1e72019-02-16 01:23:41157 TmpMaxMutationLen = 0; // Will be set once we load the corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50158 AllocateCurrentUnitData();
159 CurrentUnitSize = 0;
160 memset(BaseSha1, 0, sizeof(BaseSha1));
161}
162
Alex Shlyapnikov5ded0702017-10-23 23:24:33163Fuzzer::~Fuzzer() {}
George Karpenkov10ab2ac2017-08-21 23:25:50164
165void Fuzzer::AllocateCurrentUnitData() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33166 if (CurrentUnitData || MaxInputLen == 0)
167 return;
George Karpenkov10ab2ac2017-08-21 23:25:50168 CurrentUnitData = new uint8_t[MaxInputLen];
169}
170
171void Fuzzer::StaticDeathCallback() {
172 assert(F);
173 F->DeathCallback();
174}
175
176void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33177 if (!CurrentUnitData)
178 return; // Happens when running individual inputs.
Matt Morehousea34c65e2018-07-09 23:51:08179 ScopedDisableMsanInterceptorChecks S;
Marco Vanottic5d72512021-07-02 16:44:54180 MD.PrintMutationSequence();
George Karpenkov10ab2ac2017-08-21 23:25:50181 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
191NO_SANITIZE_MEMORY
192void Fuzzer::DeathCallback() {
193 DumpCurrentUnit("crash-");
194 PrintFinalStats();
195}
196
197void Fuzzer::StaticAlarmCallback() {
198 assert(F);
199 F->AlarmCallback();
200}
201
202void Fuzzer::StaticCrashSignalCallback() {
203 assert(F);
204 F->CrashCallback();
205}
206
207void Fuzzer::StaticExitCallback() {
208 assert(F);
209 F->ExitCallback();
210}
211
212void Fuzzer::StaticInterruptCallback() {
213 assert(F);
214 F->InterruptCallback();
215}
216
Kostya Serebryanya2ca2dc2017-11-09 20:30:19217void Fuzzer::StaticGracefulExitCallback() {
218 assert(F);
219 F->GracefulExitRequested = true;
220 Printf("INFO: signal received, trying to exit gracefully\n");
221}
222
George Karpenkov10ab2ac2017-08-21 23:25:50223void Fuzzer::StaticFileSizeExceedCallback() {
224 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
225 exit(1);
226}
227
228void Fuzzer::CrashCallback() {
Julian Lettner15df2732019-01-31 01:24:01229 if (EF->__sanitizer_acquire_crash_state &&
230 !EF->__sanitizer_acquire_crash_state())
231 return;
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() {
Matt Morehouse43a22962018-07-17 16:12:00244 if (!RunningUserCallback)
George Karpenkov10ab2ac2017-08-21 23:25:50245 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() {
Kostya Serebryanyf762a112019-02-08 21:27:23258 if (!F->GracefulExitRequested) return;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19259 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
Yuanfang Chen4f3c3bb2020-02-11 02:22:09260 RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
Kostya Serebryanyf762a112019-02-08 21:27:23261 F->PrintFinalStats();
Kostya Serebryanya2ca2dc2017-11-09 20:30:19262 _Exit(0);
263}
264
George Karpenkov10ab2ac2017-08-21 23:25:50265void Fuzzer::InterruptCallback() {
266 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
267 PrintFinalStats();
Matt Morehouse1b760632019-04-26 00:17:41268 ScopedDisableMsanInterceptorChecks S; // RmDirRecursive may call opendir().
Yuanfang Chen4f3c3bb2020-02-11 02:22:09269 RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
Kostya Serebryany0fda9dc2019-02-09 00:16:21270 // Stop right now, don't perform any at-exit actions.
271 _Exit(Options.InterruptExitCode);
George Karpenkov10ab2ac2017-08-21 23:25:50272}
273
274NO_SANITIZE_MEMORY
275void Fuzzer::AlarmCallback() {
276 assert(Options.UnitTimeoutSec > 0);
Jake Ehrliche7bfce72019-10-09 21:01:50277 // In Windows and Fuchsia, Alarm callback is executed by a different thread.
Kamil Rytarowski2e611862018-11-06 01:28:01278 // NetBSD's current behavior needs this change too.
Jake Ehrliche7bfce72019-10-09 21:01:50279#if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD && !LIBFUZZER_FUCHSIA
Alex Shlyapnikov5ded0702017-10-23 23:24:33280 if (!InFuzzingThread())
281 return;
George Karpenkov10ab2ac2017-08-21 23:25:50282#endif
Matt Morehouse43a22962018-07-17 16:12:00283 if (!RunningUserCallback)
George Karpenkov10ab2ac2017-08-21 23:25:50284 return; // We have not started running units yet.
285 size_t Seconds =
286 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
287 if (Seconds == 0)
288 return;
289 if (Options.Verbosity >= 2)
290 Printf("AlarmCallback %zd\n", Seconds);
291 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Matt Morehouse52fd1692018-05-01 21:01:53292 if (EF->__sanitizer_acquire_crash_state &&
293 !EF->__sanitizer_acquire_crash_state())
294 return;
George Karpenkov10ab2ac2017-08-21 23:25:50295 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
296 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
297 Options.UnitTimeoutSec);
298 DumpCurrentUnit("timeout-");
299 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
300 Seconds);
Matt Morehouse14cf71a2018-05-08 23:45:05301 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50302 Printf("SUMMARY: libFuzzer: timeout\n");
303 PrintFinalStats();
304 _Exit(Options.TimeoutExitCode); // Stop right now.
305 }
306}
307
308void Fuzzer::RssLimitCallback() {
Matt Morehouse52fd1692018-05-01 21:01:53309 if (EF->__sanitizer_acquire_crash_state &&
310 !EF->__sanitizer_acquire_crash_state())
311 return;
George Karpenkov10ab2ac2017-08-21 23:25:50312 Printf(
313 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
314 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
315 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Matt Morehouse14cf71a2018-05-08 23:45:05316 PrintMemoryProfile();
George Karpenkov10ab2ac2017-08-21 23:25:50317 DumpCurrentUnit("oom-");
318 Printf("SUMMARY: libFuzzer: out-of-memory\n");
319 PrintFinalStats();
Kostya Serebryany0fda9dc2019-02-09 00:16:21320 _Exit(Options.OOMExitCode); // Stop right now.
George Karpenkov10ab2ac2017-08-21 23:25:50321}
322
Max Moroz74cec612019-08-12 20:21:27323void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units,
324 size_t Features) {
George Karpenkov10ab2ac2017-08-21 23:25:50325 size_t ExecPerSec = execPerSec();
326 if (!Options.Verbosity)
327 return;
328 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
329 if (size_t N = TPC.GetTotalPCCoverage())
330 Printf(" cov: %zd", N);
Max Moroz74cec612019-08-12 20:21:27331 if (size_t N = Features ? Features : Corpus.NumFeatures())
Alex Shlyapnikov5ded0702017-10-23 23:24:33332 Printf(" ft: %zd", N);
George Karpenkov10ab2ac2017-08-21 23:25:50333 if (!Corpus.empty()) {
334 Printf(" corp: %zd", Corpus.NumActiveUnits());
335 if (size_t N = Corpus.SizeInBytes()) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33336 if (N < (1 << 14))
George Karpenkov10ab2ac2017-08-21 23:25:50337 Printf("/%zdb", N);
338 else if (N < (1 << 24))
339 Printf("/%zdKb", N >> 10);
340 else
341 Printf("/%zdMb", N >> 20);
342 }
Kostya Serebryanye9c6f062018-05-16 23:26:37343 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
344 Printf(" focus: %zd", FF);
George Karpenkov10ab2ac2017-08-21 23:25:50345 }
Matt Morehouseddf352b2018-02-22 19:00:17346 if (TmpMaxMutationLen)
347 Printf(" lim: %zd", TmpMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50348 if (Units)
349 Printf(" units: %zd", Units);
350
351 Printf(" exec/s: %zd", ExecPerSec);
352 Printf(" rss: %zdMb", GetPeakRSSMb());
353 Printf("%s", End);
354}
355
356void Fuzzer::PrintFinalStats() {
Max Morozdc62d5e2020-10-23 18:07:30357 if (Options.PrintFullCoverage)
358 TPC.PrintCoverage(/*PrintAllCounters=*/true);
George Karpenkov10ab2ac2017-08-21 23:25:50359 if (Options.PrintCoverage)
Max Morozdc62d5e2020-10-23 18:07:30360 TPC.PrintCoverage(/*PrintAllCounters=*/false);
George Karpenkov10ab2ac2017-08-21 23:25:50361 if (Options.PrintCorpusStats)
362 Corpus.PrintStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33363 if (!Options.PrintFinalStats)
364 return;
George Karpenkov10ab2ac2017-08-21 23:25:50365 size_t ExecPerSec = execPerSec();
366 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
367 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
368 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
369 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
370 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
371}
372
373void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
374 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
375 assert(MaxInputLen);
376 this->MaxInputLen = MaxInputLen;
377 this->MaxMutationLen = MaxInputLen;
378 AllocateCurrentUnitData();
379 Printf("INFO: -max_len is not provided; "
380 "libFuzzer will not generate inputs larger than %zd bytes\n",
381 MaxInputLen);
382}
383
384void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
385 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
386 this->MaxMutationLen = MaxMutationLen;
387}
388
389void Fuzzer::CheckExitOnSrcPosOrItem() {
390 if (!Options.ExitOnSrcPos.empty()) {
Kostya Serebryany7c921752021-08-03 17:04:16391 static auto *PCsSet = new std::set<uintptr_t>;
Kostya Serebryany96f81bc2019-02-14 23:12:33392 auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
393 if (!PCsSet->insert(TE->PC).second)
Alex Shlyapnikov5ded0702017-10-23 23:24:33394 return;
Kostya Serebryany96f81bc2019-02-14 23:12:33395 std::string Descr = DescribePC("%F %L", TE->PC + 1);
George Karpenkov10ab2ac2017-08-21 23:25:50396 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
397 Printf("INFO: found line matching '%s', exiting.\n",
398 Options.ExitOnSrcPos.c_str());
399 _Exit(0);
400 }
401 };
402 TPC.ForEachObservedPC(HandlePC);
403 }
404 if (!Options.ExitOnItem.empty()) {
405 if (Corpus.HasUnit(Options.ExitOnItem)) {
406 Printf("INFO: found item with checksum '%s', exiting.\n",
407 Options.ExitOnItem.c_str());
408 _Exit(0);
409 }
410 }
411}
412
413void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33414 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
415 return;
Kostya Serebryany7c921752021-08-03 17:04:16416 std::vector<Unit> AdditionalCorpus;
417 std::vector<std::string> AdditionalCorpusPaths;
Alexey Vishnyakov827ccc92021-04-16 16:21:49418 ReadDirToVectorOfUnits(
419 Options.OutputCorpus.c_str(), &AdditionalCorpus,
420 &EpochOfLastReadOfOutputCorpus, MaxSize,
421 /*ExitOnError*/ false,
422 (Options.Verbosity >= 2 ? &AdditionalCorpusPaths : nullptr));
George Karpenkov10ab2ac2017-08-21 23:25:50423 if (Options.Verbosity >= 2)
424 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
425 bool Reloaded = false;
Alexey Vishnyakov827ccc92021-04-16 16:21:49426 for (size_t i = 0; i != AdditionalCorpus.size(); ++i) {
427 auto &U = AdditionalCorpus[i];
George Karpenkov10ab2ac2017-08-21 23:25:50428 if (U.size() > MaxSize)
429 U.resize(MaxSize);
430 if (!Corpus.HasUnit(U)) {
431 if (RunOne(U.data(), U.size())) {
432 CheckExitOnSrcPosOrItem();
433 Reloaded = true;
Alexey Vishnyakov827ccc92021-04-16 16:21:49434 if (Options.Verbosity >= 2)
435 Printf("Reloaded %s\n", AdditionalCorpusPaths[i].c_str());
George Karpenkov10ab2ac2017-08-21 23:25:50436 }
437 }
438 }
439 if (Reloaded)
440 PrintStats("RELOAD");
441}
442
George Karpenkov10ab2ac2017-08-21 23:25:50443void 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 ");
Aaron Green67081862021-03-12 00:00:53449 auto Threshhold =
450 static_cast<long>(static_cast<double>(TimeOfLongestUnitInSeconds) * 1.1);
451 if (TimeOfUnit > Threshhold && TimeOfUnit >= Options.ReportSlowUnits) {
George Karpenkov10ab2ac2017-08-21 23:25:50452 TimeOfLongestUnitInSeconds = TimeOfUnit;
453 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
454 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
455 }
456}
457
Kostya Serebryany4614cc32019-04-13 00:20:31458static void WriteFeatureSetToFile(const std::string &FeaturesDir,
Kostya Serebryany5e67abd2019-04-13 01:57:33459 const std::string &FileName,
Kostya Serebryany7c921752021-08-03 17:04:16460 const std::vector<uint32_t> &FeatureSet) {
Kostya Serebryany4614cc32019-04-13 00:20:31461 if (FeaturesDir.empty() || FeatureSet.empty()) return;
462 WriteToFile(reinterpret_cast<const uint8_t *>(FeatureSet.data()),
463 FeatureSet.size() * sizeof(FeatureSet[0]),
Kostya Serebryany5e67abd2019-04-13 01:57:33464 DirPlusFile(FeaturesDir, FileName));
Kostya Serebryany4614cc32019-04-13 00:20:31465}
466
467static void RenameFeatureSetFile(const std::string &FeaturesDir,
468 const std::string &OldFile,
469 const std::string &NewFile) {
470 if (FeaturesDir.empty()) return;
471 RenameFile(DirPlusFile(FeaturesDir, OldFile),
472 DirPlusFile(FeaturesDir, NewFile));
473}
474
Dokyung Song1bb1eac2020-07-08 19:30:53475static void WriteEdgeToMutationGraphFile(const std::string &MutationGraphFile,
476 const InputInfo *II,
477 const InputInfo *BaseII,
478 const std::string &MS) {
479 if (MutationGraphFile.empty())
480 return;
481
482 std::string Sha1 = Sha1ToString(II->Sha1);
483
484 std::string OutputString;
485
486 // Add a new vertex.
487 OutputString.append("\"");
488 OutputString.append(Sha1);
489 OutputString.append("\"\n");
490
491 // Add a new edge if there is base input.
492 if (BaseII) {
493 std::string BaseSha1 = Sha1ToString(BaseII->Sha1);
494 OutputString.append("\"");
495 OutputString.append(BaseSha1);
496 OutputString.append("\" -> \"");
497 OutputString.append(Sha1);
498 OutputString.append("\" [label=\"");
499 OutputString.append(MS);
500 OutputString.append("\"];\n");
501 }
502
503 AppendToFile(OutputString, MutationGraphFile);
504}
505
George Karpenkov10ab2ac2017-08-21 23:25:50506bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
Dokyung Song62673c42020-07-31 00:07:20507 InputInfo *II, bool ForceAddToCorpus,
508 bool *FoundUniqFeatures) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33509 if (!Size)
510 return false;
Aaron Green67081862021-03-12 00:00:53511 // Largest input length should be INT_MAX.
512 assert(Size < std::numeric_limits<uint32_t>::max());
George Karpenkov10ab2ac2017-08-21 23:25:50513
Kostya Serebryany92fb3102022-06-28 18:36:30514 if(!ExecuteCallback(Data, Size)) return false;
Dokyung Song5cda4dc2020-08-17 16:59:59515 auto TimeOfUnit = duration_cast<microseconds>(UnitStopTime - UnitStartTime);
George Karpenkov10ab2ac2017-08-21 23:25:50516
517 UniqFeatureSetTmp.clear();
518 size_t FoundUniqFeaturesOfII = 0;
519 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
Aaron Green67081862021-03-12 00:00:53520 TPC.CollectFeatures([&](uint32_t Feature) {
521 if (Corpus.AddFeature(Feature, static_cast<uint32_t>(Size), Options.Shrink))
George Karpenkov10ab2ac2017-08-21 23:25:50522 UniqFeatureSetTmp.push_back(Feature);
Matt Morehousee2e38fc2020-05-19 17:28:18523 if (Options.Entropic)
524 Corpus.UpdateFeatureFrequency(II, Feature);
Dokyung Song62673c42020-07-31 00:07:20525 if (Options.ReduceInputs && II && !II->NeverReduce)
George Karpenkov10ab2ac2017-08-21 23:25:50526 if (std::binary_search(II->UniqFeatureSet.begin(),
527 II->UniqFeatureSet.end(), Feature))
528 FoundUniqFeaturesOfII++;
529 });
Kostya Serebryanyad05ee02017-12-01 19:18:38530 if (FoundUniqFeatures)
531 *FoundUniqFeatures = FoundUniqFeaturesOfII;
George Karpenkov10ab2ac2017-08-21 23:25:50532 PrintPulseAndReportSlowInput(Data, Size);
533 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
Dokyung Song62673c42020-07-31 00:07:20534 if (NumNewFeatures || ForceAddToCorpus) {
George Karpenkov10ab2ac2017-08-21 23:25:50535 TPC.UpdateObservedPCs();
Dokyung Song62673c42020-07-31 00:07:20536 auto NewII =
537 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
538 TPC.ObservedFocusFunction(), ForceAddToCorpus,
Dokyung Song5cda4dc2020-08-17 16:59:59539 TimeOfUnit, UniqFeatureSetTmp, DFT, II);
Kostya Serebryany5e67abd2019-04-13 01:57:33540 WriteFeatureSetToFile(Options.FeaturesDir, Sha1ToString(NewII->Sha1),
Kostya Serebryany4614cc32019-04-13 00:20:31541 NewII->UniqFeatureSet);
Dokyung Song1bb1eac2020-07-08 19:30:53542 WriteEdgeToMutationGraphFile(Options.MutationGraphFile, NewII, II,
Marco Vanottic5d72512021-07-02 16:44:54543 MD.MutationSequence());
George Karpenkov10ab2ac2017-08-21 23:25:50544 return true;
545 }
546 if (II && FoundUniqFeaturesOfII &&
Kostya Serebryany67af9922018-06-07 01:40:20547 II->DataFlowTraceForFocusFunction.empty() &&
George Karpenkov10ab2ac2017-08-21 23:25:50548 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
549 II->U.size() > Size) {
Kostya Serebryany4614cc32019-04-13 00:20:31550 auto OldFeaturesFile = Sha1ToString(II->Sha1);
PZ Read9e7b7302021-10-20 13:14:22551 Corpus.Replace(II, {Data, Data + Size}, TimeOfUnit);
Kostya Serebryany4614cc32019-04-13 00:20:31552 RenameFeatureSetFile(Options.FeaturesDir, OldFeaturesFile,
553 Sha1ToString(II->Sha1));
George Karpenkov10ab2ac2017-08-21 23:25:50554 return true;
555 }
556 return false;
557}
558
Max Morozdc62d5e2020-10-23 18:07:30559void Fuzzer::TPCUpdateObservedPCs() { TPC.UpdateObservedPCs(); }
560
George Karpenkov10ab2ac2017-08-21 23:25:50561size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
562 assert(InFuzzingThread());
563 *Data = CurrentUnitData;
564 return CurrentUnitSize;
565}
566
567void Fuzzer::CrashOnOverwrittenData() {
Mitch Phillipsda3cf612019-09-26 00:54:30568 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites its const input\n",
George Karpenkov10ab2ac2017-08-21 23:25:50569 GetPid());
Mitch Phillipsd1e222e2019-09-27 22:04:36570 PrintStackTrace();
571 Printf("SUMMARY: libFuzzer: overwrites-const-input\n");
George Karpenkov10ab2ac2017-08-21 23:25:50572 DumpCurrentUnit("crash-");
Mitch Phillipsd1e222e2019-09-27 22:04:36573 PrintFinalStats();
George Karpenkov10ab2ac2017-08-21 23:25:50574 _Exit(Options.ErrorExitCode); // Stop right now.
575}
576
577// Compare two arrays, but not all bytes if the arrays are large.
578static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
579 const size_t Limit = 64;
580 if (Size <= 64)
581 return !memcmp(A, B, Size);
582 // Compare first and last Limit/2 bytes.
583 return !memcmp(A, B, Limit / 2) &&
584 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
585}
586
Jonas Paulsson5908c7c2021-03-04 20:55:41587// This method is not inlined because it would cause a test to fail where it
588// is part of the stack unwinding. See D97975 for details.
Kostya Serebryany92fb3102022-06-28 18:36:30589ATTRIBUTE_NOINLINE bool Fuzzer::ExecuteCallback(const uint8_t *Data,
Matt Morehouse4b82f612021-03-12 22:36:57590 size_t Size) {
George Karpenkov10ab2ac2017-08-21 23:25:50591 TPC.RecordInitialStack();
592 TotalNumberOfRuns++;
593 assert(InFuzzingThread());
George Karpenkov10ab2ac2017-08-21 23:25:50594 // We copy the contents of Unit into a separate heap buffer
595 // so that we reliably find buffer overflows in it.
596 uint8_t *DataCopy = new uint8_t[Size];
597 memcpy(DataCopy, Data, Size);
Matt Morehousea34c65e2018-07-09 23:51:08598 if (EF->__msan_unpoison)
599 EF->__msan_unpoison(DataCopy, Size);
Matt Morehouse34784942019-05-09 22:48:46600 if (EF->__msan_unpoison_param)
601 EF->__msan_unpoison_param(2);
George Karpenkov10ab2ac2017-08-21 23:25:50602 if (CurrentUnitData && CurrentUnitData != Data)
603 memcpy(CurrentUnitData, Data, Size);
604 CurrentUnitSize = Size;
Kostya Serebryany92fb3102022-06-28 18:36:30605 int CBRes = 0;
Matt Morehousea34c65e2018-07-09 23:51:08606 {
607 ScopedEnableMsanInterceptorChecks S;
608 AllocTracer.Start(Options.TraceMalloc);
609 UnitStartTime = system_clock::now();
610 TPC.ResetMaps();
Matt Morehouse43a22962018-07-17 16:12:00611 RunningUserCallback = true;
Kostya Serebryany92fb3102022-06-28 18:36:30612 CBRes = CB(DataCopy, Size);
Matt Morehouse43a22962018-07-17 16:12:00613 RunningUserCallback = false;
Matt Morehousea34c65e2018-07-09 23:51:08614 UnitStopTime = system_clock::now();
Kostya Serebryany92fb3102022-06-28 18:36:30615 assert(CBRes == 0 || CBRes == -1);
Matt Morehousea34c65e2018-07-09 23:51:08616 HasMoreMallocsThanFrees = AllocTracer.Stop();
617 }
George Karpenkov10ab2ac2017-08-21 23:25:50618 if (!LooseMemeq(DataCopy, Data, Size))
619 CrashOnOverwrittenData();
620 CurrentUnitSize = 0;
621 delete[] DataCopy;
Kostya Serebryany92fb3102022-06-28 18:36:30622 return CBRes == 0;
George Karpenkov10ab2ac2017-08-21 23:25:50623}
624
Kostya Serebryany63f48712019-02-12 00:12:33625std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
George Karpenkov10ab2ac2017-08-21 23:25:50626 if (Options.OnlyASCII)
627 assert(IsASCII(U));
628 if (Options.OutputCorpus.empty())
Kostya Serebryany63f48712019-02-12 00:12:33629 return "";
George Karpenkov10ab2ac2017-08-21 23:25:50630 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
631 WriteToFile(U, Path);
632 if (Options.Verbosity >= 2)
633 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
Kostya Serebryany63f48712019-02-12 00:12:33634 return Path;
George Karpenkov10ab2ac2017-08-21 23:25:50635}
636
637void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
638 if (!Options.SaveArtifacts)
639 return;
640 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
641 if (!Options.ExactArtifactPath.empty())
642 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
643 WriteToFile(U, Path);
644 Printf("artifact_prefix='%s'; Test unit written to %s\n",
645 Options.ArtifactPrefix.c_str(), Path.c_str());
646 if (U.size() <= kMaxUnitSizeToPrint)
647 Printf("Base64: %s\n", Base64(U).c_str());
648}
649
650void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
651 if (!Options.PrintNEW)
652 return;
653 PrintStats(Text, "");
654 if (Options.Verbosity) {
655 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
Marco Vanottic5d72512021-07-02 16:44:54656 MD.PrintMutationSequence(Options.Verbosity >= 2);
George Karpenkov10ab2ac2017-08-21 23:25:50657 Printf("\n");
658 }
659}
660
661void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
662 II->NumSuccessfullMutations++;
663 MD.RecordSuccessfulMutationSequence();
Alex Shlyapnikov5ded0702017-10-23 23:24:33664 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
George Karpenkov10ab2ac2017-08-21 23:25:50665 WriteToOutputCorpus(U);
666 NumberOfNewUnitsAdded++;
Alex Shlyapnikov5ded0702017-10-23 23:24:33667 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50668 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50669}
670
671// Tries detecting a memory leak on the particular input that we have just
672// executed before calling this function.
673void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
674 bool DuringInitialCorpusExecution) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33675 if (!HasMoreMallocsThanFrees)
676 return; // mallocs==frees, a leak is unlikely.
677 if (!Options.DetectLeaks)
678 return;
Max Moroz3f26dac2017-09-12 02:01:54679 if (!DuringInitialCorpusExecution &&
Alex Shlyapnikov5ded0702017-10-23 23:24:33680 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
681 return;
George Karpenkov10ab2ac2017-08-21 23:25:50682 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
683 !(EF->__lsan_do_recoverable_leak_check))
Alex Shlyapnikov5ded0702017-10-23 23:24:33684 return; // No lsan.
George Karpenkov10ab2ac2017-08-21 23:25:50685 // Run the target once again, but with lsan disabled so that if there is
686 // a real leak we do not report it twice.
687 EF->__lsan_disable();
688 ExecuteCallback(Data, Size);
689 EF->__lsan_enable();
Alex Shlyapnikov5ded0702017-10-23 23:24:33690 if (!HasMoreMallocsThanFrees)
691 return; // a leak is unlikely.
George Karpenkov10ab2ac2017-08-21 23:25:50692 if (NumberOfLeakDetectionAttempts++ > 1000) {
693 Options.DetectLeaks = false;
694 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
695 " Most likely the target function accumulates allocated\n"
696 " memory in a global state w/o actually leaking it.\n"
697 " You may try running this binary with -trace_malloc=[12]"
698 " to get a trace of mallocs and frees.\n"
699 " If LeakSanitizer is enabled in this process it will still\n"
700 " run on the process shutdown.\n");
701 return;
702 }
703 // Now perform the actual lsan pass. This is expensive and we must ensure
704 // we don't call it too often.
705 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
706 if (DuringInitialCorpusExecution)
707 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
708 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
709 CurrentUnitSize = Size;
710 DumpCurrentUnit("leak-");
711 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33712 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
George Karpenkov10ab2ac2017-08-21 23:25:50713 }
714}
715
716void Fuzzer::MutateAndTestOne() {
717 MD.StartMutationSequence();
718
719 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Dokyung Songb53243e2020-09-01 16:22:59720 if (Options.DoCrossOver) {
721 auto &CrossOverII = Corpus.ChooseUnitToCrossOverWith(
722 MD.GetRand(), Options.CrossOverUniformDist);
723 MD.SetCrossOverWith(&CrossOverII.U);
724 }
George Karpenkov10ab2ac2017-08-21 23:25:50725 const auto &U = II.U;
726 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
727 assert(CurrentUnitData);
728 size_t Size = U.size();
729 assert(Size <= MaxInputLen && "Oversized Unit");
730 memcpy(CurrentUnitData, U.data(), Size);
731
732 assert(MaxMutationLen > 0);
733
734 size_t CurrentMaxMutationLen =
735 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
736 assert(CurrentMaxMutationLen > 0);
737
738 for (int i = 0; i < Options.MutateDepth; i++) {
739 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
740 break;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19741 MaybeExitGracefully();
George Karpenkov10ab2ac2017-08-21 23:25:50742 size_t NewSize = 0;
Kostya Serebryany6b87e0c2018-07-19 01:23:32743 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
744 Size <= CurrentMaxMutationLen)
745 NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
746 II.DataFlowTraceForFocusFunction);
Matt Morehouse1b760632019-04-26 00:17:41747
Max Moroz9d5e7ee2019-04-11 16:24:53748 // If MutateWithMask either failed or wasn't called, call default Mutate.
749 if (!NewSize)
Kostya Serebryany6b87e0c2018-07-19 01:23:32750 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50751 assert(NewSize > 0 && "Mutator returned empty unit");
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30752 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
George Karpenkov10ab2ac2017-08-21 23:25:50753 Size = NewSize;
754 II.NumExecutedMutations++;
Matt Morehousee2e38fc2020-05-19 17:28:18755 Corpus.IncrementNumExecutedMutations();
George Karpenkov10ab2ac2017-08-21 23:25:50756
Kostya Serebryanyad05ee02017-12-01 19:18:38757 bool FoundUniqFeatures = false;
758 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
Dokyung Song62673c42020-07-31 00:07:20759 /*ForceAddToCorpus*/ false, &FoundUniqFeatures);
George Karpenkov10ab2ac2017-08-21 23:25:50760 TryDetectingAMemoryLeak(CurrentUnitData, Size,
761 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryanyad05ee02017-12-01 19:18:38762 if (NewCov) {
Matt Morehouse947838c2017-11-09 20:44:08763 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryanyad05ee02017-12-01 19:18:38764 break; // We will mutate this input more in the next rounds.
765 }
766 if (Options.ReduceDepth && !FoundUniqFeatures)
Matt Morehouse34784942019-05-09 22:48:46767 break;
George Karpenkov10ab2ac2017-08-21 23:25:50768 }
Matt Morehousee2e38fc2020-05-19 17:28:18769
770 II.NeedsEnergyUpdate = true;
George Karpenkov10ab2ac2017-08-21 23:25:50771}
772
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30773void Fuzzer::PurgeAllocator() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33774 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30775 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30776 if (duration_cast<seconds>(system_clock::now() -
Alex Shlyapnikov5ded0702017-10-23 23:24:33777 LastAllocatorPurgeAttemptTime)
778 .count() < Options.PurgeAllocatorIntervalSec)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30779 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30780
781 if (Options.RssLimitMb <= 0 ||
Alex Shlyapnikov5ded0702017-10-23 23:24:33782 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30783 EF->__sanitizer_purge_allocator();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30784
785 LastAllocatorPurgeAttemptTime = system_clock::now();
786}
787
Kostya Serebryany7c921752021-08-03 17:04:16788void Fuzzer::ReadAndExecuteSeedCorpora(std::vector<SizedFile> &CorporaFiles) {
Kostya Serebryany3a8e3c82017-08-29 02:05:01789 const size_t kMaxSaneLen = 1 << 20;
790 const size_t kMinDefaultLen = 4096;
Kostya Serebryany4faeb872017-08-29 20:51:24791 size_t MaxSize = 0;
792 size_t MinSize = -1;
793 size_t TotalSize = 0;
Kostya Serebryany4c7353c2019-05-10 01:34:26794 for (auto &File : CorporaFiles) {
Kostya Serebryany93679be2017-09-12 21:58:07795 MaxSize = Max(File.Size, MaxSize);
796 MinSize = Min(File.Size, MinSize);
797 TotalSize += File.Size;
Kostya Serebryany3a8e3c82017-08-29 02:05:01798 }
Kostya Serebryany4faeb872017-08-29 20:51:24799 if (Options.MaxLen == 0)
800 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
801 assert(MaxInputLen > 0);
802
Kostya Serebryany51823d32017-10-13 01:12:23803 // Test the callback with empty input and never try it again.
804 uint8_t dummy = 0;
805 ExecuteCallback(&dummy, 0);
806
Kostya Serebryany4c7353c2019-05-10 01:34:26807 if (CorporaFiles.empty()) {
Kostya Serebryany4faeb872017-08-29 20:51:24808 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
809 Unit U({'\n'}); // Valid ASCII input.
810 RunOne(U.data(), U.size());
811 } else {
812 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
813 " rss: %zdMb\n",
Kostya Serebryany4c7353c2019-05-10 01:34:26814 CorporaFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
Kostya Serebryany4faeb872017-08-29 20:51:24815 if (Options.ShuffleAtStartUp)
Kostya Serebryany4c7353c2019-05-10 01:34:26816 std::shuffle(CorporaFiles.begin(), CorporaFiles.end(), MD.GetRand());
Kostya Serebryany4faeb872017-08-29 20:51:24817
Kostya Serebryany93679be2017-09-12 21:58:07818 if (Options.PreferSmall) {
Kostya Serebryany4c7353c2019-05-10 01:34:26819 std::stable_sort(CorporaFiles.begin(), CorporaFiles.end());
820 assert(CorporaFiles.front().Size <= CorporaFiles.back().Size);
Kostya Serebryany93679be2017-09-12 21:58:07821 }
Kostya Serebryany4faeb872017-08-29 20:51:24822
823 // Load and execute inputs one by one.
Kostya Serebryany4c7353c2019-05-10 01:34:26824 for (auto &SF : CorporaFiles) {
Kostya Serebryany082e9a72017-08-31 19:17:15825 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
Kostya Serebryany4faeb872017-08-29 20:51:24826 assert(U.size() <= MaxInputLen);
Dokyung Song62673c42020-07-31 00:07:20827 RunOne(U.data(), U.size(), /*MayDeleteFile*/ false, /*II*/ nullptr,
828 /*ForceAddToCorpus*/ Options.KeepSeed,
829 /*FoundUniqFeatures*/ nullptr);
Kostya Serebryany4faeb872017-08-29 20:51:24830 CheckExitOnSrcPosOrItem();
831 TryDetectingAMemoryLeak(U.data(), U.size(),
832 /*DuringInitialCorpusExecution*/ true);
833 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01834 }
835
Kostya Serebryany4faeb872017-08-29 20:51:24836 PrintStats("INITED");
Max Moroz07647572020-02-18 17:57:16837 if (!Options.FocusFunction.empty()) {
Kostya Serebryanye9c6f062018-05-16 23:26:37838 Printf("INFO: %zd/%zd inputs touch the focus function\n",
839 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
Max Moroz07647572020-02-18 17:57:16840 if (!Options.DataFlowTrace.empty())
841 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
842 Corpus.NumInputsWithDataFlowTrace(),
843 Corpus.NumInputsThatTouchFocusFunction());
844 }
Kostya Serebryanye9c6f062018-05-16 23:26:37845
Max Morozfe974412018-05-23 19:42:30846 if (Corpus.empty() && Options.MaxNumberOfRuns) {
Kostya Serebryany92fb3102022-06-28 18:36:30847 Printf("WARNING: no interesting inputs were found so far. "
848 "Is the code instrumented for coverage?\n"
849 "This may also happen if the target rejected all inputs we tried so "
850 "far\n");
851 // The remaining logic requires that the corpus is not empty,
852 // so we add one fake input to the in-memory corpus.
853 Corpus.AddToCorpus({'\n'}, /*NumFeatures=*/1, /*MayDeleteFile=*/true,
854 /*HasFocusFunction=*/false, /*NeverReduce=*/false,
855 /*TimeOfUnit=*/duration_cast<microseconds>(0s), {0}, DFT,
856 /*BaseII*/ nullptr);
Kostya Serebryany3a8e3c82017-08-29 02:05:01857 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01858}
859
Kostya Serebryany7c921752021-08-03 17:04:16860void Fuzzer::Loop(std::vector<SizedFile> &CorporaFiles) {
Kostya Serebryany060f4b42019-05-24 00:43:52861 auto FocusFunctionOrAuto = Options.FocusFunction;
862 DFT.Init(Options.DataFlowTrace, &FocusFunctionOrAuto, CorporaFiles,
863 MD.GetRand());
864 TPC.SetFocusFunction(FocusFunctionOrAuto);
Kostya Serebryany4c7353c2019-05-10 01:34:26865 ReadAndExecuteSeedCorpora(CorporaFiles);
Kostya Serebryany67af9922018-06-07 01:40:20866 DFT.Clear(); // No need for DFT any more.
George Karpenkov10ab2ac2017-08-21 23:25:50867 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryany2eef8162017-08-25 20:09:25868 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
George Karpenkov10ab2ac2017-08-21 23:25:50869 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryanyb6ca1e72019-02-16 01:23:41870
871 TmpMaxMutationLen =
872 Min(MaxMutationLen, Max(size_t(4), Corpus.MaxInputSize()));
873
George Karpenkov10ab2ac2017-08-21 23:25:50874 while (true) {
875 auto Now = system_clock::now();
Kostya Serebryanydb88fc52019-06-14 22:56:50876 if (!Options.StopFile.empty() &&
877 !FileToVector(Options.StopFile, 1, false).empty())
878 break;
George Karpenkov10ab2ac2017-08-21 23:25:50879 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
880 Options.ReloadIntervalSec) {
881 RereadOutputCorpus(MaxInputLen);
882 LastCorpusReload = system_clock::now();
883 }
884 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
885 break;
Alex Shlyapnikov5ded0702017-10-23 23:24:33886 if (TimedOut())
887 break;
George Karpenkov10ab2ac2017-08-21 23:25:50888
889 // Update TmpMaxMutationLen
Matt Morehouse36c89b32018-02-13 20:52:15890 if (Options.LenControl) {
George Karpenkov10ab2ac2017-08-21 23:25:50891 if (TmpMaxMutationLen < MaxMutationLen &&
Kostya Serebryanye9ed2322017-12-12 23:11:28892 TotalNumberOfRuns - LastCorpusUpdateRun >
Matt Morehouse36c89b32018-02-13 20:52:15893 Options.LenControl * Log(TmpMaxMutationLen)) {
George Karpenkov10ab2ac2017-08-21 23:25:50894 TmpMaxMutationLen =
Kostya Serebryanye9ed2322017-12-12 23:11:28895 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
Kostya Serebryanye9ed2322017-12-12 23:11:28896 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50897 }
898 } else {
899 TmpMaxMutationLen = MaxMutationLen;
900 }
901
902 // Perform several mutations and runs.
903 MutateAndTestOne();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30904
905 PurgeAllocator();
George Karpenkov10ab2ac2017-08-21 23:25:50906 }
907
908 PrintStats("DONE ", "\n");
Marco Vanottic5d72512021-07-02 16:44:54909 MD.PrintRecommendedDictionary();
George Karpenkov10ab2ac2017-08-21 23:25:50910}
911
912void Fuzzer::MinimizeCrashLoop(const Unit &U) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33913 if (U.size() <= 1)
914 return;
George Karpenkov10ab2ac2017-08-21 23:25:50915 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
916 MD.StartMutationSequence();
917 memcpy(CurrentUnitData, U.data(), U.size());
918 for (int i = 0; i < Options.MutateDepth; i++) {
919 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
920 assert(NewSize > 0 && NewSize <= MaxMutationLen);
921 ExecuteCallback(CurrentUnitData, NewSize);
922 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
923 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
924 /*DuringInitialCorpusExecution*/ false);
925 }
926 }
927}
928
George Karpenkov10ab2ac2017-08-21 23:25:50929} // namespace fuzzer
930
931extern "C" {
932
Jonathan Metzmanb795c312019-01-17 16:36:05933ATTRIBUTE_INTERFACE size_t
Petr Hosekeac2b472018-01-17 20:39:14934LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
George Karpenkov10ab2ac2017-08-21 23:25:50935 assert(fuzzer::F);
936 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
937}
938
Alex Shlyapnikov5ded0702017-10-23 23:24:33939} // extern "C"