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