blob: 959d5a2355980531e29db80742aa046750e3dc84 [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +00001//===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
2//
chandlerc40284492019-01-19 08:50:56 +00003// 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.karpenkov29efa6d2017-08-21 23:25:50 +00006//
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.karpenkov29efa6d2017-08-21 23:25:50 +000016#include "FuzzerTracePC.h"
17#include <algorithm>
18#include <cstring>
19#include <memory>
vitalybukab3e5a2c2017-11-01 03:02:59 +000020#include <mutex>
george.karpenkov29efa6d2017-08-21 23:25:50 +000021#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
morehousec6ee8752018-07-17 16:12:00 +000042bool RunningUserCallback = false;
43
george.karpenkov29efa6d2017-08-21 23:25:50 +000044// 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;
vitalybukae6504cf2017-11-02 04:12:10 +000071
72 std::recursive_mutex TraceMutex;
73 bool TraceDisabled = false;
george.karpenkov29efa6d2017-08-21 23:25:50 +000074};
75
76static MallocFreeTracer AllocTracer;
77
vitalybukae6504cf2017-11-02 04:12:10 +000078// 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};
vitalybukab3e5a2c2017-11-01 03:02:59 +000095
george.karpenkov29efa6d2017-08-21 23:25:50 +000096ATTRIBUTE_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) {
vitalybukae6504cf2017-11-02 04:12:10 +0000101 TraceLock Lock;
102 if (Lock.IsDisabled())
103 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000104 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
105 if (TraceLevel >= 2 && EF)
morehousebd67cc22018-05-08 23:45:05 +0000106 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000107 }
108}
109
110ATTRIBUTE_NO_SANITIZE_MEMORY
111void FreeHook(const volatile void *ptr) {
112 size_t N = AllocTracer.Frees++;
113 if (int TraceLevel = AllocTracer.TraceLevel) {
vitalybukae6504cf2017-11-02 04:12:10 +0000114 TraceLock Lock;
115 if (Lock.IsDisabled())
116 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000117 Printf("FREE[%zd] %p\n", N, ptr);
118 if (TraceLevel >= 2 && EF)
morehousebd67cc22018-05-08 23:45:05 +0000119 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000120 }
121}
122
123// Crash on a single malloc that exceeds the rss limit.
124void Fuzzer::HandleMalloc(size_t Size) {
kcc120e40b2017-12-01 22:12:04 +0000125 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000126 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");
morehousebd67cc22018-05-08 23:45:05 +0000130 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000131 DumpCurrentUnit("oom-");
132 Printf("SUMMARY: libFuzzer: out-of-memory\n");
133 PrintFinalStats();
134 _Exit(Options.ErrorExitCode); // Stop right now.
135}
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);
kcc3850d062018-07-03 22:33:09 +0000149 TPC.SetUseValueProfileMask(Options.UseValueProfile);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000150
151 if (Options.Verbosity)
152 TPC.PrintModuleInfo();
153 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
154 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
155 MaxInputLen = MaxMutationLen = Options.MaxLen;
156 TmpMaxMutationLen = Max(size_t(4), Corpus.MaxInputSize());
157 AllocateCurrentUnitData();
158 CurrentUnitSize = 0;
159 memset(BaseSha1, 0, sizeof(BaseSha1));
kcc3acbe072018-05-16 23:26:37 +0000160 TPC.SetFocusFunction(Options.FocusFunction);
kcc86e43882018-06-06 01:23:29 +0000161 DFT.Init(Options.DataFlowTrace, Options.FocusFunction);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000162}
163
alekseyshl9f6a9f22017-10-23 23:24:33 +0000164Fuzzer::~Fuzzer() {}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000165
166void Fuzzer::AllocateCurrentUnitData() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000167 if (CurrentUnitData || MaxInputLen == 0)
168 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000169 CurrentUnitData = new uint8_t[MaxInputLen];
170}
171
172void Fuzzer::StaticDeathCallback() {
173 assert(F);
174 F->DeathCallback();
175}
176
177void Fuzzer::DumpCurrentUnit(const char *Prefix) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000178 if (!CurrentUnitData)
179 return; // Happens when running individual inputs.
morehouse1467b792018-07-09 23:51:08 +0000180 ScopedDisableMsanInterceptorChecks S;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000181 MD.PrintMutationSequence();
182 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
183 size_t UnitSize = CurrentUnitSize;
184 if (UnitSize <= kMaxUnitSizeToPrint) {
185 PrintHexArray(CurrentUnitData, UnitSize, "\n");
186 PrintASCII(CurrentUnitData, UnitSize, "\n");
187 }
188 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
189 Prefix);
190}
191
192NO_SANITIZE_MEMORY
193void Fuzzer::DeathCallback() {
194 DumpCurrentUnit("crash-");
195 PrintFinalStats();
196}
197
198void Fuzzer::StaticAlarmCallback() {
199 assert(F);
200 F->AlarmCallback();
201}
202
203void Fuzzer::StaticCrashSignalCallback() {
204 assert(F);
205 F->CrashCallback();
206}
207
kccda168932019-01-31 00:09:43 +0000208void Fuzzer::StaticSegvSignalCallback(void *Addr) {
209 if (TPC.UnprotectLazyCounters(Addr)) return;
210 StaticCrashSignalCallback();
211}
212
george.karpenkov29efa6d2017-08-21 23:25:50 +0000213void Fuzzer::StaticExitCallback() {
214 assert(F);
215 F->ExitCallback();
216}
217
218void Fuzzer::StaticInterruptCallback() {
219 assert(F);
220 F->InterruptCallback();
221}
222
kcc1239a992017-11-09 20:30:19 +0000223void Fuzzer::StaticGracefulExitCallback() {
224 assert(F);
225 F->GracefulExitRequested = true;
226 Printf("INFO: signal received, trying to exit gracefully\n");
227}
228
george.karpenkov29efa6d2017-08-21 23:25:50 +0000229void Fuzzer::StaticFileSizeExceedCallback() {
230 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
231 exit(1);
232}
233
234void Fuzzer::CrashCallback() {
morehousef7b44452018-05-02 02:55:28 +0000235 if (EF->__sanitizer_acquire_crash_state)
236 EF->__sanitizer_acquire_crash_state();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000237 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000238 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000239 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
240 " Combine libFuzzer with AddressSanitizer or similar for better "
241 "crash reports.\n");
242 Printf("SUMMARY: libFuzzer: deadly signal\n");
243 DumpCurrentUnit("crash-");
244 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000245 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000246}
247
248void Fuzzer::ExitCallback() {
morehousec6ee8752018-07-17 16:12:00 +0000249 if (!RunningUserCallback)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000250 return; // This exit did not come from the user callback
morehouse5a4566a2018-05-01 21:01:53 +0000251 if (EF->__sanitizer_acquire_crash_state &&
252 !EF->__sanitizer_acquire_crash_state())
253 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000254 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000255 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000256 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
257 DumpCurrentUnit("crash-");
258 PrintFinalStats();
259 _Exit(Options.ErrorExitCode);
260}
261
kcc1239a992017-11-09 20:30:19 +0000262void Fuzzer::MaybeExitGracefully() {
263 if (!GracefulExitRequested) return;
264 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
265 PrintFinalStats();
266 _Exit(0);
267}
268
george.karpenkov29efa6d2017-08-21 23:25:50 +0000269void Fuzzer::InterruptCallback() {
270 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
271 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000272 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000273}
274
275NO_SANITIZE_MEMORY
276void Fuzzer::AlarmCallback() {
277 assert(Options.UnitTimeoutSec > 0);
278 // In Windows Alarm callback is executed by a different thread.
kamil3849ee02018-11-06 01:28:01 +0000279 // NetBSD's current behavior needs this change too.
280#if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD
alekseyshl9f6a9f22017-10-23 23:24:33 +0000281 if (!InFuzzingThread())
282 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000283#endif
morehousec6ee8752018-07-17 16:12:00 +0000284 if (!RunningUserCallback)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000285 return; // We have not started running units yet.
286 size_t Seconds =
287 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
288 if (Seconds == 0)
289 return;
290 if (Options.Verbosity >= 2)
291 Printf("AlarmCallback %zd\n", Seconds);
292 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000293 if (EF->__sanitizer_acquire_crash_state &&
294 !EF->__sanitizer_acquire_crash_state())
295 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000296 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
297 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
298 Options.UnitTimeoutSec);
299 DumpCurrentUnit("timeout-");
300 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
301 Seconds);
morehousebd67cc22018-05-08 23:45:05 +0000302 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000303 Printf("SUMMARY: libFuzzer: timeout\n");
304 PrintFinalStats();
305 _Exit(Options.TimeoutExitCode); // Stop right now.
306 }
307}
308
309void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000310 if (EF->__sanitizer_acquire_crash_state &&
311 !EF->__sanitizer_acquire_crash_state())
312 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000313 Printf(
314 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
315 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
316 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000317 PrintMemoryProfile();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000318 DumpCurrentUnit("oom-");
319 Printf("SUMMARY: libFuzzer: out-of-memory\n");
320 PrintFinalStats();
321 _Exit(Options.ErrorExitCode); // Stop right now.
322}
323
324void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
325 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);
331 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000332 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000333 if (!Corpus.empty()) {
334 Printf(" corp: %zd", Corpus.NumActiveUnits());
335 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000336 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000337 Printf("/%zdb", N);
338 else if (N < (1 << 24))
339 Printf("/%zdKb", N >> 10);
340 else
341 Printf("/%zdMb", N >> 20);
342 }
kcc3acbe072018-05-16 23:26:37 +0000343 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
344 Printf(" focus: %zd", FF);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000345 }
morehousea6c692c2018-02-22 19:00:17 +0000346 if (TmpMaxMutationLen)
347 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000348 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() {
357 if (Options.PrintCoverage)
358 TPC.PrintCoverage();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000359 if (Options.PrintCorpusStats)
360 Corpus.PrintStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000361 if (!Options.PrintFinalStats)
362 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000363 size_t ExecPerSec = execPerSec();
364 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
365 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
366 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
367 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
368 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
369}
370
371void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
372 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
373 assert(MaxInputLen);
374 this->MaxInputLen = MaxInputLen;
375 this->MaxMutationLen = MaxInputLen;
376 AllocateCurrentUnitData();
377 Printf("INFO: -max_len is not provided; "
378 "libFuzzer will not generate inputs larger than %zd bytes\n",
379 MaxInputLen);
380}
381
382void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
383 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
384 this->MaxMutationLen = MaxMutationLen;
385}
386
387void Fuzzer::CheckExitOnSrcPosOrItem() {
388 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000389 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000390 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000391 if (!PCsSet->insert(PC).second)
392 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000393 std::string Descr = DescribePC("%F %L", PC + 1);
394 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
395 Printf("INFO: found line matching '%s', exiting.\n",
396 Options.ExitOnSrcPos.c_str());
397 _Exit(0);
398 }
399 };
400 TPC.ForEachObservedPC(HandlePC);
401 }
402 if (!Options.ExitOnItem.empty()) {
403 if (Corpus.HasUnit(Options.ExitOnItem)) {
404 Printf("INFO: found item with checksum '%s', exiting.\n",
405 Options.ExitOnItem.c_str());
406 _Exit(0);
407 }
408 }
409}
410
411void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000412 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
413 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000414 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000415 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
416 &EpochOfLastReadOfOutputCorpus, MaxSize,
417 /*ExitOnError*/ false);
418 if (Options.Verbosity >= 2)
419 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
420 bool Reloaded = false;
421 for (auto &U : AdditionalCorpus) {
422 if (U.size() > MaxSize)
423 U.resize(MaxSize);
424 if (!Corpus.HasUnit(U)) {
425 if (RunOne(U.data(), U.size())) {
426 CheckExitOnSrcPosOrItem();
427 Reloaded = true;
428 }
429 }
430 }
431 if (Reloaded)
432 PrintStats("RELOAD");
433}
434
george.karpenkov29efa6d2017-08-21 23:25:50 +0000435void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
436 auto TimeOfUnit =
437 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
438 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
439 secondsSinceProcessStartUp() >= 2)
440 PrintStats("pulse ");
441 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
442 TimeOfUnit >= Options.ReportSlowUnits) {
443 TimeOfLongestUnitInSeconds = TimeOfUnit;
444 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
445 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
446 }
447}
448
449bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000450 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000451 if (!Size)
452 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000453
454 ExecuteCallback(Data, Size);
455
456 UniqFeatureSetTmp.clear();
457 size_t FoundUniqFeaturesOfII = 0;
458 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
459 TPC.CollectFeatures([&](size_t Feature) {
460 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
461 UniqFeatureSetTmp.push_back(Feature);
462 if (Options.ReduceInputs && II)
463 if (std::binary_search(II->UniqFeatureSet.begin(),
464 II->UniqFeatureSet.end(), Feature))
465 FoundUniqFeaturesOfII++;
466 });
kccb6836be2017-12-01 19:18:38 +0000467 if (FoundUniqFeatures)
468 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000469 PrintPulseAndReportSlowInput(Data, Size);
470 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
471 if (NumNewFeatures) {
472 TPC.UpdateObservedPCs();
473 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
kcc0cab3f02018-07-19 01:23:32 +0000474 TPC.ObservedFocusFunction(), UniqFeatureSetTmp, DFT, II);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000475 return true;
476 }
477 if (II && FoundUniqFeaturesOfII &&
kccadf188b2018-06-07 01:40:20 +0000478 II->DataFlowTraceForFocusFunction.empty() &&
george.karpenkov29efa6d2017-08-21 23:25:50 +0000479 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
480 II->U.size() > Size) {
481 Corpus.Replace(II, {Data, Data + Size});
482 return true;
483 }
484 return false;
485}
486
487size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
488 assert(InFuzzingThread());
489 *Data = CurrentUnitData;
490 return CurrentUnitSize;
491}
492
493void Fuzzer::CrashOnOverwrittenData() {
494 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
495 GetPid());
496 DumpCurrentUnit("crash-");
497 Printf("SUMMARY: libFuzzer: out-of-memory\n");
498 _Exit(Options.ErrorExitCode); // Stop right now.
499}
500
501// Compare two arrays, but not all bytes if the arrays are large.
502static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
503 const size_t Limit = 64;
504 if (Size <= 64)
505 return !memcmp(A, B, Size);
506 // Compare first and last Limit/2 bytes.
507 return !memcmp(A, B, Limit / 2) &&
508 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
509}
510
511void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
512 TPC.RecordInitialStack();
513 TotalNumberOfRuns++;
514 assert(InFuzzingThread());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000515 // We copy the contents of Unit into a separate heap buffer
516 // so that we reliably find buffer overflows in it.
517 uint8_t *DataCopy = new uint8_t[Size];
518 memcpy(DataCopy, Data, Size);
morehouse1467b792018-07-09 23:51:08 +0000519 if (EF->__msan_unpoison)
520 EF->__msan_unpoison(DataCopy, Size);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000521 if (CurrentUnitData && CurrentUnitData != Data)
522 memcpy(CurrentUnitData, Data, Size);
523 CurrentUnitSize = Size;
morehouse1467b792018-07-09 23:51:08 +0000524 {
525 ScopedEnableMsanInterceptorChecks S;
526 AllocTracer.Start(Options.TraceMalloc);
527 UnitStartTime = system_clock::now();
528 TPC.ResetMaps();
morehousec6ee8752018-07-17 16:12:00 +0000529 RunningUserCallback = true;
morehouse1467b792018-07-09 23:51:08 +0000530 int Res = CB(DataCopy, Size);
morehousec6ee8752018-07-17 16:12:00 +0000531 RunningUserCallback = false;
morehouse1467b792018-07-09 23:51:08 +0000532 UnitStopTime = system_clock::now();
533 (void)Res;
534 assert(Res == 0);
535 HasMoreMallocsThanFrees = AllocTracer.Stop();
536 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000537 if (!LooseMemeq(DataCopy, Data, Size))
538 CrashOnOverwrittenData();
539 CurrentUnitSize = 0;
540 delete[] DataCopy;
541}
542
543void Fuzzer::WriteToOutputCorpus(const Unit &U) {
544 if (Options.OnlyASCII)
545 assert(IsASCII(U));
546 if (Options.OutputCorpus.empty())
547 return;
548 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
549 WriteToFile(U, Path);
550 if (Options.Verbosity >= 2)
551 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
552}
553
554void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
555 if (!Options.SaveArtifacts)
556 return;
557 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
558 if (!Options.ExactArtifactPath.empty())
559 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
560 WriteToFile(U, Path);
561 Printf("artifact_prefix='%s'; Test unit written to %s\n",
562 Options.ArtifactPrefix.c_str(), Path.c_str());
563 if (U.size() <= kMaxUnitSizeToPrint)
564 Printf("Base64: %s\n", Base64(U).c_str());
565}
566
567void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
568 if (!Options.PrintNEW)
569 return;
570 PrintStats(Text, "");
571 if (Options.Verbosity) {
572 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
573 MD.PrintMutationSequence();
574 Printf("\n");
575 }
576}
577
578void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
579 II->NumSuccessfullMutations++;
580 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000581 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000582 WriteToOutputCorpus(U);
583 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000584 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000585 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000586}
587
588// Tries detecting a memory leak on the particular input that we have just
589// executed before calling this function.
590void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
591 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000592 if (!HasMoreMallocsThanFrees)
593 return; // mallocs==frees, a leak is unlikely.
594 if (!Options.DetectLeaks)
595 return;
dor1s38279cb2017-09-12 02:01:54 +0000596 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000597 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
598 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000599 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
600 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000601 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000602 // Run the target once again, but with lsan disabled so that if there is
603 // a real leak we do not report it twice.
604 EF->__lsan_disable();
605 ExecuteCallback(Data, Size);
606 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000607 if (!HasMoreMallocsThanFrees)
608 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000609 if (NumberOfLeakDetectionAttempts++ > 1000) {
610 Options.DetectLeaks = false;
611 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
612 " Most likely the target function accumulates allocated\n"
613 " memory in a global state w/o actually leaking it.\n"
614 " You may try running this binary with -trace_malloc=[12]"
615 " to get a trace of mallocs and frees.\n"
616 " If LeakSanitizer is enabled in this process it will still\n"
617 " run on the process shutdown.\n");
618 return;
619 }
620 // Now perform the actual lsan pass. This is expensive and we must ensure
621 // we don't call it too often.
622 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
623 if (DuringInitialCorpusExecution)
624 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
625 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
626 CurrentUnitSize = Size;
627 DumpCurrentUnit("leak-");
628 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000629 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000630 }
631}
632
633void Fuzzer::MutateAndTestOne() {
634 MD.StartMutationSequence();
635
636 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
637 const auto &U = II.U;
638 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
639 assert(CurrentUnitData);
640 size_t Size = U.size();
641 assert(Size <= MaxInputLen && "Oversized Unit");
642 memcpy(CurrentUnitData, U.data(), Size);
643
644 assert(MaxMutationLen > 0);
645
646 size_t CurrentMaxMutationLen =
647 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
648 assert(CurrentMaxMutationLen > 0);
649
650 for (int i = 0; i < Options.MutateDepth; i++) {
651 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
652 break;
kcc1239a992017-11-09 20:30:19 +0000653 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000654 size_t NewSize = 0;
kcc0cab3f02018-07-19 01:23:32 +0000655 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
656 Size <= CurrentMaxMutationLen)
657 NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
658 II.DataFlowTraceForFocusFunction);
659 else
660 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000661 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000662 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000663 Size = NewSize;
664 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000665
kccb6836be2017-12-01 19:18:38 +0000666 bool FoundUniqFeatures = false;
667 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
668 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000669 TryDetectingAMemoryLeak(CurrentUnitData, Size,
670 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000671 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000672 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000673 break; // We will mutate this input more in the next rounds.
674 }
675 if (Options.ReduceDepth && !FoundUniqFeatures)
dor1se6729cb2018-07-16 15:15:34 +0000676 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000677 }
678}
679
alekseyshld995b552017-10-23 22:04:30 +0000680void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000681 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000682 return;
alekseyshld995b552017-10-23 22:04:30 +0000683 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000684 LastAllocatorPurgeAttemptTime)
685 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000686 return;
alekseyshld995b552017-10-23 22:04:30 +0000687
688 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000689 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000690 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000691
692 LastAllocatorPurgeAttemptTime = system_clock::now();
693}
694
kcc2e93b3f2017-08-29 02:05:01 +0000695void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
696 const size_t kMaxSaneLen = 1 << 20;
697 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000698 Vector<SizedFile> SizedFiles;
699 size_t MaxSize = 0;
700 size_t MinSize = -1;
701 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000702 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000703 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000704 GetSizedFilesFromDir(Dir, &SizedFiles);
705 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
706 Dir.c_str());
707 LastNumFiles = SizedFiles.size();
708 }
709 for (auto &File : SizedFiles) {
710 MaxSize = Max(File.Size, MaxSize);
711 MinSize = Min(File.Size, MinSize);
712 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000713 }
kccdc00cd32017-08-29 20:51:24 +0000714 if (Options.MaxLen == 0)
715 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
716 assert(MaxInputLen > 0);
717
kcc2cd9f092017-10-13 01:12:23 +0000718 // Test the callback with empty input and never try it again.
719 uint8_t dummy = 0;
720 ExecuteCallback(&dummy, 0);
721
kccdc00cd32017-08-29 20:51:24 +0000722 if (SizedFiles.empty()) {
723 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
724 Unit U({'\n'}); // Valid ASCII input.
725 RunOne(U.data(), U.size());
726 } else {
727 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
728 " rss: %zdMb\n",
729 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
730 if (Options.ShuffleAtStartUp)
731 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
732
kcc7f5f2222017-09-12 21:58:07 +0000733 if (Options.PreferSmall) {
734 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
735 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
736 }
kccdc00cd32017-08-29 20:51:24 +0000737
738 // Load and execute inputs one by one.
739 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000740 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000741 assert(U.size() <= MaxInputLen);
742 RunOne(U.data(), U.size());
743 CheckExitOnSrcPosOrItem();
744 TryDetectingAMemoryLeak(U.data(), U.size(),
745 /*DuringInitialCorpusExecution*/ true);
746 }
kcc2e93b3f2017-08-29 02:05:01 +0000747 }
748
kccdc00cd32017-08-29 20:51:24 +0000749 PrintStats("INITED");
kcc3acbe072018-05-16 23:26:37 +0000750 if (!Options.FocusFunction.empty())
751 Printf("INFO: %zd/%zd inputs touch the focus function\n",
752 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
kccadf188b2018-06-07 01:40:20 +0000753 if (!Options.DataFlowTrace.empty())
754 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
755 Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
kcc3acbe072018-05-16 23:26:37 +0000756
dor1s770a9bc2018-05-23 19:42:30 +0000757 if (Corpus.empty() && Options.MaxNumberOfRuns) {
kccdc00cd32017-08-29 20:51:24 +0000758 Printf("ERROR: no interesting inputs were found. "
759 "Is the code instrumented for coverage? Exiting.\n");
760 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000761 }
kcc2e93b3f2017-08-29 02:05:01 +0000762}
763
764void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
765 ReadAndExecuteSeedCorpora(CorpusDirs);
kccadf188b2018-06-07 01:40:20 +0000766 DFT.Clear(); // No need for DFT any more.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000767 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000768 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000769 system_clock::time_point LastCorpusReload = system_clock::now();
770 if (Options.DoCrossOver)
771 MD.SetCorpus(&Corpus);
772 while (true) {
773 auto Now = system_clock::now();
774 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
775 Options.ReloadIntervalSec) {
776 RereadOutputCorpus(MaxInputLen);
777 LastCorpusReload = system_clock::now();
778 }
779 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
780 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000781 if (TimedOut())
782 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000783
784 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000785 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000786 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000787 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000788 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000789 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000790 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000791 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000792 }
793 } else {
794 TmpMaxMutationLen = MaxMutationLen;
795 }
796
797 // Perform several mutations and runs.
798 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000799
800 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000801 }
802
803 PrintStats("DONE ", "\n");
804 MD.PrintRecommendedDictionary();
805}
806
807void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000808 if (U.size() <= 1)
809 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000810 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
811 MD.StartMutationSequence();
812 memcpy(CurrentUnitData, U.data(), U.size());
813 for (int i = 0; i < Options.MutateDepth; i++) {
814 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
815 assert(NewSize > 0 && NewSize <= MaxMutationLen);
816 ExecuteCallback(CurrentUnitData, NewSize);
817 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
818 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
819 /*DuringInitialCorpusExecution*/ false);
820 }
821 }
822}
823
george.karpenkov29efa6d2017-08-21 23:25:50 +0000824} // namespace fuzzer
825
826extern "C" {
827
metzman2fe66e62019-01-17 16:36:05 +0000828ATTRIBUTE_INTERFACE size_t
phosek966475e2018-01-17 20:39:14 +0000829LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000830 assert(fuzzer::F);
831 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
832}
833
alekseyshl9f6a9f22017-10-23 23:24:33 +0000834} // extern "C"