blob: 5998ef9d3193d5cfb58bb2b34e6ed85671e66f47 [file] [log] [blame]
Aaron Ballmanef116982015-01-29 16:58:29 +00001//===- 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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000012#include "FuzzerMutate.h"
Kostya Serebryany556894f2016-09-21 02:05:39 +000013#include "FuzzerCorpus.h"
14#include "FuzzerDefs.h"
15#include "FuzzerExtFunctions.h"
Zachary Turner24a148b2016-11-30 19:06:14 +000016#include "FuzzerIO.h"
Kostya Serebryany556894f2016-09-21 02:05:39 +000017#include "FuzzerOptions.h"
Kostya Serebryanybf29ff22015-08-06 01:29:13 +000018
Aaron Ballmanef116982015-01-29 16:58:29 +000019namespace fuzzer {
20
Kostya Serebryany2f13f222016-01-21 01:52:14 +000021const size_t Dictionary::kMaxDictSize;
22
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000023static void PrintASCII(const Word &W, const char *PrintAfter) {
24 PrintASCII(W.data(), W.size(), PrintAfter);
25}
26
Mike Aizatskyf0b3e852016-06-23 20:44:48 +000027MutationDispatcher::MutationDispatcher(Random &Rand,
28 const FuzzingOptions &Options)
29 : Rand(Rand), Options(Options) {
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000030 DefaultMutators.insert(
31 DefaultMutators.begin(),
32 {
Kostya Serebryanydfbe59b2016-08-15 17:48:28 +000033 {&MutationDispatcher::Mutate_EraseBytes, "EraseBytes"},
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000034 {&MutationDispatcher::Mutate_InsertByte, "InsertByte"},
Kostya Serebryanydfbe59b2016-08-15 17:48:28 +000035 {&MutationDispatcher::Mutate_InsertRepeatedBytes,
36 "InsertRepeatedBytes"},
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000037 {&MutationDispatcher::Mutate_ChangeByte, "ChangeByte"},
38 {&MutationDispatcher::Mutate_ChangeBit, "ChangeBit"},
39 {&MutationDispatcher::Mutate_ShuffleBytes, "ShuffleBytes"},
40 {&MutationDispatcher::Mutate_ChangeASCIIInteger, "ChangeASCIIInt"},
Kostya Serebryany0c537b12016-08-17 21:30:30 +000041 {&MutationDispatcher::Mutate_ChangeBinaryInteger, "ChangeBinInt"},
Kostya Serebryanya7398ba2016-08-17 18:10:42 +000042 {&MutationDispatcher::Mutate_CopyPart, "CopyPart"},
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000043 {&MutationDispatcher::Mutate_CrossOver, "CrossOver"},
44 {&MutationDispatcher::Mutate_AddWordFromManualDictionary,
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +000045 "ManualDict"},
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000046 {&MutationDispatcher::Mutate_AddWordFromPersistentAutoDictionary,
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +000047 "PersAutoDict"},
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000048 });
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +000049 if(Options.UseCmp)
50 DefaultMutators.push_back(
Kostya Serebryany3364f902016-10-25 02:04:43 +000051 {&MutationDispatcher::Mutate_AddWordFromTORC, "CMP"});
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000052
Dan Liew1873a492016-06-07 23:32:50 +000053 if (EF->LLVMFuzzerCustomMutator)
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000054 Mutators.push_back({&MutationDispatcher::Mutate_Custom, "Custom"});
55 else
56 Mutators = DefaultMutators;
Mike Aizatsky41d66832016-06-07 20:22:15 +000057
Dan Liew1873a492016-06-07 23:32:50 +000058 if (EF->LLVMFuzzerCustomCrossOver)
Mike Aizatsky41d66832016-06-07 20:22:15 +000059 Mutators.push_back(
60 {&MutationDispatcher::Mutate_CustomCrossOver, "CustomCrossOver"});
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000061}
Kostya Serebryany23194962016-02-13 03:46:26 +000062
Kostya Serebryanya3992212016-02-13 03:00:53 +000063static char RandCh(Random &Rand) {
Kostya Serebryany404c69f2015-07-24 01:06:40 +000064 if (Rand.RandBool()) return Rand(256);
Kostya Serebryanya7398ba2016-08-17 18:10:42 +000065 const char *Special = "!*'();:@&=+$,/?%#[]012Az-`~.\xff\x00";
Kostya Serebryany404c69f2015-07-24 01:06:40 +000066 return Special[Rand(sizeof(Special) - 1)];
Aaron Ballmanef116982015-01-29 16:58:29 +000067}
68
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000069size_t MutationDispatcher::Mutate_Custom(uint8_t *Data, size_t Size,
70 size_t MaxSize) {
Dan Liew1873a492016-06-07 23:32:50 +000071 return EF->LLVMFuzzerCustomMutator(Data, Size, MaxSize, Rand.Rand());
Mike Aizatsky70fd3e42016-06-03 21:34:29 +000072}
73
Mike Aizatsky41d66832016-06-07 20:22:15 +000074size_t MutationDispatcher::Mutate_CustomCrossOver(uint8_t *Data, size_t Size,
75 size_t MaxSize) {
76 if (!Corpus || Corpus->size() < 2 || Size == 0)
77 return 0;
Vitaly Bukafbf031f2017-03-15 23:08:18 +000078 size_t Idx = Rand(Corpus->size());
Mike Aizatsky41d66832016-06-07 20:22:15 +000079 const Unit &Other = (*Corpus)[Idx];
80 if (Other.empty())
81 return 0;
Vitaly Buka91266b42017-03-07 20:37:38 +000082 CustomCrossOverInPlaceHere.resize(MaxSize);
83 auto &U = CustomCrossOverInPlaceHere;
Dan Liew1873a492016-06-07 23:32:50 +000084 size_t NewSize = EF->LLVMFuzzerCustomCrossOver(
Mike Aizatsky41d66832016-06-07 20:22:15 +000085 Data, Size, Other.data(), Other.size(), U.data(), U.size(), Rand.Rand());
86 if (!NewSize)
87 return 0;
88 assert(NewSize <= MaxSize && "CustomCrossOver returned overisized unit");
89 memcpy(Data, U.data(), NewSize);
90 return NewSize;
91}
92
Kostya Serebryanyec2dcb12015-09-03 21:24:19 +000093size_t MutationDispatcher::Mutate_ShuffleBytes(uint8_t *Data, size_t Size,
94 size_t MaxSize) {
Kostya Serebryanyb7a00862017-01-23 22:52:13 +000095 if (Size > MaxSize || Size == 0) return 0;
Kostya Serebryany152ac7a2016-01-07 01:49:35 +000096 size_t ShuffleAmount =
97 Rand(std::min(Size, (size_t)8)) + 1; // [1,8] and <= Size.
Kostya Serebryanybf29ff22015-08-06 01:29:13 +000098 size_t ShuffleStart = Rand(Size - ShuffleAmount);
99 assert(ShuffleStart + ShuffleAmount <= Size);
Kostya Serebryany6ac64c32017-02-07 22:37:34 +0000100 std::shuffle(Data + ShuffleStart, Data + ShuffleStart + ShuffleAmount, Rand);
Kostya Serebryanybf29ff22015-08-06 01:29:13 +0000101 return Size;
102}
103
Kostya Serebryanydfbe59b2016-08-15 17:48:28 +0000104size_t MutationDispatcher::Mutate_EraseBytes(uint8_t *Data, size_t Size,
105 size_t MaxSize) {
Kostya Serebryanyb7a00862017-01-23 22:52:13 +0000106 if (Size <= 1) return 0;
Kostya Serebryanydfbe59b2016-08-15 17:48:28 +0000107 size_t N = Rand(Size / 2) + 1;
108 assert(N < Size);
109 size_t Idx = Rand(Size - N + 1);
110 // Erase Data[Idx:Idx+N].
111 memmove(Data + Idx, Data + Idx + N, Size - Idx - N);
112 // Printf("Erase: %zd %zd => %zd; Idx %zd\n", N, Size, Size - N, Idx);
113 return Size - N;
Kostya Serebryany8ce74242015-08-01 01:42:51 +0000114}
115
Kostya Serebryanyec2dcb12015-09-03 21:24:19 +0000116size_t MutationDispatcher::Mutate_InsertByte(uint8_t *Data, size_t Size,
117 size_t MaxSize) {
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000118 if (Size >= MaxSize) return 0;
Kostya Serebryany86a5fba2015-08-01 02:23:06 +0000119 size_t Idx = Rand(Size + 1);
120 // Insert new value at Data[Idx].
121 memmove(Data + Idx + 1, Data + Idx, Size - Idx);
122 Data[Idx] = RandCh(Rand);
123 return Size + 1;
124}
125
Kostya Serebryanydfbe59b2016-08-15 17:48:28 +0000126size_t MutationDispatcher::Mutate_InsertRepeatedBytes(uint8_t *Data,
127 size_t Size,
128 size_t MaxSize) {
129 const size_t kMinBytesToInsert = 3;
130 if (Size + kMinBytesToInsert >= MaxSize) return 0;
131 size_t MaxBytesToInsert = std::min(MaxSize - Size, (size_t)128);
132 size_t N = Rand(MaxBytesToInsert - kMinBytesToInsert + 1) + kMinBytesToInsert;
133 assert(Size + N <= MaxSize && N);
134 size_t Idx = Rand(Size + 1);
135 // Insert new values at Data[Idx].
136 memmove(Data + Idx + N, Data + Idx, Size - Idx);
Kostya Serebryanye72774d2016-08-17 21:50:54 +0000137 // Give preference to 0x00 and 0xff.
138 uint8_t Byte = Rand.RandBool() ? Rand(256) : (Rand.RandBool() ? 0 : 255);
Kostya Serebryanydfbe59b2016-08-15 17:48:28 +0000139 for (size_t i = 0; i < N; i++)
140 Data[Idx + i] = Byte;
141 return Size + N;
142}
143
Kostya Serebryanyec2dcb12015-09-03 21:24:19 +0000144size_t MutationDispatcher::Mutate_ChangeByte(uint8_t *Data, size_t Size,
145 size_t MaxSize) {
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000146 if (Size > MaxSize) return 0;
Kostya Serebryany86a5fba2015-08-01 02:23:06 +0000147 size_t Idx = Rand(Size);
148 Data[Idx] = RandCh(Rand);
149 return Size;
150}
151
Kostya Serebryanyec2dcb12015-09-03 21:24:19 +0000152size_t MutationDispatcher::Mutate_ChangeBit(uint8_t *Data, size_t Size,
153 size_t MaxSize) {
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000154 if (Size > MaxSize) return 0;
Kostya Serebryany86a5fba2015-08-01 02:23:06 +0000155 size_t Idx = Rand(Size);
Kostya Serebryanya7398ba2016-08-17 18:10:42 +0000156 Data[Idx] ^= 1 << Rand(8);
Kostya Serebryany86a5fba2015-08-01 02:23:06 +0000157 return Size;
158}
159
Kostya Serebryany152ac7a2016-01-07 01:49:35 +0000160size_t MutationDispatcher::Mutate_AddWordFromManualDictionary(uint8_t *Data,
161 size_t Size,
162 size_t MaxSize) {
Kostya Serebryany292cf032016-02-13 03:37:24 +0000163 return AddWordFromDictionary(ManualDictionary, Data, Size, MaxSize);
Kostya Serebryany152ac7a2016-01-07 01:49:35 +0000164}
165
Kostya Serebryany3364f902016-10-25 02:04:43 +0000166size_t MutationDispatcher::ApplyDictionaryEntry(uint8_t *Data, size_t Size,
167 size_t MaxSize,
168 DictionaryEntry &DE) {
169 const Word &W = DE.GetW();
170 bool UsePositionHint = DE.HasPositionHint() &&
171 DE.GetPositionHint() + W.size() < Size &&
172 Rand.RandBool();
173 if (Rand.RandBool()) { // Insert W.
174 if (Size + W.size() > MaxSize) return 0;
175 size_t Idx = UsePositionHint ? DE.GetPositionHint() : Rand(Size + 1);
176 memmove(Data + Idx + W.size(), Data + Idx, Size - Idx);
177 memcpy(Data + Idx, W.data(), W.size());
178 Size += W.size();
179 } else { // Overwrite some bytes with W.
180 if (W.size() > Size) return 0;
181 size_t Idx = UsePositionHint ? DE.GetPositionHint() : Rand(Size - W.size());
182 memcpy(Data + Idx, W.data(), W.size());
183 }
184 return Size;
185}
186
187// Somewhere in the past we have observed a comparison instructions
188// with arguments Arg1 Arg2. This function tries to guess a dictionary
189// entry that will satisfy that comparison.
190// It first tries to find one of the arguments (possibly swapped) in the
191// input and if it succeeds it creates a DE with a position hint.
192// Otherwise it creates a DE with one of the arguments w/o a position hint.
Kostya Serebryany3364f902016-10-25 02:04:43 +0000193DictionaryEntry MutationDispatcher::MakeDictionaryEntryFromCMP(
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000194 const void *Arg1, const void *Arg2,
195 const void *Arg1Mutation, const void *Arg2Mutation,
196 size_t ArgSize, const uint8_t *Data,
197 size_t Size) {
Kostya Serebryanyaf2dfce2017-03-31 02:21:28 +0000198 ScopedDoingMyOwnMemOrStr scoped_doing_my_own_mem_os_str;
Kostya Serebryany3364f902016-10-25 02:04:43 +0000199 bool HandleFirst = Rand.RandBool();
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000200 const void *ExistingBytes, *DesiredBytes;
Kostya Serebryany3364f902016-10-25 02:04:43 +0000201 Word W;
202 const uint8_t *End = Data + Size;
203 for (int Arg = 0; Arg < 2; Arg++) {
204 ExistingBytes = HandleFirst ? Arg1 : Arg2;
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000205 DesiredBytes = HandleFirst ? Arg2Mutation : Arg1Mutation;
Kostya Serebryany3364f902016-10-25 02:04:43 +0000206 HandleFirst = !HandleFirst;
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000207 W.Set(reinterpret_cast<const uint8_t*>(DesiredBytes), ArgSize);
Kostya Serebryany3364f902016-10-25 02:04:43 +0000208 const size_t kMaxNumPositions = 8;
209 size_t Positions[kMaxNumPositions];
210 size_t NumPositions = 0;
211 for (const uint8_t *Cur = Data;
212 Cur < End && NumPositions < kMaxNumPositions; Cur++) {
Kostya Serebryanyae0317e2017-05-10 23:59:03 +0000213 Cur =
214 (const uint8_t *)SearchMemory(Cur, End - Cur, ExistingBytes, ArgSize);
Kostya Serebryany3364f902016-10-25 02:04:43 +0000215 if (!Cur) break;
216 Positions[NumPositions++] = Cur - Data;
217 }
Kostya Serebryanye8a49b32017-05-15 17:39:42 +0000218 if (!NumPositions) continue;
Kostya Serebryany3364f902016-10-25 02:04:43 +0000219 return DictionaryEntry(W, Positions[Rand(NumPositions)]);
220 }
221 DictionaryEntry DE(W);
222 return DE;
223}
224
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000225
226template <class T>
227DictionaryEntry MutationDispatcher::MakeDictionaryEntryFromCMP(
228 T Arg1, T Arg2, const uint8_t *Data, size_t Size) {
229 if (Rand.RandBool()) Arg1 = Bswap(Arg1);
230 if (Rand.RandBool()) Arg2 = Bswap(Arg2);
231 T Arg1Mutation = Arg1 + Rand(-1, 1);
232 T Arg2Mutation = Arg2 + Rand(-1, 1);
233 return MakeDictionaryEntryFromCMP(&Arg1, &Arg2, &Arg1Mutation, &Arg2Mutation,
234 sizeof(Arg1), Data, Size);
235}
236
237DictionaryEntry MutationDispatcher::MakeDictionaryEntryFromCMP(
238 const Word &Arg1, const Word &Arg2, const uint8_t *Data, size_t Size) {
239 return MakeDictionaryEntryFromCMP(Arg1.data(), Arg2.data(), Arg1.data(),
240 Arg2.data(), Arg1.size(), Data, Size);
241}
242
Kostya Serebryany3364f902016-10-25 02:04:43 +0000243size_t MutationDispatcher::Mutate_AddWordFromTORC(
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000244 uint8_t *Data, size_t Size, size_t MaxSize) {
Kostya Serebryany3364f902016-10-25 02:04:43 +0000245 Word W;
246 DictionaryEntry DE;
Kostya Serebryanyf64b8482017-07-14 00:06:27 +0000247 switch (Rand(4)) {
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000248 case 0: {
Kostya Serebryany3364f902016-10-25 02:04:43 +0000249 auto X = TPC.TORC8.Get(Rand.Rand());
250 DE = MakeDictionaryEntryFromCMP(X.A, X.B, Data, Size);
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000251 } break;
252 case 1: {
Kostya Serebryany3364f902016-10-25 02:04:43 +0000253 auto X = TPC.TORC4.Get(Rand.Rand());
254 if ((X.A >> 16) == 0 && (X.B >> 16) == 0 && Rand.RandBool())
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000255 DE = MakeDictionaryEntryFromCMP((uint16_t)X.A, (uint16_t)X.B, Data, Size);
Kostya Serebryany3364f902016-10-25 02:04:43 +0000256 else
257 DE = MakeDictionaryEntryFromCMP(X.A, X.B, Data, Size);
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000258 } break;
259 case 2: {
260 auto X = TPC.TORCW.Get(Rand.Rand());
261 DE = MakeDictionaryEntryFromCMP(X.A, X.B, Data, Size);
262 } break;
Kostya Serebryanyf64b8482017-07-14 00:06:27 +0000263 case 3: if (Options.UseMemmem) {
264 auto X = TPC.MMT.Get(Rand.Rand());
265 DE = DictionaryEntry(X);
266 } break;
Kostya Serebryany1d8c2ce2017-01-17 23:09:05 +0000267 default:
268 assert(0);
Kostya Serebryany3364f902016-10-25 02:04:43 +0000269 }
Kostya Serebryanya44ebf4d2017-01-19 21:14:47 +0000270 if (!DE.GetW().size()) return 0;
Kostya Serebryany3364f902016-10-25 02:04:43 +0000271 Size = ApplyDictionaryEntry(Data, Size, MaxSize, DE);
272 if (!Size) return 0;
Kostya Serebryany3364f902016-10-25 02:04:43 +0000273 DictionaryEntry &DERef =
274 CmpDictionaryEntriesDeque[CmpDictionaryEntriesDequeIdx++ %
275 kCmpDictionaryEntriesDequeSize];
276 DERef = DE;
277 CurrentDictionaryEntrySequence.push_back(&DERef);
278 return Size;
Kostya Serebryanya5f94fb2016-10-14 20:20:33 +0000279}
280
Kostya Serebryany4b358742016-01-14 02:36:44 +0000281size_t MutationDispatcher::Mutate_AddWordFromPersistentAutoDictionary(
282 uint8_t *Data, size_t Size, size_t MaxSize) {
Kostya Serebryany292cf032016-02-13 03:37:24 +0000283 return AddWordFromDictionary(PersistentAutoDictionary, Data, Size, MaxSize);
Kostya Serebryany152ac7a2016-01-07 01:49:35 +0000284}
285
Kostya Serebryany292cf032016-02-13 03:37:24 +0000286size_t MutationDispatcher::AddWordFromDictionary(Dictionary &D, uint8_t *Data,
287 size_t Size, size_t MaxSize) {
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000288 if (Size > MaxSize) return 0;
Kostya Serebryanyb2e98972015-09-04 00:40:29 +0000289 if (D.empty()) return 0;
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000290 DictionaryEntry &DE = D[Rand(D.size())];
Kostya Serebryany3364f902016-10-25 02:04:43 +0000291 Size = ApplyDictionaryEntry(Data, Size, MaxSize, DE);
292 if (!Size) return 0;
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000293 DE.IncUseCount();
294 CurrentDictionaryEntrySequence.push_back(&DE);
Kostya Serebryany41740052016-01-12 02:36:59 +0000295 return Size;
Kostya Serebryany7d211662015-09-04 00:12:11 +0000296}
297
Kostya Serebryanya7398ba2016-08-17 18:10:42 +0000298// Overwrites part of To[0,ToSize) with a part of From[0,FromSize).
299// Returns ToSize.
300size_t MutationDispatcher::CopyPartOf(const uint8_t *From, size_t FromSize,
301 uint8_t *To, size_t ToSize) {
302 // Copy From[FromBeg, FromBeg + CopySize) into To[ToBeg, ToBeg + CopySize).
303 size_t ToBeg = Rand(ToSize);
304 size_t CopySize = Rand(ToSize - ToBeg) + 1;
305 assert(ToBeg + CopySize <= ToSize);
306 CopySize = std::min(CopySize, FromSize);
307 size_t FromBeg = Rand(FromSize - CopySize + 1);
308 assert(FromBeg + CopySize <= FromSize);
309 memmove(To + ToBeg, From + FromBeg, CopySize);
310 return ToSize;
311}
312
313// Inserts part of From[0,ToSize) into To.
314// Returns new size of To on success or 0 on failure.
315size_t MutationDispatcher::InsertPartOf(const uint8_t *From, size_t FromSize,
316 uint8_t *To, size_t ToSize,
317 size_t MaxToSize) {
318 if (ToSize >= MaxToSize) return 0;
319 size_t AvailableSpace = MaxToSize - ToSize;
320 size_t MaxCopySize = std::min(AvailableSpace, FromSize);
321 size_t CopySize = Rand(MaxCopySize) + 1;
322 size_t FromBeg = Rand(FromSize - CopySize + 1);
323 assert(FromBeg + CopySize <= FromSize);
324 size_t ToInsertPos = Rand(ToSize + 1);
325 assert(ToInsertPos + CopySize <= MaxToSize);
326 size_t TailSize = ToSize - ToInsertPos;
327 if (To == From) {
328 MutateInPlaceHere.resize(MaxToSize);
329 memcpy(MutateInPlaceHere.data(), From + FromBeg, CopySize);
330 memmove(To + ToInsertPos + CopySize, To + ToInsertPos, TailSize);
331 memmove(To + ToInsertPos, MutateInPlaceHere.data(), CopySize);
332 } else {
333 memmove(To + ToInsertPos + CopySize, To + ToInsertPos, TailSize);
334 memmove(To + ToInsertPos, From + FromBeg, CopySize);
335 }
336 return ToSize + CopySize;
337}
338
339size_t MutationDispatcher::Mutate_CopyPart(uint8_t *Data, size_t Size,
340 size_t MaxSize) {
Kostya Serebryanyb7a00862017-01-23 22:52:13 +0000341 if (Size > MaxSize || Size == 0) return 0;
Kostya Serebryanya7398ba2016-08-17 18:10:42 +0000342 if (Rand.RandBool())
343 return CopyPartOf(Data, Size, Data, Size);
344 else
345 return InsertPartOf(Data, Size, Data, Size, MaxSize);
346}
347
Kostya Serebryany25425ad2015-09-08 17:19:31 +0000348size_t MutationDispatcher::Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size,
349 size_t MaxSize) {
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000350 if (Size > MaxSize) return 0;
Kostya Serebryany25425ad2015-09-08 17:19:31 +0000351 size_t B = Rand(Size);
352 while (B < Size && !isdigit(Data[B])) B++;
353 if (B == Size) return 0;
354 size_t E = B;
355 while (E < Size && isdigit(Data[E])) E++;
356 assert(B < E);
357 // now we have digits in [B, E).
358 // strtol and friends don't accept non-zero-teminated data, parse it manually.
359 uint64_t Val = Data[B] - '0';
360 for (size_t i = B + 1; i < E; i++)
361 Val = Val * 10 + Data[i] - '0';
362
363 // Mutate the integer value.
364 switch(Rand(5)) {
365 case 0: Val++; break;
366 case 1: Val--; break;
367 case 2: Val /= 2; break;
368 case 3: Val *= 2; break;
369 case 4: Val = Rand(Val * Val); break;
370 default: assert(0);
371 }
372 // Just replace the bytes with the new ones, don't bother moving bytes.
373 for (size_t i = B; i < E; i++) {
374 size_t Idx = E + B - i - 1;
375 assert(Idx >= B && Idx < E);
376 Data[Idx] = (Val % 10) + '0';
377 Val /= 10;
378 }
379 return Size;
380}
381
Kostya Serebryany0c537b12016-08-17 21:30:30 +0000382template<class T>
383size_t ChangeBinaryInteger(uint8_t *Data, size_t Size, Random &Rand) {
384 if (Size < sizeof(T)) return 0;
385 size_t Off = Rand(Size - sizeof(T) + 1);
386 assert(Off + sizeof(T) <= Size);
387 T Val;
Kostya Serebryany65f102d2016-10-22 03:48:53 +0000388 if (Off < 64 && !Rand(4)) {
389 Val = Size;
390 if (Rand.RandBool())
391 Val = Bswap(Val);
392 } else {
393 memcpy(&Val, Data + Off, sizeof(Val));
394 T Add = Rand(21);
395 Add -= 10;
396 if (Rand.RandBool())
397 Val = Bswap(T(Bswap(Val) + Add)); // Add assuming different endiannes.
398 else
399 Val = Val + Add; // Add assuming current endiannes.
400 if (Add == 0 || Rand.RandBool()) // Maybe negate.
401 Val = -Val;
402 }
Kostya Serebryany0c537b12016-08-17 21:30:30 +0000403 memcpy(Data + Off, &Val, sizeof(Val));
404 return Size;
405}
406
407size_t MutationDispatcher::Mutate_ChangeBinaryInteger(uint8_t *Data,
408 size_t Size,
409 size_t MaxSize) {
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000410 if (Size > MaxSize) return 0;
Kostya Serebryany0c537b12016-08-17 21:30:30 +0000411 switch (Rand(4)) {
412 case 3: return ChangeBinaryInteger<uint64_t>(Data, Size, Rand);
413 case 2: return ChangeBinaryInteger<uint32_t>(Data, Size, Rand);
414 case 1: return ChangeBinaryInteger<uint16_t>(Data, Size, Rand);
415 case 0: return ChangeBinaryInteger<uint8_t>(Data, Size, Rand);
416 default: assert(0);
417 }
Kostya Serebryanya533e512016-08-19 20:57:09 +0000418 return 0;
Kostya Serebryany0c537b12016-08-17 21:30:30 +0000419}
420
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000421size_t MutationDispatcher::Mutate_CrossOver(uint8_t *Data, size_t Size,
422 size_t MaxSize) {
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000423 if (Size > MaxSize) return 0;
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000424 if (!Corpus || Corpus->size() < 2 || Size == 0) return 0;
425 size_t Idx = Rand(Corpus->size());
Kostya Serebryanya7398ba2016-08-17 18:10:42 +0000426 const Unit &O = (*Corpus)[Idx];
427 if (O.empty()) return 0;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000428 MutateInPlaceHere.resize(MaxSize);
429 auto &U = MutateInPlaceHere;
Kostya Serebryanya533e512016-08-19 20:57:09 +0000430 size_t NewSize = 0;
Kostya Serebryanya7398ba2016-08-17 18:10:42 +0000431 switch(Rand(3)) {
432 case 0:
433 NewSize = CrossOver(Data, Size, O.data(), O.size(), U.data(), U.size());
434 break;
435 case 1:
436 NewSize = InsertPartOf(O.data(), O.size(), U.data(), U.size(), MaxSize);
Kostya Serebryanyc24ec322017-02-06 21:21:37 +0000437 if (!NewSize)
438 NewSize = CopyPartOf(O.data(), O.size(), U.data(), U.size());
439 break;
Kostya Serebryanya7398ba2016-08-17 18:10:42 +0000440 case 2:
441 NewSize = CopyPartOf(O.data(), O.size(), U.data(), U.size());
442 break;
443 default: assert(0);
444 }
Kostya Serebryany27ab2d72015-12-19 02:49:09 +0000445 assert(NewSize > 0 && "CrossOver returned empty unit");
446 assert(NewSize <= MaxSize && "CrossOver returned overisized unit");
447 memcpy(Data, U.data(), NewSize);
448 return NewSize;
449}
450
Kostya Serebryany14c50282015-12-19 01:09:49 +0000451void MutationDispatcher::StartMutationSequence() {
Kostya Serebryany292cf032016-02-13 03:37:24 +0000452 CurrentMutatorSequence.clear();
453 CurrentDictionaryEntrySequence.clear();
Kostya Serebryany14c50282015-12-19 01:09:49 +0000454}
455
Kostya Serebryany4b358742016-01-14 02:36:44 +0000456// Copy successful dictionary entries to PersistentAutoDictionary.
457void MutationDispatcher::RecordSuccessfulMutationSequence() {
Kostya Serebryany292cf032016-02-13 03:37:24 +0000458 for (auto DE : CurrentDictionaryEntrySequence) {
459 // PersistentAutoDictionary.AddWithSuccessCountOne(DE);
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000460 DE->IncSuccessCount();
Kostya Serebryanya44ebf4d2017-01-19 21:14:47 +0000461 assert(DE->GetW().size());
Kostya Serebryany4b358742016-01-14 02:36:44 +0000462 // Linear search is fine here as this happens seldom.
Kostya Serebryany292cf032016-02-13 03:37:24 +0000463 if (!PersistentAutoDictionary.ContainsWord(DE->GetW()))
464 PersistentAutoDictionary.push_back({DE->GetW(), 1});
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000465 }
Kostya Serebryany4b358742016-01-14 02:36:44 +0000466}
467
468void MutationDispatcher::PrintRecommendedDictionary() {
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000469 std::vector<DictionaryEntry> V;
Kostya Serebryany292cf032016-02-13 03:37:24 +0000470 for (auto &DE : PersistentAutoDictionary)
471 if (!ManualDictionary.ContainsWord(DE.GetW()))
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000472 V.push_back(DE);
Kostya Serebryany4b358742016-01-14 02:36:44 +0000473 if (V.empty()) return;
474 Printf("###### Recommended dictionary. ######\n");
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000475 for (auto &DE: V) {
Kostya Serebryanya44ebf4d2017-01-19 21:14:47 +0000476 assert(DE.GetW().size());
Kostya Serebryany4b358742016-01-14 02:36:44 +0000477 Printf("\"");
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000478 PrintASCII(DE.GetW(), "\"");
479 Printf(" # Uses: %zd\n", DE.GetUseCount());
Kostya Serebryany4b358742016-01-14 02:36:44 +0000480 }
481 Printf("###### End of recommended dictionary. ######\n");
482}
483
Kostya Serebryany14c50282015-12-19 01:09:49 +0000484void MutationDispatcher::PrintMutationSequence() {
Kostya Serebryany292cf032016-02-13 03:37:24 +0000485 Printf("MS: %zd ", CurrentMutatorSequence.size());
486 for (auto M : CurrentMutatorSequence)
Kostya Serebryany14c50282015-12-19 01:09:49 +0000487 Printf("%s-", M.Name);
Kostya Serebryany292cf032016-02-13 03:37:24 +0000488 if (!CurrentDictionaryEntrySequence.empty()) {
Kostya Serebryany41740052016-01-12 02:36:59 +0000489 Printf(" DE: ");
Kostya Serebryany292cf032016-02-13 03:37:24 +0000490 for (auto DE : CurrentDictionaryEntrySequence) {
Kostya Serebryany41740052016-01-12 02:36:59 +0000491 Printf("\"");
Kostya Serebryany160dcba2016-01-22 23:55:14 +0000492 PrintASCII(DE->GetW(), "\"-");
Kostya Serebryany41740052016-01-12 02:36:59 +0000493 }
494 }
Kostya Serebryany14c50282015-12-19 01:09:49 +0000495}
496
Kostya Serebryanyec2dcb12015-09-03 21:24:19 +0000497size_t MutationDispatcher::Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000498 return MutateImpl(Data, Size, MaxSize, Mutators);
499}
500
501size_t MutationDispatcher::DefaultMutate(uint8_t *Data, size_t Size,
502 size_t MaxSize) {
503 return MutateImpl(Data, Size, MaxSize, DefaultMutators);
504}
505
506// Mutates Data in place, returns new size.
507size_t MutationDispatcher::MutateImpl(uint8_t *Data, size_t Size,
508 size_t MaxSize,
509 const std::vector<Mutator> &Mutators) {
Kostya Serebryanyf3424592015-05-22 22:35:31 +0000510 assert(MaxSize > 0);
Kostya Serebryanyb2e98972015-09-04 00:40:29 +0000511 // Some mutations may fail (e.g. can't insert more bytes if Size == MaxSize),
512 // in which case they will return 0.
513 // Try several times before returning un-mutated data.
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000514 for (int Iter = 0; Iter < 100; Iter++) {
Mike Aizatsky70fd3e42016-06-03 21:34:29 +0000515 auto M = Mutators[Rand(Mutators.size())];
Kostya Serebryany14c50282015-12-19 01:09:49 +0000516 size_t NewSize = (this->*(M.Fn))(Data, Size, MaxSize);
Kostya Serebryany624f59f2016-09-22 01:34:58 +0000517 if (NewSize && NewSize <= MaxSize) {
Mike Aizatskyf0b3e852016-06-23 20:44:48 +0000518 if (Options.OnlyASCII)
519 ToASCII(Data, NewSize);
Kostya Serebryany292cf032016-02-13 03:37:24 +0000520 CurrentMutatorSequence.push_back(M);
Kostya Serebryany14c50282015-12-19 01:09:49 +0000521 return NewSize;
522 }
Kostya Serebryanyb2e98972015-09-04 00:40:29 +0000523 }
Kostya Serebryanyb7a00862017-01-23 22:52:13 +0000524 *Data = ' ';
525 return 1; // Fallback, should not happen frequently.
Aaron Ballmanef116982015-01-29 16:58:29 +0000526}
527
Kostya Serebryany476f0ce2016-01-16 03:53:32 +0000528void MutationDispatcher::AddWordToManualDictionary(const Word &W) {
Kostya Serebryany292cf032016-02-13 03:37:24 +0000529 ManualDictionary.push_back(
Kostya Serebryany476f0ce2016-01-16 03:53:32 +0000530 {W, std::numeric_limits<size_t>::max()});
Kostya Serebryany152ac7a2016-01-07 01:49:35 +0000531}
532
Aaron Ballmanef116982015-01-29 16:58:29 +0000533} // namespace fuzzer