blob: 6a7fe7d2bf4dda104cb26fff32eec6afc9558c0e [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
Kostya Serebryany7ec0c562016-02-13 03:25:16 +000084Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
85 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000086 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000087 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000088 assert(!F);
89 F = this;
90}
Aaron Ballmanef116982015-01-29 16:58:29 +000091
92void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000093 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000094 __sanitizer_set_death_callback(StaticDeathCallback);
95}
96
Kostya Serebryany52a788e2015-03-31 20:13:20 +000097void Fuzzer::StaticDeathCallback() {
98 assert(F);
99 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +0000100}
101
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000102void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000103 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
104 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
105 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000106 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000107 WriteUnitToFileWithPrefix(
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000108 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, Prefix);
109}
110
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000111NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000112void Fuzzer::DeathCallback() {
113 if (!CurrentUnitSize) return;
114 Printf("DEATH:\n");
115 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000116 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000117}
118
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000119void Fuzzer::StaticAlarmCallback() {
120 assert(F);
121 F->AlarmCallback();
122}
123
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000124void Fuzzer::StaticCrashSignalCallback() {
125 assert(F);
126 F->CrashCallback();
127}
128
129void Fuzzer::StaticInterruptCallback() {
130 assert(F);
131 F->InterruptCallback();
132}
133
134void Fuzzer::CrashCallback() {
135 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
136 if (__sanitizer_print_stack_trace)
137 __sanitizer_print_stack_trace();
138 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
139 " Combine libFuzzer with AddressSanitizer or similar for better "
140 "crash reports.\n");
141 Printf("SUMMARY: libFuzzer: deadly signal\n");
142 DumpCurrentUnit("crash-");
143 PrintFinalStats();
144 exit(Options.ErrorExitCode);
145}
146
147void Fuzzer::InterruptCallback() {
148 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
149 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000150 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000151}
152
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000153NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000154void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000155 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000156 if (InOOMState) {
157 Printf("==%d== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
158 GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
159 Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n");
160 if (CurrentUnitSize && CurrentUnitData) {
161 DumpCurrentUnit("oom-");
162 if (__sanitizer_print_stack_trace)
163 __sanitizer_print_stack_trace();
164 }
165 Printf("SUMMARY: libFuzzer: out-of-memory\n");
166 PrintFinalStats();
167 _Exit(Options.ErrorExitCode); // Stop right now.
168 }
169
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000170 if (!CurrentUnitSize)
171 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000172 size_t Seconds =
173 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000174 if (Seconds == 0)
175 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000176 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000177 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000178 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000179 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000180 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
181 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000182 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000183 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
184 Seconds);
185 if (__sanitizer_print_stack_trace)
186 __sanitizer_print_stack_trace();
187 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000188 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000189 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000190 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000191}
192
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +0000193void Fuzzer::RssLimitCallback() {
194 InOOMState = true;
195 SignalToMainThread();
196 SleepSeconds(5);
197 Printf("Signal to main thread failed (non-linux?). Exiting.\n");
198 _Exit(Options.ErrorExitCode);
199 return;
Kostya Serebryany52b394e2016-05-06 21:58:35 +0000200}
201
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000202void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000203 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000204 if (Options.OutputCSV) {
205 static bool csvHeaderPrinted = false;
206 if (!csvHeaderPrinted) {
207 csvHeaderPrinted = true;
208 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
209 }
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000210 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
Mike Aizatskya9c23872015-11-12 04:38:40 +0000211 LastRecordedBlockCoverage, TotalBits(),
212 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
Kostya Serebryany9ba19182016-04-25 19:41:45 +0000213 Where);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000214 }
215
216 if (!Options.Verbosity)
217 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000218 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000219 if (LastRecordedBlockCoverage)
220 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryanyda63c1d2016-02-26 21:33:56 +0000221 if (LastRecordedPcMapSize)
222 Printf(" path: %zd", LastRecordedPcMapSize);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000223 if (auto TB = TotalBits())
224 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000225 if (LastRecordedCallerCalleeCoverage)
226 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000227 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000228 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000229}
230
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000231void Fuzzer::PrintFinalStats() {
232 if (!Options.PrintFinalStats) return;
233 size_t ExecPerSec = execPerSec();
234 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
235 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
236 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
237 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
238 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
239}
240
Kostya Serebryany64d24572016-03-12 01:57:04 +0000241size_t Fuzzer::MaxUnitSizeInCorpus() const {
242 size_t Res = 0;
243 for (auto &X : Corpus)
244 Res = std::max(Res, X.size());
245 return Res;
246}
247
248void Fuzzer::SetMaxLen(size_t MaxLen) {
249 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
250 assert(MaxLen);
251 Options.MaxLen = MaxLen;
252 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
253}
254
255
256void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000257 if (Options.OutputCorpus.empty())
258 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000259 std::vector<Unit> AdditionalCorpus;
260 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000261 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000262 if (Corpus.empty()) {
263 Corpus = AdditionalCorpus;
264 return;
265 }
Ivan Krasindf919102016-01-22 22:28:27 +0000266 if (!Options.Reload)
267 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000268 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000269 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000270 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000271 if (X.size() > MaxSize)
272 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000273 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000274 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000275 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000276 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000277 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000278 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000279 }
280 }
281}
282
Kostya Serebryany945761b2016-03-18 00:23:29 +0000283void Fuzzer::ShuffleCorpus(UnitVector *V) {
284 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
285 if (Options.PreferSmall)
286 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
287 return A.size() < B.size();
288 });
289}
290
Aaron Ballmanef116982015-01-29 16:58:29 +0000291void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000292 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000293 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000294 if (Options.ShuffleAtStartUp)
295 ShuffleCorpus(&Corpus);
296
297 for (const auto &U : Corpus) {
298 if (RunOne(U)) {
299 NewCorpus.push_back(U);
300 if (Options.Verbosity >= 2)
301 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000302 }
303 }
304 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000305 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000306 for (auto &X : Corpus)
307 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000308 PrintStats("INITED");
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000309 CheckForMemoryLeaks();
Aaron Ballmanef116982015-01-29 16:58:29 +0000310}
311
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000312bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000313 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000314
315 PrepareCoverageBeforeRun();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000316 ExecuteCallback(Data, Size);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000317 bool Res = CheckCoverageAfterRun();
318
Kostya Serebryany16901a92015-03-30 23:04:35 +0000319 auto UnitStopTime = system_clock::now();
320 auto TimeOfUnit =
321 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000322 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
323 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000324 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000325 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
326 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000327 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000328 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000329 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000330 }
331 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000332}
333
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000334void Fuzzer::RunOneAndUpdateCorpus(uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000335 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
336 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000337 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000338 ToASCII(Data, Size);
339 if (RunOne(Data, Size))
340 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000341}
342
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000343// Leak detection is expensive, so we first check if there were more mallocs
344// than frees (using the sanitizer malloc hooks) and only then try to call lsan.
345struct MallocFreeTracer {
346 void Start() {
347 Mallocs = 0;
348 Frees = 0;
349 }
350 // Returns true if there were more mallocs than frees.
351 bool Stop() { return Mallocs > Frees; }
352 size_t Mallocs;
353 size_t Frees;
354};
355
356static thread_local MallocFreeTracer AllocTracer;
357
358extern "C" {
359void __sanitizer_malloc_hook(void *ptr, size_t size) { AllocTracer.Mallocs++; }
360void __sanitizer_free_hook(void *ptr) { AllocTracer.Frees++; }
361} // extern "C"
362
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000363void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000364 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000365 // We copy the contents of Unit into a separate heap buffer
366 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000367 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
368 memcpy(DataCopy.get(), Data, Size);
369 AssignTaintLabels(DataCopy.get(), Size);
370 CurrentUnitData = DataCopy.get();
371 CurrentUnitSize = Size;
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000372 AllocTracer.Start();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000373 int Res = CB(DataCopy.get(), Size);
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000374 (void)Res;
375 HasMoreMallocsThanFrees = AllocTracer.Stop();
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000376 CurrentUnitSize = 0;
377 CurrentUnitData = nullptr;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000378 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000379}
380
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000381size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000382 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000383 uintptr_t PrevCoverage = LastRecordedBlockCoverage;
384 LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
385
386 if (PrevCoverage == LastRecordedBlockCoverage || !Options.PrintNewCovPcs)
387 return LastRecordedBlockCoverage;
388
389 uintptr_t PrevBufferLen = LastCoveragePcBufferLen;
390 uintptr_t *CoverageBuf;
391 LastCoveragePcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
392 assert(CoverageBuf);
393 for (size_t i = PrevBufferLen; i < LastCoveragePcBufferLen; ++i) {
Mike Aizatskye313f8f2016-01-21 00:02:09 +0000394 Printf("%p\n", CoverageBuf[i]);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000395 }
396
397 return LastRecordedBlockCoverage;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000398}
399
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000400size_t Fuzzer::RecordCallerCalleeCoverage() {
401 if (!Options.UseIndirCalls)
402 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000403 if (!__sanitizer_get_total_unique_caller_callee_pairs)
404 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000405 return LastRecordedCallerCalleeCoverage =
406 __sanitizer_get_total_unique_caller_callee_pairs();
407}
408
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000409void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000410 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000411 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000412 CounterBitmap.resize(NumCounters);
413 __sanitizer_update_counter_bitset_and_clear_counters(0);
414 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000415 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000416 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000417}
418
419bool Fuzzer::CheckCoverageAfterRun() {
420 size_t OldCoverage = LastRecordedBlockCoverage;
421 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000422 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
423 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000424 size_t NumNewBits = 0;
Kostya Serebryanyda63c1d2016-02-26 21:33:56 +0000425 size_t OldPcMapSize = LastRecordedPcMapSize;
426 PcMapMergeCurrentToCombined();
427 size_t NewPcMapSize = PcMapCombinedSize();
428 LastRecordedPcMapSize = NewPcMapSize;
429 if (NewPcMapSize > OldPcMapSize)
430 return true;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000431 if (Options.UseCounters)
432 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
433 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000434 return NewCoverage > OldCoverage ||
435 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000436}
437
438void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Ivan Krasindf919102016-01-22 22:28:27 +0000439 if (Options.OutputCorpus.empty())
440 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000441 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
442 WriteToFile(U, Path);
443 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000444 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000445 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000446}
447
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000448void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000449 if (!Options.SaveArtifacts)
450 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000451 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000452 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000453 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000454 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000455 Printf("artifact_prefix='%s'; Test unit written to %s\n",
456 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000457 if (U.size() <= kMaxUnitSizeToPrint)
458 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000459}
460
461void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000462 if (Options.OutputCorpus.empty())
463 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000464 for (const auto &U : Corpus)
465 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
466 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000467 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
468 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000469}
470
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000471void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
472 if (!Options.PrintNEW)
473 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000474 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000475 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000476 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000477 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000478 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000479 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000480}
481
482void Fuzzer::ReportNewCoverage(const Unit &U) {
483 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000484 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000485 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000486 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000487 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000488 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000489 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000490}
491
Kostya Serebryany945761b2016-03-18 00:23:29 +0000492// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
493// We do it by actually executing the units, sometimes more than once,
494// because we may be using different coverage-like signals and the only
495// common thing between them is that we can say "this unit found new stuff".
496UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
497 const UnitVector &Extra) {
498 UnitVector Res = Extra;
499 size_t OldSize = Res.size();
500 for (int Iter = 0; Iter < 10; Iter++) {
501 ShuffleCorpus(&Res);
502 ResetCoverage();
503
504 for (auto &U : Initial)
505 RunOne(U);
506
507 Corpus.clear();
508 for (auto &U : Res)
509 if (RunOne(U))
510 Corpus.push_back(U);
511
512 char Stat[7] = "MIN ";
513 Stat[3] = '0' + Iter;
514 PrintStats(Stat);
515
516 size_t NewSize = Corpus.size();
517 Res.swap(Corpus);
518
519 if (NewSize == OldSize)
520 break;
521 OldSize = NewSize;
522 }
523 return Res;
524}
525
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000526void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
527 if (Corpora.size() <= 1) {
528 Printf("Merge requires two or more corpus dirs\n");
529 return;
530 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000531 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
532
Kostya Serebryany945761b2016-03-18 00:23:29 +0000533 assert(Options.MaxLen > 0);
534 UnitVector Initial, Extra;
535 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
536 for (auto &C : ExtraCorpora)
537 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
538
539 if (!Initial.empty()) {
540 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
541 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000542 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000543
544 Printf("=== Merging extra %zd units\n", Extra.size());
545 auto Res = FindExtraUnits(Initial, Extra);
546
547 for (auto &U: Res)
548 WriteToOutputCorpus(U);
549
550 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000551}
552
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000553// Tries to call lsan, and if there are leaks exits. We call this right after
554// the initial corpus was read because if there are leaky inputs in the corpus
555// further fuzzing will likely hit OOMs.
556void Fuzzer::CheckForMemoryLeaks() {
557 if (!Options.DetectLeaks) return;
558 if (!__lsan_do_recoverable_leak_check)
559 return;
560 if (__lsan_do_recoverable_leak_check()) {
561 Printf("==%d== ERROR: libFuzzer: initial corpus triggers memory leaks.\n"
562 "Exiting now. Use -detect_leaks=0 to disable leak detection here.\n"
563 "LeakSanitizer will still check for leaks at the process exit.\n",
564 GetPid());
565 PrintFinalStats();
566 _Exit(Options.ErrorExitCode);
567 }
568}
569
570// Tries detecting a memory leak on the particular input that we have just
571// executed before calling this function.
572void Fuzzer::TryDetectingAMemoryLeak(uint8_t *Data, size_t Size) {
573 if (!HasMoreMallocsThanFrees) return; // mallocs==frees, a leak is unlikely.
574 if (!Options.DetectLeaks) return;
575 if (!&__lsan_enable || !&__lsan_disable || !__lsan_do_recoverable_leak_check)
576 return; // No lsan.
577 // Run the target once again, but with lsan disabled so that if there is
578 // a real leak we do not report it twice.
579 __lsan_disable();
580 RunOneAndUpdateCorpus(Data, Size);
581 __lsan_enable();
582 if (!HasMoreMallocsThanFrees) return; // a leak is unlikely.
Kostya Serebryany7018a1a2016-04-27 19:52:34 +0000583 if (NumberOfLeakDetectionAttempts++ > 1000) {
584 Options.DetectLeaks = false;
585 Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
586 " Most likely the target function accumulates allocated\n"
587 " memory in a global state w/o actually leaking it.\n"
588 " If LeakSanitizer is enabled in this process it will still\n"
589 " run on the process shutdown.\n");
590 return;
591 }
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000592 // Now perform the actual lsan pass. This is expensive and we must ensure
593 // we don't call it too often.
594 if (__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
595 CurrentUnitData = Data;
596 CurrentUnitSize = Size;
597 DumpCurrentUnit("leak-");
598 PrintFinalStats();
599 _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
600 }
601}
602
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000603void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000604 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000605
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000606 auto &U = ChooseUnitToMutate();
607 MutateInPlaceHere.resize(Options.MaxLen);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000608 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000609 assert(Size <= Options.MaxLen && "Oversized Unit");
610 memcpy(MutateInPlaceHere.data(), U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000611
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000612 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000613 size_t NewSize = 0;
614 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000615 NewSize = LLVMFuzzerCustomMutator(MutateInPlaceHere.data(), Size,
616 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000617 else
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000618 NewSize = MD.Mutate(MutateInPlaceHere.data(), Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000619 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000620 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000621 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000622 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000623 if (i == 0)
624 StartTraceRecording();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000625 RunOneAndUpdateCorpus(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000626 StopTraceRecording();
Kostya Serebryany1bfd5832016-04-20 00:24:21 +0000627 TryDetectingAMemoryLeak(MutateInPlaceHere.data(), Size);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000628 }
629}
630
Kostya Serebryanye6926212015-11-04 23:22:25 +0000631// Returns an index of random unit from the corpus to mutate.
632// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000633// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000634size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000635 size_t Idx =
636 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000637 assert(Idx < Corpus.size());
638 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000639}
640
Kostya Serebryany945761b2016-03-18 00:23:29 +0000641void Fuzzer::ResetCoverage() {
642 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
643 __sanitizer_reset_coverage();
644 CounterBitmap.clear();
645}
646
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000647// Experimental search heuristic: drilling.
648// - Read, shuffle, execute and minimize the corpus.
649// - Choose one random unit.
650// - Reset the coverage.
651// - Start fuzzing as if the chosen unit was the only element of the corpus.
652// - When done, reset the coverage again.
653// - Merge the newly created corpus into the original one.
654void Fuzzer::Drill() {
655 // The corpus is already read, shuffled, and minimized.
656 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000657 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000658
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000659 Unit U = ChooseUnitToMutate();
660
Kostya Serebryany945761b2016-03-18 00:23:29 +0000661 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000662
663 std::vector<Unit> SavedCorpus;
664 SavedCorpus.swap(Corpus);
665 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000666 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000667 assert(Corpus.size() == 1);
668 RunOne(U);
669 PrintStats("DRILL ");
670 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
671 SavedOutputCorpusPath.swap(Options.OutputCorpus);
672 Loop();
673
Kostya Serebryany945761b2016-03-18 00:23:29 +0000674 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000675
676 PrintStats("REINIT");
677 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000678 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000679 RunOne(U);
680 PrintStats("MERGE ");
681 Options.PrintNEW = true;
682 size_t NumMerged = 0;
683 for (auto &U : Corpus) {
684 if (RunOne(U)) {
685 PrintStatusForNewUnit(U);
686 NumMerged++;
687 WriteToOutputCorpus(U);
688 }
689 }
690 PrintStats("MERGED");
691 if (NumMerged && Options.Verbosity)
692 Printf("Drilling discovered %zd new units\n", NumMerged);
693}
694
695void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000696 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000697 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000698 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000699 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000700 auto Now = system_clock::now();
701 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000702 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000703 LastCorpusReload = Now;
704 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000705 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000706 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000707 if (Options.MaxTotalTimeSec > 0 &&
708 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000709 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000710 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000711 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000712 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000713 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000714
715 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000716 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000717}
718
Ivan Krasindf919102016-01-22 22:28:27 +0000719void Fuzzer::UpdateCorpusDistribution() {
720 size_t N = Corpus.size();
721 std::vector<double> Intervals(N + 1);
722 std::vector<double> Weights(N);
723 std::iota(Intervals.begin(), Intervals.end(), 0);
724 std::iota(Weights.begin(), Weights.end(), 1);
725 CorpusDistribution = std::piecewise_constant_distribution<double>(
726 Intervals.begin(), Intervals.end(), Weights.begin());
727}
728
729} // namespace fuzzer