1 //===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 //===----------------------------------------------------------------------===//
12 #include "FuzzerInternal.h"
13 #include <sanitizer/coverage_interface.h>
20 Unit Fuzzer::CurrentUnit;
21 system_clock::time_point Fuzzer::UnitStartTime;
23 void Fuzzer::SetDeathCallback() {
24 __sanitizer_set_death_callback(DeathCallback);
27 void Fuzzer::DeathCallback() {
28 std::cerr << "DEATH: " << std::endl;
29 Print(CurrentUnit, "\n");
30 PrintASCII(CurrentUnit, "\n");
31 WriteToCrash(CurrentUnit, "crash-");
34 void Fuzzer::AlarmCallback() {
36 duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
37 std::cerr << "ALARM: working on the last Unit for " << Seconds << " seconds"
40 Print(CurrentUnit, "\n");
41 PrintASCII(CurrentUnit, "\n");
42 WriteToCrash(CurrentUnit, "timeout-");
47 void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
48 if (!Options.Verbosity) return;
49 size_t Seconds = secondsSinceProcessStartUp();
50 size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
52 << "#" << TotalNumberOfRuns
55 << " bits " << TotalBits()
56 << " units " << Corpus.size()
57 << " exec/s " << ExecPerSec
61 void Fuzzer::ShuffleAndMinimize() {
64 (Options.PreferSmallDuringInitialShuffle == 1 ||
65 (Options.PreferSmallDuringInitialShuffle == -1 && rand() % 2));
66 if (Options.Verbosity)
67 std::cerr << "PreferSmall: " << PreferSmall << "\n";
68 PrintStats("READ ", 0);
69 std::vector<Unit> NewCorpus;
70 std::random_shuffle(Corpus.begin(), Corpus.end());
73 Corpus.begin(), Corpus.end(),
74 [](const Unit &A, const Unit &B) { return A.size() < B.size(); });
75 Unit &U = CurrentUnit;
76 for (const auto &C : Corpus) {
77 for (size_t First = 0; First < 1; First++) {
79 size_t Last = std::min(First + Options.MaxLen, C.size());
80 U.insert(U.begin(), C.begin() + First, C.begin() + Last);
81 size_t NewCoverage = RunOne(U);
84 NewCorpus.push_back(U);
85 if (Options.Verbosity >= 2)
86 std::cerr << "NEW0: " << NewCoverage
93 PrintStats("INITED", MaxCov);
96 size_t Fuzzer::RunOne(const Unit &U) {
97 UnitStartTime = system_clock::now();
100 if (Options.UseFullCoverageSet)
101 Res = RunOneMaximizeFullCoverageSet(U);
102 else if (Options.UseCoveragePairs)
103 Res = RunOneMaximizeCoveragePairs(U);
105 Res = RunOneMaximizeTotalCoverage(U);
106 auto UnitStopTime = system_clock::now();
108 duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
109 if (TimeOfUnit > TimeOfLongestUnitInSeconds) {
110 TimeOfLongestUnitInSeconds = TimeOfUnit;
111 std::cerr << "Longest unit: " << TimeOfLongestUnitInSeconds
118 static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
120 for (uintptr_t i = 0; i < NumPCs; i++) {
121 Res = (Res + PCs[i]) * 7;
126 // Experimental. Does not yet scale.
127 // Fuly reset the current coverage state, run a single unit,
128 // collect all coverage pairs and return non-zero if a new pair is observed.
129 size_t Fuzzer::RunOneMaximizeCoveragePairs(const Unit &U) {
130 __sanitizer_reset_coverage();
131 Callback(U.data(), U.size());
133 uintptr_t NumPCs = __sanitizer_get_coverage_guards(&PCs);
134 bool HasNewPairs = false;
135 for (uintptr_t i = 0; i < NumPCs; i++) {
136 if (!PCs[i]) continue;
137 for (uintptr_t j = 0; j < NumPCs; j++) {
138 if (!PCs[j]) continue;
139 uint64_t Pair = (i << 32) | j;
140 HasNewPairs |= CoveragePairs.insert(Pair).second;
144 return CoveragePairs.size();
149 // Fuly reset the current coverage state, run a single unit,
150 // compute a hash function from the full coverage set,
151 // return non-zero if the hash value is new.
152 // This produces tons of new units and as is it's only suitable for small tests,
153 // e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
154 size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
155 __sanitizer_reset_coverage();
156 Callback(U.data(), U.size());
158 uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
159 if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
160 return FullCoverageSets.size();
164 size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
165 size_t NumCounters = __sanitizer_get_number_of_counters();
166 if (Options.UseCounters) {
167 CounterBitmap.resize(NumCounters);
168 __sanitizer_update_counter_bitset_and_clear_counters(0);
170 size_t OldCoverage = __sanitizer_get_total_unique_coverage();
171 Callback(U.data(), U.size());
172 size_t NewCoverage = __sanitizer_get_total_unique_coverage();
173 size_t NumNewBits = 0;
174 if (Options.UseCounters)
175 NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
176 CounterBitmap.data());
178 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
179 PrintStats("pulse ", NewCoverage);
181 if (NewCoverage > OldCoverage || NumNewBits)
186 void Fuzzer::WriteToOutputCorpus(const Unit &U) {
187 if (Options.OutputCorpus.empty()) return;
188 std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
189 WriteToFile(U, Path);
190 if (Options.Verbosity >= 2)
191 std::cerr << "Written to " << Path << std::endl;
194 void Fuzzer::WriteToCrash(const Unit &U, const char *Prefix) {
195 std::string Path = Prefix + Hash(U);
196 WriteToFile(U, Path);
197 std::cerr << "CRASHED; file written to " << Path << std::endl;
200 void Fuzzer::SaveCorpus() {
201 if (Options.OutputCorpus.empty()) return;
202 for (const auto &U : Corpus)
203 WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
204 if (Options.Verbosity)
205 std::cerr << "Written corpus of " << Corpus.size() << " files to "
206 << Options.OutputCorpus << "\n";
209 size_t Fuzzer::MutateAndTestOne(Unit *U) {
211 for (int i = 0; i < Options.MutateDepth; i++) {
212 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
215 Mutate(U, Options.MaxLen);
216 size_t NewCoverage = RunOne(*U);
218 Corpus.push_back(*U);
220 PrintStats("NEW ", NewCoverage, "");
221 if (Options.Verbosity) {
222 std::cerr << " L: " << U->size();
223 if (U->size() < 30) {
231 WriteToOutputCorpus(*U);
232 if (Options.ExitOnFirst)
239 size_t Fuzzer::Loop(size_t NumIterations) {
241 for (size_t i = 1; i <= NumIterations; i++) {
242 for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
243 if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
245 // First, simply mutate the unit w/o doing crosses.
246 CurrentUnit = Corpus[J1];
247 NewUnits += MutateAndTestOne(&CurrentUnit);
248 // Now, cross with others.
249 if (Options.DoCrossOver) {
250 for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
252 CrossOver(Corpus[J1], Corpus[J2], &CurrentUnit, Options.MaxLen);
253 NewUnits += MutateAndTestOne(&CurrentUnit);
261 } // namespace fuzzer