blob: 0438f418957d755d1496482b39a1bcea844f16b5 [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
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000023extern "C" {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000024// Re-declare some of the sanitizer functions as "weak" so that
Kostya Serebryany2a48c242015-11-13 01:54:40 +000025// libFuzzer can be linked w/o the sanitizers and sanitizer-coverage
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000026// (in which case it will complain at start-up time).
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000027__attribute__((weak)) void __sanitizer_print_stack_trace();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +000028__attribute__((weak)) void __sanitizer_reset_coverage();
Kostya Serebryany94660b32015-10-23 18:37:58 +000029__attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000030__attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
Ivan Krasindf919102016-01-22 22:28:27 +000031__attribute__((weak)) void
32__sanitizer_set_death_callback(void (*callback)(void));
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000033__attribute__((weak)) size_t __sanitizer_get_number_of_counters();
Ivan Krasindf919102016-01-22 22:28:27 +000034__attribute__((weak)) uintptr_t
35__sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
Mike Aizatsky8b11f872016-01-06 00:21:22 +000036__attribute__((weak)) uintptr_t
37__sanitizer_get_coverage_pc_buffer(uintptr_t **data);
Kostya Serebryany22cc5e22016-02-13 02:29:38 +000038
39__attribute__((weak)) size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
40 size_t MaxSize,
41 unsigned int Seed);
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000042}
43
Aaron Ballmanef116982015-01-29 16:58:29 +000044namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000045static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000046
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000047static void MissingWeakApiFunction(const char *FnName) {
48 Printf("ERROR: %s is not defined. Exiting.\n"
Ivan Krasindf919102016-01-22 22:28:27 +000049 "Did you use -fsanitize-coverage=... to build your code?\n",
50 FnName);
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000051 exit(1);
52}
53
54#define CHECK_WEAK_API_FUNCTION(fn) \
55 do { \
56 if (!fn) \
57 MissingWeakApiFunction(#fn); \
58 } while (false)
59
Kostya Serebryany52a788e2015-03-31 20:13:20 +000060// Only one Fuzzer per process.
61static Fuzzer *F;
62
Kostya Serebryany1deb0492016-02-13 06:24:18 +000063size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
64 assert(F);
65 return F->GetMD().Mutate(Data, Size, MaxSize);
66}
67
Kostya Serebryany7ec0c562016-02-13 03:25:16 +000068Fuzzer::Fuzzer(UserCallback CB, MutationDispatcher &MD, FuzzingOptions Options)
69 : CB(CB), MD(MD), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000070 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000071 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000072 assert(!F);
73 F = this;
74}
Aaron Ballmanef116982015-01-29 16:58:29 +000075
76void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000077 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000078 __sanitizer_set_death_callback(StaticDeathCallback);
79}
80
Kostya Serebryany52a788e2015-03-31 20:13:20 +000081void Fuzzer::StaticDeathCallback() {
82 assert(F);
83 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000084}
85
Kostya Serebryany228d5b12016-03-01 22:19:21 +000086void Fuzzer::DumpCurrentUnit(const char *Prefix) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000087 if (CurrentUnitSize <= kMaxUnitSizeToPrint) {
88 PrintHexArray(CurrentUnitData, CurrentUnitSize, "\n");
89 PrintASCII(CurrentUnitData, CurrentUnitSize, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000090 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000091 WriteUnitToFileWithPrefix(
Kostya Serebryany228d5b12016-03-01 22:19:21 +000092 {CurrentUnitData, CurrentUnitData + CurrentUnitSize}, Prefix);
93}
94
95void Fuzzer::DeathCallback() {
96 if (!CurrentUnitSize) return;
97 Printf("DEATH:\n");
98 DumpCurrentUnit("crash-");
Kostya Serebryany66ff0752016-02-26 22:42:23 +000099 PrintFinalStats();
Aaron Ballmanef116982015-01-29 16:58:29 +0000100}
101
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000102void Fuzzer::StaticAlarmCallback() {
103 assert(F);
104 F->AlarmCallback();
105}
106
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000107void Fuzzer::StaticCrashSignalCallback() {
108 assert(F);
109 F->CrashCallback();
110}
111
112void Fuzzer::StaticInterruptCallback() {
113 assert(F);
114 F->InterruptCallback();
115}
116
117void Fuzzer::CrashCallback() {
118 Printf("==%d== ERROR: libFuzzer: deadly signal\n", GetPid());
119 if (__sanitizer_print_stack_trace)
120 __sanitizer_print_stack_trace();
121 Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
122 " Combine libFuzzer with AddressSanitizer or similar for better "
123 "crash reports.\n");
124 Printf("SUMMARY: libFuzzer: deadly signal\n");
125 DumpCurrentUnit("crash-");
126 PrintFinalStats();
127 exit(Options.ErrorExitCode);
128}
129
130void Fuzzer::InterruptCallback() {
131 Printf("==%d== libFuzzer: run interrupted; exiting\n", GetPid());
132 PrintFinalStats();
Kostya Serebryanye483ed22016-03-03 22:36:37 +0000133 _Exit(0); // Stop right now, don't perform any at-exit actions.
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000134}
135
Aaron Ballmanef116982015-01-29 16:58:29 +0000136void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000137 assert(Options.UnitTimeoutSec > 0);
Kostya Serebryanycfbcf902016-02-17 19:42:34 +0000138 if (!CurrentUnitSize)
139 return; // We have not started running units yet.
Aaron Ballmanef116982015-01-29 16:58:29 +0000140 size_t Seconds =
141 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Ivan Krasindf919102016-01-22 22:28:27 +0000142 if (Seconds == 0)
143 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000144 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000145 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000146 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000147 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000148 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
149 Options.UnitTimeoutSec);
Kostya Serebryany228d5b12016-03-01 22:19:21 +0000150 DumpCurrentUnit("timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000151 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
152 Seconds);
153 if (__sanitizer_print_stack_trace)
154 __sanitizer_print_stack_trace();
155 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000156 PrintFinalStats();
Kostya Serebryany54a63632016-01-29 23:30:07 +0000157 exit(Options.TimeoutExitCode);
Aaron Ballmanef116982015-01-29 16:58:29 +0000158 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000159}
160
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000161void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000162 size_t ExecPerSec = execPerSec();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000163 if (Options.OutputCSV) {
164 static bool csvHeaderPrinted = false;
165 if (!csvHeaderPrinted) {
166 csvHeaderPrinted = true;
167 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
168 }
169 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
170 LastRecordedBlockCoverage, TotalBits(),
171 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
172 TotalNumberOfExecutedTraceBasedMutations, Where);
173 }
174
175 if (!Options.Verbosity)
176 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000177 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000178 if (LastRecordedBlockCoverage)
179 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryanyda63c1d2016-02-26 21:33:56 +0000180 if (LastRecordedPcMapSize)
181 Printf(" path: %zd", LastRecordedPcMapSize);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000182 if (auto TB = TotalBits())
183 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000184 if (LastRecordedCallerCalleeCoverage)
185 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000186 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000187 if (TotalNumberOfExecutedTraceBasedMutations)
188 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
189 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000190}
191
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000192void Fuzzer::PrintFinalStats() {
193 if (!Options.PrintFinalStats) return;
194 size_t ExecPerSec = execPerSec();
195 Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
196 Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
197 Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
198 Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
199 Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
200}
201
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000202void Fuzzer::RereadOutputCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000203 if (Options.OutputCorpus.empty())
204 return;
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000205 std::vector<Unit> AdditionalCorpus;
206 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
Kostya Serebryanya35f7d32016-02-18 21:49:10 +0000207 &EpochOfLastReadOfOutputCorpus, Options.MaxLen);
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000208 if (Corpus.empty()) {
209 Corpus = AdditionalCorpus;
210 return;
211 }
Ivan Krasindf919102016-01-22 22:28:27 +0000212 if (!Options.Reload)
213 return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000214 if (Options.Verbosity >= 2)
Ivan Krasindf919102016-01-22 22:28:27 +0000215 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000216 for (auto &X : AdditionalCorpus) {
217 if (X.size() > (size_t)Options.MaxLen)
218 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000219 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000220 if (RunOne(X)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000221 Corpus.push_back(X);
Ivan Krasindf919102016-01-22 22:28:27 +0000222 UpdateCorpusDistribution();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000223 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000224 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000225 }
226 }
227}
228
Aaron Ballmanef116982015-01-29 16:58:29 +0000229void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000230 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
231 (Options.PreferSmallDuringInitialShuffle == -1 &&
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000232 MD.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000233 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000234 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000235 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000236 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000237 if (Options.ShuffleAtStartUp) {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000238 std::random_shuffle(Corpus.begin(), Corpus.end(), MD.GetRand());
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000239 if (PreferSmall)
240 std::stable_sort(
241 Corpus.begin(), Corpus.end(),
242 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
243 }
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000244 Unit U;
Aaron Ballmanef116982015-01-29 16:58:29 +0000245 for (const auto &C : Corpus) {
246 for (size_t First = 0; First < 1; First++) {
247 U.clear();
248 size_t Last = std::min(First + Options.MaxLen, C.size());
249 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000250 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000251 ToASCII(U.data(), U.size());
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000252 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000253 NewCorpus.push_back(U);
254 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000255 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000256 }
257 }
258 }
259 Corpus = NewCorpus;
Ivan Krasindf919102016-01-22 22:28:27 +0000260 UpdateCorpusDistribution();
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000261 for (auto &X : Corpus)
262 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000263 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000264}
265
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000266bool Fuzzer::RunOne(const uint8_t *Data, size_t Size) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000267 UnitStartTime = system_clock::now();
268 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000269
270 PrepareCoverageBeforeRun();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000271 ExecuteCallback(Data, Size);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000272 bool Res = CheckCoverageAfterRun();
273
Kostya Serebryany16901a92015-03-30 23:04:35 +0000274 auto UnitStopTime = system_clock::now();
275 auto TimeOfUnit =
276 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000277 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
278 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000279 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000280 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
281 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000282 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000283 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000284 WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000285 }
286 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000287}
288
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000289void Fuzzer::RunOneAndUpdateCorpus(uint8_t *Data, size_t Size) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000290 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
291 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000292 if (Options.OnlyASCII)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000293 ToASCII(Data, Size);
294 if (RunOne(Data, Size))
295 ReportNewCoverage({Data, Data + Size});
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000296}
297
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000298void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) {
Kostya Serebryanyd50a3ee2016-01-13 23:02:30 +0000299 // We copy the contents of Unit into a separate heap buffer
300 // so that we reliably find buffer overflows in it.
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000301 std::unique_ptr<uint8_t[]> DataCopy(new uint8_t[Size]);
302 memcpy(DataCopy.get(), Data, Size);
303 AssignTaintLabels(DataCopy.get(), Size);
304 CurrentUnitData = DataCopy.get();
305 CurrentUnitSize = Size;
306 int Res = CB(DataCopy.get(), Size);
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000307 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000308 assert(Res == 0);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000309 CurrentUnitData = nullptr;
310 CurrentUnitSize = 0;
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000311}
312
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000313size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000314 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000315 uintptr_t PrevCoverage = LastRecordedBlockCoverage;
316 LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
317
318 if (PrevCoverage == LastRecordedBlockCoverage || !Options.PrintNewCovPcs)
319 return LastRecordedBlockCoverage;
320
321 uintptr_t PrevBufferLen = LastCoveragePcBufferLen;
322 uintptr_t *CoverageBuf;
323 LastCoveragePcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
324 assert(CoverageBuf);
325 for (size_t i = PrevBufferLen; i < LastCoveragePcBufferLen; ++i) {
Mike Aizatskye313f8f2016-01-21 00:02:09 +0000326 Printf("%p\n", CoverageBuf[i]);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000327 }
328
329 return LastRecordedBlockCoverage;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000330}
331
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000332size_t Fuzzer::RecordCallerCalleeCoverage() {
333 if (!Options.UseIndirCalls)
334 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000335 if (!__sanitizer_get_total_unique_caller_callee_pairs)
336 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000337 return LastRecordedCallerCalleeCoverage =
338 __sanitizer_get_total_unique_caller_callee_pairs();
339}
340
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000341void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000342 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000343 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000344 CounterBitmap.resize(NumCounters);
345 __sanitizer_update_counter_bitset_and_clear_counters(0);
346 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000347 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000348 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000349}
350
351bool Fuzzer::CheckCoverageAfterRun() {
352 size_t OldCoverage = LastRecordedBlockCoverage;
353 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000354 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
355 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000356 size_t NumNewBits = 0;
Kostya Serebryanyda63c1d2016-02-26 21:33:56 +0000357 size_t OldPcMapSize = LastRecordedPcMapSize;
358 PcMapMergeCurrentToCombined();
359 size_t NewPcMapSize = PcMapCombinedSize();
360 LastRecordedPcMapSize = NewPcMapSize;
361 if (NewPcMapSize > OldPcMapSize)
362 return true;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000363 if (Options.UseCounters)
364 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
365 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000366 return NewCoverage > OldCoverage ||
367 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000368}
369
370void Fuzzer::WriteToOutputCorpus(const Unit &U) {
Ivan Krasindf919102016-01-22 22:28:27 +0000371 if (Options.OutputCorpus.empty())
372 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000373 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
374 WriteToFile(U, Path);
375 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000376 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000377 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000378}
379
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000380void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000381 if (!Options.SaveArtifacts)
382 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000383 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000384 if (!Options.ExactArtifactPath.empty())
Ivan Krasindf919102016-01-22 22:28:27 +0000385 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000386 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000387 Printf("artifact_prefix='%s'; Test unit written to %s\n",
388 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000389 if (U.size() <= kMaxUnitSizeToPrint)
390 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000391}
392
393void Fuzzer::SaveCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000394 if (Options.OutputCorpus.empty())
395 return;
Aaron Ballmanef116982015-01-29 16:58:29 +0000396 for (const auto &U : Corpus)
397 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
398 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000399 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
400 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000401}
402
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000403void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
404 if (!Options.PrintNEW)
405 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000406 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000407 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000408 Printf(" L: %zd ", U.size());
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000409 MD.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000410 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000411 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000412}
413
414void Fuzzer::ReportNewCoverage(const Unit &U) {
415 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000416 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000417 UnitHashesAddedToCorpus.insert(Hash(U));
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000418 MD.RecordSuccessfulMutationSequence();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000419 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000420 WriteToOutputCorpus(U);
Kostya Serebryany66ff0752016-02-26 22:42:23 +0000421 NumberOfNewUnitsAdded++;
Aaron Ballmanef116982015-01-29 16:58:29 +0000422}
423
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000424void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
425 if (Corpora.size() <= 1) {
426 Printf("Merge requires two or more corpus dirs\n");
427 return;
428 }
429 auto InitialCorpusDir = Corpora[0];
Kostya Serebryanya35f7d32016-02-18 21:49:10 +0000430 ReadDir(InitialCorpusDir, nullptr, Options.MaxLen);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000431 Printf("Merge: running the initial corpus '%s' of %d units\n",
432 InitialCorpusDir.c_str(), Corpus.size());
433 for (auto &U : Corpus)
434 RunOne(U);
435
436 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
437
438 size_t NumTried = 0;
439 size_t NumMerged = 0;
440 for (auto &C : ExtraCorpora) {
441 Corpus.clear();
Kostya Serebryanya35f7d32016-02-18 21:49:10 +0000442 ReadDir(C, nullptr, Options.MaxLen);
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000443 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
444 Corpus.size());
445 for (auto &U : Corpus) {
446 NumTried++;
447 if (RunOne(U)) {
448 WriteToOutputCorpus(U);
449 NumMerged++;
450 }
451 }
452 }
453 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
454}
455
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000456void Fuzzer::MutateAndTestOne() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000457 MD.StartMutationSequence();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000458
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000459 auto &U = ChooseUnitToMutate();
460 MutateInPlaceHere.resize(Options.MaxLen);
461 memcpy(MutateInPlaceHere.data(), U.data(), U.size());
462 size_t Size = U.size();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000463
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000464 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000465 size_t NewSize = 0;
466 if (LLVMFuzzerCustomMutator)
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000467 NewSize = LLVMFuzzerCustomMutator(MutateInPlaceHere.data(), Size,
468 Options.MaxLen, MD.GetRand().Rand());
Kostya Serebryany22cc5e22016-02-13 02:29:38 +0000469 else
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000470 NewSize = MD.Mutate(MutateInPlaceHere.data(), Size, Options.MaxLen);
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000471 assert(NewSize > 0 && "Mutator returned empty unit");
472 assert(NewSize <= (size_t)Options.MaxLen &&
473 "Mutator return overisized unit");
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000474 Size = NewSize;
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000475 if (i == 0)
476 StartTraceRecording();
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000477 RunOneAndUpdateCorpus(MutateInPlaceHere.data(), Size);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000478 StopTraceRecording();
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000479 }
480}
481
Kostya Serebryanye6926212015-11-04 23:22:25 +0000482// Returns an index of random unit from the corpus to mutate.
483// Hypothesis: units added to the corpus last are more likely to be interesting.
Ivan Krasindf919102016-01-22 22:28:27 +0000484// This function gives more weight to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000485size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000486 size_t Idx =
487 static_cast<size_t>(CorpusDistribution(MD.GetRand().Get_mt19937()));
Ivan Krasindf919102016-01-22 22:28:27 +0000488 assert(Idx < Corpus.size());
489 return Idx;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000490}
491
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000492// Experimental search heuristic: drilling.
493// - Read, shuffle, execute and minimize the corpus.
494// - Choose one random unit.
495// - Reset the coverage.
496// - Start fuzzing as if the chosen unit was the only element of the corpus.
497// - When done, reset the coverage again.
498// - Merge the newly created corpus into the original one.
499void Fuzzer::Drill() {
500 // The corpus is already read, shuffled, and minimized.
501 assert(!Corpus.empty());
Ivan Krasindf919102016-01-22 22:28:27 +0000502 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000503
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000504 Unit U = ChooseUnitToMutate();
505
506 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
507 __sanitizer_reset_coverage();
508
509 std::vector<Unit> SavedCorpus;
510 SavedCorpus.swap(Corpus);
511 Corpus.push_back(U);
Ivan Krasindf919102016-01-22 22:28:27 +0000512 UpdateCorpusDistribution();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000513 assert(Corpus.size() == 1);
514 RunOne(U);
515 PrintStats("DRILL ");
516 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
517 SavedOutputCorpusPath.swap(Options.OutputCorpus);
518 Loop();
519
520 __sanitizer_reset_coverage();
521
522 PrintStats("REINIT");
523 SavedOutputCorpusPath.swap(Options.OutputCorpus);
Kostya Serebryany98abb2c2016-01-13 23:46:01 +0000524 for (auto &U : SavedCorpus)
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000525 RunOne(U);
526 PrintStats("MERGE ");
527 Options.PrintNEW = true;
528 size_t NumMerged = 0;
529 for (auto &U : Corpus) {
530 if (RunOne(U)) {
531 PrintStatusForNewUnit(U);
532 NumMerged++;
533 WriteToOutputCorpus(U);
534 }
535 }
536 PrintStats("MERGED");
537 if (NumMerged && Options.Verbosity)
538 Printf("Drilling discovered %zd new units\n", NumMerged);
539}
540
541void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000542 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000543 if (Options.DoCrossOver)
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000544 MD.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000545 while (true) {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000546 SyncCorpus();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000547 auto Now = system_clock::now();
548 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
549 RereadOutputCorpus();
550 LastCorpusReload = Now;
551 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000552 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000553 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000554 if (Options.MaxTotalTimeSec > 0 &&
555 secondsSinceProcessStartUp() >
Ivan Krasindf919102016-01-22 22:28:27 +0000556 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000557 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000558 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000559 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000560 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000561
562 PrintStats("DONE ", "\n");
Kostya Serebryany7ec0c562016-02-13 03:25:16 +0000563 MD.PrintRecommendedDictionary();
Aaron Ballmanef116982015-01-29 16:58:29 +0000564}
565
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000566void Fuzzer::SyncCorpus() {
Ivan Krasindf919102016-01-22 22:28:27 +0000567 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty())
568 return;
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000569 auto Now = system_clock::now();
570 if (duration_cast<seconds>(Now - LastExternalSync).count() <
571 Options.SyncTimeout)
572 return;
573 LastExternalSync = Now;
574 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
575}
576
Ivan Krasindf919102016-01-22 22:28:27 +0000577void Fuzzer::UpdateCorpusDistribution() {
578 size_t N = Corpus.size();
579 std::vector<double> Intervals(N + 1);
580 std::vector<double> Weights(N);
581 std::iota(Intervals.begin(), Intervals.end(), 0);
582 std::iota(Weights.begin(), Weights.end(), 1);
583 CorpusDistribution = std::piecewise_constant_distribution<double>(
584 Intervals.begin(), Intervals.end(), Weights.begin());
585}
586
587} // namespace fuzzer