[libFuzzer] when choosing the next unit to mutate, give some preference to the most...
[oota-llvm.git] / lib / Fuzzer / FuzzerInternal.h
1 //===- FuzzerInternal.h - Internal header for the Fuzzer --------*- C++ -* ===//
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 // Define the main class fuzzer::Fuzzer and most functions.
10 //===----------------------------------------------------------------------===//
11
12 #ifndef LLVM_FUZZER_INTERNAL_H
13 #define LLVM_FUZZER_INTERNAL_H
14
15 #include <cassert>
16 #include <climits>
17 #include <chrono>
18 #include <cstddef>
19 #include <cstdlib>
20 #include <string>
21 #include <vector>
22 #include <unordered_set>
23
24 #include "FuzzerInterface.h"
25
26 namespace fuzzer {
27 typedef std::vector<uint8_t> Unit;
28 using namespace std::chrono;
29
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,
33                             long *Epoch);
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);
39
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);
47
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);
52
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);
57
58 int NumberOfCpuCores();
59 int GetPid();
60
61 // Dictionary.
62
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);
70
71 class Fuzzer {
72  public:
73   struct FuzzingOptions {
74     int Verbosity = 1;
75     int MaxLen = 0;
76     int UnitTimeoutSec = 300;
77     int MaxTotalTimeSec = 0;
78     bool DoCrossOver = true;
79     int  MutateDepth = 5;
80     bool ExitOnFirst = false;
81     bool UseCounters = false;
82     bool UseIndirCalls = true;
83     bool UseTraces = false;
84     bool UseFullCoverageSet  = false;
85     bool Reload = true;
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     int TBMDepth = 10;
93     int TBMWidth = 10;
94     std::string OutputCorpus;
95     std::string SyncCommand;
96     std::string ArtifactPrefix = "./";
97     std::vector<Unit> Dictionary;
98     bool SaveArtifacts = true;
99   };
100   Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options);
101   void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
102   size_t ChooseUnitToMutate();
103   void Loop();
104   void ShuffleAndMinimize();
105   void InitializeTraceState();
106   size_t CorpusSize() const { return Corpus.size(); }
107   void ReadDir(const std::string &Path, long *Epoch) {
108     Printf("Loading corpus: %s\n", Path.c_str());
109     ReadDirToVectorOfUnits(Path.c_str(), &Corpus, Epoch);
110   }
111   void RereadOutputCorpus();
112   // Save the current corpus to OutputCorpus.
113   void SaveCorpus();
114
115   size_t secondsSinceProcessStartUp() {
116     return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
117         .count();
118   }
119
120   size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
121
122   static void StaticAlarmCallback();
123
124   void ExecuteCallback(const Unit &U);
125
126   // Merge Corpora[1:] into Corpora[0].
127   void Merge(const std::vector<std::string> &Corpora);
128
129  private:
130   void AlarmCallback();
131   void MutateAndTestOne(Unit *U);
132   void ReportNewCoverage(const Unit &U);
133   bool RunOne(const Unit &U);
134   void RunOneAndUpdateCorpus(Unit &U);
135   void WriteToOutputCorpus(const Unit &U);
136   void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
137   void PrintStats(const char *Where, const char *End = "\n");
138   void PrintUnitInASCII(const Unit &U, const char *PrintAfter = "");
139
140   void SyncCorpus();
141
142   size_t RecordBlockCoverage();
143   size_t RecordCallerCalleeCoverage();
144   void PrepareCoverageBeforeRun();
145   bool CheckCoverageAfterRun();
146
147
148   // Trace-based fuzzing: we run a unit with some kind of tracing
149   // enabled and record potentially useful mutations. Then
150   // We apply these mutations one by one to the unit and run it again.
151
152   // Start tracing; forget all previously proposed mutations.
153   void StartTraceRecording();
154   // Stop tracing and return the number of proposed mutations.
155   size_t StopTraceRecording();
156   // Apply Idx-th trace-based mutation to U.
157   void ApplyTraceBasedMutation(size_t Idx, Unit *U);
158
159   void SetDeathCallback();
160   static void StaticDeathCallback();
161   void DeathCallback();
162   Unit CurrentUnit;
163
164   size_t TotalNumberOfRuns = 0;
165   size_t TotalNumberOfExecutedTraceBasedMutations = 0;
166
167   std::vector<Unit> Corpus;
168   std::unordered_set<std::string> UnitHashesAddedToCorpus;
169
170   // For UseCounters
171   std::vector<uint8_t> CounterBitmap;
172   size_t TotalBits() {  // Slow. Call it only for printing stats.
173     size_t Res = 0;
174     for (auto x : CounterBitmap) Res += __builtin_popcount(x);
175     return Res;
176   }
177
178   UserSuppliedFuzzer &USF;
179   FuzzingOptions Options;
180   system_clock::time_point ProcessStartTime = system_clock::now();
181   system_clock::time_point LastExternalSync = system_clock::now();
182   system_clock::time_point UnitStartTime;
183   long TimeOfLongestUnitInSeconds = 0;
184   long EpochOfLastReadOfOutputCorpus = 0;
185   size_t LastRecordedBlockCoverage = 0;
186   size_t LastRecordedCallerCalleeCoverage = 0;
187 };
188
189 class SimpleUserSuppliedFuzzer: public UserSuppliedFuzzer {
190  public:
191   SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, UserCallback Callback)
192       : UserSuppliedFuzzer(Rand), Callback(Callback) {}
193
194   virtual int TargetFunction(const uint8_t *Data, size_t Size) override {
195     return Callback(Data, Size);
196   }
197
198  private:
199   UserCallback Callback = nullptr;
200 };
201
202 };  // namespace fuzzer
203
204 #endif // LLVM_FUZZER_INTERNAL_H