1 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 2 // See https://llvm.org/LICENSE.txt for license information. 3 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 4 5 // Simple test for a fuzzer. 6 // This is a sample fuzz target for a custom serialization format that uses 7 // a magic separator to split the input into several independent buffers. 8 // The fuzzer must find the input consisting of 2 subinputs: "Fuzz" and "me". 9 #include <cassert> 10 #include <cstdint> 11 #include <cstdio> 12 #include <cstdlib> 13 #include <cstring> 14 15 #include <algorithm> 16 #include <vector> 17 18 // Splits [data,data+size) into a vector of strings using a "magic" Separator. 19 std::vector<std::vector<uint8_t>> SplitInput(const uint8_t *Data, size_t Size, 20 const uint8_t *Separator, 21 size_t SeparatorSize) { 22 std::vector<std::vector<uint8_t>> Res; 23 assert(SeparatorSize > 0); 24 auto Beg = Data; 25 auto End = Data + Size; 26 // Using memmem here. std::search may be harder for libFuzzer today. 27 while (const uint8_t *Pos = (const uint8_t *)memmem(Beg, End - Beg, 28 Separator, SeparatorSize)) { 29 Res.push_back({Beg, Pos}); 30 Beg = Pos + SeparatorSize; 31 } 32 if (Beg < End) 33 Res.push_back({Beg, End}); 34 return Res; 35 } 36 37 static volatile int *Nil = nullptr; 38 39 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { 40 if (Size > 10) return 0; // To make the test quick. 41 const uint8_t Separator[] = {0xDE, 0xAD, 0xBE, 0xEF}; 42 auto Inputs = SplitInput(Data, Size, Separator, sizeof(Separator)); 43 std::vector<uint8_t> Fuzz({'F', 'u', 'z', 'z'}); 44 std::vector<uint8_t> Me({'m', 'e'}); 45 if (Inputs.size() == 2 && Inputs[0] == Fuzz && Inputs[1] == Me) 46 *Nil = 42; // crash. 47 return 0; 48 } 49 50