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