xref: /aosp_15_r20/external/pigweed/pw_fuzzer/examples/libfuzzer/toy_fuzzer.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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 <string_view>
25 
26 #include "pw_fuzzer/fuzzed_data_provider.h"
27 #include "pw_status/status.h"
28 
29 namespace pw::fuzzer::example {
30 namespace {
31 
32 // The code to fuzz. This would normally be in separate library.
SomeAPI(std::string_view s1,std::string_view s2)33 Status SomeAPI(std::string_view s1, std::string_view s2) {
34   if (s1 == "hello") {
35     if (s2 == "world") {
36       abort();
37     }
38   }
39   return OkStatus();
40 }
41 
42 }  // namespace
43 }  // namespace pw::fuzzer::example
44 
45 // The fuzz target function
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)46 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
47   FuzzedDataProvider provider(data, size);
48   std::string s1 = provider.ConsumeRandomLengthString();
49   std::string s2 = provider.ConsumeRemainingBytesAsString();
50   pw::fuzzer::example::SomeAPI(s1, s2).IgnoreError();
51   return 0;
52 }
53