1 //===- FuzzerMutate.cpp - Mutate a test input -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // Mutate a test input.
10 //===----------------------------------------------------------------------===//
14 #include "FuzzerInternal.h"
21 size_t (MutationDispatcher::*Fn)(uint8_t *Data, size_t Size, size_t Max);
25 struct DictionaryEntry {
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;
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,
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);
58 static char FlipRandomBit(char X, FuzzerRandomBase &Rand) {
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)];
76 size_t MutationDispatcher::Mutate_ShuffleBytes(uint8_t *Data, size_t 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,
88 size_t MutationDispatcher::Mutate_EraseByte(uint8_t *Data, size_t Size,
91 if (Size == 1) return 0;
92 size_t Idx = Rand(Size);
94 memmove(Data + Idx, Data + Idx + 1, Size - Idx - 1);
98 size_t MutationDispatcher::Mutate_InsertByte(uint8_t *Data, size_t Size,
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);
108 size_t MutationDispatcher::Mutate_ChangeByte(uint8_t *Data, size_t Size,
110 size_t Idx = Rand(Size);
111 Data[Idx] = RandCh(Rand);
115 size_t MutationDispatcher::Mutate_ChangeBit(uint8_t *Data, size_t Size,
117 size_t Idx = Rand(Size);
118 Data[Idx] = FlipRandomBit(Data[Idx], Rand);
122 size_t MutationDispatcher::Mutate_AddWordFromManualDictionary(uint8_t *Data,
125 return MDImpl->AddWordFromDictionary(MDImpl->ManualDictionary, Data, Size,
129 size_t MutationDispatcher::Mutate_AddWordFromAutoDictionary(uint8_t *Data,
132 return MDImpl->AddWordFromDictionary(MDImpl->AutoDictionary, Data, Size,
136 size_t MutationDispatcher::Impl::AddWordFromDictionary(
137 const std::vector<DictionaryEntry> &D, uint8_t *Data, size_t Size,
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());
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());
156 CurrentDictionaryEntrySequence.push_back(DE);
160 size_t MutationDispatcher::Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size,
162 size_t B = Rand(Size);
163 while (B < Size && !isdigit(Data[B])) B++;
164 if (B == Size) return 0;
166 while (E < Size && isdigit(Data[E])) 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';
174 // Mutate the integer value.
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;
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';
193 size_t MutationDispatcher::Mutate_CrossOver(uint8_t *Data, size_t Size,
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;
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);
209 void MutationDispatcher::StartMutationSequence() {
210 MDImpl->CurrentMutatorSequence.clear();
211 MDImpl->CurrentDictionaryEntrySequence.clear();
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()) {
220 for (auto DE : MDImpl->CurrentDictionaryEntrySequence) {
222 PrintASCII(DE.Word, "\"-");
227 // Mutates Data in place, returns new size.
228 size_t MutationDispatcher::Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
230 assert(Size <= MaxSize);
232 for (size_t i = 0; i < MaxSize; i++)
233 Data[i] = RandCh(Rand);
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);
245 MDImpl->CurrentMutatorSequence.push_back(M);
252 void MutationDispatcher::SetCorpus(const std::vector<Unit> *Corpus) {
253 MDImpl->SetCorpus(Corpus);
256 void MutationDispatcher::AddWordToManualDictionary(const Unit &Word) {
257 MDImpl->ManualDictionary.push_back(
258 {Word, std::numeric_limits<size_t>::max()});
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});
268 void MutationDispatcher::ClearAutoDictionary() {
269 MDImpl->AutoDictionary.clear();
272 MutationDispatcher::MutationDispatcher(FuzzerRandomBase &Rand) : Rand(Rand) {
273 MDImpl = new Impl(Rand);
276 MutationDispatcher::~MutationDispatcher() { delete MDImpl; }
278 } // namespace fuzzer