[lib/Fuzzer] Add SHA1 implementation from public domain.
[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 // 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     std::string OutputCorpus;
70     std::vector<std::string> Tokens;
71   };
72   Fuzzer(UserCallback Callback, 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 WriteToCrash(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   // Trace-based fuzzing: we run a unit with some kind of tracing
112   // enabled and record potentially useful mutations. Then
113   // We apply these mutations one by one to the unit and run it again.
114
115   // Start tracing; forget all previously proposed mutations.
116   void StartTraceRecording();
117   // Stop tracing and return the number of proposed mutations.
118   size_t StopTraceRecording();
119   // Apply Idx-th trace-based mutation to U.
120   void ApplyTraceBasedMutation(size_t Idx, Unit *U);
121
122   void SetDeathCallback();
123   static void StaticDeathCallback();
124   void DeathCallback();
125   Unit CurrentUnit;
126
127   size_t TotalNumberOfRuns = 0;
128
129   std::vector<Unit> Corpus;
130   std::set<Unit> UnitsAddedAfterInitialLoad;
131   std::unordered_set<uintptr_t> FullCoverageSets;
132   std::unordered_set<uint64_t>  CoveragePairs;
133
134   // For UseCounters
135   std::vector<uint8_t> CounterBitmap;
136   size_t TotalBits() {  // Slow. Call it only for printing stats.
137     size_t Res = 0;
138     for (auto x : CounterBitmap) Res += __builtin_popcount(x);
139     return Res;
140   }
141
142   UserCallback Callback;
143   FuzzingOptions Options;
144   system_clock::time_point ProcessStartTime = system_clock::now();
145   system_clock::time_point UnitStartTime;
146   long TimeOfLongestUnitInSeconds = 0;
147   long EpochOfLastReadOfOutputCorpus = 0;
148 };
149
150 };  // namespace fuzzer