Rename OSError -> OsError and merge with redundant Error::File (#1944)

* OSError -> OsError

* Move File errors to io Errors

* Removing File errors

* fixes :)

* More format

* fix libfuzzer runtime
This commit is contained in:
Dominik Maier 2024-03-18 08:46:48 +01:00 committed by GitHub
parent fbd0d497d4
commit a0143d02a6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 69 additions and 68 deletions

View File

@ -1202,7 +1202,7 @@ where
return Err(Error::shutting_down()); return Err(Error::shutting_down());
} }
Err(Error::File(_, _)) => { Err(Error::OsError(..)) => {
// port was likely already bound // port was likely already bound
let mgr = TcpEventManager::<EMH, S>::with_hooks( let mgr = TcpEventManager::<EMH, S>::with_hooks(
&("127.0.0.1", self.broker_port), &("127.0.0.1", self.broker_port),

View File

@ -445,10 +445,10 @@ impl Forkserver {
pub fn read_st_timed(&mut self, timeout: &TimeSpec) -> Result<Option<i32>, Error> { pub fn read_st_timed(&mut self, timeout: &TimeSpec) -> Result<Option<i32>, Error> {
let mut buf: [u8; 4] = [0_u8; 4]; let mut buf: [u8; 4] = [0_u8; 4];
let Some(st_read) = self.st_pipe.read_end() else { let Some(st_read) = self.st_pipe.read_end() else {
return Err(Error::file(io::Error::new( return Err(Error::os_error(
ErrorKind::BrokenPipe, io::Error::new(ErrorKind::BrokenPipe, "Read pipe end was already closed"),
"Read pipe end was already closed", "read_st_timed failed",
))); ));
}; };
// # Safety // # Safety

View File

@ -142,13 +142,19 @@ where
let corpus_dir = corpus_dir.into(); let corpus_dir = corpus_dir.into();
if let Err(e) = fs::create_dir(&corpus_dir) { if let Err(e) = fs::create_dir(&corpus_dir) {
if !corpus_dir.is_dir() { if !corpus_dir.is_dir() {
return Err(Error::file(e)); return Err(Error::os_error(
e,
format!("Error creating directory {corpus_dir:?}"),
));
} }
} }
let solutions_dir = solutions_dir.into(); let solutions_dir = solutions_dir.into();
if let Err(e) = fs::create_dir(&solutions_dir) { if let Err(e) = fs::create_dir(&solutions_dir) {
if !corpus_dir.is_dir() { if !corpus_dir.is_dir() {
return Err(Error::file(e)); return Err(Error::os_error(
e,
format!("Error creating directory {solutions_dir:?}"),
));
} }
} }
Ok(Self { Ok(Self {

View File

@ -295,9 +295,6 @@ pub enum Error {
/// Compression error /// Compression error
#[cfg(feature = "gzip")] #[cfg(feature = "gzip")]
Compression(ErrorBacktrace), Compression(ErrorBacktrace),
/// File related error
#[cfg(feature = "std")]
File(io::Error, ErrorBacktrace),
/// Optional val was supposed to be set, but isn't. /// Optional val was supposed to be set, but isn't.
EmptyOptional(String, ErrorBacktrace), EmptyOptional(String, ErrorBacktrace),
/// Key not in Map /// Key not in Map
@ -316,9 +313,9 @@ pub enum Error {
Unsupported(String, ErrorBacktrace), Unsupported(String, ErrorBacktrace),
/// Shutting down, not really an error. /// Shutting down, not really an error.
ShuttingDown, ShuttingDown,
/// OS error from `std::io::Error::last_os_error`; /// OS error, wrapping a [`std::io::Error`]
#[cfg(feature = "std")] #[cfg(feature = "std")]
OSError(io::Error, String, ErrorBacktrace), OsError(io::Error, String, ErrorBacktrace),
/// Something else happened /// Something else happened
Unknown(String, ErrorBacktrace), Unknown(String, ErrorBacktrace),
} }
@ -338,12 +335,6 @@ impl Error {
pub fn compression() -> Self { pub fn compression() -> Self {
Error::Compression(ErrorBacktrace::new()) Error::Compression(ErrorBacktrace::new())
} }
#[cfg(feature = "std")]
/// File related error
#[must_use]
pub fn file(arg: io::Error) -> Self {
Error::File(arg, ErrorBacktrace::new())
}
/// Optional val was supposed to be set, but isn't. /// Optional val was supposed to be set, but isn't.
#[must_use] #[must_use]
pub fn empty_optional<S>(arg: S) -> Self pub fn empty_optional<S>(arg: S) -> Self
@ -413,14 +404,27 @@ impl Error {
{ {
Error::Unsupported(arg.into(), ErrorBacktrace::new()) Error::Unsupported(arg.into(), ErrorBacktrace::new())
} }
/// OS error with additional message
#[cfg(feature = "std")] #[cfg(feature = "std")]
/// OS error from `std::io::Error::last_os_error`;
#[must_use] #[must_use]
pub fn os_error<S>(err: io::Error, msg: S) -> Self pub fn os_error<S>(err: io::Error, msg: S) -> Self
where where
S: Into<String>, S: Into<String>,
{ {
Error::OSError(err, msg.into(), ErrorBacktrace::new()) Error::OsError(err, msg.into(), ErrorBacktrace::new())
}
/// OS error from [`std::io::Error::last_os_error`] with additional message
#[cfg(feature = "std")]
#[must_use]
pub fn last_os_error<S>(msg: S) -> Self
where
S: Into<String>,
{
Error::OsError(
io::Error::last_os_error(),
msg.into(),
ErrorBacktrace::new(),
)
} }
/// Something else happened /// Something else happened
#[must_use] #[must_use]
@ -444,11 +448,6 @@ impl Display for Error {
write!(f, "Error in decompression")?; write!(f, "Error in decompression")?;
display_error_backtrace(f, b) display_error_backtrace(f, b)
} }
#[cfg(feature = "std")]
Self::File(err, b) => {
write!(f, "File IO failed: {:?}", &err)?;
display_error_backtrace(f, b)
}
Self::EmptyOptional(s, b) => { Self::EmptyOptional(s, b) => {
write!(f, "Optional value `{0}` was not set", &s)?; write!(f, "Optional value `{0}` was not set", &s)?;
display_error_backtrace(f, b) display_error_backtrace(f, b)
@ -487,7 +486,7 @@ impl Display for Error {
} }
Self::ShuttingDown => write!(f, "Shutting down!"), Self::ShuttingDown => write!(f, "Shutting down!"),
#[cfg(feature = "std")] #[cfg(feature = "std")]
Self::OSError(err, s, b) => { Self::OsError(err, s, b) => {
write!(f, "OS error: {0}: {1}", &s, err)?; write!(f, "OS error: {0}: {1}", &s, err)?;
display_error_backtrace(f, b) display_error_backtrace(f, b)
} }
@ -544,7 +543,7 @@ impl From<nix::Error> for Error {
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl From<io::Error> for Error { impl From<io::Error> for Error {
fn from(err: io::Error) -> Self { fn from(err: io::Error) -> Self {
Self::file(err) Self::os_error(err, "io::Error ocurred")
} }
} }

View File

@ -705,7 +705,7 @@ where
let _listener_thread = broker.launch_listener(Listener::Tcp(listener))?; let _listener_thread = broker.launch_listener(Listener::Tcp(listener))?;
Ok(LlmpConnection::IsBroker { broker }) Ok(LlmpConnection::IsBroker { broker })
} }
Err(Error::File(e, _)) if e.kind() == ErrorKind::AddrInUse => { Err(Error::OsError(e, ..)) if e.kind() == ErrorKind::AddrInUse => {
// We are the client :) // We are the client :)
log::info!("We're the client (internal port already bound by broker, {e:#?})"); log::info!("We're the client (internal port already bound by broker, {e:#?})");
Ok(LlmpConnection::IsClient { Ok(LlmpConnection::IsClient {
@ -2623,7 +2623,7 @@ where
.expect("B2B: Error forwarding message. Exiting."); .expect("B2B: Error forwarding message. Exiting.");
} }
Err(e) => { Err(e) => {
if let Error::File(e, _) = e { if let Error::OsError(e, ..) = e {
if e.kind() == ErrorKind::UnexpectedEof { if e.kind() == ErrorKind::UnexpectedEof {
log::info!( log::info!(
"Broker {peer_address} seems to have disconnected, exiting" "Broker {peer_address} seems to have disconnected, exiting"

View File

@ -107,7 +107,7 @@ pub fn startable_self() -> Result<Command, Error> {
#[cfg(all(unix, feature = "std"))] #[cfg(all(unix, feature = "std"))]
pub fn dup(fd: RawFd) -> Result<RawFd, Error> { pub fn dup(fd: RawFd) -> Result<RawFd, Error> {
match unsafe { libc::dup(fd) } { match unsafe { libc::dup(fd) } {
-1 => Err(Error::file(std::io::Error::last_os_error())), -1 => Err(Error::last_os_error(format!("Error calling dup({fd})"))),
new_fd => Ok(new_fd), new_fd => Ok(new_fd),
} }
} }
@ -119,7 +119,9 @@ pub fn dup(fd: RawFd) -> Result<RawFd, Error> {
#[cfg(all(unix, feature = "std"))] #[cfg(all(unix, feature = "std"))]
pub fn dup2(fd: RawFd, device: RawFd) -> Result<(), Error> { pub fn dup2(fd: RawFd, device: RawFd) -> Result<(), Error> {
match unsafe { libc::dup2(fd, device) } { match unsafe { libc::dup2(fd, device) } {
-1 => Err(Error::file(std::io::Error::last_os_error())), -1 => Err(Error::last_os_error(format!(
"Error calling dup2({fd}, {device})"
))),
_ => Ok(()), _ => Ok(()),
} }
} }

View File

@ -590,7 +590,7 @@ pub mod unix_shmem {
use alloc::string::ToString; use alloc::string::ToString;
use core::{ptr, slice}; use core::{ptr, slice};
use std::{io, io::Write, process}; use std::{io::Write, process};
use libc::{ use libc::{
c_int, c_uchar, close, ftruncate, mmap, munmap, shm_open, shm_unlink, shmat, shmctl, c_int, c_uchar, close, ftruncate, mmap, munmap, shm_open, shm_unlink, shmat, shmctl,
@ -648,21 +648,17 @@ pub mod unix_shmem {
0o600, 0o600,
); );
if shm_fd == -1 { if shm_fd == -1 {
return Err(Error::os_error( return Err(Error::last_os_error(format!(
io::Error::last_os_error(), "Failed to shm_open map with id {filename_path:?}",
format!("Failed to shm_open map with id {filename_path:?}",), )));
));
} }
/* configure the size of the shared memory segment */ /* configure the size of the shared memory segment */
if ftruncate(shm_fd, map_size.try_into()?) != 0 { if ftruncate(shm_fd, map_size.try_into()?) != 0 {
shm_unlink(filename_path.as_ptr() as *const _); shm_unlink(filename_path.as_ptr() as *const _);
return Err(Error::os_error( return Err(Error::last_os_error(format!(
io::Error::last_os_error(),
format!(
"setup_shm(): ftruncate() failed for map with id {filename_path:?}", "setup_shm(): ftruncate() failed for map with id {filename_path:?}",
), )));
));
} }
/* map the shared memory segment to the address space of the process */ /* map the shared memory segment to the address space of the process */
@ -677,10 +673,9 @@ pub mod unix_shmem {
if map == libc::MAP_FAILED || map.is_null() { if map == libc::MAP_FAILED || map.is_null() {
close(shm_fd); close(shm_fd);
shm_unlink(filename_path.as_ptr() as *const _); shm_unlink(filename_path.as_ptr() as *const _);
return Err(Error::os_error( return Err(Error::last_os_error(format!(
io::Error::last_os_error(), "mmap() failed for map with id {filename_path:?}",
format!("mmap() failed for map with id {filename_path:?}",), )));
));
} }
Ok(Self { Ok(Self {
@ -708,10 +703,9 @@ pub mod unix_shmem {
); );
if map == libc::MAP_FAILED || map.is_null() { if map == libc::MAP_FAILED || map.is_null() {
close(shm_fd); close(shm_fd);
return Err(Error::os_error( return Err(Error::last_os_error(format!(
io::Error::last_os_error(), "mmap() failed for map with fd {shm_fd:?}"
format!("mmap() failed for map with fd {shm_fd:?}"), )));
));
} }
Ok(Self { Ok(Self {
@ -854,10 +848,7 @@ pub mod unix_shmem {
let map = shmat(os_id, ptr::null(), 0) as *mut c_uchar; let map = shmat(os_id, ptr::null(), 0) as *mut c_uchar;
if map as c_int == -1 || map.is_null() { if map as c_int == -1 || map.is_null() {
return Err(Error::os_error( return Err(Error::last_os_error("Failed to map the shared mapping"));
io::Error::last_os_error(),
"Failed to map the shared mapping",
));
} }
Ok(Self { Ok(Self {
@ -875,10 +866,9 @@ pub mod unix_shmem {
let map = shmat(id_int, ptr::null(), 0) as *mut c_uchar; let map = shmat(id_int, ptr::null(), 0) as *mut c_uchar;
if map.is_null() || map == ptr::null_mut::<c_uchar>().wrapping_sub(1) { if map.is_null() || map == ptr::null_mut::<c_uchar>().wrapping_sub(1) {
return Err(Error::os_error( return Err(Error::last_os_error(format!(
io::Error::last_os_error(), "Failed to map the shared mapping with id {id_int}"
format!("Failed to map the shared mapping with id {id_int}"), )));
));
} }
Ok(Self { id, map, map_size }) Ok(Self { id, map, map_size })

View File

@ -114,7 +114,7 @@ where
let path = self.corpus_dir.join(&name); let path = self.corpus_dir.join(&name);
match input.to_file(&path) { match input.to_file(&path) {
Err(Error::File(e, _)) if e.kind() == ErrorKind::AlreadyExists => { Err(Error::OsError(e, ..)) if e.kind() == ErrorKind::AlreadyExists => {
// we do not care if the file already exists; in this case, we assume it is equal // we do not care if the file already exists; in this case, we assume it is equal
} }
res => res?, res => res?,
@ -192,7 +192,7 @@ where
Error::empty("The testcase, when being saved, must have a file path!") Error::empty("The testcase, when being saved, must have a file path!")
})?; })?;
match input.to_file(path) { match input.to_file(path) {
Err(Error::File(e, _)) if e.kind() == ErrorKind::AlreadyExists => { Err(Error::OsError(e, ..)) if e.kind() == ErrorKind::AlreadyExists => {
// we do not care if the file already exists; in this case, we assume it is equal // we do not care if the file already exists; in this case, we assume it is equal
Ok(()) Ok(())
} }
@ -250,7 +250,7 @@ where
Error::illegal_state("Should have set the path in the LibfuzzerCrashCauseFeedback.") Error::illegal_state("Should have set the path in the LibfuzzerCrashCauseFeedback.")
})?; })?;
match input.to_file(path) { match input.to_file(path) {
Err(Error::File(e, _)) if e.kind() == ErrorKind::AlreadyExists => { Err(Error::OsError(e, ..)) if e.kind() == ErrorKind::AlreadyExists => {
// we do not care if the file already exists; in this case, we assume it is equal // we do not care if the file already exists; in this case, we assume it is equal
} }
res => res?, res => res?,

View File

@ -4,7 +4,8 @@ use std::{
fs::{rename, File}, fs::{rename, File},
io::Write, io::Write,
os::fd::{AsRawFd, FromRawFd}, os::fd::{AsRawFd, FromRawFd},
time::{SystemTime, UNIX_EPOCH}, ptr::addr_of_mut, ptr::addr_of_mut,
time::{SystemTime, UNIX_EPOCH},
}; };
use libafl::{ use libafl::{

View File

@ -394,11 +394,7 @@ impl<'a> LibfuzzerOptionsBuilder<'a> {
tui: self.tui, tui: self.tui,
runs: self.runs, runs: self.runs,
close_fd_mask: self.close_fd_mask, close_fd_mask: self.close_fd_mask,
unknown: self unknown: self.unknown.into_iter().map(ToString::to_string).collect(),
.unknown
.into_iter()
.map(ToString::to_string)
.collect(),
} }
} }
} }

View File

@ -462,7 +462,7 @@ impl QemuSnapshotHelper {
)); ));
} }
for (i, _, _) in found { for (i, ..) in found {
new_maps.tree.delete(i); new_maps.tree.delete(i);
} }
} }

View File

@ -26,3 +26,10 @@ do
cargo +nightly fmt --all cargo +nightly fmt --all
popd || exit 1 popd || exit 1
done done
echo "[*] Formatting libafl_libfuzzer_runtime"
pushd "libafl_libfuzzer/libafl_libfuzzer_runtime" || exit 1
cargo +nightly fmt --all
popd || exit 1
echo "[*] Done :)"