Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_fuzzer / examples / toy_fuzzer.cc
1 // Copyright 2020 The Pigweed Authors
2 //
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
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
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
13 // the License.
14
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.
18 //
19 // See build_and_run_toy_fuzzer.sh for examples of how you can build and run
20 // this example.
21
22 #include <cstddef>
23 #include <cstdint>
24 #include <cstring>
25
26 #include "pw_string/util.h"
27
28 namespace {
29
30 // The code to fuzz. This would normally be in separate library.
31 void toy_example(const char* word1, const char* word2) {
32   bool greeted = false;
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') {
38             greeted = true;
39           }
40         }
41       }
42     }
43   }
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') {
49             if (greeted) {
50               // Our "defect", simulating a crash.
51               __builtin_trap();
52             }
53           }
54         }
55       }
56     }
57   }
58 }
59
60 }  // namespace
61
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);
66
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;
70   if (offset >= size) {
71     return 0;
72   }
73
74   // Actually, inputs without TWO null terminators are uninteresting.
75   const char* word2 = reinterpret_cast<const char*>(&data[offset]);
76   size -= offset;
77   if (pw::string::Length(word2, size) == size) {
78     return 0;
79   }
80
81   // Call the code we're targeting!
82   toy_example(word1, word2);
83
84   // By convention, the fuzzer always returns zero.
85   return 0;
86 }