blob: 60d5623ada608ad6dfc1c54c2ce4ca3839b7cc7a [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
12#include "FuzzerInternal.h"
13
14namespace fuzzer {
15
16static 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
28static char RandCh() {
29 if (rand() % 2) return rand();
30 const char *Special = "!*'();:@&=+$,/?%#[]123ABCxyz-`~.";
31 return Special[rand() % (sizeof(Special) - 1)];
32}
33
Kostya Serebryany5b266a82015-02-04 19:10:20 +000034// Mutate U in place.
Aaron Ballmanef116982015-01-29 16:58:29 +000035void Mutate(Unit *U, size_t MaxLen) {
36 assert(MaxLen > 0);
37 assert(U->size() <= MaxLen);
Kostya Serebryany5b266a82015-02-04 19:10:20 +000038 if (U->empty()) {
39 for (size_t i = 0; i < MaxLen; i++)
40 U->push_back(RandCh());
41 return;
42 }
43 assert(!U->empty());
Aaron Ballmanef116982015-01-29 16:58:29 +000044 switch (rand() % 3) {
45 case 0:
Kostya Serebryany5b266a82015-02-04 19:10:20 +000046 if (U->size() > 1) {
Aaron Ballmanef116982015-01-29 16:58:29 +000047 U->erase(U->begin() + rand() % U->size());
Kostya Serebryany5b266a82015-02-04 19:10:20 +000048 break;
49 }
50 // Fallthrough
Aaron Ballmanef116982015-01-29 16:58:29 +000051 case 1:
Kostya Serebryany5b266a82015-02-04 19:10:20 +000052 if (U->size() < MaxLen) {
Aaron Ballmanef116982015-01-29 16:58:29 +000053 U->insert(U->begin() + rand() % U->size(), RandCh());
54 } else { // At MaxLen.
55 uint8_t Ch = RandCh();
56 size_t Idx = rand() % U->size();
57 (*U)[Idx] = Ch;
58 }
59 break;
60 default:
Kostya Serebryany5b266a82015-02-04 19:10:20 +000061 {
62 size_t Idx = rand() % U->size();
63 (*U)[Idx] = FlipRandomBit((*U)[Idx]);
Aaron Ballmanef116982015-01-29 16:58:29 +000064 }
65 break;
66 }
Kostya Serebryany5b266a82015-02-04 19:10:20 +000067 assert(!U->empty());
Aaron Ballmanef116982015-01-29 16:58:29 +000068}
69
70} // namespace fuzzer