blob: 3609c7fcd8a557085e3d761922904c27ee91edc4 [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
Maxim Schessleraa0e9042022-08-15 18:44:06265int Fuzzer::InterruptExitCode() {
266 assert(F);
267 return F->Options.InterruptExitCode;
268}
269
George Karpenkov10ab2ac2017-08-21 23:25:50270void Fuzzer::InterruptCallback() {
271 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
272 PrintFinalStats();
Matt Morehouse1b760632019-04-26 00:17:41273 ScopedDisableMsanInterceptorChecks S; // RmDirRecursive may call opendir().
Yuanfang Chen4f3c3bb2020-02-11 02:22:09274 RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
Kostya Serebryany0fda9dc2019-02-09 00:16:21275 // Stop right now, don't perform any at-exit actions.
276 _Exit(Options.InterruptExitCode);
George Karpenkov10ab2ac2017-08-21 23:25:50277}
278
279NO_SANITIZE_MEMORY
280void Fuzzer::AlarmCallback() {
281 assert(Options.UnitTimeoutSec > 0);
Jake Ehrliche7bfce72019-10-09 21:01:50282 // In Windows and Fuchsia, Alarm callback is executed by a different thread.
Kamil Rytarowski2e611862018-11-06 01:28:01283 // NetBSD's current behavior needs this change too.
Jake Ehrliche7bfce72019-10-09 21:01:50284#if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD && !LIBFUZZER_FUCHSIA
Alex Shlyapnikov5ded0702017-10-23 23:24:33285 if (!InFuzzingThread())
286 return;
George Karpenkov10ab2ac2017-08-21 23:25:50287#endif
Matt Morehouse43a22962018-07-17 16:12:00288 if (!RunningUserCallback)
George Karpenkov10ab2ac2017-08-21 23:25:50289 return; // We have not started running units yet.
290 size_t Seconds =
291 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
292 if (Seconds == 0)
293 return;
294 if (Options.Verbosity >= 2)
295 Printf("AlarmCallback %zd\n", Seconds);
296 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Matt Morehouse52fd1692018-05-01 21:01:53297 if (EF->__sanitizer_acquire_crash_state &&
298 !EF->__sanitizer_acquire_crash_state())
299 return;
George Karpenkov10ab2ac2017-08-21 23:25:50300 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
301 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
302 Options.UnitTimeoutSec);
303 DumpCurrentUnit("timeout-");
Wu, Yingcong91985c22023-03-08 05:55:33304 Printf("==%lu== ERROR: libFuzzer: timeout after %zu seconds\n", GetPid(),
George Karpenkov10ab2ac2017-08-21 23:25:50305 Seconds);
Matt Morehouse14cf71a2018-05-08 23:45:05306 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50307 Printf("SUMMARY: libFuzzer: timeout\n");
308 PrintFinalStats();
309 _Exit(Options.TimeoutExitCode); // Stop right now.
310 }
311}
312
313void Fuzzer::RssLimitCallback() {
Matt Morehouse52fd1692018-05-01 21:01:53314 if (EF->__sanitizer_acquire_crash_state &&
315 !EF->__sanitizer_acquire_crash_state())
316 return;
Wu, Yingcong91985c22023-03-08 05:55:33317 Printf("==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %dMb)\n",
318 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
George Karpenkov10ab2ac2017-08-21 23:25:50319 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Matt Morehouse14cf71a2018-05-08 23:45:05320 PrintMemoryProfile();
George Karpenkov10ab2ac2017-08-21 23:25:50321 DumpCurrentUnit("oom-");
322 Printf("SUMMARY: libFuzzer: out-of-memory\n");
323 PrintFinalStats();
Kostya Serebryany0fda9dc2019-02-09 00:16:21324 _Exit(Options.OOMExitCode); // Stop right now.
George Karpenkov10ab2ac2017-08-21 23:25:50325}
326
Max Moroz74cec612019-08-12 20:21:27327void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units,
328 size_t Features) {
George Karpenkov10ab2ac2017-08-21 23:25:50329 size_t ExecPerSec = execPerSec();
330 if (!Options.Verbosity)
331 return;
332 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
333 if (size_t N = TPC.GetTotalPCCoverage())
334 Printf(" cov: %zd", N);
Max Moroz74cec612019-08-12 20:21:27335 if (size_t N = Features ? Features : Corpus.NumFeatures())
Alex Shlyapnikov5ded0702017-10-23 23:24:33336 Printf(" ft: %zd", N);
George Karpenkov10ab2ac2017-08-21 23:25:50337 if (!Corpus.empty()) {
338 Printf(" corp: %zd", Corpus.NumActiveUnits());
339 if (size_t N = Corpus.SizeInBytes()) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33340 if (N < (1 << 14))
George Karpenkov10ab2ac2017-08-21 23:25:50341 Printf("/%zdb", N);
342 else if (N < (1 << 24))
343 Printf("/%zdKb", N >> 10);
344 else
345 Printf("/%zdMb", N >> 20);
346 }
Kostya Serebryanye9c6f062018-05-16 23:26:37347 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
348 Printf(" focus: %zd", FF);
George Karpenkov10ab2ac2017-08-21 23:25:50349 }
Matt Morehouseddf352b2018-02-22 19:00:17350 if (TmpMaxMutationLen)
351 Printf(" lim: %zd", TmpMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50352 if (Units)
353 Printf(" units: %zd", Units);
354
355 Printf(" exec/s: %zd", ExecPerSec);
356 Printf(" rss: %zdMb", GetPeakRSSMb());
357 Printf("%s", End);
358}
359
360void Fuzzer::PrintFinalStats() {
Max Morozdc62d5e2020-10-23 18:07:30361 if (Options.PrintFullCoverage)
362 TPC.PrintCoverage(/*PrintAllCounters=*/true);
George Karpenkov10ab2ac2017-08-21 23:25:50363 if (Options.PrintCoverage)
Max Morozdc62d5e2020-10-23 18:07:30364 TPC.PrintCoverage(/*PrintAllCounters=*/false);
George Karpenkov10ab2ac2017-08-21 23:25:50365 if (Options.PrintCorpusStats)
366 Corpus.PrintStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33367 if (!Options.PrintFinalStats)
368 return;
George Karpenkov10ab2ac2017-08-21 23:25:50369 size_t ExecPerSec = execPerSec();
370 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
371 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
372 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
Wu, Yingcong91985c22023-03-08 05:55:33373 Printf("stat::slowest_unit_time_sec: %ld\n", TimeOfLongestUnitInSeconds);
George Karpenkov10ab2ac2017-08-21 23:25:50374 Printf("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("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()) {
Kostya Serebryany7c921752021-08-03 17:04:16395 static auto *PCsSet = new std::set<uintptr_t>;
Kostya Serebryany96f81bc2019-02-14 23:12:33396 auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
397 if (!PCsSet->insert(TE->PC).second)
Alex Shlyapnikov5ded0702017-10-23 23:24:33398 return;
Kostya Serebryany96f81bc2019-02-14 23:12:33399 std::string Descr = DescribePC("%F %L", TE->PC + 1);
George Karpenkov10ab2ac2017-08-21 23:25:50400 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
401 Printf("INFO: found line matching '%s', exiting.\n",
402 Options.ExitOnSrcPos.c_str());
403 _Exit(0);
404 }
405 };
406 TPC.ForEachObservedPC(HandlePC);
407 }
408 if (!Options.ExitOnItem.empty()) {
409 if (Corpus.HasUnit(Options.ExitOnItem)) {
410 Printf("INFO: found item with checksum '%s', exiting.\n",
411 Options.ExitOnItem.c_str());
412 _Exit(0);
413 }
414 }
415}
416
417void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33418 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
419 return;
Kostya Serebryany7c921752021-08-03 17:04:16420 std::vector<Unit> AdditionalCorpus;
421 std::vector<std::string> AdditionalCorpusPaths;
Alexey Vishnyakov827ccc92021-04-16 16:21:49422 ReadDirToVectorOfUnits(
423 Options.OutputCorpus.c_str(), &AdditionalCorpus,
424 &EpochOfLastReadOfOutputCorpus, MaxSize,
425 /*ExitOnError*/ false,
426 (Options.Verbosity >= 2 ? &AdditionalCorpusPaths : nullptr));
George Karpenkov10ab2ac2017-08-21 23:25:50427 if (Options.Verbosity >= 2)
428 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
429 bool Reloaded = false;
Alexey Vishnyakov827ccc92021-04-16 16:21:49430 for (size_t i = 0; i != AdditionalCorpus.size(); ++i) {
431 auto &U = AdditionalCorpus[i];
George Karpenkov10ab2ac2017-08-21 23:25:50432 if (U.size() > MaxSize)
433 U.resize(MaxSize);
434 if (!Corpus.HasUnit(U)) {
435 if (RunOne(U.data(), U.size())) {
436 CheckExitOnSrcPosOrItem();
437 Reloaded = true;
Alexey Vishnyakov827ccc92021-04-16 16:21:49438 if (Options.Verbosity >= 2)
439 Printf("Reloaded %s\n", AdditionalCorpusPaths[i].c_str());
George Karpenkov10ab2ac2017-08-21 23:25:50440 }
441 }
442 }
443 if (Reloaded)
444 PrintStats("RELOAD");
445}
446
George Karpenkov10ab2ac2017-08-21 23:25:50447void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
448 auto TimeOfUnit =
449 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
450 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
451 secondsSinceProcessStartUp() >= 2)
452 PrintStats("pulse ");
Aaron Green67081862021-03-12 00:00:53453 auto Threshhold =
454 static_cast<long>(static_cast<double>(TimeOfLongestUnitInSeconds) * 1.1);
455 if (TimeOfUnit > Threshhold && TimeOfUnit >= Options.ReportSlowUnits) {
George Karpenkov10ab2ac2017-08-21 23:25:50456 TimeOfLongestUnitInSeconds = TimeOfUnit;
Wu, Yingcong91985c22023-03-08 05:55:33457 Printf("Slowest unit: %ld s:\n", TimeOfLongestUnitInSeconds);
George Karpenkov10ab2ac2017-08-21 23:25:50458 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
459 }
460}
461
Kostya Serebryany4614cc32019-04-13 00:20:31462static void WriteFeatureSetToFile(const std::string &FeaturesDir,
Kostya Serebryany5e67abd2019-04-13 01:57:33463 const std::string &FileName,
Kostya Serebryany7c921752021-08-03 17:04:16464 const std::vector<uint32_t> &FeatureSet) {
Kostya Serebryany4614cc32019-04-13 00:20:31465 if (FeaturesDir.empty() || FeatureSet.empty()) return;
466 WriteToFile(reinterpret_cast<const uint8_t *>(FeatureSet.data()),
467 FeatureSet.size() * sizeof(FeatureSet[0]),
Kostya Serebryany5e67abd2019-04-13 01:57:33468 DirPlusFile(FeaturesDir, FileName));
Kostya Serebryany4614cc32019-04-13 00:20:31469}
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(DirPlusFile(FeaturesDir, OldFile),
476 DirPlusFile(FeaturesDir, NewFile));
477}
478
Dokyung Song1bb1eac2020-07-08 19:30:53479static 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(II->Sha1);
487
488 std::string OutputString;
489
490 // Add a new vertex.
491 OutputString.append("\"");
492 OutputString.append(Sha1);
493 OutputString.append("\"\n");
494
495 // Add a new edge if there is base input.
496 if (BaseII) {
497 std::string BaseSha1 = Sha1ToString(BaseII->Sha1);
498 OutputString.append("\"");
499 OutputString.append(BaseSha1);
500 OutputString.append("\" -> \"");
501 OutputString.append(Sha1);
502 OutputString.append("\" [label=\"");
503 OutputString.append(MS);
504 OutputString.append("\"];\n");
505 }
506
507 AppendToFile(OutputString, MutationGraphFile);
508}
509
George Karpenkov10ab2ac2017-08-21 23:25:50510bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
Dokyung Song62673c42020-07-31 00:07:20511 InputInfo *II, bool ForceAddToCorpus,
512 bool *FoundUniqFeatures) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33513 if (!Size)
514 return false;
Aaron Green67081862021-03-12 00:00:53515 // Largest input length should be INT_MAX.
516 assert(Size < std::numeric_limits<uint32_t>::max());
George Karpenkov10ab2ac2017-08-21 23:25:50517
Kostya Serebryany92fb3102022-06-28 18:36:30518 if(!ExecuteCallback(Data, Size)) return false;
Dokyung Song5cda4dc2020-08-17 16:59:59519 auto TimeOfUnit = duration_cast<microseconds>(UnitStopTime - UnitStartTime);
George Karpenkov10ab2ac2017-08-21 23:25:50520
521 UniqFeatureSetTmp.clear();
522 size_t FoundUniqFeaturesOfII = 0;
523 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
Aaron Green67081862021-03-12 00:00:53524 TPC.CollectFeatures([&](uint32_t Feature) {
525 if (Corpus.AddFeature(Feature, static_cast<uint32_t>(Size), Options.Shrink))
George Karpenkov10ab2ac2017-08-21 23:25:50526 UniqFeatureSetTmp.push_back(Feature);
Matt Morehousee2e38fc2020-05-19 17:28:18527 if (Options.Entropic)
528 Corpus.UpdateFeatureFrequency(II, Feature);
Dokyung Song62673c42020-07-31 00:07:20529 if (Options.ReduceInputs && II && !II->NeverReduce)
George Karpenkov10ab2ac2017-08-21 23:25:50530 if (std::binary_search(II->UniqFeatureSet.begin(),
531 II->UniqFeatureSet.end(), Feature))
532 FoundUniqFeaturesOfII++;
533 });
Kostya Serebryanyad05ee02017-12-01 19:18:38534 if (FoundUniqFeatures)
535 *FoundUniqFeatures = FoundUniqFeaturesOfII;
George Karpenkov10ab2ac2017-08-21 23:25:50536 PrintPulseAndReportSlowInput(Data, Size);
537 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
Dokyung Song62673c42020-07-31 00:07:20538 if (NumNewFeatures || ForceAddToCorpus) {
George Karpenkov10ab2ac2017-08-21 23:25:50539 TPC.UpdateObservedPCs();
Dokyung Song62673c42020-07-31 00:07:20540 auto NewII =
541 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
542 TPC.ObservedFocusFunction(), ForceAddToCorpus,
Dokyung Song5cda4dc2020-08-17 16:59:59543 TimeOfUnit, UniqFeatureSetTmp, DFT, II);
Kostya Serebryany5e67abd2019-04-13 01:57:33544 WriteFeatureSetToFile(Options.FeaturesDir, Sha1ToString(NewII->Sha1),
Kostya Serebryany4614cc32019-04-13 00:20:31545 NewII->UniqFeatureSet);
Dokyung Song1bb1eac2020-07-08 19:30:53546 WriteEdgeToMutationGraphFile(Options.MutationGraphFile, NewII, II,
Marco Vanottic5d72512021-07-02 16:44:54547 MD.MutationSequence());
George Karpenkov10ab2ac2017-08-21 23:25:50548 return true;
549 }
550 if (II && FoundUniqFeaturesOfII &&
Kostya Serebryany67af9922018-06-07 01:40:20551 II->DataFlowTraceForFocusFunction.empty() &&
George Karpenkov10ab2ac2017-08-21 23:25:50552 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
553 II->U.size() > Size) {
Kostya Serebryany4614cc32019-04-13 00:20:31554 auto OldFeaturesFile = Sha1ToString(II->Sha1);
PZ Read9e7b7302021-10-20 13:14:22555 Corpus.Replace(II, {Data, Data + Size}, TimeOfUnit);
Kostya Serebryany4614cc32019-04-13 00:20:31556 RenameFeatureSetFile(Options.FeaturesDir, OldFeaturesFile,
557 Sha1ToString(II->Sha1));
George Karpenkov10ab2ac2017-08-21 23:25:50558 return true;
559 }
560 return false;
561}
562
Max Morozdc62d5e2020-10-23 18:07:30563void Fuzzer::TPCUpdateObservedPCs() { TPC.UpdateObservedPCs(); }
564
George Karpenkov10ab2ac2017-08-21 23:25:50565size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
566 assert(InFuzzingThread());
567 *Data = CurrentUnitData;
568 return CurrentUnitSize;
569}
570
571void Fuzzer::CrashOnOverwrittenData() {
Mitch Phillipsda3cf612019-09-26 00:54:30572 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites its const input\n",
George Karpenkov10ab2ac2017-08-21 23:25:50573 GetPid());
Mitch Phillipsd1e222e2019-09-27 22:04:36574 PrintStackTrace();
575 Printf("SUMMARY: libFuzzer: overwrites-const-input\n");
George Karpenkov10ab2ac2017-08-21 23:25:50576 DumpCurrentUnit("crash-");
Mitch Phillipsd1e222e2019-09-27 22:04:36577 PrintFinalStats();
George Karpenkov10ab2ac2017-08-21 23:25:50578 _Exit(Options.ErrorExitCode); // Stop right now.
579}
580
581// Compare two arrays, but not all bytes if the arrays are large.
582static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
583 const size_t Limit = 64;
584 if (Size <= 64)
585 return !memcmp(A, B, Size);
586 // Compare first and last Limit/2 bytes.
587 return !memcmp(A, B, Limit / 2) &&
588 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
589}
590
Jonas Paulsson5908c7c2021-03-04 20:55:41591// This method is not inlined because it would cause a test to fail where it
592// is part of the stack unwinding. See D97975 for details.
Kostya Serebryany92fb3102022-06-28 18:36:30593ATTRIBUTE_NOINLINE bool Fuzzer::ExecuteCallback(const uint8_t *Data,
Matt Morehouse4b82f612021-03-12 22:36:57594 size_t Size) {
George Karpenkov10ab2ac2017-08-21 23:25:50595 TPC.RecordInitialStack();
596 TotalNumberOfRuns++;
597 assert(InFuzzingThread());
George Karpenkov10ab2ac2017-08-21 23:25:50598 // We copy the contents of Unit into a separate heap buffer
599 // so that we reliably find buffer overflows in it.
600 uint8_t *DataCopy = new uint8_t[Size];
601 memcpy(DataCopy, Data, Size);
Matt Morehousea34c65e2018-07-09 23:51:08602 if (EF->__msan_unpoison)
603 EF->__msan_unpoison(DataCopy, Size);
Matt Morehouse34784942019-05-09 22:48:46604 if (EF->__msan_unpoison_param)
605 EF->__msan_unpoison_param(2);
George Karpenkov10ab2ac2017-08-21 23:25:50606 if (CurrentUnitData && CurrentUnitData != Data)
607 memcpy(CurrentUnitData, Data, Size);
608 CurrentUnitSize = Size;
Kostya Serebryany92fb3102022-06-28 18:36:30609 int CBRes = 0;
Matt Morehousea34c65e2018-07-09 23:51:08610 {
611 ScopedEnableMsanInterceptorChecks S;
612 AllocTracer.Start(Options.TraceMalloc);
613 UnitStartTime = system_clock::now();
614 TPC.ResetMaps();
Matt Morehouse43a22962018-07-17 16:12:00615 RunningUserCallback = true;
Kostya Serebryany92fb3102022-06-28 18:36:30616 CBRes = CB(DataCopy, Size);
Matt Morehouse43a22962018-07-17 16:12:00617 RunningUserCallback = false;
Matt Morehousea34c65e2018-07-09 23:51:08618 UnitStopTime = system_clock::now();
Kostya Serebryany92fb3102022-06-28 18:36:30619 assert(CBRes == 0 || CBRes == -1);
Matt Morehousea34c65e2018-07-09 23:51:08620 HasMoreMallocsThanFrees = AllocTracer.Stop();
621 }
George Karpenkov10ab2ac2017-08-21 23:25:50622 if (!LooseMemeq(DataCopy, Data, Size))
623 CrashOnOverwrittenData();
624 CurrentUnitSize = 0;
625 delete[] DataCopy;
Kostya Serebryany92fb3102022-06-28 18:36:30626 return CBRes == 0;
George Karpenkov10ab2ac2017-08-21 23:25:50627}
628
Kostya Serebryany63f48712019-02-12 00:12:33629std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
George Karpenkov10ab2ac2017-08-21 23:25:50630 if (Options.OnlyASCII)
631 assert(IsASCII(U));
632 if (Options.OutputCorpus.empty())
Kostya Serebryany63f48712019-02-12 00:12:33633 return "";
George Karpenkov10ab2ac2017-08-21 23:25:50634 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
635 WriteToFile(U, Path);
636 if (Options.Verbosity >= 2)
637 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
Kostya Serebryany63f48712019-02-12 00:12:33638 return Path;
George Karpenkov10ab2ac2017-08-21 23:25:50639}
640
641void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
642 if (!Options.SaveArtifacts)
643 return;
644 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
645 if (!Options.ExactArtifactPath.empty())
646 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
647 WriteToFile(U, Path);
648 Printf("artifact_prefix='%s'; Test unit written to %s\n",
649 Options.ArtifactPrefix.c_str(), Path.c_str());
650 if (U.size() <= kMaxUnitSizeToPrint)
651 Printf("Base64: %s\n", Base64(U).c_str());
652}
653
654void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
655 if (!Options.PrintNEW)
656 return;
657 PrintStats(Text, "");
658 if (Options.Verbosity) {
659 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
Marco Vanottic5d72512021-07-02 16:44:54660 MD.PrintMutationSequence(Options.Verbosity >= 2);
George Karpenkov10ab2ac2017-08-21 23:25:50661 Printf("\n");
662 }
663}
664
665void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
666 II->NumSuccessfullMutations++;
667 MD.RecordSuccessfulMutationSequence();
Alex Shlyapnikov5ded0702017-10-23 23:24:33668 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
George Karpenkov10ab2ac2017-08-21 23:25:50669 WriteToOutputCorpus(U);
670 NumberOfNewUnitsAdded++;
Alex Shlyapnikov5ded0702017-10-23 23:24:33671 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50672 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50673}
674
675// Tries detecting a memory leak on the particular input that we have just
676// executed before calling this function.
677void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
678 bool DuringInitialCorpusExecution) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33679 if (!HasMoreMallocsThanFrees)
680 return; // mallocs==frees, a leak is unlikely.
681 if (!Options.DetectLeaks)
682 return;
Max Moroz3f26dac2017-09-12 02:01:54683 if (!DuringInitialCorpusExecution &&
Alex Shlyapnikov5ded0702017-10-23 23:24:33684 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
685 return;
George Karpenkov10ab2ac2017-08-21 23:25:50686 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
687 !(EF->__lsan_do_recoverable_leak_check))
Alex Shlyapnikov5ded0702017-10-23 23:24:33688 return; // No lsan.
George Karpenkov10ab2ac2017-08-21 23:25:50689 // Run the target once again, but with lsan disabled so that if there is
690 // a real leak we do not report it twice.
691 EF->__lsan_disable();
692 ExecuteCallback(Data, Size);
693 EF->__lsan_enable();
Alex Shlyapnikov5ded0702017-10-23 23:24:33694 if (!HasMoreMallocsThanFrees)
695 return; // a leak is unlikely.
George Karpenkov10ab2ac2017-08-21 23:25:50696 if (NumberOfLeakDetectionAttempts++ > 1000) {
697 Options.DetectLeaks = false;
698 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
699 " Most likely the target function accumulates allocated\n"
700 " memory in a global state w/o actually leaking it.\n"
701 " You may try running this binary with -trace_malloc=[12]"
702 " to get a trace of mallocs and frees.\n"
703 " If LeakSanitizer is enabled in this process it will still\n"
704 " run on the process shutdown.\n");
705 return;
706 }
707 // Now perform the actual lsan pass. This is expensive and we must ensure
708 // we don't call it too often.
709 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
710 if (DuringInitialCorpusExecution)
711 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
712 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
713 CurrentUnitSize = Size;
714 DumpCurrentUnit("leak-");
715 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33716 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
George Karpenkov10ab2ac2017-08-21 23:25:50717 }
718}
719
720void Fuzzer::MutateAndTestOne() {
721 MD.StartMutationSequence();
722
723 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Dokyung Songb53243e2020-09-01 16:22:59724 if (Options.DoCrossOver) {
725 auto &CrossOverII = Corpus.ChooseUnitToCrossOverWith(
726 MD.GetRand(), Options.CrossOverUniformDist);
727 MD.SetCrossOverWith(&CrossOverII.U);
728 }
George Karpenkov10ab2ac2017-08-21 23:25:50729 const auto &U = II.U;
730 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
731 assert(CurrentUnitData);
732 size_t Size = U.size();
733 assert(Size <= MaxInputLen && "Oversized Unit");
734 memcpy(CurrentUnitData, U.data(), Size);
735
736 assert(MaxMutationLen > 0);
737
738 size_t CurrentMaxMutationLen =
739 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
740 assert(CurrentMaxMutationLen > 0);
741
742 for (int i = 0; i < Options.MutateDepth; i++) {
743 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
744 break;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19745 MaybeExitGracefully();
George Karpenkov10ab2ac2017-08-21 23:25:50746 size_t NewSize = 0;
Kostya Serebryany6b87e0c2018-07-19 01:23:32747 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
748 Size <= CurrentMaxMutationLen)
749 NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
750 II.DataFlowTraceForFocusFunction);
Matt Morehouse1b760632019-04-26 00:17:41751
Max Moroz9d5e7ee2019-04-11 16:24:53752 // If MutateWithMask either failed or wasn't called, call default Mutate.
753 if (!NewSize)
Kostya Serebryany6b87e0c2018-07-19 01:23:32754 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50755 assert(NewSize > 0 && "Mutator returned empty unit");
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30756 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
George Karpenkov10ab2ac2017-08-21 23:25:50757 Size = NewSize;
758 II.NumExecutedMutations++;
Matt Morehousee2e38fc2020-05-19 17:28:18759 Corpus.IncrementNumExecutedMutations();
George Karpenkov10ab2ac2017-08-21 23:25:50760
Kostya Serebryanyad05ee02017-12-01 19:18:38761 bool FoundUniqFeatures = false;
762 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
Dokyung Song62673c42020-07-31 00:07:20763 /*ForceAddToCorpus*/ false, &FoundUniqFeatures);
George Karpenkov10ab2ac2017-08-21 23:25:50764 TryDetectingAMemoryLeak(CurrentUnitData, Size,
765 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryanyad05ee02017-12-01 19:18:38766 if (NewCov) {
Matt Morehouse947838c2017-11-09 20:44:08767 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryanyad05ee02017-12-01 19:18:38768 break; // We will mutate this input more in the next rounds.
769 }
770 if (Options.ReduceDepth && !FoundUniqFeatures)
Matt Morehouse34784942019-05-09 22:48:46771 break;
George Karpenkov10ab2ac2017-08-21 23:25:50772 }
Matt Morehousee2e38fc2020-05-19 17:28:18773
774 II.NeedsEnergyUpdate = true;
George Karpenkov10ab2ac2017-08-21 23:25:50775}
776
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30777void Fuzzer::PurgeAllocator() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33778 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30779 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30780 if (duration_cast<seconds>(system_clock::now() -
Alex Shlyapnikov5ded0702017-10-23 23:24:33781 LastAllocatorPurgeAttemptTime)
782 .count() < Options.PurgeAllocatorIntervalSec)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30783 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30784
785 if (Options.RssLimitMb <= 0 ||
Alex Shlyapnikov5ded0702017-10-23 23:24:33786 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30787 EF->__sanitizer_purge_allocator();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30788
789 LastAllocatorPurgeAttemptTime = system_clock::now();
790}
791
Kostya Serebryany7c921752021-08-03 17:04:16792void Fuzzer::ReadAndExecuteSeedCorpora(std::vector<SizedFile> &CorporaFiles) {
Kostya Serebryany3a8e3c82017-08-29 02:05:01793 const size_t kMaxSaneLen = 1 << 20;
794 const size_t kMinDefaultLen = 4096;
Kostya Serebryany4faeb872017-08-29 20:51:24795 size_t MaxSize = 0;
796 size_t MinSize = -1;
797 size_t TotalSize = 0;
Kostya Serebryany4c7353c2019-05-10 01:34:26798 for (auto &File : CorporaFiles) {
Kostya Serebryany93679be2017-09-12 21:58:07799 MaxSize = Max(File.Size, MaxSize);
800 MinSize = Min(File.Size, MinSize);
801 TotalSize += File.Size;
Kostya Serebryany3a8e3c82017-08-29 02:05:01802 }
Kostya Serebryany4faeb872017-08-29 20:51:24803 if (Options.MaxLen == 0)
804 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
805 assert(MaxInputLen > 0);
806
Kostya Serebryany51823d32017-10-13 01:12:23807 // Test the callback with empty input and never try it again.
808 uint8_t dummy = 0;
809 ExecuteCallback(&dummy, 0);
810
Kostya Serebryany4c7353c2019-05-10 01:34:26811 if (CorporaFiles.empty()) {
Kostya Serebryany4faeb872017-08-29 20:51:24812 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
813 Unit U({'\n'}); // Valid ASCII input.
814 RunOne(U.data(), U.size());
815 } else {
816 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
817 " rss: %zdMb\n",
Kostya Serebryany4c7353c2019-05-10 01:34:26818 CorporaFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
Kostya Serebryany4faeb872017-08-29 20:51:24819 if (Options.ShuffleAtStartUp)
Kostya Serebryany4c7353c2019-05-10 01:34:26820 std::shuffle(CorporaFiles.begin(), CorporaFiles.end(), MD.GetRand());
Kostya Serebryany4faeb872017-08-29 20:51:24821
Kostya Serebryany93679be2017-09-12 21:58:07822 if (Options.PreferSmall) {
Kostya Serebryany4c7353c2019-05-10 01:34:26823 std::stable_sort(CorporaFiles.begin(), CorporaFiles.end());
824 assert(CorporaFiles.front().Size <= CorporaFiles.back().Size);
Kostya Serebryany93679be2017-09-12 21:58:07825 }
Kostya Serebryany4faeb872017-08-29 20:51:24826
827 // Load and execute inputs one by one.
Kostya Serebryany4c7353c2019-05-10 01:34:26828 for (auto &SF : CorporaFiles) {
Kostya Serebryany082e9a72017-08-31 19:17:15829 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
Kostya Serebryany4faeb872017-08-29 20:51:24830 assert(U.size() <= MaxInputLen);
Dokyung Song62673c42020-07-31 00:07:20831 RunOne(U.data(), U.size(), /*MayDeleteFile*/ false, /*II*/ nullptr,
832 /*ForceAddToCorpus*/ Options.KeepSeed,
833 /*FoundUniqFeatures*/ nullptr);
Kostya Serebryany4faeb872017-08-29 20:51:24834 CheckExitOnSrcPosOrItem();
835 TryDetectingAMemoryLeak(U.data(), U.size(),
836 /*DuringInitialCorpusExecution*/ true);
837 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01838 }
839
Kostya Serebryany4faeb872017-08-29 20:51:24840 PrintStats("INITED");
Max Moroz07647572020-02-18 17:57:16841 if (!Options.FocusFunction.empty()) {
Kostya Serebryanye9c6f062018-05-16 23:26:37842 Printf("INFO: %zd/%zd inputs touch the focus function\n",
843 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
Max Moroz07647572020-02-18 17:57:16844 if (!Options.DataFlowTrace.empty())
845 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
846 Corpus.NumInputsWithDataFlowTrace(),
847 Corpus.NumInputsThatTouchFocusFunction());
848 }
Kostya Serebryanye9c6f062018-05-16 23:26:37849
Max Morozfe974412018-05-23 19:42:30850 if (Corpus.empty() && Options.MaxNumberOfRuns) {
Kostya Serebryany92fb3102022-06-28 18:36:30851 Printf("WARNING: no interesting inputs were found so far. "
852 "Is the code instrumented for coverage?\n"
853 "This may also happen if the target rejected all inputs we tried so "
854 "far\n");
855 // The remaining logic requires that the corpus is not empty,
856 // so we add one fake input to the in-memory corpus.
857 Corpus.AddToCorpus({'\n'}, /*NumFeatures=*/1, /*MayDeleteFile=*/true,
858 /*HasFocusFunction=*/false, /*NeverReduce=*/false,
859 /*TimeOfUnit=*/duration_cast<microseconds>(0s), {0}, DFT,
860 /*BaseII*/ nullptr);
Kostya Serebryany3a8e3c82017-08-29 02:05:01861 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01862}
863
Kostya Serebryany7c921752021-08-03 17:04:16864void Fuzzer::Loop(std::vector<SizedFile> &CorporaFiles) {
Kostya Serebryany060f4b42019-05-24 00:43:52865 auto FocusFunctionOrAuto = Options.FocusFunction;
866 DFT.Init(Options.DataFlowTrace, &FocusFunctionOrAuto, CorporaFiles,
867 MD.GetRand());
868 TPC.SetFocusFunction(FocusFunctionOrAuto);
Kostya Serebryany4c7353c2019-05-10 01:34:26869 ReadAndExecuteSeedCorpora(CorporaFiles);
Kostya Serebryany67af9922018-06-07 01:40:20870 DFT.Clear(); // No need for DFT any more.
George Karpenkov10ab2ac2017-08-21 23:25:50871 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryany2eef8162017-08-25 20:09:25872 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
George Karpenkov10ab2ac2017-08-21 23:25:50873 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryanyb6ca1e72019-02-16 01:23:41874
875 TmpMaxMutationLen =
876 Min(MaxMutationLen, Max(size_t(4), Corpus.MaxInputSize()));
877
George Karpenkov10ab2ac2017-08-21 23:25:50878 while (true) {
879 auto Now = system_clock::now();
Kostya Serebryanydb88fc52019-06-14 22:56:50880 if (!Options.StopFile.empty() &&
881 !FileToVector(Options.StopFile, 1, false).empty())
882 break;
George Karpenkov10ab2ac2017-08-21 23:25:50883 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
884 Options.ReloadIntervalSec) {
885 RereadOutputCorpus(MaxInputLen);
886 LastCorpusReload = system_clock::now();
887 }
888 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
889 break;
Alex Shlyapnikov5ded0702017-10-23 23:24:33890 if (TimedOut())
891 break;
George Karpenkov10ab2ac2017-08-21 23:25:50892
893 // Update TmpMaxMutationLen
Matt Morehouse36c89b32018-02-13 20:52:15894 if (Options.LenControl) {
George Karpenkov10ab2ac2017-08-21 23:25:50895 if (TmpMaxMutationLen < MaxMutationLen &&
Kostya Serebryanye9ed2322017-12-12 23:11:28896 TotalNumberOfRuns - LastCorpusUpdateRun >
Matt Morehouse36c89b32018-02-13 20:52:15897 Options.LenControl * Log(TmpMaxMutationLen)) {
George Karpenkov10ab2ac2017-08-21 23:25:50898 TmpMaxMutationLen =
Kostya Serebryanye9ed2322017-12-12 23:11:28899 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
Kostya Serebryanye9ed2322017-12-12 23:11:28900 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50901 }
902 } else {
903 TmpMaxMutationLen = MaxMutationLen;
904 }
905
906 // Perform several mutations and runs.
907 MutateAndTestOne();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30908
909 PurgeAllocator();
George Karpenkov10ab2ac2017-08-21 23:25:50910 }
911
912 PrintStats("DONE ", "\n");
Marco Vanottic5d72512021-07-02 16:44:54913 MD.PrintRecommendedDictionary();
George Karpenkov10ab2ac2017-08-21 23:25:50914}
915
916void Fuzzer::MinimizeCrashLoop(const Unit &U) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33917 if (U.size() <= 1)
918 return;
George Karpenkov10ab2ac2017-08-21 23:25:50919 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
920 MD.StartMutationSequence();
921 memcpy(CurrentUnitData, U.data(), U.size());
922 for (int i = 0; i < Options.MutateDepth; i++) {
923 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
924 assert(NewSize > 0 && NewSize <= MaxMutationLen);
925 ExecuteCallback(CurrentUnitData, NewSize);
926 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
927 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
928 /*DuringInitialCorpusExecution*/ false);
929 }
930 }
931}
932
George Karpenkov10ab2ac2017-08-21 23:25:50933} // namespace fuzzer
934
935extern "C" {
936
Jonathan Metzmanb795c312019-01-17 16:36:05937ATTRIBUTE_INTERFACE size_t
Petr Hosekeac2b472018-01-17 20:39:14938LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
George Karpenkov10ab2ac2017-08-21 23:25:50939 assert(fuzzer::F);
940 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
941}
942
Alex Shlyapnikov5ded0702017-10-23 23:24:33943} // extern "C"