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