f549218220841228c8957a1e432487a64d7b0110
[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 std::vector<std::string> ListFilesInDir(const std::string &Dir);
24 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V);
25 void WriteToFile(const Unit &U, const std::string &Path);
26
27 void Mutate(Unit *U, size_t MaxLen);
28
29 void CrossOver(const Unit &A, const Unit &B, Unit *U, size_t MaxLen);
30
31 void Print(const Unit &U, const char *PrintAfter = "");
32 void PrintASCII(const Unit &U, const char *PrintAfter = "");
33 std::string Hash(const Unit &U);
34 void SetTimer(int Seconds);
35
36 class Fuzzer {
37  public:
38   struct FuzzingOptions {
39     int Verbosity = 1;
40     int MaxLen = 0;
41     bool DoCrossOver = true;
42     bool MutateDepth = 10;
43     bool ExitOnFirst = false;
44     std::string OutputCorpus;
45   };
46   Fuzzer(FuzzingOptions Options) : Options(Options) {
47     SetDeathCallback();
48   }
49   void AddToCorpus(const Unit &U) { Corpus.push_back(U); }
50   size_t Loop(size_t NumIterations);
51   void ShuffleAndMinimize();
52   size_t CorpusSize() const { return Corpus.size(); }
53   void ReadDir(const std::string &Path) {
54     ReadDirToVectorOfUnits(Path.c_str(), &Corpus);
55   }
56
57   static void AlarmCallback();
58
59  private:
60   size_t MutateAndTestOne(Unit *U);
61   size_t RunOne(const Unit &U);
62   void WriteToOutputCorpus(const Unit &U);
63   static void WriteToCrash(const Unit &U, const char *Prefix);
64
65   void SetDeathCallback();
66   static void DeathCallback();
67   static Unit CurrentUnit;
68
69   size_t TotalNumberOfRuns = 0;
70
71   std::vector<Unit> Corpus;
72   FuzzingOptions Options;
73   system_clock::time_point ProcessStartTime = system_clock::now();
74   static system_clock::time_point UnitStartTime;
75 };
76
77 };  // namespace fuzzer