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