blob: 117c1c75823b6f5cc6be77307ba6b0a6f78deaa1 [file] [log] [blame]
Aaron Ballmanef116982015-01-29 16:58:29 +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 "FuzzerInternal.h"
Aaron Ballmanef116982015-01-29 16:58:29 +000013#include <algorithm>
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +000014#include <cstring>
15#include <memory>
Aaron Ballmanef116982015-01-29 16:58:29 +000016
Kostya Serebryany2a48c242015-11-13 01:54:40 +000017#if defined(__has_include)
Ivan Krasindf919102016-01-22 22:28:27 +000018#if __has_include(<sanitizer / coverage_interface.h>)
19#include <sanitizer/coverage_interface.h>
20#endif
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000021#if __has_include(<sanitizer / lsan_interface.h>)
22#include <sanitizer/lsan_interface.h>
23#endif
Kostya Serebryany2a48c242015-11-13 01:54:40 +000024#endif
25
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000026#define NO_SANITIZE_MEMORY
27#if defined(__has_feature)
28#if __has_feature(memory_sanitizer)
29#undef NO_SANITIZE_MEMORY
30#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
31#endif
32#endif
33
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000034extern "C" {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000035// Re-declare some of the sanitizer functions as "weak" so that
Kostya Serebryany2a48c242015-11-13 01:54:40 +000036// libFuzzer can be linked w/o the sanitizers and sanitizer-coverage
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000037// (in which case it will complain at start-up time).
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000038__attribute__((weak)) void __sanitizer_print_stack_trace();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +000039__attribute__((weak)) void __sanitizer_reset_coverage();
Kostya Serebryany94660b32015-10-23 18:37:58 +000040__attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000041__attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
Ivan Krasindf919102016-01-22 22:28:27 +000042__attribute__((weak)) void
43__sanitizer_set_death_callback(void (*callback)(void));
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000044__attribute__((weak)) size_t __sanitizer_get_number_of_counters();
Ivan Krasindf919102016-01-22 22:28:27 +000045__attribute__((weak)) uintptr_t
46__sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
Mike Aizatsky8b11f872016-01-06 00:21:22 +000047__attribute__((weak)) uintptr_t
48__sanitizer_get_coverage_pc_buffer(uintptr_t **data);
Kostya Serebryany22cc5e22016-02-13 02:29:38 +000049
50__attribute__((weak)) size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
51 size_t MaxSize,
52 unsigned int Seed);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +000053__attribute__((weak)) void __sanitizer_malloc_hook(void *ptr, size_t size);
54__attribute__((weak)) void __sanitizer_free_hook(void *ptr);
55__attribute__((weak)) void __lsan_enable();
56__attribute__((weak)) void __lsan_disable();
57__attribute__((weak)) int __lsan_do_recoverable_leak_check();
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000058}
59
Aaron Ballmanef116982015-01-29 16:58:29 +000060namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000061static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000062
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000063static void MissingWeakApiFunction(const char *FnName) {
64 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000065 "Did you use -fsanitize-coverage=... to build your code?\n",
66 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000067 exit(1);
68}
69
70#define CHECK_WEAK_API_FUNCTION(fn) \
71 do { \
72 if (!fn) \
73 MissingWeakApiFunction(#fn); \
74 } while (false)
75
Kostya Serebryany52a788e2015-03-31 20:13:20 +000076// Only one Fuzzer per process.
77static Fuzzer *F;
78
Kostya Serebryany1deb0492016-02-13 06:24:18 +000079size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
80 assert(F);
81 return F->GetMD().Mutate(Data, Size, MaxSize);
82}
83
Mike Aizatsky1aa501e2016-05-10 23:43:15 +000084struct CoverageController {
85 static void Reset() {
86 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
87 __sanitizer_reset_coverage();
88 PcMapResetCurrent();
89 }
90
91 static void ResetCounters(const Fuzzer::FuzzingOptions &Options) {
92 if (Options.UseCounters) {
93 __sanitizer_update_counter_bitset_and_clear_counters(0);
94 }
95 }
96
97 static void Prepare(const Fuzzer::FuzzingOptions &Options,
98 Fuzzer::Coverage *C) {
99 if (Options.UseCounters) {
100 size_t NumCounters = __sanitizer_get_number_of_counters();
101 C->CounterBitmap.resize(NumCounters);
102 }
103 }
104
105 // Records data to a maximum coverage tracker. Returns true if additional
106 // coverage was discovered.
107 static bool RecordMax(const Fuzzer::FuzzingOptions &Options,
108 Fuzzer::Coverage *C) {
109 bool Res = false;
110
111 uint64_t NewBlockCoverage = __sanitizer_get_total_unique_coverage();
112 if (NewBlockCoverage > C->BlockCoverage) {
113 Res = true;
114 C->BlockCoverage = NewBlockCoverage;
115 }
116
117 if (Options.UseIndirCalls &&
118 __sanitizer_get_total_unique_caller_callee_pairs) {
119 uint64_t NewCallerCalleeCoverage =
120 __sanitizer_get_total_unique_caller_callee_pairs();
121 if (NewCallerCalleeCoverage > C->CallerCalleeCoverage) {
122 Res = true;
123 C->CallerCalleeCoverage = NewCallerCalleeCoverage;
124 }
125 }
126
127 if (Options.UseCounters) {
128 uint64_t CounterDelta =
129 __sanitizer_update_counter_bitset_and_clear_counters(
130 C->CounterBitmap.data());
131 if (CounterDelta > 0) {
132 Res = true;
133 C->CounterBitmapBits += CounterDelta;
134 }
135 }
136
137 uint64_t NewPcMapBits = PcMapMergeInto(&C->PCMap);
138 if (NewPcMapBits > C->PcMapBits) {
139 Res = true;
140 C->PcMapBits = NewPcMapBits;
141 }
142
143 uintptr_t *CoverageBuf;
144 uint64_t NewPcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
145 if (NewPcBufferLen > C->PcBufferLen) {
146 Res = true;
147 C->PcBufferLen = NewPcBufferLen;
148 }
149
150 return Res;
151 }
152};
153
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000154Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
155 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000156 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +0000157 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000158 assert(!F);
159 F = this;
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000160 ResetCoverage();
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000161}
Aaron Ballmanef116982015-01-29 16:58:29 +0000162
163void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000164 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000165 __sanitizer_set_death_callback(StaticDeathCallback);
166}
167
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000168void Fuzzer::StaticDeathCallback() {
169 assert(F);
170 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000171}
172
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000173void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000174 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
175 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
176 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000177 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000178 WriteUnitToFileWithPrefix(
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000179 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, Prefix);
180}
181
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000182NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000183void Fuzzer::DeathCallback() {
184 if (!CurrentUnitSize) return;
185 Printf("DEATH:\n");
186 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000187 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000188}
189
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000190void Fuzzer::StaticAlarmCallback() {
191 assert(F);
192 F->AlarmCallback();
193}
194
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000195void Fuzzer::StaticCrashSignalCallback() {
196 assert(F);
197 F->CrashCallback();
198}
199
200void Fuzzer::StaticInterruptCallback() {
201 assert(F);
202 F->InterruptCallback();
203}
204
205void Fuzzer::CrashCallback() {
206 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
207 if (__sanitizer_print_stack_trace)
208 __sanitizer_print_stack_trace();
209 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
210 " Combine libFuzzer with AddressSanitizer or similar for better "
211 "crash reports.\n");
212 Printf("SUMMARY: libFuzzer: deadly signal\n");
213 DumpCurrentUnit("crash-");
214 PrintFinalStats();
215 exit(Options.ErrorExitCode);
216}
217
218void Fuzzer::InterruptCallback() {
219 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
220 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000221 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000222}
223
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000224NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000225void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000226 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000227 if (InOOMState) {
228 Printf("==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
229 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
230 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n");
231 if (CurrentUnitSize && CurrentUnitData) {
232 DumpCurrentUnit("oom-");
233 if (__sanitizer_print_stack_trace)
234 __sanitizer_print_stack_trace();
235 }
236 Printf("SUMMARY: libFuzzer: out-of-memory\n");
237 PrintFinalStats();
238 _Exit(Options.ErrorExitCode); // Stop right now.
239 }
240
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000241 if (!CurrentUnitSize)
242 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000243 size_t Seconds =
244 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000245 if (Seconds == 0)
246 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000247 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000248 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000249 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000250 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000251 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
252 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000253 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000254 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
255 Seconds);
256 if (__sanitizer_print_stack_trace)
257 __sanitizer_print_stack_trace();
258 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000259 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000260 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000261 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000262}
263
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000264void Fuzzer::RssLimitCallback() {
265 InOOMState = true;
266 SignalToMainThread();
267 SleepSeconds(5);
268 Printf("Signal to main thread failed (non-linux?). Exiting.\n");
269 _Exit(Options.ErrorExitCode);
270 return;
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000271}
272
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000273void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000274 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000275 if (Options.OutputCSV) {
276 static bool csvHeaderPrinted = false;
277 if (!csvHeaderPrinted) {
278 csvHeaderPrinted = true;
279 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
280 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000281 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000282 MaxCoverage.BlockCoverage, MaxCoverage.CounterBitmapBits,
283 MaxCoverage.CallerCalleeCoverage, Corpus.size(), ExecPerSec, Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000284 }
285
286 if (!Options.Verbosity)
287 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000288 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000289 if (MaxCoverage.BlockCoverage)
290 Printf(" cov: %zd", MaxCoverage.BlockCoverage);
291 if (MaxCoverage.PcMapBits)
292 Printf(" path: %zd", MaxCoverage.PcMapBits);
293 if (auto TB = MaxCoverage.CounterBitmapBits)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000294 Printf(" bits: %zd", TB);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000295 if (MaxCoverage.CallerCalleeCoverage)
296 Printf(" indir: %zd", MaxCoverage.CallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000297 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000298 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000299}
300
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000301void Fuzzer::PrintFinalStats() {
302 if (!Options.PrintFinalStats) return;
303 size_t ExecPerSec = execPerSec();
304 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
305 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
306 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
307 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
308 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
309}
310
Kostya Serebryany64d24572016-03-12 01:57:04 +0000311size_t Fuzzer::MaxUnitSizeInCorpus() const {
312 size_t Res = 0;
313 for (auto &X : Corpus)
314 Res = std::max(Res, X.size());
315 return Res;
316}
317
318void Fuzzer::SetMaxLen(size_t MaxLen) {
319 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
320 assert(MaxLen);
321 Options.MaxLen = MaxLen;
322 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
323}
324
325
326void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000327 if (Options.OutputCorpus.empty())
328 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000329 std::vector<Unit> AdditionalCorpus;
330 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000331 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000332 if (Corpus.empty()) {
333 Corpus = AdditionalCorpus;
334 return;
335 }
Ivan Krasindf919102016-01-22 22:28:27 +0000336 if (!Options.Reload)
337 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000338 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000339 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000340 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000341 if (X.size() > MaxSize)
342 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000343 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000344 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000345 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000346 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000347 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000348 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000349 }
350 }
351}
352
Kostya Serebryany945761b2016-03-18 00:23:29 +0000353void Fuzzer::ShuffleCorpus(UnitVector *V) {
354 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
355 if (Options.PreferSmall)
356 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
357 return A.size() < B.size();
358 });
359}
360
Aaron Ballmanef116982015-01-29 16:58:29 +0000361void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000362 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000363 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000364 if (Options.ShuffleAtStartUp)
365 ShuffleCorpus(&Corpus);
366
367 for (const auto &U : Corpus) {
368 if (RunOne(U)) {
369 NewCorpus.push_back(U);
370 if (Options.Verbosity >= 2)
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000371 Printf("NEW0: %zd L %zd\n", MaxCoverage.BlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000372 }
373 }
374 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000375 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000376 for (auto &X : Corpus)
377 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000378 PrintStats("INITED");
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000379 CheckForMemoryLeaks();
Aaron Ballmanef116982015-01-29 16:58:29 +0000380}
381
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000382bool Fuzzer::UpdateMaxCoverage() {
383 uintptr_t PrevBufferLen = MaxCoverage.PcBufferLen;
384 bool Res = CoverageController::RecordMax(Options, &MaxCoverage);
385
386 if (Options.PrintNewCovPcs && PrevBufferLen != MaxCoverage.PcBufferLen) {
387 uintptr_t *CoverageBuf;
388 __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
389 assert(CoverageBuf);
390 for (size_t I = PrevBufferLen; I < MaxCoverage.PcBufferLen; ++I) {
391 Printf("%p\n", CoverageBuf[I]);
392 }
393 }
394
395 return Res;
396}
397
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000398bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000399 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000400
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000401 // TODO(aizatsky): this Reset call seems to be not needed.
402 CoverageController::ResetCounters(Options);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000403 ExecuteCallback(Data, Size);
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000404 bool Res = UpdateMaxCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000405
Kostya Serebryany16901a92015-03-30 23:04:35 +0000406 auto UnitStopTime = system_clock::now();
407 auto TimeOfUnit =
408 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000409 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
410 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000411 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000412 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
413 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000414 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000415 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000416 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000417 }
418 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000419}
420
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000421void Fuzzer::RunOneAndUpdateCorpus(uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000422 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
423 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000424 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000425 ToASCII(Data, Size);
426 if (RunOne(Data, Size))
427 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000428}
429
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000430// Leak detection is expensive, so we first check if there were more mallocs
431// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
432struct MallocFreeTracer {
433 void Start() {
434 Mallocs = 0;
435 Frees = 0;
436 }
437 // Returns true if there were more mallocs than frees.
438 bool Stop() { return Mallocs > Frees; }
439 size_t Mallocs;
440 size_t Frees;
441};
442
443static thread_local MallocFreeTracer AllocTracer;
444
445extern "C" {
446void __sanitizer_malloc_hook(void *ptr, size_t size) { AllocTracer.Mallocs++; }
447void __sanitizer_free_hook(void *ptr) { AllocTracer.Frees++; }
448} // extern "C"
449
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000450void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000451 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000452 // We copy the contents of Unit into a separate heap buffer
453 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000454 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
455 memcpy(DataCopy.get(), Data, Size);
456 AssignTaintLabels(DataCopy.get(), Size);
457 CurrentUnitData = DataCopy.get();
458 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000459 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000460 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000461 (void)Res;
462 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000463 CurrentUnitSize = 0;
464 CurrentUnitData = nullptr;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000465 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000466}
467
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000468std::string Fuzzer::Coverage::DebugString() const {
469 std::string Result =
470 std::string("Coverage{") + "BlockCoverage=" +
471 std::to_string(BlockCoverage) + " CallerCalleeCoverage=" +
472 std::to_string(CallerCalleeCoverage) + " CounterBitmapBits=" +
473 std::to_string(CounterBitmapBits) + " PcMapBits=" +
474 std::to_string(PcMapBits) + "}";
475 return Result;
Aaron Ballmanef116982015-01-29 16:58:29 +0000476}
477
478void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Ivan Krasindf919102016-01-22 22:28:27 +0000479 if (Options.OutputCorpus.empty())
480 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000481 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
482 WriteToFile(U, Path);
483 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000484 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000485 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000486}
487
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000488void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000489 if (!Options.SaveArtifacts)
490 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000491 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000492 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000493 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000494 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000495 Printf("artifact_prefix='%s'; Test unit written to %s\n",
496 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000497 if (U.size() <= kMaxUnitSizeToPrint)
498 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000499}
500
501void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000502 if (Options.OutputCorpus.empty())
503 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000504 for (const auto &U : Corpus)
505 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
506 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000507 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
508 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000509}
510
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000511void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
512 if (!Options.PrintNEW)
513 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000514 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000515 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000516 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000517 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000518 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000519 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000520}
521
522void Fuzzer::ReportNewCoverage(const Unit &U) {
523 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000524 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000525 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000526 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000527 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000528 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000529 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000530}
531
Kostya Serebryany945761b2016-03-18 00:23:29 +0000532// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
533// We do it by actually executing the units, sometimes more than once,
534// because we may be using different coverage-like signals and the only
535// common thing between them is that we can say "this unit found new stuff".
536UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
537 const UnitVector &Extra) {
538 UnitVector Res = Extra;
539 size_t OldSize = Res.size();
540 for (int Iter = 0; Iter < 10; Iter++) {
541 ShuffleCorpus(&Res);
542 ResetCoverage();
543
544 for (auto &U : Initial)
545 RunOne(U);
546
547 Corpus.clear();
548 for (auto &U : Res)
549 if (RunOne(U))
550 Corpus.push_back(U);
551
552 char Stat[7] = "MIN ";
553 Stat[3] = '0' + Iter;
554 PrintStats(Stat);
555
556 size_t NewSize = Corpus.size();
557 Res.swap(Corpus);
558
559 if (NewSize == OldSize)
560 break;
561 OldSize = NewSize;
562 }
563 return Res;
564}
565
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000566void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
567 if (Corpora.size() <= 1) {
568 Printf("Merge requires two or more corpus dirs\n");
569 return;
570 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000571 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
572
Kostya Serebryany945761b2016-03-18 00:23:29 +0000573 assert(Options.MaxLen > 0);
574 UnitVector Initial, Extra;
575 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
576 for (auto &C : ExtraCorpora)
577 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
578
579 if (!Initial.empty()) {
580 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
581 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000582 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000583
584 Printf("=== Merging extra %zd units\n", Extra.size());
585 auto Res = FindExtraUnits(Initial, Extra);
586
587 for (auto &U: Res)
588 WriteToOutputCorpus(U);
589
590 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000591}
592
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000593// Tries to call lsan, and if there are leaks exits. We call this right after
594// the initial corpus was read because if there are leaky inputs in the corpus
595// further fuzzing will likely hit OOMs.
596void Fuzzer::CheckForMemoryLeaks() {
597 if (!Options.DetectLeaks) return;
598 if (!__lsan_do_recoverable_leak_check)
599 return;
600 if (__lsan_do_recoverable_leak_check()) {
601 Printf("==%d== ERROR: libFuzzer: initial corpus triggers memory leaks.\n"
602 "Exiting now. Use -detect_leaks=0 to disable leak detection here.\n"
603 "LeakSanitizer will still check for leaks at the process exit.\n",
604 GetPid());
605 PrintFinalStats();
606 _Exit(Options.ErrorExitCode);
607 }
608}
609
610// Tries detecting a memory leak on the particular input that we have just
611// executed before calling this function.
612void Fuzzer::TryDetectingAMemoryLeak(uint8_t *Data, size_t Size) {
613 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
614 if (!Options.DetectLeaks) return;
615 if (!&__lsan_enable || !&__lsan_disable || !__lsan_do_recoverable_leak_check)
616 return; // No lsan.
617 // Run the target once again, but with lsan disabled so that if there is
618 // a real leak we do not report it twice.
619 __lsan_disable();
620 RunOneAndUpdateCorpus(Data, Size);
621 __lsan_enable();
622 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000623 if (NumberOfLeakDetectionAttempts++ > 1000) {
624 Options.DetectLeaks = false;
625 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
626 " Most likely the target function accumulates allocated\n"
627 " memory in a global state w/o actually leaking it.\n"
628 " If LeakSanitizer is enabled in this process it will still\n"
629 " run on the process shutdown.\n");
630 return;
631 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000632 // Now perform the actual lsan pass. This is expensive and we must ensure
633 // we don't call it too often.
634 if (__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
635 CurrentUnitData = Data;
636 CurrentUnitSize = Size;
637 DumpCurrentUnit("leak-");
638 PrintFinalStats();
639 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
640 }
641}
642
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000643void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000644 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000645
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000646 auto &U = ChooseUnitToMutate();
647 MutateInPlaceHere.resize(Options.MaxLen);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000648 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000649 assert(Size <= Options.MaxLen && "Oversized Unit");
650 memcpy(MutateInPlaceHere.data(), U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000651
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000652 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000653 size_t NewSize = 0;
654 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000655 NewSize = LLVMFuzzerCustomMutator(MutateInPlaceHere.data(), Size,
656 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000657 else
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000658 NewSize = MD.Mutate(MutateInPlaceHere.data(), Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000659 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000660 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000661 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000662 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000663 if (i == 0)
664 StartTraceRecording();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000665 RunOneAndUpdateCorpus(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000666 StopTraceRecording();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000667 TryDetectingAMemoryLeak(MutateInPlaceHere.data(), Size);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000668 }
669}
670
Kostya Serebryanye6926212015-11-04 23:22:25 +0000671// Returns an index of random unit from the corpus to mutate.
672// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000673// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000674size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000675 size_t Idx =
676 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000677 assert(Idx < Corpus.size());
678 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000679}
680
Kostya Serebryany945761b2016-03-18 00:23:29 +0000681void Fuzzer::ResetCoverage() {
Mike Aizatsky1aa501e2016-05-10 23:43:15 +0000682 CoverageController::Reset();
683 MaxCoverage.Reset();
684 CoverageController::Prepare(Options, &MaxCoverage);
Kostya Serebryany945761b2016-03-18 00:23:29 +0000685}
686
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000687// Experimental search heuristic: drilling.
688// - Read, shuffle, execute and minimize the corpus.
689// - Choose one random unit.
690// - Reset the coverage.
691// - Start fuzzing as if the chosen unit was the only element of the corpus.
692// - When done, reset the coverage again.
693// - Merge the newly created corpus into the original one.
694void Fuzzer::Drill() {
695 // The corpus is already read, shuffled, and minimized.
696 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000697 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000698
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000699 Unit U = ChooseUnitToMutate();
700
Kostya Serebryany945761b2016-03-18 00:23:29 +0000701 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000702
703 std::vector<Unit> SavedCorpus;
704 SavedCorpus.swap(Corpus);
705 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000706 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000707 assert(Corpus.size() == 1);
708 RunOne(U);
709 PrintStats("DRILL ");
710 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
711 SavedOutputCorpusPath.swap(Options.OutputCorpus);
712 Loop();
713
Kostya Serebryany945761b2016-03-18 00:23:29 +0000714 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000715
716 PrintStats("REINIT");
717 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000718 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000719 RunOne(U);
720 PrintStats("MERGE ");
721 Options.PrintNEW = true;
722 size_t NumMerged = 0;
723 for (auto &U : Corpus) {
724 if (RunOne(U)) {
725 PrintStatusForNewUnit(U);
726 NumMerged++;
727 WriteToOutputCorpus(U);
728 }
729 }
730 PrintStats("MERGED");
731 if (NumMerged && Options.Verbosity)
732 Printf("Drilling discovered %zd new units\n", NumMerged);
733}
734
735void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000736 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000737 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000738 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000739 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000740 auto Now = system_clock::now();
741 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000742 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000743 LastCorpusReload = Now;
744 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000745 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000746 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000747 if (Options.MaxTotalTimeSec > 0 &&
748 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000749 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000750 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000751 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000752 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000753 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000754
755 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000756 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000757}
758
Ivan Krasindf919102016-01-22 22:28:27 +0000759void Fuzzer::UpdateCorpusDistribution() {
760 size_t N = Corpus.size();
761 std::vector<double> Intervals(N + 1);
762 std::vector<double> Weights(N);
763 std::iota(Intervals.begin(), Intervals.end(), 0);
764 std::iota(Weights.begin(), Weights.end(), 1);
765 CorpusDistribution = std::piecewise_constant_distribution<double>(
766 Intervals.begin(), Intervals.end(), Weights.begin());
767}
768
769} // namespace fuzzer