[libFuzzer] move the mutators to public interface so that custom mutators may reuse...
[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   MyFuzzer(fuzzer::FuzzerRandomBase *Rand)
18       : fuzzer::UserSuppliedFuzzer(Rand) {}
19   void TargetFunction(const uint8_t *Data, size_t Size) {
20     if (Size <= 10) return;
21     if (memcmp(Data, &kMagic, sizeof(kMagic))) return;
22     // It's hard to get here w/o advanced fuzzing techniques (e.g. cmp tracing).
23     // So, we simply 'fix' the data in the custom mutator.
24     if (Data[8] == 'H') {
25       if (Data[9] == 'i') {
26         if (Data[10] == '!') {
27           std::cout << "BINGO; Found the target, exiting\n";
28           exit(1);
29         }
30       }
31     }
32   }
33   // Custom mutator.
34   virtual size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
35     assert(MaxSize > sizeof(kMagic));
36     if (Size < sizeof(kMagic))
37       Size = sizeof(kMagic);
38     // "Fix" the data, then mutate.
39     memcpy(Data, &kMagic, std::min(MaxSize, sizeof(kMagic)));
40     return fuzzer::UserSuppliedFuzzer::Mutate(
41         Data + sizeof(kMagic), Size - sizeof(kMagic), MaxSize - sizeof(kMagic));
42   }
43   // No need to redefine CrossOver() here.
44 };
45
46 int main(int argc, char **argv) {
47   fuzzer::FuzzerRandomLibc Rand(0);
48   MyFuzzer F(&Rand);
49   fuzzer::FuzzerDriver(argc, argv, F);
50 }