blob: 0247b574df840557a58331ea67208ece475abe36 [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
208void Fuzzer::StaticExitCallback() {
209 assert(F);
210 F->ExitCallback();
211}
212
213void Fuzzer::StaticInterruptCallback() {
214 assert(F);
215 F->InterruptCallback();
216}
217
kcc1239a992017-11-09 20:30:19 +0000218void Fuzzer::StaticGracefulExitCallback() {
219 assert(F);
220 F->GracefulExitRequested = true;
221 Printf("INFO: signal received, trying to exit gracefully\n");
222}
223
george.karpenkov29efa6d2017-08-21 23:25:50 +0000224void Fuzzer::StaticFileSizeExceedCallback() {
225 Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
226 exit(1);
227}
228
229void Fuzzer::CrashCallback() {
morehousef7b44452018-05-02 02:55:28 +0000230 if (EF->__sanitizer_acquire_crash_state)
231 EF->__sanitizer_acquire_crash_state();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000232 Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000233 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000234 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
235 " Combine libFuzzer with AddressSanitizer or similar for better "
236 "crash reports.\n");
237 Printf("SUMMARY: libFuzzer: deadly signal\n");
238 DumpCurrentUnit("crash-");
239 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000240 _Exit(Options.ErrorExitCode); // Stop right now.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000241}
242
243void Fuzzer::ExitCallback() {
morehousec6ee8752018-07-17 16:12:00 +0000244 if (!RunningUserCallback)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000245 return; // This exit did not come from the user callback
morehouse5a4566a2018-05-01 21:01:53 +0000246 if (EF->__sanitizer_acquire_crash_state &&
247 !EF->__sanitizer_acquire_crash_state())
248 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000249 Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
morehousebd67cc22018-05-08 23:45:05 +0000250 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000251 Printf("SUMMARY: libFuzzer: fuzz target exited\n");
252 DumpCurrentUnit("crash-");
253 PrintFinalStats();
254 _Exit(Options.ErrorExitCode);
255}
256
kcc1239a992017-11-09 20:30:19 +0000257void Fuzzer::MaybeExitGracefully() {
258 if (!GracefulExitRequested) return;
259 Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
260 PrintFinalStats();
261 _Exit(0);
262}
263
george.karpenkov29efa6d2017-08-21 23:25:50 +0000264void Fuzzer::InterruptCallback() {
265 Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
266 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000267 _Exit(0); // Stop right now, don't perform any at-exit actions.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000268}
269
270NO_SANITIZE_MEMORY
271void Fuzzer::AlarmCallback() {
272 assert(Options.UnitTimeoutSec > 0);
273 // In Windows Alarm callback is executed by a different thread.
kamil3849ee02018-11-06 01:28:01 +0000274 // NetBSD's current behavior needs this change too.
275#if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD
alekseyshl9f6a9f22017-10-23 23:24:33 +0000276 if (!InFuzzingThread())
277 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000278#endif
morehousec6ee8752018-07-17 16:12:00 +0000279 if (!RunningUserCallback)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000280 return; // We have not started running units yet.
281 size_t Seconds =
282 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
283 if (Seconds == 0)
284 return;
285 if (Options.Verbosity >= 2)
286 Printf("AlarmCallback %zd\n", Seconds);
287 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000288 if (EF->__sanitizer_acquire_crash_state &&
289 !EF->__sanitizer_acquire_crash_state())
290 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000291 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
292 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
293 Options.UnitTimeoutSec);
294 DumpCurrentUnit("timeout-");
295 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
296 Seconds);
morehousebd67cc22018-05-08 23:45:05 +0000297 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000298 Printf("SUMMARY: libFuzzer: timeout\n");
299 PrintFinalStats();
300 _Exit(Options.TimeoutExitCode); // Stop right now.
301 }
302}
303
304void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000305 if (EF->__sanitizer_acquire_crash_state &&
306 !EF->__sanitizer_acquire_crash_state())
307 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000308 Printf(
309 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
310 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
311 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000312 PrintMemoryProfile();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000313 DumpCurrentUnit("oom-");
314 Printf("SUMMARY: libFuzzer: out-of-memory\n");
315 PrintFinalStats();
316 _Exit(Options.ErrorExitCode); // Stop right now.
317}
318
319void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
320 size_t ExecPerSec = execPerSec();
321 if (!Options.Verbosity)
322 return;
323 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
324 if (size_t N = TPC.GetTotalPCCoverage())
325 Printf(" cov: %zd", N);
326 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000327 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000328 if (!Corpus.empty()) {
329 Printf(" corp: %zd", Corpus.NumActiveUnits());
330 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000331 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000332 Printf("/%zdb", N);
333 else if (N < (1 << 24))
334 Printf("/%zdKb", N >> 10);
335 else
336 Printf("/%zdMb", N >> 20);
337 }
kcc3acbe072018-05-16 23:26:37 +0000338 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
339 Printf(" focus: %zd", FF);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000340 }
morehousea6c692c2018-02-22 19:00:17 +0000341 if (TmpMaxMutationLen)
342 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000343 if (Units)
344 Printf(" units: %zd", Units);
345
346 Printf(" exec/s: %zd", ExecPerSec);
347 Printf(" rss: %zdMb", GetPeakRSSMb());
348 Printf("%s", End);
349}
350
351void Fuzzer::PrintFinalStats() {
352 if (Options.PrintCoverage)
353 TPC.PrintCoverage();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000354 if (Options.PrintCorpusStats)
355 Corpus.PrintStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000356 if (!Options.PrintFinalStats)
357 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000358 size_t ExecPerSec = execPerSec();
359 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
360 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
361 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
362 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
363 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
364}
365
366void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
367 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
368 assert(MaxInputLen);
369 this->MaxInputLen = MaxInputLen;
370 this->MaxMutationLen = MaxInputLen;
371 AllocateCurrentUnitData();
372 Printf("INFO: -max_len is not provided; "
373 "libFuzzer will not generate inputs larger than %zd bytes\n",
374 MaxInputLen);
375}
376
377void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
378 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
379 this->MaxMutationLen = MaxMutationLen;
380}
381
382void Fuzzer::CheckExitOnSrcPosOrItem() {
383 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000384 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000385 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000386 if (!PCsSet->insert(PC).second)
387 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000388 std::string Descr = DescribePC("%F %L", PC + 1);
389 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
390 Printf("INFO: found line matching '%s', exiting.\n",
391 Options.ExitOnSrcPos.c_str());
392 _Exit(0);
393 }
394 };
395 TPC.ForEachObservedPC(HandlePC);
396 }
397 if (!Options.ExitOnItem.empty()) {
398 if (Corpus.HasUnit(Options.ExitOnItem)) {
399 Printf("INFO: found item with checksum '%s', exiting.\n",
400 Options.ExitOnItem.c_str());
401 _Exit(0);
402 }
403 }
404}
405
406void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000407 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
408 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000409 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000410 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
411 &EpochOfLastReadOfOutputCorpus, MaxSize,
412 /*ExitOnError*/ false);
413 if (Options.Verbosity >= 2)
414 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
415 bool Reloaded = false;
416 for (auto &U : AdditionalCorpus) {
417 if (U.size() > MaxSize)
418 U.resize(MaxSize);
419 if (!Corpus.HasUnit(U)) {
420 if (RunOne(U.data(), U.size())) {
421 CheckExitOnSrcPosOrItem();
422 Reloaded = true;
423 }
424 }
425 }
426 if (Reloaded)
427 PrintStats("RELOAD");
428}
429
george.karpenkov29efa6d2017-08-21 23:25:50 +0000430void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
431 auto TimeOfUnit =
432 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
433 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
434 secondsSinceProcessStartUp() >= 2)
435 PrintStats("pulse ");
436 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
437 TimeOfUnit >= Options.ReportSlowUnits) {
438 TimeOfLongestUnitInSeconds = TimeOfUnit;
439 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
440 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
441 }
442}
443
444bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000445 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000446 if (!Size)
447 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000448
449 ExecuteCallback(Data, Size);
450
451 UniqFeatureSetTmp.clear();
452 size_t FoundUniqFeaturesOfII = 0;
453 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
454 TPC.CollectFeatures([&](size_t Feature) {
455 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
456 UniqFeatureSetTmp.push_back(Feature);
457 if (Options.ReduceInputs && II)
458 if (std::binary_search(II->UniqFeatureSet.begin(),
459 II->UniqFeatureSet.end(), Feature))
460 FoundUniqFeaturesOfII++;
461 });
kccb6836be2017-12-01 19:18:38 +0000462 if (FoundUniqFeatures)
463 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000464 PrintPulseAndReportSlowInput(Data, Size);
465 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
466 if (NumNewFeatures) {
467 TPC.UpdateObservedPCs();
468 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
kcc0cab3f02018-07-19 01:23:32 +0000469 TPC.ObservedFocusFunction(), UniqFeatureSetTmp, DFT, II);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000470 return true;
471 }
472 if (II && FoundUniqFeaturesOfII &&
kccadf188b2018-06-07 01:40:20 +0000473 II->DataFlowTraceForFocusFunction.empty() &&
george.karpenkov29efa6d2017-08-21 23:25:50 +0000474 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
475 II->U.size() > Size) {
476 Corpus.Replace(II, {Data, Data + Size});
477 return true;
478 }
479 return false;
480}
481
482size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
483 assert(InFuzzingThread());
484 *Data = CurrentUnitData;
485 return CurrentUnitSize;
486}
487
488void Fuzzer::CrashOnOverwrittenData() {
489 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
490 GetPid());
491 DumpCurrentUnit("crash-");
492 Printf("SUMMARY: libFuzzer: out-of-memory\n");
493 _Exit(Options.ErrorExitCode); // Stop right now.
494}
495
496// Compare two arrays, but not all bytes if the arrays are large.
497static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
498 const size_t Limit = 64;
499 if (Size <= 64)
500 return !memcmp(A, B, Size);
501 // Compare first and last Limit/2 bytes.
502 return !memcmp(A, B, Limit / 2) &&
503 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
504}
505
506void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
507 TPC.RecordInitialStack();
508 TotalNumberOfRuns++;
509 assert(InFuzzingThread());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000510 // We copy the contents of Unit into a separate heap buffer
511 // so that we reliably find buffer overflows in it.
512 uint8_t *DataCopy = new uint8_t[Size];
513 memcpy(DataCopy, Data, Size);
morehouse1467b792018-07-09 23:51:08 +0000514 if (EF->__msan_unpoison)
515 EF->__msan_unpoison(DataCopy, Size);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000516 if (CurrentUnitData && CurrentUnitData != Data)
517 memcpy(CurrentUnitData, Data, Size);
518 CurrentUnitSize = Size;
morehouse1467b792018-07-09 23:51:08 +0000519 {
520 ScopedEnableMsanInterceptorChecks S;
521 AllocTracer.Start(Options.TraceMalloc);
522 UnitStartTime = system_clock::now();
523 TPC.ResetMaps();
morehousec6ee8752018-07-17 16:12:00 +0000524 RunningUserCallback = true;
morehouse1467b792018-07-09 23:51:08 +0000525 int Res = CB(DataCopy, Size);
morehousec6ee8752018-07-17 16:12:00 +0000526 RunningUserCallback = false;
morehouse1467b792018-07-09 23:51:08 +0000527 UnitStopTime = system_clock::now();
528 (void)Res;
529 assert(Res == 0);
530 HasMoreMallocsThanFrees = AllocTracer.Stop();
531 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000532 if (!LooseMemeq(DataCopy, Data, Size))
533 CrashOnOverwrittenData();
534 CurrentUnitSize = 0;
535 delete[] DataCopy;
536}
537
538void Fuzzer::WriteToOutputCorpus(const Unit &U) {
539 if (Options.OnlyASCII)
540 assert(IsASCII(U));
541 if (Options.OutputCorpus.empty())
542 return;
543 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
544 WriteToFile(U, Path);
545 if (Options.Verbosity >= 2)
546 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
547}
548
549void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
550 if (!Options.SaveArtifacts)
551 return;
552 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
553 if (!Options.ExactArtifactPath.empty())
554 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
555 WriteToFile(U, Path);
556 Printf("artifact_prefix='%s'; Test unit written to %s\n",
557 Options.ArtifactPrefix.c_str(), Path.c_str());
558 if (U.size() <= kMaxUnitSizeToPrint)
559 Printf("Base64: %s\n", Base64(U).c_str());
560}
561
562void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
563 if (!Options.PrintNEW)
564 return;
565 PrintStats(Text, "");
566 if (Options.Verbosity) {
567 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
568 MD.PrintMutationSequence();
569 Printf("\n");
570 }
571}
572
573void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
574 II->NumSuccessfullMutations++;
575 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000576 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000577 WriteToOutputCorpus(U);
578 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000579 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000580 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000581}
582
583// Tries detecting a memory leak on the particular input that we have just
584// executed before calling this function.
585void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
586 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000587 if (!HasMoreMallocsThanFrees)
588 return; // mallocs==frees, a leak is unlikely.
589 if (!Options.DetectLeaks)
590 return;
dor1s38279cb2017-09-12 02:01:54 +0000591 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000592 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
593 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000594 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
595 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000596 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000597 // Run the target once again, but with lsan disabled so that if there is
598 // a real leak we do not report it twice.
599 EF->__lsan_disable();
600 ExecuteCallback(Data, Size);
601 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000602 if (!HasMoreMallocsThanFrees)
603 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000604 if (NumberOfLeakDetectionAttempts++ > 1000) {
605 Options.DetectLeaks = false;
606 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
607 " Most likely the target function accumulates allocated\n"
608 " memory in a global state w/o actually leaking it.\n"
609 " You may try running this binary with -trace_malloc=[12]"
610 " to get a trace of mallocs and frees.\n"
611 " If LeakSanitizer is enabled in this process it will still\n"
612 " run on the process shutdown.\n");
613 return;
614 }
615 // Now perform the actual lsan pass. This is expensive and we must ensure
616 // we don't call it too often.
617 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
618 if (DuringInitialCorpusExecution)
619 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
620 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
621 CurrentUnitSize = Size;
622 DumpCurrentUnit("leak-");
623 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000624 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000625 }
626}
627
628void Fuzzer::MutateAndTestOne() {
629 MD.StartMutationSequence();
630
631 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
632 const auto &U = II.U;
633 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
634 assert(CurrentUnitData);
635 size_t Size = U.size();
636 assert(Size <= MaxInputLen && "Oversized Unit");
637 memcpy(CurrentUnitData, U.data(), Size);
638
639 assert(MaxMutationLen > 0);
640
641 size_t CurrentMaxMutationLen =
642 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
643 assert(CurrentMaxMutationLen > 0);
644
645 for (int i = 0; i < Options.MutateDepth; i++) {
646 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
647 break;
kcc1239a992017-11-09 20:30:19 +0000648 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000649 size_t NewSize = 0;
kcc0cab3f02018-07-19 01:23:32 +0000650 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
651 Size <= CurrentMaxMutationLen)
652 NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
653 II.DataFlowTraceForFocusFunction);
654 else
655 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000656 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000657 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000658 Size = NewSize;
659 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000660
kccb6836be2017-12-01 19:18:38 +0000661 bool FoundUniqFeatures = false;
662 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
663 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000664 TryDetectingAMemoryLeak(CurrentUnitData, Size,
665 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000666 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000667 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000668 break; // We will mutate this input more in the next rounds.
669 }
670 if (Options.ReduceDepth && !FoundUniqFeatures)
dor1se6729cb2018-07-16 15:15:34 +0000671 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000672 }
673}
674
alekseyshld995b552017-10-23 22:04:30 +0000675void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000676 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000677 return;
alekseyshld995b552017-10-23 22:04:30 +0000678 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000679 LastAllocatorPurgeAttemptTime)
680 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000681 return;
alekseyshld995b552017-10-23 22:04:30 +0000682
683 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000684 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000685 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000686
687 LastAllocatorPurgeAttemptTime = system_clock::now();
688}
689
kcc2e93b3f2017-08-29 02:05:01 +0000690void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
691 const size_t kMaxSaneLen = 1 << 20;
692 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000693 Vector<SizedFile> SizedFiles;
694 size_t MaxSize = 0;
695 size_t MinSize = -1;
696 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000697 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000698 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000699 GetSizedFilesFromDir(Dir, &SizedFiles);
700 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
701 Dir.c_str());
702 LastNumFiles = SizedFiles.size();
703 }
704 for (auto &File : SizedFiles) {
705 MaxSize = Max(File.Size, MaxSize);
706 MinSize = Min(File.Size, MinSize);
707 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000708 }
kccdc00cd32017-08-29 20:51:24 +0000709 if (Options.MaxLen == 0)
710 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
711 assert(MaxInputLen > 0);
712
kcc2cd9f092017-10-13 01:12:23 +0000713 // Test the callback with empty input and never try it again.
714 uint8_t dummy = 0;
715 ExecuteCallback(&dummy, 0);
716
kccdc00cd32017-08-29 20:51:24 +0000717 if (SizedFiles.empty()) {
718 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
719 Unit U({'\n'}); // Valid ASCII input.
720 RunOne(U.data(), U.size());
721 } else {
722 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
723 " rss: %zdMb\n",
724 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
725 if (Options.ShuffleAtStartUp)
726 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
727
kcc7f5f2222017-09-12 21:58:07 +0000728 if (Options.PreferSmall) {
729 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
730 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
731 }
kccdc00cd32017-08-29 20:51:24 +0000732
733 // Load and execute inputs one by one.
734 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000735 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000736 assert(U.size() <= MaxInputLen);
737 RunOne(U.data(), U.size());
738 CheckExitOnSrcPosOrItem();
739 TryDetectingAMemoryLeak(U.data(), U.size(),
740 /*DuringInitialCorpusExecution*/ true);
741 }
kcc2e93b3f2017-08-29 02:05:01 +0000742 }
743
kccdc00cd32017-08-29 20:51:24 +0000744 PrintStats("INITED");
kcc3acbe072018-05-16 23:26:37 +0000745 if (!Options.FocusFunction.empty())
746 Printf("INFO: %zd/%zd inputs touch the focus function\n",
747 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
kccadf188b2018-06-07 01:40:20 +0000748 if (!Options.DataFlowTrace.empty())
749 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
750 Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
kcc3acbe072018-05-16 23:26:37 +0000751
dor1s770a9bc2018-05-23 19:42:30 +0000752 if (Corpus.empty() && Options.MaxNumberOfRuns) {
kccdc00cd32017-08-29 20:51:24 +0000753 Printf("ERROR: no interesting inputs were found. "
754 "Is the code instrumented for coverage? Exiting.\n");
755 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000756 }
kcc2e93b3f2017-08-29 02:05:01 +0000757}
758
759void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
760 ReadAndExecuteSeedCorpora(CorpusDirs);
kccadf188b2018-06-07 01:40:20 +0000761 DFT.Clear(); // No need for DFT any more.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000762 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000763 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000764 system_clock::time_point LastCorpusReload = system_clock::now();
765 if (Options.DoCrossOver)
766 MD.SetCorpus(&Corpus);
767 while (true) {
768 auto Now = system_clock::now();
769 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
770 Options.ReloadIntervalSec) {
771 RereadOutputCorpus(MaxInputLen);
772 LastCorpusReload = system_clock::now();
773 }
774 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
775 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000776 if (TimedOut())
777 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000778
779 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000780 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000781 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000782 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000783 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000784 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000785 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000786 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000787 }
788 } else {
789 TmpMaxMutationLen = MaxMutationLen;
790 }
791
792 // Perform several mutations and runs.
793 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000794
795 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000796 }
797
798 PrintStats("DONE ", "\n");
799 MD.PrintRecommendedDictionary();
800}
801
802void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000803 if (U.size() <= 1)
804 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000805 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
806 MD.StartMutationSequence();
807 memcpy(CurrentUnitData, U.data(), U.size());
808 for (int i = 0; i < Options.MutateDepth; i++) {
809 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
810 assert(NewSize > 0 && NewSize <= MaxMutationLen);
811 ExecuteCallback(CurrentUnitData, NewSize);
812 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
813 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
814 /*DuringInitialCorpusExecution*/ false);
815 }
816 }
817}
818
george.karpenkov29efa6d2017-08-21 23:25:50 +0000819} // namespace fuzzer
820
821extern "C" {
822
metzman2fe66e62019-01-17 16:36:05 +0000823ATTRIBUTE_INTERFACE size_t
phosek966475e2018-01-17 20:39:14 +0000824LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000825 assert(fuzzer::F);
826 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
827}
828
alekseyshl9f6a9f22017-10-23 23:24:33 +0000829} // extern "C"