[libFuzzer] move the mutators to public interface so that custom mutators may reuse...
[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 #include <cassert>
12 #include <climits>
13 #include <chrono>
14 #include <cstddef>
15 #include <cstdlib>
16 #include <string>
17 #include <vector>
18 #include <unordered_set>
19
20 #include "FuzzerInterface.h"
21
22 namespace fuzzer {
23 typedef std::vector<uint8_t> Unit;
24 using namespace std::chrono;
25
26 std::string FileToString(const std::string &Path);
27 Unit FileToVector(const std::string &Path);
28 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
29                             long *Epoch);
30 void WriteToFile(const Unit &U, const std::string &Path);
31 void CopyFileToErr(const std::string &Path);
32 // Returns "Dir/FileName" or equivalent for the current OS.
33 std::string DirPlusFile(const std::string &DirPath,
34                         const std::string &FileName);
35
36 void Printf(const char *Fmt, ...);
37 void Print(const Unit &U, const char *PrintAfter = "");
38 void PrintASCII(const Unit &U, const char *PrintAfter = "");
39 std::string Hash(const Unit &U);
40 void SetTimer(int Seconds);
41 void PrintFileAsBase64(const std::string &Path);
42 void ExecuteCommand(const std::string &Command);
43
44 // Private copy of SHA1 implementation.
45 static const int kSHA1NumBytes = 20;
46 // Computes SHA1 hash of 'Len' bytes in 'Data', writes kSHA1NumBytes to 'Out'.
47 void ComputeSHA1(const uint8_t *Data, size_t Len, uint8_t *Out);
48
49 int NumberOfCpuCores();
50
51 class Fuzzer {
52  public:
53   struct FuzzingOptions {
54     int Verbosity = 1;
55     int MaxLen = 0;
56     int UnitTimeoutSec = 300;
57     bool DoCrossOver = true;
58     int  MutateDepth = 5;
59     bool ExitOnFirst = false;
60     bool UseCounters = false;
61     bool UseTraces = false;
62     bool UseFullCoverageSet  = false;
63     bool Reload = true;
64     int PreferSmallDuringInitialShuffle = -1;
65     size_t MaxNumberOfRuns = ULONG_MAX;
66     int SyncTimeout = 600;
67     int ReportSlowUnits = 10;
68     std::string OutputCorpus;
69     std::string SyncCommand;
70     std::vector<std::string> Tokens;
71   };
72   Fuzzer(UserSuppliedFuzzer &USF, FuzzingOptions Options);
73   void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
74   void Loop(size_t NumIterations);
75   void ShuffleAndMinimize();
76   void InitializeTraceState();
77   size_t CorpusSize() const { return Corpus.size(); }
78   void ReadDir(const std::string &Path, long *Epoch) {
79     ReadDirToVectorOfUnits(Path.c_str(), &Corpus, Epoch);
80   }
81   void RereadOutputCorpus();
82   // Save the current corpus to OutputCorpus.
83   void SaveCorpus();
84
85   size_t secondsSinceProcessStartUp() {
86     return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
87         .count();
88   }
89
90   size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
91
92   static void StaticAlarmCallback();
93
94   Unit SubstituteTokens(const Unit &U) const;
95
96  private:
97   void AlarmCallback();
98   void ExecuteCallback(const Unit &U);
99   void MutateAndTestOne(Unit *U);
100   void ReportNewCoverage(size_t NewCoverage, const Unit &U);
101   size_t RunOne(const Unit &U);
102   void RunOneAndUpdateCorpus(const Unit &U);
103   size_t RunOneMaximizeTotalCoverage(const Unit &U);
104   size_t RunOneMaximizeFullCoverageSet(const Unit &U);
105   size_t RunOneMaximizeCoveragePairs(const Unit &U);
106   void WriteToOutputCorpus(const Unit &U);
107   void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
108   void PrintStats(const char *Where, size_t Cov, const char *End = "\n");
109   void PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter = "");
110
111   void SyncCorpus();
112
113   // Trace-based fuzzing: we run a unit with some kind of tracing
114   // enabled and record potentially useful mutations. Then
115   // We apply these mutations one by one to the unit and run it again.
116
117   // Start tracing; forget all previously proposed mutations.
118   void StartTraceRecording();
119   // Stop tracing and return the number of proposed mutations.
120   size_t StopTraceRecording();
121   // Apply Idx-th trace-based mutation to U.
122   void ApplyTraceBasedMutation(size_t Idx, Unit *U);
123
124   void SetDeathCallback();
125   static void StaticDeathCallback();
126   void DeathCallback();
127   Unit CurrentUnit;
128
129   size_t TotalNumberOfRuns = 0;
130
131   std::vector<Unit> Corpus;
132   std::unordered_set<std::string> UnitHashesAddedToCorpus;
133   std::unordered_set<uintptr_t> FullCoverageSets;
134
135   // For UseCounters
136   std::vector<uint8_t> CounterBitmap;
137   size_t TotalBits() {  // Slow. Call it only for printing stats.
138     size_t Res = 0;
139     for (auto x : CounterBitmap) Res += __builtin_popcount(x);
140     return Res;
141   }
142
143   UserSuppliedFuzzer &USF;
144   FuzzingOptions Options;
145   system_clock::time_point ProcessStartTime = system_clock::now();
146   system_clock::time_point LastExternalSync = system_clock::now();
147   system_clock::time_point UnitStartTime;
148   long TimeOfLongestUnitInSeconds = 0;
149   long EpochOfLastReadOfOutputCorpus = 0;
150 };
151
152 class SimpleUserSuppliedFuzzer: public UserSuppliedFuzzer {
153  public:
154   SimpleUserSuppliedFuzzer(FuzzerRandomBase *Rand, UserCallback Callback)
155       : UserSuppliedFuzzer(Rand), Callback(Callback) {}
156   virtual void TargetFunction(const uint8_t *Data, size_t Size) {
157     return Callback(Data, Size);
158   }
159
160  private:
161   UserCallback Callback;
162 };
163
164 };  // namespace fuzzer