ReleaseNotes: new Win EH instructions; by David Majnemer
[oota-llvm.git] / lib / Fuzzer / FuzzerMutate.cpp
1 //===- FuzzerMutate.cpp - Mutate a test input -----------------------------===//
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 // Mutate a test input.
10 //===----------------------------------------------------------------------===//
11
12 #include <cstring>
13
14 #include "FuzzerInternal.h"
15
16 #include <algorithm>
17
18 namespace fuzzer {
19
20 struct Mutator {
21   size_t (MutationDispatcher::*Fn)(uint8_t *Data, size_t Size, size_t Max);
22   const char *Name;
23 };
24
25 struct DictionaryEntry {
26   Unit Word;
27   size_t PositionHint;
28 };
29
30 struct MutationDispatcher::Impl {
31   std::vector<DictionaryEntry> ManualDictionary;
32   std::vector<DictionaryEntry> AutoDictionary;
33   std::vector<Mutator> Mutators;
34   std::vector<Mutator> CurrentMutatorSequence;
35   std::vector<DictionaryEntry> CurrentDictionaryEntrySequence;
36   const std::vector<Unit> *Corpus = nullptr;
37   FuzzerRandomBase &Rand;
38
39   void Add(Mutator M) { Mutators.push_back(M); }
40   Impl(FuzzerRandomBase &Rand) : Rand(Rand) {
41     Add({&MutationDispatcher::Mutate_EraseByte, "EraseByte"});
42     Add({&MutationDispatcher::Mutate_InsertByte, "InsertByte"});
43     Add({&MutationDispatcher::Mutate_ChangeByte, "ChangeByte"});
44     Add({&MutationDispatcher::Mutate_ChangeBit, "ChangeBit"});
45     Add({&MutationDispatcher::Mutate_ShuffleBytes, "ShuffleBytes"});
46     Add({&MutationDispatcher::Mutate_ChangeASCIIInteger, "ChangeASCIIInt"});
47     Add({&MutationDispatcher::Mutate_CrossOver, "CrossOver"});
48     Add({&MutationDispatcher::Mutate_AddWordFromManualDictionary,
49          "AddFromManualDict"});
50     Add({&MutationDispatcher::Mutate_AddWordFromAutoDictionary,
51          "AddFromAutoDict"});
52   }
53   void SetCorpus(const std::vector<Unit> *Corpus) { this->Corpus = Corpus; }
54   size_t AddWordFromDictionary(const std::vector<DictionaryEntry> &D,
55                                uint8_t *Data, size_t Size, size_t MaxSize);
56 };
57
58 static char FlipRandomBit(char X, FuzzerRandomBase &Rand) {
59   int Bit = Rand(8);
60   char Mask = 1 << Bit;
61   char R;
62   if (X & (1 << Bit))
63     R = X & ~Mask;
64   else
65     R = X | Mask;
66   assert(R != X);
67   return R;
68 }
69
70 static char RandCh(FuzzerRandomBase &Rand) {
71   if (Rand.RandBool()) return Rand(256);
72   const char *Special = "!*'();:@&=+$,/?%#[]123ABCxyz-`~.";
73   return Special[Rand(sizeof(Special) - 1)];
74 }
75
76 size_t MutationDispatcher::Mutate_ShuffleBytes(uint8_t *Data, size_t Size,
77                                                size_t MaxSize) {
78   assert(Size);
79   size_t ShuffleAmount =
80       Rand(std::min(Size, (size_t)8)) + 1; // [1,8] and <= Size.
81   size_t ShuffleStart = Rand(Size - ShuffleAmount);
82   assert(ShuffleStart + ShuffleAmount <= Size);
83   std::random_shuffle(Data + ShuffleStart, Data + ShuffleStart + ShuffleAmount,
84                       Rand);
85   return Size;
86 }
87
88 size_t MutationDispatcher::Mutate_EraseByte(uint8_t *Data, size_t Size,
89                                             size_t MaxSize) {
90   assert(Size);
91   if (Size == 1) return 0;
92   size_t Idx = Rand(Size);
93   // Erase Data[Idx].
94   memmove(Data + Idx, Data + Idx + 1, Size - Idx - 1);
95   return Size - 1;
96 }
97
98 size_t MutationDispatcher::Mutate_InsertByte(uint8_t *Data, size_t Size,
99                                              size_t MaxSize) {
100   if (Size == MaxSize) return 0;
101   size_t Idx = Rand(Size + 1);
102   // Insert new value at Data[Idx].
103   memmove(Data + Idx + 1, Data + Idx, Size - Idx);
104   Data[Idx] = RandCh(Rand);
105   return Size + 1;
106 }
107
108 size_t MutationDispatcher::Mutate_ChangeByte(uint8_t *Data, size_t Size,
109                                              size_t MaxSize) {
110   size_t Idx = Rand(Size);
111   Data[Idx] = RandCh(Rand);
112   return Size;
113 }
114
115 size_t MutationDispatcher::Mutate_ChangeBit(uint8_t *Data, size_t Size,
116                                             size_t MaxSize) {
117   size_t Idx = Rand(Size);
118   Data[Idx] = FlipRandomBit(Data[Idx], Rand);
119   return Size;
120 }
121
122 size_t MutationDispatcher::Mutate_AddWordFromManualDictionary(uint8_t *Data,
123                                                               size_t Size,
124                                                               size_t MaxSize) {
125   return MDImpl->AddWordFromDictionary(MDImpl->ManualDictionary, Data, Size,
126                                        MaxSize);
127 }
128
129 size_t MutationDispatcher::Mutate_AddWordFromAutoDictionary(uint8_t *Data,
130                                                             size_t Size,
131                                                             size_t MaxSize) {
132   return MDImpl->AddWordFromDictionary(MDImpl->AutoDictionary, Data, Size,
133                                        MaxSize);
134 }
135
136 size_t MutationDispatcher::Impl::AddWordFromDictionary(
137     const std::vector<DictionaryEntry> &D, uint8_t *Data, size_t Size,
138     size_t MaxSize) {
139   if (D.empty()) return 0;
140   const DictionaryEntry &DE = D[Rand(D.size())];
141   const Unit &Word = DE.Word;
142   size_t PositionHint = DE.PositionHint;
143   bool UsePositionHint = PositionHint != std::numeric_limits<size_t>::max() &&
144                          PositionHint + Word.size() < Size && Rand.RandBool();
145   if (Rand.RandBool()) {  // Insert Word.
146     if (Size + Word.size() > MaxSize) return 0;
147     size_t Idx = UsePositionHint ? PositionHint : Rand(Size + 1);
148     memmove(Data + Idx + Word.size(), Data + Idx, Size - Idx);
149     memcpy(Data + Idx, Word.data(), Word.size());
150     Size += Word.size();
151   } else {  // Overwrite some bytes with Word.
152     if (Word.size() > Size) return 0;
153     size_t Idx = UsePositionHint ? PositionHint : Rand(Size - Word.size());
154     memcpy(Data + Idx, Word.data(), Word.size());
155   }
156   CurrentDictionaryEntrySequence.push_back(DE);
157   return Size;
158 }
159
160 size_t MutationDispatcher::Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size,
161                                                      size_t MaxSize) {
162   size_t B = Rand(Size);
163   while (B < Size && !isdigit(Data[B])) B++;
164   if (B == Size) return 0;
165   size_t E = B;
166   while (E < Size && isdigit(Data[E])) E++;
167   assert(B < E);
168   // now we have digits in [B, E).
169   // strtol and friends don't accept non-zero-teminated data, parse it manually.
170   uint64_t Val = Data[B] - '0';
171   for (size_t i = B + 1; i < E; i++)
172     Val = Val * 10 + Data[i] - '0';
173
174   // Mutate the integer value.
175   switch(Rand(5)) {
176     case 0: Val++; break;
177     case 1: Val--; break;
178     case 2: Val /= 2; break;
179     case 3: Val *= 2; break;
180     case 4: Val = Rand(Val * Val); break;
181     default: assert(0);
182   }
183   // Just replace the bytes with the new ones, don't bother moving bytes.
184   for (size_t i = B; i < E; i++) {
185     size_t Idx = E + B - i - 1;
186     assert(Idx >= B && Idx < E);
187     Data[Idx] = (Val % 10) + '0';
188     Val /= 10;
189   }
190   return Size;
191 }
192
193 size_t MutationDispatcher::Mutate_CrossOver(uint8_t *Data, size_t Size,
194                                             size_t MaxSize) {
195   auto Corpus = MDImpl->Corpus;
196   if (!Corpus || Corpus->size() < 2 || Size == 0) return 0;
197   size_t Idx = Rand(Corpus->size());
198   const Unit &Other = (*Corpus)[Idx];
199   if (Other.empty()) return 0;
200   Unit U(MaxSize);
201   size_t NewSize =
202       CrossOver(Data, Size, Other.data(), Other.size(), U.data(), U.size());
203   assert(NewSize > 0 && "CrossOver returned empty unit");
204   assert(NewSize <= MaxSize && "CrossOver returned overisized unit");
205   memcpy(Data, U.data(), NewSize);
206   return NewSize;
207 }
208
209 void MutationDispatcher::StartMutationSequence() {
210   MDImpl->CurrentMutatorSequence.clear();
211   MDImpl->CurrentDictionaryEntrySequence.clear();
212 }
213
214 void MutationDispatcher::PrintMutationSequence() {
215   Printf("MS: %zd ", MDImpl->CurrentMutatorSequence.size());
216   for (auto M : MDImpl->CurrentMutatorSequence)
217     Printf("%s-", M.Name);
218   if (!MDImpl->CurrentDictionaryEntrySequence.empty()) {
219     Printf(" DE: ");
220     for (auto DE : MDImpl->CurrentDictionaryEntrySequence) {
221       Printf("\"");
222       PrintASCII(DE.Word, "\"-");
223     }
224   }
225 }
226
227 // Mutates Data in place, returns new size.
228 size_t MutationDispatcher::Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
229   assert(MaxSize > 0);
230   assert(Size <= MaxSize);
231   if (Size == 0) {
232     for (size_t i = 0; i < MaxSize; i++)
233       Data[i] = RandCh(Rand);
234     return MaxSize;
235   }
236   assert(Size > 0);
237   // Some mutations may fail (e.g. can't insert more bytes if Size == MaxSize),
238   // in which case they will return 0.
239   // Try several times before returning un-mutated data.
240   for (int Iter = 0; Iter < 10; Iter++) {
241     size_t MutatorIdx = Rand(MDImpl->Mutators.size());
242     auto M = MDImpl->Mutators[MutatorIdx];
243     size_t NewSize = (this->*(M.Fn))(Data, Size, MaxSize);
244     if (NewSize) {
245       MDImpl->CurrentMutatorSequence.push_back(M);
246       return NewSize;
247     }
248   }
249   return Size;
250 }
251
252 void MutationDispatcher::SetCorpus(const std::vector<Unit> *Corpus) {
253   MDImpl->SetCorpus(Corpus);
254 }
255
256 void MutationDispatcher::AddWordToManualDictionary(const Unit &Word) {
257   MDImpl->ManualDictionary.push_back(
258       {Word, std::numeric_limits<size_t>::max()});
259 }
260
261 void MutationDispatcher::AddWordToAutoDictionary(const Unit &Word,
262                                                  size_t PositionHint) {
263   static const size_t kMaxAutoDictSize = 1 << 14;
264   if (MDImpl->AutoDictionary.size() >= kMaxAutoDictSize) return;
265   MDImpl->AutoDictionary.push_back({Word, PositionHint});
266 }
267
268 void MutationDispatcher::ClearAutoDictionary() {
269   MDImpl->AutoDictionary.clear();
270 }
271
272 MutationDispatcher::MutationDispatcher(FuzzerRandomBase &Rand) : Rand(Rand) {
273   MDImpl = new Impl(Rand);
274 }
275
276 MutationDispatcher::~MutationDispatcher() { delete MDImpl; }
277
278 }  // namespace fuzzer