diff --git a/Cargo.toml b/Cargo.toml index 86b8c4a001..3386088bfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -156,8 +156,8 @@ std_instead_of_core = "deny" cargo = { level = "warn", priority = -1 } # Allow -negative_feature_names = "allow" # TODO: turn into 'warn' when working -multiple_crate_versions = "allow" # TODO: turn into `warn` when working +negative_feature_names = "allow" # TODO: turn into 'warn' when working +multiple_crate_versions = "allow" # TODO: turn into `warn` when working unreadable_literal = "allow" type_repetition_in_bounds = "allow" missing_errors_doc = "allow" @@ -169,8 +169,8 @@ module_name_repetitions = "allow" unsafe_derive_deserialize = "allow" similar_names = "allow" too_many_lines = "allow" -comparison_chain = "allow" # This lint makes **ZERO** sense - +comparison_chain = "allow" # This lint makes **ZERO** sense +unnecessary_debug_formatting = "allow" # :thumbsdown: :thumbsdown: :thumbsdown: :thumbsdown: :thumbsdown: :thumbsdown: [workspace.lints.rustdoc] # Deny diff --git a/Dockerfile b/Dockerfile index b467e1a0ca..fe57bdd19b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -68,28 +68,33 @@ RUN set -ex &&\ chmod +x llvm.sh &&\ ./llvm.sh ${LLVM_VERSION} +RUN apt-get update && \ + apt-get install -y \ + clang-format-${LLVM_VERSION} + RUN git config --global core.pager cat # Install a modern version of QEMU - WORKDIR /root ENV QEMU_VER=9.2.1 -RUN wget https://download.qemu.org/qemu-${QEMU_VER}.tar.xz -RUN tar xvJf qemu-${QEMU_VER}.tar.xz -WORKDIR /root/qemu-${QEMU_VER} -RUN ./configure --target-list="\ - arm-linux-user,\ - aarch64-linux-user,\ - i386-linux-user,\ - ppc-linux-user,\ - mips-linux-user,\ - arm-softmmu,\ - aarch64-softmmu,\ - i386-softmmu,\ - ppc-softmmu,\ - mips-softmmu" -RUN make -j -RUN make install +RUN wget https://download.qemu.org/qemu-${QEMU_VER}.tar.xz && \ + tar xvJf qemu-${QEMU_VER}.tar.xz && \ + cd /root/qemu-${QEMU_VER} && \ + ./configure --target-list="\ + arm-linux-user,\ + aarch64-linux-user,\ + i386-linux-user,\ + ppc-linux-user,\ + mips-linux-user,\ + arm-softmmu,\ + aarch64-softmmu,\ + i386-softmmu,\ + ppc-softmmu,\ + mips-softmmu" && \ + make -j && \ + make install && \ + cd /root && \ + rm -rf qemu-${QEMU_VER} # Copy a dummy.rs and Cargo.toml first, so that dependencies are cached WORKDIR /libafl diff --git a/fuzzers/forkserver/libafl-fuzz/src/corpus.rs b/fuzzers/forkserver/libafl-fuzz/src/corpus.rs index a69efdb702..6d5376adc5 100644 --- a/fuzzers/forkserver/libafl-fuzz/src/corpus.rs +++ b/fuzzers/forkserver/libafl-fuzz/src/corpus.rs @@ -146,12 +146,10 @@ pub fn check_autoresume(fuzzer_dir: &Path, auto_resume: bool) -> Result io::Result<()> { if path.is_file() { - return Err(io::Error::new( - // TODO: change this to ErrorKind::NotADirectory - // when stabilitzed https://github.com/rust-lang/rust/issues/86442 - io::ErrorKind::Other, - format!("{} expected a directory; got a file", path.display()), - )); + return Err(io::Error::other(format!( + "{} expected a directory; got a file", + path.display() + ))); } match std::fs::create_dir(path) { Ok(()) => Ok(()), diff --git a/fuzzers/forkserver/libafl-fuzz/src/feedback/seed.rs b/fuzzers/forkserver/libafl-fuzz/src/feedback/seed.rs index 9f18cb5665..89aec0b462 100644 --- a/fuzzers/forkserver/libafl-fuzz/src/feedback/seed.rs +++ b/fuzzers/forkserver/libafl-fuzz/src/feedback/seed.rs @@ -100,12 +100,6 @@ where Ok(()) } - /// Discard the stored metadata in case that the testcase is not added to the corpus - #[inline] - fn discard_metadata(&mut self, state: &mut S, input: &I) -> Result<(), Error> { - self.inner.discard_metadata(state, input)?; - Ok(()) - } #[cfg(feature = "track_hit_feedbacks")] fn last_result(&self) -> Result { self.inner.last_result() diff --git a/fuzzers/inprocess/fuzzbench_ctx/src/lib.rs b/fuzzers/inprocess/fuzzbench_ctx/src/lib.rs index 8bf1081663..02c5f0e339 100644 --- a/fuzzers/inprocess/fuzzbench_ctx/src/lib.rs +++ b/fuzzers/inprocess/fuzzbench_ctx/src/lib.rs @@ -345,16 +345,6 @@ fn fuzz( let mut tracing_harness = harness; let ctx_hook = CtxHook::new(); - // Create the executor for an in-process function with one observer for edge coverage and one for the execution time - let mut executor = HookableInProcessExecutor::with_timeout_generic( - tuple_list!(ctx_hook), - &mut harness, - tuple_list!(edges_observer, time_observer), - &mut fuzzer, - &mut state, - &mut mgr, - timeout, - )?; // Setup a tracing stage in which we log comparisons let tracing = TracingStage::new( @@ -369,6 +359,17 @@ fn fuzz( // Give it more time! ); + // Create the executor for an in-process function with one observer for edge coverage and one for the execution time + let mut executor = HookableInProcessExecutor::with_timeout_generic( + tuple_list!(ctx_hook), + &mut harness, + tuple_list!(edges_observer, time_observer), + &mut fuzzer, + &mut state, + &mut mgr, + timeout, + )?; + // The order of the stages matter! let mut stages = tuple_list!(calibration, tracing, i2s, power); diff --git a/libafl/src/events/launcher.rs b/libafl/src/events/launcher.rs index 3f0d7ce8b8..b7f7aeb52f 100644 --- a/libafl/src/events/launcher.rs +++ b/libafl/src/events/launcher.rs @@ -274,7 +274,7 @@ where // Spawn clients let mut index = 0_usize; for bind_to in core_ids { - if self.cores.ids.iter().any(|&x| x == bind_to) { + if self.cores.ids.contains(&bind_to) { for overcommit_id in 0..self.overcommit { index += 1; self.shmem_provider.pre_fork()?; @@ -456,7 +456,7 @@ where //spawn clients let mut index = 0; for core_id in core_ids { - if self.cores.ids.iter().any(|&x| x == core_id) { + if self.cores.ids.contains(&core_id) { for overcommit_i in 0..self.overcommit { index += 1; // Forward own stdio to child processes, if requested by user @@ -748,7 +748,7 @@ where // Spawn clients let mut index = 0_usize; for bind_to in core_ids { - if self.cores.ids.iter().any(|&x| x == bind_to) { + if self.cores.ids.contains(&bind_to) { for overcommit_id in 0..self.overcommit { index += 1; self.shmem_provider.pre_fork()?; diff --git a/libafl/src/executors/hooks/inprocess.rs b/libafl/src/executors/hooks/inprocess.rs index b7d8b28d92..3156b6e572 100644 --- a/libafl/src/executors/hooks/inprocess.rs +++ b/libafl/src/executors/hooks/inprocess.rs @@ -24,7 +24,7 @@ use windows::Win32::System::Threading::{CRITICAL_SECTION, PTP_TIMER}; #[cfg(feature = "std")] use crate::executors::hooks::timer::TimerStruct; use crate::{ - Error, HasObjective, + Error, HasFeedback, HasObjective, events::{EventFirer, EventRestarter}, executors::{Executor, HasObservers, hooks::ExecutorHook, inprocess::HasInProcessHooks}, feedbacks::Feedback, @@ -202,7 +202,7 @@ impl ExecutorHook for InProcessHooks { // Imagine there are two executors, you have to set the correct crash handlers for each of the executor. unsafe { let data = &raw mut GLOBAL_STATE; - assert!((*data).crash_handler == null()); + assert!((*data).crash_handler.is_null()); // usually timeout handler and crash handler is set together // so no check for timeout handler is null or not (*data).crash_handler = self.crash_handler; @@ -232,14 +232,15 @@ impl InProcessHooks { /// Create new [`InProcessHooks`]. #[cfg(unix)] #[allow(unused_variables)] // for `exec_tmout` without `std` - pub fn new(exec_tmout: Duration) -> Result + pub fn new(exec_tmout: Duration) -> Result where E: Executor + HasObservers + HasInProcessHooks, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone, { // # Safety @@ -249,7 +250,7 @@ impl InProcessHooks { #[cfg(all(not(miri), unix, feature = "std"))] let data = unsafe { &raw mut GLOBAL_STATE }; #[cfg(feature = "std")] - unix_signal_handler::setup_panic_hook::(); + unix_signal_handler::setup_panic_hook::(); // # Safety // Setting up the signal handlers with a pointer to the `GLOBAL_STATE` which should not be NULL at this point. // We are the sole users of `GLOBAL_STATE` right now, and only dereference it in case of Segfault/Panic. @@ -262,10 +263,10 @@ impl InProcessHooks { compiler_fence(Ordering::SeqCst); Ok(Self { #[cfg(feature = "std")] - crash_handler: unix_signal_handler::inproc_crash_handler:: + crash_handler: unix_signal_handler::inproc_crash_handler:: as *const c_void, #[cfg(feature = "std")] - timeout_handler: unix_signal_handler::inproc_timeout_handler:: + timeout_handler: unix_signal_handler::inproc_timeout_handler:: as *const _, #[cfg(feature = "std")] timer: TimerStruct::new(exec_tmout), @@ -276,15 +277,16 @@ impl InProcessHooks { /// Create new [`InProcessHooks`]. #[cfg(windows)] #[allow(unused_variables)] // for `exec_tmout` without `std` - pub fn new(exec_tmout: Duration) -> Result + pub fn new(exec_tmout: Duration) -> Result where E: Executor + HasObservers + HasInProcessHooks, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, I: Input + Clone, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, { let ret; #[cfg(feature = "std")] @@ -293,6 +295,7 @@ impl InProcessHooks { crate::executors::hooks::windows::windows_exception_handler::setup_panic_hook::< E, EM, + F, I, OF, S, @@ -304,6 +307,7 @@ impl InProcessHooks { crate::executors::hooks::windows::windows_exception_handler::inproc_crash_handler::< E, EM, + F, I, OF, S, @@ -313,6 +317,7 @@ impl InProcessHooks { crate::executors::hooks::windows::windows_exception_handler::inproc_timeout_handler::< E, EM, + F, I, OF, S, @@ -339,13 +344,14 @@ impl InProcessHooks { /// Create a new [`InProcessHooks`] #[cfg(all(not(unix), not(windows)))] #[expect(unused_variables)] - pub fn new(exec_tmout: Duration) -> Result + pub fn new(exec_tmout: Duration) -> Result where E: Executor + HasObservers + HasInProcessHooks, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions, - Z: HasObjective, + Z: HasObjective + HasFeedback, { #[cfg_attr(miri, allow(unused_variables))] let ret = Self { @@ -472,7 +478,7 @@ impl InProcessExecutorHandlerData { /// /// Should only be called to signal a crash in the target #[cfg(all(unix, feature = "std"))] - pub unsafe fn maybe_report_crash( + pub unsafe fn maybe_report_crash( &mut self, bsod_info: Option, ) -> bool @@ -480,9 +486,10 @@ impl InProcessExecutorHandlerData { E: Executor + HasObservers, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCorpus + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone, { unsafe { @@ -510,7 +517,7 @@ impl InProcessExecutorHandlerData { } } - run_observers_and_save_state::( + run_observers_and_save_state::( executor, state, input, diff --git a/libafl/src/executors/hooks/timer.rs b/libafl/src/executors/hooks/timer.rs index cea8edc340..c31b98450a 100644 --- a/libafl/src/executors/hooks/timer.rs +++ b/libafl/src/executors/hooks/timer.rs @@ -178,7 +178,7 @@ impl TimerStruct { pub unsafe fn new(exec_tmout: Duration, timeout_handler: *const c_void) -> Self { let milli_sec = exec_tmout.as_millis() as i64; - let timeout_handler: PTP_TIMER_CALLBACK = unsafe { std::mem::transmute(timeout_handler) }; + let timeout_handler: PTP_TIMER_CALLBACK = unsafe { core::mem::transmute(timeout_handler) }; let ptp_timer = unsafe { CreateThreadpoolTimer( Some(timeout_handler), diff --git a/libafl/src/executors/hooks/unix.rs b/libafl/src/executors/hooks/unix.rs index 41f01b94d1..71bcbf10f2 100644 --- a/libafl/src/executors/hooks/unix.rs +++ b/libafl/src/executors/hooks/unix.rs @@ -12,6 +12,7 @@ pub mod unix_signal_handler { use libc::siginfo_t; use crate::{ + HasFeedback, events::{EventFirer, EventRestarter}, executors::{ Executor, ExitKind, HasObservers, common_signals, @@ -86,14 +87,15 @@ pub mod unix_signal_handler { } /// invokes the `post_exec` hook on all observer in case of panic - pub fn setup_panic_hook() + pub fn setup_panic_hook() where E: Executor + HasObservers, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone, { let old_hook = panic::take_hook(); @@ -117,7 +119,7 @@ pub mod unix_signal_handler { let fuzzer = (*data).fuzzer_mut::(); let event_mgr = (*data).event_mgr_mut::(); - run_observers_and_save_state::( + run_observers_and_save_state::( executor, state, input, @@ -140,7 +142,7 @@ pub mod unix_signal_handler { /// Well, signal handling is not safe #[cfg(unix)] #[allow(clippy::needless_pass_by_value)] // nightly no longer requires this - pub unsafe fn inproc_timeout_handler( + pub unsafe fn inproc_timeout_handler( _signal: Signal, _info: &mut siginfo_t, _context: Option<&mut ucontext_t>, @@ -149,9 +151,10 @@ pub mod unix_signal_handler { E: HasInProcessHooks + HasObservers, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone, { unsafe { @@ -178,7 +181,7 @@ pub mod unix_signal_handler { log::error!("Timeout in fuzz run."); - run_observers_and_save_state::( + run_observers_and_save_state::( executor, state, input, @@ -198,7 +201,7 @@ pub mod unix_signal_handler { /// # Safety /// Well, signal handling is not safe #[allow(clippy::needless_pass_by_value)] // nightly no longer requires this - pub unsafe fn inproc_crash_handler( + pub unsafe fn inproc_crash_handler( signal: Signal, _info: &mut siginfo_t, _context: Option<&mut ucontext_t>, @@ -207,9 +210,10 @@ pub mod unix_signal_handler { E: Executor + HasObservers, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone, { unsafe { @@ -251,7 +255,7 @@ pub mod unix_signal_handler { } } - run_observers_and_save_state::( + run_observers_and_save_state::( executor, state, input, diff --git a/libafl/src/executors/hooks/windows.rs b/libafl/src/executors/hooks/windows.rs index 9fcf8b869e..82f5ad78ba 100644 --- a/libafl/src/executors/hooks/windows.rs +++ b/libafl/src/executors/hooks/windows.rs @@ -9,6 +9,7 @@ pub mod windows_asan_handler { }; use crate::{ + HasFeedback, events::{EventFirer, EventRestarter}, executors::{ Executor, ExitKind, HasObservers, hooks::inprocess::GLOBAL_STATE, @@ -23,15 +24,16 @@ pub mod windows_asan_handler { /// # Safety /// ASAN deatch handler - pub unsafe extern "C" fn asan_death_handler() + pub unsafe extern "C" fn asan_death_handler() where E: Executor + HasObservers, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, I: Input + Clone, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, { unsafe { let data = &raw mut GLOBAL_STATE; @@ -94,7 +96,7 @@ pub mod windows_asan_handler { // Make sure we don't crash in the crash handler forever. let input = (*data).take_current_input::(); - run_observers_and_save_state::( + run_observers_and_save_state::( executor, state, input, @@ -137,6 +139,7 @@ pub mod windows_exception_handler { }; use crate::{ + HasFeedback, events::{EventFirer, EventRestarter}, executors::{ Executor, ExitKind, HasObservers, @@ -197,15 +200,16 @@ pub mod windows_exception_handler { /// # Safety /// Well, exception handling is not safe #[cfg(feature = "std")] - pub fn setup_panic_hook() + pub fn setup_panic_hook() where E: Executor + HasObservers, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, I: Input + Clone, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, { let old_hook = panic::take_hook(); panic::set_hook(Box::new(move |panic_info| unsafe { @@ -242,7 +246,7 @@ pub mod windows_exception_handler { let input = (*data).take_current_input::(); - run_observers_and_save_state::( + run_observers_and_save_state::( executor, state, input, @@ -262,7 +266,7 @@ pub mod windows_exception_handler { /// /// # Safety /// Well, exception handling is not safe - pub unsafe extern "system" fn inproc_timeout_handler( + pub unsafe extern "system" fn inproc_timeout_handler( _p0: *mut u8, global_state: *mut c_void, _p1: *mut u8, @@ -271,9 +275,10 @@ pub mod windows_exception_handler { E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, I: Input + Clone, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, { let data: &mut InProcessExecutorHandlerData = unsafe { &mut *(global_state as *mut InProcessExecutorHandlerData) }; @@ -313,7 +318,7 @@ pub mod windows_exception_handler { let input = unsafe { (data.current_input_ptr as *const I).as_ref().unwrap() }; data.current_input_ptr = ptr::null_mut(); - run_observers_and_save_state::( + run_observers_and_save_state::( executor, state, input, @@ -341,7 +346,7 @@ pub mod windows_exception_handler { /// /// # Safety /// Well, exception handling is not safe - pub unsafe fn inproc_crash_handler( + pub unsafe fn inproc_crash_handler( exception_pointers: *mut EXCEPTION_POINTERS, data: &mut InProcessExecutorHandlerData, ) where @@ -349,9 +354,10 @@ pub mod windows_exception_handler { E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, I: Input + Clone, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, { // Have we set a timer_before? if data.ptp_timer.is_some() { @@ -456,7 +462,7 @@ pub mod windows_exception_handler { log::warn!("Running observers and exiting!"); // // I want to disable the hooks before doing anything, especially before taking a stack dump let input = unsafe { data.take_current_input::() }; - run_observers_and_save_state::( + run_observers_and_save_state::( executor, state, input, @@ -473,7 +479,7 @@ pub mod windows_exception_handler { .unwrap(); writer.flush().unwrap(); } - log::error!("{}", std::str::from_utf8(&bsod).unwrap()); + log::error!("{}", core::str::from_utf8(&bsod).unwrap()); } } else { // This is not worth saving diff --git a/libafl/src/executors/inprocess/inner.rs b/libafl/src/executors/inprocess/inner.rs index cca507dab8..6e75a49d9a 100644 --- a/libafl/src/executors/inprocess/inner.rs +++ b/libafl/src/executors/inprocess/inner.rs @@ -16,7 +16,7 @@ use crate::executors::hooks::inprocess::HasTimeout; #[cfg(all(windows, feature = "std"))] use crate::executors::hooks::inprocess::HasTimeout; use crate::{ - Error, + Error, HasFeedback, events::{EventFirer, EventRestarter}, executors::{ Executor, HasObservers, @@ -132,7 +132,7 @@ where S: HasExecutions + HasSolutions, { /// Create a new in mem executor with the default timeout (5 sec) - pub fn generic( + pub fn generic( user_hooks: HT, observers: OT, fuzzer: &mut Z, @@ -144,11 +144,12 @@ where E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, I: Input + Clone, + F: Feedback, OF: Feedback, S: HasCurrentTestcase + HasSolutions, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - Self::with_timeout_generic::( + Self::with_timeout_generic::( user_hooks, observers, fuzzer, @@ -160,7 +161,7 @@ where /// Create a new in mem executor with the default timeout and use batch mode(5 sec) #[cfg(all(feature = "std", target_os = "linux"))] - pub fn batched_timeout_generic( + pub fn batched_timeout_generic( user_hooks: HT, observers: OT, fuzzer: &mut Z, @@ -173,11 +174,12 @@ where E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, I: Input + Clone, + F: Feedback, OF: Feedback, S: HasCurrentTestcase + HasSolutions, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let mut me = Self::with_timeout_generic::( + let mut me = Self::with_timeout_generic::( user_hooks, observers, fuzzer, state, event_mgr, exec_tmout, )?; me.hooks_mut().0.timer_mut().batch_mode = true; @@ -192,7 +194,7 @@ where /// * `observers` - the observers observing the target during execution /// /// This may return an error on unix, if signal handler setup fails - pub fn with_timeout_generic( + pub fn with_timeout_generic( user_hooks: HT, observers: OT, _fuzzer: &mut Z, @@ -204,12 +206,13 @@ where E: Executor + HasObservers + HasInProcessHooks, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasCurrentTestcase + HasSolutions, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone, { - let default = InProcessHooks::new::(timeout)?; + let default = InProcessHooks::new::(timeout)?; let mut hooks = tuple_list!(default).merge(user_hooks); hooks.init_all(state); diff --git a/libafl/src/executors/inprocess/mod.rs b/libafl/src/executors/inprocess/mod.rs index a1eba71dd9..fd92a20e47 100644 --- a/libafl/src/executors/inprocess/mod.rs +++ b/libafl/src/executors/inprocess/mod.rs @@ -15,7 +15,7 @@ use core::{ use libafl_bolts::tuples::{RefIndexable, tuple_list}; use crate::{ - Error, HasMetadata, + Error, HasFeedback, HasMetadata, corpus::{Corpus, Testcase}, events::{Event, EventFirer, EventRestarter}, executors::{ @@ -132,7 +132,7 @@ where I: Input, { /// Create a new in mem executor with the default timeout (5 sec) - pub fn new( + pub fn new( harness_fn: &'a mut H, observers: OT, fuzzer: &mut Z, @@ -141,10 +141,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - Self::with_timeout_generic::( + Self::with_timeout_generic::( tuple_list!(), harness_fn, observers, @@ -157,7 +158,7 @@ where /// Create a new in mem executor with the default timeout and use batch mode(5 sec) #[cfg(all(feature = "std", target_os = "linux"))] - pub fn batched_timeout( + pub fn batched_timeout( harness_fn: &'a mut H, observers: OT, fuzzer: &mut Z, @@ -167,10 +168,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let inner = GenericInProcessExecutorInner::batched_timeout_generic::( + let inner = GenericInProcessExecutorInner::batched_timeout_generic::( tuple_list!(), observers, fuzzer, @@ -194,7 +196,7 @@ where /// * `observers` - the observers observing the target during execution /// /// This may return an error on unix, if signal handler setup fails - pub fn with_timeout( + pub fn with_timeout( harness_fn: &'a mut H, observers: OT, fuzzer: &mut Z, @@ -204,10 +206,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let inner = GenericInProcessExecutorInner::with_timeout_generic::( + let inner = GenericInProcessExecutorInner::with_timeout_generic::( tuple_list!(), observers, fuzzer, @@ -234,7 +237,7 @@ where I: Input, { /// Create a new in mem executor with the default timeout (5 sec) - pub fn generic( + pub fn generic( user_hooks: HT, harness_fn: HB, observers: OT, @@ -244,10 +247,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - Self::with_timeout_generic::( + Self::with_timeout_generic::( user_hooks, harness_fn, observers, @@ -260,7 +264,7 @@ where /// Create a new in mem executor with the default timeout and use batch mode(5 sec) #[cfg(all(feature = "std", target_os = "linux"))] - pub fn batched_timeout_generic( + pub fn batched_timeout_generic( user_hooks: HT, harness_fn: HB, observers: OT, @@ -271,10 +275,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let inner = GenericInProcessExecutorInner::batched_timeout_generic::( + let inner = GenericInProcessExecutorInner::batched_timeout_generic::( user_hooks, observers, fuzzer, state, event_mgr, exec_tmout, )?; @@ -293,7 +298,7 @@ where /// * `observers` - the observers observing the target during execution /// /// This may return an error on unix, if signal handler setup fails - pub fn with_timeout_generic( + pub fn with_timeout_generic( user_hooks: HT, harness_fn: HB, observers: OT, @@ -304,10 +309,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let inner = GenericInProcessExecutorInner::with_timeout_generic::( + let inner = GenericInProcessExecutorInner::with_timeout_generic::( user_hooks, observers, fuzzer, state, event_mgr, timeout, )?; @@ -370,7 +376,7 @@ impl HasInProcessHooks #[inline] /// Save state if it is an objective -pub fn run_observers_and_save_state( +pub fn run_observers_and_save_state( executor: &mut E, state: &mut S, input: &I, @@ -382,8 +388,9 @@ pub fn run_observers_and_save_state( E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, OF: Feedback, + F: Feedback, S: HasExecutions + HasSolutions + HasCorpus + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone, { let mut observers = executor.observers_mut(); @@ -392,12 +399,17 @@ pub fn run_observers_and_save_state( .post_exec_all(state, input, &exitkind) .expect("Observers post_exec_all failed"); - let interesting = fuzzer + let _is_corpus = fuzzer + .feedback_mut() + .is_interesting(state, event_mgr, input, &*observers, &exitkind) + .expect("In run_observers_and_save_state feedback failure"); + + let is_solution = fuzzer .objective_mut() .is_interesting(state, event_mgr, input, &*observers, &exitkind) .expect("In run_observers_and_save_state objective failure."); - if interesting { + if is_solution { let mut new_testcase = Testcase::from(input.clone()); new_testcase.add_metadata(exitkind); new_testcase.set_parent_id_optional(*state.corpus().current()); diff --git a/libafl/src/executors/inprocess/stateful.rs b/libafl/src/executors/inprocess/stateful.rs index 43ab1598f1..b7d502db7a 100644 --- a/libafl/src/executors/inprocess/stateful.rs +++ b/libafl/src/executors/inprocess/stateful.rs @@ -11,7 +11,7 @@ use core::{ use libafl_bolts::tuples::{RefIndexable, tuple_list}; use crate::{ - Error, + Error, HasFeedback, events::{EventFirer, EventRestarter}, executors::{ Executor, ExitKind, HasObservers, @@ -131,7 +131,7 @@ where I: Clone + Input, { /// Create a new in mem executor with the default timeout (5 sec) - pub fn new( + pub fn new( harness_fn: &'a mut H, exposed_executor_state: ES, observers: OT, @@ -141,8 +141,9 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { Self::with_timeout_generic( tuple_list!(), @@ -158,7 +159,7 @@ where /// Create a new in mem executor with the default timeout and use batch mode(5 sec) #[cfg(all(feature = "std", target_os = "linux"))] - pub fn batched_timeout( + pub fn batched_timeout( harness_fn: &'a mut H, exposed_executor_state: ES, observers: OT, @@ -169,10 +170,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let inner = GenericInProcessExecutorInner::batched_timeout_generic::( + let inner = GenericInProcessExecutorInner::batched_timeout_generic::( tuple_list!(), observers, fuzzer, @@ -197,7 +199,7 @@ where /// * `observers` - the observers observing the target during execution /// /// This may return an error on unix, if signal handler setup fails - pub fn with_timeout( + pub fn with_timeout( harness_fn: &'a mut H, exposed_executor_state: ES, observers: OT, @@ -208,10 +210,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let inner = GenericInProcessExecutorInner::with_timeout_generic::( + let inner = GenericInProcessExecutorInner::with_timeout_generic::( tuple_list!(), observers, fuzzer, @@ -254,7 +257,7 @@ where S: HasExecutions + HasSolutions + HasCurrentTestcase, { /// Create a new in mem executor with the default timeout (5 sec) - pub fn generic( + pub fn generic( user_hooks: HT, harness_fn: HB, exposed_executor_state: ES, @@ -265,8 +268,9 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { Self::with_timeout_generic( user_hooks, @@ -283,7 +287,7 @@ where /// Create a new in mem executor with the default timeout and use batch mode(5 sec) #[cfg(all(feature = "std", target_os = "linux"))] #[expect(clippy::too_many_arguments)] - pub fn batched_timeout_generic( + pub fn batched_timeout_generic( user_hooks: HT, harness_fn: HB, exposed_executor_state: ES, @@ -295,10 +299,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let inner = GenericInProcessExecutorInner::batched_timeout_generic::( + let inner = GenericInProcessExecutorInner::batched_timeout_generic::( user_hooks, observers, fuzzer, state, event_mgr, exec_tmout, )?; @@ -319,7 +324,7 @@ where /// /// This may return an error on unix, if signal handler setup fails #[expect(clippy::too_many_arguments)] - pub fn with_timeout_generic( + pub fn with_timeout_generic( user_hooks: HT, harness_fn: HB, exposed_executor_state: ES, @@ -331,10 +336,11 @@ where ) -> Result where EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective, + Z: HasObjective + HasFeedback, { - let inner = GenericInProcessExecutorInner::with_timeout_generic::( + let inner = GenericInProcessExecutorInner::with_timeout_generic::( user_hooks, observers, fuzzer, state, event_mgr, timeout, )?; diff --git a/libafl/src/feedbacks/bool.rs b/libafl/src/feedbacks/bool.rs index fc9335da95..912f73e887 100644 --- a/libafl/src/feedbacks/bool.rs +++ b/libafl/src/feedbacks/bool.rs @@ -91,10 +91,6 @@ where Ok(()) } - fn discard_metadata(&mut self, _state: &mut S, _input: &I) -> Result<(), Error> { - Ok(()) - } - #[cfg(feature = "track_hit_feedbacks")] fn last_result(&self) -> Result { self.last_result.ok_or_else(|| Error::illegal_state("No last result set in `BoolValuefeedback`. Either `is_interesting` has never been called or the fuzzer restarted in the meantime.")) diff --git a/libafl/src/feedbacks/mod.rs b/libafl/src/feedbacks/mod.rs index 5c24d87856..60a6217227 100644 --- a/libafl/src/feedbacks/mod.rs +++ b/libafl/src/feedbacks/mod.rs @@ -148,12 +148,6 @@ pub trait Feedback: StateInitializer + Named { ) -> Result<(), Error> { Ok(()) } - - /// Discard the stored metadata in case that the testcase is not added to the corpus - #[inline] - fn discard_metadata(&mut self, _state: &mut S, _input: &I) -> Result<(), Error> { - Ok(()) - } } /// Has an associated observer name (mostly used to retrieve the observer with `MatchName` from an `ObserverTuple`) @@ -306,12 +300,6 @@ where self.second .append_metadata(state, manager, observers, testcase) } - - #[inline] - fn discard_metadata(&mut self, state: &mut S, input: &I) -> Result<(), Error> { - self.first.discard_metadata(state, input)?; - self.second.discard_metadata(state, input) - } } impl FeedbackFactory, T> for CombinedFeedback @@ -670,11 +658,6 @@ where self.inner .append_metadata(state, manager, observers, testcase) } - - #[inline] - fn discard_metadata(&mut self, state: &mut S, input: &I) -> Result<(), Error> { - self.inner.discard_metadata(state, input) - } } impl Named for NotFeedback { diff --git a/libafl/src/feedbacks/nautilus.rs b/libafl/src/feedbacks/nautilus.rs index f2c51bb167..f58c018db0 100644 --- a/libafl/src/feedbacks/nautilus.rs +++ b/libafl/src/feedbacks/nautilus.rs @@ -115,9 +115,6 @@ where self.append_nautilus_metadata_to_state(state, testcase) } - fn discard_metadata(&mut self, _state: &mut S, _input: &NautilusInput) -> Result<(), Error> { - Ok(()) - } #[cfg(feature = "track_hit_feedbacks")] fn last_result(&self) -> Result { Ok(false) diff --git a/libafl/src/fuzzer/mod.rs b/libafl/src/fuzzer/mod.rs index 787c4d1f36..d7a0f73ccc 100644 --- a/libafl/src/fuzzer/mod.rs +++ b/libafl/src/fuzzer/mod.rs @@ -188,7 +188,7 @@ pub trait Evaluator { executor: &mut E, manager: &mut EM, input: I, - ) -> Result; + ) -> Result<(CorpusId, ExecuteInputResult), Error>; /// Adds the input to the corpus as a disabled input. /// Used during initial corpus loading. @@ -246,14 +246,43 @@ pub trait Fuzzer { } /// The corpus this input should be added to -#[derive(Debug, PartialEq, Eq)] -pub enum ExecuteInputResult { - /// No special input - None, - /// This input should be stored in the corpus - Corpus, - /// This input leads to a solution - Solution, +#[derive(Debug, PartialEq, Eq, Default)] +pub struct ExecuteInputResult { + is_corpus: bool, + is_solution: bool, +} + +impl ExecuteInputResult { + /// Constructor + #[must_use] + pub fn new(is_corpus: bool, is_solution: bool) -> Self { + Self { + is_corpus, + is_solution, + } + } + + /// if this is corpus worthy + #[must_use] + pub fn is_corpus(&self) -> bool { + self.is_corpus + } + + /// if this is solution worthy + #[must_use] + pub fn is_solution(&self) -> bool { + self.is_solution + } + + /// tell that this is corpus + pub fn set_is_corpus(&mut self, v: bool) { + self.is_corpus = v; + } + + /// tell that this is solution + pub fn set_is_solution(&mut self, v: bool) { + self.is_solution = v; + } } /// Your default fuzzer instance, for everyday use. @@ -326,7 +355,7 @@ where observers: &OT, exit_kind: &ExitKind, ) -> Result { - let mut res = ExecuteInputResult::None; + let mut res = ExecuteInputResult::default(); #[cfg(not(feature = "introspection"))] let is_solution = self @@ -339,26 +368,27 @@ where .is_interesting_introspection(state, manager, input, observers, exit_kind)?; if is_solution { - res = ExecuteInputResult::Solution; - } else { - #[cfg(not(feature = "introspection"))] - let corpus_worthy = self - .feedback_mut() - .is_interesting(state, manager, input, observers, exit_kind)?; - - #[cfg(feature = "introspection")] - let corpus_worthy = self - .feedback_mut() - .is_interesting_introspection(state, manager, input, observers, exit_kind)?; - - if corpus_worthy { - res = ExecuteInputResult::Corpus; - } + res.set_is_solution(true); } + + #[cfg(not(feature = "introspection"))] + let corpus_worthy = self + .feedback_mut() + .is_interesting(state, manager, input, observers, exit_kind)?; + #[cfg(feature = "introspection")] + let corpus_worthy = self + .feedback_mut() + .is_interesting_introspection(state, manager, input, observers, exit_kind)?; + + if corpus_worthy { + res.set_is_corpus(true); + } + Ok(res) } - /// Evaluate if a set of observation channels has an interesting state + /// Post process a testcase depending the testcase execution results + /// returns corpus id if it put something into corpus (not solution) fn process_execution( &mut self, state: &mut S, @@ -367,48 +397,36 @@ where exec_res: &ExecuteInputResult, observers: &OT, ) -> Result, Error> { - match exec_res { - ExecuteInputResult::None => { - self.feedback_mut().discard_metadata(state, input)?; - self.objective_mut().discard_metadata(state, input)?; - Ok(None) - } - ExecuteInputResult::Corpus => { - // Not a solution - self.objective_mut().discard_metadata(state, input)?; - - // Add the input to the main corpus - let mut testcase = Testcase::from(input.clone()); - #[cfg(feature = "track_hit_feedbacks")] - self.feedback_mut() - .append_hit_feedbacks(testcase.hit_feedbacks_mut())?; - self.feedback_mut() - .append_metadata(state, manager, observers, &mut testcase)?; - let id = state.corpus_mut().add(testcase)?; - self.scheduler_mut().on_add(state, id)?; - - Ok(Some(id)) - } - ExecuteInputResult::Solution => { - // Not interesting - self.feedback_mut().discard_metadata(state, input)?; - - // The input is a solution, add it to the respective corpus - let mut testcase = Testcase::from(input.clone()); - testcase.set_parent_id_optional(*state.corpus().current()); - if let Ok(mut tc) = state.current_testcase_mut() { - tc.found_objective(); - } - #[cfg(feature = "track_hit_feedbacks")] - self.objective_mut() - .append_hit_feedbacks(testcase.hit_objectives_mut())?; - self.objective_mut() - .append_metadata(state, manager, observers, &mut testcase)?; - state.solutions_mut().add(testcase)?; - - Ok(None) + let corpus = if exec_res.is_corpus() { + // Add the input to the main corpus + let mut testcase = Testcase::from(input.clone()); + #[cfg(feature = "track_hit_feedbacks")] + self.feedback_mut() + .append_hit_feedbacks(testcase.hit_feedbacks_mut())?; + self.feedback_mut() + .append_metadata(state, manager, observers, &mut testcase)?; + let id = state.corpus_mut().add(testcase)?; + self.scheduler_mut().on_add(state, id)?; + Ok(Some(id)) + } else { + Ok(None) + }; + + if exec_res.is_solution() { + // The input is a solution, add it to the respective corpus + let mut testcase = Testcase::from(input.clone()); + testcase.set_parent_id_optional(*state.corpus().current()); + if let Ok(mut tc) = state.current_testcase_mut() { + tc.found_objective(); } + #[cfg(feature = "track_hit_feedbacks")] + self.objective_mut() + .append_hit_feedbacks(testcase.hit_objectives_mut())?; + self.objective_mut() + .append_metadata(state, manager, observers, &mut testcase)?; + state.solutions_mut().add(testcase)?; } + corpus } fn serialize_and_dispatch( @@ -421,20 +439,14 @@ where exit_kind: &ExitKind, ) -> Result<(), Error> { // Now send off the event - let observers_buf = match exec_res { - ExecuteInputResult::Corpus => { - if manager.should_send() { - // TODO set None for fast targets - if manager.configuration() == EventConfig::AlwaysUnique { - None - } else { - manager.serialize_observers(observers)? - } - } else { - None - } - } - _ => None, + let observers_buf = if exec_res.is_solution() + && manager.should_send() + && manager.configuration() != EventConfig::AlwaysUnique + { + // TODO set None for fast targets + manager.serialize_observers(observers)? + } else { + None }; self.dispatch_event(state, manager, input, exec_res, observers_buf, exit_kind)?; @@ -451,41 +463,38 @@ where exit_kind: &ExitKind, ) -> Result<(), Error> { // Now send off the event - match exec_res { - ExecuteInputResult::Corpus => { - if manager.should_send() { - manager.fire( - state, - Event::NewTestcase { - input: input.clone(), - observers_buf, - exit_kind: *exit_kind, - corpus_size: state.corpus().count(), - client_config: manager.configuration(), - time: current_time(), - forward_id: None, - #[cfg(all(unix, feature = "std", feature = "multi_machine"))] - node_id: None, - }, - )?; - } + if manager.should_send() { + if exec_res.is_corpus() { + manager.fire( + state, + Event::NewTestcase { + input: input.clone(), + observers_buf, + exit_kind: *exit_kind, + corpus_size: state.corpus().count(), + client_config: manager.configuration(), + time: current_time(), + forward_id: None, + #[cfg(all(unix, feature = "std", feature = "multi_machine"))] + node_id: None, + }, + )?; } - ExecuteInputResult::Solution => { - if manager.should_send() { - manager.fire( - state, - Event::Objective { - #[cfg(feature = "share_objectives")] - input: input.clone(), - objective_size: state.solutions().count(), - time: current_time(), - }, - )?; - } + if exec_res.is_solution() { + manager.fire( + state, + Event::Objective { + #[cfg(feature = "share_objectives")] + input: input.clone(), + + objective_size: state.solutions().count(), + time: current_time(), + }, + )?; } - ExecuteInputResult::None => (), } + Ok(()) } @@ -503,7 +512,7 @@ where if send_events { self.serialize_and_dispatch(state, manager, input, &exec_res, observers, exit_kind)?; } - if exec_res != ExecuteInputResult::None { + if exec_res.is_corpus() || exec_res.is_solution() { *state.last_found_time_mut() = current_time(); } Ok((exec_res, corpus_id)) @@ -610,7 +619,7 @@ where if self.input_filter.should_execute(input) { self.evaluate_input(state, executor, manager, input) } else { - Ok((ExecuteInputResult::None, None)) + Ok((ExecuteInputResult::default(), None)) } } @@ -633,7 +642,7 @@ where executor: &mut E, manager: &mut EM, input: I, - ) -> Result { + ) -> Result<(CorpusId, ExecuteInputResult), Error> { *state.last_found_time_mut() = current_time(); let exit_kind = self.execute_input(state, executor, manager, &input)?; @@ -662,33 +671,30 @@ where .append_hit_feedbacks(testcase.hit_objectives_mut())?; self.objective_mut() .append_metadata(state, manager, &*observers, &mut testcase)?; - let id = state.solutions_mut().add(testcase)?; + // we don't care about solution id + let _ = state.solutions_mut().add(testcase.clone())?; manager.fire( state, Event::Objective { #[cfg(feature = "share_objectives")] - input, + input: input.clone(), objective_size: state.solutions().count(), time: current_time(), }, )?; - return Ok(id); } - // Not a solution - self.objective_mut().discard_metadata(state, &input)?; - // several is_interesting implementations collect some data about the run, later used in // append_metadata; we *must* invoke is_interesting here to collect it #[cfg(not(feature = "introspection"))] - let _corpus_worthy = + let corpus_worthy = self.feedback_mut() .is_interesting(state, manager, &input, &*observers, &exit_kind)?; #[cfg(feature = "introspection")] - let _corpus_worthy = self.feedback_mut().is_interesting_introspection( + let corpus_worthy = self.feedback_mut().is_interesting_introspection( state, manager, &input, @@ -724,7 +730,7 @@ where node_id: None, }, )?; - Ok(id) + Ok((id, ExecuteInputResult::new(corpus_worthy, is_solution))) } fn add_disabled_input(&mut self, state: &mut S, input: I) -> Result { diff --git a/libafl/src/observers/mod.rs b/libafl/src/observers/mod.rs index 266237730b..b0c38ea2a8 100644 --- a/libafl/src/observers/mod.rs +++ b/libafl/src/observers/mod.rs @@ -14,12 +14,6 @@ pub mod stacktrace; #[cfg(feature = "regex")] pub use stacktrace::*; -/// Profiler observer -#[cfg(feature = "std")] -pub mod profiling; -#[cfg(feature = "std")] -pub use profiling::*; - pub mod concolic; pub mod map; pub use map::*; diff --git a/libafl/src/observers/profiling.rs b/libafl/src/observers/profiling.rs deleted file mode 100644 index 3938b6d4bd..0000000000 --- a/libafl/src/observers/profiling.rs +++ /dev/null @@ -1,146 +0,0 @@ -use alloc::{borrow::Cow, string::String}; -use std::{fs::File, io::BufReader, path::Path}; - -use hashbrown::HashMap; -use libafl_bolts::{Named, ownedref::OwnedMutPtr}; -use serde::{Deserialize, Serialize}; - -use crate::{Error, observers::Observer}; -#[derive(Debug, Serialize, Deserialize)] -/// The json data -pub struct FunctionData { - #[serde(rename = "name")] - name: String, - #[serde(rename = "# BBs")] - bb_count: Option, - #[serde(rename = "# insts")] - inst_count: Option, - #[serde(rename = "# edges")] - edge_count: Option, - #[serde(rename = "# binaryOp")] - binary_op_count: Option, - #[serde(rename = "# call")] - call_count: Option, - #[serde(rename = "# cmp")] - cmp_count: Option, - #[serde(rename = "# load")] - load_count: Option, - #[serde(rename = "# store")] - store_count: Option, - #[serde(rename = "# alloca")] - alloca_count: Option, - #[serde(rename = "# branch")] - branch_count: Option, - #[serde(rename = "ABC metric")] - abc_metric: Option, - cyclomatic: Option, - #[serde(rename = "AP")] - api_calls: Option>, - #[serde(rename = "h AP")] - heap_apis: Option>, - #[serde(rename = "m AP")] - memory_apis: Option>, - #[serde(rename = "ne lv")] - nested_level: Option>, - #[serde(rename = "cm gl")] - cmp_globals: Option>, - #[serde(rename = "cm nz")] - cmp_non_zeros: Option>, - #[serde(rename = "wr st")] - struct_writes: Option>, - #[serde(rename = "str arg")] - struct_args: Option>, - #[serde(rename = "cm ty")] - cmp_types: Option>, - #[serde(rename = "cm cm")] - cmp_complexity: Option>, - #[serde(rename = "ar ty")] - call_arg_types: Option>, - #[serde(rename = "st ty")] - store_types: Option>, - #[serde(rename = "l ty")] - load_types: Option>, - #[serde(rename = "al ty")] - alloca_types: Option>, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -struct AnalysisData { - data: HashMap, -} - -/// The observer to lookup the static analysis data at runtime -#[derive(Debug, Serialize, Deserialize)] -pub struct ProfilingObserver { - /// The name of the observer. - pub name: Cow<'static, str>, - db: AnalysisData, - /// The map - map: OwnedMutPtr>, -} - -impl ProfilingObserver { - /// The constructor - pub fn new

(json_path: P, map: OwnedMutPtr>) -> Result - where - P: AsRef, - { - let f = File::open(json_path.as_ref())?; - let reader = BufReader::new(f); - let analysis_data: AnalysisData = serde_json::from_reader(reader).map_err(|err| { - let path = json_path.as_ref().to_string_lossy(); - Error::illegal_argument(format!("Failed to read from path {path}: {err:?}")) - })?; - // debug - /* - for record in &analysis_data.data { - for (key, _value) in record.iter() { - log::info!("Record {} found!", key); - } - } - */ - - Ok(Self { - name: Cow::from("profiling"), - db: analysis_data, - map, - }) - } - - /// Get the map - #[must_use] - pub fn map(&self) -> &HashMap { - self.map.as_ref() - } - - /// lookup the data through db - #[must_use] - pub fn lookup(&self, function_id: usize) -> Option<&FunctionData> { - let item = self.db.data.get(&function_id); - item - } -} - -impl Named for ProfilingObserver { - fn name(&self) -> &Cow<'static, str> { - &self.name - } -} - -impl Observer for ProfilingObserver { - fn post_exec( - &mut self, - _state: &mut S, - _input: &I, - _exit_kind: &crate::executors::ExitKind, - ) -> Result<(), Error> { - // in reality, this should be done in a stage - // but here just for poc - for (key, _item) in self.map() { - let found = self.lookup(*key); - log::info!("key: {}, data: {:#?}", key, found); - } - log::info!(""); - Ok(()) - } -} diff --git a/libafl/src/schedulers/accounting.rs b/libafl/src/schedulers/accounting.rs index e85d5336fb..87ba1c0084 100644 --- a/libafl/src/schedulers/accounting.rs +++ b/libafl/src/schedulers/accounting.rs @@ -141,12 +141,11 @@ where } let mut id = self.inner.base_mut().next(state)?; while { - let has = !state + !state .corpus() .get(id)? .borrow() - .has_metadata::(); - has + .has_metadata::() } && state.rand_mut().coinflip(self.skip_non_favored_prob) { id = self.inner.base_mut().next(state)?; diff --git a/libafl/src/schedulers/minimizer.rs b/libafl/src/schedulers/minimizer.rs index 53dccf25ff..bb430cbee6 100644 --- a/libafl/src/schedulers/minimizer.rs +++ b/libafl/src/schedulers/minimizer.rs @@ -107,12 +107,10 @@ where self.base.on_remove(state, id, testcase)?; let mut entries = if let Some(meta) = state.metadata_map_mut().get_mut::() { - let entries = meta - .map + meta.map .extract_if(|_, other_id| *other_id == id) .map(|(entry, _)| entry) - .collect::>(); - entries + .collect::>() } else { return Ok(()); }; @@ -215,12 +213,11 @@ where self.cull(state)?; let mut id = self.base.next(state)?; while { - let has = !state + !state .corpus() .get(id)? .borrow() - .has_metadata::(); - has + .has_metadata::() } && state.rand_mut().coinflip(self.skip_non_favored_prob) { id = self.base.next(state)?; diff --git a/libafl/src/stages/dump.rs b/libafl/src/stages/dump.rs index 95dc6b9ca8..c97c116628 100644 --- a/libafl/src/stages/dump.rs +++ b/libafl/src/stages/dump.rs @@ -139,7 +139,7 @@ where if !corpus_dir.is_dir() { return Err(Error::os_error( e, - format!("Error creating directory {corpus_dir:?}"), + format!("Error creating directory {}", corpus_dir.display()), )); } } @@ -148,7 +148,7 @@ where if !solutions_dir.is_dir() { return Err(Error::os_error( e, - format!("Error creating directory {solutions_dir:?}"), + format!("Error creating directory {}", solutions_dir.display()), )); } } diff --git a/libafl/src/state/mod.rs b/libafl/src/state/mod.rs index c441c960a8..445ab79bb8 100644 --- a/libafl/src/state/mod.rs +++ b/libafl/src/state/mod.rs @@ -26,6 +26,8 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned}; mod stack; pub use stack::StageStack; +#[cfg(feature = "std")] +use crate::fuzzer::ExecuteInputResult; #[cfg(feature = "introspection")] use crate::monitors::stats::ClientPerfStats; use crate::{ @@ -33,7 +35,7 @@ use crate::{ corpus::{Corpus, CorpusId, HasCurrentCorpusId, HasTestcase, InMemoryCorpus, Testcase}, events::{Event, EventFirer, LogSeverity}, feedbacks::StateInitializer, - fuzzer::{Evaluator, ExecuteInputResult}, + fuzzer::Evaluator, generators::Generator, inputs::{Input, NopInput}, stages::StageId, @@ -715,15 +717,15 @@ where Ok(input) => input, Err(err) => { log::error!("Skipping input that we could not load from {path:?}: {err:?}"); - return Ok(ExecuteInputResult::None); + return Ok(ExecuteInputResult::default()); } }; if config.forced { - let _: CorpusId = fuzzer.add_input(self, executor, manager, input)?; - Ok(ExecuteInputResult::Corpus) + let (_id, result) = fuzzer.add_input(self, executor, manager, input)?; + Ok(result) } else { let (res, _) = fuzzer.evaluate_input(self, executor, manager, &input)?; - if res == ExecuteInputResult::None { + if !(res.is_corpus() || res.is_solution()) { fuzzer.add_disabled_input(self, input)?; log::warn!("input {:?} was not interesting, adding as disabled.", &path); } @@ -748,7 +750,7 @@ where match self.next_file() { Ok(path) => { let res = self.load_file(&path, manager, fuzzer, executor, &mut config)?; - if config.exit_on_solution && matches!(res, ExecuteInputResult::Solution) { + if config.exit_on_solution && res.is_solution() { return Err(Error::invalid_corpus(format!( "Input {} resulted in a solution.", path.display() @@ -1052,11 +1054,11 @@ where for _ in 0..num { let input = generator.generate(self)?; if forced { - let _: CorpusId = fuzzer.add_input(self, executor, manager, input)?; + let (_, _) = fuzzer.add_input(self, executor, manager, input)?; added += 1; } else { let (res, _) = fuzzer.evaluate_input(self, executor, manager, &input)?; - if res != ExecuteInputResult::None { + if res.is_corpus() { added += 1; } } diff --git a/libafl_bolts/src/core_affinity.rs b/libafl_bolts/src/core_affinity.rs index b23d705a78..48fd148c3a 100644 --- a/libafl_bolts/src/core_affinity.rs +++ b/libafl_bolts/src/core_affinity.rs @@ -463,7 +463,7 @@ mod windows { #[expect(clippy::cast_ptr_alignment)] pub fn get_num_logical_cpus_ex_windows() -> Option { - use std::{ptr, slice}; + use core::{ptr, slice}; #[expect(non_upper_case_globals)] const RelationProcessorCore: u32 = 0; diff --git a/libafl_bolts/src/lib.rs b/libafl_bolts/src/lib.rs index 8b14267418..85db227e29 100644 --- a/libafl_bolts/src/lib.rs +++ b/libafl_bolts/src/lib.rs @@ -990,7 +990,7 @@ impl SimpleStdoutLogger { #[must_use] /// Return thread ID without using TLS pub fn get_thread_id() -> u64 { - use std::arch::asm; + use core::arch::asm; #[cfg(target_arch = "x86_64")] unsafe { let teb: *const u8; @@ -1031,7 +1031,7 @@ pub fn get_thread_id() -> u64 { #[cfg(feature = "std")] #[cfg(target_os = "windows")] mod windows_logging { - use std::ptr; + use core::ptr; use once_cell::sync::OnceCell; use winapi::um::{ @@ -1291,7 +1291,7 @@ struct TEB { #[inline(always)] #[cfg(target_os = "windows")] fn nt_current_teb() -> *mut TEB { - use std::arch::asm; + use core::arch::asm; let teb: *mut TEB; unsafe { asm!("mov {}, gs:0x30", out(reg) teb); diff --git a/libafl_bolts/src/math.rs b/libafl_bolts/src/math.rs index 947a317b61..f9ac732a13 100644 --- a/libafl_bolts/src/math.rs +++ b/libafl_bolts/src/math.rs @@ -47,7 +47,7 @@ pub const fn integer_sqrt(val: u64) -> u64 { let mut m; while ret != i - 1 { - m = (ret + i) / 2; + m = u64::midpoint(ret, i); if m.saturating_mul(m) <= val { ret = m; diff --git a/libafl_bolts/src/os/unix_shmem_server.rs b/libafl_bolts/src/os/unix_shmem_server.rs index 1ae1dcbbe2..fba5e2b6f2 100644 --- a/libafl_bolts/src/os/unix_shmem_server.rs +++ b/libafl_bolts/src/os/unix_shmem_server.rs @@ -499,7 +499,7 @@ where // log::trace!("got ashmem client: {}, request:{:?}", client_id, request); // Handle the client request - let response = match request { + match request { ServedShMemRequest::Hello() => Ok(ServedShMemResponse::Id(client_id)), ServedShMemRequest::PreFork() => { // We clone the provider already, waiting for it to reconnect [`PostFork`]. @@ -590,12 +590,10 @@ where ServedShMemRequest::Exit => { log::info!("ShMemService - Exiting"); // stopping the server - return Err(Error::shutting_down()); + Err(Error::shutting_down()) } - }; + } // log::info!("send ashmem client: {}, response: {:?}", client_id, &response); - - response } fn read_request(&mut self, client_id: RawFd) -> Result { diff --git a/libafl_bolts/src/serdeany.rs b/libafl_bolts/src/serdeany.rs index b4cc50be05..e6d1bb3872 100644 --- a/libafl_bolts/src/serdeany.rs +++ b/libafl_bolts/src/serdeany.rs @@ -554,7 +554,6 @@ pub mod serdeany_registry { #[cfg(not(feature = "stable_anymap"))] let type_repr = &type_repr; - #[expect(clippy::manual_map)] match self.map.get(type_repr) { None => None, Some(h) => Some(h.values().map(|x| x.as_any().downcast_ref::().unwrap())), @@ -580,7 +579,6 @@ pub mod serdeany_registry { #[cfg(not(feature = "stable_anymap"))] let type_repr = &type_repr; - #[expect(clippy::manual_map)] match self.map.get_mut(type_repr) { None => None, Some(h) => Some( diff --git a/libafl_bolts/src/staterestore.rs b/libafl_bolts/src/staterestore.rs index 4db493a905..ebd7d12c3c 100644 --- a/libafl_bolts/src/staterestore.rs +++ b/libafl_bolts/src/staterestore.rs @@ -141,9 +141,9 @@ where return Err(Error::illegal_state(format!( "The state restorer map is too small to fit anything, even the filename! It needs to be at least {} bytes. - The tmpfile was written to {:?}.", + The tmpfile was written to {}.", len, - temp_dir().join(&filename) + temp_dir().join(&filename).display() ))); } diff --git a/libafl_concolic/symcc_runtime/src/lib.rs b/libafl_concolic/symcc_runtime/src/lib.rs index 5a9ee5225c..09bb54db73 100644 --- a/libafl_concolic/symcc_runtime/src/lib.rs +++ b/libafl_concolic/symcc_runtime/src/lib.rs @@ -28,6 +28,8 @@ //! name = "SymRuntime" //! ``` +#![allow(clippy::std_instead_of_core)] + pub mod filter; pub mod tracing; diff --git a/libafl_frida/src/asan/asan_rt.rs b/libafl_frida/src/asan/asan_rt.rs index c1a4cffe09..621b2373de 100644 --- a/libafl_frida/src/asan/asan_rt.rs +++ b/libafl_frida/src/asan/asan_rt.rs @@ -1697,7 +1697,7 @@ impl AsanRuntime { let insn = disas_count( &decoder, - unsafe { std::slice::from_raw_parts(actual_pc as *mut u8, 4) }, + unsafe { core::slice::from_raw_parts(actual_pc as *mut u8, 4) }, 1, )[0]; diff --git a/libafl_frida/src/asan/errors.rs b/libafl_frida/src/asan/errors.rs index 5f8e465bab..147dae917d 100644 --- a/libafl_frida/src/asan/errors.rs +++ b/libafl_frida/src/asan/errors.rs @@ -269,7 +269,7 @@ impl AsanErrors { #[cfg(target_arch = "aarch64")] let insts = disas_count( &decoder, - unsafe { std::slice::from_raw_parts(start_pc as *mut u8, 4 * 11) }, + unsafe { core::slice::from_raw_parts(start_pc as *mut u8, 4 * 11) }, 11, ); @@ -540,7 +540,7 @@ impl AsanErrors { #[cfg(target_arch = "aarch64")] let insts = disas_count( &decoder, - unsafe { std::slice::from_raw_parts(*start_pc as *mut u8, 4 * 11) }, + unsafe { core::slice::from_raw_parts(*start_pc as *mut u8, 4 * 11) }, 11, ); @@ -691,11 +691,6 @@ where Ok(()) } - fn discard_metadata(&mut self, _state: &mut S, _input: &I) -> Result<(), Error> { - self.errors = None; - Ok(()) - } - #[cfg(feature = "track_hit_feedbacks")] fn last_result(&self) -> Result { Ok(self.errors.is_some()) diff --git a/libafl_frida/src/asan/hook_funcs.rs b/libafl_frida/src/asan/hook_funcs.rs index 5e2592d672..8db66e7fb0 100644 --- a/libafl_frida/src/asan/hook_funcs.rs +++ b/libafl_frida/src/asan/hook_funcs.rs @@ -837,7 +837,6 @@ impl AsanRuntime { #[expect(non_snake_case)] #[allow(unknown_lints)] // the compiler is contradicting itself - #[expect(clippy::used_underscore_items)] #[inline] pub fn hook__Znwm( &mut self, @@ -874,7 +873,6 @@ impl AsanRuntime { #[expect(non_snake_case)] #[allow(unknown_lints)] // the compiler is contradicting itself - #[expect(clippy::used_underscore_items)] #[inline] pub fn hook__ZnwmSt11align_val_t( &mut self, diff --git a/libafl_frida/src/pthread_hook.rs b/libafl_frida/src/pthread_hook.rs index b988f1d50a..9b9b579640 100644 --- a/libafl_frida/src/pthread_hook.rs +++ b/libafl_frida/src/pthread_hook.rs @@ -47,12 +47,12 @@ impl PreviousHook { let inner = self.0; if inner.is_null() { unsafe { - pthread_introspection_hook_install(std::ptr::null()); + pthread_introspection_hook_install(core::ptr::null()); } return; } unsafe { - self.0 = std::ptr::null(); + self.0 = core::ptr::null(); pthread_introspection_hook_install(inner); } } @@ -64,7 +64,7 @@ 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()); +static mut PREVIOUS_HOOK: PreviousHook = PreviousHook(core::ptr::null()); /// The currently set hook static CURRENT_HOOK: RwLock> = RwLock::new(None); @@ -197,11 +197,9 @@ pub unsafe fn reset() { /// The following tests fail if they are not run sequentially. #[cfg(test)] mod test { - use std::{ - sync::{Arc, Mutex}, - thread, - time::Duration, - }; + use alloc::sync::Arc; + use core::time::Duration; + use std::{sync::Mutex, thread}; use serial_test::serial; diff --git a/libafl_libfuzzer/runtime/src/feedbacks.rs b/libafl_libfuzzer/runtime/src/feedbacks.rs index fbbfb3975a..130a29bfcb 100644 --- a/libafl_libfuzzer/runtime/src/feedbacks.rs +++ b/libafl_libfuzzer/runtime/src/feedbacks.rs @@ -103,8 +103,7 @@ impl LibfuzzerCrashCauseFeedback { let base = if let Some(filename) = testcase.filename() { filename.clone() } else { - let name = testcase.input().as_ref().unwrap().generate_name(None); - name + testcase.input().as_ref().unwrap().generate_name(None) }; let file_path = self.artifact_prefix.dir().join(format!( "{}{prefix}-{base}", diff --git a/libafl_libfuzzer/runtime/src/observers.rs b/libafl_libfuzzer/runtime/src/observers.rs index f6b45181b7..436da33982 100644 --- a/libafl_libfuzzer/runtime/src/observers.rs +++ b/libafl_libfuzzer/runtime/src/observers.rs @@ -194,9 +194,11 @@ where fn next(&mut self) -> Option { self.inner.next().map(|e| { - (*e == self.initial) - .then(|| self.value_obs.default_value()) - .unwrap_or_else(|| self.value_obs.value()) + if *e == self.initial { + self.value_obs.default_value() + } else { + self.value_obs.value() + } }) } } diff --git a/libafl_qemu/libafl_qemu_sys/src/lib.rs b/libafl_qemu/libafl_qemu_sys/src/lib.rs index 51f8999faa..41021ee40d 100644 --- a/libafl_qemu/libafl_qemu_sys/src/lib.rs +++ b/libafl_qemu/libafl_qemu_sys/src/lib.rs @@ -6,6 +6,7 @@ __Warning__: The documentation is built by default for `x86_64` in `usermode`. T */ #![cfg_attr(nightly, feature(used_with_arg))] +#![allow(clippy::std_instead_of_core)] use core::ffi::c_void; #[cfg(target_os = "linux")] diff --git a/libafl_qemu/src/executor.rs b/libafl_qemu/src/executor.rs index 9776c5a331..795b53eec5 100644 --- a/libafl_qemu/src/executor.rs +++ b/libafl_qemu/src/executor.rs @@ -21,7 +21,7 @@ use libafl::{ inprocess_fork::stateful::StatefulInProcessForkExecutor, }, feedbacks::Feedback, - fuzzer::HasObjective, + fuzzer::{HasFeedback, HasObjective}, inputs::Input, observers::ObserversTuple, state::{HasCurrentTestcase, HasExecutions, HasSolutions}, @@ -60,7 +60,7 @@ pub struct QemuExecutor<'a, C, CM, ED, EM, ET, H, I, OT, S, SM, Z> { /// /// This should be used as a crash handler, and nothing else. #[cfg(feature = "usermode")] -pub unsafe fn inproc_qemu_crash_handler( +pub unsafe fn inproc_qemu_crash_handler( signal: Signal, info: &mut siginfo_t, mut context: Option<&mut ucontext_t>, @@ -70,9 +70,10 @@ pub unsafe fn inproc_qemu_crash_handler( E: Executor + HasObservers, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCorpus + HasCurrentTestcase + Unpin, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone + Unpin, { log::debug!("QEMU signal handler has been triggered (signal {signal})"); @@ -126,7 +127,7 @@ pub unsafe fn inproc_qemu_crash_handler( log::debug!("Running crash hooks."); run_target_crash_hooks::(signal.into()); - assert!(unsafe { data.maybe_report_crash::(None) }); + assert!(unsafe { data.maybe_report_crash::(None) }); if let Some(cpu) = qemu.current_cpu() { eprint!("QEMU Context:\n{}", cpu.display_context()); @@ -163,7 +164,7 @@ pub(crate) static BREAK_ON_TMOUT: AtomicBool = AtomicBool::new(false); /// # Safety /// Can call through the `unix_signal_handler::inproc_timeout_handler`. /// Calling this method multiple times concurrently can lead to race conditions. -pub unsafe fn inproc_qemu_timeout_handler( +pub unsafe fn inproc_qemu_timeout_handler( signal: Signal, info: &mut siginfo_t, context: Option<&mut ucontext_t>, @@ -173,11 +174,12 @@ pub unsafe fn inproc_qemu_timeout_handler( E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, ET: EmulatorModuleTuple, + F: Feedback, I: Unpin, OF: Feedback, S: HasExecutions + HasSolutions + Unpin + HasCurrentTestcase, I: Input, - Z: HasObjective, + Z: HasObjective + HasFeedback, { #[cfg(feature = "systemmode")] unsafe { @@ -187,6 +189,7 @@ pub unsafe fn inproc_qemu_timeout_handler( libafl::executors::hooks::unix::unix_signal_handler::inproc_timeout_handler::< E, EM, + F, I, OF, S, @@ -205,6 +208,7 @@ pub unsafe fn inproc_qemu_timeout_handler( libafl::executors::hooks::unix::unix_signal_handler::inproc_timeout_handler::< E, EM, + F, I, OF, S, @@ -234,7 +238,7 @@ where OT: ObserversTuple, S: Unpin + HasExecutions + HasSolutions + HasCurrentTestcase, { - pub fn new( + pub fn new( emulator: Emulator, harness_fn: &'a mut H, observers: OT, @@ -248,8 +252,12 @@ where CM: CommandManager, ED: EmulatorDriver, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, - Z: HasObjective + HasScheduler + ExecutionProcessor, + Z: HasObjective + + HasScheduler + + ExecutionProcessor + + HasFeedback, { let mut inner = StatefulInProcessExecutor::with_timeout( harness_fn, emulator, observers, fuzzer, state, event_mgr, timeout, @@ -259,7 +267,7 @@ where #[cfg(feature = "usermode")] { inner.inprocess_hooks_mut().crash_handler = - inproc_qemu_crash_handler:: as *const c_void; + inproc_qemu_crash_handler:: as *const c_void; } // rewrite the timeout handler pointer @@ -267,6 +275,7 @@ where StatefulInProcessExecutor<'a, EM, Emulator, H, I, OT, S, Z>, EM, ET, + F, I, OF, S, diff --git a/libafl_qemu/src/lib.rs b/libafl_qemu/src/lib.rs index e27b7df3c4..00972bf367 100644 --- a/libafl_qemu/src/lib.rs +++ b/libafl_qemu/src/lib.rs @@ -16,6 +16,10 @@ // This causes bindgen to generate empty Rust struct that are generally not FFI-safe due to C++ having empty structs with size 1 // As the QEMU codebase is C, it is FFI-safe and we just ignore the warning #![allow(improper_ctypes)] +// you don't build this without std +#![allow(clippy::std_instead_of_core)] +// same +#![allow(clippy::std_instead_of_alloc)] use std::env; diff --git a/libafl_qemu/src/modules/edges/helpers.rs b/libafl_qemu/src/modules/edges/helpers.rs index f82a70259e..9a92d16a17 100644 --- a/libafl_qemu/src/modules/edges/helpers.rs +++ b/libafl_qemu/src/modules/edges/helpers.rs @@ -1,4 +1,4 @@ -use std::ptr; +use core::ptr; /// Generators, responsible for generating block/edge ids pub use generators::{gen_hashed_block_ids, gen_hashed_edge_ids, gen_unique_edge_ids}; diff --git a/libafl_qemu/src/modules/utils/addr2line.rs b/libafl_qemu/src/modules/utils/addr2line.rs index 3c1c9d24d3..a28bc86b1e 100644 --- a/libafl_qemu/src/modules/utils/addr2line.rs +++ b/libafl_qemu/src/modules/utils/addr2line.rs @@ -11,19 +11,17 @@ use rangemap::RangeMap; use crate::Qemu; // (almost) Copy paste from addr2line/src/bin/addr2line.rs fn print_function(name: Option<&str>, language: Option) -> String { - let ret = if let Some(name) = name { + if let Some(name) = name { addr2line::demangle_auto(Cow::from(name), language).to_string() } else { "??".to_string() - }; - // println!("{ret:?}"); - ret + } } /// check if this binary is pie (for 64bit binary only) #[must_use] pub fn is_pie(file: object::File<'_>) -> bool { - let is_pie = match file { + match file { object::File::Elf64(elf) => { let mut is_pie = false; let table = elf.elf_section_table(); @@ -41,9 +39,7 @@ pub fn is_pie(file: object::File<'_>) -> bool { is_pie } _ => false, - }; - - is_pie + } } pub struct AddressResolver { diff --git a/libafl_qemu/src/qemu/mod.rs b/libafl_qemu/src/qemu/mod.rs index d412aaf1db..2def923471 100644 --- a/libafl_qemu/src/qemu/mod.rs +++ b/libafl_qemu/src/qemu/mod.rs @@ -172,7 +172,7 @@ pub struct HookData(u64); unsafe extern "C" fn gdb_cmd(data: *mut c_void, buf: *mut u8, len: usize) -> bool { unsafe { let closure = &mut *(data as *mut Box FnMut(Qemu, &'r str) -> bool>); - let cmd = std::str::from_utf8_unchecked(std::slice::from_raw_parts(buf, len)); + let cmd = core::str::from_utf8_unchecked(std::slice::from_raw_parts(buf, len)); let qemu = Qemu::get_unchecked(); closure(qemu, cmd) } diff --git a/libafl_sugar/src/forkserver.rs b/libafl_sugar/src/forkserver.rs index c536f69711..7ac5adb47b 100644 --- a/libafl_sugar/src/forkserver.rs +++ b/libafl_sugar/src/forkserver.rs @@ -1,6 +1,7 @@ //! An `afl`-style forkserver fuzzer. //! Use this if your target has complex state that needs to be reset. -use std::{fs, net::SocketAddr, path::PathBuf, time::Duration}; +use core::{net::SocketAddr, time::Duration}; +use std::{fs, path::PathBuf}; use libafl::{ Error, HasMetadata, diff --git a/libafl_sugar/src/inmemory.rs b/libafl_sugar/src/inmemory.rs index 45e31b4c3f..66b8d72f75 100644 --- a/libafl_sugar/src/inmemory.rs +++ b/libafl_sugar/src/inmemory.rs @@ -1,8 +1,12 @@ //! In-Memory fuzzing made easy. //! Use this sugar for scaling `libfuzzer`-style fuzzers. -use core::fmt::{self, Debug, Formatter}; -use std::{fs, net::SocketAddr, path::PathBuf, time::Duration}; +use core::{ + fmt::{self, Debug, Formatter}, + net::SocketAddr, + time::Duration, +}; +use std::{fs, path::PathBuf}; use libafl::{ Error, HasMetadata, diff --git a/libafl_sugar/src/qemu.rs b/libafl_sugar/src/qemu.rs index 7dc98aeeb2..59602f0f94 100644 --- a/libafl_sugar/src/qemu.rs +++ b/libafl_sugar/src/qemu.rs @@ -1,6 +1,10 @@ //! In-memory fuzzer with `QEMU`-based binary-only instrumentation -use core::fmt::{self, Debug, Formatter}; -use std::{fs, net::SocketAddr, path::PathBuf, time::Duration}; +use core::{ + fmt::{self, Debug, Formatter}, + net::SocketAddr, + time::Duration, +}; +use std::{fs, path::PathBuf}; use libafl::{ HasMetadata, diff --git a/libafl_targets/src/drcov.rs b/libafl_targets/src/drcov.rs index f9f4891a8a..83170ae32b 100644 --- a/libafl_targets/src/drcov.rs +++ b/libafl_targets/src/drcov.rs @@ -217,8 +217,8 @@ impl DrCovModuleEntry { #[must_use] pub fn to_module_line(&self) -> String { format!( - "{:03}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, {:?}", - self.id, self.base, self.end, self.entry, self.checksum, self.timestamp, self.path + "{:03}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, {}", + self.id, self.base, self.end, self.entry, self.checksum, self.timestamp, self.path.display() ) } } diff --git a/libafl_targets/src/windows_asan.rs b/libafl_targets/src/windows_asan.rs index f93f40f099..1d40db6290 100644 --- a/libafl_targets/src/windows_asan.rs +++ b/libafl_targets/src/windows_asan.rs @@ -1,7 +1,7 @@ //! Setup asan death callbback use libafl::{ - HasObjective, + HasFeedback, HasObjective, events::{EventFirer, EventRestarter}, executors::{Executor, HasObservers, hooks::windows::windows_asan_handler::asan_death_handler}, feedbacks::Feedback, @@ -29,17 +29,21 @@ unsafe extern "C" { /// /// # Safety /// Calls the unsafe `__sanitizer_set_death_callback` symbol, but should be safe to call otherwise. -pub unsafe fn setup_asan_callback(_executor: &E, _event_mgr: &EM, _fuzzer: &Z) -where +pub unsafe fn setup_asan_callback( + _executor: &E, + _event_mgr: &EM, + _fuzzer: &Z, +) where E: Executor + HasObservers, E::Observers: ObserversTuple, EM: EventFirer + EventRestarter, + F: Feedback, OF: Feedback, S: HasExecutions + HasSolutions + HasCurrentTestcase, - Z: HasObjective, + Z: HasObjective + HasFeedback, I: Input + Clone, { unsafe { - __sanitizer_set_death_callback(Some(asan_death_handler::)); + __sanitizer_set_death_callback(Some(asan_death_handler::)); } } diff --git a/utils/desyscall/src/mmap.rs b/utils/desyscall/src/mmap.rs index 898646c272..3dc4f47612 100644 --- a/utils/desyscall/src/mmap.rs +++ b/utils/desyscall/src/mmap.rs @@ -1,6 +1,6 @@ //! Stub out syscalls. Linux only. -use std::ptr; +use core::ptr; use libc::{c_int, c_void, off_t, size_t}; use meminterval::Interval;