Make the test actually test what it's supposed to test. Add a test for the from memor...
[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 "FuzzerInternal.h"
13
14 namespace fuzzer {
15
16 static char FlipRandomBit(char X) {
17   int Bit = rand() % 8;
18   char Mask = 1 << Bit;
19   char R;
20   if (X & (1 << Bit))
21     R = X & ~Mask;
22   else
23     R = X | Mask;
24   assert(R != X);
25   return R;
26 }
27
28 static char RandCh() {
29   if (rand() % 2) return rand();
30   const char *Special = "!*'();:@&=+$,/?%#[]123ABCxyz-`~.";
31   return Special[rand() % (sizeof(Special) - 1)];
32 }
33
34 void Mutate(Unit *U, size_t MaxLen) {
35   assert(MaxLen > 0);
36   assert(U->size() <= MaxLen);
37   switch (rand() % 3) {
38   case 0:
39     if (U->size())
40       U->erase(U->begin() + rand() % U->size());
41     break;
42   case 1:
43     if (U->empty()) {
44       U->push_back(RandCh());
45     } else if (U->size() < MaxLen) {
46       U->insert(U->begin() + rand() % U->size(), RandCh());
47     } else { // At MaxLen.
48       uint8_t Ch = RandCh();
49       size_t Idx = rand() % U->size();
50       (*U)[Idx] = Ch;
51     }
52     break;
53   default:
54     if (!U->empty()) {
55       size_t idx = rand() % U->size();
56       (*U)[idx] = FlipRandomBit((*U)[idx]);
57     }
58     break;
59   }
60 }
61
62 }  // namespace fuzzer