blob: 7ef310d37ab8512e7365bc8cd1235109791a5f2a [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"
16#include "FuzzerShmem.h"
17#include "FuzzerTracePC.h"
18#include <algorithm>
19#include <cstring>
20#include <memory>
vitalybukab3e5a2c2017-11-01 03:02:59 +000021#include <mutex>
george.karpenkov29efa6d2017-08-21 23:25:50 +000022#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
43SharedMemoryRegion SMR;
44
morehousec6ee8752018-07-17 16:12:00 +000045bool RunningUserCallback = false;
46
george.karpenkov29efa6d2017-08-21 23:25:50 +000047// Only one Fuzzer per process.
48static Fuzzer *F;
49
50// Leak detection is expensive, so we first check if there were more mallocs
51// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
52struct MallocFreeTracer {
53 void Start(int TraceLevel) {
54 this->TraceLevel = TraceLevel;
55 if (TraceLevel)
56 Printf("MallocFreeTracer: START\n");
57 Mallocs = 0;
58 Frees = 0;
59 }
60 // Returns true if there were more mallocs than frees.
61 bool Stop() {
62 if (TraceLevel)
63 Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
64 Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
65 bool Result = Mallocs > Frees;
66 Mallocs = 0;
67 Frees = 0;
68 TraceLevel = 0;
69 return Result;
70 }
71 std::atomic<size_t> Mallocs;
72 std::atomic<size_t> Frees;
73 int TraceLevel = 0;
vitalybukae6504cf2017-11-02 04:12:10 +000074
75 std::recursive_mutex TraceMutex;
76 bool TraceDisabled = false;
george.karpenkov29efa6d2017-08-21 23:25:50 +000077};
78
79static MallocFreeTracer AllocTracer;
80
vitalybukae6504cf2017-11-02 04:12:10 +000081// Locks printing and avoids nested hooks triggered from mallocs/frees in
82// sanitizer.
83class TraceLock {
84public:
85 TraceLock() : Lock(AllocTracer.TraceMutex) {
86 AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
87 }
88 ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
89
90 bool IsDisabled() const {
91 // This is already inverted value.
92 return !AllocTracer.TraceDisabled;
93 }
94
95private:
96 std::lock_guard<std::recursive_mutex> Lock;
97};
vitalybukab3e5a2c2017-11-01 03:02:59 +000098
george.karpenkov29efa6d2017-08-21 23:25:50 +000099ATTRIBUTE_NO_SANITIZE_MEMORY
100void MallocHook(const volatile void *ptr, size_t size) {
101 size_t N = AllocTracer.Mallocs++;
102 F->HandleMalloc(size);
103 if (int TraceLevel = AllocTracer.TraceLevel) {
vitalybukae6504cf2017-11-02 04:12:10 +0000104 TraceLock Lock;
105 if (Lock.IsDisabled())
106 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000107 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
108 if (TraceLevel >= 2 && EF)
morehousebd67cc22018-05-08 23:45:05 +0000109 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000110 }
111}
112
113ATTRIBUTE_NO_SANITIZE_MEMORY
114void FreeHook(const volatile void *ptr) {
115 size_t N = AllocTracer.Frees++;
116 if (int TraceLevel = AllocTracer.TraceLevel) {
vitalybukae6504cf2017-11-02 04:12:10 +0000117 TraceLock Lock;
118 if (Lock.IsDisabled())
119 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000120 Printf("FREE[%zd] %p\n", N, ptr);
121 if (TraceLevel >= 2 && EF)
morehousebd67cc22018-05-08 23:45:05 +0000122 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000123 }
124}
125
126// Crash on a single malloc that exceeds the rss limit.
127void Fuzzer::HandleMalloc(size_t Size) {
kcc120e40b2017-12-01 22:12:04 +0000128 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000129 return;
130 Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
131 Size);
132 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000133 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000134 DumpCurrentUnit("oom-");
135 Printf("SUMMARY: libFuzzer: out-of-memory\n");
136 PrintFinalStats();
137 _Exit(Options.ErrorExitCode); // Stop right now.
138}
139
140Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
141 FuzzingOptions Options)
142 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
143 if (EF->__sanitizer_set_death_callback)
144 EF->__sanitizer_set_death_callback(StaticDeathCallback);
145 assert(!F);
146 F = this;
147 TPC.ResetMaps();
148 IsMyThread = true;
149 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
150 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
151 TPC.SetUseCounters(Options.UseCounters);
kcc3850d062018-07-03 22:33:09 +0000152 TPC.SetUseValueProfileMask(Options.UseValueProfile);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000153
154 if (Options.Verbosity)
155 TPC.PrintModuleInfo();
156 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
157 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
158 MaxInputLen = MaxMutationLen = Options.MaxLen;
159 TmpMaxMutationLen = Max(size_t(4), Corpus.MaxInputSize());
160 AllocateCurrentUnitData();
161 CurrentUnitSize = 0;
162 memset(BaseSha1, 0, sizeof(BaseSha1));
kcc3acbe072018-05-16 23:26:37 +0000163 TPC.SetFocusFunction(Options.FocusFunction);
kcc86e43882018-06-06 01:23:29 +0000164 DFT.Init(Options.DataFlowTrace, Options.FocusFunction);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000165}
166
alekseyshl9f6a9f22017-10-23 23:24:33 +0000167Fuzzer::~Fuzzer() {}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000168
169void Fuzzer::AllocateCurrentUnitData() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000170 if (CurrentUnitData || MaxInputLen == 0)
171 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000172 CurrentUnitData = new uint8_t[MaxInputLen];
173}
174
175void Fuzzer::StaticDeathCallback() {
176 assert(F);
177 F->DeathCallback();
178}
179
180void Fuzzer::DumpCurrentUnit(const char *Prefix) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000181 if (!CurrentUnitData)
182 return; // Happens when running individual inputs.
morehouse1467b792018-07-09 23:51:08 +0000183 ScopedDisableMsanInterceptorChecks S;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000184 MD.PrintMutationSequence();
185 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
186 size_t UnitSize = CurrentUnitSize;
187 if (UnitSize <= kMaxUnitSizeToPrint) {
188 PrintHexArray(CurrentUnitData, UnitSize, "\n");
189 PrintASCII(CurrentUnitData, UnitSize, "\n");
190 }
191 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
192 Prefix);
193}
194
195NO_SANITIZE_MEMORY
196void Fuzzer::DeathCallback() {
197 DumpCurrentUnit("crash-");
198 PrintFinalStats();
199}
200
201void Fuzzer::StaticAlarmCallback() {
202 assert(F);
203 F->AlarmCallback();
204}
205
206void Fuzzer::StaticCrashSignalCallback() {
207 assert(F);
208 F->CrashCallback();
209}
210
211void Fuzzer::StaticExitCallback() {
212 assert(F);
213 F->ExitCallback();
214}
215
216void Fuzzer::StaticInterruptCallback() {
217 assert(F);
218 F->InterruptCallback();
219}
220
kcc1239a992017-11-09 20:30:19 +0000221void Fuzzer::StaticGracefulExitCallback() {
222 assert(F);
223 F->GracefulExitRequested = true;
224 Printf("INFO: signal received, trying to exit gracefully\n");
225}
226
george.karpenkov29efa6d2017-08-21 23:25:50 +0000227void Fuzzer::StaticFileSizeExceedCallback() {
228 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
229 exit(1);
230}
231
232void Fuzzer::CrashCallback() {
morehousef7b44452018-05-02 02:55:28 +0000233 if (EF->__sanitizer_acquire_crash_state)
234 EF->__sanitizer_acquire_crash_state();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000235 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000236 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000237 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
238 " Combine libFuzzer with AddressSanitizer or similar for better "
239 "crash reports.\n");
240 Printf("SUMMARY: libFuzzer: deadly signal\n");
241 DumpCurrentUnit("crash-");
242 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000243 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000244}
245
246void Fuzzer::ExitCallback() {
morehousec6ee8752018-07-17 16:12:00 +0000247 if (!RunningUserCallback)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000248 return; // This exit did not come from the user callback
morehouse5a4566a2018-05-01 21:01:53 +0000249 if (EF->__sanitizer_acquire_crash_state &&
250 !EF->__sanitizer_acquire_crash_state())
251 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000252 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000253 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000254 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
255 DumpCurrentUnit("crash-");
256 PrintFinalStats();
257 _Exit(Options.ErrorExitCode);
258}
259
kcc1239a992017-11-09 20:30:19 +0000260void Fuzzer::MaybeExitGracefully() {
261 if (!GracefulExitRequested) return;
262 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
263 PrintFinalStats();
264 _Exit(0);
265}
266
george.karpenkov29efa6d2017-08-21 23:25:50 +0000267void Fuzzer::InterruptCallback() {
268 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
269 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000270 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000271}
272
273NO_SANITIZE_MEMORY
274void Fuzzer::AlarmCallback() {
275 assert(Options.UnitTimeoutSec > 0);
276 // In Windows Alarm callback is executed by a different thread.
kamil3849ee02018-11-06 01:28:01 +0000277 // NetBSD's current behavior needs this change too.
278#if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD
alekseyshl9f6a9f22017-10-23 23:24:33 +0000279 if (!InFuzzingThread())
280 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000281#endif
morehousec6ee8752018-07-17 16:12:00 +0000282 if (!RunningUserCallback)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000283 return; // We have not started running units yet.
284 size_t Seconds =
285 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
286 if (Seconds == 0)
287 return;
288 if (Options.Verbosity >= 2)
289 Printf("AlarmCallback %zd\n", Seconds);
290 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000291 if (EF->__sanitizer_acquire_crash_state &&
292 !EF->__sanitizer_acquire_crash_state())
293 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000294 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
295 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
296 Options.UnitTimeoutSec);
297 DumpCurrentUnit("timeout-");
298 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
299 Seconds);
morehousebd67cc22018-05-08 23:45:05 +0000300 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000301 Printf("SUMMARY: libFuzzer: timeout\n");
302 PrintFinalStats();
303 _Exit(Options.TimeoutExitCode); // Stop right now.
304 }
305}
306
307void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000308 if (EF->__sanitizer_acquire_crash_state &&
309 !EF->__sanitizer_acquire_crash_state())
310 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000311 Printf(
312 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
313 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
314 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000315 PrintMemoryProfile();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000316 DumpCurrentUnit("oom-");
317 Printf("SUMMARY: libFuzzer: out-of-memory\n");
318 PrintFinalStats();
319 _Exit(Options.ErrorExitCode); // Stop right now.
320}
321
322void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
323 size_t ExecPerSec = execPerSec();
324 if (!Options.Verbosity)
325 return;
326 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
327 if (size_t N = TPC.GetTotalPCCoverage())
328 Printf(" cov: %zd", N);
329 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000330 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000331 if (!Corpus.empty()) {
332 Printf(" corp: %zd", Corpus.NumActiveUnits());
333 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000334 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000335 Printf("/%zdb", N);
336 else if (N < (1 << 24))
337 Printf("/%zdKb", N >> 10);
338 else
339 Printf("/%zdMb", N >> 20);
340 }
kcc3acbe072018-05-16 23:26:37 +0000341 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
342 Printf(" focus: %zd", FF);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000343 }
morehousea6c692c2018-02-22 19:00:17 +0000344 if (TmpMaxMutationLen)
345 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000346 if (Units)
347 Printf(" units: %zd", Units);
348
349 Printf(" exec/s: %zd", ExecPerSec);
350 Printf(" rss: %zdMb", GetPeakRSSMb());
351 Printf("%s", End);
352}
353
354void Fuzzer::PrintFinalStats() {
355 if (Options.PrintCoverage)
356 TPC.PrintCoverage();
kcca7dd2a92018-05-21 19:47:00 +0000357 if (Options.DumpCoverage)
358 TPC.DumpCoverage();
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());
515 if (SMR.IsClient())
516 SMR.WriteByteArray(Data, Size);
517 // We copy the contents of Unit into a separate heap buffer
518 // so that we reliably find buffer overflows in it.
519 uint8_t *DataCopy = new uint8_t[Size];
520 memcpy(DataCopy, Data, Size);
morehouse1467b792018-07-09 23:51:08 +0000521 if (EF->__msan_unpoison)
522 EF->__msan_unpoison(DataCopy, Size);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000523 if (CurrentUnitData && CurrentUnitData != Data)
524 memcpy(CurrentUnitData, Data, Size);
525 CurrentUnitSize = Size;
morehouse1467b792018-07-09 23:51:08 +0000526 {
527 ScopedEnableMsanInterceptorChecks S;
528 AllocTracer.Start(Options.TraceMalloc);
529 UnitStartTime = system_clock::now();
530 TPC.ResetMaps();
morehousec6ee8752018-07-17 16:12:00 +0000531 RunningUserCallback = true;
morehouse1467b792018-07-09 23:51:08 +0000532 int Res = CB(DataCopy, Size);
morehousec6ee8752018-07-17 16:12:00 +0000533 RunningUserCallback = false;
morehouse1467b792018-07-09 23:51:08 +0000534 UnitStopTime = system_clock::now();
535 (void)Res;
536 assert(Res == 0);
537 HasMoreMallocsThanFrees = AllocTracer.Stop();
538 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000539 if (!LooseMemeq(DataCopy, Data, Size))
540 CrashOnOverwrittenData();
541 CurrentUnitSize = 0;
542 delete[] DataCopy;
543}
544
545void Fuzzer::WriteToOutputCorpus(const Unit &U) {
546 if (Options.OnlyASCII)
547 assert(IsASCII(U));
548 if (Options.OutputCorpus.empty())
549 return;
550 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
551 WriteToFile(U, Path);
552 if (Options.Verbosity >= 2)
553 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
554}
555
556void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
557 if (!Options.SaveArtifacts)
558 return;
559 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
560 if (!Options.ExactArtifactPath.empty())
561 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
562 WriteToFile(U, Path);
563 Printf("artifact_prefix='%s'; Test unit written to %s\n",
564 Options.ArtifactPrefix.c_str(), Path.c_str());
565 if (U.size() <= kMaxUnitSizeToPrint)
566 Printf("Base64: %s\n", Base64(U).c_str());
567}
568
569void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
570 if (!Options.PrintNEW)
571 return;
572 PrintStats(Text, "");
573 if (Options.Verbosity) {
574 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
575 MD.PrintMutationSequence();
576 Printf("\n");
577 }
578}
579
580void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
581 II->NumSuccessfullMutations++;
582 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000583 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000584 WriteToOutputCorpus(U);
585 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000586 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000587 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000588}
589
590// Tries detecting a memory leak on the particular input that we have just
591// executed before calling this function.
592void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
593 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000594 if (!HasMoreMallocsThanFrees)
595 return; // mallocs==frees, a leak is unlikely.
596 if (!Options.DetectLeaks)
597 return;
dor1s38279cb2017-09-12 02:01:54 +0000598 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000599 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
600 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000601 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
602 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000603 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000604 // Run the target once again, but with lsan disabled so that if there is
605 // a real leak we do not report it twice.
606 EF->__lsan_disable();
607 ExecuteCallback(Data, Size);
608 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000609 if (!HasMoreMallocsThanFrees)
610 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000611 if (NumberOfLeakDetectionAttempts++ > 1000) {
612 Options.DetectLeaks = false;
613 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
614 " Most likely the target function accumulates allocated\n"
615 " memory in a global state w/o actually leaking it.\n"
616 " You may try running this binary with -trace_malloc=[12]"
617 " to get a trace of mallocs and frees.\n"
618 " If LeakSanitizer is enabled in this process it will still\n"
619 " run on the process shutdown.\n");
620 return;
621 }
622 // Now perform the actual lsan pass. This is expensive and we must ensure
623 // we don't call it too often.
624 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
625 if (DuringInitialCorpusExecution)
626 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
627 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
628 CurrentUnitSize = Size;
629 DumpCurrentUnit("leak-");
630 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000631 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000632 }
633}
634
635void Fuzzer::MutateAndTestOne() {
636 MD.StartMutationSequence();
637
638 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
639 const auto &U = II.U;
640 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
641 assert(CurrentUnitData);
642 size_t Size = U.size();
643 assert(Size <= MaxInputLen && "Oversized Unit");
644 memcpy(CurrentUnitData, U.data(), Size);
645
646 assert(MaxMutationLen > 0);
647
648 size_t CurrentMaxMutationLen =
649 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
650 assert(CurrentMaxMutationLen > 0);
651
652 for (int i = 0; i < Options.MutateDepth; i++) {
653 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
654 break;
kcc1239a992017-11-09 20:30:19 +0000655 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000656 size_t NewSize = 0;
kcc0cab3f02018-07-19 01:23:32 +0000657 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
658 Size <= CurrentMaxMutationLen)
659 NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
660 II.DataFlowTraceForFocusFunction);
661 else
662 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000663 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000664 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000665 Size = NewSize;
666 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000667
kccb6836be2017-12-01 19:18:38 +0000668 bool FoundUniqFeatures = false;
669 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
670 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000671 TryDetectingAMemoryLeak(CurrentUnitData, Size,
672 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000673 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000674 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000675 break; // We will mutate this input more in the next rounds.
676 }
677 if (Options.ReduceDepth && !FoundUniqFeatures)
dor1se6729cb2018-07-16 15:15:34 +0000678 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000679 }
680}
681
alekseyshld995b552017-10-23 22:04:30 +0000682void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000683 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000684 return;
alekseyshld995b552017-10-23 22:04:30 +0000685 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000686 LastAllocatorPurgeAttemptTime)
687 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000688 return;
alekseyshld995b552017-10-23 22:04:30 +0000689
690 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000691 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000692 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000693
694 LastAllocatorPurgeAttemptTime = system_clock::now();
695}
696
kcc2e93b3f2017-08-29 02:05:01 +0000697void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
698 const size_t kMaxSaneLen = 1 << 20;
699 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000700 Vector<SizedFile> SizedFiles;
701 size_t MaxSize = 0;
702 size_t MinSize = -1;
703 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000704 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000705 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000706 GetSizedFilesFromDir(Dir, &SizedFiles);
707 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
708 Dir.c_str());
709 LastNumFiles = SizedFiles.size();
710 }
711 for (auto &File : SizedFiles) {
712 MaxSize = Max(File.Size, MaxSize);
713 MinSize = Min(File.Size, MinSize);
714 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000715 }
kccdc00cd32017-08-29 20:51:24 +0000716 if (Options.MaxLen == 0)
717 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
718 assert(MaxInputLen > 0);
719
kcc2cd9f092017-10-13 01:12:23 +0000720 // Test the callback with empty input and never try it again.
721 uint8_t dummy = 0;
722 ExecuteCallback(&dummy, 0);
723
kccdc00cd32017-08-29 20:51:24 +0000724 if (SizedFiles.empty()) {
725 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
726 Unit U({'\n'}); // Valid ASCII input.
727 RunOne(U.data(), U.size());
728 } else {
729 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
730 " rss: %zdMb\n",
731 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
732 if (Options.ShuffleAtStartUp)
733 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
734
kcc7f5f2222017-09-12 21:58:07 +0000735 if (Options.PreferSmall) {
736 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
737 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
738 }
kccdc00cd32017-08-29 20:51:24 +0000739
740 // Load and execute inputs one by one.
741 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000742 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000743 assert(U.size() <= MaxInputLen);
744 RunOne(U.data(), U.size());
745 CheckExitOnSrcPosOrItem();
746 TryDetectingAMemoryLeak(U.data(), U.size(),
747 /*DuringInitialCorpusExecution*/ true);
748 }
kcc2e93b3f2017-08-29 02:05:01 +0000749 }
750
kccdc00cd32017-08-29 20:51:24 +0000751 PrintStats("INITED");
kcc3acbe072018-05-16 23:26:37 +0000752 if (!Options.FocusFunction.empty())
753 Printf("INFO: %zd/%zd inputs touch the focus function\n",
754 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
kccadf188b2018-06-07 01:40:20 +0000755 if (!Options.DataFlowTrace.empty())
756 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
757 Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
kcc3acbe072018-05-16 23:26:37 +0000758
dor1s770a9bc2018-05-23 19:42:30 +0000759 if (Corpus.empty() && Options.MaxNumberOfRuns) {
kccdc00cd32017-08-29 20:51:24 +0000760 Printf("ERROR: no interesting inputs were found. "
761 "Is the code instrumented for coverage? Exiting.\n");
762 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000763 }
kcc2e93b3f2017-08-29 02:05:01 +0000764}
765
766void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
767 ReadAndExecuteSeedCorpora(CorpusDirs);
kccadf188b2018-06-07 01:40:20 +0000768 DFT.Clear(); // No need for DFT any more.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000769 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000770 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000771 system_clock::time_point LastCorpusReload = system_clock::now();
772 if (Options.DoCrossOver)
773 MD.SetCorpus(&Corpus);
774 while (true) {
775 auto Now = system_clock::now();
776 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
777 Options.ReloadIntervalSec) {
778 RereadOutputCorpus(MaxInputLen);
779 LastCorpusReload = system_clock::now();
780 }
781 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
782 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000783 if (TimedOut())
784 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000785
786 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000787 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000788 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000789 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000790 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000791 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000792 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000793 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000794 }
795 } else {
796 TmpMaxMutationLen = MaxMutationLen;
797 }
798
799 // Perform several mutations and runs.
800 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000801
802 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000803 }
804
805 PrintStats("DONE ", "\n");
806 MD.PrintRecommendedDictionary();
807}
808
809void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000810 if (U.size() <= 1)
811 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000812 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
813 MD.StartMutationSequence();
814 memcpy(CurrentUnitData, U.data(), U.size());
815 for (int i = 0; i < Options.MutateDepth; i++) {
816 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
817 assert(NewSize > 0 && NewSize <= MaxMutationLen);
818 ExecuteCallback(CurrentUnitData, NewSize);
819 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
820 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
821 /*DuringInitialCorpusExecution*/ false);
822 }
823 }
824}
825
826void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
827 if (SMR.IsServer()) {
828 SMR.WriteByteArray(Data, Size);
829 } else if (SMR.IsClient()) {
830 SMR.PostClient();
831 SMR.WaitServer();
832 size_t OtherSize = SMR.ReadByteArraySize();
833 uint8_t *OtherData = SMR.GetByteArray();
834 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
835 size_t i = 0;
836 for (i = 0; i < Min(Size, OtherSize); i++)
837 if (Data[i] != OtherData[i])
838 break;
839 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000840 "offset %zd\n",
841 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000842 DumpCurrentUnit("mismatch-");
843 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
844 PrintFinalStats();
845 _Exit(Options.ErrorExitCode);
846 }
847 }
848}
849
850} // namespace fuzzer
851
852extern "C" {
853
metzman2fe66e62019-01-17 16:36:05 +0000854ATTRIBUTE_INTERFACE size_t
phosek966475e2018-01-17 20:39:14 +0000855LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000856 assert(fuzzer::F);
857 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
858}
859
860// Experimental
metzman2fe66e62019-01-17 16:36:05 +0000861ATTRIBUTE_INTERFACE void
phosek966475e2018-01-17 20:39:14 +0000862LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000863 assert(fuzzer::F);
864 fuzzer::F->AnnounceOutput(Data, Size);
865}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000866} // extern "C"