1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
15 // This is a simple example of how to write a fuzzer. The target function is
16 // crafted to demonstrates how the fuzzer can analyze conditional branches and
17 // incrementally cover more and more code until a defect is found.
19 // See build_and_run_toy_fuzzer.sh for examples of how you can build and run
26 #include "pw_string/util.h"
30 // The code to fuzz. This would normally be in separate library.
31 void toy_example(const char* word1, const char* word2) {
33 if (word1[0] == 'h') {
34 if (word1[1] == 'e') {
35 if (word1[2] == 'l') {
36 if (word1[3] == 'l') {
37 if (word1[4] == 'o') {
44 if (word2[0] == 'w') {
45 if (word2[1] == 'o') {
46 if (word2[2] == 'r') {
47 if (word2[3] == 'l') {
48 if (word2[4] == 'd') {
50 // Our "defect", simulating a crash.
62 // The fuzz target function
63 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
64 // We want to split our input into two strings.
65 const char* word1 = reinterpret_cast<const char*>(data);
67 // If that's not feasible, toss this input. The fuzzer will quickly learn that
68 // inputs without null-terminators are uninteresting.
69 size_t offset = pw::string::Length(word1, size) + 1;
74 // Actually, inputs without TWO null terminators are uninteresting.
75 const char* word2 = reinterpret_cast<const char*>(&data[offset]);
77 if (pw::string::Length(word2, size) == size) {
81 // Call the code we're targeting!
82 toy_example(word1, word2);
84 // By convention, the fuzzer always returns zero.