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 typedef std::vector<uint8_t> Unit;
28 using namespace std::chrono;
30 std::string FileToString(const std::string &Path);
31 Unit FileToVector(const std::string &Path);
32 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
34 void WriteToFile(const Unit &U, const std::string &Path);
35 void CopyFileToErr(const std::string &Path);
36 // Returns "Dir/FileName" or equivalent for the current OS.
37 std::string DirPlusFile(const std::string &DirPath,
38 const std::string &FileName);
40 void Printf(const char *Fmt, ...);
41 void Print(const Unit &U, const char *PrintAfter = "");
42 void PrintASCII(const Unit &U, const char *PrintAfter = "");
43 std::string Hash(const Unit &U);
44 void SetTimer(int Seconds);
45 void PrintFileAsBase64(const std::string &Path);
46 void ExecuteCommand(const std::string &Command);
48 // Private copy of SHA1 implementation.
49 static const int kSHA1NumBytes = 20;
50 // Computes SHA1 hash of 'Len' bytes in 'Data', writes kSHA1NumBytes to 'Out'.
51 void ComputeSHA1(const uint8_t *Data, size_t Len, uint8_t *Out);
53 // Changes U to contain only ASCII (isprint+isspace) characters.
54 // Returns true iff U has been changed.
55 bool ToASCII(Unit &U);
56 bool IsASCII(const Unit &U);
58 int NumberOfCpuCores();
63 // Parses one dictionary entry.
64 // If successfull, write the enty to Unit and returns true,
65 // otherwise returns false.
66 bool ParseOneDictionaryEntry(const std::string &Str, Unit *U);
67 // Parses the dictionary file, fills Units, returns true iff all lines
68 // were parsed succesfully.
69 bool ParseDictionaryFile(const std::string &Text, std::vector<Unit> *Units);
73 struct FuzzingOptions {
76 int UnitTimeoutSec = 300;
77 int MaxTotalTimeSec = 0;
78 bool DoCrossOver = true;
80 bool ExitOnFirst = false;
81 bool UseCounters = false;
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;
93 std::string OutputCorpus;
94 std::string SyncCommand;
95 std::string ArtifactPrefix = "./";
96 std::vector<Unit> Dictionary;
97 bool SaveArtifacts = true;
99 Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options);
100 void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
102 void ShuffleAndMinimize();
103 void InitializeTraceState();
104 size_t CorpusSize() const { return Corpus.size(); }
105 void ReadDir(const std::string &Path, long *Epoch) {
106 ReadDirToVectorOfUnits(Path.c_str(), &Corpus, Epoch);
108 void RereadOutputCorpus();
109 // Save the current corpus to OutputCorpus.
112 size_t secondsSinceProcessStartUp() {
113 return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
117 size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
119 static void StaticAlarmCallback();
121 void ExecuteCallback(const Unit &U);
124 void AlarmCallback();
125 void MutateAndTestOne(Unit *U);
126 void ReportNewCoverage(const Unit &U);
127 bool RunOne(const Unit &U);
128 void RunOneAndUpdateCorpus(Unit &U);
129 void WriteToOutputCorpus(const Unit &U);
130 void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
131 void PrintStats(const char *Where, size_t Cov, const char *End = "\n");
132 void PrintUnitInASCII(const Unit &U, const char *PrintAfter = "");
136 size_t RecordBlockCoverage();
137 void PrepareCoverageBeforeRun();
138 bool CheckCoverageAfterRun();
141 // Trace-based fuzzing: we run a unit with some kind of tracing
142 // enabled and record potentially useful mutations. Then
143 // We apply these mutations one by one to the unit and run it again.
145 // Start tracing; forget all previously proposed mutations.
146 void StartTraceRecording();
147 // Stop tracing and return the number of proposed mutations.
148 size_t StopTraceRecording();
149 // Apply Idx-th trace-based mutation to U.
150 void ApplyTraceBasedMutation(size_t Idx, Unit *U);
152 void SetDeathCallback();
153 static void StaticDeathCallback();
154 void DeathCallback();
157 size_t TotalNumberOfRuns = 0;
158 size_t TotalNumberOfExecutedTraceBasedMutations = 0;
160 std::vector<Unit> Corpus;
161 std::unordered_set<std::string> UnitHashesAddedToCorpus;
164 std::vector<uint8_t> CounterBitmap;
165 size_t TotalBits() { // Slow. Call it only for printing stats.
167 for (auto x : CounterBitmap) Res += __builtin_popcount(x);
171 UserSuppliedFuzzer &USF;
172 FuzzingOptions Options;
173 system_clock::time_point ProcessStartTime = system_clock::now();
174 system_clock::time_point LastExternalSync = system_clock::now();
175 system_clock::time_point UnitStartTime;
176 long TimeOfLongestUnitInSeconds = 0;
177 long EpochOfLastReadOfOutputCorpus = 0;
178 size_t LastRecordedBlockCoverage = 0;
181 class SimpleUserSuppliedFuzzer: public UserSuppliedFuzzer {
183 SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, UserCallback Callback)
184 : UserSuppliedFuzzer(Rand), Callback(Callback) {}
186 SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, DeprecatedUserCallback Callback)
187 : UserSuppliedFuzzer(Rand), DeprecatedCallback(Callback) {}
189 virtual int TargetFunction(const uint8_t *Data, size_t Size) override {
190 if (Callback) return Callback(Data, Size);
191 DeprecatedCallback(Data, Size);
196 DeprecatedUserCallback DeprecatedCallback = nullptr;
197 UserCallback Callback = nullptr;
200 }; // namespace fuzzer
202 #endif // LLVM_FUZZER_INTERNAL_H