blob: d1ad3e37efad8d5e9bde4daa6b27d50b79b4bf7b [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"
15#include "FuzzerRandom.h"
George Karpenkov10ab2ac2017-08-21 23:25:5016#include "FuzzerTracePC.h"
17#include <algorithm>
18#include <cstring>
19#include <memory>
Vitaly Buka7dbc1d82017-11-01 03:02:5920#include <mutex>
George Karpenkov10ab2ac2017-08-21 23:25:5021#include <set>
22
23#if defined(__has_include)
24#if __has_include(<sanitizer / lsan_interface.h>)
25#include <sanitizer/lsan_interface.h>
26#endif
27#endif
28
29#define NO_SANITIZE_MEMORY
30#if defined(__has_feature)
31#if __has_feature(memory_sanitizer)
32#undef NO_SANITIZE_MEMORY
33#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
34#endif
35#endif
36
37namespace fuzzer {
38static const size_t kMaxUnitSizeToPrint = 256;
39
40thread_local bool Fuzzer::IsMyThread;
41
Matt Morehouse43a22962018-07-17 16:12:0042bool RunningUserCallback = false;
43
George Karpenkov10ab2ac2017-08-21 23:25:5044// Only one Fuzzer per process.
45static Fuzzer *F;
46
47// Leak detection is expensive, so we first check if there were more mallocs
48// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
49struct MallocFreeTracer {
50 void Start(int TraceLevel) {
51 this->TraceLevel = TraceLevel;
52 if (TraceLevel)
53 Printf("MallocFreeTracer: START\n");
54 Mallocs = 0;
55 Frees = 0;
56 }
57 // Returns true if there were more mallocs than frees.
58 bool Stop() {
59 if (TraceLevel)
60 Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
61 Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
62 bool Result = Mallocs > Frees;
63 Mallocs = 0;
64 Frees = 0;
65 TraceLevel = 0;
66 return Result;
67 }
68 std::atomic<size_t> Mallocs;
69 std::atomic<size_t> Frees;
70 int TraceLevel = 0;
Vitaly Buka7d223242017-11-02 04:12:1071
72 std::recursive_mutex TraceMutex;
73 bool TraceDisabled = false;
George Karpenkov10ab2ac2017-08-21 23:25:5074};
75
76static MallocFreeTracer AllocTracer;
77
Vitaly Buka7d223242017-11-02 04:12:1078// Locks printing and avoids nested hooks triggered from mallocs/frees in
79// sanitizer.
80class TraceLock {
81public:
82 TraceLock() : Lock(AllocTracer.TraceMutex) {
83 AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
84 }
85 ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
86
87 bool IsDisabled() const {
88 // This is already inverted value.
89 return !AllocTracer.TraceDisabled;
90 }
91
92private:
93 std::lock_guard<std::recursive_mutex> Lock;
94};
Vitaly Buka7dbc1d82017-11-01 03:02:5995
George Karpenkov10ab2ac2017-08-21 23:25:5096ATTRIBUTE_NO_SANITIZE_MEMORY
97void MallocHook(const volatile void *ptr, size_t size) {
98 size_t N = AllocTracer.Mallocs++;
99 F->HandleMalloc(size);
100 if (int TraceLevel = AllocTracer.TraceLevel) {
Vitaly Buka7d223242017-11-02 04:12:10101 TraceLock Lock;
102 if (Lock.IsDisabled())
103 return;
George Karpenkov10ab2ac2017-08-21 23:25:50104 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
105 if (TraceLevel >= 2 && EF)
Matt Morehouse14cf71a2018-05-08 23:45:05106 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50107 }
108}
109
110ATTRIBUTE_NO_SANITIZE_MEMORY
111void FreeHook(const volatile void *ptr) {
112 size_t N = AllocTracer.Frees++;
113 if (int TraceLevel = AllocTracer.TraceLevel) {
Vitaly Buka7d223242017-11-02 04:12:10114 TraceLock Lock;
115 if (Lock.IsDisabled())
116 return;
George Karpenkov10ab2ac2017-08-21 23:25:50117 Printf("FREE[%zd] %p\n", N, ptr);
118 if (TraceLevel >= 2 && EF)
Matt Morehouse14cf71a2018-05-08 23:45:05119 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50120 }
121}
122
123// Crash on a single malloc that exceeds the rss limit.
124void Fuzzer::HandleMalloc(size_t Size) {
Kostya Serebryanyde9bafb2017-12-01 22:12:04125 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
George Karpenkov10ab2ac2017-08-21 23:25:50126 return;
127 Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
128 Size);
129 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Matt Morehouse14cf71a2018-05-08 23:45:05130 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50131 DumpCurrentUnit("oom-");
132 Printf("SUMMARY: libFuzzer: out-of-memory\n");
133 PrintFinalStats();
Kostya Serebryany0fda9dc2019-02-09 00:16:21134 _Exit(Options.OOMExitCode); // Stop right now.
George Karpenkov10ab2ac2017-08-21 23:25:50135}
136
137Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
138 FuzzingOptions Options)
139 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
140 if (EF->__sanitizer_set_death_callback)
141 EF->__sanitizer_set_death_callback(StaticDeathCallback);
142 assert(!F);
143 F = this;
144 TPC.ResetMaps();
145 IsMyThread = true;
146 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
147 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
148 TPC.SetUseCounters(Options.UseCounters);
Kostya Serebryany51ddb882018-07-03 22:33:09149 TPC.SetUseValueProfileMask(Options.UseValueProfile);
George Karpenkov10ab2ac2017-08-21 23:25:50150
151 if (Options.Verbosity)
152 TPC.PrintModuleInfo();
153 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
154 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
155 MaxInputLen = MaxMutationLen = Options.MaxLen;
Kostya Serebryanyb6ca1e72019-02-16 01:23:41156 TmpMaxMutationLen = 0; // Will be set once we load the corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50157 AllocateCurrentUnitData();
158 CurrentUnitSize = 0;
159 memset(BaseSha1, 0, sizeof(BaseSha1));
Kostya Serebryanye9aaa552019-05-09 21:29:45160 auto FocusFunctionOrAuto = Options.FocusFunction;
161 DFT.Init(Options.DataFlowTrace, &FocusFunctionOrAuto , MD.GetRand());
162 TPC.SetFocusFunction(FocusFunctionOrAuto);
George Karpenkov10ab2ac2017-08-21 23:25:50163}
164
Alex Shlyapnikov5ded0702017-10-23 23:24:33165Fuzzer::~Fuzzer() {}
George Karpenkov10ab2ac2017-08-21 23:25:50166
167void Fuzzer::AllocateCurrentUnitData() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33168 if (CurrentUnitData || MaxInputLen == 0)
169 return;
George Karpenkov10ab2ac2017-08-21 23:25:50170 CurrentUnitData = new uint8_t[MaxInputLen];
171}
172
173void Fuzzer::StaticDeathCallback() {
174 assert(F);
175 F->DeathCallback();
176}
177
178void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33179 if (!CurrentUnitData)
180 return; // Happens when running individual inputs.
Matt Morehousea34c65e2018-07-09 23:51:08181 ScopedDisableMsanInterceptorChecks S;
George Karpenkov10ab2ac2017-08-21 23:25:50182 MD.PrintMutationSequence();
183 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
184 size_t UnitSize = CurrentUnitSize;
185 if (UnitSize <= kMaxUnitSizeToPrint) {
186 PrintHexArray(CurrentUnitData, UnitSize, "\n");
187 PrintASCII(CurrentUnitData, UnitSize, "\n");
188 }
189 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
190 Prefix);
191}
192
193NO_SANITIZE_MEMORY
194void Fuzzer::DeathCallback() {
195 DumpCurrentUnit("crash-");
196 PrintFinalStats();
197}
198
199void Fuzzer::StaticAlarmCallback() {
200 assert(F);
201 F->AlarmCallback();
202}
203
204void Fuzzer::StaticCrashSignalCallback() {
205 assert(F);
206 F->CrashCallback();
207}
208
George Karpenkov10ab2ac2017-08-21 23:25:50209void Fuzzer::StaticExitCallback() {
210 assert(F);
211 F->ExitCallback();
212}
213
214void Fuzzer::StaticInterruptCallback() {
215 assert(F);
216 F->InterruptCallback();
217}
218
Kostya Serebryanya2ca2dc2017-11-09 20:30:19219void Fuzzer::StaticGracefulExitCallback() {
220 assert(F);
221 F->GracefulExitRequested = true;
222 Printf("INFO: signal received, trying to exit gracefully\n");
223}
224
George Karpenkov10ab2ac2017-08-21 23:25:50225void Fuzzer::StaticFileSizeExceedCallback() {
226 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
227 exit(1);
228}
229
230void Fuzzer::CrashCallback() {
Julian Lettner15df2732019-01-31 01:24:01231 if (EF->__sanitizer_acquire_crash_state &&
232 !EF->__sanitizer_acquire_crash_state())
233 return;
George Karpenkov10ab2ac2017-08-21 23:25:50234 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
Matt Morehouse14cf71a2018-05-08 23:45:05235 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50236 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
237 " Combine libFuzzer with AddressSanitizer or similar for better "
238 "crash reports.\n");
239 Printf("SUMMARY: libFuzzer: deadly signal\n");
240 DumpCurrentUnit("crash-");
241 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33242 _Exit(Options.ErrorExitCode); // Stop right now.
George Karpenkov10ab2ac2017-08-21 23:25:50243}
244
245void Fuzzer::ExitCallback() {
Matt Morehouse43a22962018-07-17 16:12:00246 if (!RunningUserCallback)
George Karpenkov10ab2ac2017-08-21 23:25:50247 return; // This exit did not come from the user callback
Matt Morehouse52fd1692018-05-01 21:01:53248 if (EF->__sanitizer_acquire_crash_state &&
249 !EF->__sanitizer_acquire_crash_state())
250 return;
George Karpenkov10ab2ac2017-08-21 23:25:50251 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
Matt Morehouse14cf71a2018-05-08 23:45:05252 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50253 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
254 DumpCurrentUnit("crash-");
255 PrintFinalStats();
256 _Exit(Options.ErrorExitCode);
257}
258
Kostya Serebryanya2ca2dc2017-11-09 20:30:19259void Fuzzer::MaybeExitGracefully() {
Kostya Serebryanyf762a112019-02-08 21:27:23260 if (!F->GracefulExitRequested) return;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19261 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
Kostya Serebryany312af152019-02-16 00:14:16262 RmDirRecursive(TempPath(".dir"));
Kostya Serebryanyf762a112019-02-08 21:27:23263 F->PrintFinalStats();
Kostya Serebryanya2ca2dc2017-11-09 20:30:19264 _Exit(0);
265}
266
George Karpenkov10ab2ac2017-08-21 23:25:50267void Fuzzer::InterruptCallback() {
268 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
269 PrintFinalStats();
Matt Morehouse1b760632019-04-26 00:17:41270 ScopedDisableMsanInterceptorChecks S; // RmDirRecursive may call opendir().
Kostya Serebryany312af152019-02-16 00:14:16271 RmDirRecursive(TempPath(".dir"));
Kostya Serebryany0fda9dc2019-02-09 00:16:21272 // Stop right now, don't perform any at-exit actions.
273 _Exit(Options.InterruptExitCode);
George Karpenkov10ab2ac2017-08-21 23:25:50274}
275
276NO_SANITIZE_MEMORY
277void Fuzzer::AlarmCallback() {
278 assert(Options.UnitTimeoutSec > 0);
279 // In Windows Alarm callback is executed by a different thread.
Kamil Rytarowski2e611862018-11-06 01:28:01280 // NetBSD's current behavior needs this change too.
281#if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD
Alex Shlyapnikov5ded0702017-10-23 23:24:33282 if (!InFuzzingThread())
283 return;
George Karpenkov10ab2ac2017-08-21 23:25:50284#endif
Matt Morehouse43a22962018-07-17 16:12:00285 if (!RunningUserCallback)
George Karpenkov10ab2ac2017-08-21 23:25:50286 return; // We have not started running units yet.
287 size_t Seconds =
288 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
289 if (Seconds == 0)
290 return;
291 if (Options.Verbosity >= 2)
292 Printf("AlarmCallback %zd\n", Seconds);
293 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Matt Morehouse52fd1692018-05-01 21:01:53294 if (EF->__sanitizer_acquire_crash_state &&
295 !EF->__sanitizer_acquire_crash_state())
296 return;
George Karpenkov10ab2ac2017-08-21 23:25:50297 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
298 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
299 Options.UnitTimeoutSec);
300 DumpCurrentUnit("timeout-");
301 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
302 Seconds);
Matt Morehouse14cf71a2018-05-08 23:45:05303 PrintStackTrace();
George Karpenkov10ab2ac2017-08-21 23:25:50304 Printf("SUMMARY: libFuzzer: timeout\n");
305 PrintFinalStats();
306 _Exit(Options.TimeoutExitCode); // Stop right now.
307 }
308}
309
310void Fuzzer::RssLimitCallback() {
Matt Morehouse52fd1692018-05-01 21:01:53311 if (EF->__sanitizer_acquire_crash_state &&
312 !EF->__sanitizer_acquire_crash_state())
313 return;
George Karpenkov10ab2ac2017-08-21 23:25:50314 Printf(
315 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
316 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
317 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
Matt Morehouse14cf71a2018-05-08 23:45:05318 PrintMemoryProfile();
George Karpenkov10ab2ac2017-08-21 23:25:50319 DumpCurrentUnit("oom-");
320 Printf("SUMMARY: libFuzzer: out-of-memory\n");
321 PrintFinalStats();
Kostya Serebryany0fda9dc2019-02-09 00:16:21322 _Exit(Options.OOMExitCode); // Stop right now.
George Karpenkov10ab2ac2017-08-21 23:25:50323}
324
325void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
326 size_t ExecPerSec = execPerSec();
327 if (!Options.Verbosity)
328 return;
329 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
330 if (size_t N = TPC.GetTotalPCCoverage())
331 Printf(" cov: %zd", N);
332 if (size_t N = Corpus.NumFeatures())
Alex Shlyapnikov5ded0702017-10-23 23:24:33333 Printf(" ft: %zd", N);
George Karpenkov10ab2ac2017-08-21 23:25:50334 if (!Corpus.empty()) {
335 Printf(" corp: %zd", Corpus.NumActiveUnits());
336 if (size_t N = Corpus.SizeInBytes()) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33337 if (N < (1 << 14))
George Karpenkov10ab2ac2017-08-21 23:25:50338 Printf("/%zdb", N);
339 else if (N < (1 << 24))
340 Printf("/%zdKb", N >> 10);
341 else
342 Printf("/%zdMb", N >> 20);
343 }
Kostya Serebryanye9c6f062018-05-16 23:26:37344 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
345 Printf(" focus: %zd", FF);
George Karpenkov10ab2ac2017-08-21 23:25:50346 }
Matt Morehouseddf352b2018-02-22 19:00:17347 if (TmpMaxMutationLen)
348 Printf(" lim: %zd", TmpMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50349 if (Units)
350 Printf(" units: %zd", Units);
351
352 Printf(" exec/s: %zd", ExecPerSec);
353 Printf(" rss: %zdMb", GetPeakRSSMb());
354 Printf("%s", End);
355}
356
357void Fuzzer::PrintFinalStats() {
358 if (Options.PrintCoverage)
359 TPC.PrintCoverage();
George Karpenkov10ab2ac2017-08-21 23:25:50360 if (Options.PrintCorpusStats)
361 Corpus.PrintStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33362 if (!Options.PrintFinalStats)
363 return;
George Karpenkov10ab2ac2017-08-21 23:25:50364 size_t ExecPerSec = execPerSec();
365 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
366 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
367 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
368 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
369 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
370}
371
372void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
373 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
374 assert(MaxInputLen);
375 this->MaxInputLen = MaxInputLen;
376 this->MaxMutationLen = MaxInputLen;
377 AllocateCurrentUnitData();
378 Printf("INFO: -max_len is not provided; "
379 "libFuzzer will not generate inputs larger than %zd bytes\n",
380 MaxInputLen);
381}
382
383void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
384 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
385 this->MaxMutationLen = MaxMutationLen;
386}
387
388void Fuzzer::CheckExitOnSrcPosOrItem() {
389 if (!Options.ExitOnSrcPos.empty()) {
George Karpenkovbebcbfb2017-08-27 23:20:09390 static auto *PCsSet = new Set<uintptr_t>;
Kostya Serebryany96f81bc2019-02-14 23:12:33391 auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
392 if (!PCsSet->insert(TE->PC).second)
Alex Shlyapnikov5ded0702017-10-23 23:24:33393 return;
Kostya Serebryany96f81bc2019-02-14 23:12:33394 std::string Descr = DescribePC("%F %L", TE->PC + 1);
George Karpenkov10ab2ac2017-08-21 23:25:50395 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
396 Printf("INFO: found line matching '%s', exiting.\n",
397 Options.ExitOnSrcPos.c_str());
398 _Exit(0);
399 }
400 };
401 TPC.ForEachObservedPC(HandlePC);
402 }
403 if (!Options.ExitOnItem.empty()) {
404 if (Corpus.HasUnit(Options.ExitOnItem)) {
405 Printf("INFO: found item with checksum '%s', exiting.\n",
406 Options.ExitOnItem.c_str());
407 _Exit(0);
408 }
409 }
410}
411
412void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33413 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
414 return;
George Karpenkovbebcbfb2017-08-27 23:20:09415 Vector<Unit> AdditionalCorpus;
George Karpenkov10ab2ac2017-08-21 23:25:50416 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
417 &EpochOfLastReadOfOutputCorpus, MaxSize,
418 /*ExitOnError*/ false);
419 if (Options.Verbosity >= 2)
420 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
421 bool Reloaded = false;
422 for (auto &U : AdditionalCorpus) {
423 if (U.size() > MaxSize)
424 U.resize(MaxSize);
425 if (!Corpus.HasUnit(U)) {
426 if (RunOne(U.data(), U.size())) {
427 CheckExitOnSrcPosOrItem();
428 Reloaded = true;
429 }
430 }
431 }
432 if (Reloaded)
433 PrintStats("RELOAD");
434}
435
George Karpenkov10ab2ac2017-08-21 23:25:50436void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
437 auto TimeOfUnit =
438 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
439 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
440 secondsSinceProcessStartUp() >= 2)
441 PrintStats("pulse ");
442 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
443 TimeOfUnit >= Options.ReportSlowUnits) {
444 TimeOfLongestUnitInSeconds = TimeOfUnit;
445 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
446 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
447 }
448}
449
Kostya Serebryany4614cc32019-04-13 00:20:31450static void WriteFeatureSetToFile(const std::string &FeaturesDir,
Kostya Serebryany5e67abd2019-04-13 01:57:33451 const std::string &FileName,
Kostya Serebryany4614cc32019-04-13 00:20:31452 const Vector<uint32_t> &FeatureSet) {
453 if (FeaturesDir.empty() || FeatureSet.empty()) return;
454 WriteToFile(reinterpret_cast<const uint8_t *>(FeatureSet.data()),
455 FeatureSet.size() * sizeof(FeatureSet[0]),
Kostya Serebryany5e67abd2019-04-13 01:57:33456 DirPlusFile(FeaturesDir, FileName));
Kostya Serebryany4614cc32019-04-13 00:20:31457}
458
459static void RenameFeatureSetFile(const std::string &FeaturesDir,
460 const std::string &OldFile,
461 const std::string &NewFile) {
462 if (FeaturesDir.empty()) return;
463 RenameFile(DirPlusFile(FeaturesDir, OldFile),
464 DirPlusFile(FeaturesDir, NewFile));
465}
466
George Karpenkov10ab2ac2017-08-21 23:25:50467bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
Kostya Serebryanyad05ee02017-12-01 19:18:38468 InputInfo *II, bool *FoundUniqFeatures) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33469 if (!Size)
470 return false;
George Karpenkov10ab2ac2017-08-21 23:25:50471
472 ExecuteCallback(Data, Size);
473
474 UniqFeatureSetTmp.clear();
475 size_t FoundUniqFeaturesOfII = 0;
476 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
477 TPC.CollectFeatures([&](size_t Feature) {
George Karpenkov10ab2ac2017-08-21 23:25:50478 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
479 UniqFeatureSetTmp.push_back(Feature);
480 if (Options.ReduceInputs && II)
481 if (std::binary_search(II->UniqFeatureSet.begin(),
482 II->UniqFeatureSet.end(), Feature))
483 FoundUniqFeaturesOfII++;
484 });
Kostya Serebryanyad05ee02017-12-01 19:18:38485 if (FoundUniqFeatures)
486 *FoundUniqFeatures = FoundUniqFeaturesOfII;
George Karpenkov10ab2ac2017-08-21 23:25:50487 PrintPulseAndReportSlowInput(Data, Size);
488 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
489 if (NumNewFeatures) {
490 TPC.UpdateObservedPCs();
Kostya Serebryany4614cc32019-04-13 00:20:31491 auto NewII = Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures,
492 MayDeleteFile, TPC.ObservedFocusFunction(),
493 UniqFeatureSetTmp, DFT, II);
Kostya Serebryany5e67abd2019-04-13 01:57:33494 WriteFeatureSetToFile(Options.FeaturesDir, Sha1ToString(NewII->Sha1),
Kostya Serebryany4614cc32019-04-13 00:20:31495 NewII->UniqFeatureSet);
George Karpenkov10ab2ac2017-08-21 23:25:50496 return true;
497 }
498 if (II && FoundUniqFeaturesOfII &&
Kostya Serebryany67af9922018-06-07 01:40:20499 II->DataFlowTraceForFocusFunction.empty() &&
George Karpenkov10ab2ac2017-08-21 23:25:50500 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
501 II->U.size() > Size) {
Kostya Serebryany4614cc32019-04-13 00:20:31502 auto OldFeaturesFile = Sha1ToString(II->Sha1);
George Karpenkov10ab2ac2017-08-21 23:25:50503 Corpus.Replace(II, {Data, Data + Size});
Kostya Serebryany4614cc32019-04-13 00:20:31504 RenameFeatureSetFile(Options.FeaturesDir, OldFeaturesFile,
505 Sha1ToString(II->Sha1));
George Karpenkov10ab2ac2017-08-21 23:25:50506 return true;
507 }
508 return false;
509}
510
511size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
512 assert(InFuzzingThread());
513 *Data = CurrentUnitData;
514 return CurrentUnitSize;
515}
516
517void Fuzzer::CrashOnOverwrittenData() {
518 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
519 GetPid());
520 DumpCurrentUnit("crash-");
521 Printf("SUMMARY: libFuzzer: out-of-memory\n");
522 _Exit(Options.ErrorExitCode); // Stop right now.
523}
524
525// Compare two arrays, but not all bytes if the arrays are large.
526static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
527 const size_t Limit = 64;
528 if (Size <= 64)
529 return !memcmp(A, B, Size);
530 // Compare first and last Limit/2 bytes.
531 return !memcmp(A, B, Limit / 2) &&
532 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
533}
534
535void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
536 TPC.RecordInitialStack();
537 TotalNumberOfRuns++;
538 assert(InFuzzingThread());
George Karpenkov10ab2ac2017-08-21 23:25:50539 // We copy the contents of Unit into a separate heap buffer
540 // so that we reliably find buffer overflows in it.
541 uint8_t *DataCopy = new uint8_t[Size];
542 memcpy(DataCopy, Data, Size);
Matt Morehousea34c65e2018-07-09 23:51:08543 if (EF->__msan_unpoison)
544 EF->__msan_unpoison(DataCopy, Size);
George Karpenkov10ab2ac2017-08-21 23:25:50545 if (CurrentUnitData && CurrentUnitData != Data)
546 memcpy(CurrentUnitData, Data, Size);
547 CurrentUnitSize = Size;
Matt Morehousea34c65e2018-07-09 23:51:08548 {
549 ScopedEnableMsanInterceptorChecks S;
550 AllocTracer.Start(Options.TraceMalloc);
551 UnitStartTime = system_clock::now();
552 TPC.ResetMaps();
Matt Morehouse43a22962018-07-17 16:12:00553 RunningUserCallback = true;
Matt Morehousea34c65e2018-07-09 23:51:08554 int Res = CB(DataCopy, Size);
Matt Morehouse43a22962018-07-17 16:12:00555 RunningUserCallback = false;
Matt Morehousea34c65e2018-07-09 23:51:08556 UnitStopTime = system_clock::now();
557 (void)Res;
558 assert(Res == 0);
559 HasMoreMallocsThanFrees = AllocTracer.Stop();
560 }
George Karpenkov10ab2ac2017-08-21 23:25:50561 if (!LooseMemeq(DataCopy, Data, Size))
562 CrashOnOverwrittenData();
563 CurrentUnitSize = 0;
564 delete[] DataCopy;
565}
566
Kostya Serebryany63f48712019-02-12 00:12:33567std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
George Karpenkov10ab2ac2017-08-21 23:25:50568 if (Options.OnlyASCII)
569 assert(IsASCII(U));
570 if (Options.OutputCorpus.empty())
Kostya Serebryany63f48712019-02-12 00:12:33571 return "";
George Karpenkov10ab2ac2017-08-21 23:25:50572 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
573 WriteToFile(U, Path);
574 if (Options.Verbosity >= 2)
575 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
Kostya Serebryany63f48712019-02-12 00:12:33576 return Path;
George Karpenkov10ab2ac2017-08-21 23:25:50577}
578
579void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
580 if (!Options.SaveArtifacts)
581 return;
582 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
583 if (!Options.ExactArtifactPath.empty())
584 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
585 WriteToFile(U, Path);
586 Printf("artifact_prefix='%s'; Test unit written to %s\n",
587 Options.ArtifactPrefix.c_str(), Path.c_str());
588 if (U.size() <= kMaxUnitSizeToPrint)
589 Printf("Base64: %s\n", Base64(U).c_str());
590}
591
592void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
593 if (!Options.PrintNEW)
594 return;
595 PrintStats(Text, "");
596 if (Options.Verbosity) {
597 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
598 MD.PrintMutationSequence();
599 Printf("\n");
600 }
601}
602
603void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
604 II->NumSuccessfullMutations++;
605 MD.RecordSuccessfulMutationSequence();
Alex Shlyapnikov5ded0702017-10-23 23:24:33606 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
George Karpenkov10ab2ac2017-08-21 23:25:50607 WriteToOutputCorpus(U);
608 NumberOfNewUnitsAdded++;
Alex Shlyapnikov5ded0702017-10-23 23:24:33609 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
George Karpenkov10ab2ac2017-08-21 23:25:50610 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50611}
612
613// Tries detecting a memory leak on the particular input that we have just
614// executed before calling this function.
615void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
616 bool DuringInitialCorpusExecution) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33617 if (!HasMoreMallocsThanFrees)
618 return; // mallocs==frees, a leak is unlikely.
619 if (!Options.DetectLeaks)
620 return;
Max Moroz3f26dac2017-09-12 02:01:54621 if (!DuringInitialCorpusExecution &&
Alex Shlyapnikov5ded0702017-10-23 23:24:33622 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
623 return;
George Karpenkov10ab2ac2017-08-21 23:25:50624 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
625 !(EF->__lsan_do_recoverable_leak_check))
Alex Shlyapnikov5ded0702017-10-23 23:24:33626 return; // No lsan.
George Karpenkov10ab2ac2017-08-21 23:25:50627 // Run the target once again, but with lsan disabled so that if there is
628 // a real leak we do not report it twice.
629 EF->__lsan_disable();
630 ExecuteCallback(Data, Size);
631 EF->__lsan_enable();
Alex Shlyapnikov5ded0702017-10-23 23:24:33632 if (!HasMoreMallocsThanFrees)
633 return; // a leak is unlikely.
George Karpenkov10ab2ac2017-08-21 23:25:50634 if (NumberOfLeakDetectionAttempts++ > 1000) {
635 Options.DetectLeaks = false;
636 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
637 " Most likely the target function accumulates allocated\n"
638 " memory in a global state w/o actually leaking it.\n"
639 " You may try running this binary with -trace_malloc=[12]"
640 " to get a trace of mallocs and frees.\n"
641 " If LeakSanitizer is enabled in this process it will still\n"
642 " run on the process shutdown.\n");
643 return;
644 }
645 // Now perform the actual lsan pass. This is expensive and we must ensure
646 // we don't call it too often.
647 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
648 if (DuringInitialCorpusExecution)
649 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
650 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
651 CurrentUnitSize = Size;
652 DumpCurrentUnit("leak-");
653 PrintFinalStats();
Alex Shlyapnikov5ded0702017-10-23 23:24:33654 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
George Karpenkov10ab2ac2017-08-21 23:25:50655 }
656}
657
658void Fuzzer::MutateAndTestOne() {
659 MD.StartMutationSequence();
660
661 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
Kostya Serebryany0719b352019-02-08 01:20:54662 if (Options.DoCrossOver)
663 MD.SetCrossOverWith(&Corpus.ChooseUnitToMutate(MD.GetRand()).U);
George Karpenkov10ab2ac2017-08-21 23:25:50664 const auto &U = II.U;
665 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
666 assert(CurrentUnitData);
667 size_t Size = U.size();
668 assert(Size <= MaxInputLen && "Oversized Unit");
669 memcpy(CurrentUnitData, U.data(), Size);
670
671 assert(MaxMutationLen > 0);
672
673 size_t CurrentMaxMutationLen =
674 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
675 assert(CurrentMaxMutationLen > 0);
676
677 for (int i = 0; i < Options.MutateDepth; i++) {
678 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
679 break;
Kostya Serebryanya2ca2dc2017-11-09 20:30:19680 MaybeExitGracefully();
George Karpenkov10ab2ac2017-08-21 23:25:50681 size_t NewSize = 0;
Kostya Serebryany6b87e0c2018-07-19 01:23:32682 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
683 Size <= CurrentMaxMutationLen)
684 NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
685 II.DataFlowTraceForFocusFunction);
Matt Morehouse1b760632019-04-26 00:17:41686
Max Moroz9d5e7ee2019-04-11 16:24:53687 // If MutateWithMask either failed or wasn't called, call default Mutate.
688 if (!NewSize)
Kostya Serebryany6b87e0c2018-07-19 01:23:32689 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
George Karpenkov10ab2ac2017-08-21 23:25:50690 assert(NewSize > 0 && "Mutator returned empty unit");
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30691 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
George Karpenkov10ab2ac2017-08-21 23:25:50692 Size = NewSize;
693 II.NumExecutedMutations++;
George Karpenkov10ab2ac2017-08-21 23:25:50694
Kostya Serebryanyad05ee02017-12-01 19:18:38695 bool FoundUniqFeatures = false;
696 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
697 &FoundUniqFeatures);
George Karpenkov10ab2ac2017-08-21 23:25:50698 TryDetectingAMemoryLeak(CurrentUnitData, Size,
699 /*DuringInitialCorpusExecution*/ false);
Kostya Serebryanyad05ee02017-12-01 19:18:38700 if (NewCov) {
Matt Morehouse947838c2017-11-09 20:44:08701 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
Kostya Serebryanyad05ee02017-12-01 19:18:38702 break; // We will mutate this input more in the next rounds.
703 }
704 if (Options.ReduceDepth && !FoundUniqFeatures)
Max Moroz1d369a52018-07-16 15:15:34705 break;
George Karpenkov10ab2ac2017-08-21 23:25:50706 }
707}
708
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30709void Fuzzer::PurgeAllocator() {
Alex Shlyapnikov5ded0702017-10-23 23:24:33710 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30711 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30712 if (duration_cast<seconds>(system_clock::now() -
Alex Shlyapnikov5ded0702017-10-23 23:24:33713 LastAllocatorPurgeAttemptTime)
714 .count() < Options.PurgeAllocatorIntervalSec)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30715 return;
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30716
717 if (Options.RssLimitMb <= 0 ||
Alex Shlyapnikov5ded0702017-10-23 23:24:33718 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30719 EF->__sanitizer_purge_allocator();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30720
721 LastAllocatorPurgeAttemptTime = system_clock::now();
722}
723
Kostya Serebryany0719b352019-02-08 01:20:54724void Fuzzer::ReadAndExecuteSeedCorpora(
725 const Vector<std::string> &CorpusDirs,
726 const Vector<std::string> &ExtraSeedFiles) {
Kostya Serebryany3a8e3c82017-08-29 02:05:01727 const size_t kMaxSaneLen = 1 << 20;
728 const size_t kMinDefaultLen = 4096;
Kostya Serebryany4faeb872017-08-29 20:51:24729 Vector<SizedFile> SizedFiles;
730 size_t MaxSize = 0;
731 size_t MinSize = -1;
732 size_t TotalSize = 0;
Kostya Serebryany93679be2017-09-12 21:58:07733 size_t LastNumFiles = 0;
Kostya Serebryany4faeb872017-08-29 20:51:24734 for (auto &Dir : CorpusDirs) {
Kostya Serebryany93679be2017-09-12 21:58:07735 GetSizedFilesFromDir(Dir, &SizedFiles);
736 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
737 Dir.c_str());
738 LastNumFiles = SizedFiles.size();
739 }
Kostya Serebryany0719b352019-02-08 01:20:54740 // Add files from -seed_inputs.
741 for (auto &File : ExtraSeedFiles)
742 if (auto Size = FileSize(File))
743 SizedFiles.push_back({File, Size});
744
Kostya Serebryany93679be2017-09-12 21:58:07745 for (auto &File : SizedFiles) {
746 MaxSize = Max(File.Size, MaxSize);
747 MinSize = Min(File.Size, MinSize);
748 TotalSize += File.Size;
Kostya Serebryany3a8e3c82017-08-29 02:05:01749 }
Kostya Serebryany4faeb872017-08-29 20:51:24750 if (Options.MaxLen == 0)
751 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
752 assert(MaxInputLen > 0);
753
Kostya Serebryany51823d32017-10-13 01:12:23754 // Test the callback with empty input and never try it again.
755 uint8_t dummy = 0;
756 ExecuteCallback(&dummy, 0);
757
Kostya Serebryany23482e12019-01-31 01:40:14758 // Protect lazy counters here, after the once-init code has been executed.
759 if (Options.LazyCounters)
760 TPC.ProtectLazyCounters();
761
Kostya Serebryany4faeb872017-08-29 20:51:24762 if (SizedFiles.empty()) {
763 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
764 Unit U({'\n'}); // Valid ASCII input.
765 RunOne(U.data(), U.size());
766 } else {
767 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
768 " rss: %zdMb\n",
769 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
770 if (Options.ShuffleAtStartUp)
771 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
772
Kostya Serebryany93679be2017-09-12 21:58:07773 if (Options.PreferSmall) {
774 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
775 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
776 }
Kostya Serebryany4faeb872017-08-29 20:51:24777
778 // Load and execute inputs one by one.
779 for (auto &SF : SizedFiles) {
Kostya Serebryany082e9a72017-08-31 19:17:15780 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
Kostya Serebryany4faeb872017-08-29 20:51:24781 assert(U.size() <= MaxInputLen);
782 RunOne(U.data(), U.size());
783 CheckExitOnSrcPosOrItem();
784 TryDetectingAMemoryLeak(U.data(), U.size(),
785 /*DuringInitialCorpusExecution*/ true);
786 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01787 }
788
Kostya Serebryany4faeb872017-08-29 20:51:24789 PrintStats("INITED");
Kostya Serebryanye9c6f062018-05-16 23:26:37790 if (!Options.FocusFunction.empty())
791 Printf("INFO: %zd/%zd inputs touch the focus function\n",
792 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
Kostya Serebryany67af9922018-06-07 01:40:20793 if (!Options.DataFlowTrace.empty())
794 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
795 Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
Kostya Serebryanye9c6f062018-05-16 23:26:37796
Max Morozfe974412018-05-23 19:42:30797 if (Corpus.empty() && Options.MaxNumberOfRuns) {
Kostya Serebryany4faeb872017-08-29 20:51:24798 Printf("ERROR: no interesting inputs were found. "
799 "Is the code instrumented for coverage? Exiting.\n");
800 exit(1);
Kostya Serebryany3a8e3c82017-08-29 02:05:01801 }
Kostya Serebryany3a8e3c82017-08-29 02:05:01802}
803
Kostya Serebryany0719b352019-02-08 01:20:54804void Fuzzer::Loop(const Vector<std::string> &CorpusDirs,
805 const Vector<std::string> &ExtraSeedFiles) {
806 ReadAndExecuteSeedCorpora(CorpusDirs, ExtraSeedFiles);
Kostya Serebryany67af9922018-06-07 01:40:20807 DFT.Clear(); // No need for DFT any more.
George Karpenkov10ab2ac2017-08-21 23:25:50808 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
Kostya Serebryany2eef8162017-08-25 20:09:25809 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
George Karpenkov10ab2ac2017-08-21 23:25:50810 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryanyb6ca1e72019-02-16 01:23:41811
812 TmpMaxMutationLen =
813 Min(MaxMutationLen, Max(size_t(4), Corpus.MaxInputSize()));
814
George Karpenkov10ab2ac2017-08-21 23:25:50815 while (true) {
816 auto Now = system_clock::now();
817 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
818 Options.ReloadIntervalSec) {
819 RereadOutputCorpus(MaxInputLen);
820 LastCorpusReload = system_clock::now();
821 }
822 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
823 break;
Alex Shlyapnikov5ded0702017-10-23 23:24:33824 if (TimedOut())
825 break;
George Karpenkov10ab2ac2017-08-21 23:25:50826
827 // Update TmpMaxMutationLen
Matt Morehouse36c89b32018-02-13 20:52:15828 if (Options.LenControl) {
George Karpenkov10ab2ac2017-08-21 23:25:50829 if (TmpMaxMutationLen < MaxMutationLen &&
Kostya Serebryanye9ed2322017-12-12 23:11:28830 TotalNumberOfRuns - LastCorpusUpdateRun >
Matt Morehouse36c89b32018-02-13 20:52:15831 Options.LenControl * Log(TmpMaxMutationLen)) {
George Karpenkov10ab2ac2017-08-21 23:25:50832 TmpMaxMutationLen =
Kostya Serebryanye9ed2322017-12-12 23:11:28833 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
Kostya Serebryanye9ed2322017-12-12 23:11:28834 LastCorpusUpdateRun = TotalNumberOfRuns;
George Karpenkov10ab2ac2017-08-21 23:25:50835 }
836 } else {
837 TmpMaxMutationLen = MaxMutationLen;
838 }
839
840 // Perform several mutations and runs.
841 MutateAndTestOne();
Alex Shlyapnikov6f1c26f2017-10-23 22:04:30842
843 PurgeAllocator();
George Karpenkov10ab2ac2017-08-21 23:25:50844 }
845
846 PrintStats("DONE ", "\n");
847 MD.PrintRecommendedDictionary();
848}
849
850void Fuzzer::MinimizeCrashLoop(const Unit &U) {
Alex Shlyapnikov5ded0702017-10-23 23:24:33851 if (U.size() <= 1)
852 return;
George Karpenkov10ab2ac2017-08-21 23:25:50853 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
854 MD.StartMutationSequence();
855 memcpy(CurrentUnitData, U.data(), U.size());
856 for (int i = 0; i < Options.MutateDepth; i++) {
857 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
858 assert(NewSize > 0 && NewSize <= MaxMutationLen);
859 ExecuteCallback(CurrentUnitData, NewSize);
860 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
861 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
862 /*DuringInitialCorpusExecution*/ false);
863 }
864 }
865}
866
George Karpenkov10ab2ac2017-08-21 23:25:50867} // namespace fuzzer
868
869extern "C" {
870
Jonathan Metzmanb795c312019-01-17 16:36:05871ATTRIBUTE_INTERFACE size_t
Petr Hosekeac2b472018-01-17 20:39:14872LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
George Karpenkov10ab2ac2017-08-21 23:25:50873 assert(fuzzer::F);
874 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
875}
876
Alex Shlyapnikov5ded0702017-10-23 23:24:33877} // extern "C"