Make a bunch of static arrays const.
[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 UseTraces = false;
83     bool UseFullCoverageSet  = false;
84     bool Reload = true;
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     int TBMDepth = 10;
92     int TBMWidth = 10;
93     std::string OutputCorpus;
94     std::string SyncCommand;
95     std::string ArtifactPrefix = "./";
96     std::vector<std::string> Tokens;
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   void Loop();
103   void ShuffleAndMinimize();
104   void InitializeTraceState();
105   size_t CorpusSize() const { return Corpus.size(); }
106   void ReadDir(const std::string &Path, long *Epoch) {
107     ReadDirToVectorOfUnits(Path.c_str(), &Corpus, Epoch);
108   }
109   void RereadOutputCorpus();
110   // Save the current corpus to OutputCorpus.
111   void SaveCorpus();
112
113   size_t secondsSinceProcessStartUp() {
114     return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
115         .count();
116   }
117
118   size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
119
120   static void StaticAlarmCallback();
121
122   Unit SubstituteTokens(const Unit &U) const;
123   void ExecuteCallback(const Unit &U);
124
125  private:
126   void AlarmCallback();
127   void MutateAndTestOne(Unit *U);
128   void ReportNewCoverage(size_t NewCoverage, const Unit &U);
129   size_t RunOne(const Unit &U);
130   void RunOneAndUpdateCorpus(Unit &U);
131   size_t RunOneMaximizeTotalCoverage(const Unit &U);
132   size_t RunOneMaximizeCoveragePairs(const Unit &U);
133   void WriteToOutputCorpus(const Unit &U);
134   void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
135   void PrintStats(const char *Where, size_t Cov, const char *End = "\n");
136   void PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter = "");
137
138   void SyncCorpus();
139
140   // Trace-based fuzzing: we run a unit with some kind of tracing
141   // enabled and record potentially useful mutations. Then
142   // We apply these mutations one by one to the unit and run it again.
143
144   // Start tracing; forget all previously proposed mutations.
145   void StartTraceRecording();
146   // Stop tracing and return the number of proposed mutations.
147   size_t StopTraceRecording();
148   // Apply Idx-th trace-based mutation to U.
149   void ApplyTraceBasedMutation(size_t Idx, Unit *U);
150
151   void SetDeathCallback();
152   static void StaticDeathCallback();
153   void DeathCallback();
154   Unit CurrentUnit;
155
156   size_t TotalNumberOfRuns = 0;
157   size_t TotalNumberOfExecutedTraceBasedMutations = 0;
158
159   std::vector<Unit> Corpus;
160   std::unordered_set<std::string> UnitHashesAddedToCorpus;
161
162   // For UseCounters
163   std::vector<uint8_t> CounterBitmap;
164   size_t TotalBits() {  // Slow. Call it only for printing stats.
165     size_t Res = 0;
166     for (auto x : CounterBitmap) Res += __builtin_popcount(x);
167     return Res;
168   }
169
170   UserSuppliedFuzzer &USF;
171   FuzzingOptions Options;
172   system_clock::time_point ProcessStartTime = system_clock::now();
173   system_clock::time_point LastExternalSync = system_clock::now();
174   system_clock::time_point UnitStartTime;
175   long TimeOfLongestUnitInSeconds = 0;
176   long EpochOfLastReadOfOutputCorpus = 0;
177 };
178
179 class SimpleUserSuppliedFuzzer: public UserSuppliedFuzzer {
180  public:
181   SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, UserCallback Callback)
182       : UserSuppliedFuzzer(Rand), Callback(Callback) {}
183
184   SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, DeprecatedUserCallback Callback)
185       : UserSuppliedFuzzer(Rand), DeprecatedCallback(Callback) {}
186
187   virtual int TargetFunction(const uint8_t *Data, size_t Size) override {
188     if (Callback) return Callback(Data, Size);
189     DeprecatedCallback(Data, Size);
190     return 0;
191   }
192
193  private:
194   DeprecatedUserCallback DeprecatedCallback = nullptr;
195   UserCallback Callback = nullptr;
196 };
197
198 };  // namespace fuzzer
199
200 #endif // LLVM_FUZZER_INTERNAL_H