LLVM  5.0.0
FuzzerCorpus.h
Go to the documentation of this file.
1 //===- FuzzerCorpus.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 // fuzzer::InputCorpus
10 //===----------------------------------------------------------------------===//
11 
12 #ifndef LLVM_FUZZER_CORPUS
13 #define LLVM_FUZZER_CORPUS
14 
15 #include "FuzzerDefs.h"
16 #include "FuzzerIO.h"
17 #include "FuzzerRandom.h"
18 #include "FuzzerSHA1.h"
19 #include "FuzzerTracePC.h"
20 #include <algorithm>
21 #include <numeric>
22 #include <random>
23 #include <unordered_set>
24 
25 namespace fuzzer {
26 
27 struct InputInfo {
28  Unit U; // The actual input data.
29  uint8_t Sha1[kSHA1NumBytes]; // Checksum.
30  // Number of features that this input has and no smaller input has.
31  size_t NumFeatures = 0;
32  size_t Tmp = 0; // Used by ValidateFeatureSet.
33  // Stats.
36  bool MayDeleteFile = false;
37  bool Reduced = false;
38  std::vector<uint32_t> UniqFeatureSet;
39 };
40 
41 class InputCorpus {
42  static const size_t kFeatureSetSize = 1 << 21;
43  public:
44  InputCorpus(const std::string &OutputCorpus) : OutputCorpus(OutputCorpus) {
45  memset(InputSizesPerFeature, 0, sizeof(InputSizesPerFeature));
46  memset(SmallestElementPerFeature, 0, sizeof(SmallestElementPerFeature));
47  }
49  for (auto II : Inputs)
50  delete II;
51  }
52  size_t size() const { return Inputs.size(); }
53  size_t SizeInBytes() const {
54  size_t Res = 0;
55  for (auto II : Inputs)
56  Res += II->U.size();
57  return Res;
58  }
59  size_t NumActiveUnits() const {
60  size_t Res = 0;
61  for (auto II : Inputs)
62  Res += !II->U.empty();
63  return Res;
64  }
65  size_t MaxInputSize() const {
66  size_t Res = 0;
67  for (auto II : Inputs)
68  Res = std::max(Res, II->U.size());
69  return Res;
70  }
71  bool empty() const { return Inputs.empty(); }
72  const Unit &operator[] (size_t Idx) const { return Inputs[Idx]->U; }
73  void AddToCorpus(const Unit &U, size_t NumFeatures, bool MayDeleteFile,
74  const std::vector<uint32_t> &FeatureSet) {
75  assert(!U.empty());
76  if (FeatureDebug)
77  Printf("ADD_TO_CORPUS %zd NF %zd\n", Inputs.size(), NumFeatures);
78  Inputs.push_back(new InputInfo());
79  InputInfo &II = *Inputs.back();
80  II.U = U;
82  II.MayDeleteFile = MayDeleteFile;
83  II.UniqFeatureSet = FeatureSet;
84  std::sort(II.UniqFeatureSet.begin(), II.UniqFeatureSet.end());
85  ComputeSHA1(U.data(), U.size(), II.Sha1);
86  Hashes.insert(Sha1ToString(II.Sha1));
87  UpdateCorpusDistribution();
88  PrintCorpus();
89  // ValidateFeatureSet();
90  }
91 
92  // Debug-only
93  void PrintUnit(const Unit &U) {
94  if (!FeatureDebug) return;
95  for (uint8_t C : U) {
96  if (C != 'F' && C != 'U' && C != 'Z')
97  C = '.';
98  Printf("%c", C);
99  }
100  }
101 
102  // Debug-only
103  void PrintFeatureSet(const std::vector<uint32_t> &FeatureSet) {
104  if (!FeatureDebug) return;
105  Printf("{");
106  for (uint32_t Feature: FeatureSet)
107  Printf("%u,", Feature);
108  Printf("}");
109  }
110 
111  // Debug-only
112  void PrintCorpus() {
113  if (!FeatureDebug) return;
114  Printf("======= CORPUS:\n");
115  int i = 0;
116  for (auto II : Inputs) {
117  if (std::find(II->U.begin(), II->U.end(), 'F') != II->U.end()) {
118  Printf("[%2d] ", i);
119  Printf("%s sz=%zd ", Sha1ToString(II->Sha1).c_str(), II->U.size());
120  PrintUnit(II->U);
121  Printf(" ");
122  PrintFeatureSet(II->UniqFeatureSet);
123  Printf("\n");
124  }
125  i++;
126  }
127  }
128 
129  void Replace(InputInfo *II, const Unit &U) {
130  assert(II->U.size() > U.size());
131  Hashes.erase(Sha1ToString(II->Sha1));
132  DeleteFile(*II);
133  ComputeSHA1(U.data(), U.size(), II->Sha1);
134  Hashes.insert(Sha1ToString(II->Sha1));
135  II->U = U;
136  II->Reduced = true;
137  }
138 
139  bool HasUnit(const Unit &U) { return Hashes.count(Hash(U)); }
140  bool HasUnit(const std::string &H) { return Hashes.count(H); }
142  InputInfo &II = *Inputs[ChooseUnitIdxToMutate(Rand)];
143  assert(!II.U.empty());
144  return II;
145  };
146 
147  // Returns an index of random unit from the corpus to mutate.
148  // Hypothesis: units added to the corpus last are more likely to be
149  // interesting. This function gives more weight to the more recent units.
151  size_t Idx = static_cast<size_t>(CorpusDistribution(Rand));
152  assert(Idx < Inputs.size());
153  return Idx;
154  }
155 
156  void PrintStats() {
157  for (size_t i = 0; i < Inputs.size(); i++) {
158  const auto &II = *Inputs[i];
159  Printf(" [%zd %s]\tsz: %zd\truns: %zd\tsucc: %zd\n", i,
160  Sha1ToString(II.Sha1).c_str(), II.U.size(),
161  II.NumExecutedMutations, II.NumSuccessfullMutations);
162  }
163  }
164 
166  for (size_t i = 0; i < kFeatureSetSize; i++) {
167  if(size_t Sz = GetFeature(i))
168  Printf("[%zd: id %zd sz%zd] ", i, SmallestElementPerFeature[i], Sz);
169  }
170  Printf("\n\t");
171  for (size_t i = 0; i < Inputs.size(); i++)
172  if (size_t N = Inputs[i]->NumFeatures)
173  Printf(" %zd=>%zd ", i, N);
174  Printf("\n");
175  }
176 
177  void DeleteFile(const InputInfo &II) {
178  if (!OutputCorpus.empty() && II.MayDeleteFile)
179  RemoveFile(DirPlusFile(OutputCorpus, Sha1ToString(II.Sha1)));
180  }
181 
182  void DeleteInput(size_t Idx) {
183  InputInfo &II = *Inputs[Idx];
184  DeleteFile(II);
185  Unit().swap(II.U);
186  if (FeatureDebug)
187  Printf("EVICTED %zd\n", Idx);
188  }
189 
190  bool AddFeature(size_t Idx, uint32_t NewSize, bool Shrink) {
191  assert(NewSize);
192  Idx = Idx % kFeatureSetSize;
193  uint32_t OldSize = GetFeature(Idx);
194  if (OldSize == 0 || (Shrink && OldSize > NewSize)) {
195  if (OldSize > 0) {
196  size_t OldIdx = SmallestElementPerFeature[Idx];
197  InputInfo &II = *Inputs[OldIdx];
198  assert(II.NumFeatures > 0);
199  II.NumFeatures--;
200  if (II.NumFeatures == 0)
201  DeleteInput(OldIdx);
202  } else {
203  NumAddedFeatures++;
204  }
205  NumUpdatedFeatures++;
206  if (FeatureDebug)
207  Printf("ADD FEATURE %zd sz %d\n", Idx, NewSize);
208  SmallestElementPerFeature[Idx] = Inputs.size();
209  InputSizesPerFeature[Idx] = NewSize;
210  return true;
211  }
212  return false;
213  }
214 
215  size_t NumFeatures() const { return NumAddedFeatures; }
216  size_t NumFeatureUpdates() const { return NumUpdatedFeatures; }
217 
219  assert(Inputs.empty());
220  memset(InputSizesPerFeature, 0, sizeof(InputSizesPerFeature));
221  memset(SmallestElementPerFeature, 0, sizeof(SmallestElementPerFeature));
222  }
223 
224 private:
225 
226  static const bool FeatureDebug = false;
227 
228  size_t GetFeature(size_t Idx) const { return InputSizesPerFeature[Idx]; }
229 
230  void ValidateFeatureSet() {
231  if (FeatureDebug)
232  PrintFeatureSet();
233  for (size_t Idx = 0; Idx < kFeatureSetSize; Idx++)
234  if (GetFeature(Idx))
235  Inputs[SmallestElementPerFeature[Idx]]->Tmp++;
236  for (auto II: Inputs) {
237  if (II->Tmp != II->NumFeatures)
238  Printf("ZZZ %zd %zd\n", II->Tmp, II->NumFeatures);
239  assert(II->Tmp == II->NumFeatures);
240  II->Tmp = 0;
241  }
242  }
243 
244  // Updates the probability distribution for the units in the corpus.
245  // Must be called whenever the corpus or unit weights are changed.
246  void UpdateCorpusDistribution() {
247  size_t N = Inputs.size();
248  assert(N);
249  Intervals.resize(N + 1);
250  Weights.resize(N);
251  std::iota(Intervals.begin(), Intervals.end(), 0);
252  for (size_t i = 0; i < N; i++)
253  Weights[i] = Inputs[i]->NumFeatures * (i + 1);
254  CorpusDistribution = std::piecewise_constant_distribution<double>(
255  Intervals.begin(), Intervals.end(), Weights.begin());
256  }
257  std::piecewise_constant_distribution<double> CorpusDistribution;
258 
259  std::vector<double> Intervals;
260  std::vector<double> Weights;
261 
262  std::unordered_set<std::string> Hashes;
263  std::vector<InputInfo*> Inputs;
264 
265  size_t NumAddedFeatures = 0;
266  size_t NumUpdatedFeatures = 0;
267  uint32_t InputSizesPerFeature[kFeatureSetSize];
268  uint32_t SmallestElementPerFeature[kFeatureSetSize];
269 
270  std::string OutputCorpus;
271 };
272 
273 } // namespace fuzzer
274 
275 #endif // LLVM_FUZZER_CORPUS
void DeleteFile(const InputInfo &II)
Definition: FuzzerCorpus.h:177
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
size_t ChooseUnitIdxToMutate(Random &Rand)
Definition: FuzzerCorpus.h:150
void PrintUnit(const Unit &U)
Definition: FuzzerCorpus.h:93
std::vector< uint32_t > UniqFeatureSet
Definition: FuzzerCorpus.h:38
InputCorpus(const std::string &OutputCorpus)
Definition: FuzzerCorpus.h:44
const Unit & operator[](size_t Idx) const
Definition: FuzzerCorpus.h:72
void ComputeSHA1(const uint8_t *Data, size_t Len, uint8_t *Out)
Definition: FuzzerSHA1.cpp:202
#define H(x, y, z)
Definition: MD5.cpp:57
size_t NumFeatureUpdates() const
Definition: FuzzerCorpus.h:216
bool empty() const
Definition: FuzzerCorpus.h:71
std::string DirPlusFile(const std::string &DirPath, const std::string &FileName)
Definition: FuzzerIO.cpp:87
uint8_t Sha1[kSHA1NumBytes]
Definition: FuzzerCorpus.h:29
size_t size() const
Definition: FuzzerCorpus.h:52
void DeleteInput(size_t Idx)
Definition: FuzzerCorpus.h:182
void AddToCorpus(const Unit &U, size_t NumFeatures, bool MayDeleteFile, const std::vector< uint32_t > &FeatureSet)
Definition: FuzzerCorpus.h:73
size_t NumActiveUnits() const
Definition: FuzzerCorpus.h:59
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:839
void Replace(InputInfo *II, const Unit &U)
Definition: FuzzerCorpus.h:129
bool HasUnit(const std::string &H)
Definition: FuzzerCorpus.h:140
ATTRIBUTE_NO_SANITIZE_ALL __attribute__((noinline)) void TracePC size_t N
void RemoveFile(const std::string &Path)
size_t SizeInBytes() const
Definition: FuzzerCorpus.h:53
size_t NumSuccessfullMutations
Definition: FuzzerCorpus.h:35
std::string Sha1ToString(const uint8_t Sha1[kSHA1NumBytes])
Definition: FuzzerSHA1.cpp:209
#define C
Definition: LargeTest.cpp:25
size_t MaxInputSize() const
Definition: FuzzerCorpus.h:65
std::vector< uint8_t > Unit
Definition: FuzzerDefs.h:105
void PrintFeatureSet(const std::vector< uint32_t > &FeatureSet)
Definition: FuzzerCorpus.h:103
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
size_t NumFeatures() const
Definition: FuzzerCorpus.h:215
InputInfo & ChooseUnitToMutate(Random &Rand)
Definition: FuzzerCorpus.h:141
bool HasUnit(const Unit &U)
Definition: FuzzerCorpus.h:139
std::string Hash(const Unit &U)
Definition: FuzzerSHA1.cpp:216
bool AddFeature(size_t Idx, uint32_t NewSize, bool Shrink)
Definition: FuzzerCorpus.h:190
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:201
Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i])
static const int kSHA1NumBytes
Definition: FuzzerSHA1.h:22
size_t NumExecutedMutations
Definition: FuzzerCorpus.h:34