c361ffba83aa44ec1877959144923f99454a8a2e
[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 <chrono>
13 #include <cstddef>
14 #include <cstdlib>
15 #include <string>
16 #include <vector>
17
18 namespace fuzzer {
19 typedef std::vector<uint8_t> Unit;
20 using namespace std::chrono;
21
22 Unit ReadFile(const char *Path);
23 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V);
24 void WriteToFile(const Unit &U, const std::string &Path);
25 // Returns "Dir/FileName" or equivalent for the current OS.
26 std::string DirPlusFile(const std::string &DirPath,
27                         const std::string &FileName);
28
29 void Mutate(Unit *U, size_t MaxLen);
30
31 void CrossOver(const Unit &A, const Unit &B, Unit *U, size_t MaxLen);
32
33 void Print(const Unit &U, const char *PrintAfter = "");
34 void PrintASCII(const Unit &U, const char *PrintAfter = "");
35 std::string Hash(const Unit &U);
36 void SetTimer(int Seconds);
37
38 class Fuzzer {
39  public:
40   struct FuzzingOptions {
41     int Verbosity = 1;
42     int MaxLen = 0;
43     bool DoCrossOver = true;
44     bool MutateDepth = 10;
45     bool ExitOnFirst = false;
46     std::string OutputCorpus;
47   };
48   Fuzzer(FuzzingOptions Options) : Options(Options) {
49     SetDeathCallback();
50   }
51   void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
52   size_t Loop(size_t NumIterations);
53   void ShuffleAndMinimize();
54   size_t CorpusSize() const { return Corpus.size(); }
55   void ReadDir(const std::string &Path) {
56     ReadDirToVectorOfUnits(Path.c_str(), &Corpus);
57   }
58   // Save the current corpus to OutputCorpus.
59   void SaveCorpus();
60
61   static void AlarmCallback();
62
63  private:
64   size_t MutateAndTestOne(Unit *U);
65   size_t RunOne(const Unit &U);
66   void WriteToOutputCorpus(const Unit &U);
67   static void WriteToCrash(const Unit &U, const char *Prefix);
68
69   void SetDeathCallback();
70   static void DeathCallback();
71   static Unit CurrentUnit;
72
73   size_t TotalNumberOfRuns = 0;
74
75   std::vector<Unit> Corpus;
76   FuzzingOptions Options;
77   system_clock::time_point ProcessStartTime = system_clock::now();
78   static system_clock::time_point UnitStartTime;
79 };
80
81 };  // namespace fuzzer