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 uint8_t *Data, size_t Size, 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 std::string Base64(const Unit &U);
46 int 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 UseIndirCalls = true;
83 bool UseTraces = false;
84 bool UseFullCoverageSet = false;
86 bool ShuffleAtStartUp = true;
87 int PreferSmallDuringInitialShuffle = -1;
88 size_t MaxNumberOfRuns = ULONG_MAX;
89 int SyncTimeout = 600;
90 int ReportSlowUnits = 10;
91 bool OnlyASCII = false;
92 std::string OutputCorpus;
93 std::string SyncCommand;
94 std::string ArtifactPrefix = "./";
95 std::string ExactArtifactPath;
96 bool SaveArtifacts = true;
97 bool PrintNEW = true; // Print a status line when new units are found;
98 bool OutputCSV = false;
99 bool PrintNewCovPcs = false;
101 Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options);
102 void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
103 size_t ChooseUnitIdxToMutate();
104 const Unit &ChooseUnitToMutate() { return Corpus[ChooseUnitIdxToMutate()]; };
107 void ShuffleAndMinimize();
108 void InitializeTraceState();
109 size_t CorpusSize() const { return Corpus.size(); }
110 void ReadDir(const std::string &Path, long *Epoch) {
111 Printf("Loading corpus: %s\n", Path.c_str());
112 ReadDirToVectorOfUnits(Path.c_str(), &Corpus, Epoch);
114 void RereadOutputCorpus();
115 // Save the current corpus to OutputCorpus.
118 size_t secondsSinceProcessStartUp() {
119 return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
123 size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
125 static void StaticAlarmCallback();
127 void ExecuteCallback(const Unit &U);
129 // Merge Corpora[1:] into Corpora[0].
130 void Merge(const std::vector<std::string> &Corpora);
133 void AlarmCallback();
134 void MutateAndTestOne();
135 void ReportNewCoverage(const Unit &U);
136 bool RunOne(const Unit &U);
137 void RunOneAndUpdateCorpus(Unit &U);
138 void WriteToOutputCorpus(const Unit &U);
139 void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
140 void PrintStats(const char *Where, const char *End = "\n");
141 void PrintStatusForNewUnit(const Unit &U);
142 void PrintUnitInASCII(const Unit &U, const char *PrintAfter = "");
146 size_t RecordBlockCoverage();
147 size_t RecordCallerCalleeCoverage();
148 void PrepareCoverageBeforeRun();
149 bool CheckCoverageAfterRun();
152 // Trace-based fuzzing: we run a unit with some kind of tracing
153 // enabled and record potentially useful mutations. Then
154 // We apply these mutations one by one to the unit and run it again.
156 // Start tracing; forget all previously proposed mutations.
157 void StartTraceRecording();
159 void StopTraceRecording();
161 void SetDeathCallback();
162 static void StaticDeathCallback();
163 void DeathCallback();
166 size_t TotalNumberOfRuns = 0;
167 size_t TotalNumberOfExecutedTraceBasedMutations = 0;
169 std::vector<Unit> Corpus;
170 std::unordered_set<std::string> UnitHashesAddedToCorpus;
173 std::vector<uint8_t> CounterBitmap;
174 size_t TotalBits() { // Slow. Call it only for printing stats.
176 for (auto x : CounterBitmap) Res += __builtin_popcount(x);
180 UserSuppliedFuzzer &USF;
181 FuzzingOptions Options;
182 system_clock::time_point ProcessStartTime = system_clock::now();
183 system_clock::time_point LastExternalSync = system_clock::now();
184 system_clock::time_point UnitStartTime;
185 long TimeOfLongestUnitInSeconds = 0;
186 long EpochOfLastReadOfOutputCorpus = 0;
187 size_t LastRecordedBlockCoverage = 0;
188 size_t LastRecordedCallerCalleeCoverage = 0;
189 size_t LastCoveragePcBufferLen = 0;
192 class SimpleUserSuppliedFuzzer: public UserSuppliedFuzzer {
194 SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, UserCallback Callback)
195 : UserSuppliedFuzzer(Rand), Callback(Callback) {}
197 virtual int TargetFunction(const uint8_t *Data, size_t Size) override {
198 return Callback(Data, Size);
202 UserCallback Callback = nullptr;
205 }; // namespace fuzzer
207 #endif // LLVM_FUZZER_INTERNAL_H