496b6db1650d9cee3511d145e11fedbd782c5dd9
[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 #include <set>
20
21 #include "FuzzerInterface.h"
22
23 namespace fuzzer {
24 typedef std::vector<uint8_t> Unit;
25 using namespace std::chrono;
26
27 std::string FileToString(const std::string &Path);
28 Unit FileToVector(const std::string &Path);
29 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
30                             long *Epoch);
31 void WriteToFile(const Unit &U, const std::string &Path);
32 void CopyFileToErr(const std::string &Path);
33 // Returns "Dir/FileName" or equivalent for the current OS.
34 std::string DirPlusFile(const std::string &DirPath,
35                         const std::string &FileName);
36
37 void Mutate(Unit *U, size_t MaxLen);
38
39 void CrossOver(const Unit &A, const Unit &B, Unit *U, size_t MaxLen);
40
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
47 int NumberOfCpuCores();
48
49 class Fuzzer {
50  public:
51   struct FuzzingOptions {
52     int Verbosity = 1;
53     int MaxLen = 0;
54     bool DoCrossOver = true;
55     int  MutateDepth = 5;
56     bool ExitOnFirst = false;
57     bool UseCounters = false;
58     bool UseTraces = false;
59     bool UseFullCoverageSet  = false;
60     bool UseCoveragePairs = false;
61     bool Reload = true;
62     int PreferSmallDuringInitialShuffle = -1;
63     size_t MaxNumberOfRuns = ULONG_MAX;
64     std::string OutputCorpus;
65     std::vector<std::string> Tokens;
66   };
67   Fuzzer(UserCallback Callback, FuzzingOptions Options);
68   void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
69   void Loop(size_t NumIterations);
70   void ShuffleAndMinimize();
71   void InitializeTraceState();
72   size_t CorpusSize() const { return Corpus.size(); }
73   void ReadDir(const std::string &Path, long *Epoch) {
74     ReadDirToVectorOfUnits(Path.c_str(), &Corpus, Epoch);
75   }
76   void RereadOutputCorpus();
77   // Save the current corpus to OutputCorpus.
78   void SaveCorpus();
79
80   size_t secondsSinceProcessStartUp() {
81     return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
82         .count();
83   }
84
85   size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
86
87   static void StaticAlarmCallback();
88
89   Unit SubstituteTokens(const Unit &U) const;
90
91  private:
92   void AlarmCallback();
93   void ExecuteCallback(const Unit &U);
94   void MutateAndTestOne(Unit *U);
95   void ReportNewCoverage(size_t NewCoverage, const Unit &U);
96   size_t RunOne(const Unit &U);
97   void RunOneAndUpdateCorpus(const Unit &U);
98   size_t RunOneMaximizeTotalCoverage(const Unit &U);
99   size_t RunOneMaximizeFullCoverageSet(const Unit &U);
100   size_t RunOneMaximizeCoveragePairs(const Unit &U);
101   void WriteToOutputCorpus(const Unit &U);
102   void WriteToCrash(const Unit &U, const char *Prefix);
103   void PrintStats(const char *Where, size_t Cov, const char *End = "\n");
104   void PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter = "");
105
106   // Trace-based fuzzing: we run a unit with some kind of tracing
107   // enabled and record potentially useful mutations. Then
108   // We apply these mutations one by one to the unit and run it again.
109
110   // Start tracing; forget all previously proposed mutations.
111   void StartTraceRecording();
112   // Stop tracing and return the number of proposed mutations.
113   size_t StopTraceRecording();
114   // Apply Idx-th trace-based mutation to U.
115   void ApplyTraceBasedMutation(size_t Idx, Unit *U);
116
117   void SetDeathCallback();
118   static void StaticDeathCallback();
119   void DeathCallback();
120   Unit CurrentUnit;
121
122   size_t TotalNumberOfRuns = 0;
123
124   std::vector<Unit> Corpus;
125   std::set<Unit> UnitsAddedAfterInitialLoad;
126   std::unordered_set<uintptr_t> FullCoverageSets;
127   std::unordered_set<uint64_t>  CoveragePairs;
128
129   // For UseCounters
130   std::vector<uint8_t> CounterBitmap;
131   size_t TotalBits() {  // Slow. Call it only for printing stats.
132     size_t Res = 0;
133     for (auto x : CounterBitmap) Res += __builtin_popcount(x);
134     return Res;
135   }
136
137   UserCallback Callback;
138   FuzzingOptions Options;
139   system_clock::time_point ProcessStartTime = system_clock::now();
140   system_clock::time_point UnitStartTime;
141   long TimeOfLongestUnitInSeconds = 0;
142   long EpochOfLastReadOfOutputCorpus = 0;
143 };
144
145 };  // namespace fuzzer