1 //===- FuzzerInternal.h - Internal header for the Fuzzer --------*- C++ -* ===//
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 //===----------------------------------------------------------------------===//
9 // Define the main class fuzzer::Fuzzer and most functions.
10 //===----------------------------------------------------------------------===//
12 #ifndef LLVM_FUZZER_INTERNAL_H
13 #define LLVM_FUZZER_INTERNAL_H
22 #include <unordered_set>
24 #include "FuzzerInterface.h"
27 using namespace std::chrono;
29 std::string FileToString(const std::string &Path);
30 Unit FileToVector(const std::string &Path);
31 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
33 void WriteToFile(const Unit &U, const std::string &Path);
34 void CopyFileToErr(const std::string &Path);
35 // Returns "Dir/FileName" or equivalent for the current OS.
36 std::string DirPlusFile(const std::string &DirPath,
37 const std::string &FileName);
39 void Printf(const char *Fmt, ...);
40 void Print(const Unit &U, const char *PrintAfter = "");
41 void PrintASCII(const Unit &U, const char *PrintAfter = "");
42 std::string Hash(const Unit &U);
43 void SetTimer(int Seconds);
44 std::string Base64(const Unit &U);
45 int ExecuteCommand(const std::string &Command);
47 // Private copy of SHA1 implementation.
48 static const int kSHA1NumBytes = 20;
49 // Computes SHA1 hash of 'Len' bytes in 'Data', writes kSHA1NumBytes to 'Out'.
50 void ComputeSHA1(const uint8_t *Data, size_t Len, uint8_t *Out);
52 // Changes U to contain only ASCII (isprint+isspace) characters.
53 // Returns true iff U has been changed.
54 bool ToASCII(Unit &U);
55 bool IsASCII(const Unit &U);
57 int NumberOfCpuCores();
62 // Parses one dictionary entry.
63 // If successfull, write the enty to Unit and returns true,
64 // otherwise returns false.
65 bool ParseOneDictionaryEntry(const std::string &Str, Unit *U);
66 // Parses the dictionary file, fills Units, returns true iff all lines
67 // were parsed succesfully.
68 bool ParseDictionaryFile(const std::string &Text, std::vector<Unit> *Units);
72 struct FuzzingOptions {
75 int UnitTimeoutSec = 300;
76 int MaxTotalTimeSec = 0;
77 bool DoCrossOver = true;
79 bool ExitOnFirst = false;
80 bool UseCounters = false;
81 bool UseIndirCalls = true;
82 bool UseTraces = false;
83 bool UseFullCoverageSet = false;
85 bool ShuffleAtStartUp = true;
86 int PreferSmallDuringInitialShuffle = -1;
87 size_t MaxNumberOfRuns = ULONG_MAX;
88 int SyncTimeout = 600;
89 int ReportSlowUnits = 10;
90 bool OnlyASCII = false;
91 std::string OutputCorpus;
92 std::string SyncCommand;
93 std::string ArtifactPrefix = "./";
94 std::string ExactArtifactPath;
95 bool SaveArtifacts = true;
96 bool PrintNEW = true; // Print a status line when new units are found;
97 bool OutputCSV = false;
98 bool PrintNewCovPcs = false;
100 Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options);
101 void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
102 size_t ChooseUnitIdxToMutate();
103 const Unit &ChooseUnitToMutate() { return Corpus[ChooseUnitIdxToMutate()]; };
106 void ShuffleAndMinimize();
107 void InitializeTraceState();
108 size_t CorpusSize() const { return Corpus.size(); }
109 void ReadDir(const std::string &Path, long *Epoch) {
110 Printf("Loading corpus: %s\n", Path.c_str());
111 ReadDirToVectorOfUnits(Path.c_str(), &Corpus, Epoch);
113 void RereadOutputCorpus();
114 // Save the current corpus to OutputCorpus.
117 size_t secondsSinceProcessStartUp() {
118 return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
122 size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
124 static void StaticAlarmCallback();
126 void ExecuteCallback(const Unit &U);
128 // Merge Corpora[1:] into Corpora[0].
129 void Merge(const std::vector<std::string> &Corpora);
132 void AlarmCallback();
133 void MutateAndTestOne();
134 void ReportNewCoverage(const Unit &U);
135 bool RunOne(const Unit &U);
136 void RunOneAndUpdateCorpus(Unit &U);
137 void WriteToOutputCorpus(const Unit &U);
138 void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
139 void PrintStats(const char *Where, const char *End = "\n");
140 void PrintStatusForNewUnit(const Unit &U);
141 void PrintUnitInASCII(const Unit &U, const char *PrintAfter = "");
145 size_t RecordBlockCoverage();
146 size_t RecordCallerCalleeCoverage();
147 void PrepareCoverageBeforeRun();
148 bool CheckCoverageAfterRun();
151 // Trace-based fuzzing: we run a unit with some kind of tracing
152 // enabled and record potentially useful mutations. Then
153 // We apply these mutations one by one to the unit and run it again.
155 // Start tracing; forget all previously proposed mutations.
156 void StartTraceRecording();
158 void StopTraceRecording();
160 void SetDeathCallback();
161 static void StaticDeathCallback();
162 void DeathCallback();
165 size_t TotalNumberOfRuns = 0;
166 size_t TotalNumberOfExecutedTraceBasedMutations = 0;
168 std::vector<Unit> Corpus;
169 std::unordered_set<std::string> UnitHashesAddedToCorpus;
172 std::vector<uint8_t> CounterBitmap;
173 size_t TotalBits() { // Slow. Call it only for printing stats.
175 for (auto x : CounterBitmap) Res += __builtin_popcount(x);
179 UserSuppliedFuzzer &USF;
180 FuzzingOptions Options;
181 system_clock::time_point ProcessStartTime = system_clock::now();
182 system_clock::time_point LastExternalSync = system_clock::now();
183 system_clock::time_point UnitStartTime;
184 long TimeOfLongestUnitInSeconds = 0;
185 long EpochOfLastReadOfOutputCorpus = 0;
186 size_t LastRecordedBlockCoverage = 0;
187 size_t LastRecordedCallerCalleeCoverage = 0;
188 size_t LastCoveragePcBufferLen = 0;
191 class SimpleUserSuppliedFuzzer: public UserSuppliedFuzzer {
193 SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, UserCallback Callback)
194 : UserSuppliedFuzzer(Rand), Callback(Callback) {}
196 virtual int TargetFunction(const uint8_t *Data, size_t Size) override {
197 return Callback(Data, Size);
201 UserCallback Callback = nullptr;
204 }; // namespace fuzzer
206 #endif // LLVM_FUZZER_INTERNAL_H