blob: 3b00e47d233905c06d888bf477616d610ef6ec67 [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 Serebryany2a48c242015-11-13 01:54:40 +000021#endif
22
Benjamin Kramerd96b0c12016-03-18 14:19:19 +000023#define NO_SANITIZE_MEMORY
24#if defined(__has_feature)
25#if __has_feature(memory_sanitizer)
26#undef NO_SANITIZE_MEMORY
27#define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
28#endif
29#endif
30
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000031extern "C" {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000032// Re-declare some of the sanitizer functions as "weak" so that
Kostya Serebryany2a48c242015-11-13 01:54:40 +000033// libFuzzer can be linked w/o the sanitizers and sanitizer-coverage
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000034// (in which case it will complain at start-up time).
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000035__attribute__((weak)) void __sanitizer_print_stack_trace();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +000036__attribute__((weak)) void __sanitizer_reset_coverage();
Kostya Serebryany94660b32015-10-23 18:37:58 +000037__attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000038__attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
Ivan Krasindf919102016-01-22 22:28:27 +000039__attribute__((weak)) void
40__sanitizer_set_death_callback(void (*callback)(void));
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000041__attribute__((weak)) size_t __sanitizer_get_number_of_counters();
Ivan Krasindf919102016-01-22 22:28:27 +000042__attribute__((weak)) uintptr_t
43__sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
Mike Aizatsky8b11f872016-01-06 00:21:22 +000044__attribute__((weak)) uintptr_t
45__sanitizer_get_coverage_pc_buffer(uintptr_t **data);
Kostya Serebryany22cc5e22016-02-13 02:29:38 +000046
47__attribute__((weak)) size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
48 size_t MaxSize,
49 unsigned int Seed);
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000050}
51
Aaron Ballmanef116982015-01-29 16:58:29 +000052namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000053static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000054
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000055static void MissingWeakApiFunction(const char *FnName) {
56 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000057 "Did you use -fsanitize-coverage=... to build your code?\n",
58 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000059 exit(1);
60}
61
62#define CHECK_WEAK_API_FUNCTION(fn) \
63 do { \
64 if (!fn) \
65 MissingWeakApiFunction(#fn); \
66 } while (false)
67
Kostya Serebryany52a788e2015-03-31 20:13:20 +000068// Only one Fuzzer per process.
69static Fuzzer *F;
70
Kostya Serebryany1deb0492016-02-13 06:24:18 +000071size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
72 assert(F);
73 return F->GetMD().Mutate(Data, Size, MaxSize);
74}
75
Kostya Serebryany7ec0c562016-02-13 03:25:16 +000076Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
77 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000078 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000079 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000080 assert(!F);
81 F = this;
82}
Aaron Ballmanef116982015-01-29 16:58:29 +000083
84void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000085 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000086 __sanitizer_set_death_callback(StaticDeathCallback);
87}
88
Kostya Serebryany52a788e2015-03-31 20:13:20 +000089void Fuzzer::StaticDeathCallback() {
90 assert(F);
91 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000092}
93
Kostya Serebryany228d5b12016-03-01 22:19:21 +000094void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000095 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
96 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
97 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000098 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000099 WriteUnitToFileWithPrefix(
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000100 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, Prefix);
101}
102
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000103NO_SANITIZE_MEMORY
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000104void Fuzzer::DeathCallback() {
105 if (!CurrentUnitSize) return;
106 Printf("DEATH:\n");
107 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000108 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000109}
110
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000111void Fuzzer::StaticAlarmCallback() {
112 assert(F);
113 F->AlarmCallback();
114}
115
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000116void Fuzzer::StaticCrashSignalCallback() {
117 assert(F);
118 F->CrashCallback();
119}
120
121void Fuzzer::StaticInterruptCallback() {
122 assert(F);
123 F->InterruptCallback();
124}
125
126void Fuzzer::CrashCallback() {
127 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
128 if (__sanitizer_print_stack_trace)
129 __sanitizer_print_stack_trace();
130 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
131 " Combine libFuzzer with AddressSanitizer or similar for better "
132 "crash reports.\n");
133 Printf("SUMMARY: libFuzzer: deadly signal\n");
134 DumpCurrentUnit("crash-");
135 PrintFinalStats();
136 exit(Options.ErrorExitCode);
137}
138
139void Fuzzer::InterruptCallback() {
140 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
141 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000142 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000143}
144
Benjamin Kramerd96b0c12016-03-18 14:19:19 +0000145NO_SANITIZE_MEMORY
Aaron Ballmanef116982015-01-29 16:58:29 +0000146void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000147 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000148 if (!CurrentUnitSize)
149 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000150 size_t Seconds =
151 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000152 if (Seconds == 0)
153 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000154 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000155 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000156 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000157 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000158 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
159 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000160 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000161 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
162 Seconds);
163 if (__sanitizer_print_stack_trace)
164 __sanitizer_print_stack_trace();
165 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000166 PrintFinalStats();
Kostya Serebryany31516732016-03-24 01:32:08 +0000167 _Exit(Options.TimeoutExitCode); // Stop right now.
Aaron Ballmanef116982015-01-29 16:58:29 +0000168 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000169}
170
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000171void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000172 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000173 if (Options.OutputCSV) {
174 static bool csvHeaderPrinted = false;
175 if (!csvHeaderPrinted) {
176 csvHeaderPrinted = true;
177 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
178 }
179 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
180 LastRecordedBlockCoverage, TotalBits(),
181 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
182 TotalNumberOfExecutedTraceBasedMutations, Where);
183 }
184
185 if (!Options.Verbosity)
186 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000187 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000188 if (LastRecordedBlockCoverage)
189 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryanyda63c1d2016-02-26 21:33:56 +0000190 if (LastRecordedPcMapSize)
191 Printf(" path: %zd", LastRecordedPcMapSize);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000192 if (auto TB = TotalBits())
193 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000194 if (LastRecordedCallerCalleeCoverage)
195 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000196 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000197 if (TotalNumberOfExecutedTraceBasedMutations)
198 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
199 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000200}
201
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000202void Fuzzer::PrintFinalStats() {
203 if (!Options.PrintFinalStats) return;
204 size_t ExecPerSec = execPerSec();
205 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
206 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
207 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
208 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
209 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
210}
211
Kostya Serebryany64d24572016-03-12 01:57:04 +0000212size_t Fuzzer::MaxUnitSizeInCorpus() const {
213 size_t Res = 0;
214 for (auto &X : Corpus)
215 Res = std::max(Res, X.size());
216 return Res;
217}
218
219void Fuzzer::SetMaxLen(size_t MaxLen) {
220 assert(Options.MaxLen == 0); // Can only reset MaxLen from 0 to non-0.
221 assert(MaxLen);
222 Options.MaxLen = MaxLen;
223 Printf("INFO: -max_len is not provided, using %zd\n", Options.MaxLen);
224}
225
226
227void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
Ivan Krasindf919102016-01-22 22:28:27 +0000228 if (Options.OutputCorpus.empty())
229 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000230 std::vector<Unit> AdditionalCorpus;
231 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryany64d24572016-03-12 01:57:04 +0000232 &EpochOfLastReadOfOutputCorpus, MaxSize);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000233 if (Corpus.empty()) {
234 Corpus = AdditionalCorpus;
235 return;
236 }
Ivan Krasindf919102016-01-22 22:28:27 +0000237 if (!Options.Reload)
238 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000239 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000240 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000241 for (auto &X : AdditionalCorpus) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000242 if (X.size() > MaxSize)
243 X.resize(MaxSize);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000244 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000245 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000246 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000247 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000248 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000249 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000250 }
251 }
252}
253
Kostya Serebryany945761b2016-03-18 00:23:29 +0000254void Fuzzer::ShuffleCorpus(UnitVector *V) {
255 std::random_shuffle(V->begin(), V->end(), MD.GetRand());
256 if (Options.PreferSmall)
257 std::stable_sort(V->begin(), V->end(), [](const Unit &A, const Unit &B) {
258 return A.size() < B.size();
259 });
260}
261
Aaron Ballmanef116982015-01-29 16:58:29 +0000262void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000263 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000264 std::vector<Unit> NewCorpus;
Kostya Serebryany945761b2016-03-18 00:23:29 +0000265 if (Options.ShuffleAtStartUp)
266 ShuffleCorpus(&Corpus);
267
268 for (const auto &U : Corpus) {
269 if (RunOne(U)) {
270 NewCorpus.push_back(U);
271 if (Options.Verbosity >= 2)
272 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000273 }
274 }
275 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000276 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000277 for (auto &X : Corpus)
278 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000279 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000280}
281
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000282bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000283 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000284
285 PrepareCoverageBeforeRun();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000286 ExecuteCallback(Data, Size);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000287 bool Res = CheckCoverageAfterRun();
288
Kostya Serebryany16901a92015-03-30 23:04:35 +0000289 auto UnitStopTime = system_clock::now();
290 auto TimeOfUnit =
291 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000292 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
293 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000294 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000295 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
296 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000297 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000298 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000299 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000300 }
301 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000302}
303
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000304void Fuzzer::RunOneAndUpdateCorpus(uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000305 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
306 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000307 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000308 ToASCII(Data, Size);
309 if (RunOne(Data, Size))
310 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000311}
312
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000313void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000314 UnitStartTime = system_clock::now();
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000315 // We copy the contents of Unit into a separate heap buffer
316 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000317 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
318 memcpy(DataCopy.get(), Data, Size);
319 AssignTaintLabels(DataCopy.get(), Size);
320 CurrentUnitData = DataCopy.get();
321 CurrentUnitSize = Size;
322 int Res = CB(DataCopy.get(), Size);
Kostya Serebryanyebb932d2016-04-18 22:50:39 +0000323 CurrentUnitSize = 0;
324 CurrentUnitData = nullptr;
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000325 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000326 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000327}
328
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000329size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000330 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000331 uintptr_t PrevCoverage = LastRecordedBlockCoverage;
332 LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
333
334 if (PrevCoverage == LastRecordedBlockCoverage || !Options.PrintNewCovPcs)
335 return LastRecordedBlockCoverage;
336
337 uintptr_t PrevBufferLen = LastCoveragePcBufferLen;
338 uintptr_t *CoverageBuf;
339 LastCoveragePcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
340 assert(CoverageBuf);
341 for (size_t i = PrevBufferLen; i < LastCoveragePcBufferLen; ++i) {
Mike Aizatskye313f8f2016-01-21 00:02:09 +0000342 Printf("%p\n", CoverageBuf[i]);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000343 }
344
345 return LastRecordedBlockCoverage;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000346}
347
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000348size_t Fuzzer::RecordCallerCalleeCoverage() {
349 if (!Options.UseIndirCalls)
350 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000351 if (!__sanitizer_get_total_unique_caller_callee_pairs)
352 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000353 return LastRecordedCallerCalleeCoverage =
354 __sanitizer_get_total_unique_caller_callee_pairs();
355}
356
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000357void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000358 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000359 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000360 CounterBitmap.resize(NumCounters);
361 __sanitizer_update_counter_bitset_and_clear_counters(0);
362 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000363 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000364 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000365}
366
367bool Fuzzer::CheckCoverageAfterRun() {
368 size_t OldCoverage = LastRecordedBlockCoverage;
369 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000370 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
371 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000372 size_t NumNewBits = 0;
Kostya Serebryanyda63c1d2016-02-26 21:33:56 +0000373 size_t OldPcMapSize = LastRecordedPcMapSize;
374 PcMapMergeCurrentToCombined();
375 size_t NewPcMapSize = PcMapCombinedSize();
376 LastRecordedPcMapSize = NewPcMapSize;
377 if (NewPcMapSize > OldPcMapSize)
378 return true;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000379 if (Options.UseCounters)
380 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
381 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000382 return NewCoverage > OldCoverage ||
383 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000384}
385
386void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Ivan Krasindf919102016-01-22 22:28:27 +0000387 if (Options.OutputCorpus.empty())
388 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000389 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
390 WriteToFile(U, Path);
391 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000392 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000393 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000394}
395
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000396void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000397 if (!Options.SaveArtifacts)
398 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000399 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000400 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000401 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000402 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000403 Printf("artifact_prefix='%s'; Test unit written to %s\n",
404 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000405 if (U.size() <= kMaxUnitSizeToPrint)
406 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000407}
408
409void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000410 if (Options.OutputCorpus.empty())
411 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000412 for (const auto &U : Corpus)
413 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
414 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000415 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
416 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000417}
418
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000419void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
420 if (!Options.PrintNEW)
421 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000422 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000423 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000424 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000425 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000426 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000427 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000428}
429
430void Fuzzer::ReportNewCoverage(const Unit &U) {
431 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000432 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000433 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000434 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000435 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000436 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000437 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000438}
439
Kostya Serebryany945761b2016-03-18 00:23:29 +0000440// Finds minimal number of units in 'Extra' that add coverage to 'Initial'.
441// We do it by actually executing the units, sometimes more than once,
442// because we may be using different coverage-like signals and the only
443// common thing between them is that we can say "this unit found new stuff".
444UnitVector Fuzzer::FindExtraUnits(const UnitVector &Initial,
445 const UnitVector &Extra) {
446 UnitVector Res = Extra;
447 size_t OldSize = Res.size();
448 for (int Iter = 0; Iter < 10; Iter++) {
449 ShuffleCorpus(&Res);
450 ResetCoverage();
451
452 for (auto &U : Initial)
453 RunOne(U);
454
455 Corpus.clear();
456 for (auto &U : Res)
457 if (RunOne(U))
458 Corpus.push_back(U);
459
460 char Stat[7] = "MIN ";
461 Stat[3] = '0' + Iter;
462 PrintStats(Stat);
463
464 size_t NewSize = Corpus.size();
465 Res.swap(Corpus);
466
467 if (NewSize == OldSize)
468 break;
469 OldSize = NewSize;
470 }
471 return Res;
472}
473
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000474void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
475 if (Corpora.size() <= 1) {
476 Printf("Merge requires two or more corpus dirs\n");
477 return;
478 }
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000479 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
480
Kostya Serebryany945761b2016-03-18 00:23:29 +0000481 assert(Options.MaxLen > 0);
482 UnitVector Initial, Extra;
483 ReadDirToVectorOfUnits(Corpora[0].c_str(), &Initial, nullptr, Options.MaxLen);
484 for (auto &C : ExtraCorpora)
485 ReadDirToVectorOfUnits(C.c_str(), &Extra, nullptr, Options.MaxLen);
486
487 if (!Initial.empty()) {
488 Printf("=== Minimizing the initial corpus of %zd units\n", Initial.size());
489 Initial = FindExtraUnits({}, Initial);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000490 }
Kostya Serebryany945761b2016-03-18 00:23:29 +0000491
492 Printf("=== Merging extra %zd units\n", Extra.size());
493 auto Res = FindExtraUnits(Initial, Extra);
494
495 for (auto &U: Res)
496 WriteToOutputCorpus(U);
497
498 Printf("=== Merge: written %zd units\n", Res.size());
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000499}
500
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000501void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000502 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000503
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000504 auto &U = ChooseUnitToMutate();
505 MutateInPlaceHere.resize(Options.MaxLen);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000506 size_t Size = U.size();
Mike Aizatsky94e29662016-04-08 23:32:24 +0000507 assert(Size <= Options.MaxLen && "Oversized Unit");
508 memcpy(MutateInPlaceHere.data(), U.data(), Size);
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000509
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000510 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000511 size_t NewSize = 0;
512 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000513 NewSize = LLVMFuzzerCustomMutator(MutateInPlaceHere.data(), Size,
514 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000515 else
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000516 NewSize = MD.Mutate(MutateInPlaceHere.data(), Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000517 assert(NewSize > 0 && "Mutator returned empty unit");
Kostya Serebryany64d24572016-03-12 01:57:04 +0000518 assert(NewSize <= Options.MaxLen &&
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000519 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000520 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000521 if (i == 0)
522 StartTraceRecording();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000523 RunOneAndUpdateCorpus(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000524 StopTraceRecording();
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000525 }
526}
527
Kostya Serebryanye6926212015-11-04 23:22:25 +0000528// Returns an index of random unit from the corpus to mutate.
529// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000530// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000531size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000532 size_t Idx =
533 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000534 assert(Idx < Corpus.size());
535 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000536}
537
Kostya Serebryany945761b2016-03-18 00:23:29 +0000538void Fuzzer::ResetCoverage() {
539 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
540 __sanitizer_reset_coverage();
541 CounterBitmap.clear();
542}
543
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000544// Experimental search heuristic: drilling.
545// - Read, shuffle, execute and minimize the corpus.
546// - Choose one random unit.
547// - Reset the coverage.
548// - Start fuzzing as if the chosen unit was the only element of the corpus.
549// - When done, reset the coverage again.
550// - Merge the newly created corpus into the original one.
551void Fuzzer::Drill() {
552 // The corpus is already read, shuffled, and minimized.
553 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000554 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000555
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000556 Unit U = ChooseUnitToMutate();
557
Kostya Serebryany945761b2016-03-18 00:23:29 +0000558 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000559
560 std::vector<Unit> SavedCorpus;
561 SavedCorpus.swap(Corpus);
562 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000563 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000564 assert(Corpus.size() == 1);
565 RunOne(U);
566 PrintStats("DRILL ");
567 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
568 SavedOutputCorpusPath.swap(Options.OutputCorpus);
569 Loop();
570
Kostya Serebryany945761b2016-03-18 00:23:29 +0000571 ResetCoverage();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000572
573 PrintStats("REINIT");
574 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000575 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000576 RunOne(U);
577 PrintStats("MERGE ");
578 Options.PrintNEW = true;
579 size_t NumMerged = 0;
580 for (auto &U : Corpus) {
581 if (RunOne(U)) {
582 PrintStatusForNewUnit(U);
583 NumMerged++;
584 WriteToOutputCorpus(U);
585 }
586 }
587 PrintStats("MERGED");
588 if (NumMerged && Options.Verbosity)
589 Printf("Drilling discovered %zd new units\n", NumMerged);
590}
591
592void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000593 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000594 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000595 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000596 while (true) {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000597 auto Now = system_clock::now();
598 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
Kostya Serebryany64d24572016-03-12 01:57:04 +0000599 RereadOutputCorpus(Options.MaxLen);
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000600 LastCorpusReload = Now;
601 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000602 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000603 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000604 if (Options.MaxTotalTimeSec > 0 &&
605 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000606 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000607 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000608 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000609 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000610 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000611
612 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000613 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000614}
615
Ivan Krasindf919102016-01-22 22:28:27 +0000616void Fuzzer::UpdateCorpusDistribution() {
617 size_t N = Corpus.size();
618 std::vector<double> Intervals(N + 1);
619 std::vector<double> Weights(N);
620 std::iota(Intervals.begin(), Intervals.end(), 0);
621 std::iota(Weights.begin(), Weights.end(), 1);
622 CorpusDistribution = std::piecewise_constant_distribution<double>(
623 Intervals.begin(), Intervals.end(), Weights.begin());
624}
625
626} // namespace fuzzer