blob: 23fcb8a402d46d14649e94ace2c7f5752e7367de [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +00001//===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// Fuzzer's main loop.
10//===----------------------------------------------------------------------===//
11
12#include "FuzzerCorpus.h"
13#include "FuzzerIO.h"
14#include "FuzzerInternal.h"
15#include "FuzzerMutate.h"
16#include "FuzzerRandom.h"
17#include "FuzzerShmem.h"
18#include "FuzzerTracePC.h"
19#include <algorithm>
20#include <cstring>
21#include <memory>
vitalybukab3e5a2c2017-11-01 03:02:59 +000022#include <mutex>
george.karpenkov29efa6d2017-08-21 23:25:50 +000023#include <set>
24
25#if defined(__has_include)
26#if __has_include(<sanitizer / lsan_interface.h>)
27#include <sanitizer/lsan_interface.h>
28#endif
29#endif
30
31#define NO_SANITIZE_MEMORY
32#if defined(__has_feature)
33#if __has_feature(memory_sanitizer)
34#undef NO_SANITIZE_MEMORY
35#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
36#endif
37#endif
38
39namespace fuzzer {
40static const size_t kMaxUnitSizeToPrint = 256;
dor1s9dfdc272018-08-02 22:30:03 +000041static const size_t kUpdateMutationWeightRuns = 10000;
george.karpenkov29efa6d2017-08-21 23:25:50 +000042
43thread_local bool Fuzzer::IsMyThread;
44
45SharedMemoryRegion SMR;
46
morehousec6ee8752018-07-17 16:12:00 +000047bool RunningUserCallback = false;
48
george.karpenkov29efa6d2017-08-21 23:25:50 +000049// Only one Fuzzer per process.
50static Fuzzer *F;
51
52// Leak detection is expensive, so we first check if there were more mallocs
53// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
54struct MallocFreeTracer {
55 void Start(int TraceLevel) {
56 this->TraceLevel = TraceLevel;
57 if (TraceLevel)
58 Printf("MallocFreeTracer: START\n");
59 Mallocs = 0;
60 Frees = 0;
61 }
62 // Returns true if there were more mallocs than frees.
63 bool Stop() {
64 if (TraceLevel)
65 Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
66 Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
67 bool Result = Mallocs > Frees;
68 Mallocs = 0;
69 Frees = 0;
70 TraceLevel = 0;
71 return Result;
72 }
73 std::atomic<size_t> Mallocs;
74 std::atomic<size_t> Frees;
75 int TraceLevel = 0;
vitalybukae6504cf2017-11-02 04:12:10 +000076
77 std::recursive_mutex TraceMutex;
78 bool TraceDisabled = false;
george.karpenkov29efa6d2017-08-21 23:25:50 +000079};
80
81static MallocFreeTracer AllocTracer;
82
vitalybukae6504cf2017-11-02 04:12:10 +000083// Locks printing and avoids nested hooks triggered from mallocs/frees in
84// sanitizer.
85class TraceLock {
86public:
87 TraceLock() : Lock(AllocTracer.TraceMutex) {
88 AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
89 }
90 ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
91
92 bool IsDisabled() const {
93 // This is already inverted value.
94 return !AllocTracer.TraceDisabled;
95 }
96
97private:
98 std::lock_guard<std::recursive_mutex> Lock;
99};
vitalybukab3e5a2c2017-11-01 03:02:59 +0000100
george.karpenkov29efa6d2017-08-21 23:25:50 +0000101ATTRIBUTE_NO_SANITIZE_MEMORY
102void MallocHook(const volatile void *ptr, size_t size) {
103 size_t N = AllocTracer.Mallocs++;
104 F->HandleMalloc(size);
105 if (int TraceLevel = AllocTracer.TraceLevel) {
vitalybukae6504cf2017-11-02 04:12:10 +0000106 TraceLock Lock;
107 if (Lock.IsDisabled())
108 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000109 Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
110 if (TraceLevel >= 2 && EF)
morehousebd67cc22018-05-08 23:45:05 +0000111 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000112 }
113}
114
115ATTRIBUTE_NO_SANITIZE_MEMORY
116void FreeHook(const volatile void *ptr) {
117 size_t N = AllocTracer.Frees++;
118 if (int TraceLevel = AllocTracer.TraceLevel) {
vitalybukae6504cf2017-11-02 04:12:10 +0000119 TraceLock Lock;
120 if (Lock.IsDisabled())
121 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000122 Printf("FREE[%zd] %p\n", N, ptr);
123 if (TraceLevel >= 2 && EF)
morehousebd67cc22018-05-08 23:45:05 +0000124 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000125 }
126}
127
128// Crash on a single malloc that exceeds the rss limit.
129void Fuzzer::HandleMalloc(size_t Size) {
kcc120e40b2017-12-01 22:12:04 +0000130 if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000131 return;
132 Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
133 Size);
134 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000135 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000136 DumpCurrentUnit("oom-");
137 Printf("SUMMARY: libFuzzer: out-of-memory\n");
138 PrintFinalStats();
139 _Exit(Options.ErrorExitCode); // Stop right now.
140}
141
142Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
143 FuzzingOptions Options)
144 : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
145 if (EF->__sanitizer_set_death_callback)
146 EF->__sanitizer_set_death_callback(StaticDeathCallback);
147 assert(!F);
148 F = this;
149 TPC.ResetMaps();
150 IsMyThread = true;
151 if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
152 EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
153 TPC.SetUseCounters(Options.UseCounters);
kcc3850d062018-07-03 22:33:09 +0000154 TPC.SetUseValueProfileMask(Options.UseValueProfile);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000155
156 if (Options.Verbosity)
157 TPC.PrintModuleInfo();
158 if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
159 EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
160 MaxInputLen = MaxMutationLen = Options.MaxLen;
161 TmpMaxMutationLen = Max(size_t(4), Corpus.MaxInputSize());
162 AllocateCurrentUnitData();
163 CurrentUnitSize = 0;
164 memset(BaseSha1, 0, sizeof(BaseSha1));
kcc3acbe072018-05-16 23:26:37 +0000165 TPC.SetFocusFunction(Options.FocusFunction);
kcc86e43882018-06-06 01:23:29 +0000166 DFT.Init(Options.DataFlowTrace, Options.FocusFunction);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000167}
168
alekseyshl9f6a9f22017-10-23 23:24:33 +0000169Fuzzer::~Fuzzer() {}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000170
171void Fuzzer::AllocateCurrentUnitData() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000172 if (CurrentUnitData || MaxInputLen == 0)
173 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000174 CurrentUnitData = new uint8_t[MaxInputLen];
175}
176
177void Fuzzer::StaticDeathCallback() {
178 assert(F);
179 F->DeathCallback();
180}
181
182void Fuzzer::DumpCurrentUnit(const char *Prefix) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000183 if (!CurrentUnitData)
184 return; // Happens when running individual inputs.
morehouse1467b792018-07-09 23:51:08 +0000185 ScopedDisableMsanInterceptorChecks S;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000186 MD.PrintMutationSequence();
187 Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
188 size_t UnitSize = CurrentUnitSize;
189 if (UnitSize <= kMaxUnitSizeToPrint) {
190 PrintHexArray(CurrentUnitData, UnitSize, "\n");
191 PrintASCII(CurrentUnitData, UnitSize, "\n");
192 }
193 WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
194 Prefix);
195}
196
197NO_SANITIZE_MEMORY
198void Fuzzer::DeathCallback() {
199 DumpCurrentUnit("crash-");
200 PrintFinalStats();
201}
202
203void Fuzzer::StaticAlarmCallback() {
204 assert(F);
205 F->AlarmCallback();
206}
207
208void Fuzzer::StaticCrashSignalCallback() {
209 assert(F);
210 F->CrashCallback();
211}
212
213void 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.
279#if !LIBFUZZER_WINDOWS
alekseyshl9f6a9f22017-10-23 23:24:33 +0000280 if (!InFuzzingThread())
281 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000282#endif
morehousec6ee8752018-07-17 16:12:00 +0000283 if (!RunningUserCallback)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000284 return; // We have not started running units yet.
285 size_t Seconds =
286 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
287 if (Seconds == 0)
288 return;
289 if (Options.Verbosity >= 2)
290 Printf("AlarmCallback %zd\n", Seconds);
291 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
morehouse5a4566a2018-05-01 21:01:53 +0000292 if (EF->__sanitizer_acquire_crash_state &&
293 !EF->__sanitizer_acquire_crash_state())
294 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000295 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
296 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
297 Options.UnitTimeoutSec);
298 DumpCurrentUnit("timeout-");
299 Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
300 Seconds);
morehousebd67cc22018-05-08 23:45:05 +0000301 PrintStackTrace();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000302 Printf("SUMMARY: libFuzzer: timeout\n");
303 PrintFinalStats();
304 _Exit(Options.TimeoutExitCode); // Stop right now.
305 }
306}
307
308void Fuzzer::RssLimitCallback() {
morehouse5a4566a2018-05-01 21:01:53 +0000309 if (EF->__sanitizer_acquire_crash_state &&
310 !EF->__sanitizer_acquire_crash_state())
311 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000312 Printf(
313 "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
314 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
315 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
morehousebd67cc22018-05-08 23:45:05 +0000316 PrintMemoryProfile();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000317 DumpCurrentUnit("oom-");
318 Printf("SUMMARY: libFuzzer: out-of-memory\n");
319 PrintFinalStats();
320 _Exit(Options.ErrorExitCode); // Stop right now.
321}
322
323void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) {
324 size_t ExecPerSec = execPerSec();
325 if (!Options.Verbosity)
326 return;
327 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
328 if (size_t N = TPC.GetTotalPCCoverage())
329 Printf(" cov: %zd", N);
330 if (size_t N = Corpus.NumFeatures())
alekseyshl9f6a9f22017-10-23 23:24:33 +0000331 Printf(" ft: %zd", N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000332 if (!Corpus.empty()) {
333 Printf(" corp: %zd", Corpus.NumActiveUnits());
334 if (size_t N = Corpus.SizeInBytes()) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000335 if (N < (1 << 14))
george.karpenkov29efa6d2017-08-21 23:25:50 +0000336 Printf("/%zdb", N);
337 else if (N < (1 << 24))
338 Printf("/%zdKb", N >> 10);
339 else
340 Printf("/%zdMb", N >> 20);
341 }
kcc3acbe072018-05-16 23:26:37 +0000342 if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
343 Printf(" focus: %zd", FF);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000344 }
morehousea6c692c2018-02-22 19:00:17 +0000345 if (TmpMaxMutationLen)
346 Printf(" lim: %zd", TmpMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000347 if (Units)
348 Printf(" units: %zd", Units);
349
350 Printf(" exec/s: %zd", ExecPerSec);
351 Printf(" rss: %zdMb", GetPeakRSSMb());
352 Printf("%s", End);
353}
354
355void Fuzzer::PrintFinalStats() {
356 if (Options.PrintCoverage)
357 TPC.PrintCoverage();
dor1sbb933292018-07-16 16:01:31 +0000358 if (Options.PrintUnstableStats)
359 TPC.PrintUnstableStats();
kcca7dd2a92018-05-21 19:47:00 +0000360 if (Options.DumpCoverage)
361 TPC.DumpCoverage();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000362 if (Options.PrintCorpusStats)
363 Corpus.PrintStats();
dor1s2f728942018-07-17 20:37:40 +0000364 if (Options.PrintMutationStats) MD.PrintMutationStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000365 if (!Options.PrintFinalStats)
366 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000367 size_t ExecPerSec = execPerSec();
368 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
369 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
370 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
371 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
372 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
373}
374
375void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
376 assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
377 assert(MaxInputLen);
378 this->MaxInputLen = MaxInputLen;
379 this->MaxMutationLen = MaxInputLen;
380 AllocateCurrentUnitData();
381 Printf("INFO: -max_len is not provided; "
382 "libFuzzer will not generate inputs larger than %zd bytes\n",
383 MaxInputLen);
384}
385
386void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
387 assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
388 this->MaxMutationLen = MaxMutationLen;
389}
390
391void Fuzzer::CheckExitOnSrcPosOrItem() {
392 if (!Options.ExitOnSrcPos.empty()) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000393 static auto *PCsSet = new Set<uintptr_t>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000394 auto HandlePC = [&](uintptr_t PC) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000395 if (!PCsSet->insert(PC).second)
396 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000397 std::string Descr = DescribePC("%F %L", PC + 1);
398 if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
399 Printf("INFO: found line matching '%s', exiting.\n",
400 Options.ExitOnSrcPos.c_str());
401 _Exit(0);
402 }
403 };
404 TPC.ForEachObservedPC(HandlePC);
405 }
406 if (!Options.ExitOnItem.empty()) {
407 if (Corpus.HasUnit(Options.ExitOnItem)) {
408 Printf("INFO: found item with checksum '%s', exiting.\n",
409 Options.ExitOnItem.c_str());
410 _Exit(0);
411 }
412 }
413}
414
415void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000416 if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
417 return;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000418 Vector<Unit> AdditionalCorpus;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000419 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
420 &EpochOfLastReadOfOutputCorpus, MaxSize,
421 /*ExitOnError*/ false);
422 if (Options.Verbosity >= 2)
423 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
424 bool Reloaded = false;
425 for (auto &U : AdditionalCorpus) {
426 if (U.size() > MaxSize)
427 U.resize(MaxSize);
428 if (!Corpus.HasUnit(U)) {
429 if (RunOne(U.data(), U.size())) {
430 CheckExitOnSrcPosOrItem();
431 Reloaded = true;
432 }
433 }
434 }
435 if (Reloaded)
436 PrintStats("RELOAD");
437}
438
george.karpenkov29efa6d2017-08-21 23:25:50 +0000439void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
440 auto TimeOfUnit =
441 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
442 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
443 secondsSinceProcessStartUp() >= 2)
444 PrintStats("pulse ");
445 if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 &&
446 TimeOfUnit >= Options.ReportSlowUnits) {
447 TimeOfLongestUnitInSeconds = TimeOfUnit;
448 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
449 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
450 }
451}
452
dor1sbb933292018-07-16 16:01:31 +0000453void Fuzzer::CheckForUnstableCounters(const uint8_t *Data, size_t Size) {
454 auto CBSetupAndRun = [&]() {
455 ScopedEnableMsanInterceptorChecks S;
456 UnitStartTime = system_clock::now();
457 TPC.ResetMaps();
morehousec6ee8752018-07-17 16:12:00 +0000458 RunningUserCallback = true;
dor1sbb933292018-07-16 16:01:31 +0000459 CB(Data, Size);
morehousec6ee8752018-07-17 16:12:00 +0000460 RunningUserCallback = false;
dor1sbb933292018-07-16 16:01:31 +0000461 UnitStopTime = system_clock::now();
462 };
463
464 // Copy original run counters into our unstable counters
465 TPC.InitializeUnstableCounters();
466
467 // First Rerun
468 CBSetupAndRun();
dor1sf50b3bb2018-07-23 14:20:52 +0000469 TPC.UpdateUnstableCounters(Options.HandleUnstable);
dor1sbb933292018-07-16 16:01:31 +0000470
471 // Second Rerun
472 CBSetupAndRun();
dor1sf50b3bb2018-07-23 14:20:52 +0000473 TPC.UpdateUnstableCounters(Options.HandleUnstable);
474
475 // Move minimum hit counts back to ModuleInline8bitCounters
dor1sd6266262018-07-24 21:02:44 +0000476 if (Options.HandleUnstable == TracePC::MinUnstable ||
477 Options.HandleUnstable == TracePC::ZeroUnstable)
dor1sf50b3bb2018-07-23 14:20:52 +0000478 TPC.ApplyUnstableCounters();
dor1sbb933292018-07-16 16:01:31 +0000479}
480
george.karpenkov29efa6d2017-08-21 23:25:50 +0000481bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
kccb6836be2017-12-01 19:18:38 +0000482 InputInfo *II, bool *FoundUniqFeatures) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000483 if (!Size)
484 return false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000485
486 ExecuteCallback(Data, Size);
487
488 UniqFeatureSetTmp.clear();
489 size_t FoundUniqFeaturesOfII = 0;
490 size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
dor1sf50b3bb2018-07-23 14:20:52 +0000491 bool NewFeaturesUnstable = false;
492
493 if (Options.HandleUnstable || Options.PrintUnstableStats) {
494 TPC.CollectFeatures([&](size_t Feature) {
495 if (Corpus.IsFeatureNew(Feature, Size, Options.Shrink))
496 NewFeaturesUnstable = true;
497 });
498 if (NewFeaturesUnstable)
499 CheckForUnstableCounters(Data, Size);
500 }
501
george.karpenkov29efa6d2017-08-21 23:25:50 +0000502 TPC.CollectFeatures([&](size_t Feature) {
503 if (Corpus.AddFeature(Feature, Size, Options.Shrink))
504 UniqFeatureSetTmp.push_back(Feature);
505 if (Options.ReduceInputs && II)
506 if (std::binary_search(II->UniqFeatureSet.begin(),
507 II->UniqFeatureSet.end(), Feature))
508 FoundUniqFeaturesOfII++;
509 });
dor1sf50b3bb2018-07-23 14:20:52 +0000510
kccb6836be2017-12-01 19:18:38 +0000511 if (FoundUniqFeatures)
512 *FoundUniqFeatures = FoundUniqFeaturesOfII;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000513 PrintPulseAndReportSlowInput(Data, Size);
514 size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
dor1sbb933292018-07-16 16:01:31 +0000515
george.karpenkov29efa6d2017-08-21 23:25:50 +0000516 if (NumNewFeatures) {
517 TPC.UpdateObservedPCs();
518 Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
kcc0cab3f02018-07-19 01:23:32 +0000519 TPC.ObservedFocusFunction(), UniqFeatureSetTmp, DFT, II);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000520 return true;
521 }
522 if (II && FoundUniqFeaturesOfII &&
kccadf188b2018-06-07 01:40:20 +0000523 II->DataFlowTraceForFocusFunction.empty() &&
george.karpenkov29efa6d2017-08-21 23:25:50 +0000524 FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
525 II->U.size() > Size) {
526 Corpus.Replace(II, {Data, Data + Size});
527 return true;
528 }
529 return false;
530}
531
532size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
533 assert(InFuzzingThread());
534 *Data = CurrentUnitData;
535 return CurrentUnitSize;
536}
537
538void Fuzzer::CrashOnOverwrittenData() {
539 Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n",
540 GetPid());
541 DumpCurrentUnit("crash-");
542 Printf("SUMMARY: libFuzzer: out-of-memory\n");
543 _Exit(Options.ErrorExitCode); // Stop right now.
544}
545
546// Compare two arrays, but not all bytes if the arrays are large.
547static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
548 const size_t Limit = 64;
549 if (Size <= 64)
550 return !memcmp(A, B, Size);
551 // Compare first and last Limit/2 bytes.
552 return !memcmp(A, B, Limit / 2) &&
553 !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
554}
555
556void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
557 TPC.RecordInitialStack();
dor1s9dfdc272018-08-02 22:30:03 +0000558 if (Options.UseWeightedMutations &&
559 TotalNumberOfRuns % kUpdateMutationWeightRuns == 0)
560 MD.UpdateDistribution();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000561 TotalNumberOfRuns++;
562 assert(InFuzzingThread());
563 if (SMR.IsClient())
564 SMR.WriteByteArray(Data, Size);
565 // We copy the contents of Unit into a separate heap buffer
566 // so that we reliably find buffer overflows in it.
567 uint8_t *DataCopy = new uint8_t[Size];
568 memcpy(DataCopy, Data, Size);
morehouse1467b792018-07-09 23:51:08 +0000569 if (EF->__msan_unpoison)
570 EF->__msan_unpoison(DataCopy, Size);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000571 if (CurrentUnitData && CurrentUnitData != Data)
572 memcpy(CurrentUnitData, Data, Size);
573 CurrentUnitSize = Size;
morehouse1467b792018-07-09 23:51:08 +0000574 {
575 ScopedEnableMsanInterceptorChecks S;
576 AllocTracer.Start(Options.TraceMalloc);
577 UnitStartTime = system_clock::now();
578 TPC.ResetMaps();
morehousec6ee8752018-07-17 16:12:00 +0000579 RunningUserCallback = true;
morehouse1467b792018-07-09 23:51:08 +0000580 int Res = CB(DataCopy, Size);
morehousec6ee8752018-07-17 16:12:00 +0000581 RunningUserCallback = false;
morehouse1467b792018-07-09 23:51:08 +0000582 UnitStopTime = system_clock::now();
583 (void)Res;
584 assert(Res == 0);
585 HasMoreMallocsThanFrees = AllocTracer.Stop();
586 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000587 if (!LooseMemeq(DataCopy, Data, Size))
588 CrashOnOverwrittenData();
589 CurrentUnitSize = 0;
590 delete[] DataCopy;
591}
592
593void Fuzzer::WriteToOutputCorpus(const Unit &U) {
594 if (Options.OnlyASCII)
595 assert(IsASCII(U));
596 if (Options.OutputCorpus.empty())
597 return;
598 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
599 WriteToFile(U, Path);
600 if (Options.Verbosity >= 2)
601 Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
602}
603
604void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
605 if (!Options.SaveArtifacts)
606 return;
607 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
608 if (!Options.ExactArtifactPath.empty())
609 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
610 WriteToFile(U, Path);
611 Printf("artifact_prefix='%s'; Test unit written to %s\n",
612 Options.ArtifactPrefix.c_str(), Path.c_str());
613 if (U.size() <= kMaxUnitSizeToPrint)
614 Printf("Base64: %s\n", Base64(U).c_str());
615}
616
617void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
618 if (!Options.PrintNEW)
619 return;
620 PrintStats(Text, "");
621 if (Options.Verbosity) {
622 Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
623 MD.PrintMutationSequence();
624 Printf("\n");
625 }
626}
627
628void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
629 II->NumSuccessfullMutations++;
630 MD.RecordSuccessfulMutationSequence();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000631 PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000632 WriteToOutputCorpus(U);
633 NumberOfNewUnitsAdded++;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000634 CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000635 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000636}
637
638// Tries detecting a memory leak on the particular input that we have just
639// executed before calling this function.
640void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
641 bool DuringInitialCorpusExecution) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000642 if (!HasMoreMallocsThanFrees)
643 return; // mallocs==frees, a leak is unlikely.
644 if (!Options.DetectLeaks)
645 return;
dor1s38279cb2017-09-12 02:01:54 +0000646 if (!DuringInitialCorpusExecution &&
alekseyshl9f6a9f22017-10-23 23:24:33 +0000647 TotalNumberOfRuns >= Options.MaxNumberOfRuns)
648 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000649 if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
650 !(EF->__lsan_do_recoverable_leak_check))
alekseyshl9f6a9f22017-10-23 23:24:33 +0000651 return; // No lsan.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000652 // Run the target once again, but with lsan disabled so that if there is
653 // a real leak we do not report it twice.
654 EF->__lsan_disable();
655 ExecuteCallback(Data, Size);
656 EF->__lsan_enable();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000657 if (!HasMoreMallocsThanFrees)
658 return; // a leak is unlikely.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000659 if (NumberOfLeakDetectionAttempts++ > 1000) {
660 Options.DetectLeaks = false;
661 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
662 " Most likely the target function accumulates allocated\n"
663 " memory in a global state w/o actually leaking it.\n"
664 " You may try running this binary with -trace_malloc=[12]"
665 " to get a trace of mallocs and frees.\n"
666 " If LeakSanitizer is enabled in this process it will still\n"
667 " run on the process shutdown.\n");
668 return;
669 }
670 // Now perform the actual lsan pass. This is expensive and we must ensure
671 // we don't call it too often.
672 if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
673 if (DuringInitialCorpusExecution)
674 Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
675 Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
676 CurrentUnitSize = Size;
677 DumpCurrentUnit("leak-");
678 PrintFinalStats();
alekseyshl9f6a9f22017-10-23 23:24:33 +0000679 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000680 }
681}
682
683void Fuzzer::MutateAndTestOne() {
684 MD.StartMutationSequence();
685
686 auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
687 const auto &U = II.U;
688 memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
689 assert(CurrentUnitData);
690 size_t Size = U.size();
691 assert(Size <= MaxInputLen && "Oversized Unit");
692 memcpy(CurrentUnitData, U.data(), Size);
693
694 assert(MaxMutationLen > 0);
695
696 size_t CurrentMaxMutationLen =
697 Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
698 assert(CurrentMaxMutationLen > 0);
699
700 for (int i = 0; i < Options.MutateDepth; i++) {
701 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
702 break;
kcc1239a992017-11-09 20:30:19 +0000703 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000704 size_t NewSize = 0;
kcc0cab3f02018-07-19 01:23:32 +0000705 if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
706 Size <= CurrentMaxMutationLen)
707 NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
708 II.DataFlowTraceForFocusFunction);
709 else
710 NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000711 assert(NewSize > 0 && "Mutator returned empty unit");
alekseyshld995b552017-10-23 22:04:30 +0000712 assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000713 Size = NewSize;
714 II.NumExecutedMutations++;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000715
kccb6836be2017-12-01 19:18:38 +0000716 bool FoundUniqFeatures = false;
717 bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
718 &FoundUniqFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000719 TryDetectingAMemoryLeak(CurrentUnitData, Size,
720 /*DuringInitialCorpusExecution*/ false);
kccb6836be2017-12-01 19:18:38 +0000721 if (NewCov) {
morehouse553f00b2017-11-09 20:44:08 +0000722 ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
kccb6836be2017-12-01 19:18:38 +0000723 break; // We will mutate this input more in the next rounds.
724 }
725 if (Options.ReduceDepth && !FoundUniqFeatures)
dor1se6729cb2018-07-16 15:15:34 +0000726 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000727 }
728}
729
alekseyshld995b552017-10-23 22:04:30 +0000730void Fuzzer::PurgeAllocator() {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000731 if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
alekseyshld995b552017-10-23 22:04:30 +0000732 return;
alekseyshld995b552017-10-23 22:04:30 +0000733 if (duration_cast<seconds>(system_clock::now() -
alekseyshl9f6a9f22017-10-23 23:24:33 +0000734 LastAllocatorPurgeAttemptTime)
735 .count() < Options.PurgeAllocatorIntervalSec)
alekseyshld995b552017-10-23 22:04:30 +0000736 return;
alekseyshld995b552017-10-23 22:04:30 +0000737
738 if (Options.RssLimitMb <= 0 ||
alekseyshl9f6a9f22017-10-23 23:24:33 +0000739 GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
alekseyshld995b552017-10-23 22:04:30 +0000740 EF->__sanitizer_purge_allocator();
alekseyshld995b552017-10-23 22:04:30 +0000741
742 LastAllocatorPurgeAttemptTime = system_clock::now();
743}
744
kcc2e93b3f2017-08-29 02:05:01 +0000745void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) {
746 const size_t kMaxSaneLen = 1 << 20;
747 const size_t kMinDefaultLen = 4096;
kccdc00cd32017-08-29 20:51:24 +0000748 Vector<SizedFile> SizedFiles;
749 size_t MaxSize = 0;
750 size_t MinSize = -1;
751 size_t TotalSize = 0;
kcc7f5f2222017-09-12 21:58:07 +0000752 size_t LastNumFiles = 0;
kccdc00cd32017-08-29 20:51:24 +0000753 for (auto &Dir : CorpusDirs) {
kcc7f5f2222017-09-12 21:58:07 +0000754 GetSizedFilesFromDir(Dir, &SizedFiles);
755 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles,
756 Dir.c_str());
757 LastNumFiles = SizedFiles.size();
758 }
759 for (auto &File : SizedFiles) {
760 MaxSize = Max(File.Size, MaxSize);
761 MinSize = Min(File.Size, MinSize);
762 TotalSize += File.Size;
kcc2e93b3f2017-08-29 02:05:01 +0000763 }
kccdc00cd32017-08-29 20:51:24 +0000764 if (Options.MaxLen == 0)
765 SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
766 assert(MaxInputLen > 0);
767
kcc2cd9f092017-10-13 01:12:23 +0000768 // Test the callback with empty input and never try it again.
769 uint8_t dummy = 0;
770 ExecuteCallback(&dummy, 0);
771
kccdc00cd32017-08-29 20:51:24 +0000772 if (SizedFiles.empty()) {
773 Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
774 Unit U({'\n'}); // Valid ASCII input.
775 RunOne(U.data(), U.size());
776 } else {
777 Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
778 " rss: %zdMb\n",
779 SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
780 if (Options.ShuffleAtStartUp)
781 std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand());
782
kcc7f5f2222017-09-12 21:58:07 +0000783 if (Options.PreferSmall) {
784 std::stable_sort(SizedFiles.begin(), SizedFiles.end());
785 assert(SizedFiles.front().Size <= SizedFiles.back().Size);
786 }
kccdc00cd32017-08-29 20:51:24 +0000787
788 // Load and execute inputs one by one.
789 for (auto &SF : SizedFiles) {
kccae85e292017-08-31 19:17:15 +0000790 auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
kccdc00cd32017-08-29 20:51:24 +0000791 assert(U.size() <= MaxInputLen);
792 RunOne(U.data(), U.size());
793 CheckExitOnSrcPosOrItem();
794 TryDetectingAMemoryLeak(U.data(), U.size(),
795 /*DuringInitialCorpusExecution*/ true);
796 }
kcc2e93b3f2017-08-29 02:05:01 +0000797 }
798
kccdc00cd32017-08-29 20:51:24 +0000799 PrintStats("INITED");
kcc3acbe072018-05-16 23:26:37 +0000800 if (!Options.FocusFunction.empty())
801 Printf("INFO: %zd/%zd inputs touch the focus function\n",
802 Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
kccadf188b2018-06-07 01:40:20 +0000803 if (!Options.DataFlowTrace.empty())
804 Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
805 Corpus.NumInputsWithDataFlowTrace(), Corpus.size());
kcc3acbe072018-05-16 23:26:37 +0000806
dor1s770a9bc2018-05-23 19:42:30 +0000807 if (Corpus.empty() && Options.MaxNumberOfRuns) {
kccdc00cd32017-08-29 20:51:24 +0000808 Printf("ERROR: no interesting inputs were found. "
809 "Is the code instrumented for coverage? Exiting.\n");
810 exit(1);
kcc2e93b3f2017-08-29 02:05:01 +0000811 }
kcc2e93b3f2017-08-29 02:05:01 +0000812}
813
814void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) {
815 ReadAndExecuteSeedCorpora(CorpusDirs);
kccadf188b2018-06-07 01:40:20 +0000816 DFT.Clear(); // No need for DFT any more.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000817 TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
kcc00da6482017-08-25 20:09:25 +0000818 TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000819 system_clock::time_point LastCorpusReload = system_clock::now();
820 if (Options.DoCrossOver)
821 MD.SetCorpus(&Corpus);
822 while (true) {
823 auto Now = system_clock::now();
824 if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
825 Options.ReloadIntervalSec) {
826 RereadOutputCorpus(MaxInputLen);
827 LastCorpusReload = system_clock::now();
828 }
829 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
830 break;
alekseyshl9f6a9f22017-10-23 23:24:33 +0000831 if (TimedOut())
832 break;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000833
834 // Update TmpMaxMutationLen
morehouse8c42ada2018-02-13 20:52:15 +0000835 if (Options.LenControl) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000836 if (TmpMaxMutationLen < MaxMutationLen &&
kcce29d7e32017-12-12 23:11:28 +0000837 TotalNumberOfRuns - LastCorpusUpdateRun >
morehouse8c42ada2018-02-13 20:52:15 +0000838 Options.LenControl * Log(TmpMaxMutationLen)) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000839 TmpMaxMutationLen =
kcce29d7e32017-12-12 23:11:28 +0000840 Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
kcce29d7e32017-12-12 23:11:28 +0000841 LastCorpusUpdateRun = TotalNumberOfRuns;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000842 }
843 } else {
844 TmpMaxMutationLen = MaxMutationLen;
845 }
846
847 // Perform several mutations and runs.
848 MutateAndTestOne();
alekseyshld995b552017-10-23 22:04:30 +0000849
850 PurgeAllocator();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000851 }
852
853 PrintStats("DONE ", "\n");
854 MD.PrintRecommendedDictionary();
855}
856
857void Fuzzer::MinimizeCrashLoop(const Unit &U) {
alekseyshl9f6a9f22017-10-23 23:24:33 +0000858 if (U.size() <= 1)
859 return;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000860 while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
861 MD.StartMutationSequence();
862 memcpy(CurrentUnitData, U.data(), U.size());
863 for (int i = 0; i < Options.MutateDepth; i++) {
864 size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
865 assert(NewSize > 0 && NewSize <= MaxMutationLen);
866 ExecuteCallback(CurrentUnitData, NewSize);
867 PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
868 TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
869 /*DuringInitialCorpusExecution*/ false);
870 }
871 }
872}
873
874void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) {
875 if (SMR.IsServer()) {
876 SMR.WriteByteArray(Data, Size);
877 } else if (SMR.IsClient()) {
878 SMR.PostClient();
879 SMR.WaitServer();
880 size_t OtherSize = SMR.ReadByteArraySize();
881 uint8_t *OtherData = SMR.GetByteArray();
882 if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) {
883 size_t i = 0;
884 for (i = 0; i < Min(Size, OtherSize); i++)
885 if (Data[i] != OtherData[i])
886 break;
887 Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; "
alekseyshl9f6a9f22017-10-23 23:24:33 +0000888 "offset %zd\n",
889 GetPid(), Size, OtherSize, i);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000890 DumpCurrentUnit("mismatch-");
891 Printf("SUMMARY: libFuzzer: equivalence-mismatch\n");
892 PrintFinalStats();
893 _Exit(Options.ErrorExitCode);
894 }
895 }
896}
897
898} // namespace fuzzer
899
900extern "C" {
901
phosek966475e2018-01-17 20:39:14 +0000902__attribute__((visibility("default"))) size_t
903LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000904 assert(fuzzer::F);
905 return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
906}
907
908// Experimental
phosek966475e2018-01-17 20:39:14 +0000909__attribute__((visibility("default"))) void
910LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000911 assert(fuzzer::F);
912 fuzzer::F->AnnounceOutput(Data, Size);
913}
alekseyshl9f6a9f22017-10-23 23:24:33 +0000914} // extern "C"