b46313dbafbf469fd19d61ea465ef4f8bb342b2e
[oota-llvm.git] / lib / Fuzzer / test / UserSuppliedFuzzerTest.cpp
1 // Simple test for a fuzzer.
2 // The fuzzer must find the string "Hi!" preceded by a magic value.
3 // Uses UserSuppliedFuzzer which ensures that the magic is present.
4 #include <cstdint>
5 #include <cassert>
6 #include <cstdlib>
7 #include <cstddef>
8 #include <cstring>
9 #include <iostream>
10
11 #include "FuzzerInterface.h"
12
13 static const uint64_t kMagic = 8860221463604ULL;
14
15 class MyFuzzer : public fuzzer::UserSuppliedFuzzer {
16  public:
17   void TargetFunction(const uint8_t *Data, size_t Size) {
18     if (Size <= 10) return;
19     if (memcmp(Data, &kMagic, sizeof(kMagic))) return;
20     // It's hard to get here w/o advanced fuzzing techniques (e.g. cmp tracing).
21     // So, we simply 'fix' the data in the custom mutator.
22     if (Data[8] == 'H') {
23       if (Data[9] == 'i') {
24         if (Data[10] == '!') {
25           std::cout << "BINGO; Found the target, exiting\n";
26           exit(1);
27         }
28       }
29     }
30   }
31   // Custom mutator.
32   virtual size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
33     assert(MaxSize > sizeof(kMagic));
34     if (Size < sizeof(kMagic))
35       Size = sizeof(kMagic);
36     // "Fix" the data, then mutate.
37     memcpy(Data, &kMagic, std::min(MaxSize, sizeof(kMagic)));
38     return BasicMutate(Data + sizeof(kMagic), Size - sizeof(kMagic),
39                        MaxSize - sizeof(kMagic));
40   }
41   // No need to redefine CrossOver() here.
42 };
43
44 int main(int argc, char **argv) {
45   MyFuzzer F;
46   fuzzer::FuzzerDriver(argc, argv, F);
47 }