[libFuzzer] remove -iterations as redundant (there is also -num_runs)
[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
60 // Dictionary.
61
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);
69
70 class Fuzzer {
71  public:
72   struct FuzzingOptions {
73     int Verbosity = 1;
74     int MaxLen = 0;
75     int UnitTimeoutSec = 300;
76     bool DoCrossOver = true;
77     int  MutateDepth = 5;
78     bool ExitOnFirst = false;
79     bool UseCounters = false;
80     bool UseTraces = false;
81     bool UseFullCoverageSet  = false;
82     bool Reload = true;
83     int PreferSmallDuringInitialShuffle = -1;
84     size_t MaxNumberOfRuns = ULONG_MAX;
85     int SyncTimeout = 600;
86     int ReportSlowUnits = 10;
87     bool OnlyASCII = false;
88     int TBMDepth = 10;
89     int TBMWidth = 10;
90     std::string OutputCorpus;
91     std::string SyncCommand;
92     std::vector<std::string> Tokens;
93     std::vector<Unit> Dictionary;
94   };
95   Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options);
96   void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
97   void Loop();
98   void ShuffleAndMinimize();
99   void InitializeTraceState();
100   size_t CorpusSize() const { return Corpus.size(); }
101   void ReadDir(const std::string &Path, long *Epoch) {
102     ReadDirToVectorOfUnits(Path.c_str(), &Corpus, Epoch);
103   }
104   void RereadOutputCorpus();
105   // Save the current corpus to OutputCorpus.
106   void SaveCorpus();
107
108   size_t secondsSinceProcessStartUp() {
109     return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
110         .count();
111   }
112
113   size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
114
115   static void StaticAlarmCallback();
116
117   Unit SubstituteTokens(const Unit &U) const;
118
119  private:
120   void AlarmCallback();
121   void ExecuteCallback(const Unit &U);
122   void MutateAndTestOne(Unit *U);
123   void ReportNewCoverage(size_t NewCoverage, const Unit &U);
124   size_t RunOne(const Unit &U);
125   void RunOneAndUpdateCorpus(Unit &U);
126   size_t RunOneMaximizeTotalCoverage(const Unit &U);
127   size_t RunOneMaximizeFullCoverageSet(const Unit &U);
128   size_t RunOneMaximizeCoveragePairs(const 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 PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter = "");
133
134   void SyncCorpus();
135
136   // Trace-based fuzzing: we run a unit with some kind of tracing
137   // enabled and record potentially useful mutations. Then
138   // We apply these mutations one by one to the unit and run it again.
139
140   // Start tracing; forget all previously proposed mutations.
141   void StartTraceRecording();
142   // Stop tracing and return the number of proposed mutations.
143   size_t StopTraceRecording();
144   // Apply Idx-th trace-based mutation to U.
145   void ApplyTraceBasedMutation(size_t Idx, Unit *U);
146
147   void SetDeathCallback();
148   static void StaticDeathCallback();
149   void DeathCallback();
150   Unit CurrentUnit;
151
152   size_t TotalNumberOfRuns = 0;
153   size_t TotalNumberOfExecutedTraceBasedMutations = 0;
154
155   std::vector<Unit> Corpus;
156   std::unordered_set<std::string> UnitHashesAddedToCorpus;
157   std::unordered_set<uintptr_t> FullCoverageSets;
158
159   // For UseCounters
160   std::vector<uint8_t> CounterBitmap;
161   size_t TotalBits() {  // Slow. Call it only for printing stats.
162     size_t Res = 0;
163     for (auto x : CounterBitmap) Res += __builtin_popcount(x);
164     return Res;
165   }
166
167   UserSuppliedFuzzer &USF;
168   FuzzingOptions Options;
169   system_clock::time_point ProcessStartTime = system_clock::now();
170   system_clock::time_point LastExternalSync = system_clock::now();
171   system_clock::time_point UnitStartTime;
172   long TimeOfLongestUnitInSeconds = 0;
173   long EpochOfLastReadOfOutputCorpus = 0;
174 };
175
176 class SimpleUserSuppliedFuzzer: public UserSuppliedFuzzer {
177  public:
178   SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, UserCallback Callback)
179       : UserSuppliedFuzzer(Rand), Callback(Callback) {}
180   virtual void TargetFunction(const uint8_t *Data, size_t Size) {
181     return Callback(Data, Size);
182   }
183
184  private:
185   UserCallback Callback;
186 };
187
188 };  // namespace fuzzer
189
190 #endif // LLVM_FUZZER_INTERNAL_H