From be7477446387e5b04cd7ac4d619f42f29729e1b4 Mon Sep 17 00:00:00 2001 From: lazymio Date: Fri, 16 May 2025 23:06:23 +0800 Subject: [PATCH] Use `Arc<()>` to ref-counting `InputFile` (#3240) * clean lib_bolts::fs * clippy * avoid racy --- libafl_bolts/src/fs.rs | 33 ++++++++++----------------------- 1 file changed, 10 insertions(+), 23 deletions(-) diff --git a/libafl_bolts/src/fs.rs b/libafl_bolts/src/fs.rs index bdf6c7af78..fd4fdae8f3 100644 --- a/libafl_bolts/src/fs.rs +++ b/libafl_bolts/src/fs.rs @@ -1,14 +1,14 @@ //! `LibAFL` functionality for filesystem interaction -#[cfg(feature = "std")] -use alloc::{borrow::ToOwned, vec::Vec}; -use alloc::{rc::Rc, string::String}; -use core::cell::RefCell; -#[cfg(feature = "std")] -use core::time::Duration; #[cfg(unix)] use std::os::unix::prelude::{AsRawFd, RawFd}; -#[cfg(feature = "std")] + +use alloc::string::String; +use alloc::sync::Arc; +use alloc::{borrow::ToOwned, vec::Vec}; +use core::time::Duration; + +use crate::Error; use std::time::SystemTime; use std::{ fs::{self, File, OpenOptions, remove_file}, @@ -16,8 +16,6 @@ use std::{ path::{Path, PathBuf}, }; -use crate::Error; - /// The default filename to use to deliver testcases to the target pub const INPUTFILE_STD: &str = ".cur_input"; @@ -62,7 +60,6 @@ where /// An [`InputFile`] to write fuzzer input to. /// The target/forkserver will read from this file. -#[cfg(feature = "std")] #[derive(Debug)] pub struct InputFile { /// The filename/path too this [`InputFile`] @@ -71,7 +68,7 @@ pub struct InputFile { pub file: File, /// The ref count for this [`InputFile`]. /// Once it reaches 0, the underlying [`File`] will be removed. - pub rc: Rc>, + pub rc: Arc<()>, } impl Eq for InputFile {} @@ -84,11 +81,6 @@ impl PartialEq for InputFile { impl Clone for InputFile { fn clone(&self) -> Self { - { - let mut rc = self.rc.borrow_mut(); - assert_ne!(*rc, usize::MAX, "InputFile rc overflow"); - *rc += 1; - } Self { path: self.path.clone(), file: self.file.try_clone().unwrap(), @@ -113,7 +105,7 @@ impl InputFile { Ok(Self { path: filename.as_ref().to_owned(), file: f, - rc: Rc::new(RefCell::new(1)), + rc: Arc::new(()), }) } @@ -147,7 +139,6 @@ impl InputFile { /// Finds new files in the given directory, taking the last time we looked at this path as parameter. /// This method works recursively. /// If `last` is `None`, it'll load all file. -#[cfg(feature = "std")] pub fn find_new_files_rec>( dir: P, last_check: &Option, @@ -182,13 +173,9 @@ pub fn find_new_files_rec>( Ok(new_files) } -#[cfg(feature = "std")] impl Drop for InputFile { fn drop(&mut self) { - let mut rc = self.rc.borrow_mut(); - assert_ne!(*rc, 0, "InputFile rc should never be 0"); - *rc -= 1; - if *rc == 0 { + if Arc::into_inner(core::mem::take(&mut self.rc)).is_some() { // try to remove the file, but ignore errors drop(remove_file(&self.path)); }