blob: b1ce294b97210d4819b44918073a7ffa18d0956b [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);
Kostya Serebryanyd6edce92015-10-16 23:04:31 +000034}
35
Aaron Ballmanef116982015-01-29 16:58:29 +000036namespace fuzzer {
Kostya Serebryanya9da9b42015-10-16 22:47:20 +000037static const size_t kMaxUnitSizeToPrint = 256;
Aaron Ballmanef116982015-01-29 16:58:29 +000038
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000039static void MissingWeakApiFunction(const char *FnName) {
40 Printf("ERROR: %s is not defined. Exiting.\n"
41 "Did you use -fsanitize-coverage=... to build your code?\n", FnName);
42 exit(1);
43}
44
45#define CHECK_WEAK_API_FUNCTION(fn) \
46 do { \
47 if (!fn) \
48 MissingWeakApiFunction(#fn); \
49 } while (false)
50
Kostya Serebryany52a788e2015-03-31 20:13:20 +000051// Only one Fuzzer per process.
52static Fuzzer *F;
53
Kostya Serebryanyf3424592015-05-22 22:35:31 +000054Fuzzer::Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options)
55 : USF(USF), Options(Options) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000056 SetDeathCallback();
Kostya Serebryany22526252015-05-11 21:16:27 +000057 InitializeTraceState();
Kostya Serebryany52a788e2015-03-31 20:13:20 +000058 assert(!F);
59 F = this;
60}
Aaron Ballmanef116982015-01-29 16:58:29 +000061
62void Fuzzer::SetDeathCallback() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +000063 CHECK_WEAK_API_FUNCTION(__sanitizer_set_death_callback);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000064 __sanitizer_set_death_callback(StaticDeathCallback);
65}
66
Kostya Serebryanyb3602562015-10-22 21:48:09 +000067void Fuzzer::PrintUnitInASCII(const Unit &U, const char *PrintAfter) {
68 PrintASCII(U, PrintAfter);
Kostya Serebryany52a788e2015-03-31 20:13:20 +000069}
70
71void Fuzzer::StaticDeathCallback() {
72 assert(F);
73 F->DeathCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000074}
75
76void Fuzzer::DeathCallback() {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000077 Printf("DEATH:\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000078 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
79 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +000080 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +000081 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +000082 WriteUnitToFileWithPrefix(CurrentUnit, "crash-");
Aaron Ballmanef116982015-01-29 16:58:29 +000083}
84
Kostya Serebryany52a788e2015-03-31 20:13:20 +000085void Fuzzer::StaticAlarmCallback() {
86 assert(F);
87 F->AlarmCallback();
88}
89
Aaron Ballmanef116982015-01-29 16:58:29 +000090void Fuzzer::AlarmCallback() {
Kostya Serebryany490bbd62015-05-19 22:12:57 +000091 assert(Options.UnitTimeoutSec > 0);
Aaron Ballmanef116982015-01-29 16:58:29 +000092 size_t Seconds =
93 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
Kostya Serebryany490bbd62015-05-19 22:12:57 +000094 if (Seconds == 0) return;
95 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000096 Printf("AlarmCallback %zd\n", Seconds);
Kostya Serebryany490bbd62015-05-19 22:12:57 +000097 if (Seconds >= (size_t)Options.UnitTimeoutSec) {
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000098 Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
Kostya Serebryany316b5712015-05-26 20:57:47 +000099 Printf(" and the timeout value is %d (use -timeout=N to change)\n",
100 Options.UnitTimeoutSec);
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000101 if (CurrentUnit.size() <= kMaxUnitSizeToPrint) {
Kostya Serebryany1165efd2015-07-31 22:07:17 +0000102 Print(CurrentUnit, "\n");
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000103 PrintUnitInASCII(CurrentUnit, "\n");
Kostya Serebryanye95022a2015-10-09 04:03:14 +0000104 }
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000105 WriteUnitToFileWithPrefix(CurrentUnit, "timeout-");
Kostya Serebryanyd6edce92015-10-16 23:04:31 +0000106 Printf("==%d== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
107 Seconds);
108 if (__sanitizer_print_stack_trace)
109 __sanitizer_print_stack_trace();
110 Printf("SUMMARY: libFuzzer: timeout\n");
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000111 exit(1);
Aaron Ballmanef116982015-01-29 16:58:29 +0000112 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000113}
114
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000115void Fuzzer::PrintStats(const char *Where, const char *End) {
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000116 size_t Seconds = secondsSinceProcessStartUp();
117 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000118
119 if (Options.OutputCSV) {
120 static bool csvHeaderPrinted = false;
121 if (!csvHeaderPrinted) {
122 csvHeaderPrinted = true;
123 Printf("runs,block_cov,bits,cc_cov,corpus,execs_per_sec,tbms,reason\n");
124 }
125 Printf("%zd,%zd,%zd,%zd,%zd,%zd,%zd,%s\n", TotalNumberOfRuns,
126 LastRecordedBlockCoverage, TotalBits(),
127 LastRecordedCallerCalleeCoverage, Corpus.size(), ExecPerSec,
128 TotalNumberOfExecutedTraceBasedMutations, Where);
129 }
130
131 if (!Options.Verbosity)
132 return;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000133 Printf("#%zd\t%s", TotalNumberOfRuns, Where);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000134 if (LastRecordedBlockCoverage)
135 Printf(" cov: %zd", LastRecordedBlockCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000136 if (auto TB = TotalBits())
137 Printf(" bits: %zd", TB);
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000138 if (LastRecordedCallerCalleeCoverage)
139 Printf(" indir: %zd", LastRecordedCallerCalleeCoverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000140 Printf(" units: %zd exec/s: %zd", Corpus.size(), ExecPerSec);
Kostya Serebryany12c78372015-08-12 01:55:37 +0000141 if (TotalNumberOfExecutedTraceBasedMutations)
142 Printf(" tbm: %zd", TotalNumberOfExecutedTraceBasedMutations);
143 Printf("%s", End);
Kostya Serebryany03db8b92015-03-30 22:44:03 +0000144}
145
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000146void Fuzzer::RereadOutputCorpus() {
147 if (Options.OutputCorpus.empty()) return;
148 std::vector<Unit> AdditionalCorpus;
149 ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
150 &EpochOfLastReadOfOutputCorpus);
151 if (Corpus.empty()) {
152 Corpus = AdditionalCorpus;
153 return;
154 }
155 if (!Options.Reload) return;
Kostya Serebryany490bbd62015-05-19 22:12:57 +0000156 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000157 Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000158 for (auto &X : AdditionalCorpus) {
159 if (X.size() > (size_t)Options.MaxLen)
160 X.resize(Options.MaxLen);
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000161 if (UnitHashesAddedToCorpus.insert(Hash(X)).second) {
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000162 CurrentUnit.clear();
163 CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000164 if (RunOne(CurrentUnit)) {
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000165 Corpus.push_back(X);
Mike Aizatskya9c23872015-11-12 04:38:40 +0000166 PrintStats("RELOAD");
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000167 }
Kostya Serebryany1ac80552015-05-08 21:30:55 +0000168 }
169 }
170}
171
Aaron Ballmanef116982015-01-29 16:58:29 +0000172void Fuzzer::ShuffleAndMinimize() {
Kostya Serebryany404c69f2015-07-24 01:06:40 +0000173 bool PreferSmall = (Options.PreferSmallDuringInitialShuffle == 1 ||
174 (Options.PreferSmallDuringInitialShuffle == -1 &&
175 USF.GetRand().RandBool()));
Aaron Ballmanef116982015-01-29 16:58:29 +0000176 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000177 Printf("PreferSmall: %d\n", PreferSmall);
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000178 PrintStats("READ ");
Aaron Ballmanef116982015-01-29 16:58:29 +0000179 std::vector<Unit> NewCorpus;
Kostya Serebryanyfed509e2015-10-17 04:38:26 +0000180 if (Options.ShuffleAtStartUp) {
181 std::random_shuffle(Corpus.begin(), Corpus.end(), USF.GetRand());
182 if (PreferSmall)
183 std::stable_sort(
184 Corpus.begin(), Corpus.end(),
185 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
186 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000187 Unit &U = CurrentUnit;
188 for (const auto &C : Corpus) {
189 for (size_t First = 0; First < 1; First++) {
190 U.clear();
191 size_t Last = std::min(First + Options.MaxLen, C.size());
192 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000193 if (Options.OnlyASCII)
194 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000195 if (RunOne(U)) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000196 NewCorpus.push_back(U);
197 if (Options.Verbosity >= 2)
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000198 Printf("NEW0: %zd L %zd\n", LastRecordedBlockCoverage, U.size());
Aaron Ballmanef116982015-01-29 16:58:29 +0000199 }
200 }
201 }
202 Corpus = NewCorpus;
Kostya Serebryanycbb23342015-05-19 01:06:07 +0000203 for (auto &X : Corpus)
204 UnitHashesAddedToCorpus.insert(Hash(X));
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000205 PrintStats("INITED");
Aaron Ballmanef116982015-01-29 16:58:29 +0000206}
207
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000208bool Fuzzer::RunOne(const Unit &U) {
Aaron Ballmanef116982015-01-29 16:58:29 +0000209 UnitStartTime = system_clock::now();
210 TotalNumberOfRuns++;
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000211
212 PrepareCoverageBeforeRun();
213 ExecuteCallback(U);
214 bool Res = CheckCoverageAfterRun();
215
Kostya Serebryany16901a92015-03-30 23:04:35 +0000216 auto UnitStopTime = system_clock::now();
217 auto TimeOfUnit =
218 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
Mike Aizatskya9c23872015-11-12 04:38:40 +0000219 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
220 secondsSinceProcessStartUp() >= 2)
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000221 PrintStats("pulse ");
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000222 if (TimeOfUnit > TimeOfLongestUnitInSeconds &&
223 TimeOfUnit >= Options.ReportSlowUnits) {
Kostya Serebryany16901a92015-03-30 23:04:35 +0000224 TimeOfLongestUnitInSeconds = TimeOfUnit;
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000225 Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
Kostya Serebryany70926ae2015-08-05 21:43:48 +0000226 WriteUnitToFileWithPrefix(U, "slow-unit-");
Kostya Serebryany16901a92015-03-30 23:04:35 +0000227 }
228 return Res;
Kostya Serebryany2c1b33b2015-01-29 23:01:07 +0000229}
230
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000231void Fuzzer::RunOneAndUpdateCorpus(Unit &U) {
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000232 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
233 return;
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000234 if (Options.OnlyASCII)
235 ToASCII(U);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000236 if (RunOne(U))
237 ReportNewCoverage(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000238}
239
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000240void Fuzzer::ExecuteCallback(const Unit &U) {
Mike Aizatsky71552ce2015-12-02 22:43:53 +0000241 const uint8_t *Data = U.data();
242 uint8_t EmptyData;
243 if (!Data)
244 Data = &EmptyData;
245 int Res = USF.TargetFunction(Data, U.size());
Kostya Serebryanyb3602562015-10-22 21:48:09 +0000246 (void)Res;
Kostya Serebryany20bb5e72015-10-02 23:34:06 +0000247 assert(Res == 0);
Kostya Serebryany52a788e2015-03-31 20:13:20 +0000248}
249
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000250size_t Fuzzer::RecordBlockCoverage() {
Kostya Serebryany5eab74e2015-11-09 23:17:45 +0000251 CHECK_WEAK_API_FUNCTION(__sanitizer_get_total_unique_coverage);
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000252 return LastRecordedBlockCoverage = __sanitizer_get_total_unique_coverage();
253}
254
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000255size_t Fuzzer::RecordCallerCalleeCoverage() {
256 if (!Options.UseIndirCalls)
257 return 0;
Kostya Serebryany94660b32015-10-23 18:37:58 +0000258 if (!__sanitizer_get_total_unique_caller_callee_pairs)
259 return 0;
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000260 return LastRecordedCallerCalleeCoverage =
261 __sanitizer_get_total_unique_caller_callee_pairs();
262}
263
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000264void Fuzzer::PrepareCoverageBeforeRun() {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000265 if (Options.UseCounters) {
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000266 size_t NumCounters = __sanitizer_get_number_of_counters();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000267 CounterBitmap.resize(NumCounters);
268 __sanitizer_update_counter_bitset_and_clear_counters(0);
269 }
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000270 RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000271 RecordCallerCalleeCoverage();
Kostya Serebryany007c9b22015-10-22 22:50:47 +0000272}
273
274bool Fuzzer::CheckCoverageAfterRun() {
275 size_t OldCoverage = LastRecordedBlockCoverage;
276 size_t NewCoverage = RecordBlockCoverage();
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000277 size_t OldCallerCalleeCoverage = LastRecordedCallerCalleeCoverage;
278 size_t NewCallerCalleeCoverage = RecordCallerCalleeCoverage();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000279 size_t NumNewBits = 0;
280 if (Options.UseCounters)
281 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
282 CounterBitmap.data());
Kostya Serebryany2e9fca92015-10-22 23:55:39 +0000283 return NewCoverage > OldCoverage ||
284 NewCallerCalleeCoverage > OldCallerCalleeCoverage || NumNewBits;
Aaron Ballmanef116982015-01-29 16:58:29 +0000285}
286
287void Fuzzer::WriteToOutputCorpus(const Unit &U) {
288 if (Options.OutputCorpus.empty()) return;
289 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
290 WriteToFile(U, Path);
291 if (Options.Verbosity >= 2)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000292 Printf("Written to %s\n", Path.c_str());
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000293 assert(!Options.OnlyASCII || IsASCII(U));
Aaron Ballmanef116982015-01-29 16:58:29 +0000294}
295
Kostya Serebryany2b7d2e92015-07-23 18:37:22 +0000296void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
Kostya Serebryanyb91c62b2015-10-16 22:41:47 +0000297 if (!Options.SaveArtifacts)
298 return;
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000299 std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
Kostya Serebryany2d0ef142015-11-25 21:40:46 +0000300 if (!Options.ExactArtifactPath.empty())
301 Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
Aaron Ballmanef116982015-01-29 16:58:29 +0000302 WriteToFile(U, Path);
Kostya Serebryanybd5d1cd2015-10-09 03:57:59 +0000303 Printf("artifact_prefix='%s'; Test unit written to %s\n",
304 Options.ArtifactPrefix.c_str(), Path.c_str());
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000305 if (U.size() <= kMaxUnitSizeToPrint)
306 Printf("Base64: %s\n", Base64(U).c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000307}
308
309void Fuzzer::SaveCorpus() {
310 if (Options.OutputCorpus.empty()) return;
311 for (const auto &U : Corpus)
312 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
313 if (Options.Verbosity)
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000314 Printf("Written corpus of %zd files to %s\n", Corpus.size(),
315 Options.OutputCorpus.c_str());
Aaron Ballmanef116982015-01-29 16:58:29 +0000316}
317
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000318void Fuzzer::PrintStatusForNewUnit(const Unit &U) {
319 if (!Options.PrintNEW)
320 return;
Kostya Serebryany09d2a5f2015-10-22 22:56:45 +0000321 PrintStats("NEW ", "");
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000322 if (Options.Verbosity) {
Kostya Serebryany14c50282015-12-19 01:09:49 +0000323 Printf(" L: %zd ", U.size());
324 USF.PrintMutationSequence();
Kostya Serebryany7c180ea2015-05-23 01:22:35 +0000325 Printf("\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000326 }
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000327}
328
329void Fuzzer::ReportNewCoverage(const Unit &U) {
330 Corpus.push_back(U);
331 UnitHashesAddedToCorpus.insert(Hash(U));
332 PrintStatusForNewUnit(U);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000333 WriteToOutputCorpus(U);
334 if (Options.ExitOnFirst)
335 exit(0);
Aaron Ballmanef116982015-01-29 16:58:29 +0000336}
337
Kostya Serebryany9cc3b0d2015-10-24 01:16:40 +0000338void Fuzzer::Merge(const std::vector<std::string> &Corpora) {
339 if (Corpora.size() <= 1) {
340 Printf("Merge requires two or more corpus dirs\n");
341 return;
342 }
343 auto InitialCorpusDir = Corpora[0];
344 ReadDir(InitialCorpusDir, nullptr);
345 Printf("Merge: running the initial corpus '%s' of %d units\n",
346 InitialCorpusDir.c_str(), Corpus.size());
347 for (auto &U : Corpus)
348 RunOne(U);
349
350 std::vector<std::string> ExtraCorpora(Corpora.begin() + 1, Corpora.end());
351
352 size_t NumTried = 0;
353 size_t NumMerged = 0;
354 for (auto &C : ExtraCorpora) {
355 Corpus.clear();
356 ReadDir(C, nullptr);
357 Printf("Merge: merging the extra corpus '%s' of %zd units\n", C.c_str(),
358 Corpus.size());
359 for (auto &U : Corpus) {
360 NumTried++;
361 if (RunOne(U)) {
362 WriteToOutputCorpus(U);
363 NumMerged++;
364 }
365 }
366 }
367 Printf("Merge: written %zd out of %zd units\n", NumMerged, NumTried);
368}
369
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000370void Fuzzer::MutateAndTestOne(Unit *U) {
371 for (int i = 0; i < Options.MutateDepth; i++) {
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000372 StartTraceRecording();
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000373 size_t Size = U->size();
374 U->resize(Options.MaxLen);
375 size_t NewSize = USF.Mutate(U->data(), Size, U->size());
Kostya Serebryany2ea204e2015-05-30 17:33:13 +0000376 assert(NewSize > 0 && "Mutator returned empty unit");
377 assert(NewSize <= (size_t)Options.MaxLen &&
378 "Mutator return overisized unit");
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000379 U->resize(NewSize);
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000380 RunOneAndUpdateCorpus(*U);
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000381 size_t NumTraceBasedMutations = StopTraceRecording();
Kostya Serebryany12c78372015-08-12 01:55:37 +0000382 size_t TBMWidth =
383 std::min((size_t)Options.TBMWidth, NumTraceBasedMutations);
384 size_t TBMDepth =
385 std::min((size_t)Options.TBMDepth, NumTraceBasedMutations);
386 Unit BackUp = *U;
387 for (size_t w = 0; w < TBMWidth; w++) {
388 *U = BackUp;
389 for (size_t d = 0; d < TBMDepth; d++) {
390 TotalNumberOfExecutedTraceBasedMutations++;
391 ApplyTraceBasedMutation(USF.GetRand()(NumTraceBasedMutations), U);
392 RunOneAndUpdateCorpus(*U);
393 }
Kostya Serebryanybeb24c32015-05-07 21:02:11 +0000394 }
Kostya Serebryany7d470cf2015-05-07 18:32:29 +0000395 }
396}
397
Kostya Serebryanye6926212015-11-04 23:22:25 +0000398// Returns an index of random unit from the corpus to mutate.
399// Hypothesis: units added to the corpus last are more likely to be interesting.
400// This function gives more wieght to the more recent units.
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000401size_t Fuzzer::ChooseUnitIdxToMutate() {
Kostya Serebryanye6926212015-11-04 23:22:25 +0000402 size_t N = Corpus.size();
403 size_t Total = (N + 1) * N / 2;
404 size_t R = USF.GetRand()(Total);
405 size_t IdxBeg = 0, IdxEnd = N;
406 // Binary search.
407 while (IdxEnd - IdxBeg >= 2) {
408 size_t Idx = IdxBeg + (IdxEnd - IdxBeg) / 2;
409 if (R > (Idx + 1) * Idx / 2)
410 IdxBeg = Idx;
411 else
412 IdxEnd = Idx;
413 }
414 assert(IdxBeg < N);
415 return IdxBeg;
416}
417
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000418// Experimental search heuristic: drilling.
419// - Read, shuffle, execute and minimize the corpus.
420// - Choose one random unit.
421// - Reset the coverage.
422// - Start fuzzing as if the chosen unit was the only element of the corpus.
423// - When done, reset the coverage again.
424// - Merge the newly created corpus into the original one.
425void Fuzzer::Drill() {
426 // The corpus is already read, shuffled, and minimized.
427 assert(!Corpus.empty());
428 Options.PrintNEW = false; // Don't print NEW status lines when drilling.
Kostya Serebryany7d211662015-09-04 00:12:11 +0000429
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000430 Unit U = ChooseUnitToMutate();
431
432 CHECK_WEAK_API_FUNCTION(__sanitizer_reset_coverage);
433 __sanitizer_reset_coverage();
434
435 std::vector<Unit> SavedCorpus;
436 SavedCorpus.swap(Corpus);
437 Corpus.push_back(U);
438 assert(Corpus.size() == 1);
439 RunOne(U);
440 PrintStats("DRILL ");
441 std::string SavedOutputCorpusPath; // Don't write new units while drilling.
442 SavedOutputCorpusPath.swap(Options.OutputCorpus);
443 Loop();
444
445 __sanitizer_reset_coverage();
446
447 PrintStats("REINIT");
448 SavedOutputCorpusPath.swap(Options.OutputCorpus);
449 for (auto &U : SavedCorpus)
450 RunOne(U);
451 PrintStats("MERGE ");
452 Options.PrintNEW = true;
453 size_t NumMerged = 0;
454 for (auto &U : Corpus) {
455 if (RunOne(U)) {
456 PrintStatusForNewUnit(U);
457 NumMerged++;
458 WriteToOutputCorpus(U);
459 }
460 }
461 PrintStats("MERGED");
462 if (NumMerged && Options.Verbosity)
463 Printf("Drilling discovered %zd new units\n", NumMerged);
464}
465
466void Fuzzer::Loop() {
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000467 system_clock::time_point LastCorpusReload = system_clock::now();
Kostya Serebryany468ed782015-09-08 17:30:35 +0000468 while (true) {
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000469 size_t J1 = ChooseUnitIdxToMutate();;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000470 SyncCorpus();
Kostya Serebryany8617aaa2015-12-05 02:09:22 +0000471 auto Now = system_clock::now();
472 if (duration_cast<seconds>(Now - LastCorpusReload).count()) {
473 RereadOutputCorpus();
474 LastCorpusReload = Now;
475 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000476 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
Mike Aizatskya9c23872015-11-12 04:38:40 +0000477 break;
Kostya Serebryanye6926212015-11-04 23:22:25 +0000478 if (Options.MaxTotalTimeSec > 0 &&
479 secondsSinceProcessStartUp() >
480 static_cast<size_t>(Options.MaxTotalTimeSec))
Mike Aizatskya9c23872015-11-12 04:38:40 +0000481 break;
Kostya Serebryany14c50282015-12-19 01:09:49 +0000482 USF.StartMutationSequence();
Kostya Serebryanye6926212015-11-04 23:22:25 +0000483 CurrentUnit = Corpus[J1];
484 // Optionally, cross with another unit.
485 if (Options.DoCrossOver && USF.GetRand().RandBool()) {
Kostya Serebryanydc3135d2015-11-12 01:02:01 +0000486 size_t J2 = ChooseUnitIdxToMutate();
Kostya Serebryanye6926212015-11-04 23:22:25 +0000487 if (!Corpus[J1].empty() && !Corpus[J2].empty()) {
488 assert(!Corpus[J2].empty());
489 CurrentUnit.resize(Options.MaxLen);
490 size_t NewSize = USF.CrossOver(
491 Corpus[J1].data(), Corpus[J1].size(), Corpus[J2].data(),
492 Corpus[J2].size(), CurrentUnit.data(), CurrentUnit.size());
493 assert(NewSize > 0 && "CrossOver returned empty unit");
494 assert(NewSize <= (size_t)Options.MaxLen &&
495 "CrossOver returned overisized unit");
496 CurrentUnit.resize(NewSize);
Aaron Ballmanef116982015-01-29 16:58:29 +0000497 }
Aaron Ballmanef116982015-01-29 16:58:29 +0000498 }
Kostya Serebryanye6926212015-11-04 23:22:25 +0000499 // Perform several mutations and runs.
500 MutateAndTestOne(&CurrentUnit);
Aaron Ballmanef116982015-01-29 16:58:29 +0000501 }
Mike Aizatskya9c23872015-11-12 04:38:40 +0000502
503 PrintStats("DONE ", "\n");
Aaron Ballmanef116982015-01-29 16:58:29 +0000504}
505
Kostya Serebryany2da7b842015-05-18 21:34:20 +0000506void Fuzzer::SyncCorpus() {
507 if (Options.SyncCommand.empty() || Options.OutputCorpus.empty()) return;
508 auto Now = system_clock::now();
509 if (duration_cast<seconds>(Now - LastExternalSync).count() <
510 Options.SyncTimeout)
511 return;
512 LastExternalSync = Now;
513 ExecuteCommand(Options.SyncCommand + " " + Options.OutputCorpus);
514}
515
Aaron Ballmanef116982015-01-29 16:58:29 +0000516} // namespace fuzzer