diff --git a/Cargo.toml b/Cargo.toml index 5857d58b55..88274a9d3d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -92,11 +92,3 @@ lto = true codegen-units = 1 opt-level = 3 debug = true - -[profile.release-abort] -inherits = "release" -lto = true -codegen-units = 1 -opt-level = 3 -debug = true -abort = true diff --git a/fuzzers/baby/baby_fuzzer_custom_executor/src/main.rs b/fuzzers/baby/baby_fuzzer_custom_executor/src/main.rs index aa46efbf03..04b7993c6f 100644 --- a/fuzzers/baby/baby_fuzzer_custom_executor/src/main.rs +++ b/fuzzers/baby/baby_fuzzer_custom_executor/src/main.rs @@ -1,10 +1,6 @@ #[cfg(windows)] use std::ptr::write_volatile; -use std::{ - marker::PhantomData, - path::PathBuf, - ptr::{addr_of, addr_of_mut, write}, -}; +use std::{marker::PhantomData, path::PathBuf, ptr::write}; #[cfg(feature = "tui")] use libafl::monitors::tui::TuiMonitor; @@ -29,8 +25,8 @@ use libafl_bolts::{current_nanos, nonzero, rands::StdRand, tuples::tuple_list, A /// Coverage map with explicit assignments due to the lack of instrumentation static mut SIGNALS: [u8; 16] = [0; 16]; -static mut SIGNALS_PTR: *mut u8 = addr_of_mut!(SIGNALS) as _; -static SIGNALS_LEN: usize = unsafe { (*addr_of!(SIGNALS)).len() }; +static mut SIGNALS_PTR: *mut u8 = &raw mut SIGNALS as _; +static SIGNALS_LEN: usize = unsafe { (*&raw const (SIGNALS)).len() }; /// Assign a signal to the signals map fn signals_set(idx: usize) { diff --git a/fuzzers/baby/baby_fuzzer_unicode/src/main.rs b/fuzzers/baby/baby_fuzzer_unicode/src/main.rs index a3e2cc03d3..77d5772b9d 100644 --- a/fuzzers/baby/baby_fuzzer_unicode/src/main.rs +++ b/fuzzers/baby/baby_fuzzer_unicode/src/main.rs @@ -1,9 +1,6 @@ #[cfg(windows)] use std::ptr::write_volatile; -use std::{ - path::PathBuf, - ptr::{addr_of, addr_of_mut, write}, -}; +use std::{path::PathBuf, ptr::write}; #[cfg(feature = "tui")] use libafl::monitors::tui::TuiMonitor; @@ -27,8 +24,8 @@ use libafl_bolts::{rands::StdRand, tuples::tuple_list, AsSlice}; /// Coverage map with explicit assignments due to the lack of instrumentation static mut SIGNALS: [u8; 64] = [0; 64]; -static mut SIGNALS_PTR: *mut u8 = addr_of_mut!(SIGNALS).cast(); -static mut SIGNALS_LEN: usize = unsafe { (*addr_of!(SIGNALS)).len() }; +static mut SIGNALS_PTR: *mut u8 = (&raw mut SIGNALS).cast(); +static mut SIGNALS_LEN: usize = unsafe { (*&raw const SIGNALS).len() }; /// Assign a signal to the signals map fn signals_set(idx: usize) { diff --git a/fuzzers/binary_only/fuzzbench_qemu/src/fuzzer.rs b/fuzzers/binary_only/fuzzbench_qemu/src/fuzzer.rs index c71620d2f8..5fc1e3dd9d 100644 --- a/fuzzers/binary_only/fuzzbench_qemu/src/fuzzer.rs +++ b/fuzzers/binary_only/fuzzbench_qemu/src/fuzzer.rs @@ -1,6 +1,6 @@ //! A singlethreaded QEMU fuzzer that can auto-restart. -use core::{cell::RefCell, ptr::addr_of_mut, time::Duration}; +use core::{cell::RefCell, time::Duration}; #[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd}; use std::{ @@ -260,7 +260,7 @@ fn fuzz( HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_ALLOCATED_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/fuzzers/binary_only/qemu_launcher/src/instance.rs b/fuzzers/binary_only/qemu_launcher/src/instance.rs index 979fe6bd22..c2d8a943da 100644 --- a/fuzzers/binary_only/qemu_launcher/src/instance.rs +++ b/fuzzers/binary_only/qemu_launcher/src/instance.rs @@ -1,4 +1,4 @@ -use core::{fmt::Debug, ptr::addr_of_mut}; +use core::fmt::Debug; use std::{fs, marker::PhantomData, ops::Range, process, time::Duration}; #[cfg(feature = "simplemgr")] @@ -117,7 +117,7 @@ impl Instance<'_, M> { HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/fuzzers/binary_only/tinyinst_simple/src/main.rs b/fuzzers/binary_only/tinyinst_simple/src/main.rs index 2ca5cf72eb..aa32678f58 100644 --- a/fuzzers/binary_only/tinyinst_simple/src/main.rs +++ b/fuzzers/binary_only/tinyinst_simple/src/main.rs @@ -1,4 +1,4 @@ -use std::{path::PathBuf, ptr::addr_of_mut, time::Duration}; +use std::{path::PathBuf, time::Duration}; use libafl::{ corpus::{CachedOnDiskCorpus, Corpus, OnDiskCorpus, Testcase}, @@ -37,7 +37,7 @@ fn main() { // use file to pass testcases // let args = vec!["test.exe".to_string(), "-f".to_string(), "@@".to_string()]; - let coverage = OwnedMutPtr::Ptr(addr_of_mut!(COVERAGE)); + let coverage = OwnedMutPtr::Ptr(&raw mut COVERAGE); let observer = ListObserver::new("cov", coverage); let mut feedback = ListFeedback::new(&observer); #[cfg(windows)] @@ -69,7 +69,7 @@ fn main() { .persistent("test.exe".to_string(), "fuzz".to_string(), 1, 10000) .timeout(Duration::new(5, 0)) .shmem_provider(&mut shmem_provider) - .coverage_ptr(addr_of_mut!(COVERAGE)) + .coverage_ptr(&raw mut COVERAGE) .build(tuple_list!(observer)) .unwrap(); diff --git a/fuzzers/full_system/qemu_baremetal/src/fuzzer_breakpoint.rs b/fuzzers/full_system/qemu_baremetal/src/fuzzer_breakpoint.rs index d33aac5b5e..f77e91507a 100644 --- a/fuzzers/full_system/qemu_baremetal/src/fuzzer_breakpoint.rs +++ b/fuzzers/full_system/qemu_baremetal/src/fuzzer_breakpoint.rs @@ -1,6 +1,6 @@ //! A fuzzer using qemu in systemmode for binary-only coverage of kernels //! -use core::{ptr::addr_of_mut, time::Duration}; +use core::time::Duration; use std::{env, path::PathBuf, process}; use libafl::{ @@ -97,7 +97,7 @@ pub fn fuzz() { HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/fuzzers/full_system/qemu_baremetal/src/fuzzer_low_level.rs b/fuzzers/full_system/qemu_baremetal/src/fuzzer_low_level.rs index f7f67c22b7..fa2d6bcc31 100644 --- a/fuzzers/full_system/qemu_baremetal/src/fuzzer_low_level.rs +++ b/fuzzers/full_system/qemu_baremetal/src/fuzzer_low_level.rs @@ -1,6 +1,6 @@ //! A fuzzer using qemu in systemmode for binary-only coverage of kernels //! -use core::{ptr::addr_of_mut, time::Duration}; +use core::time::Duration; use std::{env, path::PathBuf, process}; use libafl::{ @@ -88,7 +88,7 @@ pub fn fuzz() { HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/fuzzers/full_system/qemu_baremetal/src/fuzzer_sync_exit.rs b/fuzzers/full_system/qemu_baremetal/src/fuzzer_sync_exit.rs index 082ce8d021..b2f1d2944c 100644 --- a/fuzzers/full_system/qemu_baremetal/src/fuzzer_sync_exit.rs +++ b/fuzzers/full_system/qemu_baremetal/src/fuzzer_sync_exit.rs @@ -1,6 +1,6 @@ //! A fuzzer using qemu in systemmode for binary-only coverage of kernels //! -use core::{ptr::addr_of_mut, time::Duration}; +use core::time::Duration; use std::{env, path::PathBuf, process}; use libafl::{ @@ -52,7 +52,7 @@ pub fn fuzz() { HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/fuzzers/full_system/qemu_linux_kernel/src/fuzzer.rs b/fuzzers/full_system/qemu_linux_kernel/src/fuzzer.rs index 786a3f33e6..ea2735c690 100644 --- a/fuzzers/full_system/qemu_linux_kernel/src/fuzzer.rs +++ b/fuzzers/full_system/qemu_linux_kernel/src/fuzzer.rs @@ -1,6 +1,6 @@ //! A fuzzer using qemu in systemmode for binary-only coverage of linux -use core::{ptr::addr_of_mut, time::Duration}; +use core::time::Duration; use std::{env, path::PathBuf, process}; use libafl::{ @@ -91,7 +91,7 @@ pub fn fuzz() { HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_ALLOCATED_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/fuzzers/full_system/qemu_linux_process/src/fuzzer.rs b/fuzzers/full_system/qemu_linux_process/src/fuzzer.rs index e7f2b519b0..809991c095 100644 --- a/fuzzers/full_system/qemu_linux_process/src/fuzzer.rs +++ b/fuzzers/full_system/qemu_linux_process/src/fuzzer.rs @@ -1,6 +1,6 @@ //! A fuzzer using qemu in systemmode for binary-only coverage of linux -use core::{ptr::addr_of_mut, time::Duration}; +use core::time::Duration; use std::{env, path::PathBuf, process}; use libafl::{ @@ -56,7 +56,7 @@ pub fn fuzz() { HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/fuzzers/fuzz_anything/push_harness/src/main.rs b/fuzzers/fuzz_anything/push_harness/src/main.rs index d4872dfec6..40b744c819 100644 --- a/fuzzers/fuzz_anything/push_harness/src/main.rs +++ b/fuzzers/fuzz_anything/push_harness/src/main.rs @@ -1,6 +1,6 @@ //! [`Klo-routines`](https://github.com/andreafioraldi/klo-routines/) based fuzzer. //! The target loops and the harness pulls inputs out of `LibAFL`, instead of being called by `LibAFL`. -use std::{path::PathBuf, ptr::addr_of_mut}; +use std::path::PathBuf; use klo_routines::{yield_, KloRoutine}; use libafl::{ @@ -39,12 +39,12 @@ fn input_generator() { ExitKind::Ok }; - let signals_ptr = unsafe { addr_of_mut!(SIGNALS) }; + let signals_ptr = unsafe { &raw mut SIGNALS }; let signals_len = unsafe { *signals_ptr }.len(); // Create an observation channel using the signals map let observer = - unsafe { StdMapObserver::from_mut_ptr("signals", addr_of_mut!(SIGNALS) as _, signals_len) }; + unsafe { StdMapObserver::from_mut_ptr("signals", &raw mut SIGNALS as _, signals_len) }; // Feedback to rate the interestingness of an input let mut feedback = MaxMapFeedback::new(&observer); diff --git a/fuzzers/inprocess/dynamic_analysis/src/lib.rs b/fuzzers/inprocess/dynamic_analysis/src/lib.rs index 5de077d2a5..a6c5cf3d3a 100644 --- a/fuzzers/inprocess/dynamic_analysis/src/lib.rs +++ b/fuzzers/inprocess/dynamic_analysis/src/lib.rs @@ -11,7 +11,6 @@ use std::{ io::{self, Read, Write}, path::PathBuf, process, - ptr::addr_of_mut, }; use clap::{Arg, Command}; @@ -254,7 +253,7 @@ fn fuzz( let time_observer = TimeObserver::new("time"); let func_list = - unsafe { OwnedMutPtr::from_raw_mut(Lazy::force_mut(&mut *addr_of_mut!(FUNCTION_LIST))) }; + unsafe { OwnedMutPtr::from_raw_mut(Lazy::force_mut(&mut *&raw mut FUNCTION_LIST)) }; let profiling_observer = ProfilingObserver::new("concatenated.json", func_list)?; let callhook = CallHook::new(); diff --git a/fuzzers/structure_aware/baby_fuzzer_custom_input/src/main.rs b/fuzzers/structure_aware/baby_fuzzer_custom_input/src/main.rs index ca2db81aaf..2cf5d2c7a0 100644 --- a/fuzzers/structure_aware/baby_fuzzer_custom_input/src/main.rs +++ b/fuzzers/structure_aware/baby_fuzzer_custom_input/src/main.rs @@ -2,10 +2,7 @@ mod input; #[cfg(windows)] use std::ptr::write_volatile; -use std::{ - path::PathBuf, - ptr::{addr_of_mut, write}, -}; +use std::{path::PathBuf, ptr::write}; use input::{ CustomInput, CustomInputGenerator, ToggleBooleanMutator, ToggleOptionalByteArrayMutator, @@ -43,7 +40,7 @@ use { /// Coverage map with explicit assignments due to the lack of instrumentation const SIGNALS_LEN: usize = 16; static mut SIGNALS: [u8; SIGNALS_LEN] = [0; 16]; -static mut SIGNALS_PTR: *mut u8 = addr_of_mut!(SIGNALS) as _; +static mut SIGNALS_PTR: *mut u8 = &raw mut SIGNALS as _; /// Assign a signal to the signals map fn signals_set(idx: usize) { diff --git a/fuzzers/structure_aware/baby_fuzzer_gramatron/src/main.rs b/fuzzers/structure_aware/baby_fuzzer_gramatron/src/main.rs index f950639983..b4efb17f55 100644 --- a/fuzzers/structure_aware/baby_fuzzer_gramatron/src/main.rs +++ b/fuzzers/structure_aware/baby_fuzzer_gramatron/src/main.rs @@ -4,7 +4,6 @@ use std::{ fs, io::{BufReader, Read}, path::{Path, PathBuf}, - ptr::addr_of_mut, }; use libafl::{ @@ -30,7 +29,7 @@ use libafl_bolts::{rands::StdRand, tuples::tuple_list}; /// Coverage map with explicit assignments due to the lack of instrumentation const SIGNALS_LEN: usize = 16; static mut SIGNALS: [u8; SIGNALS_LEN] = [0; SIGNALS_LEN]; -static mut SIGNALS_PTR: *mut u8 = unsafe { addr_of_mut!(SIGNALS) as _ }; +static mut SIGNALS_PTR: *mut u8 = unsafe { &raw mut SIGNALS as _ }; /* /// Assign a signal to the signals map fn signals_set(idx: usize) { diff --git a/libafl/src/common/nautilus/regex_mutator/mod.rs b/libafl/src/common/nautilus/regex_mutator/mod.rs index e5885a0d86..b7ece90ba3 100644 --- a/libafl/src/common/nautilus/regex_mutator/mod.rs +++ b/libafl/src/common/nautilus/regex_mutator/mod.rs @@ -53,6 +53,7 @@ fn append_unicode_range( cls: ClassUnicodeRange, ) { let mut chr_a_buf = [0; 4]; + #[allow(clippy::similar_names)] let mut chr_b_buf = [0; 4]; cls.start().encode_utf8(&mut chr_a_buf); cls.end().encode_utf8(&mut chr_b_buf); @@ -129,10 +130,10 @@ pub fn generate(rand: &mut R, hir: &Hir) -> Vec { HirKind::Empty => {} HirKind::Literal(lit) => append_lit(&mut res, lit), HirKind::Class(cls) => append_class(rand, &mut res, &mut scr, cls), - HirKind::Repetition(rep) => { - let num = get_repetitions(rand, rep.min, rep.max, &mut scr); + HirKind::Repetition(repetition) => { + let num = get_repetitions(rand, repetition.min, repetition.max, &mut scr); for _ in 0..num { - stack.push(&rep.sub); + stack.push(&repetition.sub); } } HirKind::Capture(grp) => stack.push(&grp.sub), diff --git a/libafl/src/events/llmp/restarting.rs b/libafl/src/events/llmp/restarting.rs index 1177e270a4..00fa2e3020 100644 --- a/libafl/src/events/llmp/restarting.rs +++ b/libafl/src/events/llmp/restarting.rs @@ -4,8 +4,6 @@ //! restart/refork it. use alloc::{boxed::Box, vec::Vec}; -#[cfg(all(unix, not(miri), feature = "std"))] -use core::ptr::addr_of_mut; #[cfg(feature = "std")] use core::sync::atomic::{compiler_fence, Ordering}; #[cfg(feature = "std")] @@ -653,7 +651,7 @@ where // At this point we are the fuzzer *NOT* the restarter. // We setup signal handlers to clean up shmem segments used by state restorer #[cfg(all(unix, not(miri)))] - if let Err(_e) = unsafe { setup_signal_handler(addr_of_mut!(EVENTMGR_SIGHANDLER_STATE)) } { + if let Err(_e) = unsafe { setup_signal_handler(&raw mut EVENTMGR_SIGHANDLER_STATE) } { // We can live without a proper ctrl+c signal handler. Print and ignore. log::error!("Failed to setup signal handlers: {_e}"); } diff --git a/libafl/src/events/mod.rs b/libafl/src/events/mod.rs index abe1e9494a..43f051f1de 100644 --- a/libafl/src/events/mod.rs +++ b/libafl/src/events/mod.rs @@ -942,8 +942,6 @@ pub trait AdaptiveSerializer { #[cfg(test)] mod tests { - use core::ptr::{addr_of, addr_of_mut}; - use libafl_bolts::{current_time, tuples::tuple_list, Named}; use tuple_list::tuple_list_type; @@ -958,9 +956,10 @@ mod tests { #[test] fn test_event_serde() { + let map_ptr = &raw const MAP; let obv = unsafe { - let len = (*addr_of!(MAP)).len(); - StdMapObserver::from_mut_ptr("test", addr_of_mut!(MAP) as *mut u32, len) + let len = (*map_ptr).len(); + StdMapObserver::from_mut_ptr("test", &raw mut MAP as *mut u32, len) }; let map = tuple_list!(obv); let observers_buf = postcard::to_allocvec(&map).unwrap(); diff --git a/libafl/src/events/simple.rs b/libafl/src/events/simple.rs index b76d78546c..5289eaa2f7 100644 --- a/libafl/src/events/simple.rs +++ b/libafl/src/events/simple.rs @@ -1,8 +1,6 @@ //! A very simple event manager, that just supports log outputs, but no multiprocessing use alloc::{boxed::Box, vec::Vec}; -#[cfg(all(unix, not(miri), feature = "std"))] -use core::ptr::addr_of_mut; use core::{fmt::Debug, marker::PhantomData}; #[cfg(feature = "std")] use core::{ @@ -543,7 +541,7 @@ where // At this point we are the fuzzer *NOT* the restarter. // We setup signal handlers to clean up shmem segments used by state restorer #[cfg(all(unix, not(miri)))] - if let Err(_e) = unsafe { setup_signal_handler(addr_of_mut!(EVENTMGR_SIGHANDLER_STATE)) } { + if let Err(_e) = unsafe { setup_signal_handler(&raw mut EVENTMGR_SIGHANDLER_STATE) } { // We can live without a proper ctrl+c signal handler. Print and ignore. log::error!("Failed to setup signal handlers: {_e}"); } diff --git a/libafl/src/events/tcp.rs b/libafl/src/events/tcp.rs index 9ef81da05b..977ad9de85 100644 --- a/libafl/src/events/tcp.rs +++ b/libafl/src/events/tcp.rs @@ -1,8 +1,6 @@ //! TCP-backed event manager for scalable multi-processed fuzzing use alloc::{boxed::Box, vec::Vec}; -#[cfg(all(unix, feature = "std", not(miri)))] -use core::ptr::addr_of_mut; use core::{ marker::PhantomData, num::NonZeroUsize, @@ -1326,7 +1324,7 @@ where // At this point we are the fuzzer *NOT* the restarter. // We setup signal handlers to clean up shmem segments used by state restorer #[cfg(all(unix, not(miri)))] - if let Err(_e) = unsafe { setup_signal_handler(addr_of_mut!(EVENTMGR_SIGHANDLER_STATE)) } { + if let Err(_e) = unsafe { setup_signal_handler(&raw mut EVENTMGR_SIGHANDLER_STATE) } { // We can live without a proper ctrl+c signal handler. Print and ignore. log::error!("Failed to setup signal handlers: {_e}"); } diff --git a/libafl/src/executors/hooks/inprocess.rs b/libafl/src/executors/hooks/inprocess.rs index ab926794bb..f4a927c9c8 100644 --- a/libafl/src/executors/hooks/inprocess.rs +++ b/libafl/src/executors/hooks/inprocess.rs @@ -1,6 +1,6 @@ //! The hook for `InProcessExecutor` -#[cfg(any(unix, feature = "std"))] -use core::ptr::addr_of_mut; +#[cfg(all(target_os = "linux", feature = "std"))] +use core::mem::zeroed; #[cfg(any(unix, all(windows, feature = "std")))] use core::sync::atomic::{compiler_fence, Ordering}; use core::{ @@ -9,8 +9,6 @@ use core::{ ptr::{self, null_mut}, time::Duration, }; -#[cfg(all(target_os = "linux", feature = "std"))] -use core::{mem::zeroed, ptr::addr_of}; #[cfg(all(target_os = "linux", feature = "std"))] use libafl_bolts::current_time; @@ -151,7 +149,7 @@ where libc::timer_settime( self.timer_mut().timerid, 0, - addr_of!(disarmed), + &raw const disarmed, null_mut(), ); } @@ -173,7 +171,7 @@ where libc::timer_settime( self.timer_mut().timerid, 0, - addr_of!(self.timer_mut().itimerspec), + &raw const self.timer_mut().itimerspec, null_mut(), ); } @@ -204,7 +202,7 @@ where fn pre_exec(&mut self, state: &mut S, input: &S::Input) { #[cfg(feature = "std")] unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; (*data).crash_handler = self.crash_handler; (*data).timeout_handler = self.timeout_handler; } @@ -246,7 +244,7 @@ where // We get a pointer to `GLOBAL_STATE` that will be initialized at this point in time. // This unsafe is needed in stable but not in nightly. Remove in the future(?) #[allow(unused_unsafe)] - let data = unsafe { addr_of_mut!(GLOBAL_STATE) }; + let data = unsafe { &raw mut GLOBAL_STATE }; #[cfg(feature = "std")] unix_signal_handler::setup_panic_hook::(); // # Safety @@ -288,7 +286,7 @@ where let ret; #[cfg(feature = "std")] unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; crate::executors::hooks::windows::windows_exception_handler::setup_panic_hook::< E, EM, diff --git a/libafl/src/executors/hooks/inprocess_fork.rs b/libafl/src/executors/hooks/inprocess_fork.rs index 8f86ad9569..16af31f8b2 100644 --- a/libafl/src/executors/hooks/inprocess_fork.rs +++ b/libafl/src/executors/hooks/inprocess_fork.rs @@ -3,7 +3,7 @@ use alloc::vec::Vec; use core::{ ffi::c_void, marker::PhantomData, - ptr::{addr_of_mut, null}, + ptr::null, sync::atomic::{compiler_fence, Ordering}, }; use std::intrinsics::transmute; @@ -46,7 +46,7 @@ where /// Call before running a target. fn pre_exec(&mut self, _state: &mut S, _input: &S::Input) { unsafe { - let data = addr_of_mut!(FORK_EXECUTOR_GLOBAL_DATA); + let data = &raw mut FORK_EXECUTOR_GLOBAL_DATA; (*data).crash_handler = self.crash_handler; (*data).timeout_handler = self.timeout_handler; compiler_fence(Ordering::SeqCst); @@ -65,7 +65,7 @@ impl InChildProcessHooks { { #[cfg_attr(miri, allow(unused_variables, unused_unsafe))] unsafe { - let data = addr_of_mut!(FORK_EXECUTOR_GLOBAL_DATA); + let data = &raw mut FORK_EXECUTOR_GLOBAL_DATA; // child_signal_handlers::setup_child_panic_hook::(); #[cfg(not(miri))] setup_signal_handler(data)?; @@ -157,24 +157,14 @@ impl SignalHandler for InProcessForkExecutorGlobalData { if !FORK_EXECUTOR_GLOBAL_DATA.timeout_handler.is_null() { let func: ForkHandlerFuncPtr = transmute(FORK_EXECUTOR_GLOBAL_DATA.timeout_handler); - (func)( - signal, - info, - context, - addr_of_mut!(FORK_EXECUTOR_GLOBAL_DATA), - ); + (func)(signal, info, context, &raw mut FORK_EXECUTOR_GLOBAL_DATA); } }, _ => unsafe { if !FORK_EXECUTOR_GLOBAL_DATA.crash_handler.is_null() { let func: ForkHandlerFuncPtr = transmute(FORK_EXECUTOR_GLOBAL_DATA.crash_handler); - (func)( - signal, - info, - context, - addr_of_mut!(FORK_EXECUTOR_GLOBAL_DATA), - ); + (func)(signal, info, context, &raw mut FORK_EXECUTOR_GLOBAL_DATA); } }, } diff --git a/libafl/src/executors/hooks/timer.rs b/libafl/src/executors/hooks/timer.rs index 9d93d18d48..9d2492f9ba 100644 --- a/libafl/src/executors/hooks/timer.rs +++ b/libafl/src/executors/hooks/timer.rs @@ -1,12 +1,7 @@ //! The struct `TimerStruct` will absorb all the difference in timeout implementation in various system. -#[cfg(any(windows, target_os = "linux"))] -use core::ptr::addr_of_mut; use core::time::Duration; #[cfg(target_os = "linux")] -use core::{ - mem::zeroed, - ptr::{addr_of, null_mut}, -}; +use core::{mem::zeroed, ptr::null_mut}; #[cfg(all(unix, not(target_os = "linux")))] pub(crate) const ITIMER_REAL: core::ffi::c_int = 0; @@ -187,7 +182,7 @@ impl TimerStruct { let ptp_timer = unsafe { CreateThreadpoolTimer( Some(timeout_handler), - Some(addr_of_mut!(GLOBAL_STATE) as *mut c_void), + Some(&raw mut GLOBAL_STATE as *mut c_void), Some(&TP_CALLBACK_ENVIRON_V3::default()), ) } @@ -227,7 +222,7 @@ impl TimerStruct { unsafe { #[cfg(not(miri))] // creates a new per-process interval timer - libc::timer_create(libc::CLOCK_MONOTONIC, null_mut(), addr_of_mut!(timerid)); + libc::timer_create(libc::CLOCK_MONOTONIC, null_mut(), &raw mut timerid); } Self { @@ -268,12 +263,12 @@ impl TimerStruct { /// Set timer pub fn set_timer(&mut self) { unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; - write_volatile(addr_of_mut!((*data).ptp_timer), Some(*self.ptp_timer())); + write_volatile(&raw mut (*data).ptp_timer, Some(*self.ptp_timer())); write_volatile( - addr_of_mut!((*data).critical), - addr_of_mut!(*self.critical_mut()) as *mut c_void, + &raw mut (*data).critical, + &raw mut (*self.critical_mut()) as *mut c_void, ); let tm: i64 = -self.milli_sec() * 10 * 1000; let ft = FILETIME { @@ -300,13 +295,13 @@ impl TimerStruct { unsafe { if self.batch_mode { if self.executions == 0 { - libc::timer_settime(self.timerid, 0, addr_of_mut!(self.itimerspec), null_mut()); + libc::timer_settime(self.timerid, 0, &raw mut self.itimerspec, null_mut()); self.tmout_start_time = current_time(); } self.start_time = current_time(); } else { #[cfg(not(miri))] - libc::timer_settime(self.timerid, 0, addr_of_mut!(self.itimerspec), null_mut()); + libc::timer_settime(self.timerid, 0, &raw mut self.itimerspec, null_mut()); } } } @@ -336,7 +331,7 @@ impl TimerStruct { || self.exec_tmout.saturating_sub(elapsed) < self.avg_exec_time * self.avg_mul_k { let disarmed: libc::itimerspec = zeroed(); - libc::timer_settime(self.timerid, 0, addr_of!(disarmed), null_mut()); + libc::timer_settime(self.timerid, 0, &raw const disarmed, null_mut()); // set timer the next exec if self.executions > 0 { self.avg_exec_time = elapsed / self.executions; @@ -354,7 +349,7 @@ impl TimerStruct { unsafe { let disarmed: libc::itimerspec = zeroed(); #[cfg(not(miri))] - libc::timer_settime(self.timerid, 0, addr_of!(disarmed), null_mut()); + libc::timer_settime(self.timerid, 0, &raw const disarmed, null_mut()); } } } @@ -365,7 +360,7 @@ impl TimerStruct { // # Safety // The value accesses are guarded by a critical section. unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; compiler_fence(Ordering::SeqCst); EnterCriticalSection(self.critical_mut()); diff --git a/libafl/src/executors/hooks/unix.rs b/libafl/src/executors/hooks/unix.rs index 37ce65af9f..a63adb0563 100644 --- a/libafl/src/executors/hooks/unix.rs +++ b/libafl/src/executors/hooks/unix.rs @@ -2,7 +2,7 @@ #[cfg(unix)] pub mod unix_signal_handler { use alloc::{boxed::Box, string::String, vec::Vec}; - use core::{mem::transmute, ptr::addr_of_mut}; + use core::mem::transmute; use std::{io::Write, panic}; use libafl_bolts::os::unix_signals::{ucontext_t, Signal, SignalHandler}; @@ -51,7 +51,7 @@ pub mod unix_signal_handler { context: Option<&mut ucontext_t>, ) { unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; let in_handler = (*data).set_in_handler(true); match signal { Signal::SigUser2 | Signal::SigAlarm => { @@ -91,7 +91,7 @@ pub mod unix_signal_handler { let old_hook = panic::take_hook(); panic::set_hook(Box::new(move |panic_info| unsafe { old_hook(panic_info); - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; let in_handler = (*data).set_in_handler(true); if (*data).is_valid() { // We are fuzzing! diff --git a/libafl/src/executors/hooks/windows.rs b/libafl/src/executors/hooks/windows.rs index b6063c557d..d4ec7829ae 100644 --- a/libafl/src/executors/hooks/windows.rs +++ b/libafl/src/executors/hooks/windows.rs @@ -2,10 +2,7 @@ #[cfg(all(windows, feature = "std"))] pub mod windows_asan_handler { use alloc::string::String; - use core::{ - ptr::addr_of_mut, - sync::atomic::{compiler_fence, Ordering}, - }; + use core::sync::atomic::{compiler_fence, Ordering}; use windows::Win32::System::Threading::{ EnterCriticalSection, LeaveCriticalSection, CRITICAL_SECTION, @@ -38,7 +35,7 @@ pub mod windows_asan_handler { <::State as HasSolutions>::Solutions: Corpus, //delete me <<::State as HasCorpus>::Corpus as Corpus>::Input: Clone, //delete me { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; (*data).set_in_handler(true); // Have we set a timer_before? if (*data).ptp_timer.is_some() { @@ -114,7 +111,6 @@ pub mod windows_exception_handler { ffi::c_void, mem::transmute, ptr, - ptr::addr_of_mut, sync::atomic::{compiler_fence, Ordering}, }; #[cfg(feature = "std")] @@ -165,7 +161,7 @@ pub mod windows_exception_handler { exception_pointers: *mut EXCEPTION_POINTERS, ) { unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; let in_handler = (*data).set_in_handler(true); if !(*data).crash_handler.is_null() { let func: HandlerFuncPtr = transmute((*data).crash_handler); @@ -200,7 +196,7 @@ pub mod windows_exception_handler { { let old_hook = panic::take_hook(); panic::set_hook(Box::new(move |panic_info| unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; let in_handler = (*data).set_in_handler(true); // Have we set a timer_before? if (*data).ptp_timer.is_some() { diff --git a/libafl/src/executors/inprocess/inner.rs b/libafl/src/executors/inprocess/inner.rs index 52598a574a..cb6d38ae76 100644 --- a/libafl/src/executors/inprocess/inner.rs +++ b/libafl/src/executors/inprocess/inner.rs @@ -2,7 +2,7 @@ use core::{ ffi::c_void, fmt::{self, Debug, Formatter}, marker::PhantomData, - ptr::{self, addr_of_mut, null, write_volatile}, + ptr::{self, null, write_volatile}, sync::atomic::{compiler_fence, Ordering}, time::Duration, }; @@ -99,24 +99,24 @@ where executor_ptr: *const c_void, ) { unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; write_volatile( - addr_of_mut!((*data).current_input_ptr), + &raw mut (*data).current_input_ptr, ptr::from_ref(input) as *const c_void, ); - write_volatile(addr_of_mut!((*data).executor_ptr), executor_ptr); + write_volatile(&raw mut (*data).executor_ptr, executor_ptr); // Direct raw pointers access /aliasing is pretty undefined behavior. // Since the state and event may have moved in memory, refresh them right before the signal may happen write_volatile( - addr_of_mut!((*data).state_ptr), + &raw mut ((*data).state_ptr), ptr::from_mut(state) as *mut c_void, ); write_volatile( - addr_of_mut!((*data).event_mgr_ptr), + &raw mut (*data).event_mgr_ptr, ptr::from_mut(mgr) as *mut c_void, ); write_volatile( - addr_of_mut!((*data).fuzzer_ptr), + &raw mut (*data).fuzzer_ptr, ptr::from_mut(fuzzer) as *mut c_void, ); compiler_fence(Ordering::SeqCst); @@ -133,9 +133,9 @@ where _input: &::Input, ) { unsafe { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; - write_volatile(addr_of_mut!((*data).current_input_ptr), null()); + write_volatile(&raw mut (*data).current_input_ptr, null()); compiler_fence(Ordering::SeqCst); } } diff --git a/libafl/src/executors/inprocess/mod.rs b/libafl/src/executors/inprocess/mod.rs index 15e14486fa..e326743cce 100644 --- a/libafl/src/executors/inprocess/mod.rs +++ b/libafl/src/executors/inprocess/mod.rs @@ -5,8 +5,6 @@ #![allow(clippy::needless_pass_by_value)] use alloc::boxed::Box; -#[cfg(any(unix, feature = "std"))] -use core::ptr::addr_of_mut; use core::{ borrow::BorrowMut, ffi::c_void, @@ -510,7 +508,7 @@ where + ExecutionProcessor, <::State as HasSolutions>::Solutions: Corpus, //delete me { - let data = addr_of_mut!(GLOBAL_STATE); + let data = &raw mut GLOBAL_STATE; let in_handler = (*data).set_in_handler(true); if (*data).is_valid() { diff --git a/libafl/src/executors/inprocess_fork/inner.rs b/libafl/src/executors/inprocess_fork/inner.rs index 1552c042d4..9c82fbf70c 100644 --- a/libafl/src/executors/inprocess_fork/inner.rs +++ b/libafl/src/executors/inprocess_fork/inner.rs @@ -2,7 +2,7 @@ use core::{ ffi::c_void, fmt::{self, Debug, Formatter}, marker::PhantomData, - ptr::{self, addr_of_mut, null_mut, write_volatile}, + ptr::{self, null_mut, write_volatile}, sync::atomic::{compiler_fence, Ordering}, time::Duration, }; @@ -144,10 +144,10 @@ where let mut timerid: libc::timer_t = null_mut(); // creates a new per-process interval timer // we can't do this from the parent, timerid is unique to each process. - libc::timer_create(libc::CLOCK_MONOTONIC, null_mut(), addr_of_mut!(timerid)); + libc::timer_create(libc::CLOCK_MONOTONIC, null_mut(), &raw mut timerid); // log::info!("Set timer! {:#?} {timerid:#?}", self.itimerspec); - let _: i32 = libc::timer_settime(timerid, 0, addr_of_mut!(self.itimerspec), null_mut()); + let _: i32 = libc::timer_settime(timerid, 0, &raw mut self.itimerspec, null_mut()); } #[cfg(not(target_os = "linux"))] { @@ -224,17 +224,17 @@ where input: &::Input, ) { unsafe { - let data = addr_of_mut!(FORK_EXECUTOR_GLOBAL_DATA); + let data = &raw mut FORK_EXECUTOR_GLOBAL_DATA; write_volatile( - addr_of_mut!((*data).executor_ptr), + &raw mut (*data).executor_ptr, ptr::from_ref(self) as *const c_void, ); write_volatile( - addr_of_mut!((*data).current_input_ptr), + &raw mut (*data).current_input_ptr, ptr::from_ref(input) as *const c_void, ); write_volatile( - addr_of_mut!((*data).state_ptr), + &raw mut ((*data).state_ptr), ptr::from_mut(state) as *mut c_void, ); compiler_fence(Ordering::SeqCst); diff --git a/libafl/src/executors/inprocess_fork/mod.rs b/libafl/src/executors/inprocess_fork/mod.rs index 77c561db21..fd5e7c3f6c 100644 --- a/libafl/src/executors/inprocess_fork/mod.rs +++ b/libafl/src/executors/inprocess_fork/mod.rs @@ -259,7 +259,6 @@ where /// signal hooks and `panic_hooks` for the child process pub mod child_signal_handlers { use alloc::boxed::Box; - use core::ptr::addr_of_mut; use std::panic; use libafl_bolts::os::unix_signals::{ucontext_t, Signal}; @@ -284,7 +283,7 @@ pub mod child_signal_handlers { let old_hook = panic::take_hook(); panic::set_hook(Box::new(move |panic_info| unsafe { old_hook(panic_info); - let data = addr_of_mut!(FORK_EXECUTOR_GLOBAL_DATA); + let data = &raw mut FORK_EXECUTOR_GLOBAL_DATA; if !data.is_null() && (*data).is_valid() { let executor = (*data).executor_mut::(); let mut observers = executor.observers_mut(); diff --git a/libafl/src/observers/map/hitcount_map.rs b/libafl/src/observers/map/hitcount_map.rs index c6521775b7..56a6dbfc6e 100644 --- a/libafl/src/observers/map/hitcount_map.rs +++ b/libafl/src/observers/map/hitcount_map.rs @@ -5,7 +5,6 @@ use core::{ hash::Hash, mem::size_of, ops::{Deref, DerefMut}, - ptr::{addr_of, addr_of_mut}, slice, }; @@ -46,7 +45,8 @@ fn init_count_class_16() { // Calling this from multiple threads may be racey and hence leak 65k mem or even create a broken lookup vec. // We can live with that. unsafe { - let count_class_lookup_16 = &mut *addr_of_mut!(COUNT_CLASS_LOOKUP_16); + let count_class_lookup_16 = &raw mut COUNT_CLASS_LOOKUP_16; + let count_class_lookup_16 = &mut *count_class_lookup_16; if !count_class_lookup_16.is_empty() { return; @@ -127,11 +127,14 @@ where let map16 = unsafe { slice::from_raw_parts_mut(map.as_mut_ptr().add(align_offset) as *mut u16, cnt) }; + let count_class_lookup_16 = &raw mut COUNT_CLASS_LOOKUP_16; + // 2022-07: Adding `enumerate` here increases execution speed/register allocation on x86_64. #[allow(clippy::unused_enumerate_index)] for (_i, item) in map16[0..cnt].iter_mut().enumerate() { unsafe { - *item = *(*addr_of!(COUNT_CLASS_LOOKUP_16)).get_unchecked(*item as usize); + let count_class_lookup_16 = &mut *count_class_lookup_16; + *item = *(*count_class_lookup_16).get_unchecked(*item as usize); } } diff --git a/libafl/src/observers/mod.rs b/libafl/src/observers/mod.rs index 026e593fb5..d312b1e693 100644 --- a/libafl/src/observers/mod.rs +++ b/libafl/src/observers/mod.rs @@ -402,8 +402,6 @@ impl DifferentialObserver for TimeObserver {} #[cfg(test)] mod tests { - use core::ptr::{addr_of, addr_of_mut}; - use libafl_bolts::{ ownedref::OwnedMutSlice, tuples::{tuple_list, tuple_list_type}, @@ -416,11 +414,12 @@ mod tests { #[test] fn test_observer_serde() { + let map_ptr = &raw const MAP; let obv = tuple_list!(TimeObserver::new("time"), unsafe { - let len = (*addr_of!(MAP)).len(); + let len = (*map_ptr).len(); StdMapObserver::from_ownedref( "map", - OwnedMutSlice::from_raw_parts_mut(addr_of_mut!(MAP) as *mut u32, len), + OwnedMutSlice::from_raw_parts_mut(&raw mut MAP as *mut u32, len), ) }); let vec = postcard::to_allocvec(&obv).unwrap(); diff --git a/libafl/src/stages/afl_stats.rs b/libafl/src/stages/afl_stats.rs index 336a55be36..7f37241fc3 100644 --- a/libafl/src/stages/afl_stats.rs +++ b/libafl/src/stages/afl_stats.rs @@ -328,6 +328,7 @@ where } else { 0 }; + #[allow(clippy::similar_names)] let stats = AFLFuzzerStats { start_time: self.start_time, last_update: self.last_report_time.as_secs(), diff --git a/libafl/src/stages/mod.rs b/libafl/src/stages/mod.rs index 002ee33ff8..bcb6b8f2d4 100644 --- a/libafl/src/stages/mod.rs +++ b/libafl/src/stages/mod.rs @@ -205,6 +205,8 @@ where } Some(idx) if idx == StageId(Self::LEN) => { // perform the stage, but don't set it + + #[allow(clippy::similar_names)] let stage = &mut self.0; stage.perform_restartable(fuzzer, executor, state, manager)?; @@ -218,6 +220,7 @@ where _ => { state.set_current_stage_id(StageId(Self::LEN))?; + #[allow(clippy::similar_names)] let stage = &mut self.0; stage.perform_restartable(fuzzer, executor, state, manager)?; @@ -820,6 +823,7 @@ mod test { } } + #[allow(clippy::similar_names)] let mut state = StdState::nop()?; let stage = StageWithOneTry; diff --git a/libafl_bolts/src/anymap.rs b/libafl_bolts/src/anymap.rs index b8e786edd7..29eae29e03 100644 --- a/libafl_bolts/src/anymap.rs +++ b/libafl_bolts/src/anymap.rs @@ -1,10 +1,6 @@ //! Poor-rust-man's downcasts to have `AnyMap` -use core::{ - any::TypeId, - mem::size_of, - ptr::{addr_of, read_unaligned}, -}; +use core::{any::TypeId, mem::size_of, ptr::read_unaligned}; /// Get a `type_id` from its previously unpacked `u128`. /// Opposite of [`unpack_type_id(id)`]. @@ -17,7 +13,7 @@ use core::{ pub const fn pack_type_id(id: u128) -> TypeId { // TypeId size of other sizes is not yet supported" static_assertions::const_assert!(size_of::() == 16); - unsafe { *(addr_of!(id) as *const TypeId) } + unsafe { *(&raw const id as *const TypeId) } } /// Unpack a `type_id` to an `u128` @@ -32,7 +28,7 @@ pub const fn unpack_type_id(id: TypeId) -> u128 { // see any.rs, it's alway u128 hence 16 bytes. // TypeId size of other sizes is not yet supported" static_assertions::const_assert!(size_of::() == 16); - let ret: u128 = unsafe { read_unaligned::(addr_of!(id) as *const u128) }; + let ret: u128 = unsafe { read_unaligned::(&raw const id as *const u128) }; ret } diff --git a/libafl_bolts/src/core_affinity.rs b/libafl_bolts/src/core_affinity.rs index d3bbcbfc6b..e921425e81 100644 --- a/libafl_bolts/src/core_affinity.rs +++ b/libafl_bolts/src/core_affinity.rs @@ -595,8 +595,6 @@ fn set_for_current_helper(core_id: CoreId) -> Result<(), Error> { #[cfg(target_vendor = "apple")] mod apple { use alloc::vec::Vec; - #[cfg(target_arch = "x86_64")] - use core::ptr::addr_of_mut; use std::thread::available_parallelism; #[cfg(target_arch = "x86_64")] @@ -645,7 +643,7 @@ mod apple { let result = thread_policy_set( pthread_mach_thread_np(pthread_self()), THREAD_AFFINITY_POLICY as _, - addr_of_mut!(info) as thread_policy_t, + &raw mut info as thread_policy_t, THREAD_AFFINITY_POLICY_COUNT, ); diff --git a/libafl_bolts/src/lib.rs b/libafl_bolts/src/lib.rs index a1646a90b0..ebfee24327 100644 --- a/libafl_bolts/src/lib.rs +++ b/libafl_bolts/src/lib.rs @@ -147,8 +147,6 @@ use alloc::{borrow::Cow, vec::Vec}; use core::hash::BuildHasher; #[cfg(any(feature = "xxh3", feature = "alloc"))] use core::hash::Hasher; -#[cfg(all(unix, feature = "std"))] -use core::ptr; #[cfg(feature = "std")] use std::time::{SystemTime, UNIX_EPOCH}; #[cfg(all(unix, feature = "std"))] @@ -1038,9 +1036,11 @@ impl SimpleFdLogger { // # Safety // The passed-in `fd` has to be a legal file descriptor to log to. // We also access a shared variable here. + let logger = &raw mut LIBAFL_RAWFD_LOGGER; unsafe { - (*ptr::addr_of_mut!(LIBAFL_RAWFD_LOGGER)).set_fd(log_fd); - log::set_logger(&*ptr::addr_of!(LIBAFL_RAWFD_LOGGER))?; + let logger = &mut *logger; + logger.set_fd(log_fd); + log::set_logger(logger)?; } Ok(()) } @@ -1267,9 +1267,6 @@ pub mod pybind { #[cfg(test)] mod tests { - #[cfg(all(feature = "std", unix))] - use core::ptr; - #[cfg(all(feature = "std", unix))] use crate::LIBAFL_RAWFD_LOGGER; @@ -1279,8 +1276,10 @@ mod tests { use std::{io::stdout, os::fd::AsRawFd}; unsafe { LIBAFL_RAWFD_LOGGER.fd = stdout().as_raw_fd() }; + + let libafl_rawfd_logger_fd = &raw const LIBAFL_RAWFD_LOGGER; unsafe { - log::set_logger(&*ptr::addr_of!(LIBAFL_RAWFD_LOGGER)).unwrap(); + log::set_logger(&*libafl_rawfd_logger_fd).unwrap(); } log::set_max_level(log::LevelFilter::Debug); log::info!("Test"); diff --git a/libafl_bolts/src/llmp.rs b/libafl_bolts/src/llmp.rs index 59d322d02b..6d2f9e8725 100644 --- a/libafl_bolts/src/llmp.rs +++ b/libafl_bolts/src/llmp.rs @@ -1148,7 +1148,7 @@ where let last_msg = self.last_msg_sent; assert!((*page).size_used + EOP_MSG_SIZE <= (*page).size_total, "PROGRAM ABORT : BUG: EOP does not fit in page! page {page:?}, size_current {:?}, size_total {:?}", - ptr::addr_of!((*page).size_used), ptr::addr_of!((*page).size_total)); + &raw const (*page).size_used, &raw const (*page).size_total); let ret: *mut LlmpMsg = if last_msg.is_null() { (*page).messages.as_mut_ptr() @@ -1240,7 +1240,7 @@ where MessageId((*last_msg).message_id.0 + 1) } else { /* Oops, wrong usage! */ - panic!("BUG: The current message never got committed using send! (page->current_msg_id {:?}, last_msg->message_id: {:?})", ptr::addr_of!((*page).current_msg_id), (*last_msg).message_id); + panic!("BUG: The current message never got committed using send! (page->current_msg_id {:?}, last_msg->message_id: {:?})", &raw const (*page).current_msg_id, (*last_msg).message_id); }; (*ret).buf_len = buf_len as u64; @@ -2195,7 +2195,7 @@ impl SignalHandler for LlmpShutdownSignalHandler { _context: Option<&mut ucontext_t>, ) { unsafe { - ptr::write_volatile(ptr::addr_of_mut!(self.shutting_down), true); + ptr::write_volatile(&raw mut self.shutting_down, true); } } @@ -2352,7 +2352,7 @@ impl Brokers { #[cfg(any(all(unix, not(miri)), all(windows, feature = "std")))] fn setup_handlers() { #[cfg(all(unix, not(miri)))] - if let Err(e) = unsafe { setup_signal_handler(ptr::addr_of_mut!(LLMP_SIGHANDLER_STATE)) } { + if let Err(e) = unsafe { setup_signal_handler(&raw mut LLMP_SIGHANDLER_STATE) } { // We can live without a proper ctrl+c signal handler - Ignore. log::info!("Failed to setup signal handlers: {e}"); } else { @@ -2360,7 +2360,7 @@ impl Brokers { } #[cfg(all(windows, feature = "std"))] - if let Err(e) = unsafe { setup_ctrl_handler(ptr::addr_of_mut!(LLMP_SIGHANDLER_STATE)) } { + if let Err(e) = unsafe { setup_ctrl_handler(&raw mut LLMP_SIGHANDLER_STATE) } { // We can live without a proper ctrl+c signal handler - Ignore. log::info!("Failed to setup control handlers: {e}"); } else { @@ -2805,7 +2805,7 @@ where #[cfg(any(all(unix, not(miri)), all(windows, feature = "std")))] fn setup_handlers() { #[cfg(all(unix, not(miri)))] - if let Err(e) = unsafe { setup_signal_handler(ptr::addr_of_mut!(LLMP_SIGHANDLER_STATE)) } { + if let Err(e) = unsafe { setup_signal_handler(&raw mut LLMP_SIGHANDLER_STATE) } { // We can live without a proper ctrl+c signal handler - Ignore. log::info!("Failed to setup signal handlers: {e}"); } else { @@ -2813,7 +2813,7 @@ where } #[cfg(all(windows, feature = "std"))] - if let Err(e) = unsafe { setup_ctrl_handler(ptr::addr_of_mut!(LLMP_SIGHANDLER_STATE)) } { + if let Err(e) = unsafe { setup_ctrl_handler(&raw mut LLMP_SIGHANDLER_STATE) } { // We can live without a proper ctrl+c signal handler - Ignore. log::info!("Failed to setup control handlers: {e}"); } else { @@ -3044,7 +3044,7 @@ where // # Safety // No user-provided potentially unsafe parameters. // Volatile read. - unsafe { ptr::read_volatile(ptr::addr_of!(LLMP_SIGHANDLER_STATE.shutting_down)) } + unsafe { ptr::read_volatile(&raw const (LLMP_SIGHANDLER_STATE.shutting_down)) } } /// Always returns true on platforms, where no shutdown signal handlers are supported diff --git a/libafl_bolts/src/minibsod.rs b/libafl_bolts/src/minibsod.rs index dedd8c3ac3..757f5ebd7f 100644 --- a/libafl_bolts/src/minibsod.rs +++ b/libafl_bolts/src/minibsod.rs @@ -1212,7 +1212,7 @@ mod tests { proc, cur, proc, - std::ptr::addr_of_mut!(out), + &raw mut out, 0, true, DUPLICATE_SAME_ACCESS, @@ -1237,7 +1237,7 @@ mod tests { } else if cfg!(target_arch = "aarch64") { c.ctx.ContextFlags = CONTEXT_FULL_ARM64; } - unsafe { GetThreadContext(thread, std::ptr::addr_of_mut!(c.ctx)).unwrap() }; + unsafe { GetThreadContext(thread, &raw mut (c.ctx)).unwrap() }; let mut writer = BufWriter::new(stdout()); dump_registers(&mut writer, &c.ctx).unwrap(); diff --git a/libafl_bolts/src/os/unix_shmem_server.rs b/libafl_bolts/src/os/unix_shmem_server.rs index 77f0a6208f..d8adfb2059 100644 --- a/libafl_bolts/src/os/unix_shmem_server.rs +++ b/libafl_bolts/src/os/unix_shmem_server.rs @@ -13,7 +13,6 @@ use alloc::{ use core::{ mem::ManuallyDrop, ops::{Deref, DerefMut}, - ptr::addr_of, }; #[cfg(target_vendor = "apple")] use std::fs; @@ -694,7 +693,7 @@ where let copied_poll_fds: Vec = poll_fds.clone(); for poll_fd in copied_poll_fds { let revents = poll_fd.revents().expect("revents should not be None"); - let raw_polled_fd = unsafe { *((addr_of!(poll_fd)) as *const libc::pollfd) }.fd; + let raw_polled_fd = unsafe { *((&raw const poll_fd) as *const libc::pollfd) }.fd; if revents.contains(PollFlags::POLLHUP) { poll_fds.remove(poll_fds.iter().position(|item| *item == poll_fd).unwrap()); self.clients.remove(&raw_polled_fd); diff --git a/libafl_bolts/src/os/unix_signals.rs b/libafl_bolts/src/os/unix_signals.rs index ea1fa23018..acd8a5f48e 100644 --- a/libafl_bolts/src/os/unix_signals.rs +++ b/libafl_bolts/src/os/unix_signals.rs @@ -6,7 +6,7 @@ use core::mem::size_of; #[cfg(feature = "alloc")] use core::{ cell::UnsafeCell, - ptr::{self, addr_of_mut, write_volatile}, + ptr::{self, write_volatile}, sync::atomic::{compiler_fence, Ordering}, }; use core::{ @@ -477,23 +477,23 @@ pub unsafe fn setup_signal_handler( let mut ss: stack_t = mem::zeroed(); ss.ss_size = SIGNAL_STACK_SIZE; ss.ss_sp = SIGNAL_STACK_PTR; - sigaltstack(addr_of_mut!(ss), ptr::null_mut() as _); + sigaltstack(&raw mut ss, ptr::null_mut() as _); let mut sa: sigaction = mem::zeroed(); - sigemptyset(addr_of_mut!(sa.sa_mask)); - sigaddset(addr_of_mut!(sa.sa_mask), SIGALRM); + sigemptyset(&raw mut sa.sa_mask); + sigaddset(&raw mut sa.sa_mask, SIGALRM); sa.sa_flags = SA_NODEFER | SA_SIGINFO | SA_ONSTACK; sa.sa_sigaction = handle_signal as usize; let signals = unsafe { (*handler).signals() }; for sig in signals { write_volatile( - addr_of_mut!(SIGNAL_HANDLERS[sig as usize]), + &raw mut SIGNAL_HANDLERS[sig as usize], Some(HandlerHolder { handler: UnsafeCell::new(handler as *mut dyn SignalHandler), }), ); - if sigaction(sig as i32, addr_of_mut!(sa), ptr::null_mut()) < 0 { + if sigaction(sig as i32, &raw mut sa, ptr::null_mut()) < 0 { #[cfg(feature = "std")] { let err_str = CString::new(format!("Failed to setup {sig} handler")).unwrap(); diff --git a/libafl_bolts/src/os/windows_exceptions.rs b/libafl_bolts/src/os/windows_exceptions.rs index d9d803f863..d1098c98e8 100644 --- a/libafl_bolts/src/os/windows_exceptions.rs +++ b/libafl_bolts/src/os/windows_exceptions.rs @@ -5,7 +5,7 @@ use alloc::vec::Vec; use core::{ cell::UnsafeCell, fmt::{self, Display, Formatter}, - ptr::{self, addr_of, addr_of_mut, write_volatile}, + ptr::{self, write_volatile}, sync::atomic::{compiler_fence, Ordering}, }; use std::os::raw::{c_long, c_void}; @@ -543,7 +543,7 @@ pub unsafe fn setup_exception_handler( .position(|x| *x == exception_code) .unwrap(); write_volatile( - addr_of_mut!(EXCEPTION_HANDLERS[index]), + &raw mut EXCEPTION_HANDLERS[index], Some(HandlerHolder { handler: UnsafeCell::new(handler as *mut dyn ExceptionHandler), }), @@ -551,7 +551,7 @@ pub unsafe fn setup_exception_handler( } write_volatile( - addr_of_mut!(EXCEPTION_HANDLERS[EXCEPTION_HANDLERS_SIZE - 1]), + &raw mut (EXCEPTION_HANDLERS[EXCEPTION_HANDLERS_SIZE - 1]), Some(HandlerHolder { handler: UnsafeCell::new(handler as *mut dyn ExceptionHandler), }), @@ -592,7 +592,7 @@ pub(crate) unsafe fn setup_ctrl_handler( handler: *mut T, ) -> Result<(), Error> { write_volatile( - addr_of_mut!(CTRL_HANDLER), + &raw mut (CTRL_HANDLER), Some(CtrlHandlerHolder { handler: UnsafeCell::new(handler as *mut dyn CtrlHandler), }), @@ -614,7 +614,7 @@ pub(crate) unsafe fn setup_ctrl_handler( } unsafe extern "system" fn ctrl_handler(ctrl_type: u32) -> BOOL { - let handler = ptr::read_volatile(addr_of!(CTRL_HANDLER)); + let handler = ptr::read_volatile(&raw const (CTRL_HANDLER)); match handler { Some(handler_holder) => { log::info!("{:?}: Handling ctrl {}", std::process::id(), ctrl_type); diff --git a/libafl_bolts/src/serdeany.rs b/libafl_bolts/src/serdeany.rs index 6d98511b85..b0aecc175a 100644 --- a/libafl_bolts/src/serdeany.rs +++ b/libafl_bolts/src/serdeany.rs @@ -118,11 +118,7 @@ pub mod serdeany_registry { boxed::Box, string::{String, ToString}, }; - use core::{ - any::TypeId, - fmt, - ptr::{addr_of, addr_of_mut}, - }; + use core::{any::TypeId, fmt}; use hashbrown::{ hash_map::{Values, ValuesMut}, @@ -159,8 +155,9 @@ pub mod serdeany_registry { { let id: TypeRepr = visitor.next_element()?.unwrap(); + let registry = &raw const REGISTRY; let cb = unsafe { - (*addr_of!(REGISTRY)) + (*registry) .deserializers .as_ref() .ok_or_else(|| @@ -231,8 +228,9 @@ pub mod serdeany_registry { where T: crate::serdeany::SerdeAny + Serialize + serde::de::DeserializeOwned, { + let registry = &raw mut REGISTRY; unsafe { - (*addr_of_mut!(REGISTRY)).register::(); + (*registry).register::(); } } @@ -242,8 +240,9 @@ pub mod serdeany_registry { /// This may never be called concurrently or at the same time as `register`. /// It dereferences the `REGISTRY` hashmap and adds the given type to it. pub unsafe fn finalize() { + let registry = &raw mut REGISTRY; unsafe { - (*addr_of_mut!(REGISTRY)).finalize(); + (*registry).finalize(); } } } @@ -352,9 +351,10 @@ pub mod serdeany_registry { #[cfg(not(feature = "stable_anymap"))] let type_repr = &type_repr; + let registry = &raw const REGISTRY; assert!( unsafe { - (*addr_of!(REGISTRY)) + (*registry) .deserializers .as_ref() .expect(super::ERR_EMPTY_TYPES_REGISTER) @@ -614,10 +614,10 @@ pub mod serdeany_registry { let type_repr = type_repr::(); #[cfg(not(feature = "stable_anymap"))] let type_repr = &type_repr; - + let registry = &raw const REGISTRY; assert!( unsafe { - (*addr_of!(REGISTRY)) + (*registry) .deserializers .as_ref() .expect(super::ERR_EMPTY_TYPES_REGISTER) diff --git a/libafl_bolts/src/tuples.rs b/libafl_bolts/src/tuples.rs index 43c9d3dc2f..2aaac8715e 100644 --- a/libafl_bolts/src/tuples.rs +++ b/libafl_bolts/src/tuples.rs @@ -11,7 +11,6 @@ use core::{ marker::PhantomData, mem::transmute, ops::{Index, IndexMut}, - ptr::{addr_of, addr_of_mut}, }; #[cfg(feature = "alloc")] @@ -243,7 +242,7 @@ where { fn match_first_type(&self) -> Option<&T> { if TypeId::of::() == TypeId::of::() { - unsafe { (addr_of!(self.0) as *const T).as_ref() } + unsafe { (&raw const self.0 as *const T).as_ref() } } else { self.1.match_first_type::() } @@ -251,7 +250,7 @@ where fn match_first_type_mut(&mut self) -> Option<&mut T> { if TypeId::of::() == TypeId::of::() { - unsafe { (addr_of_mut!(self.0) as *mut T).as_mut() } + unsafe { (&raw mut self.0 as *mut T).as_mut() } } else { self.1.match_first_type_mut::() } @@ -398,7 +397,7 @@ where fn match_type(&self, f: &mut FN) { // Switch this check to https://stackoverflow.com/a/60138532/7658998 when in stable and remove 'static if TypeId::of::() == TypeId::of::() { - f(unsafe { (addr_of!(self.0) as *const T).as_ref() }.unwrap()); + f(unsafe { (&raw const self.0 as *const T).as_ref() }.unwrap()); } self.1.match_type::(f); } @@ -406,7 +405,7 @@ where fn match_type_mut(&mut self, f: &mut FN) { // Switch this check to https://stackoverflow.com/a/60138532/7658998 when in stable and remove 'static if TypeId::of::() == TypeId::of::() { - f(unsafe { (addr_of_mut!(self.0) as *mut T).as_mut() }.unwrap()); + f(unsafe { (&raw mut self.0 as *mut T).as_mut() }.unwrap()); } self.1.match_type_mut::(f); } @@ -494,7 +493,7 @@ where { fn match_name(&self, name: &str) -> Option<&T> { if type_eq::() && name == self.0.name() { - unsafe { (addr_of!(self.0) as *const T).as_ref() } + unsafe { (&raw const self.0 as *const T).as_ref() } } else { self.1.match_name::(name) } @@ -502,7 +501,7 @@ where fn match_name_mut(&mut self, name: &str) -> Option<&mut T> { if type_eq::() && name == self.0.name() { - unsafe { (addr_of_mut!(self.0) as *mut T).as_mut() } + unsafe { (&raw mut self.0 as *mut T).as_mut() } } else { self.1.match_name_mut::(name) } diff --git a/libafl_derive/src/lib.rs b/libafl_derive/src/lib.rs index ec805a6d5d..8a3139b72c 100644 --- a/libafl_derive/src/lib.rs +++ b/libafl_derive/src/lib.rs @@ -103,6 +103,9 @@ pub fn libafl_serdeany_derive(input: TokenStream) -> TokenStream { /// } /// } /// ``` +/// +/// # Panics +/// Panics for any non-structs. #[proc_macro_derive(Display)] pub fn libafl_display(input: TokenStream) -> TokenStream { let DeriveInput { ident, data, .. } = parse_macro_input!(input as DeriveInput); diff --git a/libafl_frida/src/alloc.rs b/libafl_frida/src/alloc.rs index 40a9021b64..c8b69e47b9 100644 --- a/libafl_frida/src/alloc.rs +++ b/libafl_frida/src/alloc.rs @@ -1,5 +1,3 @@ -#[cfg(target_vendor = "apple")] -use std::ptr::addr_of_mut; #[cfg(any( windows, target_os = "linux", @@ -604,11 +602,11 @@ impl Allocator { kr = unsafe { mach_vm_region_recurse( task, - addr_of_mut!(address), - addr_of_mut!(size), - addr_of_mut!(depth), - addr_of_mut!(info) as vm_region_recurse_info_t, - addr_of_mut!(info_count), + &raw mut address, + &raw mut size, + &raw mut depth, + &raw mut info as vm_region_recurse_info_t, + &raw mut info_count, ) }; diff --git a/libafl_frida/src/asan/asan_rt.rs b/libafl_frida/src/asan/asan_rt.rs index ca1f68daf8..b2592f4e69 100644 --- a/libafl_frida/src/asan/asan_rt.rs +++ b/libafl_frida/src/asan/asan_rt.rs @@ -6,10 +6,7 @@ even if the target would not have crashed under normal conditions. this helps finding mem errors early. */ -use core::{ - fmt::{self, Debug, Formatter}, - ptr::addr_of_mut, -}; +use core::fmt::{self, Debug, Formatter}; use std::{ cell::Cell, ffi::{c_char, c_void}, @@ -361,7 +358,7 @@ impl AsanRuntime { // rlim_cur: 0, // rlim_max: 0, // }; - // assert!(unsafe { getrlimit(RLIMIT_STACK, addr_of_mut!(stack_rlimit)) } == 0); + // assert!(unsafe { getrlimit(RLIMIT_STACK, &raw mut stack_rlimit) } == 0); // // stack_rlimit.rlim_cur as usize // } @@ -374,7 +371,7 @@ impl AsanRuntime { // rlim_cur: 0, // rlim_max: 0, // }; - // assert!(unsafe { getrlimit64(RLIMIT_STACK, addr_of_mut!(stack_rlimit)) } == 0); + // assert!(unsafe { getrlimit64(RLIMIT_STACK, &raw mut stack_rlimit) } == 0); // // stack_rlimit.rlim_cur as usize // } @@ -418,7 +415,7 @@ impl AsanRuntime { #[must_use] pub fn current_stack() -> (usize, usize) { let mut stack_var = 0xeadbeef; - let stack_address = addr_of_mut!(stack_var) as usize; + let stack_address = &raw mut stack_var as usize; // let range_details = RangeDetails::with_address(stack_address as u64).unwrap(); // Write something to (hopefully) make sure the val isn't optimized out @@ -1895,7 +1892,7 @@ impl AsanRuntime { ; self_addr: ; .i64 core::ptr::from_mut(self) as *mut c_void as i64 ; self_regs_addr: - ; .i64 addr_of_mut!(self.regs) as i64 + ; .i64 &raw mut self.regs as i64 ; trap_func: ; .i64 AsanRuntime::handle_trap as *mut c_void as i64 ); @@ -1994,13 +1991,13 @@ impl AsanRuntime { ; self_addr: ; .i64 core::ptr::from_mut(self) as *mut c_void as i64 ; self_regs_addr: - ; .i64 addr_of_mut!(self.regs) as i64 + ; .i64 &raw mut self.regs as i64 ; trap_func: ; .i64 AsanRuntime::handle_trap as *mut c_void as i64 ; register_frame_func: ; .i64 __register_frame as *mut c_void as i64 ; eh_frame_cie_addr: - ; .i64 addr_of_mut!(self.eh_frame) as i64 + ; .i64 &raw mut self.eh_frame as i64 ); self.eh_frame = [ 0x14, 0, 0x00527a01, 0x011e7c01, 0x001f0c1b, // diff --git a/libafl_frida/src/cmplog_rt.rs b/libafl_frida/src/cmplog_rt.rs index 3be8cc1a0a..cf769683f0 100644 --- a/libafl_frida/src/cmplog_rt.rs +++ b/libafl_frida/src/cmplog_rt.rs @@ -218,7 +218,7 @@ impl CmpLogRuntime { ; stp x26, x27, [sp, #-0x10]! ; stp x28, x29, [sp, #-0x10]! ; stp x30, xzr, [sp, #-0x10]! - ; .dword 0xd53b4218u32 as i32 // mrs x24, nzcv + ; .u32 0xd53b4218_u32 // mrs x24, nzcv // jump to rust based population of the lists ; mov x2, x0 ; adr x3, >done @@ -226,7 +226,7 @@ impl CmpLogRuntime { ; ldr x0, >self_addr ; blr x4 // restore the reg state before returning to the caller - ; .dword 0xd51b4218u32 as i32 // msr nzcv, x24 + ; .u32 0xd51b4218_u32 // msr nzcv, x24 ; ldp x30, xzr, [sp], #0x10 ; ldp x28, x29, [sp], #0x10 ; ldp x26, x27, [sp], #0x10 @@ -244,9 +244,9 @@ impl CmpLogRuntime { ; ldp x2, x3, [sp], #0x10 ; b >done ; self_addr: - ; .qword core::ptr::from_mut(self) as *mut c_void as i64 + ; .u64 core::ptr::from_mut(self) as *mut c_void as u64 ; populate_lists: - ; .qword CmpLogRuntime::populate_lists as *mut c_void as i64 + ; .u64 CmpLogRuntime::populate_lists as *mut c_void as u64 ; done: );}; } diff --git a/libafl_frida/src/coverage_rt.rs b/libafl_frida/src/coverage_rt.rs index 016a8b6089..57a496524c 100644 --- a/libafl_frida/src/coverage_rt.rs +++ b/libafl_frida/src/coverage_rt.rs @@ -1,5 +1,5 @@ //! Functionality regarding binary-only coverage collection. -use core::ptr::addr_of_mut; + use std::{cell::RefCell, marker::PhantomPinned, pin::Pin, rc::Rc}; #[cfg(target_arch = "aarch64")] @@ -83,8 +83,8 @@ impl CoverageRuntime { #[allow(clippy::cast_possible_wrap)] pub fn generate_inline_code(&mut self, h64: u64) -> Box<[u8]> { let mut borrow = self.0.borrow_mut(); - let prev_loc_ptr = addr_of_mut!(borrow.previous_pc); - let map_addr_ptr = addr_of_mut!(borrow.map); + let prev_loc_ptr = &raw mut borrow.previous_pc; + let map_addr_ptr = &raw mut borrow.map; let mut ops = dynasmrt::VecAssembler::::new(0); dynasm!(ops ; .arch aarch64 @@ -141,8 +141,8 @@ impl CoverageRuntime { #[cfg(target_arch = "x86_64")] pub fn generate_inline_code(&mut self, h64: u64) -> Box<[u8]> { let mut borrow = self.0.borrow_mut(); - let prev_loc_ptr = addr_of_mut!(borrow.previous_pc); - let map_addr_ptr = addr_of_mut!(borrow.map); + let prev_loc_ptr = &raw mut borrow.previous_pc; + let map_addr_ptr = &raw mut borrow.map; let mut ops = dynasmrt::VecAssembler::::new(0); dynasm!(ops ; .arch x64 diff --git a/libafl_frida/src/pthread_hook.rs b/libafl_frida/src/pthread_hook.rs index c436251e8b..284a7bcdaa 100644 --- a/libafl_frida/src/pthread_hook.rs +++ b/libafl_frida/src/pthread_hook.rs @@ -63,10 +63,17 @@ impl PreviousHook { unsafe impl Sync for PreviousHook {} // TODO: This could use a RwLock as well +/// The previous hook static mut PREVIOUS_HOOK: PreviousHook = PreviousHook(std::ptr::null()); +/// The currently set hook static CURRENT_HOOK: RwLock> = RwLock::new(None); +/// Get the pointer to the previous hook, mut +fn previous_hook_ptr_mut() -> *mut PreviousHook { + &raw mut PREVIOUS_HOOK +} + extern "C" fn pthread_introspection_hook( event: libc::c_uint, thread: libc::pthread_t, @@ -76,7 +83,7 @@ extern "C" fn pthread_introspection_hook( if let Some(ref hook) = *CURRENT_HOOK.read().unwrap() { hook(event.try_into().unwrap(), thread, addr, size); } - unsafe { PREVIOUS_HOOK.dispatch(event, thread, addr, size) }; + unsafe { (*previous_hook_ptr_mut()).dispatch(event, thread, addr, size) }; } /// Closure type for `pthread_introspection` hooks. @@ -159,7 +166,7 @@ where // Allow because we're sure this isn't from a different code generation unit. if !(prev).is_null() && prev != pthread_introspection_hook as _ { unsafe { - PREVIOUS_HOOK.set(prev as *const pthread_introspection_hook_t); + (*previous_hook_ptr_mut()).set(prev as *const pthread_introspection_hook_t); } } } @@ -176,7 +183,9 @@ where /// # Safety /// Potential data race when if called at the same time as `install` or `reset` from another thread pub unsafe fn reset() { - unsafe { PREVIOUS_HOOK.reset() }; + unsafe { + (*previous_hook_ptr_mut()).reset(); + }; } /// The following tests fail if they are not run sequentially. diff --git a/libafl_libfuzzer/runtime/src/merge.rs b/libafl_libfuzzer/runtime/src/merge.rs index cf50fa799f..506e0a2e41 100644 --- a/libafl_libfuzzer/runtime/src/merge.rs +++ b/libafl_libfuzzer/runtime/src/merge.rs @@ -4,7 +4,6 @@ use std::{ fs::{rename, File}, io::Write, os::fd::{AsRawFd, FromRawFd}, - ptr::addr_of_mut, time::{SystemTime, UNIX_EPOCH}, }; @@ -98,7 +97,7 @@ pub fn merge( } } - let edges = unsafe { core::mem::take(&mut *addr_of_mut!(COUNTERS_MAPS)) }; + let edges = unsafe { core::mem::take(&mut *&raw mut COUNTERS_MAPS) }; let edges_observer = MultiMapObserver::new("edges", edges); let time = TimeObserver::new("time"); diff --git a/libafl_qemu/libafl_qemu_sys/src/lib.rs b/libafl_qemu/libafl_qemu_sys/src/lib.rs index 29cf6683df..8c524fe5bf 100644 --- a/libafl_qemu/libafl_qemu_sys/src/lib.rs +++ b/libafl_qemu/libafl_qemu_sys/src/lib.rs @@ -61,7 +61,7 @@ macro_rules! extern_c_checked { #[cfg_attr(nightly, used(linker))] #[allow(unused_unsafe)] - static [<__ $c_var:upper __>]: [<__ $c_var:upper _STRUCT__>] = unsafe { [<__ $c_var:upper _STRUCT__>] { member: core::ptr::addr_of!($c_var) } }; + static [<__ $c_var:upper __>]: [<__ $c_var:upper _STRUCT__>] = unsafe { [<__ $c_var:upper _STRUCT__>] { member: &raw const $c_var } }; } extern "C" { @@ -81,7 +81,7 @@ macro_rules! extern_c_checked { #[cfg_attr(nightly, used(linker))] #[allow(unused_unsafe)] - static mut [<__ $c_var:upper __>]: [<__ $c_var:upper _STRUCT__>] = unsafe { [<__ $c_var:upper _STRUCT__>] { member: core::ptr::addr_of!($c_var) } }; + static mut [<__ $c_var:upper __>]: [<__ $c_var:upper _STRUCT__>] = unsafe { [<__ $c_var:upper _STRUCT__>] { member: &raw const $c_var } }; } extern "C" { diff --git a/libafl_qemu/src/emu/hooks.rs b/libafl_qemu/src/emu/hooks.rs index 8fbcea5dba..65666ff42f 100644 --- a/libafl_qemu/src/emu/hooks.rs +++ b/libafl_qemu/src/emu/hooks.rs @@ -1,7 +1,5 @@ #![allow(clippy::missing_transmute_annotations)] -#[cfg(feature = "usermode")] -use std::ptr::addr_of_mut; use std::{fmt::Debug, marker::PhantomData, mem::transmute, pin::Pin, ptr}; use libafl::{executors::ExitKind, inputs::UsesInput, observers::ObserversTuple}; @@ -77,7 +75,9 @@ where unsafe { let emulator_modules = EmulatorModules::::emulator_modules_mut().unwrap(); - for crash_hook in &mut (*addr_of_mut!(emulator_modules.hooks.crash_hooks)) { + let crash_hooks_ptr = &raw mut emulator_modules.hooks.crash_hooks; + + for crash_hook in &mut (*crash_hooks_ptr) { match crash_hook { HookRepr::Function(ptr) => { let func: CrashHookFn = transmute(*ptr); diff --git a/libafl_qemu/src/modules/calls.rs b/libafl_qemu/src/modules/calls.rs index 323814b37e..ecb47e1b97 100644 --- a/libafl_qemu/src/modules/calls.rs +++ b/libafl_qemu/src/modules/calls.rs @@ -1,4 +1,4 @@ -use core::{cell::UnsafeCell, fmt::Debug, ptr::addr_of_mut}; +use core::{cell::UnsafeCell, fmt::Debug}; use capstone::prelude::*; use libafl::{ @@ -308,9 +308,11 @@ where &mut [0; 512] }; #[cfg(feature = "systemmode")] - unsafe { - qemu.read_mem(pc, code) - }; // TODO handle faults + if let Err(err) = qemu.read_mem(pc, code) { + // TODO handle faults + log::error!("gen_block_calls: Failed to read mem at pc {pc:#x}: {err:?}"); + return None; + } let mut iaddr = pc; @@ -347,9 +349,13 @@ where code = std::slice::from_raw_parts(qemu.g2h(iaddr), 512); } #[cfg(feature = "systemmode")] - unsafe { - qemu.read_mem(pc, code); - } // TODO handle faults + if let Err(err) = qemu.read_mem(pc, code) { + // TODO handle faults + log::error!( + "gen_block_calls error 2: Failed to read mem at pc {pc:#x}: {err:?}" + ); + return None; + } } } @@ -452,7 +458,7 @@ where #[cfg(feature = "systemmode")] fn page_filter_mut(&mut self) -> &mut Self::ModulePageFilter { - unsafe { addr_of_mut!(NOP_PAGE_FILTER).as_mut().unwrap().get_mut() } + unsafe { (&raw mut NOP_PAGE_FILTER).as_mut().unwrap().get_mut() } } } @@ -547,7 +553,8 @@ impl FullBacktraceCollector { /// # Safety /// This accesses the global [`CALLSTACKS`] variable and may not be called concurrently. pub unsafe fn new() -> Self { - unsafe { (*addr_of_mut!(CALLSTACKS)) = Some(ThreadLocal::new()) }; + let callstacks_ptr = &raw mut CALLSTACKS; + unsafe { (*callstacks_ptr) = Some(ThreadLocal::new()) }; Self {} } @@ -556,8 +563,9 @@ impl FullBacktraceCollector { // This accesses the global [`CALLSTACKS`] variable. // While it is racey, it might be fine if multiple clear the vecs concurrently. // TODO: This should probably be rewritten in a safer way. + let callstacks_ptr = &raw mut CALLSTACKS; unsafe { - for tls in (*addr_of_mut!(CALLSTACKS)).as_mut().unwrap().iter_mut() { + for tls in (*callstacks_ptr).as_mut().unwrap().iter_mut() { (*tls.get()).clear(); } } @@ -567,8 +575,9 @@ impl FullBacktraceCollector { // # Safety // This accesses the global [`CALLSTACKS`] variable. // However, the actual variable access is behind a `ThreadLocal` class. + let callstacks_ptr = &raw mut CALLSTACKS; unsafe { - if let Some(c) = (*addr_of_mut!(CALLSTACKS)).as_mut() { + if let Some(c) = (*callstacks_ptr).as_mut() { Some(&*c.get_or_default().get()) } else { None @@ -589,14 +598,11 @@ impl CallTraceCollector for FullBacktraceCollector { ET: EmulatorModuleTuple, S: Unpin + UsesInput, { + let callstacks_ptr = &raw mut CALLSTACKS; // TODO handle Thumb unsafe { - (*(*addr_of_mut!(CALLSTACKS)) - .as_mut() - .unwrap() - .get_or_default() - .get()) - .push(pc + call_len as GuestAddr); + (*(*callstacks_ptr).as_mut().unwrap().get_or_default().get()) + .push(pc + call_len as GuestAddr); } } @@ -611,12 +617,9 @@ impl CallTraceCollector for FullBacktraceCollector { ET: EmulatorModuleTuple, S: Unpin + UsesInput, { + let callstacks_ptr = &raw mut CALLSTACKS; unsafe { - let v = &mut *(*addr_of_mut!(CALLSTACKS)) - .as_mut() - .unwrap() - .get_or_default() - .get(); + let v = &mut *(*callstacks_ptr).as_mut().unwrap().get_or_default().get(); if !v.is_empty() { // if *v.last().unwrap() == ret_addr { // v.pop(); diff --git a/libafl_qemu/src/modules/cmplog.rs b/libafl_qemu/src/modules/cmplog.rs index 0943d3af6a..b595971374 100644 --- a/libafl_qemu/src/modules/cmplog.rs +++ b/libafl_qemu/src/modules/cmplog.rs @@ -1,6 +1,3 @@ -#[cfg(feature = "systemmode")] -use std::ptr::addr_of_mut; - #[cfg(feature = "usermode")] use capstone::{arch::BuildsCapstone, Capstone, InsnDetail}; use hashbrown::HashMap; @@ -105,7 +102,7 @@ where #[cfg(feature = "systemmode")] fn page_filter_mut(&mut self) -> &mut Self::ModulePageFilter { - unsafe { addr_of_mut!(NOP_PAGE_FILTER).as_mut().unwrap().get_mut() } + unsafe { (&raw mut NOP_PAGE_FILTER).as_mut().unwrap().get_mut() } } } @@ -170,7 +167,7 @@ where #[cfg(feature = "systemmode")] fn page_filter_mut(&mut self) -> &mut Self::ModulePageFilter { - unsafe { addr_of_mut!(NOP_PAGE_FILTER).as_mut().unwrap().get_mut() } + unsafe { (&raw mut NOP_PAGE_FILTER).as_mut().unwrap().get_mut() } } } diff --git a/libafl_qemu/src/modules/drcov.rs b/libafl_qemu/src/modules/drcov.rs index ccd0d8ffd8..5720f2429f 100644 --- a/libafl_qemu/src/modules/drcov.rs +++ b/libafl_qemu/src/modules/drcov.rs @@ -1,5 +1,3 @@ -#[cfg(feature = "systemmode")] -use std::ptr::addr_of_mut; use std::{path::PathBuf, sync::Mutex}; use hashbrown::{hash_map::Entry, HashMap}; @@ -352,7 +350,7 @@ where #[cfg(feature = "systemmode")] fn page_filter_mut(&mut self) -> &mut Self::ModulePageFilter { - unsafe { addr_of_mut!(NOP_PAGE_FILTER).as_mut().unwrap().get_mut() } + unsafe { (&raw mut NOP_PAGE_FILTER).as_mut().unwrap().get_mut() } } } diff --git a/libafl_qemu/src/modules/edges/helpers.rs b/libafl_qemu/src/modules/edges/helpers.rs index bf9f0255e9..497eca14d6 100644 --- a/libafl_qemu/src/modules/edges/helpers.rs +++ b/libafl_qemu/src/modules/edges/helpers.rs @@ -48,7 +48,7 @@ impl QemuEdgesMapMetadata { } mod generators { - use std::{cmp::max, ptr, ptr::addr_of}; + use std::{cmp::max, ptr}; use hashbrown::hash_map::Entry; use libafl::{inputs::UsesInput, HasMetadata}; @@ -95,7 +95,8 @@ mod generators { { unsafe { assert!(LIBAFL_QEMU_EDGES_MAP_MASK_MAX > 0); - assert_ne!(*addr_of!(LIBAFL_QEMU_EDGES_MAP_SIZE_PTR), ptr::null_mut()); + let edges_map_size_ptr = &raw const LIBAFL_QEMU_EDGES_MAP_SIZE_PTR; + assert_ne!(*edges_map_size_ptr, ptr::null_mut()); } #[cfg(feature = "usermode")] diff --git a/libafl_qemu/src/modules/edges/mod.rs b/libafl_qemu/src/modules/edges/mod.rs index e3fc3efb4e..db2538ca7e 100644 --- a/libafl_qemu/src/modules/edges/mod.rs +++ b/libafl_qemu/src/modules/edges/mod.rs @@ -365,7 +365,6 @@ where #[cfg(any(test, doc))] mod tests { - use std::ptr::addr_of_mut; use libafl::observers::{CanTrack, HitcountsMapObserver, VariableMapObserver}; use libafl_bolts::ownedref::OwnedMutSlice; @@ -390,7 +389,7 @@ mod tests { HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/libafl_qemu/src/modules/usermode/injections.rs b/libafl_qemu/src/modules/usermode/injections.rs index 43fc0fb1dc..56a3b22ce1 100644 --- a/libafl_qemu/src/modules/usermode/injections.rs +++ b/libafl_qemu/src/modules/usermode/injections.rs @@ -11,7 +11,7 @@ * */ -use std::{ffi::CStr, fmt::Display, fs, os::raw::c_char, path::Path, ptr::addr_of_mut}; +use std::{ffi::CStr, fmt::Display, fs, os::raw::c_char, path::Path}; use hashbrown::HashMap; use libafl::{inputs::UsesInput, Error}; @@ -339,16 +339,19 @@ where } fn address_filter_mut(&mut self) -> &mut Self::ModuleAddressFilter { - unsafe { addr_of_mut!(NOP_ADDRESS_FILTER).as_mut().unwrap().get_mut() } + unsafe { (&raw mut NOP_ADDRESS_FILTER).as_mut().unwrap().get_mut() } } } #[allow(clippy::too_many_arguments)] fn syscall_hook( - emulator_modules: &mut EmulatorModules, // our instantiated QemuHooks + // Our instantiated [`EmulatorModules`] + emulator_modules: &mut EmulatorModules, _state: Option<&mut S>, - syscall: i32, // syscall number - x0: GuestAddr, // registers ... + // Syscall number + syscall: i32, + // Registers + x0: GuestAddr, x1: GuestAddr, _x2: GuestAddr, _x3: GuestAddr, diff --git a/libafl_qemu/src/modules/usermode/snapshot.rs b/libafl_qemu/src/modules/usermode/snapshot.rs index e20cfd466e..d2447238ce 100644 --- a/libafl_qemu/src/modules/usermode/snapshot.rs +++ b/libafl_qemu/src/modules/usermode/snapshot.rs @@ -1,4 +1,4 @@ -use std::{cell::UnsafeCell, mem::MaybeUninit, ptr::addr_of_mut, sync::Mutex}; +use std::{cell::UnsafeCell, mem::MaybeUninit, sync::Mutex}; use hashbrown::{HashMap, HashSet}; use libafl::inputs::UsesInput; @@ -717,7 +717,7 @@ where } fn address_filter_mut(&mut self) -> &mut Self::ModuleAddressFilter { - unsafe { addr_of_mut!(NOP_ADDRESS_FILTER).as_mut().unwrap().get_mut() } + unsafe { (&raw mut NOP_ADDRESS_FILTER).as_mut().unwrap().get_mut() } } } diff --git a/libafl_qemu/src/qemu/mod.rs b/libafl_qemu/src/qemu/mod.rs index 57fcef453c..740322ecb4 100644 --- a/libafl_qemu/src/qemu/mod.rs +++ b/libafl_qemu/src/qemu/mod.rs @@ -5,8 +5,7 @@ use core::{ cmp::{Ordering, PartialOrd}, - fmt, - ptr::{self, addr_of_mut}, + fmt, ptr, }; use std::{ ffi::{c_void, CString}, @@ -398,8 +397,7 @@ impl CPU { #[cfg(not(feature = "be"))] let val = GuestReg::to_le(val.into()); - let success = - unsafe { libafl_qemu_write_reg(self.ptr, reg_id, ptr::addr_of!(val) as *mut u8) }; + let success = unsafe { libafl_qemu_write_reg(self.ptr, reg_id, &raw const val as *mut u8) }; if success == 0 { Err(QemuRWError { kind: QemuRWErrorKind::Write, @@ -894,7 +892,8 @@ impl Qemu { FatPtr, >(callback)); libafl_qemu_add_gdb_cmd(Some(gdb_cmd), ptr::from_ref(&*fat) as *mut c_void); - (*addr_of_mut!(GDB_COMMANDS)).push(fat); + let commands_ptr = &raw mut GDB_COMMANDS; + (*commands_ptr).push(fat); } pub fn gdb_reply(&self, output: &str) { @@ -1108,7 +1107,7 @@ pub mod pybind { extern "C" fn py_generic_hook_wrapper(idx: u64, _pc: GuestAddr) { let obj = unsafe { - let hooks = &mut *core::ptr::addr_of_mut!(PY_GENERIC_HOOKS); + let hooks = &mut *&raw mut PY_GENERIC_HOOKS; &hooks[idx as usize].1 }; Python::with_gil(|py| { @@ -1188,7 +1187,7 @@ pub mod pybind { /// Removes a hooke from `PY_GENERIC_HOOKS` -> may not be called concurrently! unsafe fn set_hook(&self, addr: GuestAddr, hook: PyObject) { unsafe { - let hooks = &mut *core::ptr::addr_of_mut!(PY_GENERIC_HOOKS); + let hooks = &mut *&raw mut PY_GENERIC_HOOKS; let idx = hooks.len(); hooks.push((addr, hook)); self.qemu.hooks().add_instruction_hooks( @@ -1204,7 +1203,7 @@ pub mod pybind { /// Removes a hooke from `PY_GENERIC_HOOKS` -> may not be called concurrently! unsafe fn remove_hooks_at(&self, addr: GuestAddr) -> usize { unsafe { - let hooks = &mut *core::ptr::addr_of_mut!(PY_GENERIC_HOOKS); + let hooks = &mut *&raw mut PY_GENERIC_HOOKS; hooks.retain(|(a, _)| *a != addr); } self.qemu.hooks().remove_instruction_hooks_at(addr, true) diff --git a/libafl_qemu/src/qemu/usermode.rs b/libafl_qemu/src/qemu/usermode.rs index 543b45c4c3..955de9536d 100644 --- a/libafl_qemu/src/qemu/usermode.rs +++ b/libafl_qemu/src/qemu/usermode.rs @@ -281,7 +281,7 @@ pub mod pybind { a6: u64, a7: u64, ) -> SyscallHookResult { - unsafe { (*core::ptr::addr_of!(PY_SYSCALL_HOOK)).as_ref() }.map_or_else( + unsafe { (*&raw const PY_SYSCALL_HOOK).as_ref() }.map_or_else( || SyscallHookResult::new(None), |obj| { let args = (sys_num, a0, a1, a2, a3, a4, a5, a6, a7); @@ -362,7 +362,7 @@ pub mod pybind { /// Accesses the global `PY_SYSCALL_HOOK` and may not be called concurrently. unsafe fn set_syscall_hook(&self, hook: PyObject) { unsafe { - (*core::ptr::addr_of_mut!(PY_SYSCALL_HOOK)) = Some(hook); + (*&raw mut (PY_SYSCALL_HOOK)) = Some(hook); } self.qemu .hooks() diff --git a/libafl_sugar/src/qemu.rs b/libafl_sugar/src/qemu.rs index 479abea9c2..f9d3958f57 100644 --- a/libafl_sugar/src/qemu.rs +++ b/libafl_sugar/src/qemu.rs @@ -1,9 +1,6 @@ //! In-memory fuzzer with `QEMU`-based binary-only instrumentation //! -use core::{ - fmt::{self, Debug, Formatter}, - ptr::addr_of_mut, -}; +use core::fmt::{self, Debug, Formatter}; use std::{fs, net::SocketAddr, path::PathBuf, time::Duration}; use libafl::{ @@ -162,7 +159,7 @@ where HitcountsMapObserver::new(VariableMapObserver::from_mut_slice( "edges", OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE), - addr_of_mut!(MAX_EDGES_FOUND), + &raw mut MAX_EDGES_FOUND, )) .track_indices() }; diff --git a/libafl_targets/src/call.rs b/libafl_targets/src/call.rs index 38a20a7611..c3fcc38892 100644 --- a/libafl_targets/src/call.rs +++ b/libafl_targets/src/call.rs @@ -1,4 +1,4 @@ -use core::{marker::PhantomData, ptr::addr_of_mut}; +use core::marker::PhantomData; use hashbrown::HashMap; use libafl::{ @@ -15,7 +15,8 @@ pub static mut FUNCTION_LIST: Lazy> = Lazy::new(HashMap::n /// unsafe because it touches the pub static mut `FUNCTION_LIST`. /// May not be called concurrently. pub unsafe extern "C" fn __libafl_target_call_hook(id: usize) { - let function_list = &mut *addr_of_mut!(FUNCTION_LIST); + let function_list_ptr = &raw mut FUNCTION_LIST; + let function_list = &mut *function_list_ptr; *function_list.entry(id).or_insert(0) += 1; } @@ -47,7 +48,8 @@ where // This typically happens while no other execution happens. // In theory there is a race, but we can ignore it _for this use case_. unsafe { - let function_list = &mut *addr_of_mut!(FUNCTION_LIST); + let function_list_ptr = &raw mut FUNCTION_LIST; + let function_list = &mut *function_list_ptr; function_list.clear(); } } diff --git a/libafl_targets/src/coverage.rs b/libafl_targets/src/coverage.rs index 7487656073..c93e5f3a4e 100644 --- a/libafl_targets/src/coverage.rs +++ b/libafl_targets/src/coverage.rs @@ -4,18 +4,10 @@ feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts", feature = "sancov_ngram4", + feature = "sancov_ngram8", feature = "sancov_ctx" ))] use alloc::borrow::Cow; -#[cfg(any( - feature = "sancov_pcguard_edges", - feature = "sancov_pcguard_hitcounts", - feature = "sancov_ngram4", - feature = "sancov_ctx" -))] -#[cfg(not(feature = "pointer_maps"))] -use core::ptr::addr_of; -use core::ptr::addr_of_mut; #[cfg(any(target_os = "linux", target_vendor = "apple"))] use libafl::{mutators::Tokens, Error}; @@ -73,6 +65,7 @@ pub use __ddg_area_ptr as DDG_MAP_PTR; pub fn autotokens() -> Result { // # Safety // All values are checked before dereferencing. + unsafe { if __token_start.is_null() || __token_stop.is_null() { Ok(Tokens::default()) @@ -93,6 +86,7 @@ pub static mut __afl_map_size: usize = EDGES_MAP_DEFAULT_SIZE; feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts", feature = "sancov_ngram4", + feature = "sancov_ngram8", feature = "sancov_ctx" ))] use libafl::observers::StdMapObserver; @@ -100,6 +94,7 @@ use libafl::observers::StdMapObserver; feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts", feature = "sancov_ngram4", + feature = "sancov_ngram8", feature = "sancov_ctx" ))] use libafl_bolts::ownedref::OwnedMutSlice; @@ -116,6 +111,7 @@ use libafl_bolts::ownedref::OwnedMutSlice; feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts", feature = "sancov_ngram4", + feature = "sancov_ngram8", feature = "sancov_ctx" ))] pub unsafe fn edges_map_mut_slice<'a>() -> OwnedMutSlice<'a, u8> { @@ -153,6 +149,7 @@ pub unsafe fn edges_map_mut_slice<'a>() -> OwnedMutSlice<'a, u8> { feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts", feature = "sancov_ngram4", + feature = "sancov_ngram8", feature = "sancov_ctx" ))] pub unsafe fn std_edges_map_observer<'a, S>(name: S) -> StdMapObserver<'a, u8, false> @@ -172,7 +169,7 @@ pub fn edges_map_mut_ptr() -> *mut u8 { assert!(!EDGES_MAP_PTR.is_null()); EDGES_MAP_PTR } else { - addr_of_mut!(EDGES_MAP) as *mut u8 + &raw mut EDGES_MAP as *mut u8 } } } @@ -182,6 +179,7 @@ pub fn edges_map_mut_ptr() -> *mut u8 { feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts", feature = "sancov_ngram4", + feature = "sancov_ngram8", feature = "sancov_ctx" ))] #[must_use] @@ -196,7 +194,8 @@ pub fn edges_max_num() -> usize { } #[cfg(not(feature = "pointer_maps"))] { - (*addr_of!(EDGES_MAP)).len() + let edges_map_ptr = &raw const EDGES_MAP; + (*edges_map_ptr).len() } } } diff --git a/libafl_targets/src/drcov.rs b/libafl_targets/src/drcov.rs index 1e8832c1b3..a5a7a901be 100644 --- a/libafl_targets/src/drcov.rs +++ b/libafl_targets/src/drcov.rs @@ -4,7 +4,6 @@ //! [bncov](https://github.com/ForAllSecure/bncov), [dragondance](https://github.com/0ffffffffh/dragondance), etc. use alloc::{string::String, vec::Vec}; -use core::ptr::addr_of; use std::{ fs::File, io::{BufWriter, Write}, @@ -101,7 +100,7 @@ impl<'a> DrCovWriter<'a> { }; writer .write_all(unsafe { - std::slice::from_raw_parts(addr_of!(basic_block) as *const u8, 8) + std::slice::from_raw_parts(&raw const (basic_block) as *const u8, 8) }) .unwrap(); } diff --git a/libafl_targets/src/lib.rs b/libafl_targets/src/lib.rs index 0e93351af5..74a6c5fce4 100644 --- a/libafl_targets/src/lib.rs +++ b/libafl_targets/src/lib.rs @@ -55,6 +55,7 @@ include!(concat!(env!("OUT_DIR"), "/constants.rs")); feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts", feature = "sancov_ngram4", + feature = "sancov_ngram8", feature = "sancov_ctx" ))] pub mod sancov_pcguard; @@ -62,6 +63,7 @@ pub mod sancov_pcguard; feature = "sancov_pcguard_edges", feature = "sancov_pcguard_hitcounts", feature = "sancov_ngram4", + feature = "sancov_ngram8", feature = "sancov_ctx" ))] pub use sancov_pcguard::*; diff --git a/libafl_targets/src/libfuzzer/mod.rs b/libafl_targets/src/libfuzzer/mod.rs index 5de51c0d4b..31bae56d35 100644 --- a/libafl_targets/src/libfuzzer/mod.rs +++ b/libafl_targets/src/libfuzzer/mod.rs @@ -36,7 +36,7 @@ pub unsafe fn libfuzzer_initialize(args: &[String]) -> i32 { let argc = argv.len() as i32; unsafe { let argv_ptr = argv.as_ptr(); - libafl_targets_libfuzzer_init(core::ptr::addr_of!(argc), core::ptr::addr_of!(argv_ptr)) + libafl_targets_libfuzzer_init(&raw const argc, &raw const argv_ptr) } } diff --git a/libafl_targets/src/sancov_8bit.rs b/libafl_targets/src/sancov_8bit.rs index 4a0243aab9..b4ef07bcde 100644 --- a/libafl_targets/src/sancov_8bit.rs +++ b/libafl_targets/src/sancov_8bit.rs @@ -1,6 +1,5 @@ //! [`LLVM` `8-bit-counters`](https://clang.llvm.org/docs/SanitizerCoverage.html#tracing-pcs-with-guards) runtime for `LibAFL`. use alloc::vec::Vec; -use core::ptr::{addr_of, addr_of_mut}; use libafl_bolts::{ownedref::OwnedMutSlice, AsSlice, AsSliceMut}; @@ -8,13 +7,23 @@ use libafl_bolts::{ownedref::OwnedMutSlice, AsSlice, AsSliceMut}; /// They are initialized by calling [`__sanitizer_cov_8bit_counters_init`]( pub static mut COUNTERS_MAPS: Vec> = Vec::new(); +/// Gets a pointer to [`COUNTER_MAPS`] +fn counter_maps_ptr() -> *const Vec> { + &raw const COUNTERS_MAPS +} + +/// Gets a pointer to [`COUNTER_MAPS`], mut +fn counter_maps_ptr_mut() -> *mut Vec> { + &raw mut COUNTERS_MAPS +} + /// Create more copies of the counters maps /// /// # Safety /// You are responsible for ensuring there is no multi-mutability! #[must_use] pub unsafe fn extra_counters() -> Vec> { - let counter_maps = &*addr_of!(COUNTERS_MAPS); + let counter_maps = &*counter_maps_ptr(); counter_maps .iter() .map(|counters| { @@ -35,7 +44,7 @@ pub unsafe fn extra_counters() -> Vec> { #[allow(clippy::not_unsafe_ptr_arg_deref)] pub unsafe extern "C" fn __sanitizer_cov_8bit_counters_init(start: *mut u8, stop: *mut u8) { unsafe { - let counter_maps = &mut *addr_of_mut!(COUNTERS_MAPS); + let counter_maps = &mut *counter_maps_ptr_mut(); for existing in counter_maps { let range = existing.as_slice_mut().as_mut_ptr() ..=existing @@ -52,7 +61,7 @@ pub unsafe extern "C" fn __sanitizer_cov_8bit_counters_init(start: *mut u8, stop } } - let counter_maps = &mut *addr_of_mut!(COUNTERS_MAPS); + let counter_maps = &mut *counter_maps_ptr_mut(); // we didn't overlap; keep going counter_maps.push(OwnedMutSlice::from_raw_parts_mut( start, @@ -72,7 +81,6 @@ mod observers { hash::{Hash, Hasher}, iter::Flatten, mem::size_of, - ptr::{addr_of, addr_of_mut}, slice::{from_raw_parts, Iter, IterMut}, }; @@ -87,13 +95,13 @@ mod observers { use meminterval::IntervalTree; use serde::{Deserialize, Serialize}; - use super::COUNTERS_MAPS; + use super::{counter_maps_ptr, counter_maps_ptr_mut}; #[must_use] #[export_name = "counters_maps_observer"] - /// Create a new [`CountersMultiMapObserver`] of the [`COUNTERS_MAPS`]. + /// Create a new [`CountersMultiMapObserver`] of the [`super::COUNTERS_MAPS`]. /// - /// This is a special [`libafl::observers::MultiMapObserver`] for the [`COUNTERS_MAPS`] and may be used when + /// This is a special [`libafl::observers::MultiMapObserver`] for the [`super::COUNTERS_MAPS`] and may be used when /// 8-bit counters are used for `SanitizerCoverage`. You can utilize this observer in a /// [`libafl::observers::HitcountsIterableMapObserver`] like so: /// @@ -119,7 +127,7 @@ mod observers { } /// The [`CountersMultiMapObserver`] observes all the counters that may be set by - /// `SanitizerCoverage` in [`COUNTERS_MAPS`] + /// `SanitizerCoverage` in [`super::COUNTERS_MAPS`] #[derive(Serialize, Deserialize, Debug)] #[allow(clippy::unsafe_derive_deserialize)] pub struct CountersMultiMapObserver { @@ -163,7 +171,7 @@ mod observers { impl Hash for CountersMultiMapObserver { fn hash(&self, hasher: &mut H) { - for map in unsafe { &*addr_of!(COUNTERS_MAPS) } { + for map in unsafe { &*counter_maps_ptr() } { let slice = map.as_slice(); let ptr = slice.as_ptr(); let map_size = slice.len() / size_of::(); @@ -194,7 +202,7 @@ mod observers { let elem = self.intervals.query(idx..=idx).next().unwrap(); let i = elem.value; let j = idx - elem.interval.start; - unsafe { (*addr_of!(COUNTERS_MAPS[*i])).as_slice()[j] } + unsafe { (*counter_maps_ptr())[*i].as_slice()[j] } } #[inline] @@ -202,7 +210,7 @@ mod observers { let elem = self.intervals.query_mut(idx..=idx).next().unwrap(); let i = elem.value; let j = idx - elem.interval.start; - unsafe { (*addr_of_mut!(COUNTERS_MAPS[*i])).as_slice_mut()[j] = val }; + unsafe { (*counter_maps_ptr_mut())[*i].as_slice_mut()[j] = val }; } #[inline] @@ -213,7 +221,7 @@ mod observers { fn count_bytes(&self) -> u64 { let initial = self.initial(); let mut res = 0; - for map in unsafe { &*addr_of!(COUNTERS_MAPS) } { + for map in unsafe { &*counter_maps_ptr() } { for x in map.as_slice() { if *x != initial { res += 1; @@ -230,7 +238,7 @@ mod observers { fn reset_map(&mut self) -> Result<(), Error> { let initial = self.initial(); - for map in unsafe { &mut *addr_of_mut!(COUNTERS_MAPS) } { + for map in unsafe { &mut *counter_maps_ptr_mut() } { for x in map.as_slice_mut() { *x = initial; } @@ -271,7 +279,7 @@ mod observers { fn maybe_differential(name: &'static str) -> Self { let mut idx = 0; let mut intervals = IntervalTree::new(); - for (v, x) in unsafe { &*addr_of!(COUNTERS_MAPS) }.iter().enumerate() { + for (v, x) in unsafe { &*counter_maps_ptr() }.iter().enumerate() { let l = x.as_slice().len(); intervals.insert(idx..(idx + l), v); idx += l; @@ -307,7 +315,7 @@ mod observers { let mut idx = 0; let mut v = 0; let mut intervals = IntervalTree::new(); - unsafe { &mut *addr_of_mut!(COUNTERS_MAPS) } + unsafe { &mut *counter_maps_ptr_mut() } .iter_mut() .for_each(|m| { let l = m.as_slice_mut().len(); @@ -332,7 +340,7 @@ mod observers { fn as_iter(&'it self) -> Self::IntoIter { unsafe { - let counters_maps = &*addr_of!(COUNTERS_MAPS); + let counters_maps = &*counter_maps_ptr(); counters_maps.iter().flatten() } } @@ -344,7 +352,7 @@ mod observers { fn as_iter_mut(&'it mut self) -> Self::IntoIterMut { unsafe { - let counters_maps = &mut *addr_of_mut!(COUNTERS_MAPS); + let counters_maps = &mut *counter_maps_ptr_mut(); counters_maps.iter_mut().flatten() } } @@ -355,7 +363,7 @@ mod observers { type IntoIter = Flatten>>; fn into_iter(self) -> Self::IntoIter { - unsafe { &*addr_of!(COUNTERS_MAPS) }.iter().flatten() + unsafe { &*counter_maps_ptr() }.iter().flatten() } } @@ -366,9 +374,7 @@ mod observers { type IntoIter = Flatten>>; fn into_iter(self) -> Self::IntoIter { - unsafe { &mut *addr_of_mut!(COUNTERS_MAPS) } - .iter_mut() - .flatten() + unsafe { &mut *counter_maps_ptr_mut() }.iter_mut().flatten() } } diff --git a/libafl_targets/src/sancov_pcguard.rs b/libafl_targets/src/sancov_pcguard.rs index 0cb0b73681..3fc2e63adc 100644 --- a/libafl_targets/src/sancov_pcguard.rs +++ b/libafl_targets/src/sancov_pcguard.rs @@ -3,11 +3,7 @@ #[rustversion::nightly] #[cfg(any(feature = "sancov_ngram4", feature = "sancov_ngram8"))] use core::simd::num::SimdUint; -use core::{ - mem::align_of, - ptr::{addr_of, addr_of_mut}, - slice, -}; +use core::{mem::align_of, slice}; #[cfg(any( feature = "sancov_ngram4", @@ -22,6 +18,7 @@ use libafl::executors::{hooks::ExecutorHook, HasObservers}; feature = "sancov_pcguard_hitcounts", feature = "sancov_ctx", feature = "sancov_ngram4", + feature = "sancov_ngram8", ))] use crate::coverage::EDGES_MAP; use crate::coverage::MAX_EDGES_FOUND; @@ -190,7 +187,8 @@ unsafe fn update_ngram(pos: usize) -> usize { let mut reduced = pos; #[cfg(feature = "sancov_ngram4")] { - let prev_array_4 = &mut *addr_of_mut!(PREV_ARRAY_4); + let prev_array_4_ptr = &raw mut PREV_ARRAY_4; + let prev_array_4 = &mut *prev_array_4_ptr; *prev_array_4 = prev_array_4.rotate_elements_right::<1>(); prev_array_4.shl_assign(SHR_4); prev_array_4.as_mut_array()[0] = pos as u32; @@ -198,7 +196,8 @@ unsafe fn update_ngram(pos: usize) -> usize { } #[cfg(feature = "sancov_ngram8")] { - let prev_array_8 = &mut *addr_of_mut!(PREV_ARRAY_8); + let prev_array_8_ptr = &raw mut PREV_ARRAY_8; + let prev_array_8 = &mut *prev_array_8_ptr; *prev_array_8 = prev_array_8.rotate_elements_right::<1>(); prev_array_8.shl_assign(SHR_8); prev_array_8.as_mut_array()[0] = pos as u32; @@ -256,8 +255,10 @@ pub unsafe extern "C" fn __sanitizer_cov_trace_pc_guard(guard: *mut u32) { } } #[cfg(not(feature = "pointer_maps"))] + #[cfg(any(feature = "sancov_pcguard_hitcounts", feature = "sancov_pcguard_edges"))] { - let edges_map = &mut *addr_of_mut!(EDGES_MAP); + let edges_map_ptr = &raw mut EDGES_MAP; + let edges_map = &mut *edges_map_ptr; #[cfg(feature = "sancov_pcguard_edges")] { *(edges_map).get_unchecked_mut(pos) = 1; @@ -278,7 +279,7 @@ pub unsafe extern "C" fn __sanitizer_cov_trace_pc_guard(guard: *mut u32) { pub unsafe extern "C" fn __sanitizer_cov_trace_pc_guard_init(mut start: *mut u32, stop: *mut u32) { #[cfg(feature = "pointer_maps")] if EDGES_MAP_PTR.is_null() { - EDGES_MAP_PTR = addr_of_mut!(EDGES_MAP) as *mut u8; + EDGES_MAP_PTR = &raw mut EDGES_MAP as *mut u8; } if start == stop || *start != 0 { @@ -295,7 +296,8 @@ pub unsafe extern "C" fn __sanitizer_cov_trace_pc_guard_init(mut start: *mut u32 } #[cfg(not(feature = "pointer_maps"))] { - let edges_map_len = (*addr_of!(EDGES_MAP)).len(); + let edges_map_ptr = &raw const EDGES_MAP; + let edges_map_len = (*edges_map_ptr).len(); MAX_EDGES_FOUND = MAX_EDGES_FOUND.wrapping_add(1); assert!((MAX_EDGES_FOUND <= edges_map_len), "The number of edges reported by SanitizerCoverage exceed the size of the edges map ({edges_map_len}). Use the LIBAFL_EDGES_MAP_DEFAULT_SIZE env to increase it at compile time."); } @@ -320,7 +322,8 @@ unsafe extern "C" fn __sanitizer_cov_pcs_init(pcs_beg: *const usize, pcs_end: *c "Unaligned PC Table - start: {pcs_beg:x?} end: {pcs_end:x?}" ); - let pc_tables = &mut *addr_of_mut!(PC_TABLES); + let pc_tables_ptr = &raw mut PC_TABLES; + let pc_tables = &mut *pc_tables_ptr; pc_tables.push(slice::from_raw_parts(pcs_beg as *const PcTableEntry, len)); } @@ -351,7 +354,8 @@ pub fn sanitizer_cov_pc_table<'a>() -> impl Iterator // SAFETY: Once PCS_BEG and PCS_END have been initialized, will not be written to again. So // there's no TOCTOU issue. unsafe { - let pc_tables = &*addr_of!(PC_TABLES); + let pc_tables_ptr = &raw const PC_TABLES; + let pc_tables = &*pc_tables_ptr; pc_tables.iter().copied() } } diff --git a/scripts/parallellize_cargo_check.py b/scripts/parallellize_cargo_check.py index d05ee64a24..f736c20a0c 100755 --- a/scripts/parallellize_cargo_check.py +++ b/scripts/parallellize_cargo_check.py @@ -40,10 +40,12 @@ print("Running ", task) print(os.environ) - if ("utils/libafl_jumper/Cargo.toml" in task - and "--no-default-features" in task - and "--features" not in task): - # ignore libafl_jumper no std + if ( + "utils/libafl_jumper/Cargo.toml" in task + and "--no-default-features" in task + and "--features" not in task + ): + # ignore libafl_jumper no std continue if "libafl_frida" in task: