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