From 75f12bd0eb3ffffc67f8a12d3837b8b0ef369dd6 Mon Sep 17 00:00:00 2001 From: Dominik Maier Date: Sat, 24 Dec 2022 14:20:44 +0100 Subject: [PATCH] Remodelling Observers/Examples that rely on UB, API cleanups (#950) * Tackling UB * PtrMut -> MutPtr, moved mapobservers to non-UB * QEMU fixes * test fixes * qemu * Change all interfaces, fix all fuzzers * fixes * fix more fixes * fmt * fix qemu sugar * fix some qemus * atheris * fmt * more fmt * most fmt * more fix * nyx fyx * fix qemu * clippy, fixes * more fixes * no unfix, only fix * fix * fix * more clippy * fixes * ListObserver * fmt, clippy * fix qemu on arm * update zlib target * fix? * fix * added migration guide * ignore doc * fix symcc * fix new win fuzzer * Fixes, rename PTR_SIZE to PTR_NUM * Try fix linking on win * Trying to fix win linking * more cov * trying to fix win some more * trying to fix mac * trying to fix mac * Fix tests * Fix tests * trying to fix win * more mac * giving up for windows * fmt * python3 * mac? * undo windows tests --- .github/workflows/build_and_test.yml | 3 +- docs/src/advanced_features/frida.md | 6 +- docs/src/advanced_features/nyx.md | 7 +- docs/src/design/migration-0.9.md | 23 +++ fuzzers/baby_fuzzer/src/main.rs | 6 +- fuzzers/baby_fuzzer_gramatron/src/main.rs | 4 +- fuzzers/baby_fuzzer_grimoire/src/main.rs | 4 +- fuzzers/baby_fuzzer_minimizing/src/main.rs | 6 +- fuzzers/baby_fuzzer_nautilus/src/main.rs | 4 +- .../baby_fuzzer_swap_differential/build.rs | 6 +- .../src/bin/libafl_cc.rs | 2 +- .../baby_fuzzer_swap_differential/src/main.rs | 61 ++++--- fuzzers/baby_fuzzer_tokens/src/main.rs | 5 +- .../baby_fuzzer_with_forkexecutor/src/main.rs | 4 +- fuzzers/baby_no_std/src/main.rs | 2 +- .../c_code_with_fork_executor/src/main.rs | 4 +- .../src/main.rs | 4 +- .../command_executor/src/main.rs | 4 +- .../forkserver_executor/src/main.rs | 2 +- .../rust_code_with_fork_executor/src/main.rs | 4 +- .../src/main.rs | 4 +- fuzzers/forkserver_simple/src/main.rs | 5 +- fuzzers/frida_gdiplus/src/fuzzer.rs | 18 +-- fuzzers/frida_libpng/src/fuzzer.rs | 18 +-- fuzzers/fuzzbench/src/bin/libafl_cc.rs | 2 +- fuzzers/fuzzbench/src/bin/libafl_cxx.rs | 2 +- fuzzers/fuzzbench/src/lib.rs | 48 +++--- fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs | 22 ++- fuzzers/fuzzbench_fork_qemu/src/main.rs | 2 +- fuzzers/fuzzbench_forkserver/src/main.rs | 5 +- fuzzers/fuzzbench_qemu/src/fuzzer.rs | 25 +-- fuzzers/fuzzbench_text/src/bin/libafl_cc.rs | 2 +- fuzzers/fuzzbench_text/src/lib.rs | 25 ++- fuzzers/libafl_atheris/src/lib.rs | 17 +- .../libfuzzer_libmozjpeg/src/bin/libafl_cc.rs | 2 +- .../src/bin/libafl_cxx.rs | 2 +- fuzzers/libfuzzer_libmozjpeg/src/lib.rs | 11 +- fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs | 2 +- .../libfuzzer_libpng/src/bin/libafl_cxx.rs | 2 +- fuzzers/libfuzzer_libpng/src/lib.rs | 15 +- .../src/bin/libafl_cc.rs | 2 +- .../src/bin/libafl_cxx.rs | 2 +- .../libfuzzer_libpng_accounting/src/lib.rs | 9 +- .../src/bin/libafl_cxx.rs | 2 +- fuzzers/libfuzzer_libpng_cmin/src/lib.rs | 11 +- .../libfuzzer_libpng_ctx/src/bin/libafl_cc.rs | 2 +- .../src/bin/libafl_cxx.rs | 2 +- fuzzers/libfuzzer_libpng_ctx/src/lib.rs | 8 +- .../src/bin/libafl_cc.rs | 2 +- .../src/bin/libafl_cxx.rs | 2 +- fuzzers/libfuzzer_libpng_launcher/src/lib.rs | 7 +- .../src/bin/libafl_cc.rs | 2 +- .../src/bin/libafl_cxx.rs | 2 +- fuzzers/libfuzzer_reachability/src/lib.rs | 11 +- fuzzers/libfuzzer_stb_image/src/main.rs | 13 +- .../Makefile.toml | 2 +- .../fuzzer/src/main.rs | 15 +- fuzzers/libfuzzer_windows_asan/src/lib.rs | 15 +- .../nyx_libxml2_parallel/src/bin/libafl_cc.rs | 2 +- fuzzers/nyx_libxml2_parallel/src/main.rs | 13 +- .../src/bin/libafl_cc.rs | 2 +- fuzzers/nyx_libxml2_standalone/src/main.rs | 4 +- fuzzers/push_harness/src/main.rs | 5 +- fuzzers/push_stage_harness/src/main.rs | 4 +- fuzzers/qemu_arm_launcher/Makefile.toml | 24 +-- fuzzers/qemu_arm_launcher/src/fuzzer.rs | 18 ++- fuzzers/qemu_launcher/src/fuzzer.rs | 23 ++- fuzzers/qemu_systemmode/src/fuzzer.rs | 24 +-- fuzzers/tinyinst_simple/src/main.rs | 2 +- fuzzers/tutorial/src/bin/libafl_cc.rs | 2 +- fuzzers/tutorial/src/bin/libafl_cxx.rs | 2 +- fuzzers/tutorial/src/input.rs | 2 +- fuzzers/tutorial/src/lib.rs | 11 +- libafl/build.rs | 7 +- libafl/src/bolts/ownedref.rs | 152 +++++++++--------- libafl/src/corpus/testcase.rs | 8 +- libafl/src/events/mod.rs | 2 +- libafl/src/executors/differential.rs | 14 +- libafl/src/feedbacks/mod.rs | 3 +- libafl/src/fuzzer/mod.rs | 8 +- libafl/src/monitors/prometheus.rs | 6 +- libafl/src/mutators/token_mutations.rs | 5 +- libafl/src/observers/map.rs | 150 ++++++++++------- libafl/src/observers/mod.rs | 28 ++-- libafl/src/state/mod.rs | 8 +- libafl_frida/src/asan/errors.rs | 2 +- libafl_frida/src/coverage_rt.rs | 2 +- libafl_frida/src/helper.rs | 4 +- libafl_qemu/src/cmplog.rs | 4 +- libafl_qemu/src/edges.rs | 9 +- libafl_sugar/src/forkserver.rs | 2 +- libafl_sugar/src/inmemory.rs | 11 +- libafl_sugar/src/qemu.rs | 25 +-- libafl_targets/src/cmplog.rs | 31 ++-- libafl_targets/src/coverage.rs | 89 +++++++--- libafl_targets/src/sancov_pcguard.rs | 6 +- 96 files changed, 676 insertions(+), 537 deletions(-) diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 7d6e54d7b6..2834cc1868 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -174,8 +174,9 @@ jobs: - name: Add no_std toolchain run: rustup toolchain install nightly-x86_64-unknown-linux-gnu ; rustup component add rust-src --toolchain nightly-x86_64-unknown-linux-gnu - name: Install python + # Removing macOS things already installed in CI against failed linking if: runner.os == 'macOS' - run: brew install --force-bottle --overwrite python@3.11 + run: rm /usr/local/bin/2to3 /usr/local/bin/idle3 /usr/local/bin/pydoc3 /usr/local/bin/python3 /usr/local/bin/python3-config; brew install --force-bottle --overwrite python - uses: lyricwulf/abc@v1 with: # todo: remove afl++-clang when nyx support samcov_pcguard diff --git a/docs/src/advanced_features/frida.md b/docs/src/advanced_features/frida.md index 3bb472c20f..d7d9c2c230 100644 --- a/docs/src/advanced_features/frida.md +++ b/docs/src/advanced_features/frida.md @@ -53,12 +53,12 @@ Combined with any `Runtime` you'd like to use, you can initialize the `FridaInst ## Running the Fuzzer -After setting up the `FridaInstrumentationHelper`. You can obtain the pointer to the coverage map by calling `map_ptr_mut()`. +After setting up the `FridaInstrumentationHelper`. You can obtain the pointer to the coverage map by calling `map_mut_ptr()`. ```rust,ignore - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( + let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr( "edges", - frida_helper.map_ptr_mut().unwrap(), + frida_helper.map_mut_ptr().unwrap(), MAP_SIZE, )); ``` diff --git a/docs/src/advanced_features/nyx.md b/docs/src/advanced_features/nyx.md index 2bf4e38af5..d1d859a485 100644 --- a/docs/src/advanced_features/nyx.md +++ b/docs/src/advanced_features/nyx.md @@ -63,8 +63,7 @@ let mut helper = NyxHelper::new(share_dir, cpu_id, true, parallel_mode, None).un Then, fetch `trace_bits`, create an observer and the `NyxExecutor`: ```rust,ignore -let trace_bits = unsafe { std::slice::from_raw_parts_mut(helper.trace_bits, helper.map_size) }; -let observer = StdMapObserver::new("trace", trace_bits); +let observer = unsafe { StdMapObserver::from_mut_ptr("trace", helper.trace_bits, helper.map_size) }; let mut executor = NyxExecutor::new(&mut helper, tuple_list!(observer)).unwrap(); ``` @@ -99,9 +98,7 @@ let mut helper = NyxHelper::new( Then you can fetch the trace_bits and create an observer and `NyxExecutor` ```rust,ignore -let trace_bits = - unsafe { std::slice::from_raw_parts_mut(helper.trace_bits, helper.map_size) }; -let observer = StdMapObserver::new("trace", trace_bits); +let observer = unsafe { StdMapObserver::from_mut_ptr("trace", helper.trace_bits, helper.map_size) } let mut executor = NyxExecutor::new(&mut helper, tuple_list!(observer)).unwrap(); ``` diff --git a/docs/src/design/migration-0.9.md b/docs/src/design/migration-0.9.md index b6b62b3f5c..0e73994363 100644 --- a/docs/src/design/migration-0.9.md +++ b/docs/src/design/migration-0.9.md @@ -160,3 +160,26 @@ Now, `Corpus` cannot be accidentally implemented for another type other than tha is fixed to the associated type for `UsesInput`. A more complex example of migration can be found in the "Reasons for this change" section of this document. + +## Observer Changes + +Additionally, we changed the observers API, as the API in 0.8 led to undefined behavior. +At the same time, we used the change to simplify the common case: creating an `StdMapObserver` +from libafl_target's `EDGES_MAP`. +In the future, instead of using: + +```rust,ignore +let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; +let edges_observer = StdMapObserver::new("edges", edges); +``` + +creating the edges observer is as simple as using the new `std_edges_map_observer` function. + +```rust,ignore +let edges_observer = unsafe { std_edges_map_observer("edges") }; +``` + +Alternatively, `StdMapObserver::new` will still work, but now the whole method is marked as `unsafe`. +The reason is that the caller has to make sure `EDGES_MAP` (or other maps) are not moved or freed in memory, +for the lifetime of the lifetime of the `MapObserver`. +This means that the buffer should either be `static` or `Pin`. diff --git a/fuzzers/baby_fuzzer/src/main.rs b/fuzzers/baby_fuzzer/src/main.rs index e600afcfb7..da08be3f35 100644 --- a/fuzzers/baby_fuzzer/src/main.rs +++ b/fuzzers/baby_fuzzer/src/main.rs @@ -30,7 +30,7 @@ fn signals_set(idx: usize) { unsafe { SIGNALS[idx] = 1 }; } -#[allow(clippy::similar_names)] +#[allow(clippy::similar_names, clippy::manual_assert)] pub fn main() { // The closure that we want to fuzz let mut harness = |input: &BytesInput| { @@ -61,7 +61,7 @@ pub fn main() { // Create an observation channel using the signals map let observer = - unsafe { StdMapObserver::new_from_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) }; + unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new(&observer); @@ -88,7 +88,7 @@ pub fn main() { // The Monitor trait define how the fuzzer stats are displayed to the user #[cfg(not(feature = "tui"))] - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); #[cfg(feature = "tui")] let mon = TuiMonitor::new(String::from("Baby Fuzzer"), false); diff --git a/fuzzers/baby_fuzzer_gramatron/src/main.rs b/fuzzers/baby_fuzzer_gramatron/src/main.rs index b1f3f2a7e9..f37bf34402 100644 --- a/fuzzers/baby_fuzzer_gramatron/src/main.rs +++ b/fuzzers/baby_fuzzer_gramatron/src/main.rs @@ -57,7 +57,7 @@ pub fn main() { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); + let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new(&observer); @@ -83,7 +83,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are reported to the user - let monitor = SimpleMonitor::new(|s| println!("{}", s)); + let monitor = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/baby_fuzzer_grimoire/src/main.rs b/fuzzers/baby_fuzzer_grimoire/src/main.rs index c28c3f6641..e275c96c5f 100644 --- a/fuzzers/baby_fuzzer_grimoire/src/main.rs +++ b/fuzzers/baby_fuzzer_grimoire/src/main.rs @@ -88,7 +88,7 @@ pub fn main() { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); + let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new_tracking(&observer, false, true); @@ -118,7 +118,7 @@ pub fn main() { } // The Monitor trait define how the fuzzer stats are reported to the user - let monitor = SimpleMonitor::new(|s| println!("{}", s)); + let monitor = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/baby_fuzzer_minimizing/src/main.rs b/fuzzers/baby_fuzzer_minimizing/src/main.rs index 61430cc6c2..c909e3e34b 100644 --- a/fuzzers/baby_fuzzer_minimizing/src/main.rs +++ b/fuzzers/baby_fuzzer_minimizing/src/main.rs @@ -33,7 +33,7 @@ pub fn main() -> Result<(), Error> { // Create an observation channel using the signals map let observer = - unsafe { StdMapObserver::new_from_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) }; + unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) }; let factory = MapEqualityFactory::new_from_observer(&observer); @@ -44,7 +44,7 @@ pub fn main() -> Result<(), Error> { let mut objective = CrashFeedback::new(); // The Monitor trait define how the fuzzer stats are displayed to the user - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); let mut mgr = SimpleEventManager::new(mon); @@ -116,7 +116,7 @@ pub fn main() -> Result<(), Error> { .unwrap(); // The Monitor trait define how the fuzzer stats are displayed to the user - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); let mut mgr = SimpleEventManager::new(mon); diff --git a/fuzzers/baby_fuzzer_nautilus/src/main.rs b/fuzzers/baby_fuzzer_nautilus/src/main.rs index 078451d8b1..54356830d0 100644 --- a/fuzzers/baby_fuzzer_nautilus/src/main.rs +++ b/fuzzers/baby_fuzzer_nautilus/src/main.rs @@ -46,7 +46,7 @@ pub fn main() { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); + let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) }; // Feedback to rate the interestingness of an input let mut feedback = feedback_or!( @@ -79,7 +79,7 @@ pub fn main() { } // The Monitor trait define how the fuzzer stats are reported to the user - let monitor = SimpleMonitor::new(|s| println!("{}", s)); + let monitor = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/baby_fuzzer_swap_differential/build.rs b/fuzzers/baby_fuzzer_swap_differential/build.rs index 8a216dc438..22c22830c7 100644 --- a/fuzzers/baby_fuzzer_swap_differential/build.rs +++ b/fuzzers/baby_fuzzer_swap_differential/build.rs @@ -27,9 +27,7 @@ fn main() -> anyhow::Result<()> { }) .join("release/libafl_cc"); println!("cargo:rerun-if-changed={}", compiler.to_str().unwrap()); - if !compiler.try_exists().unwrap_or(false) { - println!("cargo:warning=Can't find libafl_cc; assuming that we're building it."); - } else { + if compiler.try_exists().unwrap_or(false) { cc::Build::new() .compiler(compiler) .file("first.c") @@ -38,6 +36,8 @@ fn main() -> anyhow::Result<()> { .compile("diff-target"); println!("cargo:rustc-link-lib=diff-target"); + } else { + println!("cargo:warning=Can't find libafl_cc; assuming that we're building it."); } } diff --git a/fuzzers/baby_fuzzer_swap_differential/src/bin/libafl_cc.rs b/fuzzers/baby_fuzzer_swap_differential/src/bin/libafl_cc.rs index a4b4c980b2..4a6519f571 100644 --- a/fuzzers/baby_fuzzer_swap_differential/src/bin/libafl_cc.rs +++ b/fuzzers/baby_fuzzer_swap_differential/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/baby_fuzzer_swap_differential/src/main.rs b/fuzzers/baby_fuzzer_swap_differential/src/main.rs index 46ca57a743..07b4413ddb 100644 --- a/fuzzers/baby_fuzzer_swap_differential/src/main.rs +++ b/fuzzers/baby_fuzzer_swap_differential/src/main.rs @@ -32,10 +32,11 @@ static GLOBAL: MiMalloc = MiMalloc; // bindings to the functions defined in the target mod bindings { + #![allow(non_snake_case)] #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] #![allow(unused)] - + #![allow(clippy::unreadable_literal)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } @@ -45,23 +46,26 @@ use bindings::{inspect_first, inspect_second}; mod multimap { pub use libafl::observers::{HitcountsIterableMapObserver, MultiMapObserver}; - pub static mut FIRST_EDGES: &'static mut [u8] = &mut []; - pub static mut SECOND_EDGES: &'static mut [u8] = &mut []; - pub static mut COMBINED_EDGES: [&'static mut [u8]; 2] = [&mut [], &mut []]; + pub static mut FIRST_EDGES: &mut [u8] = &mut []; + pub static mut SECOND_EDGES: &mut [u8] = &mut []; + pub static mut COMBINED_EDGES: [&mut [u8]; 2] = [&mut [], &mut []]; } #[cfg(feature = "multimap")] -use multimap::*; +use multimap::{ + HitcountsIterableMapObserver, MultiMapObserver, COMBINED_EDGES, FIRST_EDGES, SECOND_EDGES, +}; #[cfg(not(feature = "multimap"))] mod slicemap { pub use libafl::observers::HitcountsMapObserver; - pub static mut EDGES: &'static mut [u8] = &mut []; + pub static mut EDGES: &mut [u8] = &mut []; } #[cfg(not(feature = "multimap"))] -use slicemap::*; +use slicemap::{HitcountsMapObserver, EDGES}; #[allow(clippy::similar_names)] +#[allow(clippy::too_many_lines)] pub fn main() { // The closure that we want to fuzz let mut first_harness = |input: &BytesInput| { @@ -94,8 +98,8 @@ pub fn main() { } // create the base maps used to observe the different executors from two independent maps - let mut first_map_observer = StdMapObserver::new("first-edges", unsafe { FIRST_EDGES }); - let mut second_map_observer = StdMapObserver::new("second-edges", unsafe { SECOND_EDGES }); + let mut first_map_observer = unsafe { StdMapObserver::new("first-edges", FIRST_EDGES) }; + let mut second_map_observer = unsafe { StdMapObserver::new("second-edges", SECOND_EDGES) }; // create a map swapper so that we can replace the coverage map pointer (requires feature pointer_maps!) let map_swapper = @@ -104,10 +108,13 @@ pub fn main() { // create a combined map observer, e.g. for calibration // we use MultiMapObserver::differential to indicate that we want to use the observer in // differential mode - let map_observer = HitcountsIterableMapObserver::new(MultiMapObserver::differential( - "combined-edges", - unsafe { &mut COMBINED_EDGES }, - )); + let map_observer = unsafe { + HitcountsIterableMapObserver::new(MultiMapObserver::differential( + "combined-edges", + &mut COMBINED_EDGES, + )) + }; + ( first_map_observer, second_map_observer, @@ -124,10 +131,16 @@ pub fn main() { } // create the base maps used to observe the different executors by splitting a slice - let mut first_map_observer = - StdMapObserver::new("first-edges", unsafe { &mut EDGES[..MAX_EDGES_NUM] }); - let mut second_map_observer = - StdMapObserver::new("second-edges", unsafe { &mut EDGES[MAX_EDGES_NUM..] }); + let mut first_map_observer = unsafe { + StdMapObserver::from_mut_ptr("first-edges", EDGES.as_mut_ptr(), MAX_EDGES_NUM) + }; + let mut second_map_observer = unsafe { + StdMapObserver::from_mut_ptr( + "second-edges", + EDGES.as_mut_ptr().add(MAX_EDGES_NUM), + MAX_EDGES_NUM, + ) + }; // create a map swapper so that we can replace the coverage map pointer (requires feature pointer_maps!) let map_swapper = @@ -136,10 +149,14 @@ pub fn main() { // create a combined map observer, e.g. for calibration // we use StdMapObserver::differential to indicate that we want to use the observer in // differential mode - let map_observer = - HitcountsMapObserver::new(StdMapObserver::differential("combined-edges", unsafe { - EDGES - })); + let map_observer = unsafe { + HitcountsMapObserver::new(StdMapObserver::differential_from_mut_ptr( + "combined-edges", + EDGES.as_mut_ptr(), + MAX_EDGES_NUM * 2, + )) + }; + ( first_map_observer, second_map_observer, @@ -174,7 +191,7 @@ pub fn main() { // The Monitor trait define how the fuzzer stats are displayed to the user #[cfg(not(feature = "tui"))] - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); #[cfg(feature = "tui")] let mon = TuiMonitor::new(String::from("Baby Fuzzer"), false); diff --git a/fuzzers/baby_fuzzer_tokens/src/main.rs b/fuzzers/baby_fuzzer_tokens/src/main.rs index 2f8beea6e6..d22e5afecd 100644 --- a/fuzzers/baby_fuzzer_tokens/src/main.rs +++ b/fuzzers/baby_fuzzer_tokens/src/main.rs @@ -65,7 +65,8 @@ pub fn main() { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); + let observer = + unsafe { StdMapObserver::from_mut_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new(&observer); @@ -91,7 +92,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are reported to the user - let monitor = SimpleMonitor::new(|s| println!("{}", s)); + let monitor = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/baby_fuzzer_with_forkexecutor/src/main.rs b/fuzzers/baby_fuzzer_with_forkexecutor/src/main.rs index 396a7d210a..4c9647f183 100644 --- a/fuzzers/baby_fuzzer_with_forkexecutor/src/main.rs +++ b/fuzzers/baby_fuzzer_with_forkexecutor/src/main.rs @@ -64,7 +64,7 @@ pub fn main() { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", signals_clone.as_mut_slice()); + let observer = unsafe { StdMapObserver::new("signals", signals_clone.as_mut_slice()) }; // Create a stacktrace observer to add the observers tuple // Feedback to rate the interestingness of an input, obtained by ANDing the interestingness of both feedbacks @@ -91,7 +91,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are displayed to the user - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/baby_no_std/src/main.rs b/fuzzers/baby_no_std/src/main.rs index d570351516..015bba405f 100644 --- a/fuzzers/baby_no_std/src/main.rs +++ b/fuzzers/baby_no_std/src/main.rs @@ -87,7 +87,7 @@ pub extern "C" fn main(_argc: isize, _argv: *const *const u8) -> isize { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); + let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new(&observer); diff --git a/fuzzers/backtrace_baby_fuzzers/c_code_with_fork_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/c_code_with_fork_executor/src/main.rs index 2b05f58019..22b1216b7a 100644 --- a/fuzzers/backtrace_baby_fuzzers/c_code_with_fork_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/c_code_with_fork_executor/src/main.rs @@ -45,7 +45,7 @@ pub fn main() { libafl::executors::ExitKind::Ok }; // Create an observation channel using the signals map - let observer = unsafe { ConstMapObserver::::new_from_ptr("signals", map_ptr) }; + let observer = unsafe { ConstMapObserver::::from_mut_ptr("signals", map_ptr) }; // Create a stacktrace observer let mut bt = shmem_provider.new_shmem_object::>().unwrap(); let bt_observer = BacktraceObserver::new( @@ -78,7 +78,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are displayed to the user - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/backtrace_baby_fuzzers/c_code_with_inprocess_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/c_code_with_inprocess_executor/src/main.rs index 97b5eca4cb..5521e6a19d 100644 --- a/fuzzers/backtrace_baby_fuzzers/c_code_with_inprocess_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/c_code_with_inprocess_executor/src/main.rs @@ -35,7 +35,7 @@ pub fn main() { libafl::executors::ExitKind::Ok }; // Create an observation channel using the signals map - let observer = unsafe { ConstMapObserver::::new_from_ptr("signals", array_ptr) }; + let observer = unsafe { ConstMapObserver::::from_mut_ptr("signals", array_ptr) }; // Create a stacktrace observer let mut bt = None; let bt_observer = BacktraceObserver::new( @@ -68,7 +68,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are displayed to the user - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/backtrace_baby_fuzzers/command_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/command_executor/src/main.rs index a741e53b4a..6f8c4fdbed 100644 --- a/fuzzers/backtrace_baby_fuzzers/command_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/command_executor/src/main.rs @@ -38,7 +38,7 @@ pub fn main() { let shmem_id = signals.id(); // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", signals.as_mut_slice()); + let observer = unsafe { StdMapObserver::new("signals", signals.as_mut_slice()) }; // Create a stacktrace observer let bt_observer = AsanBacktraceObserver::new("AsanBacktraceObserver"); @@ -67,7 +67,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are displayed to the user - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/backtrace_baby_fuzzers/forkserver_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/forkserver_executor/src/main.rs index bc5392c559..cdf9847e9e 100644 --- a/fuzzers/backtrace_baby_fuzzers/forkserver_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/forkserver_executor/src/main.rs @@ -78,7 +78,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are reported to the user - let monitor = SimpleMonitor::new(|s| println!("{}", s)); + let monitor = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/backtrace_baby_fuzzers/rust_code_with_fork_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/rust_code_with_fork_executor/src/main.rs index 1391aa84ed..786472b8e1 100644 --- a/fuzzers/backtrace_baby_fuzzers/rust_code_with_fork_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/rust_code_with_fork_executor/src/main.rs @@ -65,7 +65,7 @@ pub fn main() { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", signals_clone.as_mut_slice()); + let observer = unsafe { StdMapObserver::new("signals", signals_clone.as_mut_slice()) }; // Create a stacktrace observer let bt_observer = BacktraceObserver::new( "BacktraceObserver", @@ -97,7 +97,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are displayed to the user - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/backtrace_baby_fuzzers/rust_code_with_inprocess_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/rust_code_with_inprocess_executor/src/main.rs index c9982b497f..1f35338c05 100644 --- a/fuzzers/backtrace_baby_fuzzers/rust_code_with_inprocess_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/rust_code_with_inprocess_executor/src/main.rs @@ -58,7 +58,7 @@ pub fn main() { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); + let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) }; // Create a stacktrace observer to add the observers tuple let mut bt = None; let bt_observer = BacktraceObserver::new( @@ -91,7 +91,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are displayed to the user - let mon = SimpleMonitor::new(|s| println!("{}", s)); + let mon = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/forkserver_simple/src/main.rs b/fuzzers/forkserver_simple/src/main.rs index 4d4b0ee501..3f12a3eb90 100644 --- a/fuzzers/forkserver_simple/src/main.rs +++ b/fuzzers/forkserver_simple/src/main.rs @@ -103,7 +103,8 @@ pub fn main() { let shmem_buf = shmem.as_mut_slice(); // Create an observation channel using the signals map - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)); + let edges_observer = + unsafe { HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)) }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); @@ -144,7 +145,7 @@ pub fn main() { .unwrap(); // The Monitor trait define how the fuzzer stats are reported to the user - let monitor = SimpleMonitor::new(|s| println!("{}", s)); + let monitor = SimpleMonitor::new(|s| println!("{s}")); // The event manager handle the various events generated during the fuzzing loop // such as the notification of the addition of a new item to the corpus diff --git a/fuzzers/frida_gdiplus/src/fuzzer.rs b/fuzzers/frida_gdiplus/src/fuzzer.rs index d9625006cc..2ba443cce5 100644 --- a/fuzzers/frida_gdiplus/src/fuzzer.rs +++ b/fuzzers/frida_gdiplus/src/fuzzer.rs @@ -51,7 +51,7 @@ use libafl_frida::{ executor::FridaInProcessExecutor, helper::FridaInstrumentationHelper, }; -use libafl_targets::cmplog::{CmpLogObserver, CMPLOG_MAP}; +use libafl_targets::cmplog::CmpLogObserver; /// The main fn, usually parsing parameters, and starting the fuzzer pub fn main() { @@ -71,7 +71,7 @@ pub fn main() { #[allow(clippy::too_many_lines, clippy::too_many_arguments)] unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { // 'While the stats are state, they are usually used in the broker - which is likely never restarted - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); let shmem_provider = StdShMemProvider::new()?; @@ -108,9 +108,9 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage)); // Create an observation channel using the coverage map - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( + let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr( "edges", - frida_helper.map_ptr_mut().unwrap(), + frida_helper.map_mut_ptr().unwrap(), MAP_SIZE, )); @@ -228,9 +228,9 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage, cmplog)); // Create an observation channel using the coverage map - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( + let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr( "edges", - frida_helper.map_ptr_mut().unwrap(), + frida_helper.map_mut_ptr().unwrap(), MAP_SIZE, )); @@ -330,7 +330,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { } // Create an observation channel using cmplog map - let cmplog_observer = CmpLogObserver::new("cmplog", &mut CMPLOG_MAP, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); let mut executor = ShadowExecutor::new(executor, tuple_list!(cmplog_observer)); @@ -361,9 +361,9 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage)); // Create an observation channel using the coverage map - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( + let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr( "edges", - frida_helper.map_ptr_mut().unwrap(), + frida_helper.map_mut_ptr().unwrap(), MAP_SIZE, )); diff --git a/fuzzers/frida_libpng/src/fuzzer.rs b/fuzzers/frida_libpng/src/fuzzer.rs index f4ca848435..67f0546107 100644 --- a/fuzzers/frida_libpng/src/fuzzer.rs +++ b/fuzzers/frida_libpng/src/fuzzer.rs @@ -45,7 +45,7 @@ use libafl_frida::{ executor::FridaInProcessExecutor, helper::FridaInstrumentationHelper, }; -use libafl_targets::cmplog::{CmpLogObserver, CMPLOG_MAP}; +use libafl_targets::cmplog::CmpLogObserver; /// The main fn, usually parsing parameters, and starting the fuzzer pub fn main() { @@ -65,7 +65,7 @@ pub fn main() { #[allow(clippy::too_many_lines, clippy::too_many_arguments)] unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { // 'While the stats are state, they are usually used in the broker - which is likely never restarted - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); let shmem_provider = StdShMemProvider::new()?; @@ -102,9 +102,9 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage)); // Create an observation channel using the coverage map - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( + let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr( "edges", - frida_helper.map_ptr_mut().unwrap(), + frida_helper.map_mut_ptr().unwrap(), MAP_SIZE, )); @@ -222,9 +222,9 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage, cmplog)); // Create an observation channel using the coverage map - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( + let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr( "edges", - frida_helper.map_ptr_mut().unwrap(), + frida_helper.map_mut_ptr().unwrap(), MAP_SIZE, )); @@ -324,7 +324,7 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { } // Create an observation channel using cmplog map - let cmplog_observer = CmpLogObserver::new("cmplog", &mut CMPLOG_MAP, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); let mut executor = ShadowExecutor::new(executor, tuple_list!(cmplog_observer)); @@ -355,9 +355,9 @@ unsafe fn fuzz(options: FuzzerOptions) -> Result<(), Error> { FridaInstrumentationHelper::new(&gum, &options, tuple_list!(coverage)); // Create an observation channel using the coverage map - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new_from_ptr( + let edges_observer = HitcountsMapObserver::new(StdMapObserver::from_mut_ptr( "edges", - frida_helper.map_ptr_mut().unwrap(), + frida_helper.map_mut_ptr().unwrap(), MAP_SIZE, )); diff --git a/fuzzers/fuzzbench/src/bin/libafl_cc.rs b/fuzzers/fuzzbench/src/bin/libafl_cc.rs index 9d4fc05945..f0e5b7fd8d 100644 --- a/fuzzers/fuzzbench/src/bin/libafl_cc.rs +++ b/fuzzers/fuzzbench/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/fuzzbench/src/bin/libafl_cxx.rs b/fuzzers/fuzzbench/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/fuzzbench/src/bin/libafl_cxx.rs +++ b/fuzzers/fuzzbench/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/fuzzbench/src/lib.rs b/fuzzers/fuzzbench/src/lib.rs index 673758aeb9..ec2ede6775 100644 --- a/fuzzers/fuzzbench/src/lib.rs +++ b/fuzzers/fuzzbench/src/lib.rs @@ -36,7 +36,7 @@ use libafl::{ scheduled::havoc_mutations, token_mutations::I2SRandReplace, tokens_mutations, StdMOptMutator, StdScheduledMutator, Tokens, }, - observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, + observers::{HitcountsMapObserver, TimeObserver}, schedulers::{ powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler, }, @@ -50,8 +50,7 @@ use libafl::{ #[cfg(any(target_os = "linux", target_vendor = "apple"))] use libafl_targets::autotokens; use libafl_targets::{ - libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, - MAX_EDGES_NUM, + libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer, CmpLogObserver, }; #[cfg(unix)] use nix::{self, unistd::dup}; @@ -121,7 +120,7 @@ pub fn libafl_main() { ); if let Some(filenames) = res.get_many::("remaining") { - let filenames: Vec<&str> = filenames.map(|v| v.as_str()).collect(); + let filenames: Vec<&str> = filenames.map(String::as_str).collect(); if !filenames.is_empty() { run_testcases(&filenames); return; @@ -167,7 +166,7 @@ pub fn libafl_main() { .expect("Could not parse timeout in milliseconds"), ); - fuzz(out_dir, crashes, in_dir, tokens, logfile, timeout) + fuzz(out_dir, crashes, &in_dir, tokens, &logfile, timeout) .expect("An error occurred while fuzzing"); } @@ -176,7 +175,7 @@ fn run_testcases(filenames: &[&str]) { // Call LLVMFUzzerInitialize() if present. let args: Vec = env::args().collect(); if libfuzzer_initialize(&args) == -1 { - println!("Warning: LLVMFuzzerInitialize failed with -1") + println!("Warning: LLVMFuzzerInitialize failed with -1"); } println!( @@ -184,7 +183,7 @@ fn run_testcases(filenames: &[&str]) { filenames.len() ); for fname in filenames { - println!("Executing {}", fname); + println!("Executing {fname}"); let mut file = File::open(fname).expect("No file found"); let mut buffer = vec![]; @@ -195,20 +194,16 @@ fn run_testcases(filenames: &[&str]) { } /// The actual fuzzer +#[allow(clippy::too_many_lines)] fn fuzz( corpus_dir: PathBuf, objective_dir: PathBuf, - seed_dir: PathBuf, + seed_dir: &PathBuf, tokenfile: Option, - logfile: PathBuf, + logfile: &PathBuf, timeout: Duration, ) -> Result<(), Error> { - let log = RefCell::new( - OpenOptions::new() - .append(true) - .create(true) - .open(&logfile)?, - ); + let log = RefCell::new(OpenOptions::new().append(true).create(true).open(logfile)?); #[cfg(unix)] let mut stdout_cpy = unsafe { @@ -221,10 +216,10 @@ fn fuzz( // 'While the monitor are state, they are usually used in the broker - which is likely never restarted let monitor = SimpleMonitor::new(|s| { #[cfg(unix)] - writeln!(&mut stdout_cpy, "{}", s).unwrap(); + writeln!(&mut stdout_cpy, "{s}").unwrap(); #[cfg(windows)] - println!("{}", s); - writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); + println!("{s}"); + writeln!(log.borrow_mut(), "{:?} {s}", current_time()).unwrap(); }); // We need a shared map to store our state before a crash. @@ -240,21 +235,19 @@ fn fuzz( return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map // We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges) - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") }); // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); - let cmplog = unsafe { &mut CMPLOG_MAP }; - let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false); @@ -297,7 +290,7 @@ fn fuzz( // Call LLVMFUzzerInitialize() if present. let args: Vec = env::args().collect(); if libfuzzer_initialize(&args) == -1 { - println!("Warning: LLVMFuzzerInitialize failed with -1") + println!("Warning: LLVMFuzzerInitialize failed with -1"); } // Setup a randomic Input2State stage @@ -394,12 +387,7 @@ fn fuzz( dup2(null_fd, io::stderr().as_raw_fd())?; } // reopen file to make sure we're at the end - log.replace( - OpenOptions::new() - .append(true) - .create(true) - .open(&logfile)?, - ); + log.replace(OpenOptions::new().append(true).create(true).open(logfile)?); fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)?; diff --git a/fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs b/fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs index aedcb93707..74ba09d992 100644 --- a/fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs +++ b/fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs @@ -45,7 +45,7 @@ use libafl::{ Error, }; use libafl_qemu::{ - cmplog::{CmpLogMap, CmpLogObserver, QemuCmpLogChildHelper, CMPLOG_MAP_PTR}, + cmplog::{CmpLogMap, CmpLogObserver, QemuCmpLogChildHelper}, edges::{QemuEdgeCoverageChildHelper, EDGES_MAP_PTR, EDGES_MAP_SIZE}, elf::EasyElf, emu::Emulator, @@ -199,7 +199,7 @@ fn fuzz( #[cfg(unix)] writeln!(&mut stdout_cpy, "{}", s).unwrap(); #[cfg(windows)] - println!("{}", s); + println!("{s}"); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); }); @@ -213,7 +213,10 @@ fn fuzz( .new_shmem(core::mem::size_of::()) .unwrap(); let cmplog = cmp_shmem.as_mut_slice(); - unsafe { CMPLOG_MAP_PTR = cmplog.as_mut_ptr() as *mut CmpLogMap }; + + // Beginning of a page should be properly aligned. + #[allow(clippy::cast_ptr_alignment)] + let cmplog_map_ptr = cmplog.as_mut_ptr().cast::(); let (state, mut mgr) = match SimpleRestartingEventManager::launch(monitor, &mut shmem_provider) { @@ -224,21 +227,24 @@ fn fuzz( return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map - let edges_observer = - HitcountsMapObserver::new(ConstMapObserver::<_, EDGES_MAP_SIZE>::new("edges", edges)); + let edges_observer = unsafe { + HitcountsMapObserver::new(ConstMapObserver::<_, EDGES_MAP_SIZE>::from_mut_ptr( + "edges", + edges.as_mut_ptr(), + )) + }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); // Create an observation channel using cmplog map - let cmplog_observer = - CmpLogObserver::new("cmplog", unsafe { CMPLOG_MAP_PTR.as_mut().unwrap() }, true); + let cmplog_observer = unsafe { CmpLogObserver::with_map_ptr("cmplog", cmplog_map_ptr, true) }; let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false); diff --git a/fuzzers/fuzzbench_fork_qemu/src/main.rs b/fuzzers/fuzzbench_fork_qemu/src/main.rs index 6f78885bcc..cb0dc9cf3e 100644 --- a/fuzzers/fuzzbench_fork_qemu/src/main.rs +++ b/fuzzers/fuzzbench_fork_qemu/src/main.rs @@ -3,5 +3,5 @@ pub mod fuzzer; fn main() { #[cfg(target_os = "linux")] - fuzzer::main() + fuzzer::main(); } diff --git a/fuzzers/fuzzbench_forkserver/src/main.rs b/fuzzers/fuzzbench_forkserver/src/main.rs index 2ebd9d2ff9..5cecbd51c1 100644 --- a/fuzzers/fuzzbench_forkserver/src/main.rs +++ b/fuzzers/fuzzbench_forkserver/src/main.rs @@ -225,7 +225,7 @@ fn fuzz( // 'While the monitor are state, they are usually used in the broker - which is likely never restarted let monitor = SimpleMonitor::new(|s| { - println!("{}", s); + println!("{s}"); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); }); @@ -243,7 +243,8 @@ fn fuzz( let shmem_buf = shmem.as_mut_slice(); // Create an observation channel using the hitcounts map of AFL++ - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)); + let edges_observer = + unsafe { HitcountsMapObserver::new(StdMapObserver::new("shared_mem", shmem_buf)) }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); diff --git a/fuzzers/fuzzbench_qemu/src/fuzzer.rs b/fuzzers/fuzzbench_qemu/src/fuzzer.rs index 6882240286..f1c51636b6 100644 --- a/fuzzers/fuzzbench_qemu/src/fuzzer.rs +++ b/fuzzers/fuzzbench_qemu/src/fuzzer.rs @@ -1,6 +1,6 @@ //! A singlethreaded QEMU fuzzer that can auto-restart. -use core::{cell::RefCell, time::Duration}; +use core::{cell::RefCell, ptr::addr_of_mut, time::Duration}; #[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd}; use std::{ @@ -45,11 +45,11 @@ use libafl::{ Error, }; use libafl_qemu::{ - //asan::{init_with_asan, QemuAsanHelper}, - cmplog, cmplog::{CmpLogObserver, QemuCmpLogHelper}, - edges, + //asan::{init_with_asan, QemuAsanHelper}, + edges::edges_map_mut_slice, edges::QemuEdgeCoverageHelper, + edges::MAX_EDGES_NUM, elf::EasyElf, emu::Emulator, filter_qemu_args, @@ -226,7 +226,7 @@ fn fuzz( #[cfg(unix)] writeln!(&mut stdout_cpy, "{}", s).unwrap(); #[cfg(windows)] - println!("{}", s); + println!("{s}"); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); }); @@ -241,22 +241,25 @@ fn fuzz( return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map - let edges = unsafe { &mut edges::EDGES_MAP }; - let edges_counter = unsafe { &mut edges::MAX_EDGES_NUM }; - let edges_observer = - HitcountsMapObserver::new(VariableMapObserver::new("edges", edges, edges_counter)); + let edges_observer = unsafe { + HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( + "edges", + edges_map_mut_slice(), + addr_of_mut!(MAX_EDGES_NUM), + )) + }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); // Create an observation channel using cmplog map - let cmplog_observer = CmpLogObserver::new("cmplog", unsafe { &mut cmplog::CMPLOG_MAP }, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false); diff --git a/fuzzers/fuzzbench_text/src/bin/libafl_cc.rs b/fuzzers/fuzzbench_text/src/bin/libafl_cc.rs index 1a361ebe5d..ca1bd02825 100644 --- a/fuzzers/fuzzbench_text/src/bin/libafl_cc.rs +++ b/fuzzers/fuzzbench_text/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/fuzzbench_text/src/lib.rs b/fuzzers/fuzzbench_text/src/lib.rs index 8df1e7e8f3..a1436cc8ba 100644 --- a/fuzzers/fuzzbench_text/src/lib.rs +++ b/fuzzers/fuzzbench_text/src/lib.rs @@ -42,7 +42,7 @@ use libafl::{ token_mutations::I2SRandReplace, tokens_mutations, StdMOptMutator, StdScheduledMutator, Tokens, }, - observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, + observers::{HitcountsMapObserver, TimeObserver}, schedulers::{ powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler, }, @@ -56,8 +56,7 @@ use libafl::{ #[cfg(any(target_os = "linux", target_vendor = "apple"))] use libafl_targets::autotokens; use libafl_targets::{ - libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, - MAX_EDGES_NUM, + libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer, CmpLogObserver, }; #[cfg(unix)] use nix::{self, unistd::dup}; @@ -286,7 +285,7 @@ fn fuzz_binary( #[cfg(unix)] writeln!(&mut stdout_cpy, "{}", s).unwrap(); #[cfg(windows)] - println!("{}", s); + println!("{s}"); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); }); @@ -303,21 +302,19 @@ fn fuzz_binary( return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map // We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges) - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") }); // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); - let cmplog = unsafe { &mut CMPLOG_MAP }; - let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, false); @@ -490,7 +487,7 @@ fn fuzz_text( #[cfg(unix)] writeln!(&mut stdout_cpy, "{}", s).unwrap(); #[cfg(windows)] - println!("{}", s); + println!("{s}"); writeln!(log.borrow_mut(), "{:?} {}", current_time(), s).unwrap(); }); @@ -507,21 +504,19 @@ fn fuzz_text( return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map // We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges) - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") }); // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); - let cmplog = unsafe { &mut CMPLOG_MAP }; - let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); // New maximization map feedback linked to the edges observer and the feedback state let map_feedback = MaxMapFeedback::new_tracking(&edges_observer, true, true); diff --git a/fuzzers/libafl_atheris/src/lib.rs b/fuzzers/libafl_atheris/src/lib.rs index e8c6b216c1..7fc9f2b444 100644 --- a/fuzzers/libafl_atheris/src/lib.rs +++ b/fuzzers/libafl_atheris/src/lib.rs @@ -34,7 +34,7 @@ use libafl::{ scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, token_mutations::{I2SRandReplace, Tokens}, }, - observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, + observers::{HitcountsMapObserver, TimeObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::{StdMutationalStage, TracingStage}, state::{HasCorpus, HasMetadata, StdState}, @@ -42,7 +42,7 @@ use libafl::{ }; use libafl_targets::{ CmpLogObserver, __sanitizer_cov_trace_cmp1, __sanitizer_cov_trace_cmp2, - __sanitizer_cov_trace_cmp4, __sanitizer_cov_trace_cmp8, CMPLOG_MAP, EDGES_MAP_PTR, + __sanitizer_cov_trace_cmp4, __sanitizer_cov_trace_cmp8, std_edges_map_observer, EDGES_MAP_PTR, MAX_EDGES_NUM, }; @@ -211,26 +211,19 @@ pub fn LLVMFuzzerRunDriver( let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); // TODO: we need to handle Atheris calls to `exit` on errors somhow. let mut run_client = |state: Option<_>, mut mgr, _core_id| { // Create an observation channel using the coverage map - let edges_observer = unsafe { - HitcountsMapObserver::new(StdMapObserver::new_from_ptr( - "edges", - EDGES_MAP_PTR, - MAX_EDGES_NUM, - )) - }; + let edges_observer = unsafe { HitcountsMapObserver::new(std_edges_map_observer("edges")) }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); // Create the Cmp observer - let cmplog = unsafe { &mut CMPLOG_MAP }; - let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); // Feedback to rate the interestingness of an input // This one is composed by two Feedbacks in OR diff --git a/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cc.rs index 0178cf96fc..ecf2ef585f 100644 --- a/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cxx.rs b/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cxx.rs +++ b/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/libfuzzer_libmozjpeg/src/lib.rs b/fuzzers/libfuzzer_libmozjpeg/src/lib.rs index e4193fab57..878a19800c 100644 --- a/fuzzers/libfuzzer_libmozjpeg/src/lib.rs +++ b/fuzzers/libfuzzer_libmozjpeg/src/lib.rs @@ -32,7 +32,7 @@ use libafl::{ Error, }; use libafl_targets::{ - libfuzzer_initialize, libfuzzer_test_one_input, CMP_MAP, EDGES_MAP, MAX_EDGES_NUM, + libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer, CMP_MAP, }; const ALLOC_MAP_SIZE: usize = 16 * 1024; @@ -62,7 +62,7 @@ pub fn libafl_main() { /// The actual fuzzer fn fuzz(corpus_dirs: &[PathBuf], 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 monitor = SimpleMonitor::new(|s| println!("{}", s)); + let monitor = SimpleMonitor::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) = @@ -78,14 +78,13 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re }; // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = StdMapObserver::new("edges", edges); + let edges_observer = unsafe { std_edges_map_observer("edges") }; // Create an observation channel using the cmp map - let cmps_observer = StdMapObserver::new("cmps", unsafe { &mut CMP_MAP }); + let cmps_observer = unsafe { StdMapObserver::new("cmps", &mut CMP_MAP) }; // Create an observation channel using the allocations map - let allocs_observer = StdMapObserver::new("allocs", unsafe { &mut libafl_alloc_map }); + let allocs_observer = unsafe { StdMapObserver::new("allocs", &mut libafl_alloc_map) }; // Feedback to rate the interestingness of an input let mut feedback = feedback_or!( diff --git a/fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs index c4c13ab101..69f3766586 100644 --- a/fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/libfuzzer_libpng/src/bin/libafl_cxx.rs b/fuzzers/libfuzzer_libpng/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/libfuzzer_libpng/src/bin/libafl_cxx.rs +++ b/fuzzers/libfuzzer_libpng/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/libfuzzer_libpng/src/lib.rs b/fuzzers/libfuzzer_libpng/src/lib.rs index bfb4d2c91c..368603a4bc 100644 --- a/fuzzers/libfuzzer_libpng/src/lib.rs +++ b/fuzzers/libfuzzer_libpng/src/lib.rs @@ -62,7 +62,7 @@ pub fn libafl_main() { #[cfg(not(test))] fn fuzz(corpus_dirs: &[PathBuf], 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 monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::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) = @@ -73,14 +73,19 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = unsafe { + HitcountsMapObserver::new(StdMapObserver::from_mut_ptr( + "edges", + EDGES_MAP.as_mut_ptr(), + MAX_EDGES_NUM, + )) + }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); @@ -182,7 +187,7 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re // Call LLVMFUzzerInitialize() if present. let args: Vec = env::args().collect(); if libfuzzer_initialize(&args) == -1 { - println!("Warning: LLVMFuzzerInitialize failed with -1") + println!("Warning: LLVMFuzzerInitialize failed with -1"); } // In case the corpus is empty (on first run), reset diff --git a/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cc.rs index 6b23261d89..57d2985014 100644 --- a/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cc.rs @@ -13,7 +13,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cxx.rs b/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cxx.rs +++ b/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/libfuzzer_libpng_accounting/src/lib.rs b/fuzzers/libfuzzer_libpng_accounting/src/lib.rs index 9262bb1d27..cf90148cba 100644 --- a/fuzzers/libfuzzer_libpng_accounting/src/lib.rs +++ b/fuzzers/libfuzzer_libpng_accounting/src/lib.rs @@ -129,12 +129,13 @@ pub fn libafl_main() { let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); let mut run_client = |state: Option<_>, mut restarting_mgr, _core_id| { // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = HitcountsMapObserver::new(unsafe { + StdMapObserver::from_mut_ptr("edges", EDGES_MAP.as_mut_ptr(), MAX_EDGES_NUM) + }); // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); @@ -221,7 +222,7 @@ pub fn libafl_main() { // Call LLVMFUzzerInitialize() if present. let args: Vec = env::args().collect(); if libfuzzer_initialize(&args) == -1 { - println!("Warning: LLVMFuzzerInitialize failed with -1") + println!("Warning: LLVMFuzzerInitialize failed with -1"); } // In case the corpus is empty (on first run), reset diff --git a/fuzzers/libfuzzer_libpng_cmin/src/bin/libafl_cxx.rs b/fuzzers/libfuzzer_libpng_cmin/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/libfuzzer_libpng_cmin/src/bin/libafl_cxx.rs +++ b/fuzzers/libfuzzer_libpng_cmin/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/libfuzzer_libpng_cmin/src/lib.rs b/fuzzers/libfuzzer_libpng_cmin/src/lib.rs index c23609cddd..622cb207e9 100644 --- a/fuzzers/libfuzzer_libpng_cmin/src/lib.rs +++ b/fuzzers/libfuzzer_libpng_cmin/src/lib.rs @@ -31,7 +31,7 @@ use libafl::{ scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, token_mutations::Tokens, }, - observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, + observers::{HitcountsMapObserver, TimeObserver}, schedulers::{ powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler, }, @@ -39,7 +39,7 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; -use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; +use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer}; /// The main fn, `no_mangle` as it is a C main #[cfg(not(test))] @@ -65,7 +65,7 @@ pub fn libafl_main() { #[cfg(not(test))] fn fuzz(corpus_dirs: &[PathBuf], 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 monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::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) = @@ -76,14 +76,13 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") }); let minimizer = StdCorpusMinimizer::new(&edges_observer); diff --git a/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cc.rs index 96abb9ef70..6f4436f8a9 100644 --- a/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cxx.rs b/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cxx.rs +++ b/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/libfuzzer_libpng_ctx/src/lib.rs b/fuzzers/libfuzzer_libpng_ctx/src/lib.rs index aaa6d93102..5f241a7176 100644 --- a/fuzzers/libfuzzer_libpng_ctx/src/lib.rs +++ b/fuzzers/libfuzzer_libpng_ctx/src/lib.rs @@ -38,7 +38,7 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; -use libafl_targets::{edges_map_from_ptr, libfuzzer_initialize, libfuzzer_test_one_input}; +use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer}; fn timeout_from_millis_str(time: &str) -> Result { Ok(Duration::from_millis(time.parse()?)) @@ -125,13 +125,11 @@ pub fn libafl_main() { let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); let mut run_client = |state: Option<_>, mut restarting_mgr, _core_id| { // Create an observation channel using the coverage map - let edges = unsafe { edges_map_from_ptr() }; - let edges_observer = - HitcountsMapObserver::new(StdMapObserver::new_from_ownedref("edges", edges)); + let edges_observer = unsafe { HitcountsMapObserver::new(std_edges_map_observer("edges")) }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); diff --git a/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cc.rs index c4c13ab101..69f3766586 100644 --- a/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cxx.rs b/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cxx.rs +++ b/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/libfuzzer_libpng_launcher/src/lib.rs b/fuzzers/libfuzzer_libpng_launcher/src/lib.rs index ff1127e84d..fc7d9daed9 100644 --- a/fuzzers/libfuzzer_libpng_launcher/src/lib.rs +++ b/fuzzers/libfuzzer_libpng_launcher/src/lib.rs @@ -38,7 +38,7 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; -use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; +use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer}; /// Parse a millis string to a [`Duration`]. Used for arg parsing. fn timeout_from_millis_str(time: &str) -> Result { @@ -129,13 +129,12 @@ pub fn libafl_main() { let monitor = OnDiskTOMLMonitor::new( "./fuzzer_stats.toml", - MultiMonitor::new(|s| println!("{}", s)), + MultiMonitor::new(|s| println!("{s}")), ); let mut run_client = |state: Option<_>, mut restarting_mgr, _core_id| { // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") }); // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); diff --git a/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs index 4cbaa83517..b631e484de 100644 --- a/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs @@ -12,7 +12,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/libfuzzer_reachability/src/bin/libafl_cxx.rs b/fuzzers/libfuzzer_reachability/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/libfuzzer_reachability/src/bin/libafl_cxx.rs +++ b/fuzzers/libfuzzer_reachability/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/libfuzzer_reachability/src/lib.rs b/fuzzers/libfuzzer_reachability/src/lib.rs index 7b83bb1f3d..988e4314d2 100644 --- a/fuzzers/libfuzzer_reachability/src/lib.rs +++ b/fuzzers/libfuzzer_reachability/src/lib.rs @@ -22,7 +22,7 @@ use libafl::{ state::{HasCorpus, StdState}, Error, }; -use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; +use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer}; const TARGET_SIZE: usize = 4; @@ -52,7 +52,7 @@ pub fn libafl_main() { /// The actual fuzzer fn fuzz(corpus_dirs: &[PathBuf], 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 monitor = SimpleMonitor::new(|s| println!("{}", s)); + let monitor = SimpleMonitor::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) = @@ -63,17 +63,16 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") }); let reachability_observer = - unsafe { StdMapObserver::new_from_ptr("png.c", __libafl_target_list, TARGET_SIZE) }; + unsafe { StdMapObserver::from_mut_ptr("png.c", __libafl_target_list, TARGET_SIZE) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new(&edges_observer); diff --git a/fuzzers/libfuzzer_stb_image/src/main.rs b/fuzzers/libfuzzer_stb_image/src/main.rs index caab113e4a..f92a394ccb 100644 --- a/fuzzers/libfuzzer_stb_image/src/main.rs +++ b/fuzzers/libfuzzer_stb_image/src/main.rs @@ -27,8 +27,7 @@ use libafl::{ Error, }; use libafl_targets::{ - libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, - MAX_EDGES_NUM, + libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer, CmpLogObserver, }; pub fn main() { @@ -51,7 +50,7 @@ pub fn main() { /// The actual fuzzer fn fuzz(corpus_dirs: &[PathBuf], 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 monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::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) = @@ -62,21 +61,19 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map // We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges) - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = StdMapObserver::new("edges", edges); + let edges_observer = unsafe { std_edges_map_observer("edges") }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); - let cmplog = unsafe { &mut CMPLOG_MAP }; - let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); // Feedback to rate the interestingness of an input // This one is composed by two Feedbacks in OR diff --git a/fuzzers/libfuzzer_stb_image_concolic/Makefile.toml b/fuzzers/libfuzzer_stb_image_concolic/Makefile.toml index 32036970bf..2253d97e26 100644 --- a/fuzzers/libfuzzer_stb_image_concolic/Makefile.toml +++ b/fuzzers/libfuzzer_stb_image_concolic/Makefile.toml @@ -1,8 +1,8 @@ # Variables [env] +PROJECT_DIR = { script = ["pwd"] } CARGO_TARGET_DIR = { value = "${PROJECT_DIR}/target", condition = { env_not_set = ["CARGO_TARGET_DIR"] } } FUZZER_NAME='libfuzzer_stb_image_concolic' -PROJECT_DIR = { script = ["pwd"] } # Compilers [tasks.runtime] diff --git a/fuzzers/libfuzzer_stb_image_concolic/fuzzer/src/main.rs b/fuzzers/libfuzzer_stb_image_concolic/fuzzer/src/main.rs index 3c52e51314..9ee32566cf 100644 --- a/fuzzers/libfuzzer_stb_image_concolic/fuzzer/src/main.rs +++ b/fuzzers/libfuzzer_stb_image_concolic/fuzzer/src/main.rs @@ -38,7 +38,7 @@ use libafl::{ serialization_format::{DEFAULT_ENV_NAME, DEFAULT_SIZE}, ConcolicObserver, }, - StdMapObserver, TimeObserver, + TimeObserver, }, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::{ @@ -49,8 +49,7 @@ use libafl::{ Error, }; use libafl_targets::{ - libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, - MAX_EDGES_NUM, + libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer, CmpLogObserver, }; #[derive(Debug, Parser)] @@ -88,7 +87,7 @@ fn fuzz( concolic: bool, ) -> Result<(), Error> { // 'While the stats are state, they are usually used in the broker - which is likely never restarted - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::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) = @@ -99,21 +98,19 @@ fn fuzz( return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map // We don't use the hitcounts (see the Cargo.toml, we use pcguard_edges) - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = StdMapObserver::new("edges", edges); + let edges_observer = unsafe { std_edges_map_observer("edges") }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); - let cmplog = unsafe { &mut CMPLOG_MAP }; - let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); // Feedback to rate the interestingness of an input // This one is composed by two Feedbacks in OR diff --git a/fuzzers/libfuzzer_windows_asan/src/lib.rs b/fuzzers/libfuzzer_windows_asan/src/lib.rs index f9877d3909..7ad1939298 100644 --- a/fuzzers/libfuzzer_windows_asan/src/lib.rs +++ b/fuzzers/libfuzzer_windows_asan/src/lib.rs @@ -16,20 +16,16 @@ use libafl::{ fuzzer::{Fuzzer, StdFuzzer}, inputs::{BytesInput, HasTargetBytes}, monitors::MultiMonitor, - mutators::{ - scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - token_mutations::Tokens, - }, - observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, + mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + observers::{HitcountsMapObserver, TimeObserver}, schedulers::{ powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler, }, stages::{calibrate::CalibrationStage, power::StdPowerMutationalStage}, - state::{HasCorpus, HasMetadata, StdState}, + state::{HasCorpus, StdState}, Error, }; -use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; - +use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer}; #[no_mangle] pub fn libafl_main() { println!( @@ -65,8 +61,7 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re }; // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = unsafe { HitcountsMapObserver::new(std_edges_map_observer("edges")) }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); diff --git a/fuzzers/nyx_libxml2_parallel/src/bin/libafl_cc.rs b/fuzzers/nyx_libxml2_parallel/src/bin/libafl_cc.rs index 040fa0a07a..4a6519f571 100644 --- a/fuzzers/nyx_libxml2_parallel/src/bin/libafl_cc.rs +++ b/fuzzers/nyx_libxml2_parallel/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/nyx_libxml2_parallel/src/main.rs b/fuzzers/nyx_libxml2_parallel/src/main.rs index 8629e3eea8..85f123db2a 100644 --- a/fuzzers/nyx_libxml2_parallel/src/main.rs +++ b/fuzzers/nyx_libxml2_parallel/src/main.rs @@ -26,16 +26,16 @@ fn main() { let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); let broker_port = 7777; - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); let cores = Cores::all().expect("unable to get all core id"); let parent_cpu_id = cores.ids.first().expect("unable to get first core id"); // region: fuzzer start function - let mut run_client = |state: Option<_>, mut restarting_mgr, _core_id: usize| { + let mut run_client = |state: Option<_>, mut restarting_mgr, core_id: usize| { // nyx shared dir, created by nyx-fuzz/packer/packer/nyx_packer.py let share_dir = Path::new("/tmp/nyx_libxml2/"); - let cpu_id = _core_id as u32; + let cpu_id = core_id.try_into().unwrap(); let parallel_mode = true; // nyx stuff let mut helper = NyxHelper::new( @@ -43,12 +43,11 @@ fn main() { cpu_id, true, parallel_mode, - Some(parent_cpu_id.id as u32), + Some(parent_cpu_id.id.try_into().unwrap()), ) .unwrap(); - let trace_bits = - unsafe { std::slice::from_raw_parts_mut(helper.trace_bits, helper.map_size) }; - let observer = StdMapObserver::new("trace", trace_bits); + let observer = + unsafe { StdMapObserver::from_mut_ptr("trace", helper.trace_bits, helper.map_size) }; let input = BytesInput::new(b"22".to_vec()); let rand = StdRand::new(); diff --git a/fuzzers/nyx_libxml2_standalone/src/bin/libafl_cc.rs b/fuzzers/nyx_libxml2_standalone/src/bin/libafl_cc.rs index 040fa0a07a..4a6519f571 100644 --- a/fuzzers/nyx_libxml2_standalone/src/bin/libafl_cc.rs +++ b/fuzzers/nyx_libxml2_standalone/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/nyx_libxml2_standalone/src/main.rs b/fuzzers/nyx_libxml2_standalone/src/main.rs index db08592046..8ecb074d55 100644 --- a/fuzzers/nyx_libxml2_standalone/src/main.rs +++ b/fuzzers/nyx_libxml2_standalone/src/main.rs @@ -26,8 +26,8 @@ fn main() { // nyx stuff let mut helper = NyxHelper::new(share_dir, cpu_id, true, parallel_mode, None).unwrap(); - let trace_bits = unsafe { std::slice::from_raw_parts_mut(helper.trace_bits, helper.map_size) }; - let observer = StdMapObserver::new("trace", trace_bits); + let observer = + unsafe { StdMapObserver::from_mut_ptr("trace", helper.trace_bits, helper.map_size) }; let input = BytesInput::new(b"22".to_vec()); let rand = StdRand::new(); diff --git a/fuzzers/push_harness/src/main.rs b/fuzzers/push_harness/src/main.rs index 78bdd7dd7d..95e40da53a 100644 --- a/fuzzers/push_harness/src/main.rs +++ b/fuzzers/push_harness/src/main.rs @@ -2,7 +2,7 @@ //! The target loops and the harness pulls inputs out of `LibAFL`, instead of being called by `LibAFL`. use std::path::PathBuf; -use klo_routines::*; +use klo_routines::{yield_, KloRoutine}; use libafl::{ bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice}, corpus::{InMemoryCorpus, OnDiskCorpus}, @@ -40,7 +40,7 @@ fn input_generator() { }; // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); + let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new(&observer); @@ -107,6 +107,7 @@ fn input_generator() { /// the main function loops independently of the fuzzer. /// `Klo` internally switches between the `LibAFL` and harness coroutines to generate the inputs. +#[allow(clippy::manual_assert)] pub fn main() { // Set up the Klo-routines harness let mut input_generator = input_generator; diff --git a/fuzzers/push_stage_harness/src/main.rs b/fuzzers/push_stage_harness/src/main.rs index 41a4c3f32b..13492fa1d9 100644 --- a/fuzzers/push_stage_harness/src/main.rs +++ b/fuzzers/push_stage_harness/src/main.rs @@ -1,6 +1,6 @@ //! A fuzzer that uses a `PushStage`, generating input to be subsequently executed, //! instead of executing input iteslf in a loop. -//! Using this method, we can add LibAFL, for example, into an emulation loop +//! Using this method, we can add `LibAFL`, for example, into an emulation loop //! or use its mutations for another fuzzer. //! This is a less hacky alternative to the `KloRoutines` based fuzzer, that will also work on non-`Unix`. @@ -34,7 +34,7 @@ fn signals_set(idx: usize) { #[allow(clippy::similar_names)] pub fn main() { // Create an observation channel using the signals map - let observer = StdMapObserver::new("signals", unsafe { &mut SIGNALS }); + let observer = unsafe { StdMapObserver::new("signals", &mut SIGNALS) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new(&observer); diff --git a/fuzzers/qemu_arm_launcher/Makefile.toml b/fuzzers/qemu_arm_launcher/Makefile.toml index dcbef5c7d3..2984ffe5e0 100644 --- a/fuzzers/qemu_arm_launcher/Makefile.toml +++ b/fuzzers/qemu_arm_launcher/Makefile.toml @@ -18,20 +18,20 @@ mac_alias = "unsupported" windows_alias = "unsupported" [tasks.zlib_unix_wget] -condition = { files_not_exist = [ "./zlib-1.2.12" ] } +condition = { files_not_exist = [ "./zlib-1.2.13" ] } script_runner="@shell" # NOTE: There's no specific reason we're using an old version of zlib, # but newer versions get moved to fossils/ after a while. script=''' -wget https://zlib.net/fossils/zlib-1.2.12.tar.gz -tar -xvf zlib-1.2.12.tar.gz +wget https://zlib.net/fossils/zlib-1.2.13.tar.gz +tar -xvf zlib-1.2.13.tar.gz ''' [tasks.zlib_unix] -condition = { files_not_exist = [ "./zlib-1.2.12/zlib/lib/libz.a" ] } +condition = { files_not_exist = [ "./zlib-1.2.13/zlib/lib/libz.a" ] } script_runner="@shell" script=''' -cd zlib-1.2.12 && CC=$CROSS_CC ./configure --prefix=./zlib +cd zlib-1.2.13 && CC=$CROSS_CC ./configure --prefix=./zlib make install ''' dependencies = [ "zlib_unix_wget" ] @@ -54,7 +54,7 @@ tar -xvf libpng-1.6.37.tar.xz condition = { files_not_exist = [ "./libpng-1.6.37/.libs/libpng16.a" ] } script_runner="@shell" script=''' -cd libpng-1.6.37 && CC=$CROSS_CC CFLAGS=-I../zlib-1.2.12/zlib/lib LDFLAGS=-L../zlib-1.2.12/zlib/lib ./configure --enable-shared=no --with-pic=yes --enable-hardware-optimizations=yes --host=arm +cd libpng-1.6.37 && CC=$CROSS_CC CFLAGS=-I../zlib-1.2.13/zlib/lib LDFLAGS=-L../zlib-1.2.13/zlib/lib ./configure --enable-shared=no --with-pic=yes --enable-hardware-optimizations=yes --host=arm make ''' dependencies = [ "zlib", "libpng_unix_wget" ] @@ -82,10 +82,10 @@ script=''' arm-linux-gnueabi-g++ \ ./harness.cc \ ./libpng-1.6.37/.libs/libpng16.a \ - ./zlib-1.2.12/zlib/lib/libz.a \ + ./zlib-1.2.13/zlib/lib/libz.a \ -I./libpng-1.6.37/ \ - -I../zlib-1.2.12/zlib/lib \ - -L../zlib-1.2.12/zlib/lib \ + -I../zlib-1.2.13/zlib/lib \ + -L../zlib-1.2.13/zlib/lib \ -o ${FUZZER_NAME} \ -lm \ -static @@ -116,10 +116,10 @@ script=''' arm-linux-gnueabi-g++ \ ./harness.cc \ ./libpng-1.6.37/.libs/libpng16.a \ - ./zlib-1.2.12/zlib/lib/libz.a \ + ./zlib-1.2.13/zlib/lib/libz.a \ -I./libpng-1.6.37/ \ - -I../zlib-1.2.12/zlib/lib \ - -L../zlib-1.2.12/zlib/lib \ + -I../zlib-1.2.13/zlib/lib \ + -L../zlib-1.2.13/zlib/lib \ -o ${FUZZER_NAME_CRASHING} \ -lm \ -DHAS_DUMMY_CRASH \ diff --git a/fuzzers/qemu_arm_launcher/src/fuzzer.rs b/fuzzers/qemu_arm_launcher/src/fuzzer.rs index 780cf2db1c..998a85b903 100644 --- a/fuzzers/qemu_arm_launcher/src/fuzzer.rs +++ b/fuzzers/qemu_arm_launcher/src/fuzzer.rs @@ -1,6 +1,6 @@ //! A libfuzzer-like fuzzer using qemu for binary-only coverage //! -use core::time::Duration; +use core::{ptr::addr_of_mut, time::Duration}; use std::{env, path::PathBuf, process}; use libafl::{ @@ -31,8 +31,7 @@ use libafl::{ use libafl_qemu::{ drcov::QemuDrCovHelper, //asan::QemuAsanHelper, - edges, - edges::QemuEdgeCoverageHelper, + edges::{edges_map_mut_slice, QemuEdgeCoverageHelper, MAX_EDGES_NUM}, elf::EasyElf, emu::Emulator, MmapPerms, @@ -109,10 +108,13 @@ pub fn fuzz() { let mut run_client = |state: Option<_>, mut mgr, _core_id| { // Create an observation channel using the coverage map - let edges = unsafe { &mut edges::EDGES_MAP }; - let edges_counter = unsafe { &mut edges::MAX_EDGES_NUM }; - let edges_observer = - HitcountsMapObserver::new(VariableMapObserver::new("edges", edges, edges_counter)); + let edges_observer = unsafe { + HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( + "edges", + edges_map_mut_slice(), + addr_of_mut!(MAX_EDGES_NUM), + )) + }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); @@ -215,7 +217,7 @@ pub fn fuzz() { let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); // The stats reporter for the broker - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); // Build and run a Launcher match Launcher::builder() diff --git a/fuzzers/qemu_launcher/src/fuzzer.rs b/fuzzers/qemu_launcher/src/fuzzer.rs index af656fee1e..6a5104c891 100644 --- a/fuzzers/qemu_launcher/src/fuzzer.rs +++ b/fuzzers/qemu_launcher/src/fuzzer.rs @@ -1,6 +1,6 @@ //! A libfuzzer-like fuzzer using qemu for binary-only coverage //! -use core::time::Duration; +use core::{ptr::addr_of_mut, time::Duration}; use std::{env, path::PathBuf, process}; use libafl::{ @@ -30,13 +30,9 @@ use libafl::{ }; use libafl_qemu::{ //asan::QemuAsanHelper, - cmplog, - cmplog::{CmpLogObserver, QemuCmpLogHelper}, - edges, - edges::QemuEdgeCoverageHelper, + edges::{edges_map_mut_slice, QemuEdgeCoverageHelper, MAX_EDGES_NUM}, elf::EasyElf, emu::Emulator, - filter_qemu_args, //snapshot::QemuSnapshotHelper, MmapPerms, QemuExecutor, @@ -52,7 +48,7 @@ pub fn fuzz() { let broker_port = 1337; let cores = Cores::from_cmdline("0-11").unwrap(); let corpus_dirs = [PathBuf::from("./corpus")]; - let mut objective_dir = PathBuf::from("./crashes"); + let objective_dir = PathBuf::from("./crashes"); // Initialize QEMU env::remove_var("LD_LIBRARY_PATH"); @@ -116,10 +112,13 @@ pub fn fuzz() { let mut run_client = |state: Option<_>, mut mgr, _core_id| { // Create an observation channel using the coverage map - let edges = unsafe { &mut edges::EDGES_MAP }; - let edges_counter = unsafe { &mut edges::MAX_EDGES_NUM }; - let edges_observer = - HitcountsMapObserver::new(VariableMapObserver::new("edges", edges, edges_counter)); + let edges_observer = unsafe { + HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( + "edges", + edges_map_mut_slice(), + addr_of_mut!(MAX_EDGES_NUM), + )) + }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); @@ -199,7 +198,7 @@ pub fn fuzz() { let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); // The stats reporter for the broker - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); // Build and run a Launcher match Launcher::builder() diff --git a/fuzzers/qemu_systemmode/src/fuzzer.rs b/fuzzers/qemu_systemmode/src/fuzzer.rs index 8590b0f79a..54e7b7943f 100644 --- a/fuzzers/qemu_systemmode/src/fuzzer.rs +++ b/fuzzers/qemu_systemmode/src/fuzzer.rs @@ -1,6 +1,6 @@ //! A fuzzer using qemu in systemmode for binary-only coverage of kernels //! -use core::time::Duration; +use core::{ptr::addr_of_mut, time::Duration}; use std::{env, path::PathBuf, process}; use libafl::{ @@ -22,15 +22,17 @@ use libafl::{ inputs::{BytesInput, HasTargetBytes}, monitors::MultiMonitor, mutators::scheduled::{havoc_mutations, StdScheduledMutator}, - observers::{TimeObserver, VariableMapObserver}, + observers::{HitcountsMapObserver, TimeObserver, VariableMapObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::StdMutationalStage, state::{HasCorpus, StdState}, Error, }; use libafl_qemu::{ - edges, edges::QemuEdgeCoverageHelper, elf::EasyElf, emu::Emulator, GuestPhysAddr, QemuExecutor, - QemuHooks, Regs, + edges::{edges_map_mut_slice, QemuEdgeCoverageHelper, MAX_EDGES_NUM}, + elf::EasyElf, + emu::Emulator, + GuestPhysAddr, QemuExecutor, QemuHooks, Regs, }; pub static mut MAX_INPUT_SIZE: usize = 50; @@ -138,9 +140,13 @@ pub fn fuzz() { }; // Create an observation channel using the coverage map - let edges = unsafe { &mut edges::EDGES_MAP }; - let edges_counter = unsafe { &mut edges::MAX_EDGES_NUM }; - let edges_observer = VariableMapObserver::new("edges", edges, edges_counter); + let edges_observer = unsafe { + HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( + "edges", + edges_map_mut_slice(), + addr_of_mut!(MAX_EDGES_NUM), + )) + }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); @@ -222,9 +228,9 @@ pub fn fuzz() { let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); // The stats reporter for the broker - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::new(|s| println!("{s}")); - // let monitor = SimpleMonitor::new(|s| println!("{}", s)); + // let monitor = SimpleMonitor::new(|s| println!("{s}")); // let mut mgr = SimpleEventManager::new(monitor); // run_client(None, mgr, 0); diff --git a/fuzzers/tinyinst_simple/src/main.rs b/fuzzers/tinyinst_simple/src/main.rs index 97c5ddf5e9..720eb5a1d7 100644 --- a/fuzzers/tinyinst_simple/src/main.rs +++ b/fuzzers/tinyinst_simple/src/main.rs @@ -26,7 +26,7 @@ fn main() { let args = vec![".\\test\\test.exe".to_string(), "@@".to_string()]; - let observer = ListObserver::new("cov", unsafe { &mut COVERAGE }); + let observer = unsafe { ListObserver::new("cov", &mut COVERAGE) }; let mut feedback = ListFeedback::new_with_observer(&observer); let input = BytesInput::new(b"bad".to_vec()); diff --git a/fuzzers/tutorial/src/bin/libafl_cc.rs b/fuzzers/tutorial/src/bin/libafl_cc.rs index 66ae8719d8..7b2ce8f725 100644 --- a/fuzzers/tutorial/src/bin/libafl_cc.rs +++ b/fuzzers/tutorial/src/bin/libafl_cc.rs @@ -11,7 +11,7 @@ pub fn main() { let is_cpp = match wrapper_name[wrapper_name.len()-2..].to_lowercase().as_str() { "cc" => false, "++" | "pp" | "xx" => true, - _ => panic!("Could not figure out if c or c++ warpper was called. Expected {:?} to end with c or cxx", dir), + _ => panic!("Could not figure out if c or c++ wrapper was called. Expected {dir:?} to end with c or cxx"), }; dir.pop(); diff --git a/fuzzers/tutorial/src/bin/libafl_cxx.rs b/fuzzers/tutorial/src/bin/libafl_cxx.rs index ce786239b0..dabd22971a 100644 --- a/fuzzers/tutorial/src/bin/libafl_cxx.rs +++ b/fuzzers/tutorial/src/bin/libafl_cxx.rs @@ -1,5 +1,5 @@ pub mod libafl_cc; fn main() { - libafl_cc::main() + libafl_cc::main(); } diff --git a/fuzzers/tutorial/src/input.rs b/fuzzers/tutorial/src/input.rs index d0d79cf122..3295cee6ea 100644 --- a/fuzzers/tutorial/src/input.rs +++ b/fuzzers/tutorial/src/input.rs @@ -52,7 +52,7 @@ impl Default for PacketType { impl Input for PacketData { fn generate_name(&self, idx: usize) -> String { - format!("id_{}", idx) + format!("id_{idx}") } } diff --git a/fuzzers/tutorial/src/lib.rs b/fuzzers/tutorial/src/lib.rs index 17ba5f82f5..a30ad97990 100644 --- a/fuzzers/tutorial/src/lib.rs +++ b/fuzzers/tutorial/src/lib.rs @@ -16,13 +16,13 @@ use libafl::{ fuzzer::StdFuzzer, inputs::HasTargetBytes, monitors::MultiMonitor, - observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, + observers::{HitcountsMapObserver, TimeObserver}, schedulers::{powersched::PowerSchedule, PowerQueueScheduler}, stages::{calibrate::CalibrationStage, power::StdPowerMutationalStage}, state::{HasCorpus, StdState}, Error, Fuzzer, }; -use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; +use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, std_edges_map_observer}; mod input; use input::*; @@ -64,7 +64,7 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re }; // 'While the stats are state, they are usually used in the broker - which is likely never restarted - let monitor = MultiMonitor::new(|s| println!("{}", s)); + let monitor = MultiMonitor::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) = @@ -75,14 +75,13 @@ fn fuzz(corpus_dirs: &[PathBuf], objective_dir: PathBuf, broker_port: u16) -> Re return Ok(()); } _ => { - panic!("Failed to setup the restarter: {}", err); + panic!("Failed to setup the restarter: {err}"); } }, }; // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") }); // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); diff --git a/libafl/build.rs b/libafl/build.rs index f75be9ddb9..05b7c894bc 100644 --- a/libafl/build.rs +++ b/libafl/build.rs @@ -7,7 +7,8 @@ fn main() { #[rustversion::not(nightly)] fn main() { println!("cargo:rerun-if-changed=build.rs"); - if cfg!(feature = "nautilus") { - panic!("The 'nautilus' feature of libafl requires a nightly compiler"); - } + assert!( + cfg!(not(feature = "nautilus")), + "The 'nautilus' feature of libafl requires a nightly compiler" + ); } diff --git a/libafl/src/bolts/ownedref.rs b/libafl/src/bolts/ownedref.rs index e533cb36bf..d974c75c75 100644 --- a/libafl/src/bolts/ownedref.rs +++ b/libafl/src/bolts/ownedref.rs @@ -330,14 +330,14 @@ impl<'a, T> From<&'a [T]> for OwnedSlice<'a, T> { } } -/// Create a new [`OwnedSlice`] from a [`OwnedSliceMut`] -impl<'a, T> From> for OwnedSlice<'a, T> { - fn from(mut_slice: OwnedSliceMut<'a, T>) -> Self { +/// Create a new [`OwnedSlice`] from a [`OwnedMutSlice`] +impl<'a, T> From> for OwnedSlice<'a, T> { + fn from(mut_slice: OwnedMutSlice<'a, T>) -> Self { Self { inner: match mut_slice.inner { - OwnedSliceMutInner::RefRaw(ptr, len) => OwnedSliceInner::RefRaw(ptr as _, len), - OwnedSliceMutInner::Ref(r) => OwnedSliceInner::Ref(r as _), - OwnedSliceMutInner::Owned(v) => OwnedSliceInner::Owned(v), + OwnedMutSliceInner::RefRaw(ptr, len) => OwnedSliceInner::RefRaw(ptr as _, len), + OwnedMutSliceInner::Ref(r) => OwnedSliceInner::Ref(r as _), + OwnedMutSliceInner::Owned(v) => OwnedSliceInner::Owned(v), }, } } @@ -384,7 +384,7 @@ where } } -/// Create a vector from an [`OwnedSliceMut`], or return the owned vec. +/// Create a vector from an [`OwnedMutSlice`], or return the owned vec. impl<'a, T> From> for Vec where T: Clone, @@ -400,9 +400,9 @@ where /// Wrap a mutable slice and convert to a Vec on serialize. /// We use a hidden inner enum so the public API can be safe, -/// unless the user uses the unsafe [`OwnedSliceMut::from_raw_parts_mut`] +/// unless the user uses the unsafe [`OwnedMutSlice::from_raw_parts_mut`] #[derive(Debug)] -pub enum OwnedSliceMutInner<'a, T: 'a + Sized> { +pub enum OwnedMutSliceInner<'a, T: 'a + Sized> { /// A raw ptr to a memory location and a length RefRaw(*mut T, usize), /// A ptr to a mutable slice of the type @@ -411,22 +411,22 @@ pub enum OwnedSliceMutInner<'a, T: 'a + Sized> { Owned(Vec), } -impl<'a, T: 'a + Sized + Serialize> Serialize for OwnedSliceMutInner<'a, T> { +impl<'a, T: 'a + Sized + Serialize> Serialize for OwnedMutSliceInner<'a, T> { fn serialize(&self, se: S) -> Result where S: Serializer, { match self { - OwnedSliceMutInner::RefRaw(rr, len) => { + OwnedMutSliceInner::RefRaw(rr, len) => { unsafe { slice::from_raw_parts_mut(*rr, *len) }.serialize(se) } - OwnedSliceMutInner::Ref(r) => r.serialize(se), - OwnedSliceMutInner::Owned(b) => b.serialize(se), + OwnedMutSliceInner::Ref(r) => r.serialize(se), + OwnedMutSliceInner::Owned(b) => b.serialize(se), } } } -impl<'de, 'a, T: 'a + Sized> Deserialize<'de> for OwnedSliceMutInner<'a, T> +impl<'de, 'a, T: 'a + Sized> Deserialize<'de> for OwnedMutSliceInner<'a, T> where Vec: Deserialize<'de>, { @@ -434,18 +434,18 @@ where where D: Deserializer<'de>, { - Deserialize::deserialize(deserializer).map(OwnedSliceMutInner::Owned) + Deserialize::deserialize(deserializer).map(OwnedMutSliceInner::Owned) } } /// Wrap a mutable slice and convert to a Vec on serialize #[allow(clippy::unsafe_derive_deserialize)] #[derive(Debug, Serialize, Deserialize)] -pub struct OwnedSliceMut<'a, T: 'a + Sized> { - inner: OwnedSliceMutInner<'a, T>, +pub struct OwnedMutSlice<'a, T: 'a + Sized> { + inner: OwnedMutSliceInner<'a, T>, } -impl<'a, 'it, T> IntoIterator for &'it mut OwnedSliceMut<'a, T> { +impl<'a, 'it, T> IntoIterator for &'it mut OwnedMutSlice<'a, T> { type Item = as Iterator>::Item; type IntoIter = IterMut<'it, T>; @@ -454,7 +454,7 @@ impl<'a, 'it, T> IntoIterator for &'it mut OwnedSliceMut<'a, T> { } } -impl<'a, 'it, T> IntoIterator for &'it OwnedSliceMut<'a, T> { +impl<'a, 'it, T> IntoIterator for &'it OwnedMutSlice<'a, T> { type Item = as Iterator>::Item; type IntoIter = Iter<'it, T>; @@ -463,22 +463,22 @@ impl<'a, 'it, T> IntoIterator for &'it OwnedSliceMut<'a, T> { } } -impl<'a, T: 'a + Sized> OwnedSliceMut<'a, T> { - /// Create a new [`OwnedSliceMut`] from a raw pointer and length +impl<'a, T: 'a + Sized> OwnedMutSlice<'a, T> { + /// Create a new [`OwnedMutSlice`] from a raw pointer and length /// /// # Safety /// /// The pointer must be valid and point to a map of the size `size_of() * len` /// The contents will be dereferenced in subsequent operations. #[must_use] - pub unsafe fn from_raw_parts_mut(ptr: *mut T, len: usize) -> OwnedSliceMut<'a, T> { + pub unsafe fn from_raw_parts_mut(ptr: *mut T, len: usize) -> OwnedMutSlice<'a, T> { if ptr.is_null() || len == 0 { Self { - inner: OwnedSliceMutInner::Owned(Vec::new()), + inner: OwnedMutSliceInner::Owned(Vec::new()), } } else { Self { - inner: OwnedSliceMutInner::RefRaw(ptr, len), + inner: OwnedMutSliceInner::RefRaw(ptr, len), } } } @@ -486,7 +486,7 @@ impl<'a, T: 'a + Sized> OwnedSliceMut<'a, T> { /// Downsize the inner slice or vec returning the old size on success or `None` on failure pub fn downsize(&mut self, new_len: usize) -> Option { match &mut self.inner { - OwnedSliceMutInner::RefRaw(_rr, len) => { + OwnedMutSliceInner::RefRaw(_rr, len) => { let tmp = *len; if new_len <= tmp { *len = new_len; @@ -495,7 +495,7 @@ impl<'a, T: 'a + Sized> OwnedSliceMut<'a, T> { None } } - OwnedSliceMutInner::Ref(r) => { + OwnedMutSliceInner::Ref(r) => { let tmp = r.len(); if new_len <= tmp { r.downsize(new_len); @@ -504,7 +504,7 @@ impl<'a, T: 'a + Sized> OwnedSliceMut<'a, T> { None } } - OwnedSliceMutInner::Owned(v) => { + OwnedMutSliceInner::Owned(v) => { let tmp = v.len(); if new_len <= tmp { v.truncate(new_len); @@ -517,113 +517,113 @@ impl<'a, T: 'a + Sized> OwnedSliceMut<'a, T> { } } -impl<'a, T: Sized> AsSlice for OwnedSliceMut<'a, T> { +impl<'a, T: Sized> AsSlice for OwnedMutSlice<'a, T> { type Entry = T; /// Get the value as slice #[must_use] fn as_slice(&self) -> &[T] { match &self.inner { - OwnedSliceMutInner::RefRaw(rr, len) => unsafe { slice::from_raw_parts(*rr, *len) }, - OwnedSliceMutInner::Ref(r) => r, - OwnedSliceMutInner::Owned(v) => v.as_slice(), + OwnedMutSliceInner::RefRaw(rr, len) => unsafe { slice::from_raw_parts(*rr, *len) }, + OwnedMutSliceInner::Ref(r) => r, + OwnedMutSliceInner::Owned(v) => v.as_slice(), } } } -impl<'a, T: Sized> AsMutSlice for OwnedSliceMut<'a, T> { +impl<'a, T: Sized> AsMutSlice for OwnedMutSlice<'a, T> { type Entry = T; /// Get the value as mut slice #[must_use] fn as_mut_slice(&mut self) -> &mut [T] { match &mut self.inner { - OwnedSliceMutInner::RefRaw(rr, len) => unsafe { slice::from_raw_parts_mut(*rr, *len) }, - OwnedSliceMutInner::Ref(r) => r, - OwnedSliceMutInner::Owned(v) => v.as_mut_slice(), + OwnedMutSliceInner::RefRaw(rr, len) => unsafe { slice::from_raw_parts_mut(*rr, *len) }, + OwnedMutSliceInner::Ref(r) => r, + OwnedMutSliceInner::Owned(v) => v.as_mut_slice(), } } } -impl<'a, T> IntoOwned for OwnedSliceMut<'a, T> +impl<'a, T> IntoOwned for OwnedMutSlice<'a, T> where T: Sized + Clone, { #[must_use] fn is_owned(&self) -> bool { match self.inner { - OwnedSliceMutInner::RefRaw(_, _) | OwnedSliceMutInner::Ref(_) => false, - OwnedSliceMutInner::Owned(_) => true, + OwnedMutSliceInner::RefRaw(_, _) | OwnedMutSliceInner::Ref(_) => false, + OwnedMutSliceInner::Owned(_) => true, } } #[must_use] fn into_owned(self) -> Self { let vec = match self.inner { - OwnedSliceMutInner::RefRaw(rr, len) => unsafe { + OwnedMutSliceInner::RefRaw(rr, len) => unsafe { slice::from_raw_parts_mut(rr, len).to_vec() }, - OwnedSliceMutInner::Ref(r) => r.to_vec(), - OwnedSliceMutInner::Owned(v) => v, + OwnedMutSliceInner::Ref(r) => r.to_vec(), + OwnedMutSliceInner::Owned(v) => v, }; Self { - inner: OwnedSliceMutInner::Owned(vec), + inner: OwnedMutSliceInner::Owned(vec), } } } -impl<'a, T: 'a + Clone> Clone for OwnedSliceMut<'a, T> { +impl<'a, T: 'a + Clone> Clone for OwnedMutSlice<'a, T> { fn clone(&self) -> Self { Self { - inner: OwnedSliceMutInner::Owned(self.as_slice().to_vec()), + inner: OwnedMutSliceInner::Owned(self.as_slice().to_vec()), } } } -/// Create a new [`OwnedSliceMut`] from a vector -impl<'a, T> From> for OwnedSliceMut<'a, T> { +/// Create a new [`OwnedMutSlice`] from a vector +impl<'a, T> From> for OwnedMutSlice<'a, T> { fn from(vec: Vec) -> Self { Self { - inner: OwnedSliceMutInner::Owned(vec), + inner: OwnedMutSliceInner::Owned(vec), } } } -/// Create a vector from an [`OwnedSliceMut`], or return the owned vec. -impl<'a, T> From> for Vec +/// Create a vector from an [`OwnedMutSlice`], or return the owned vec. +impl<'a, T> From> for Vec where T: Clone, { - fn from(slice: OwnedSliceMut<'a, T>) -> Self { + fn from(slice: OwnedMutSlice<'a, T>) -> Self { let slice = slice.into_owned(); match slice.inner { - OwnedSliceMutInner::Owned(vec) => vec, + OwnedMutSliceInner::Owned(vec) => vec, _ => panic!("Could not own slice!"), } } } -/// Create a new [`OwnedSliceMut`] from a vector reference -impl<'a, T> From<&'a mut Vec> for OwnedSliceMut<'a, T> { +/// Create a new [`OwnedMutSlice`] from a vector reference +impl<'a, T> From<&'a mut Vec> for OwnedMutSlice<'a, T> { fn from(vec: &'a mut Vec) -> Self { Self { - inner: OwnedSliceMutInner::Ref(vec), + inner: OwnedMutSliceInner::Ref(vec), } } } -/// Create a new [`OwnedSliceMut`] from a reference to ref to a slice -impl<'a, T> From<&'a mut [T]> for OwnedSliceMut<'a, T> { +/// Create a new [`OwnedMutSlice`] from a reference to ref to a slice +impl<'a, T> From<&'a mut [T]> for OwnedMutSlice<'a, T> { fn from(r: &'a mut [T]) -> Self { Self { - inner: OwnedSliceMutInner::Ref(r), + inner: OwnedMutSliceInner::Ref(r), } } } -/// Create a new [`OwnedSliceMut`] from a reference to ref to a slice +/// Create a new [`OwnedMutSlice`] from a reference to ref to a slice #[allow(clippy::mut_mut)] // This makes use in some iterators easier -impl<'a, T> From<&'a mut &'a mut [T]> for OwnedSliceMut<'a, T> { +impl<'a, T> From<&'a mut &'a mut [T]> for OwnedMutSlice<'a, T> { fn from(r: &'a mut &'a mut [T]) -> Self { Self { - inner: OwnedSliceMutInner::Ref(r), + inner: OwnedMutSliceInner::Ref(r), } } } @@ -691,14 +691,14 @@ where /// Wrap a C-style mutable pointer and convert to a Box on serialize #[derive(Clone, Debug)] -pub enum OwnedPtrMut { +pub enum OwnedMutPtr { /// A mut ptr to the content Ptr(*mut T), /// An owned [`Box`] to the content Owned(Box), } -impl Serialize for OwnedPtrMut { +impl Serialize for OwnedMutPtr { fn serialize(&self, se: S) -> Result where S: Serializer, @@ -707,7 +707,7 @@ impl Serialize for OwnedPtrMut { } } -impl<'de, T: Sized + serde::de::DeserializeOwned> Deserialize<'de> for OwnedPtrMut +impl<'de, T: Sized + serde::de::DeserializeOwned> Deserialize<'de> for OwnedMutPtr where Vec: Deserialize<'de>, { @@ -715,48 +715,48 @@ where where D: Deserializer<'de>, { - Deserialize::deserialize(de).map(OwnedPtrMut::Owned) + Deserialize::deserialize(de).map(OwnedMutPtr::Owned) } } -impl AsRef for OwnedPtrMut { +impl AsRef for OwnedMutPtr { #[must_use] fn as_ref(&self) -> &T { match self { - OwnedPtrMut::Ptr(p) => unsafe { p.as_ref().unwrap() }, - OwnedPtrMut::Owned(b) => b.as_ref(), + OwnedMutPtr::Ptr(p) => unsafe { p.as_ref().unwrap() }, + OwnedMutPtr::Owned(b) => b.as_ref(), } } } -impl AsMut for OwnedPtrMut { +impl AsMut for OwnedMutPtr { fn as_mut(&mut self) -> &mut T { match self { - OwnedPtrMut::Ptr(p) => unsafe { p.as_mut().unwrap() }, - OwnedPtrMut::Owned(b) => b.as_mut(), + OwnedMutPtr::Ptr(p) => unsafe { p.as_mut().unwrap() }, + OwnedMutPtr::Owned(b) => b.as_mut(), } } } -impl IntoOwned for OwnedPtrMut +impl IntoOwned for OwnedMutPtr where T: Sized + Clone, { #[must_use] fn is_owned(&self) -> bool { match self { - OwnedPtrMut::Ptr(_) => false, - OwnedPtrMut::Owned(_) => true, + OwnedMutPtr::Ptr(_) => false, + OwnedMutPtr::Owned(_) => true, } } #[must_use] fn into_owned(self) -> Self { match self { - OwnedPtrMut::Ptr(p) => unsafe { - OwnedPtrMut::Owned(Box::new(p.as_ref().unwrap().clone())) + OwnedMutPtr::Ptr(p) => unsafe { + OwnedMutPtr::Owned(Box::new(p.as_ref().unwrap().clone())) }, - OwnedPtrMut::Owned(v) => OwnedPtrMut::Owned(v), + OwnedMutPtr::Owned(v) => OwnedMutPtr::Owned(v), } } } diff --git a/libafl/src/corpus/testcase.rs b/libafl/src/corpus/testcase.rs index f5524be871..5a5e8344f9 100644 --- a/libafl/src/corpus/testcase.rs +++ b/libafl/src/corpus/testcase.rs @@ -354,7 +354,7 @@ pub mod pybind { use super::{HasMetadata, Testcase}; use crate::{ - bolts::ownedref::OwnedPtrMut, + bolts::ownedref::OwnedMutPtr, inputs::{BytesInput, HasBytesVec}, pybind::PythonMetadata, }; @@ -367,13 +367,13 @@ pub mod pybind { /// Python class for Testcase pub struct PythonTestcaseWrapper { /// Rust wrapped Testcase object - pub inner: OwnedPtrMut, + pub inner: OwnedMutPtr, } impl PythonTestcaseWrapper { pub fn wrap(r: &mut PythonTestcase) -> Self { Self { - inner: OwnedPtrMut::Ptr(r), + inner: OwnedMutPtr::Ptr(r), } } @@ -392,7 +392,7 @@ pub mod pybind { #[new] fn new(input: Vec) -> Self { Self { - inner: OwnedPtrMut::Owned(Box::new(PythonTestcase::new(BytesInput::new(input)))), + inner: OwnedMutPtr::Owned(Box::new(PythonTestcase::new(BytesInput::new(input)))), } } diff --git a/libafl/src/events/mod.rs b/libafl/src/events/mod.rs index 30a6d615c4..22a3c8f8bd 100644 --- a/libafl/src/events/mod.rs +++ b/libafl/src/events/mod.rs @@ -652,7 +652,7 @@ mod tests { #[test] fn test_event_serde() { - let obv = StdMapObserver::new("test", unsafe { &mut MAP }); + let obv = unsafe { StdMapObserver::new("test", &mut MAP) }; let map = tuple_list!(obv); let observers_buf = postcard::to_allocvec(&map).unwrap(); diff --git a/libafl/src/executors/differential.rs b/libafl/src/executors/differential.rs index fc110bb021..850a246115 100644 --- a/libafl/src/executors/differential.rs +++ b/libafl/src/executors/differential.rs @@ -7,7 +7,7 @@ use core::{cell::UnsafeCell, fmt::Debug}; use serde::{Deserialize, Serialize}; use crate::{ - bolts::{ownedref::OwnedPtrMut, tuples::MatchName}, + bolts::{ownedref::OwnedMutPtr, tuples::MatchName}, executors::{Executor, ExitKind, HasObservers}, inputs::UsesInput, observers::{DifferentialObserversTuple, ObserversTuple, UsesObservers}, @@ -37,8 +37,8 @@ impl DiffExecutor { primary, secondary, observers: UnsafeCell::new(ProxyObserversTuple { - primary: OwnedPtrMut::Ptr(core::ptr::null_mut()), - secondary: OwnedPtrMut::Ptr(core::ptr::null_mut()), + primary: OwnedMutPtr::Ptr(core::ptr::null_mut()), + secondary: OwnedMutPtr::Ptr(core::ptr::null_mut()), differential: observers, }), } @@ -116,8 +116,8 @@ where bound = "A: serde::Serialize + serde::de::DeserializeOwned, B: serde::Serialize + serde::de::DeserializeOwned, DOT: serde::Serialize + serde::de::DeserializeOwned" )] pub struct ProxyObserversTuple { - primary: OwnedPtrMut, - secondary: OwnedPtrMut, + primary: OwnedMutPtr, + secondary: OwnedMutPtr, differential: DOT, } @@ -207,8 +207,8 @@ where impl ProxyObserversTuple { fn set(&mut self, primary: &A, secondary: &B) { - self.primary = OwnedPtrMut::Ptr(primary as *const A as *mut A); - self.secondary = OwnedPtrMut::Ptr(secondary as *const B as *mut B); + self.primary = OwnedMutPtr::Ptr(primary as *const A as *mut A); + self.secondary = OwnedMutPtr::Ptr(secondary as *const B as *mut B); } } diff --git a/libafl/src/feedbacks/mod.rs b/libafl/src/feedbacks/mod.rs index 0b5ceee98d..3879365ed7 100644 --- a/libafl/src/feedbacks/mod.rs +++ b/libafl/src/feedbacks/mod.rs @@ -1,7 +1,8 @@ //! The feedbacks reduce observer state after each run to a single `is_interesting`-value. //! If a testcase is interesting, it may be added to a Corpus. //! -//! TODO: make S of Feedback an associated type when specialisation + AT is stable + +// TODO: make S of Feedback an associated type when specialisation + AT is stable pub mod map; pub use map::*; diff --git a/libafl/src/fuzzer/mod.rs b/libafl/src/fuzzer/mod.rs index 2640d62564..7784bf8604 100644 --- a/libafl/src/fuzzer/mod.rs +++ b/libafl/src/fuzzer/mod.rs @@ -731,7 +731,7 @@ pub mod pybind { use pyo3::prelude::*; use crate::{ - bolts::ownedref::OwnedPtrMut, + bolts::ownedref::OwnedMutPtr, events::pybind::PythonEventManager, executors::pybind::PythonExecutor, feedbacks::pybind::PythonFeedback, @@ -756,13 +756,13 @@ pub mod pybind { #[derive(Debug)] pub struct PythonStdFuzzerWrapper { /// Rust wrapped StdFuzzer object - pub inner: OwnedPtrMut, + pub inner: OwnedMutPtr, } impl PythonStdFuzzerWrapper { pub fn wrap(r: &mut PythonStdFuzzer) -> Self { Self { - inner: OwnedPtrMut::Ptr(r), + inner: OwnedMutPtr::Ptr(r), } } @@ -781,7 +781,7 @@ pub mod pybind { #[new] fn new(py_feedback: PythonFeedback, py_objective: PythonFeedback) -> Self { Self { - inner: OwnedPtrMut::Owned(Box::new(StdFuzzer::new( + inner: OwnedMutPtr::Owned(Box::new(StdFuzzer::new( QueueScheduler::new(), py_feedback, py_objective, diff --git a/libafl/src/monitors/prometheus.rs b/libafl/src/monitors/prometheus.rs index 2d5196c076..b0db0114f0 100644 --- a/libafl/src/monitors/prometheus.rs +++ b/libafl/src/monitors/prometheus.rs @@ -9,12 +9,16 @@ // == how to use it === // This monitor should plug into any fuzzer similar to other monitors. // In your fuzzer, include: +// ```rust,ignore // use libafl::monitors::PrometheusMonitor; +// ``` // as well as: +// ```rust,ignore // let listener = "127.0.0.1:8080".to_string(); // point prometheus to scrape here in your prometheus.yml -// let mon = PrometheusMonitor::new(listener, |s| println!("{}", s)); +// let mon = PrometheusMonitor::new(listener, |s| println!("{s}")); // and then like with any other monitor, pass it into the event manager like so: // let mut mgr = SimpleEventManager::new(mon); +// ``` // When using docker, you may need to point prometheus.yml to the docker0 interface or host.docker.internal // ==================== diff --git a/libafl/src/mutators/token_mutations.rs b/libafl/src/mutators/token_mutations.rs index 7b17ecb032..a875c547b1 100644 --- a/libafl/src/mutators/token_mutations.rs +++ b/libafl/src/mutators/token_mutations.rs @@ -106,7 +106,10 @@ impl Tokens { /// The caller must ensure that the region between `token_start` and `token_stop` /// is a valid region, containing autotokens in the exepcted format. #[cfg(any(target_os = "linux", target_vendor = "apple"))] - pub unsafe fn from_ptrs(token_start: *const u8, token_stop: *const u8) -> Result { + pub unsafe fn from_mut_ptrs( + token_start: *const u8, + token_stop: *const u8, + ) -> Result { let mut ret = Self::default(); if token_start.is_null() || token_stop.is_null() { return Ok(Self::new()); diff --git a/libafl/src/observers/map.rs b/libafl/src/observers/map.rs index 3a535ed5fc..21c7de4682 100644 --- a/libafl/src/observers/map.rs +++ b/libafl/src/observers/map.rs @@ -19,7 +19,7 @@ use serde::{Deserialize, Serialize}; use crate::{ bolts::{ - ownedref::{OwnedRefMut, OwnedSliceMut}, + ownedref::{OwnedMutPtr, OwnedMutSlice}, tuples::Named, AsIter, AsIterMut, AsMutSlice, AsSlice, HasLen, }, @@ -192,7 +192,7 @@ pub struct StdMapObserver<'a, T, const DIFFERENTIAL: bool> where T: Default + Copy + 'static + Serialize, { - map: OwnedSliceMut<'a, T>, + map: OwnedMutSlice<'a, T>, initial: T, name: String, } @@ -444,14 +444,29 @@ where T: Default + Copy + 'static + Serialize + serde::de::DeserializeOwned, { /// Creates a new [`MapObserver`] + /// + /// # Safety + /// Will get a pointer to the map and dereference it at any point in time. + /// The map must not move in memory! #[must_use] - fn maybe_differential(name: S, map: &'a mut [T]) -> Self + unsafe fn maybe_differential(name: S, map: &'a mut [T]) -> Self where S: Into, { - Self { - map: OwnedSliceMut::from(map), + let len = map.len(); + let ptr = map.as_mut_ptr(); + Self::maybe_differential_from_mut_ptr(name, ptr, len) + } + + /// Creates a new [`MapObserver`] from an [`OwnedMutSlice`] + #[must_use] + fn maybe_differential_from_mut_slice(name: S, map: OwnedMutSlice<'a, T>) -> Self + where + S: Into, + { + StdMapObserver { name: name.into(), + map, initial: T::default(), } } @@ -463,18 +478,18 @@ where S: Into, { Self { - map: OwnedSliceMut::from(map), + map: OwnedMutSlice::from(map), name: name.into(), initial: T::default(), } } - /// Creates a new [`MapObserver`] from an [`OwnedSliceMut`] map. + /// Creates a new [`MapObserver`] from an [`OwnedMutSlice`] map. /// /// # Safety /// Will dereference the owned slice with up to len elements. #[must_use] - fn maybe_differential_from_ownedref(name: S, map: OwnedSliceMut<'a, T>) -> Self + fn maybe_differential_from_ownedref(name: S, map: OwnedMutSlice<'a, T>) -> Self where S: Into, { @@ -489,24 +504,23 @@ where /// /// # Safety /// Will dereference the `map_ptr` with up to len elements. - unsafe fn maybe_differential_from_ptr(name: S, map_ptr: *mut T, len: usize) -> Self + unsafe fn maybe_differential_from_mut_ptr(name: S, map_ptr: *mut T, len: usize) -> Self where S: Into, { - StdMapObserver { - map: OwnedSliceMut::from_raw_parts_mut(map_ptr, len), - name: name.into(), - initial: T::default(), - } + Self::maybe_differential_from_mut_slice( + name, + OwnedMutSlice::from_raw_parts_mut(map_ptr, len), + ) } /// Gets the backing for this map - pub fn map(&self) -> &OwnedSliceMut<'a, T> { + pub fn map(&self) -> &OwnedMutSlice<'a, T> { &self.map } /// Gets the backing for this map mutably - pub fn map_mut(&mut self) -> &mut OwnedSliceMut<'a, T> { + pub fn map_mut(&mut self) -> &mut OwnedMutSlice<'a, T> { &mut self.map } } @@ -516,14 +530,26 @@ where T: Default + Copy + 'static + Serialize + serde::de::DeserializeOwned, { /// Creates a new [`MapObserver`] + /// + /// # Safety + /// The observer will keep a pointer to the map. + /// Hence, the map may never move in memory. #[must_use] - pub fn new(name: S, map: &'a mut [T]) -> Self + pub unsafe fn new(name: S, map: &'a mut [T]) -> Self where S: Into, { Self::maybe_differential(name, map) } + /// Creates a new [`MapObserver`] from an [`OwnedMutSlice`] + pub fn from_mut_slice(name: S, map: OwnedMutSlice<'a, T>) -> Self + where + S: Into, + { + Self::maybe_differential_from_mut_slice(name, map) + } + /// Creates a new [`MapObserver`] with an owned map #[must_use] pub fn new_owned(name: S, map: Vec) -> Self @@ -533,12 +559,12 @@ where Self::maybe_differential_owned(name, map) } - /// Creates a new [`MapObserver`] from an [`OwnedSliceMut`] map. + /// Creates a new [`MapObserver`] from an [`OwnedMutSlice`] map. /// /// # Note /// Will dereference the owned slice with up to len elements. #[must_use] - pub fn new_from_ownedref(name: S, map: OwnedSliceMut<'a, T>) -> Self + pub fn from_ownedref(name: S, map: OwnedMutSlice<'a, T>) -> Self where S: Into, { @@ -549,11 +575,11 @@ where /// /// # Safety /// Will dereference the `map_ptr` with up to len elements. - pub unsafe fn new_from_ptr(name: S, map_ptr: *mut T, len: usize) -> Self + pub unsafe fn from_mut_ptr(name: S, map_ptr: *mut T, len: usize) -> Self where S: Into, { - Self::maybe_differential_from_ptr(name, map_ptr, len) + Self::maybe_differential_from_mut_ptr(name, map_ptr, len) } } @@ -562,8 +588,12 @@ where T: Default + Copy + 'static + Serialize + serde::de::DeserializeOwned, { /// Creates a new [`MapObserver`] in differential mode + /// + /// # Safety + /// Will get a pointer to the map and dereference it at any point in time. + /// The map must not move in memory! #[must_use] - pub fn differential(name: S, map: &'a mut [T]) -> Self + pub unsafe fn differential(name: S, map: &'a mut [T]) -> Self where S: Into, { @@ -579,12 +609,12 @@ where Self::maybe_differential_owned(name, map) } - /// Creates a new [`MapObserver`] from an [`OwnedSliceMut`] map in differential mode. + /// Creates a new [`MapObserver`] from an [`OwnedMutSlice`] map in differential mode. /// /// # Note /// Will dereference the owned slice with up to len elements. #[must_use] - pub fn differential_from_ownedref(name: S, map: OwnedSliceMut<'a, T>) -> Self + pub fn differential_from_ownedref(name: S, map: OwnedMutSlice<'a, T>) -> Self where S: Into, { @@ -595,11 +625,11 @@ where /// /// # Safety /// Will dereference the `map_ptr` with up to len elements. - pub unsafe fn differential_from_ptr(name: S, map_ptr: *mut T, len: usize) -> Self + pub unsafe fn differential_from_mut_ptr(name: S, map_ptr: *mut T, len: usize) -> Self where S: Into, { - Self::maybe_differential_from_ptr(name, map_ptr, len) + Self::maybe_differential_from_mut_ptr(name, map_ptr, len) } } @@ -628,7 +658,7 @@ pub struct ConstMapObserver<'a, T, const N: usize> where T: Default + Copy + 'static + Serialize, { - map: OwnedSliceMut<'a, T>, + map: OwnedMutSlice<'a, T>, initial: T, name: String, } @@ -853,11 +883,15 @@ where T: Default + Copy + 'static + Serialize + serde::de::DeserializeOwned, { /// Creates a new [`MapObserver`] + /// + /// # Safety + /// Will get a pointer to the map and dereference it at any point in time. + /// The map must not move in memory! #[must_use] pub fn new(name: &'static str, map: &'a mut [T]) -> Self { assert!(map.len() >= N); Self { - map: OwnedSliceMut::from(map), + map: OwnedMutSlice::from(map), name: name.to_string(), initial: T::default(), } @@ -869,7 +903,7 @@ where assert!(map.len() >= N); let initial = if map.is_empty() { T::default() } else { map[0] }; Self { - map: OwnedSliceMut::from(map), + map: OwnedMutSlice::from(map), name: name.to_string(), initial, } @@ -879,9 +913,9 @@ where /// /// # Safety /// Will dereference the `map_ptr` with up to len elements. - pub unsafe fn new_from_ptr(name: &'static str, map_ptr: *mut T) -> Self { + pub unsafe fn from_mut_ptr(name: &'static str, map_ptr: *mut T) -> Self { ConstMapObserver { - map: OwnedSliceMut::from_raw_parts_mut(map_ptr, N), + map: OwnedMutSlice::from_raw_parts_mut(map_ptr, N), name: name.to_string(), initial: T::default(), } @@ -896,8 +930,8 @@ pub struct VariableMapObserver<'a, T> where T: Default + Copy + 'static + Serialize, { - map: OwnedSliceMut<'a, T>, - size: OwnedRefMut<'a, usize>, + map: OwnedMutSlice<'a, T>, + size: OwnedMutPtr, initial: T, name: String, } @@ -1126,12 +1160,20 @@ impl<'a, T> VariableMapObserver<'a, T> where T: Default + Copy + 'static + Serialize + serde::de::DeserializeOwned, { - /// Creates a new [`MapObserver`] - pub fn new(name: &'static str, map: &'a mut [T], size: &'a mut usize) -> Self { - Self { - map: OwnedSliceMut::from(map), - size: OwnedRefMut::Ref(size), + /// Creates a new [`MapObserver`] from an [`OwnedMutSlice`] + /// + /// # Safety + /// The observer will dereference the owned slice, as well as the `map_ptr`. + /// Dereferences `map_ptr` with up to `max_len` elements of size. + pub unsafe fn from_mut_slice( + name: &'static str, + map_slice: OwnedMutSlice<'a, T>, + size: *mut usize, + ) -> Self { + VariableMapObserver { name: name.into(), + map: map_slice, + size: OwnedMutPtr::Ptr(size), initial: T::default(), } } @@ -1139,19 +1181,19 @@ where /// Creates a new [`MapObserver`] from a raw pointer /// /// # Safety + /// The observer will dereference the `size` ptr, as well as the `map_ptr`. /// Dereferences `map_ptr` with up to `max_len` elements of size. - pub unsafe fn new_from_ptr( + pub unsafe fn from_mut_ptr( name: &'static str, map_ptr: *mut T, max_len: usize, - size: &'a mut usize, + size: *mut usize, ) -> Self { - VariableMapObserver { - map: OwnedSliceMut::from_raw_parts_mut(map_ptr, max_len), - size: OwnedRefMut::Ref(size), - name: name.into(), - initial: T::default(), - } + Self::from_mut_slice( + name, + OwnedMutSlice::from_raw_parts_mut(map_ptr, max_len), + size, + ) } } @@ -1618,7 +1660,7 @@ pub struct MultiMapObserver<'a, T, const DIFFERENTIAL: bool> where T: Default + Copy + 'static + Serialize + Debug, { - maps: Vec>, + maps: Vec>, intervals: IntervalTree, len: usize, initial: T, @@ -1782,7 +1824,7 @@ where idx += l; builder.push(r); v += 1; - OwnedSliceMut::from(x) + OwnedMutSlice::from(x) }) .collect(); Self { @@ -1831,7 +1873,7 @@ where idx += l; builder.push(r); v += 1; - OwnedSliceMut::from(x) + OwnedMutSlice::from(x) }) .collect(); Self { @@ -1851,7 +1893,7 @@ where 'a: 'it, { type Item = T; - type IntoIter = Flatten>>; + type IntoIter = Flatten>>; fn as_iter(&'it self) -> Self::IntoIter { self.maps.iter().flatten() @@ -1864,7 +1906,7 @@ where 'a: 'it, { type Item = T; - type IntoIter = Flatten>>; + type IntoIter = Flatten>>; fn as_iter_mut(&'it mut self) -> Self::IntoIter { self.maps.iter_mut().flatten() @@ -1877,7 +1919,7 @@ where T: Default + Copy + 'static + Serialize + serde::de::DeserializeOwned + Debug, { type Item = as Iterator>::Item; - type IntoIter = Flatten>>; + type IntoIter = Flatten>>; fn into_iter(self) -> Self::IntoIter { self.maps.iter().flatten() @@ -1890,7 +1932,7 @@ where T: Default + Copy + 'static + Serialize + serde::de::DeserializeOwned + Debug, { type Item = as Iterator>::Item; - type IntoIter = Flatten>>; + type IntoIter = Flatten>>; fn into_iter(self) -> Self::IntoIter { self.maps.iter_mut().flatten() @@ -2195,7 +2237,7 @@ pub mod pybind { #[new] fn new(name: String, ptr: usize, size: usize) -> Self { Self { - inner: unsafe { StdMapObserver::new_from_ptr(name, ptr as *mut $datatype, size) } + inner: unsafe { StdMapObserver::from_mut_ptr(name, ptr as *mut $datatype, size) } } } diff --git a/libafl/src/observers/mod.rs b/libafl/src/observers/mod.rs index d94d0d1ddb..fbe23387b9 100644 --- a/libafl/src/observers/mod.rs +++ b/libafl/src/observers/mod.rs @@ -36,7 +36,7 @@ pub use value::*; use crate::{ bolts::{ current_time, - ownedref::OwnedRefMut, + ownedref::OwnedMutPtr, tuples::{MatchName, Named}, }, executors::ExitKind, @@ -475,25 +475,30 @@ where /// A simple observer with a list of things. #[derive(Serialize, Deserialize, Debug)] #[serde(bound = "T: serde::de::DeserializeOwned")] -pub struct ListObserver<'a, T> +#[allow(clippy::unsafe_derive_deserialize)] +pub struct ListObserver where T: Debug + Serialize, { name: String, /// The list - list: OwnedRefMut<'a, Vec>, + list: OwnedMutPtr>, } -impl<'a, T> ListObserver<'a, T> +impl ListObserver where T: Debug + Serialize + serde::de::DeserializeOwned, { /// Creates a new [`ListObserver`] with the given name. + /// + /// # Safety + /// Will dereference the list. + /// The list may not move in memory. #[must_use] - pub fn new(name: &'static str, list: &'a mut Vec) -> Self { + pub unsafe fn new(name: &'static str, list: *mut Vec) -> Self { Self { name: name.to_string(), - list: OwnedRefMut::Ref(list), + list: OwnedMutPtr::Ptr(list), } } @@ -510,7 +515,7 @@ where } } -impl<'a, S, T> Observer for ListObserver<'a, T> +impl Observer for ListObserver where S: UsesInput, T: Debug + Serialize + serde::de::DeserializeOwned, @@ -521,7 +526,7 @@ where } } -impl<'a, T> Named for ListObserver<'a, T> +impl Named for ListObserver where T: Debug + Serialize + serde::de::DeserializeOwned, { @@ -1331,10 +1336,9 @@ mod tests { #[test] fn test_observer_serde() { - let obv = tuple_list!( - TimeObserver::new("time"), - StdMapObserver::new("map", unsafe { &mut MAP }) - ); + let obv = tuple_list!(TimeObserver::new("time"), unsafe { + StdMapObserver::new("map", &mut MAP) + }); let vec = postcard::to_allocvec(&obv).unwrap(); println!("{vec:?}"); let obv2: tuple_list_type!(TimeObserver, StdMapObserver) = diff --git a/libafl/src/state/mod.rs b/libafl/src/state/mod.rs index 1a91e1c5ab..8d2cee07f5 100644 --- a/libafl/src/state/mod.rs +++ b/libafl/src/state/mod.rs @@ -689,7 +689,7 @@ pub mod pybind { use pyo3::{prelude::*, types::PyDict}; use crate::{ - bolts::{ownedref::OwnedPtrMut, rands::pybind::PythonRand}, + bolts::{ownedref::OwnedMutPtr, rands::pybind::PythonRand}, corpus::pybind::PythonCorpus, events::pybind::PythonEventManager, executors::pybind::PythonExecutor, @@ -711,13 +711,13 @@ pub mod pybind { /// Python class for StdState pub struct PythonStdStateWrapper { /// Rust wrapped StdState object - pub inner: OwnedPtrMut, + pub inner: OwnedMutPtr, } impl PythonStdStateWrapper { pub fn wrap(r: &mut PythonStdState) -> Self { Self { - inner: OwnedPtrMut::Ptr(r), + inner: OwnedMutPtr::Ptr(r), } } @@ -742,7 +742,7 @@ pub mod pybind { objective: &mut PythonFeedback, ) -> Self { Self { - inner: OwnedPtrMut::Owned(Box::new( + inner: OwnedMutPtr::Owned(Box::new( StdState::new(py_rand, corpus, solutions, feedback, objective) .expect("Failed to create a new StdState"), )), diff --git a/libafl_frida/src/asan/errors.rs b/libafl_frida/src/asan/errors.rs index 00b6a8593c..031ba71673 100644 --- a/libafl_frida/src/asan/errors.rs +++ b/libafl_frida/src/asan/errors.rs @@ -586,7 +586,7 @@ impl AsanErrorsObserver { /// Creates a new `AsanErrorsObserver` from a raw ptr #[must_use] - pub fn new_from_ptr(errors: *const Option) -> Self { + pub fn from_mut_ptr(errors: *const Option) -> Self { Self { errors: OwnedPtr::Ptr(errors), } diff --git a/libafl_frida/src/coverage_rt.rs b/libafl_frida/src/coverage_rt.rs index d8ccad843b..245426c2ed 100644 --- a/libafl_frida/src/coverage_rt.rs +++ b/libafl_frida/src/coverage_rt.rs @@ -82,7 +82,7 @@ impl CoverageRuntime { } /// Retrieve the coverage map pointer - pub fn map_ptr_mut(&mut self) -> *mut u8 { + pub fn map_mut_ptr(&mut self) -> *mut u8 { self.0.borrow_mut().map.as_mut_ptr() } diff --git a/libafl_frida/src/helper.rs b/libafl_frida/src/helper.rs index 687db09a2f..0b92d931b8 100644 --- a/libafl_frida/src/helper.rs +++ b/libafl_frida/src/helper.rs @@ -404,9 +404,9 @@ where } /// Pointer to coverage map - pub fn map_ptr_mut(&mut self) -> Option<*mut u8> { + pub fn map_mut_ptr(&mut self) -> Option<*mut u8> { self.runtime_mut::() - .map(CoverageRuntime::map_ptr_mut) + .map(CoverageRuntime::map_mut_ptr) } /// Ranges diff --git a/libafl_qemu/src/cmplog.rs b/libafl_qemu/src/cmplog.rs index c2867c5924..84d6fc8cea 100644 --- a/libafl_qemu/src/cmplog.rs +++ b/libafl_qemu/src/cmplog.rs @@ -1,8 +1,8 @@ use hashbrown::HashMap; use libafl::{inputs::UsesInput, state::HasMetadata}; pub use libafl_targets::{ - cmplog::__libafl_targets_cmplog_instructions, CmpLogMap, CmpLogObserver, CMPLOG_MAP, - CMPLOG_MAP_H, CMPLOG_MAP_PTR, CMPLOG_MAP_SIZE, CMPLOG_MAP_W, + cmplog::__libafl_targets_cmplog_instructions, CmpLogMap, CmpLogObserver, CMPLOG_MAP_H, + CMPLOG_MAP_PTR, CMPLOG_MAP_SIZE, CMPLOG_MAP_W, }; use serde::{Deserialize, Serialize}; diff --git a/libafl_qemu/src/edges.rs b/libafl_qemu/src/edges.rs index ff6992df24..1bac924c1a 100644 --- a/libafl_qemu/src/edges.rs +++ b/libafl_qemu/src/edges.rs @@ -3,7 +3,8 @@ use std::{cell::UnsafeCell, cmp::max}; use hashbrown::{hash_map::Entry, HashMap}; use libafl::{inputs::UsesInput, state::HasMetadata}; pub use libafl_targets::{ - edges_max_num, EDGES_MAP, EDGES_MAP_PTR, EDGES_MAP_PTR_SIZE, EDGES_MAP_SIZE, MAX_EDGES_NUM, + edges_map_mut_slice, edges_max_num, EDGES_MAP, EDGES_MAP_PTR, EDGES_MAP_PTR_NUM, + EDGES_MAP_SIZE, MAX_EDGES_NUM, }; use serde::{Deserialize, Serialize}; @@ -229,7 +230,7 @@ where } // GuestAddress is u32 for 32 bit guests #[allow(clippy::unnecessary_cast)] - Some((hash_me(src as u64) ^ hash_me(dest as u64)) & (unsafe { EDGES_MAP_PTR_SIZE } as u64 - 1)) + Some((hash_me(src as u64) ^ hash_me(dest as u64)) & (unsafe { EDGES_MAP_PTR_NUM } as u64 - 1)) } pub extern "C" fn trace_edge_hitcount_ptr(id: u64, _data: u64) { @@ -277,7 +278,7 @@ where pub extern "C" fn trace_block_transition_hitcount(id: u64, _data: u64) { unsafe { PREV_LOC.with(|prev_loc| { - let x = ((*prev_loc.get() ^ id) as usize) & (EDGES_MAP_PTR_SIZE - 1); + let x = ((*prev_loc.get() ^ id) as usize) & (EDGES_MAP_PTR_NUM - 1); let entry = EDGES_MAP_PTR.add(x); *entry = (*entry).wrapping_add(1); *prev_loc.get() = id.overflowing_shr(1).0; @@ -288,7 +289,7 @@ pub extern "C" fn trace_block_transition_hitcount(id: u64, _data: u64) { pub extern "C" fn trace_block_transition_single(id: u64, _data: u64) { unsafe { PREV_LOC.with(|prev_loc| { - let x = ((*prev_loc.get() ^ id) as usize) & (EDGES_MAP_PTR_SIZE - 1); + let x = ((*prev_loc.get() ^ id) as usize) & (EDGES_MAP_PTR_NUM - 1); let entry = EDGES_MAP_PTR.add(x); *entry = 1; *prev_loc.get() = id.overflowing_shr(1).0; diff --git a/libafl_sugar/src/forkserver.rs b/libafl_sugar/src/forkserver.rs index 1942e1724f..7c9327c421 100644 --- a/libafl_sugar/src/forkserver.rs +++ b/libafl_sugar/src/forkserver.rs @@ -123,7 +123,7 @@ impl<'a, const MAP_SIZE: usize> ForkserverBytesCoverageSugar<'a, MAP_SIZE> { // Create an observation channel using the coverage map let edges_observer = unsafe { - HitcountsMapObserver::new(ConstMapObserver::<_, MAP_SIZE>::new_from_ptr( + HitcountsMapObserver::new(ConstMapObserver::<_, MAP_SIZE>::from_mut_ptr( "shared_mem", shmem_map.as_mut_ptr(), )) diff --git a/libafl_sugar/src/inmemory.rs b/libafl_sugar/src/inmemory.rs index 894bfd8b4f..b81d06bc14 100644 --- a/libafl_sugar/src/inmemory.rs +++ b/libafl_sugar/src/inmemory.rs @@ -27,13 +27,13 @@ use libafl::{ scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, token_mutations::{I2SRandReplace, Tokens}, }, - observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, + observers::{HitcountsMapObserver, TimeObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::{ShadowTracingStage, StdMutationalStage}, state::{HasCorpus, HasMetadata, StdState}, Error, }; -use libafl_targets::{CmpLogObserver, CMPLOG_MAP, EDGES_MAP, MAX_EDGES_NUM}; +use libafl_targets::{std_edges_map_observer, CmpLogObserver}; use typed_builder::TypedBuilder; use crate::{CORPUS_CACHE_SIZE, DEFAULT_TIMEOUT_SECS}; @@ -143,14 +143,13 @@ where mut mgr: LlmpRestartingEventManager<_, _>, _core_id| { // Create an observation channel using the coverage map - let edges = unsafe { &mut EDGES_MAP[0..MAX_EDGES_NUM] }; - let edges_observer = HitcountsMapObserver::new(StdMapObserver::new("edges", edges)); + let edges_observer = + HitcountsMapObserver::new(unsafe { std_edges_map_observer("edges") }); // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); - let cmplog = unsafe { &mut CMPLOG_MAP }; - let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); // Feedback to rate the interestingness of an input // This one is composed by two Feedbacks in OR diff --git a/libafl_sugar/src/qemu.rs b/libafl_sugar/src/qemu.rs index faab0482fb..b331fa1d6a 100644 --- a/libafl_sugar/src/qemu.rs +++ b/libafl_sugar/src/qemu.rs @@ -1,6 +1,9 @@ //! In-memory fuzzer with `QEMU`-based binary-only instrumentation //! -use core::fmt::{self, Debug, Formatter}; +use core::{ + fmt::{self, Debug, Formatter}, + ptr::addr_of_mut, +}; use std::{fs, net::SocketAddr, path::PathBuf, time::Duration}; use libafl::{ @@ -33,10 +36,8 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, }; pub use libafl_qemu::emu::Emulator; -use libafl_qemu::{ - cmplog, edges, QemuCmpLogHelper, QemuEdgeCoverageHelper, QemuExecutor, QemuHooks, -}; -use libafl_targets::CmpLogObserver; +use libafl_qemu::{edges, QemuCmpLogHelper, QemuEdgeCoverageHelper, QemuExecutor, QemuHooks}; +use libafl_targets::{edges_map_mut_slice, CmpLogObserver}; use typed_builder::TypedBuilder; use crate::{CORPUS_CACHE_SIZE, DEFAULT_TIMEOUT_SECS}; @@ -147,17 +148,19 @@ where mut mgr: LlmpRestartingEventManager<_, _>, _core_id| { // Create an observation channel using the coverage map - let edges = unsafe { &mut edges::EDGES_MAP }; - let edges_counter = unsafe { &mut edges::MAX_EDGES_NUM }; - let edges_observer = - HitcountsMapObserver::new(VariableMapObserver::new("edges", edges, edges_counter)); + let edges_observer = unsafe { + HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( + "edges", + edges_map_mut_slice(), + addr_of_mut!(edges::MAX_EDGES_NUM), + )) + }; // Create an observation channel to keep track of the execution time let time_observer = TimeObserver::new("time"); // Keep tracks of CMPs - let cmplog = unsafe { &mut cmplog::CMPLOG_MAP }; - let cmplog_observer = CmpLogObserver::new("cmplog", cmplog, true); + let cmplog_observer = CmpLogObserver::new("cmplog", true); // Feedback to rate the interestingness of an input // This one is composed by two Feedbacks in OR diff --git a/libafl_targets/src/cmplog.rs b/libafl_targets/src/cmplog.rs index dee1162105..8558087654 100644 --- a/libafl_targets/src/cmplog.rs +++ b/libafl_targets/src/cmplog.rs @@ -6,7 +6,7 @@ use alloc::string::{String, ToString}; use core::fmt::{self, Debug, Formatter}; use libafl::{ - bolts::{ownedref::OwnedRefMut, tuples::Named}, + bolts::{ownedref::OwnedMutPtr, tuples::Named}, executors::ExitKind, inputs::UsesInput, observers::{CmpMap, CmpObserver, CmpValues, Observer}, @@ -178,14 +178,14 @@ pub use libafl_cmplog_enabled as CMPLOG_ENABLED; /// A [`CmpObserver`] observer for `CmpLog` #[derive(Debug)] -pub struct CmpLogObserver<'a> { - map: OwnedRefMut<'a, CmpLogMap>, - size: Option>, +pub struct CmpLogObserver { + map: OwnedMutPtr, + size: Option>, add_meta: bool, name: String, } -impl<'a, S> CmpObserver for CmpLogObserver<'a> +impl CmpObserver for CmpLogObserver where S: UsesInput + HasMetadata, { @@ -206,7 +206,7 @@ where } } -impl<'a, S> Observer for CmpLogObserver<'a> +impl Observer for CmpLogObserver where S: UsesInput + HasMetadata, Self: CmpObserver, @@ -235,23 +235,32 @@ where } } -impl<'a> Named for CmpLogObserver<'a> { +impl Named for CmpLogObserver { fn name(&self) -> &str { &self.name } } -impl<'a> CmpLogObserver<'a> { - /// Creates a new [`CmpLogObserver`] with the given name. +impl CmpLogObserver { + /// Creates a new [`CmpLogObserver`] with the given map and name. + /// + /// # Safety + /// Will keep a ptr to the map. The map may not move in memory! #[must_use] - pub fn new(name: &'static str, map: &'a mut CmpLogMap, add_meta: bool) -> Self { + pub unsafe fn with_map_ptr(name: &'static str, map: *mut CmpLogMap, add_meta: bool) -> Self { Self { name: name.to_string(), size: None, add_meta, - map: OwnedRefMut::Ref(map), + map: OwnedMutPtr::Ptr(map), } } + /// Creates a new [`CmpLogObserver`] with the given name from the default [`CMPLOG_MAP`] + #[must_use] + pub fn new(name: &'static str, add_meta: bool) -> Self { + unsafe { Self::with_map_ptr(name, libafl_cmplog_map_ptr, add_meta) } + } + // TODO with_size } diff --git a/libafl_targets/src/coverage.rs b/libafl_targets/src/coverage.rs index 9b69115286..47c741d744 100644 --- a/libafl_targets/src/coverage.rs +++ b/libafl_targets/src/coverage.rs @@ -1,5 +1,7 @@ //! Coverage maps as static mut array +use alloc::string::String; + #[cfg(any(target_os = "linux", target_vendor = "apple"))] use libafl::{mutators::Tokens, Error}; @@ -44,7 +46,7 @@ pub fn autotokens() -> Result { Ok(Tokens::default()) } else { // we can safely unwrap - Tokens::from_ptrs(__token_start, __token_stop) + Tokens::from_mut_ptrs(__token_start, __token_stop) } } } @@ -52,19 +54,68 @@ pub fn autotokens() -> Result { /// The size of the map for edges. #[no_mangle] pub static mut __afl_map_size: usize = EDGES_MAP_SIZE; -pub use __afl_map_size as EDGES_MAP_PTR_SIZE; -use libafl::bolts::ownedref::OwnedSliceMut; +pub use __afl_map_size as EDGES_MAP_PTR_NUM; +use libafl::{bolts::ownedref::OwnedMutSlice, observers::StdMapObserver}; /// Gets the edges map from the `EDGES_MAP_PTR` raw pointer. +/// Assumes a `len` of `EDGES_MAP_PTR_NUM`. /// /// # Safety /// -/// This function will crash if `EDGES_MAP_PTR` is not a valid pointer. -/// The `EDGES_MAP_PTR_SIZE` needs to be smaller than, or equal to the size of the map. +/// This function will crash if `edges_map_mut_ptr` is not a valid pointer. +/// The [`edges_max_num`] needs to be smaller than, or equal to the size of the map. #[must_use] -pub unsafe fn edges_map_from_ptr<'a>() -> OwnedSliceMut<'a, u8> { - debug_assert!(!EDGES_MAP_PTR.is_null()); - OwnedSliceMut::from_raw_parts_mut(EDGES_MAP_PTR, EDGES_MAP_PTR_SIZE) +pub unsafe fn edges_map_mut_slice<'a>() -> OwnedMutSlice<'a, u8> { + OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), edges_max_num()) +} + +/// Gets a new [`StdMapObserver`] from the current [`edges_map_mut_slice`]. +/// This is roughly equivalent to running: +/// +/// ```rust,ignore +/// use libafl::observers::StdMapObserver; +/// use libafl_targets::{EDGES_MAP, MAX_EDGES_NUM}; +/// +/// #[cfg(not(feature = "pointer_maps"))] +/// let observer = unsafe { +/// StdMapObserver::from_mut_ptr("edges", EDGES_MAP.as_mut_ptr(), MAX_EDGES_NUM) +/// }; +/// ``` +/// +/// or, for the `pointer_maps` feature: +/// +/// ```rust,ignore +/// use libafl::observers::StdMapObserver; +/// use libafl_targets::{EDGES_MAP_PTR, EDGES_MAP_PTR_NUM}; +/// +/// #[cfg(feature = "pointer_maps")] +/// let observer = unsafe { +/// StdMapObserver::from_mut_ptr("edges", EDGES_MAP_PTR, EDGES_MAP_PTR_NUM) +/// }; +/// ``` +/// +/// # Safety +/// This will dereference [`edges_map_mut_ptr`] and crash if it is not a valid address. +pub unsafe fn std_edges_map_observer<'a, S>(name: S) -> StdMapObserver<'a, u8, false> +where + S: Into, +{ + StdMapObserver::from_mut_slice(name, edges_map_mut_slice()) +} + +/// Gets the current edges map pt +/// It will usually take `EDGES_MAP`, but `EDGES_MAP_PTR`, +/// if built with the `pointer_maps` feature. +#[must_use] +pub fn edges_map_mut_ptr() -> *mut u8 { + unsafe { + if cfg!(feature = "pointer_maps") { + assert!(!EDGES_MAP_PTR.is_null()); + EDGES_MAP_PTR + } else { + EDGES_MAP.as_mut_ptr() + } + } } /// Gets the current maximum number of edges tracked. @@ -76,7 +127,7 @@ pub fn edges_max_num() -> usize { } else { #[cfg(feature = "pointer_maps")] { - EDGES_MAP_PTR_SIZE + EDGES_MAP_PTR_NUM } #[cfg(not(feature = "pointer_maps"))] { @@ -95,14 +146,14 @@ mod swap { use core::fmt::Debug; use libafl::{ - bolts::{ownedref::OwnedSliceMut, tuples::Named, AsMutSlice}, + bolts::{ownedref::OwnedMutSlice, tuples::Named, AsMutSlice}, inputs::UsesInput, observers::{DifferentialObserver, Observer, ObserversTuple, StdMapObserver}, Error, }; use serde::{Deserialize, Serialize}; - use super::{EDGES_MAP_PTR, EDGES_MAP_PTR_SIZE}; + use super::{EDGES_MAP_PTR, EDGES_MAP_PTR_NUM}; /// Observer to be used with `DiffExecutor`s when executing a differential target that shares /// the AFL map in order to swap out the maps (and thus allow for map observing the two targets @@ -110,8 +161,8 @@ mod swap { #[allow(clippy::unsafe_derive_deserialize)] #[derive(Debug, Serialize, Deserialize)] pub struct DifferentialAFLMapSwapObserver<'a, 'b> { - first_map: OwnedSliceMut<'a, u8>, - second_map: OwnedSliceMut<'b, u8>, + first_map: OwnedMutSlice<'a, u8>, + second_map: OwnedMutSlice<'b, u8>, first_name: String, second_name: String, name: String, @@ -129,24 +180,24 @@ mod swap { name: format!("differential_{}_{}", first.name(), second.name()), first_map: unsafe { let slice = first.map_mut().as_mut_slice(); - OwnedSliceMut::from_raw_parts_mut(slice.as_mut_ptr(), slice.len()) + OwnedMutSlice::from_raw_parts_mut(slice.as_mut_ptr(), slice.len()) }, second_map: unsafe { let slice = second.map_mut().as_mut_slice(); - OwnedSliceMut::from_raw_parts_mut(slice.as_mut_ptr(), slice.len()) + OwnedMutSlice::from_raw_parts_mut(slice.as_mut_ptr(), slice.len()) }, } } /// Get the first map #[must_use] - pub fn first_map(&self) -> &OwnedSliceMut<'a, u8> { + pub fn first_map(&self) -> &OwnedMutSlice<'a, u8> { &self.first_map } /// Get the second map #[must_use] - pub fn second_map(&self) -> &OwnedSliceMut<'b, u8> { + pub fn second_map(&self) -> &OwnedMutSlice<'b, u8> { &self.second_map } @@ -182,7 +233,7 @@ mod swap { let slice = self.first_map.as_mut_slice(); unsafe { EDGES_MAP_PTR = slice.as_mut_ptr(); - EDGES_MAP_PTR_SIZE = slice.len(); + EDGES_MAP_PTR_NUM = slice.len(); } Ok(()) } @@ -191,7 +242,7 @@ mod swap { let slice = self.second_map.as_mut_slice(); unsafe { EDGES_MAP_PTR = slice.as_mut_ptr(); - EDGES_MAP_PTR_SIZE = slice.len(); + EDGES_MAP_PTR_NUM = slice.len(); } Ok(()) } diff --git a/libafl_targets/src/sancov_pcguard.rs b/libafl_targets/src/sancov_pcguard.rs index 11236ae5e8..41a4e48964 100644 --- a/libafl_targets/src/sancov_pcguard.rs +++ b/libafl_targets/src/sancov_pcguard.rs @@ -2,7 +2,7 @@ use crate::coverage::{EDGES_MAP, MAX_EDGES_NUM}; #[cfg(feature = "pointer_maps")] -use crate::coverage::{EDGES_MAP_PTR, EDGES_MAP_PTR_SIZE}; +use crate::coverage::{EDGES_MAP_PTR, EDGES_MAP_PTR_NUM}; #[cfg(all(feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts"))] #[cfg(not(any(doc, feature = "clippy")))] @@ -54,7 +54,7 @@ pub unsafe extern "C" fn __sanitizer_cov_trace_pc_guard_init(mut start: *mut u32 #[cfg(feature = "pointer_maps")] if EDGES_MAP_PTR.is_null() { EDGES_MAP_PTR = EDGES_MAP.as_mut_ptr(); - EDGES_MAP_PTR_SIZE = EDGES_MAP.len(); + EDGES_MAP_PTR_NUM = EDGES_MAP.len(); } if start == stop || *start != 0 { @@ -67,7 +67,7 @@ pub unsafe extern "C" fn __sanitizer_cov_trace_pc_guard_init(mut start: *mut u32 #[cfg(feature = "pointer_maps")] { - MAX_EDGES_NUM = MAX_EDGES_NUM.wrapping_add(1) % EDGES_MAP_PTR_SIZE; + MAX_EDGES_NUM = MAX_EDGES_NUM.wrapping_add(1) % EDGES_MAP_PTR_NUM; } #[cfg(not(feature = "pointer_maps"))] {