blob: 089e911a697bfec0aaeed4bb912ee02fc3f415de [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>
Aaron Ballmanef116982015-01-29 16:58:29 +000014
Kostya Serebryany2a48c242015-11-13 01:54:40 +000015#if defined(__has_include)
16# if __has_include(<sanitizer/coverage_interface.h>)
17# include <sanitizer/coverage_interface.h>
18# endif
19#endif
20
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000021extern "C" {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000022// Re-declare some of the sanitizer functions as "weak" so that
Kostya Serebryany2a48c242015-11-13 01:54:40 +000023// libFuzzer can be linked w/o the sanitizers and sanitizer-coverage
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000024// (in which case it will complain at start-up time).
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000025__attribute__((weak)) void __sanitizer_print_stack_trace();
Kostya Serebryanydc3135d2015-11-12 01:02:01 +000026__attribute__((weak)) void __sanitizer_reset_coverage();
Kostya Serebryany94660b32015-10-23 18:37:58 +000027__attribute__((weak)) size_t __sanitizer_get_total_unique_caller_callee_pairs();
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000028__attribute__((weak)) size_t __sanitizer_get_total_unique_coverage();
29__attribute__((weak))
30void __sanitizer_set_death_callback(void (*callback)(void));
31__attribute__((weak)) size_t __sanitizer_get_number_of_counters();
32__attribute__((weak))
33uintptr_t __sanitizer_update_counter_bitset_and_clear_counters(uint8_t *bitset);
Mike Aizatsky8b11f872016-01-06 00:21:22 +000034__attribute__((weak)) uintptr_t
35__sanitizer_get_coverage_pc_buffer(uintptr_t **data);
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000036}
37
Aaron Ballmanef116982015-01-29 16:58:29 +000038namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000039static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000040
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000041static void MissingWeakApiFunction(const char *FnName) {
42 Printf("ERROR: %s is not defined. Exiting.\n"
43 "Did you use -fsanitize-coverage=... to build your code?\n", FnName);
44 exit(1);
45}
46
47#define CHECK_WEAK_API_FUNCTION(fn) \
48 do { \
49 if (!fn) \
50 MissingWeakApiFunction(#fn); \
51 } while (false)
52
Kostya Serebryany52a788e2015-03-31 20:13:20 +000053// Only one Fuzzer per process.
54static Fuzzer *F;
55
Kostya Serebryanyf3424592015-05-22 22:35:31 +000056Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
57 : USF(USF), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000058 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000059 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000060 assert(!F);
61 F = this;
62}
Aaron Ballmanef116982015-01-29 16:58:29 +000063
64void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000065 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000066 __sanitizer_set_death_callback(StaticDeathCallback);
67}
68
Kostya Serebryanyb3602562015-10-22 21:48:09 +000069void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
70 PrintASCII(U, PrintAfter);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000071}
72
73void Fuzzer::StaticDeathCallback() {
74 assert(F);
75 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000076}
77
78void Fuzzer::DeathCallback() {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000079 Printf("DEATH:\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000080 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
81 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +000082 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000083 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +000084 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
Aaron Ballmanef116982015-01-29 16:58:29 +000085}
86
Kostya Serebryany52a788e2015-03-31 20:13:20 +000087void Fuzzer::StaticAlarmCallback() {
88 assert(F);
89 F->AlarmCallback();
90}
91
Aaron Ballmanef116982015-01-29 16:58:29 +000092void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +000093 assert(Options.UnitTimeoutSec > 0);
Aaron Ballmanef116982015-01-29 16:58:29 +000094 size_t Seconds =
95 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Kostya Serebryany490bbd62015-05-19 22:12:57 +000096 if (Seconds == 0) return;
97 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000098 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +000099 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000100 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +0000101 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
102 Options.UnitTimeoutSec);
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000103 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
Kostya Serebryany1165efd2015-07-31 22:07:17 +0000104 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000105 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000106 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000107 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000108 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
109 Seconds);
110 if (__sanitizer_print_stack_trace)
111 __sanitizer_print_stack_trace();
112 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000113 exit(1);
Aaron Ballmanef116982015-01-29 16:58:29 +0000114 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000115}
116
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000117void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000118 size_t Seconds = secondsSinceProcessStartUp();
119 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000120
121 if (Options.OutputCSV) {
122 static bool csvHeaderPrinted = false;
123 if (!csvHeaderPrinted) {
124 csvHeaderPrinted = true;
125 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
126 }
127 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
128 LastRecordedBlockCoverage, TotalBits(),
129 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
130 TotalNumberOfExecutedTraceBasedMutations, Where);
131 }
132
133 if (!Options.Verbosity)
134 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000135 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000136 if (LastRecordedBlockCoverage)
137 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000138 if (auto TB = TotalBits())
139 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000140 if (LastRecordedCallerCalleeCoverage)
141 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000142 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000143 if (TotalNumberOfExecutedTraceBasedMutations)
144 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
145 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000146}
147
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000148void Fuzzer::RereadOutputCorpus() {
149 if (Options.OutputCorpus.empty()) return;
150 std::vector<Unit> AdditionalCorpus;
151 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
152 &EpochOfLastReadOfOutputCorpus);
153 if (Corpus.empty()) {
154 Corpus = AdditionalCorpus;
155 return;
156 }
157 if (!Options.Reload) return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000158 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000159 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000160 for (auto &X : AdditionalCorpus) {
161 if (X.size() > (size_t)Options.MaxLen)
162 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000163 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000164 CurrentUnit.clear();
165 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000166 if (RunOne(CurrentUnit)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000167 Corpus.push_back(X);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000168 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000169 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000170 }
171 }
172}
173
Aaron Ballmanef116982015-01-29 16:58:29 +0000174void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000175 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
176 (Options.PreferSmallDuringInitialShuffle == -1 &&
177 USF.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000178 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000179 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000180 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000181 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000182 if (Options.ShuffleAtStartUp) {
183 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
184 if (PreferSmall)
185 std::stable_sort(
186 Corpus.begin(), Corpus.end(),
187 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
188 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000189 Unit &U = CurrentUnit;
190 for (const auto &C : Corpus) {
191 for (size_t First = 0; First < 1; First++) {
192 U.clear();
193 size_t Last = std::min(First + Options.MaxLen, C.size());
194 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000195 if (Options.OnlyASCII)
196 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000197 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000198 NewCorpus.push_back(U);
199 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000200 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000201 }
202 }
203 }
204 Corpus = NewCorpus;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000205 for (auto &X : Corpus)
206 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000207 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000208}
209
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000210bool Fuzzer::RunOne(const Unit &U) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000211 UnitStartTime = system_clock::now();
212 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000213
214 PrepareCoverageBeforeRun();
215 ExecuteCallback(U);
216 bool Res = CheckCoverageAfterRun();
217
Kostya Serebryany16901a92015-03-30 23:04:35 +0000218 auto UnitStopTime = system_clock::now();
219 auto TimeOfUnit =
220 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000221 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
222 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000223 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000224 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
225 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000226 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000227 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000228 WriteUnitToFileWithPrefix(U, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000229 }
230 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000231}
232
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000233void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000234 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
235 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000236 if (Options.OnlyASCII)
237 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000238 if (RunOne(U))
239 ReportNewCoverage(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000240}
241
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000242void Fuzzer::ExecuteCallback(const Unit &U) {
Mike Aizatsky71552ce2015-12-02 22:43:53 +0000243 const uint8_t *Data = U.data();
244 uint8_t EmptyData;
245 if (!Data)
246 Data = &EmptyData;
247 int Res = USF.TargetFunction(Data, U.size());
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000248 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000249 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000250}
251
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000252size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000253 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Mike Aizatsky8b11f872016-01-06 00:21:22 +0000254 uintptr_t PrevCoverage = LastRecordedBlockCoverage;
255 LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
256
257 if (PrevCoverage == LastRecordedBlockCoverage || !Options.PrintNewCovPcs)
258 return LastRecordedBlockCoverage;
259
260 uintptr_t PrevBufferLen = LastCoveragePcBufferLen;
261 uintptr_t *CoverageBuf;
262 LastCoveragePcBufferLen = __sanitizer_get_coverage_pc_buffer(&CoverageBuf);
263 assert(CoverageBuf);
264 for (size_t i = PrevBufferLen; i < LastCoveragePcBufferLen; ++i) {
265 Printf("0x%x\n", CoverageBuf[i]);
266 }
267
268 return LastRecordedBlockCoverage;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000269}
270
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000271size_t Fuzzer::RecordCallerCalleeCoverage() {
272 if (!Options.UseIndirCalls)
273 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000274 if (!__sanitizer_get_total_unique_caller_callee_pairs)
275 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000276 return LastRecordedCallerCalleeCoverage =
277 __sanitizer_get_total_unique_caller_callee_pairs();
278}
279
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000280void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000281 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000282 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000283 CounterBitmap.resize(NumCounters);
284 __sanitizer_update_counter_bitset_and_clear_counters(0);
285 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000286 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000287 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000288}
289
290bool Fuzzer::CheckCoverageAfterRun() {
291 size_t OldCoverage = LastRecordedBlockCoverage;
292 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000293 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
294 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000295 size_t NumNewBits = 0;
296 if (Options.UseCounters)
297 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
298 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000299 return NewCoverage > OldCoverage ||
300 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000301}
302
303void Fuzzer::WriteToOutputCorpus(const Unit &U) {
304 if (Options.OutputCorpus.empty()) return;
305 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
306 WriteToFile(U, Path);
307 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000308 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000309 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000310}
311
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000312void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000313 if (!Options.SaveArtifacts)
314 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000315 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000316 if (!Options.ExactArtifactPath.empty())
317 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000318 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000319 Printf("artifact_prefix='%s'; Test unit written to %s\n",
320 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000321 if (U.size() <= kMaxUnitSizeToPrint)
322 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000323}
324
325void Fuzzer::SaveCorpus() {
326 if (Options.OutputCorpus.empty()) return;
327 for (const auto &U : Corpus)
328 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
329 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000330 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
331 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000332}
333
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000334void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
335 if (!Options.PrintNEW)
336 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000337 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000338 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000339 Printf(" L: %zd ", U.size());
340 USF.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000341 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000342 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000343}
344
345void Fuzzer::ReportNewCoverage(const Unit &U) {
346 Corpus.push_back(U);
347 UnitHashesAddedToCorpus.insert(Hash(U));
348 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000349 WriteToOutputCorpus(U);
350 if (Options.ExitOnFirst)
351 exit(0);
Aaron Ballmanef116982015-01-29 16:58:29 +0000352}
353
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000354void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
355 if (Corpora.size() <= 1) {
356 Printf("Merge requires two or more corpus dirs\n");
357 return;
358 }
359 auto InitialCorpusDir = Corpora[0];
360 ReadDir(InitialCorpusDir, nullptr);
361 Printf("Merge: running the initial corpus '%s' of %d units\n",
362 InitialCorpusDir.c_str(), Corpus.size());
363 for (auto &U : Corpus)
364 RunOne(U);
365
366 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
367
368 size_t NumTried = 0;
369 size_t NumMerged = 0;
370 for (auto &C : ExtraCorpora) {
371 Corpus.clear();
372 ReadDir(C, nullptr);
373 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
374 Corpus.size());
375 for (auto &U : Corpus) {
376 NumTried++;
377 if (RunOne(U)) {
378 WriteToOutputCorpus(U);
379 NumMerged++;
380 }
381 }
382 }
383 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
384}
385
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000386void Fuzzer::MutateAndTestOne() {
387 auto &U = CurrentUnit;
388 USF.StartMutationSequence();
389
390 U = ChooseUnitToMutate();
391
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000392 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000393 size_t Size = U.size();
394 U.resize(Options.MaxLen);
395 size_t NewSize = USF.Mutate(U.data(), Size, U.size());
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000396 assert(NewSize > 0 && "Mutator returned empty unit");
397 assert(NewSize <= (size_t)Options.MaxLen &&
398 "Mutator return overisized unit");
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000399 U.resize(NewSize);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000400 if (i == 0)
401 StartTraceRecording();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000402 RunOneAndUpdateCorpus(U);
Kostya Serebryanyb65805a2016-01-09 03:08:58 +0000403 StopTraceRecording();
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000404 }
405}
406
Kostya Serebryanye6926212015-11-04 23:22:25 +0000407// Returns an index of random unit from the corpus to mutate.
408// Hypothesis: units added to the corpus last are more likely to be interesting.
409// This function gives more wieght to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000410size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000411 size_t N = Corpus.size();
412 size_t Total = (N + 1) * N / 2;
413 size_t R = USF.GetRand()(Total);
414 size_t IdxBeg = 0, IdxEnd = N;
415 // Binary search.
416 while (IdxEnd - IdxBeg >= 2) {
417 size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
418 if (R > (Idx + 1) * Idx / 2)
419 IdxBeg = Idx;
420 else
421 IdxEnd = Idx;
422 }
423 assert(IdxBeg < N);
424 return IdxBeg;
425}
426
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000427// Experimental search heuristic: drilling.
428// - Read, shuffle, execute and minimize the corpus.
429// - Choose one random unit.
430// - Reset the coverage.
431// - Start fuzzing as if the chosen unit was the only element of the corpus.
432// - When done, reset the coverage again.
433// - Merge the newly created corpus into the original one.
434void Fuzzer::Drill() {
435 // The corpus is already read, shuffled, and minimized.
436 assert(!Corpus.empty());
437 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000438
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000439 Unit U = ChooseUnitToMutate();
440
441 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
442 __sanitizer_reset_coverage();
443
444 std::vector<Unit> SavedCorpus;
445 SavedCorpus.swap(Corpus);
446 Corpus.push_back(U);
447 assert(Corpus.size() == 1);
448 RunOne(U);
449 PrintStats("DRILL ");
450 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
451 SavedOutputCorpusPath.swap(Options.OutputCorpus);
452 Loop();
453
454 __sanitizer_reset_coverage();
455
456 PrintStats("REINIT");
457 SavedOutputCorpusPath.swap(Options.OutputCorpus);
458 for (auto &U : SavedCorpus)
459 RunOne(U);
460 PrintStats("MERGE ");
461 Options.PrintNEW = true;
462 size_t NumMerged = 0;
463 for (auto &U : Corpus) {
464 if (RunOne(U)) {
465 PrintStatusForNewUnit(U);
466 NumMerged++;
467 WriteToOutputCorpus(U);
468 }
469 }
470 PrintStats("MERGED");
471 if (NumMerged && Options.Verbosity)
472 Printf("Drilling discovered %zd new units\n", NumMerged);
473}
474
475void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000476 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000477 if (Options.DoCrossOver)
478 USF.SetCorpus(&Corpus);
Kostya Serebryany468ed782015-09-08 17:30:35 +0000479 while (true) {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000480 SyncCorpus();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000481 auto Now = system_clock::now();
482 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
483 RereadOutputCorpus();
484 LastCorpusReload = Now;
485 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000486 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000487 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000488 if (Options.MaxTotalTimeSec > 0 &&
489 secondsSinceProcessStartUp() >
490 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000491 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000492 // Perform several mutations and runs.
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000493 MutateAndTestOne();
Aaron Ballmanef116982015-01-29 16:58:29 +0000494 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000495
496 PrintStats("DONE ", "\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000497}
498
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000499void Fuzzer::SyncCorpus() {
500 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
501 auto Now = system_clock::now();
502 if (duration_cast<seconds>(Now - LastExternalSync).count() <
503 Options.SyncTimeout)
504 return;
505 LastExternalSync = Now;
506 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
507}
508
Aaron Ballmanef116982015-01-29 16:58:29 +0000509} // namespace fuzzer