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