diff --git a/fuzzers/libfuzzer_reachability/.gitignore b/fuzzers/libfuzzer_reachability/.gitignore new file mode 100644 index 0000000000..a977a2ca5b --- /dev/null +++ b/fuzzers/libfuzzer_reachability/.gitignore @@ -0,0 +1 @@ +libpng-* \ No newline at end of file diff --git a/fuzzers/libfuzzer_reachability/Cargo.toml b/fuzzers/libfuzzer_reachability/Cargo.toml new file mode 100644 index 0000000000..86a79eb22f --- /dev/null +++ b/fuzzers/libfuzzer_reachability/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "libfuzzer_reachability" +version = "0.2.0" +authors = ["Andrea Fioraldi ", "Dominik Maier "] +edition = "2018" + +[features] +default = ["std"] +std = [] + +#[profile.release] +#lto = true +#codegen-units = 1 +#opt-level = 3 +#debug = true + +[build-dependencies] +cc = { version = "1.0", features = ["parallel"] } +which = { version = "4.0.2" } +num_cpus = "1.0" + +[dependencies] +libafl = { path = "../../libafl/" } +libafl_targets = { path = "../../libafl_targets/", features = ["pcguard_hitcounts", "libfuzzer"] } +# TODO Include it only when building cc +libafl_cc = { path = "../../libafl_cc/" } + +[lib] +name = "libfuzzer_libpng" +crate-type = ["staticlib"] diff --git a/fuzzers/libfuzzer_reachability/README.md b/fuzzers/libfuzzer_reachability/README.md new file mode 100644 index 0000000000..87ad627715 --- /dev/null +++ b/fuzzers/libfuzzer_reachability/README.md @@ -0,0 +1,79 @@ +# Libfuzzer for libpng + +This folder contains an example fuzzer for libpng, using LLMP for fast multi-process fuzzing and crash detection. + +In contrast to other fuzzer examples, this setup uses `fuzz_loop_for`, to occasionally respawn the fuzzer executor. +While this costs performance, it can be useful for targets with memory leaks or other instabilities. +If your target is really instable, however, consider exchanging the `InProcessExecutor` for a `ForkserverExecutor` instead. + +To show off crash detection, we added a `ud2` instruction to the harness, edit harness.cc if you want a non-crashing example. +It has been tested on Linux. + +## Build + +To build this example, run + +```bash +cargo build --release +``` + +This will build the library with the fuzzer (src/lib.rs) with the libfuzzer compatibility layer and the SanitizerCoverage runtime functions for coverage feedback. +In addition, it will also build two C and C++ compiler wrappers (bin/libafl_c(libafl_c/xx).rs) that you must use to compile the target. + +The compiler wrappers, `libafl_cc` and libafl_cxx`, will end up in `./target/release/` (or `./target/debug`, in case you did not build with the `--release` flag). + +Then download libpng, and unpack the archive: +```bash +wget https://deac-fra.dl.sourceforge.net/project/libpng/libpng16/1.6.37/libpng-1.6.37.tar.xz +tar -xvf libpng-1.6.37.tar.xz +``` +Run `patch libpng-1.6.37/png.c diff.patch` before compiling the libpng +Now compile libpng, using the libafl_cc compiler wrapper: + +```bash +cd libpng-1.6.37 +./configure +make CC=$(realpath ../target/release/libafl_cc) CXX=$(realpath ../target/release/libafl_cxx) -j `nproc` +``` + +You can find the static lib at `libpng-1.6.37/.libs/libpng16.a`. + +Now, we have to build the libfuzzer harness and link all together to create our fuzzer binary. + +``` +cd .. +./target/release/libafl_cxx ./harness.cc libpng-1.6.37/.libs/libpng16.a -I libpng-1.6.37/ -o fuzzer_libpng -lz -lm +``` + +Afterward, the fuzzer will be ready to run. +Note that, unless you use the `launcher`, you will have to run the binary multiple times to actually start the fuzz process, see `Run` in the following. +This allows you to run multiple different builds of the same fuzzer alongside, for example, with and without ASAN (`-fsanitize=address`) or with different mutators. + +## Run + +The first time you run the binary, the broker will open a tcp port (currently on port `1337`), waiting for fuzzer clients to connect. This port is local and only used for the initial handshake. All further communication happens via shared map, to be independent of the kernel. Currently you must run the clients from the libfuzzer_libpng directory for them to be able to access the PNG corpus. + +``` +./fuzzer_libpng + +[libafl/src/bolts/llmp.rs:407] "We're the broker" = "We\'re the broker" +Doing broker things. Run this tool again to start fuzzing in a client. +``` + +And after running the above again in a separate terminal: + +``` +[libafl/src/bolts/llmp.rs:1464] "New connection" = "New connection" +[libafl/src/bolts/llmp.rs:1464] addr = 127.0.0.1:33500 +[libafl/src/bolts/llmp.rs:1464] stream.peer_addr().unwrap() = 127.0.0.1:33500 +[LOG Debug]: Loaded 4 initial testcases. +[New Testcase #2] clients: 3, corpus: 6, objectives: 0, executions: 5, exec/sec: 0 +< fuzzing stats > +``` + +As this example uses in-process fuzzing, we added a Restarting Event Manager (`setup_restarting_mgr`). +This means each client will start itself again to listen for crashes and timeouts. +By restarting the actual fuzzer, it can recover from these exit conditions. + +In any real-world scenario, you should use `taskset` to pin each client to an empty CPU core, the lib does not pick an empty core automatically (yet). + diff --git a/fuzzers/libfuzzer_reachability/corpus/not_kitty.png b/fuzzers/libfuzzer_reachability/corpus/not_kitty.png new file mode 100644 index 0000000000..eff7c1707b Binary files /dev/null and b/fuzzers/libfuzzer_reachability/corpus/not_kitty.png differ diff --git a/fuzzers/libfuzzer_reachability/corpus/not_kitty_alpha.png b/fuzzers/libfuzzer_reachability/corpus/not_kitty_alpha.png new file mode 100644 index 0000000000..2fb8da2c8f Binary files /dev/null and b/fuzzers/libfuzzer_reachability/corpus/not_kitty_alpha.png differ diff --git a/fuzzers/libfuzzer_reachability/corpus/not_kitty_gamma.png b/fuzzers/libfuzzer_reachability/corpus/not_kitty_gamma.png new file mode 100644 index 0000000000..939d9d29a9 Binary files /dev/null and b/fuzzers/libfuzzer_reachability/corpus/not_kitty_gamma.png differ diff --git a/fuzzers/libfuzzer_reachability/corpus/not_kitty_icc.png b/fuzzers/libfuzzer_reachability/corpus/not_kitty_icc.png new file mode 100644 index 0000000000..f0c7804d99 Binary files /dev/null and b/fuzzers/libfuzzer_reachability/corpus/not_kitty_icc.png differ diff --git a/fuzzers/libfuzzer_reachability/diff.patch b/fuzzers/libfuzzer_reachability/diff.patch new file mode 100644 index 0000000000..8c0ca68b83 --- /dev/null +++ b/fuzzers/libfuzzer_reachability/diff.patch @@ -0,0 +1,9 @@ +15a16,19 +> #define TARGET_SIZE 4 +> +> size_t __lafl_dummy_list[TARGET_SIZE] = {0}; +> size_t *__libafl_target_list = __lafl_dummy_list; +2562a2567 +> __lafl_dummy_list[0] = 1; +2584a2590 +> __lafl_dummy_list[1] = 1; diff --git a/fuzzers/libfuzzer_reachability/harness.cc b/fuzzers/libfuzzer_reachability/harness.cc new file mode 100644 index 0000000000..65faff685d --- /dev/null +++ b/fuzzers/libfuzzer_reachability/harness.cc @@ -0,0 +1,197 @@ +// libpng_read_fuzzer.cc +// Copyright 2017-2018 Glenn Randers-Pehrson +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that may +// be found in the LICENSE file https://cs.chromium.org/chromium/src/LICENSE + +// Last changed in libpng 1.6.35 [July 15, 2018] + +// The modifications in 2017 by Glenn Randers-Pehrson include +// 1. addition of a PNG_CLEANUP macro, +// 2. setting the option to ignore ADLER32 checksums, +// 3. adding "#include " which is needed on some platforms +// to provide memcpy(). +// 4. adding read_end_info() and creating an end_info structure. +// 5. adding calls to png_set_*() transforms commonly used by browsers. + +#include +#include +#include + +#include + +#define PNG_INTERNAL +#include "png.h" + +#define PNG_CLEANUP \ + if(png_handler.png_ptr) \ + { \ + if (png_handler.row_ptr) \ + png_free(png_handler.png_ptr, png_handler.row_ptr); \ + if (png_handler.end_info_ptr) \ + png_destroy_read_struct(&png_handler.png_ptr, &png_handler.info_ptr,\ + &png_handler.end_info_ptr); \ + else if (png_handler.info_ptr) \ + png_destroy_read_struct(&png_handler.png_ptr, &png_handler.info_ptr,\ + nullptr); \ + else \ + png_destroy_read_struct(&png_handler.png_ptr, nullptr, nullptr); \ + png_handler.png_ptr = nullptr; \ + png_handler.row_ptr = nullptr; \ + png_handler.info_ptr = nullptr; \ + png_handler.end_info_ptr = nullptr; \ + } + +struct BufState { + const uint8_t* data; + size_t bytes_left; +}; + +struct PngObjectHandler { + png_infop info_ptr = nullptr; + png_structp png_ptr = nullptr; + png_infop end_info_ptr = nullptr; + png_voidp row_ptr = nullptr; + BufState* buf_state = nullptr; + + ~PngObjectHandler() { + if (row_ptr) + png_free(png_ptr, row_ptr); + if (end_info_ptr) + png_destroy_read_struct(&png_ptr, &info_ptr, &end_info_ptr); + else if (info_ptr) + png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); + else + png_destroy_read_struct(&png_ptr, nullptr, nullptr); + delete buf_state; + } +}; + +void user_read_data(png_structp png_ptr, png_bytep data, size_t length) { + BufState* buf_state = static_cast(png_get_io_ptr(png_ptr)); + if (length > buf_state->bytes_left) { + png_error(png_ptr, "read error"); + } + memcpy(data, buf_state->data, length); + buf_state->bytes_left -= length; + buf_state->data += length; +} + +static const int kPngHeaderSize = 8; + +// Entry point for LibFuzzer. +// Roughly follows the libpng book example: +// http://www.libpng.org/pub/png/book/chapter13.html +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (size < kPngHeaderSize) { + return 0; + } + + std::vector v(data, data + size); + if (png_sig_cmp(v.data(), 0, kPngHeaderSize)) { + // not a PNG. + return 0; + } + + PngObjectHandler png_handler; + png_handler.png_ptr = nullptr; + png_handler.row_ptr = nullptr; + png_handler.info_ptr = nullptr; + png_handler.end_info_ptr = nullptr; + + png_handler.png_ptr = png_create_read_struct + (PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + if (!png_handler.png_ptr) { + return 0; + } + + png_handler.info_ptr = png_create_info_struct(png_handler.png_ptr); + if (!png_handler.info_ptr) { + PNG_CLEANUP + return 0; + } + + png_handler.end_info_ptr = png_create_info_struct(png_handler.png_ptr); + if (!png_handler.end_info_ptr) { + PNG_CLEANUP + return 0; + } + + png_set_crc_action(png_handler.png_ptr, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE); +#ifdef PNG_IGNORE_ADLER32 + png_set_option(png_handler.png_ptr, PNG_IGNORE_ADLER32, PNG_OPTION_ON); +#endif + + // Setting up reading from buffer. + png_handler.buf_state = new BufState(); + png_handler.buf_state->data = data + kPngHeaderSize; + png_handler.buf_state->bytes_left = size - kPngHeaderSize; + png_set_read_fn(png_handler.png_ptr, png_handler.buf_state, user_read_data); + png_set_sig_bytes(png_handler.png_ptr, kPngHeaderSize); + + if (setjmp(png_jmpbuf(png_handler.png_ptr))) { + PNG_CLEANUP + return 0; + } + + // Reading. + png_read_info(png_handler.png_ptr, png_handler.info_ptr); + + // reset error handler to put png_deleter into scope. + if (setjmp(png_jmpbuf(png_handler.png_ptr))) { + PNG_CLEANUP + return 0; + } + + png_uint_32 width, height; + int bit_depth, color_type, interlace_type, compression_type; + int filter_type; + + if (!png_get_IHDR(png_handler.png_ptr, png_handler.info_ptr, &width, + &height, &bit_depth, &color_type, &interlace_type, + &compression_type, &filter_type)) { + PNG_CLEANUP + return 0; + } + + // This is going to be too slow. + if (width && height > 100000000 / width) { + PNG_CLEANUP +#ifdef HAS_DUMMY_CRASH + #ifdef __aarch64__ + asm volatile (".word 0xf7f0a000\n"); + #else + asm("ud2"); + #endif +#endif + return 0; + } + + // Set several transforms that browsers typically use: + png_set_gray_to_rgb(png_handler.png_ptr); + png_set_expand(png_handler.png_ptr); + png_set_packing(png_handler.png_ptr); + png_set_scale_16(png_handler.png_ptr); + png_set_tRNS_to_alpha(png_handler.png_ptr); + + int passes = png_set_interlace_handling(png_handler.png_ptr); + + png_read_update_info(png_handler.png_ptr, png_handler.info_ptr); + + png_handler.row_ptr = png_malloc( + png_handler.png_ptr, png_get_rowbytes(png_handler.png_ptr, + png_handler.info_ptr)); + + for (int pass = 0; pass < passes; ++pass) { + for (png_uint_32 y = 0; y < height; ++y) { + png_read_row(png_handler.png_ptr, + static_cast(png_handler.row_ptr), nullptr); + } + } + + png_read_end(png_handler.png_ptr, png_handler.end_info_ptr); + + PNG_CLEANUP + return 0; +} + diff --git a/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs new file mode 100644 index 0000000000..dc65a9a57b --- /dev/null +++ b/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs @@ -0,0 +1,33 @@ +use libafl_cc::{ClangWrapper, CompilerWrapper, LIB_EXT, LIB_PREFIX}; +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() > 1 { + let mut dir = env::current_exe().unwrap(); + dir.pop(); + + let mut cc = ClangWrapper::new("clang", "clang++"); + cc.from_args(&args) + .unwrap() + .add_arg("-fsanitize-coverage=trace-pc-guard".into()) + .unwrap() + .add_link_arg( + dir.join(format!("{}libfuzzer_libpng.{}", LIB_PREFIX, LIB_EXT)) + .display() + .to_string(), + ) + .unwrap(); + // Libraries needed by libafl on Windows + #[cfg(windows)] + cc.add_link_arg("-lws2_32".into()) + .unwrap() + .add_link_arg("-lBcrypt".into()) + .unwrap() + .add_link_arg("-lAdvapi32".into()) + .unwrap(); + cc.run().unwrap(); + } else { + panic!("LibAFL CC: No Arguments given"); + } +} diff --git a/fuzzers/libfuzzer_reachability/src/bin/libafl_cxx.rs b/fuzzers/libfuzzer_reachability/src/bin/libafl_cxx.rs new file mode 100644 index 0000000000..2183682d96 --- /dev/null +++ b/fuzzers/libfuzzer_reachability/src/bin/libafl_cxx.rs @@ -0,0 +1,34 @@ +use libafl_cc::{ClangWrapper, CompilerWrapper, LIB_EXT, LIB_PREFIX}; +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() > 1 { + let mut dir = env::current_exe().unwrap(); + dir.pop(); + + let mut cc = ClangWrapper::new("clang", "clang++"); + cc.is_cpp() + .from_args(&args) + .unwrap() + .add_arg("-fsanitize-coverage=trace-pc-guard".into()) + .unwrap() + .add_link_arg( + dir.join(format!("{}libfuzzer_libpng.{}", LIB_PREFIX, LIB_EXT)) + .display() + .to_string(), + ) + .unwrap(); + // Libraries needed by libafl on Windows + #[cfg(windows)] + cc.add_link_arg("-lws2_32".into()) + .unwrap() + .add_link_arg("-lBcrypt".into()) + .unwrap() + .add_link_arg("-lAdvapi32".into()) + .unwrap(); + cc.run().unwrap(); + } else { + panic!("LibAFL CC: No Arguments given"); + } +} diff --git a/fuzzers/libfuzzer_reachability/src/lib.rs b/fuzzers/libfuzzer_reachability/src/lib.rs new file mode 100644 index 0000000000..13015a3bc4 --- /dev/null +++ b/fuzzers/libfuzzer_reachability/src/lib.rs @@ -0,0 +1,189 @@ +//! A libfuzzer-like fuzzer with llmp-multithreading support and restarts +//! The example harness is built for libpng. + +use core::time::Duration; +use std::{env, path::PathBuf}; + +use libafl::{ + bolts::tuples::tuple_list, + corpus::{ + Corpus, InMemoryCorpus, IndexesLenTimeMinimizerCorpusScheduler, OnDiskCorpus, + QueueCorpusScheduler, + }, + events::{setup_restarting_mgr_std, EventManager}, + executors::{inprocess::InProcessExecutor, ExitKind, TimeoutExecutor}, + feedback_or, + feedbacks::{ + CrashFeedback, MaxMapFeedback, ReachabilityFeedback, TimeFeedback, TimeoutFeedback, + }, + fuzzer::{Fuzzer, StdFuzzer}, + mutators::scheduled::{havoc_mutations, StdScheduledMutator}, + mutators::token_mutations::Tokens, + observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, + stages::mutational::StdMutationalStage, + state::{HasCorpus, HasMetadata, State}, + stats::SimpleStats, + utils::{current_nanos, StdRand}, + Error, +}; + +use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; + +#[cfg(unix)] +const TARGET_SIZE: usize = 4; + +#[cfg(unix)] +extern "C" { + static __libafl_target_list: *mut usize; +} + +/// The main fn, no_mangle as it is a C main +#[no_mangle] +pub fn main() { + // Registry the metadata types used in this fuzzer + // Needed only on no_std + //RegistryBuilder::register::(); + + println!( + "Workdir: {:?}", + env::current_dir().unwrap().to_string_lossy().to_string() + ); + fuzz( + vec![PathBuf::from("./corpus")], + PathBuf::from("./crashes"), + 1337, + ) + .expect("An error occurred while fuzzing"); +} + +/// The actual fuzzer +fn fuzz(corpus_dirs: Vec, objective_dir: PathBuf, broker_port: u16) -> Result<(), Error> { + // 'While the stats are state, they are usually used in the broker - which is likely never restarted + let stats = SimpleStats::new(|s| println!("{}", s)); + + // The restarting state will spawn the same process again as child, then restarted it each time it crashes. + let (state, mut restarting_mgr) = match setup_restarting_mgr_std(stats, broker_port) { + Ok(res) => res, + Err(err) => match err { + Error::ShuttingDown => { + return Ok(()); + } + _ => { + panic!("Failed to setup the restarter: {}", err); + } + }, + }; + + // Create an observation channel using the coverage map + let edges_observer = HitcountsMapObserver::new(unsafe { + StdMapObserver::new("edges", &mut EDGES_MAP, MAX_EDGES_NUM) + }); + + let reachability_observer = + unsafe { StdMapObserver::new_from_ptr("png.c", __libafl_target_list, TARGET_SIZE) }; + // If not restarting, create a State from scratch + let mut state = state.unwrap_or_else(|| { + State::new( + // RNG + StdRand::with_seed(current_nanos()), + // Corpus that will be evolved, we keep it in memory for performance + InMemoryCorpus::new(), + // Feedbacks to rate the interestingness of an input + feedback_or!( + MaxMapFeedback::new_with_observer_track(&edges_observer, true, false), + TimeFeedback::new() + ), + // Corpus in which we store solutions (crashes in this example), + // on disk so the user can get them after stopping the fuzzer + OnDiskCorpus::new(objective_dir).unwrap(), + // Feedbacks to recognize an input as solution + feedback_or!( + CrashFeedback::new(), + TimeoutFeedback::new(), + ReachabilityFeedback::new_with_observer(&reachability_observer) + ), + ) + }); + + println!("We're a client, let's fuzz :)"); + + // Create a PNG dictionary if not existing + if state.metadata().get::().is_none() { + state.add_metadata(Tokens::new(vec![ + vec![137, 80, 78, 71, 13, 10, 26, 10], // PNG header + "IHDR".as_bytes().to_vec(), + "IDAT".as_bytes().to_vec(), + "PLTE".as_bytes().to_vec(), + "IEND".as_bytes().to_vec(), + ])); + } + + // Setup a basic mutator with a mutational stage + let mutator = StdScheduledMutator::new(havoc_mutations()); + let stage = StdMutationalStage::new(mutator); + + // A fuzzer with just one stage + let mut fuzzer = StdFuzzer::new(tuple_list!(stage)); + + // A minimization+queue policy to get testcasess from the corpus + let scheduler = IndexesLenTimeMinimizerCorpusScheduler::new(QueueCorpusScheduler::new()); + + // The wrapped harness function, calling out to the LLVM-style harness + let mut harness = |buf: &[u8]| { + libfuzzer_test_one_input(buf); + ExitKind::Ok + }; + + // Create the executor for an in-process function with one observer for edge coverage and one for the execution time + let mut executor = TimeoutExecutor::new( + InProcessExecutor::new( + &mut harness, + tuple_list!( + edges_observer, + reachability_observer, + TimeObserver::new("time") + ), + &mut state, + &mut restarting_mgr, + )?, + // 10 seconds timeout + Duration::new(10, 0), + ); + + // The actual target run starts here. + // Call LLVMFUzzerInitialize() if present. + let args: Vec = env::args().collect(); + if libfuzzer_initialize(&args) == -1 { + println!("Warning: LLVMFuzzerInitialize failed with -1") + } + + // In case the corpus is empty (on first run), reset + if state.corpus().count() < 1 { + state + .load_initial_inputs(&mut executor, &mut restarting_mgr, &scheduler, &corpus_dirs) + .expect(&format!( + "Failed to load initial corpus at {:?}", + &corpus_dirs + )); + println!("We imported {} inputs from disk.", state.corpus().count()); + } + + // This fuzzer restarts after 1 mio `fuzz_one` executions. + // Each fuzz_one will internally do many executions of the target. + // If your target is very instable, setting a low count here may help. + // However, you will lose a lot of performance that way. + let iters = 1_000_000; + fuzzer.fuzz_loop_for( + &mut state, + &mut executor, + &mut restarting_mgr, + &scheduler, + iters, + )?; + + // It's important, that we store the state before restarting! + // Else, the parent will not respawn a new child and quit. + restarting_mgr.on_restart(&mut state)?; + + Ok(()) +} diff --git a/fuzzers/libfuzzer_reachability/test.sh b/fuzzers/libfuzzer_reachability/test.sh new file mode 100755 index 0000000000..7d3873dc68 --- /dev/null +++ b/fuzzers/libfuzzer_reachability/test.sh @@ -0,0 +1,10 @@ +cargo build --release +./target/release/libafl_cxx ./harness.cc libpng-1.6.37/.libs/libpng16.a -I libpng-1.6.37/ -o fuzzer_libpng -lz -lm + +taskset -c 0 ./fuzzer_libpng & +sleep 1 +taskset -c 1 ./fuzzer_libpng 2>/dev/null + + +killall ./fuzzer_libpng +rm -rf ./fuzzer_libpng diff --git a/libafl/src/feedbacks/map.rs b/libafl/src/feedbacks/map.rs index 340d8a9c87..cc76a6cf63 100644 --- a/libafl/src/feedbacks/map.rs +++ b/libafl/src/feedbacks/map.rs @@ -320,3 +320,82 @@ where } } } + +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct ReachabilityFeedback { + name: String, + target_idx: Vec, + phantom: PhantomData, +} + +impl ReachabilityFeedback +where + O: MapObserver, +{ + pub fn new_with_observer(map_observer: &O) -> Self { + Self { + name: map_observer.name().to_string(), + target_idx: vec![], + phantom: PhantomData, + } + } + pub fn new(name: &'static str) -> Self { + Self { + name: name.to_string(), + target_idx: vec![], + phantom: PhantomData, + } + } +} + +impl Feedback for ReachabilityFeedback +where + I: Input, + O: MapObserver, +{ + fn is_interesting( + &mut self, + _input: &I, + observers: &OT, + _exit_kind: &ExitKind, + ) -> Result { + let observer = observers.match_name_type::(&self.name).unwrap(); + let size = observer.usable_count(); + let mut hit_target: bool = false; + //check if we've hit any targets. + for i in 0..size { + if observer.map()[i] > 0 { + self.target_idx.push(i); + hit_target = true; + } + } + if hit_target { + Ok(true) + } else { + Ok(false) + } + } + + fn append_metadata(&mut self, testcase: &mut Testcase) -> Result<(), Error> { + if !self.target_idx.is_empty() { + let meta = MapIndexesMetadata::new(core::mem::take(self.target_idx.as_mut())); + testcase.add_metadata(meta); + }; + Ok(()) + } + + fn discard_metadata(&mut self, _input: &I) -> Result<(), Error> { + self.target_idx.clear(); + Ok(()) + } +} + +impl Named for ReachabilityFeedback +where + O: MapObserver, +{ + #[inline] + fn name(&self) -> &str { + self.name.as_str() + } +}