Moving to named parameters in format strings (#827)

* autofix

* you're just asking for a clamping

* autofmt on linux

* fix nits

* change back nit

* unfixing as u64 for GuestAddr

* fix

* ignoring clippy for GuestAddress
This commit is contained in:
Dominik Maier 2022-10-11 13:45:01 +02:00 committed by GitHub
parent f3e8ed832b
commit 94f0c7f56e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
52 changed files with 222 additions and 226 deletions

View File

@ -157,7 +157,7 @@ where
self.shmem_provider.post_fork(false)?; self.shmem_provider.post_fork(false)?;
handles.push(child.pid); handles.push(child.pid);
#[cfg(feature = "std")] #[cfg(feature = "std")]
println!("child spawned and bound to core {}", id); println!("child spawned and bound to core {id}");
} }
ForkResult::Child => { ForkResult::Child => {
println!("{:?} PostFork", unsafe { libc::getpid() }); println!("{:?} PostFork", unsafe { libc::getpid() });
@ -221,7 +221,7 @@ where
unsafe { unsafe {
libc::waitpid(*handle, &mut status, 0); libc::waitpid(*handle, &mut status, 0);
if status != 0 { if status != 0 {
println!("Client with pid {} exited with status {}", handle, status); println!("Client with pid {handle} exited with status {status}");
} }
} }
} }

View File

@ -315,7 +315,7 @@ impl Listener {
Listener::Tcp(inner) => match inner.accept() { Listener::Tcp(inner) => match inner.accept() {
Ok(res) => ListenerStream::Tcp(res.0, res.1), Ok(res) => ListenerStream::Tcp(res.0, res.1),
Err(err) => { Err(err) => {
println!("Ignoring failed accept: {:?}", err); println!("Ignoring failed accept: {err:?}");
ListenerStream::Empty() ListenerStream::Empty()
} }
}, },
@ -366,7 +366,7 @@ const fn llmp_align(to_align: usize) -> usize {
#[cfg(feature = "std")] #[cfg(feature = "std")]
#[inline] #[inline]
fn msg_offset_from_env(env_name: &str) -> Result<Option<u64>, Error> { fn msg_offset_from_env(env_name: &str) -> Result<Option<u64>, Error> {
let msg_offset_str = env::var(&format!("{}_OFFSET", env_name))?; let msg_offset_str = env::var(&format!("{env_name}_OFFSET"))?;
Ok(if msg_offset_str == _NULL_ENV_STR { Ok(if msg_offset_str == _NULL_ENV_STR {
None None
} else { } else {
@ -433,7 +433,7 @@ fn recv_tcp_msg(stream: &mut TcpStream) -> Result<Vec<u8>, Error> {
bytes.resize(size as usize, 0_u8); bytes.resize(size as usize, 0_u8);
#[cfg(feature = "llmp_debug")] #[cfg(feature = "llmp_debug")]
println!("LLMP TCP: Receiving payload of size {}", size); println!("LLMP TCP: Receiving payload of size {size}");
stream stream
.read_exact(&mut bytes) .read_exact(&mut bytes)
@ -818,7 +818,7 @@ where
#[cfg(feature = "std")] #[cfg(feature = "std")]
#[inline] #[inline]
fn client_id_from_env(env_name: &str) -> Result<Option<ClientId>, Error> { fn client_id_from_env(env_name: &str) -> Result<Option<ClientId>, Error> {
let client_id_str = env::var(&format!("{}_CLIENT_ID", env_name))?; let client_id_str = env::var(&format!("{env_name}_CLIENT_ID"))?;
Ok(if client_id_str == _NULL_ENV_STR { Ok(if client_id_str == _NULL_ENV_STR {
None None
} else { } else {
@ -829,7 +829,7 @@ where
/// Writes the `id` to an env var /// Writes the `id` to an env var
#[cfg(feature = "std")] #[cfg(feature = "std")]
fn client_id_to_env(env_name: &str, id: ClientId) { fn client_id_to_env(env_name: &str, id: ClientId) {
env::set_var(&format!("{}_CLIENT_ID", env_name), &format!("{}", id)); env::set_var(&format!("{env_name}_CLIENT_ID"), &format!("{id}"));
} }
/// Reattach to a vacant `out_shmem`, to with a previous sender stored the information in an env before. /// Reattach to a vacant `out_shmem`, to with a previous sender stored the information in an env before.
@ -956,7 +956,7 @@ where
let page = map.page_mut(); let page = map.page_mut();
let last_msg = self.last_msg_sent; let last_msg = self.last_msg_sent;
assert!((*page).size_used + EOP_MSG_SIZE <= (*page).size_total, assert!((*page).size_used + EOP_MSG_SIZE <= (*page).size_total,
"PROGRAM ABORT : BUG: EOP does not fit in page! page {:?}, size_current {:?}, size_total {:?}", page, "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)); ptr::addr_of!((*page).size_used), ptr::addr_of!((*page).size_total));
let mut ret: *mut LlmpMsg = if last_msg.is_null() { let mut ret: *mut LlmpMsg = if last_msg.is_null() {
@ -1133,7 +1133,7 @@ where
let mut new_map = new_map_shmem.page_mut(); let mut new_map = new_map_shmem.page_mut();
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(all(feature = "llmp_debug", feature = "std"))]
println!("got new map at: {:?}", new_map); println!("got new map at: {new_map:?}");
(*new_map).current_msg_id.store( (*new_map).current_msg_id.store(
(*old_map).current_msg_id.load(Ordering::Relaxed), (*old_map).current_msg_id.load(Ordering::Relaxed),
@ -1232,7 +1232,7 @@ where
- size_of::<LlmpMsg>(); - size_of::<LlmpMsg>();
if buf_len_padded > old_len_padded.try_into().unwrap() { if buf_len_padded > old_len_padded.try_into().unwrap() {
return Err(Error::illegal_argument(format!("Cannot shrink msg of size {} (paded: {}) to requested larger size of {} (padded: {})!", (*msg).buf_len, old_len_padded, shrinked_len, buf_len_padded))); return Err(Error::illegal_argument(format!("Cannot shrink msg of size {} (paded: {old_len_padded}) to requested larger size of {shrinked_len} (padded: {buf_len_padded})!", (*msg).buf_len)));
} }
(*msg).buf_len = shrinked_len as u64; (*msg).buf_len = shrinked_len as u64;
@ -1722,10 +1722,10 @@ where
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub unsafe fn msg_to_env(&self, msg: *const LlmpMsg, map_env_name: &str) -> Result<(), Error> { pub unsafe fn msg_to_env(&self, msg: *const LlmpMsg, map_env_name: &str) -> Result<(), Error> {
if msg.is_null() { if msg.is_null() {
env::set_var(&format!("{}_OFFSET", map_env_name), _NULL_ENV_STR); env::set_var(&format!("{map_env_name}_OFFSET"), _NULL_ENV_STR);
} else { } else {
env::set_var( env::set_var(
&format!("{}_OFFSET", map_env_name), &format!("{map_env_name}_OFFSET"),
format!("{}", self.msg_to_offset(msg)?), format!("{}", self.msg_to_offset(msg)?),
); );
} }
@ -1857,13 +1857,13 @@ where
A: ToSocketAddrs, A: ToSocketAddrs,
{ {
let mut stream = TcpStream::connect(addr)?; let mut stream = TcpStream::connect(addr)?;
println!("B2B: Connected to {:?}", stream); println!("B2B: Connected to {stream:?}");
match recv_tcp_msg(&mut stream)?.try_into()? { match recv_tcp_msg(&mut stream)?.try_into()? {
TcpResponse::BrokerConnectHello { TcpResponse::BrokerConnectHello {
broker_shmem_description: _, broker_shmem_description: _,
hostname, hostname,
} => println!("B2B: Connected to {}", hostname), } => println!("B2B: Connected to {hostname}"),
_ => { _ => {
return Err(Error::illegal_state( return Err(Error::illegal_state(
"Unexpected response from B2B server received.".to_string(), "Unexpected response from B2B server received.".to_string(),
@ -1880,7 +1880,7 @@ where
let broker_id = match recv_tcp_msg(&mut stream)?.try_into()? { let broker_id = match recv_tcp_msg(&mut stream)?.try_into()? {
TcpResponse::RemoteBrokerAccepted { broker_id } => { TcpResponse::RemoteBrokerAccepted { broker_id } => {
println!("B2B: Got Connection Ack, broker_id {}", broker_id); println!("B2B: Got Connection Ack, broker_id {broker_id}");
broker_id broker_id
} }
_ => { _ => {
@ -1891,7 +1891,7 @@ where
}; };
// TODO: use broker ids! // TODO: use broker ids!
println!("B2B: We are broker {}", broker_id); println!("B2B: We are broker {broker_id}");
// TODO: handle broker_ids properly/at all. // TODO: handle broker_ids properly/at all.
let map_description = Self::b2b_thread_on( let map_description = Self::b2b_thread_on(
@ -1931,7 +1931,7 @@ where
(*out).buf_len_padded = actual_size; (*out).buf_len_padded = actual_size;
/* We need to replace the message ID with our own */ /* We need to replace the message ID with our own */
if let Err(e) = self.llmp_out.send(out, false) { if let Err(e) = self.llmp_out.send(out, false) {
panic!("Error sending msg: {:?}", e); panic!("Error sending msg: {e:?}");
} }
self.llmp_out.last_msg_sent = out; self.llmp_out.last_msg_sent = out;
Ok(()) Ok(())
@ -1979,7 +1979,7 @@ where
if let Err(_e) = unsafe { setup_signal_handler(&mut GLOBAL_SIGHANDLER_STATE) } { if let Err(_e) = unsafe { setup_signal_handler(&mut GLOBAL_SIGHANDLER_STATE) } {
// We can live without a proper ctrl+c signal handler. Print and ignore. // We can live without a proper ctrl+c signal handler. Print and ignore.
#[cfg(feature = "std")] #[cfg(feature = "std")]
println!("Failed to setup signal handlers: {}", _e); println!("Failed to setup signal handlers: {_e}");
} }
while !self.is_shutting_down() { while !self.is_shutting_down() {
@ -2017,7 +2017,7 @@ where
pub fn launch_tcp_listener_on(&mut self, port: u16) -> Result<thread::JoinHandle<()>, Error> { pub fn launch_tcp_listener_on(&mut self, port: u16) -> Result<thread::JoinHandle<()>, Error> {
let listener = tcp_bind(port)?; let listener = tcp_bind(port)?;
// accept connections and process them, spawning a new thread for each one // accept connections and process them, spawning a new thread for each one
println!("Server listening on port {}", port); println!("Server listening on port {port}");
self.launch_listener(Listener::Tcp(listener)) self.launch_listener(Listener::Tcp(listener))
} }
@ -2076,7 +2076,7 @@ where
match LlmpSender::new(shmem_provider_bg.clone(), b2b_client_id, false) { match LlmpSender::new(shmem_provider_bg.clone(), b2b_client_id, false) {
Ok(new_sender) => new_sender, Ok(new_sender) => new_sender,
Err(e) => { Err(e) => {
panic!("B2B: Could not map shared map: {}", e); panic!("B2B: Could not map shared map: {e}");
} }
}; };
@ -2180,7 +2180,7 @@ where
TcpRequest::LocalClientHello { shmem_description } => { TcpRequest::LocalClientHello { shmem_description } => {
match Self::announce_new_client(sender, shmem_description) { match Self::announce_new_client(sender, shmem_description) {
Ok(()) => (), Ok(()) => (),
Err(e) => println!("Error forwarding client on map: {:?}", e), Err(e) => println!("Error forwarding client on map: {e:?}"),
}; };
if let Err(e) = send_tcp_msg( if let Err(e) = send_tcp_msg(
@ -2189,12 +2189,12 @@ where
client_id: *current_client_id, client_id: *current_client_id,
}, },
) { ) {
println!("An error occurred sending via tcp {}", e); println!("An error occurred sending via tcp {e}");
}; };
*current_client_id += 1; *current_client_id += 1;
} }
TcpRequest::RemoteBrokerHello { hostname } => { TcpRequest::RemoteBrokerHello { hostname } => {
println!("B2B new client: {}", hostname); println!("B2B new client: {hostname}");
// TODO: Clean up broker ids. // TODO: Clean up broker ids.
if send_tcp_msg( if send_tcp_msg(
@ -2213,7 +2213,7 @@ where
Self::b2b_thread_on(stream, *current_client_id, broker_shmem_description) Self::b2b_thread_on(stream, *current_client_id, broker_shmem_description)
{ {
if Self::announce_new_client(sender, &shmem_description).is_err() { if Self::announce_new_client(sender, &shmem_description).is_err() {
println!("B2B: Error announcing client {:?}", shmem_description); println!("B2B: Error announcing client {shmem_description:?}");
}; };
*current_client_id += 1; *current_client_id += 1;
} }
@ -2284,7 +2284,7 @@ where
match send_tcp_msg(&mut stream, &broker_hello) { match send_tcp_msg(&mut stream, &broker_hello) {
Ok(()) => {} Ok(()) => {}
Err(e) => { Err(e) => {
eprintln!("Error sending initial hello: {:?}", e); eprintln!("Error sending initial hello: {e:?}");
continue; continue;
} }
} }
@ -2292,14 +2292,14 @@ where
let buf = match recv_tcp_msg(&mut stream) { let buf = match recv_tcp_msg(&mut stream) {
Ok(buf) => buf, Ok(buf) => buf,
Err(e) => { Err(e) => {
eprintln!("Error receving from tcp: {:?}", e); eprintln!("Error receving from tcp: {e:?}");
continue; continue;
} }
}; };
let req = match buf.try_into() { let req = match buf.try_into() {
Ok(req) => req, Ok(req) => req,
Err(e) => { Err(e) => {
eprintln!("Could not deserialize tcp message: {:?}", e); eprintln!("Could not deserialize tcp message: {e:?}");
continue; continue;
} }
}; };
@ -2347,7 +2347,7 @@ where
match (*msg).tag { match (*msg).tag {
// first, handle the special, llmp-internal messages // first, handle the special, llmp-internal messages
LLMP_SLOW_RECEIVER_PANIC => { LLMP_SLOW_RECEIVER_PANIC => {
return Err(Error::unknown(format!("The broker was too slow to handle messages of client {} in time, so it quit. Either the client sent messages too fast, or we (the broker) got stuck!", client_id))); return Err(Error::unknown(format!("The broker was too slow to handle messages of client {client_id} in time, so it quit. Either the client sent messages too fast, or we (the broker) got stuck!")));
} }
LLMP_TAG_NEW_SHM_CLIENT => { LLMP_TAG_NEW_SHM_CLIENT => {
/* This client informs us about yet another new client /* This client informs us about yet another new client
@ -2386,7 +2386,7 @@ where
} }
Err(e) => { Err(e) => {
#[cfg(feature = "std")] #[cfg(feature = "std")]
println!("Error adding client! Ignoring: {:?}", e); println!("Error adding client! Ignoring: {e:?}");
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
return Err(Error::unknown(format!( return Err(Error::unknown(format!(
"Error adding client! PANIC! {:?}", "Error adding client! PANIC! {:?}",
@ -2474,11 +2474,11 @@ where
Ok(Self { Ok(Self {
sender: LlmpSender::on_existing_from_env( sender: LlmpSender::on_existing_from_env(
shmem_provider.clone(), shmem_provider.clone(),
&format!("{}_SENDER", env_name), &format!("{env_name}_SENDER"),
)?, )?,
receiver: LlmpReceiver::on_existing_from_env( receiver: LlmpReceiver::on_existing_from_env(
shmem_provider, shmem_provider,
&format!("{}_RECEIVER", env_name), &format!("{env_name}_RECEIVER"),
)?, )?,
}) })
} }
@ -2487,8 +2487,8 @@ where
/// A new client can attach to exactly the same state by calling [`LlmpClient::on_existing_shmem()`]. /// A new client can attach to exactly the same state by calling [`LlmpClient::on_existing_shmem()`].
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub fn to_env(&self, env_name: &str) -> Result<(), Error> { pub fn to_env(&self, env_name: &str) -> Result<(), Error> {
self.sender.to_env(&format!("{}_SENDER", env_name))?; self.sender.to_env(&format!("{env_name}_SENDER"))?;
self.receiver.to_env(&format!("{}_RECEIVER", env_name)) self.receiver.to_env(&format!("{env_name}_RECEIVER"))
} }
/// Describe this client in a way that it can be recreated, for example after crash /// Describe this client in a way that it can be recreated, for example after crash
@ -2679,7 +2679,7 @@ where
} }
} }
}; };
println!("Connected to port {}", port); println!("Connected to port {port}");
let broker_shmem_description = if let TcpResponse::BrokerConnectHello { let broker_shmem_description = if let TcpResponse::BrokerConnectHello {
broker_shmem_description, broker_shmem_description,
@ -2776,7 +2776,7 @@ mod tests {
dbg!(std::env::vars()); dbg!(std::env::vars());
for (key, value) in std::env::vars_os() { for (key, value) in std::env::vars_os() {
println!("{:?}: {:?}", key, value); println!("{key:?}: {value:?}");
} }
/* recreate the client from env, check if it still works */ /* recreate the client from env, check if it still works */

View File

@ -442,7 +442,7 @@ pub fn generate_minibsod<W: Write>(
match std::fs::read_to_string("/proc/self/maps") { match std::fs::read_to_string("/proc/self/maps") {
Ok(maps) => writer.write_all(maps.as_bytes())?, Ok(maps) => writer.write_all(maps.as_bytes())?,
Err(e) => writeln!(writer, "Couldn't load mappings: {:?}", e)?, Err(e) => writeln!(writer, "Couldn't load mappings: {e:?}")?,
}; };
} }

View File

@ -74,7 +74,7 @@ pub unsafe fn fork() -> Result<ForkResult, Error> {
let err_str = CString::new("Fork failed").unwrap(); let err_str = CString::new("Fork failed").unwrap();
libc::perror(err_str.as_ptr()); libc::perror(err_str.as_ptr());
} }
Err(Error::unknown(format!("Fork failed ({})", pid))) Err(Error::unknown(format!("Fork failed ({pid})")))
} }
_ => Ok(ForkResult::Child), _ => Ok(ForkResult::Child),
} }

View File

@ -87,7 +87,7 @@ where
{ {
fn id(&self) -> ShMemId { fn id(&self) -> ShMemId {
let client_id = self.inner.id(); let client_id = self.inner.id();
ShMemId::from_string(&format!("{}:{}", self.server_fd, client_id)) ShMemId::from_string(&format!("{}:{client_id}", self.server_fd))
} }
fn len(&self) -> usize { fn len(&self) -> usize {
@ -191,10 +191,12 @@ where
let (server_fd, client_fd) = self.send_receive(ServedShMemRequest::NewMap(map_size))?; let (server_fd, client_fd) = self.send_receive(ServedShMemRequest::NewMap(map_size))?;
Ok(ServedShMem { Ok(ServedShMem {
inner: ManuallyDrop::new(self.inner.shmem_from_id_and_size( inner: ManuallyDrop::new(
ShMemId::from_string(&format!("{}", client_fd)), self.inner.shmem_from_id_and_size(
map_size, ShMemId::from_string(&format!("{client_fd}")),
)?), map_size,
)?,
),
server_fd, server_fd,
}) })
} }
@ -207,10 +209,8 @@ where
))?; ))?;
Ok(ServedShMem { Ok(ServedShMem {
inner: ManuallyDrop::new( inner: ManuallyDrop::new(
self.inner.shmem_from_id_and_size( self.inner
ShMemId::from_string(&format!("{}", client_fd)), .shmem_from_id_and_size(ShMemId::from_string(&format!("{client_fd}")), size)?,
size,
)?,
), ),
server_fd, server_fd,
}) })
@ -405,12 +405,12 @@ where
*lock.lock().unwrap() = ShMemServiceStatus::Failed; *lock.lock().unwrap() = ShMemServiceStatus::Failed;
cvar.notify_one(); cvar.notify_one();
println!("Error creating ShMemService: {:?}", e); println!("Error creating ShMemService: {e:?}");
return Err(e); return Err(e);
} }
}; };
if let Err(e) = worker.listen(UNIX_SERVER_NAME, &childsyncpair) { if let Err(e) = worker.listen(UNIX_SERVER_NAME, &childsyncpair) {
println!("Error spawning ShMemService: {:?}", e); println!("Error spawning ShMemService: {e:?}");
Err(e) Err(e)
} else { } else {
Ok(()) Ok(())
@ -447,7 +447,7 @@ where
let err = err.expect_err("Expected service start to have failed, but it didn't?"); let err = err.expect_err("Expected service start to have failed, but it didn't?");
Self::Failed { Self::Failed {
err_msg: format!("{}", err), err_msg: format!("{err}"),
phantom: PhantomData, phantom: PhantomData,
} }
} }
@ -642,7 +642,7 @@ where
cvar.notify_one(); cvar.notify_one();
return Err(Error::unknown(format!( return Err(Error::unknown(format!(
"The ShMem server appears to already be running. We are probably a client. Error: {:?}", err))); "The ShMem server appears to already be running. We are probably a client. Error: {err:?}")));
} }
}; };
@ -660,7 +660,7 @@ where
Ok(num_fds) if num_fds > 0 => (), Ok(num_fds) if num_fds > 0 => (),
Ok(_) => continue, Ok(_) => continue,
Err(e) => { Err(e) => {
println!("Error polling for activity: {:?}", e); println!("Error polling for activity: {e:?}");
continue; continue;
} }
}; };
@ -684,12 +684,12 @@ where
let (stream, _addr) = match listener.accept_unix_addr() { let (stream, _addr) = match listener.accept_unix_addr() {
Ok(stream_val) => stream_val, Ok(stream_val) => stream_val,
Err(e) => { Err(e) => {
println!("Error accepting client: {:?}", e); println!("Error accepting client: {e:?}");
continue; continue;
} }
}; };
println!("Recieved connection from {:?}", _addr); println!("Recieved connection from {_addr:?}");
let pollfd = PollFd::new( let pollfd = PollFd::new(
stream.as_raw_fd(), stream.as_raw_fd(),
PollFlags::POLLIN | PollFlags::POLLRDNORM | PollFlags::POLLRDBAND, PollFlags::POLLIN | PollFlags::POLLRDNORM | PollFlags::POLLRDBAND,

View File

@ -417,10 +417,10 @@ pub unsafe fn setup_signal_handler<T: 'static + Handler>(handler: &mut T) -> Res
if sigaction(sig as i32, addr_of_mut!(sa), ptr::null_mut()) < 0 { if sigaction(sig as i32, addr_of_mut!(sa), ptr::null_mut()) < 0 {
#[cfg(feature = "std")] #[cfg(feature = "std")]
{ {
let err_str = CString::new(format!("Failed to setup {} handler", sig)).unwrap(); let err_str = CString::new(format!("Failed to setup {sig} handler")).unwrap();
libc::perror(err_str.as_ptr()); libc::perror(err_str.as_ptr());
} }
return Err(Error::unknown(format!("Could not set up {} handler", sig))); return Err(Error::unknown(format!("Could not set up {sig} handler")));
} }
} }
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);

View File

@ -208,9 +208,9 @@ pub trait ShMem: Sized + Debug + Clone + AsSlice<u8> + AsMutSlice<u8> {
#[cfg(feature = "std")] #[cfg(feature = "std")]
fn write_to_env(&self, env_name: &str) -> Result<(), Error> { fn write_to_env(&self, env_name: &str) -> Result<(), Error> {
let map_size = self.len(); let map_size = self.len();
let map_size_env = format!("{}_SIZE", env_name); let map_size_env = format!("{env_name}_SIZE");
env::set_var(env_name, self.id().to_string()); env::set_var(env_name, self.id().to_string());
env::set_var(map_size_env, format!("{}", map_size)); env::set_var(map_size_env, format!("{map_size}"));
Ok(()) Ok(())
} }
} }
@ -261,7 +261,7 @@ pub trait ShMemProvider: Clone + Default + Debug {
#[cfg(feature = "std")] #[cfg(feature = "std")]
fn existing_from_env(&mut self, env_name: &str) -> Result<Self::ShMem, Error> { fn existing_from_env(&mut self, env_name: &str) -> Result<Self::ShMem, Error> {
let map_shm_str = env::var(env_name)?; let map_shm_str = env::var(env_name)?;
let map_size = str::parse::<usize>(&env::var(format!("{}_SIZE", env_name))?)?; let map_size = str::parse::<usize>(&env::var(format!("{env_name}_SIZE"))?)?;
self.shmem_from_description(ShMemDescription::from_string_and_size( self.shmem_from_description(ShMemDescription::from_string_and_size(
&map_shm_str, &map_shm_str,
map_size, map_size,
@ -666,7 +666,7 @@ pub mod unix_shmem {
map: map as *mut u8, map: map as *mut u8,
map_size, map_size,
shm_fd, shm_fd,
id: ShMemId::from_string(&format!("{}", shm_fd)), id: ShMemId::from_string(&format!("{shm_fd}")),
}) })
} }
} }
@ -698,7 +698,7 @@ pub mod unix_shmem {
map: map as *mut u8, map: map as *mut u8,
map_size, map_size,
shm_fd, shm_fd,
id: ShMemId::from_string(&format!("{}", shm_fd)), id: ShMemId::from_string(&format!("{shm_fd}")),
}) })
} }
} }
@ -819,7 +819,7 @@ pub mod unix_shmem {
); );
if os_id < 0_i32 { if os_id < 0_i32 {
return Err(Error::unknown(format!("Failed to allocate a shared mapping of size {} - check OS limits (i.e shmall, shmmax)", map_size))); return Err(Error::unknown(format!("Failed to allocate a shared mapping of size {map_size} - check OS limits (i.e shmall, shmmax)")));
} }
let map = shmat(os_id, ptr::null(), 0) as *mut c_uchar; let map = shmat(os_id, ptr::null(), 0) as *mut c_uchar;
@ -975,8 +975,7 @@ pub mod unix_shmem {
if let Ok(boot_id) = if let Ok(boot_id) =
std::fs::read_to_string("/proc/sys/kernel/random/boot_id") std::fs::read_to_string("/proc/sys/kernel/random/boot_id")
{ {
let path_str = let path_str = format!("/dev/ashmem{boot_id}").trim().to_string();
format!("{}{}", "/dev/ashmem", boot_id).trim().to_string();
if std::path::Path::new(&path_str).exists() { if std::path::Path::new(&path_str).exists() {
path_str path_str
} else { } else {
@ -1025,7 +1024,7 @@ pub mod unix_shmem {
} }
Ok(Self { Ok(Self {
id: ShMemId::from_string(&format!("{}", fd)), id: ShMemId::from_string(&format!("{fd}")),
map: map as *mut u8, map: map as *mut u8,
map_size, map_size,
}) })

View File

@ -47,7 +47,7 @@ impl StateShMemContent {
pub fn buf_len_checked(&self, shmem_size: usize) -> Result<usize, Error> { pub fn buf_len_checked(&self, shmem_size: usize) -> Result<usize, Error> {
let buf_len = unsafe { read_volatile(&self.buf_len) }; let buf_len = unsafe { read_volatile(&self.buf_len) };
if size_of::<StateShMemContent>() + buf_len > shmem_size { if size_of::<StateShMemContent>() + buf_len > shmem_size {
Err(Error::illegal_state(format!("Stored buf_len is larger than the shared map! Shared data corrupted? Expected {} bytes max, but got {} (buf_len {})", shmem_size, size_of::<StateShMemContent>() + buf_len, buf_len))) Err(Error::illegal_state(format!("Stored buf_len is larger than the shared map! Shared data corrupted? Expected {shmem_size} bytes max, but got {} (buf_len {buf_len})", size_of::<StateShMemContent>() + buf_len)))
} else { } else {
Ok(buf_len) Ok(buf_len)
} }
@ -270,7 +270,7 @@ mod tests {
assert!(state_restorer.has_content()); assert!(state_restorer.has_content());
let restored = state_restorer.restore::<String>().unwrap().unwrap(); let restored = state_restorer.restore::<String>().unwrap().unwrap();
println!("Restored {}", restored); println!("Restored {restored}");
assert_eq!(restored, "hello world"); assert_eq!(restored, "hello world");
assert!(!state_restorer.content().is_disk); assert!(!state_restorer.content().is_disk);

View File

@ -477,11 +477,11 @@ pub fn test_macros() {
let mut t = tuple_list!(1, "a"); let mut t = tuple_list!(1, "a");
tuple_for_each!(f1, std::fmt::Display, t, |x| { tuple_for_each!(f1, std::fmt::Display, t, |x| {
println!("{}", x); println!("{x}");
}); });
tuple_for_each_mut!(f2, std::fmt::Display, t, |x| { tuple_for_each_mut!(f2, std::fmt::Display, t, |x| {
println!("{}", x); println!("{x}");
}); });
} }

View File

@ -43,7 +43,7 @@ where
#[inline] #[inline]
fn replace(&mut self, idx: usize, testcase: Testcase<I>) -> Result<Testcase<I>, Error> { fn replace(&mut self, idx: usize, testcase: Testcase<I>) -> Result<Testcase<I>, Error> {
if idx >= self.entries.len() { if idx >= self.entries.len() {
return Err(Error::key_not_found(format!("Index {} out of bounds", idx))); return Err(Error::key_not_found(format!("Index {idx} out of bounds")));
} }
Ok(self.entries[idx].replace(testcase)) Ok(self.entries[idx].replace(testcase))
} }

View File

@ -76,7 +76,7 @@ where
#[inline] #[inline]
fn replace(&mut self, idx: usize, mut testcase: Testcase<I>) -> Result<Testcase<I>, Error> { fn replace(&mut self, idx: usize, mut testcase: Testcase<I>) -> Result<Testcase<I>, Error> {
if idx >= self.entries.len() { if idx >= self.entries.len() {
return Err(Error::key_not_found(format!("Index {} out of bounds", idx))); return Err(Error::key_not_found(format!("Index {idx} out of bounds")));
} }
self.save_testcase(&mut testcase)?; self.save_testcase(&mut testcase)?;
let previous = self.entries[idx].replace(testcase); let previous = self.entries[idx].replace(testcase);
@ -164,7 +164,7 @@ where
let mut ctr = 2; let mut ctr = 2;
let filename = loop { let filename = loop {
let lockfile = format!(".{}.lafl_lock", file); let lockfile = format!(".{file}.lafl_lock");
// try to create lockfile. // try to create lockfile.
if OpenOptions::new() if OpenOptions::new()
@ -176,7 +176,7 @@ where
break self.dir_path.join(file); break self.dir_path.join(file);
} }
file = format!("{}-{}", &file_orig, ctr); file = format!("{}-{ctr}", &file_orig);
ctr += 1; ctr += 1;
}; };

View File

@ -233,7 +233,7 @@ where
let (_, _) = (severity_level, message); let (_, _) = (severity_level, message);
// TODO rely on Monitor // TODO rely on Monitor
#[cfg(feature = "std")] #[cfg(feature = "std")]
println!("[LOG {}]: {}", severity_level, message); println!("[LOG {severity_level}]: {message}");
Ok(BrokerEventResult::Handled) Ok(BrokerEventResult::Handled)
} }
Event::CustomBuf { .. } => Ok(BrokerEventResult::Forward), Event::CustomBuf { .. } => Ok(BrokerEventResult::Forward),
@ -413,7 +413,7 @@ where
}; };
#[cfg(feature = "std")] #[cfg(feature = "std")]
if let Some(item) = _res.1 { if let Some(item) = _res.1 {
println!("Added received Testcase as item #{}", item); println!("Added received Testcase as item #{item}");
} }
Ok(()) Ok(())
} }
@ -878,7 +878,7 @@ where
if let Some(core_id) = core_id { if let Some(core_id) = core_id {
let core_id: CoreId = core_id; let core_id: CoreId = core_id;
println!("Setting core affinity to {:?}", core_id); println!("Setting core affinity to {core_id:?}");
core_id.set_affinity()?; core_id.set_affinity()?;
} }
@ -894,7 +894,7 @@ where
let mut ctr: u64 = 0; let mut ctr: u64 = 0;
// Client->parent loop // Client->parent loop
loop { loop {
println!("Spawning next client (id {})", ctr); println!("Spawning next client (id {ctr})");
// On Unix, we fork // On Unix, we fork
#[cfg(all(unix, feature = "fork"))] #[cfg(all(unix, feature = "fork"))]
@ -930,7 +930,7 @@ where
} }
// Storing state in the last round did not work // Storing state in the last round did not work
panic!("Fuzzer-respawner: Storing state in crashed fuzzer instance did not work, no point to spawn the next client! This can happen if the child calls `exit()`, in that case make sure it uses `abort()`, if it got killed unrecoverable (OOM), or if there is a bug in the fuzzer itself. (Child exited with: {})", child_status); panic!("Fuzzer-respawner: Storing state in crashed fuzzer instance did not work, no point to spawn the next client! This can happen if the child calls `exit()`, in that case make sure it uses `abort()`, if it got killed unrecoverable (OOM), or if there is a bug in the fuzzer itself. (Child exited with: {child_status})");
} }
ctr = ctr.wrapping_add(1); ctr = ctr.wrapping_add(1);

View File

@ -237,7 +237,7 @@ where
} => { } => {
let (_, _) = (message, severity_level); let (_, _) = (message, severity_level);
#[cfg(feature = "std")] #[cfg(feature = "std")]
println!("[LOG {}]: {}", severity_level, message); println!("[LOG {severity_level}]: {message}");
Ok(BrokerEventResult::Handled) Ok(BrokerEventResult::Handled)
} }
Event::CustomBuf { .. } => Ok(BrokerEventResult::Forward), Event::CustomBuf { .. } => Ok(BrokerEventResult::Forward),
@ -404,7 +404,7 @@ where
let mut ctr: u64 = 0; let mut ctr: u64 = 0;
// Client->parent loop // Client->parent loop
loop { loop {
println!("Spawning next client (id {})", ctr); println!("Spawning next client (id {ctr})");
// On Unix, we fork // On Unix, we fork
#[cfg(all(unix, feature = "fork"))] #[cfg(all(unix, feature = "fork"))]
@ -440,7 +440,7 @@ where
} }
// Storing state in the last round did not work // Storing state in the last round did not work
panic!("Fuzzer-respawner: Storing state in crashed fuzzer instance did not work, no point to spawn the next client! This can happen if the child calls `exit()`, in that case make sure it uses `abort()`, if it got killed unrecoverable (OOM), or if there is a bug in the fuzzer itself. (Child exited with: {})", child_status); panic!("Fuzzer-respawner: Storing state in crashed fuzzer instance did not work, no point to spawn the next client! This can happen if the child calls `exit()`, in that case make sure it uses `abort()`, if it got killed unrecoverable (OOM), or if there is a bug in the fuzzer itself. (Child exited with: {child_status})");
} }
ctr = ctr.wrapping_add(1); ctr = ctr.wrapping_add(1);

View File

@ -673,7 +673,7 @@ mod tests {
#[cfg(unix)] #[cfg(unix)]
fn test_builder() { fn test_builder() {
let mut mgr = SimpleEventManager::<BytesInput, _, ()>::new(SimpleMonitor::new(|status| { let mut mgr = SimpleEventManager::<BytesInput, _, ()>::new(SimpleMonitor::new(|status| {
println!("{}", status); println!("{status}");
})); }));
let mut executor = CommandExecutor::builder(); let mut executor = CommandExecutor::builder();
@ -699,7 +699,7 @@ mod tests {
use alloc::string::ToString; use alloc::string::ToString;
let mut mgr = SimpleEventManager::<BytesInput, _, ()>::new(SimpleMonitor::new(|status| { let mut mgr = SimpleEventManager::<BytesInput, _, ()>::new(SimpleMonitor::new(|status| {
println!("{}", status); println!("{status}");
})); }));
let mut executor = let mut executor =

View File

@ -766,7 +766,7 @@ mod unix_signal_handler {
as *mut libc::c_void as *mut ucontext_t); as *mut libc::c_void as *mut ucontext_t);
#[cfg(feature = "std")] #[cfg(feature = "std")]
eprintln!("Crashed with {}", signal); eprintln!("Crashed with {signal}");
if data.is_valid() { if data.is_valid() {
let executor = data.executor_mut::<E>(); let executor = data.executor_mut::<E>();
// disarms timeout in case of TimeoutExecutor // disarms timeout in case of TimeoutExecutor
@ -1609,10 +1609,10 @@ where
// we can't do this from the parent, timerid is unique to each process. // 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(), addr_of_mut!(timerid));
println!("Set timer! {:#?} {:#?}", self.itimerspec, timerid); println!("Set timer! {:#?} {timerid:#?}", self.itimerspec);
let v = let v =
libc::timer_settime(timerid, 0, addr_of_mut!(self.itimerspec), null_mut()); libc::timer_settime(timerid, 0, addr_of_mut!(self.itimerspec), null_mut());
println!("{:#?} {}", v, nix::errno::errno()); println!("{v:#?} {}", nix::errno::errno());
(self.harness_fn)(input); (self.harness_fn)(input);
self.observers self.observers
@ -1629,7 +1629,7 @@ where
self.shmem_provider.post_fork(false)?; self.shmem_provider.post_fork(false)?;
let res = waitpid(child, None)?; let res = waitpid(child, None)?;
println!("{:#?}", res); println!("{res:#?}");
match res { match res {
WaitStatus::Signaled(_, signal, _) => match signal { WaitStatus::Signaled(_, signal, _) => match signal {
nix::sys::signal::Signal::SIGALRM nix::sys::signal::Signal::SIGALRM

View File

@ -138,7 +138,7 @@ where
OT: ObserversTuple<I, S> + MatchName, OT: ObserversTuple<I, S> + MatchName,
{ {
fn err(name: &str) -> Error { fn err(name: &str) -> Error {
Error::illegal_argument(format!("DiffFeedback: observer {} not found", name)) Error::illegal_argument(format!("DiffFeedback: observer {name} not found"))
} }
let o1: &O1 = observers let o1: &O1 = observers

View File

@ -74,9 +74,10 @@ where
impl InputDecoder for TokenInputEncoderDecoder { impl InputDecoder for TokenInputEncoderDecoder {
fn decode(&self, input: &EncodedInput, bytes: &mut Vec<u8>) -> Result<(), Error> { fn decode(&self, input: &EncodedInput, bytes: &mut Vec<u8>) -> Result<(), Error> {
for id in input.codes() { for id in input.codes() {
let tok = self.id_table.get(&(id % self.next_id)).ok_or_else(|| { let tok = self
Error::illegal_state(format!("Id {} not in the decoder table", id)) .id_table
})?; .get(&(id % self.next_id))
.ok_or_else(|| Error::illegal_state(format!("Id {id} not in the decoder table")))?;
bytes.extend_from_slice(tok.as_bytes()); bytes.extend_from_slice(tok.as_bytes());
bytes.push(b' '); bytes.push(b' ');
} }

View File

@ -33,7 +33,7 @@ impl Input for NautilusInput {
hasher.write(term.symbol.as_bytes()); hasher.write(term.symbol.as_bytes());
} }
format!("{:016x}", hasher.finish())*/ format!("{:016x}", hasher.finish())*/
format!("id:{}", idx) format!("id:{idx}")
} }
} }

View File

@ -53,7 +53,6 @@ Welcome to `LibAFL`
test, test,
deny( deny(
bad_style, bad_style,
const_err,
dead_code, dead_code,
improper_ctypes, improper_ctypes,
non_shorthand_field_patterns, non_shorthand_field_patterns,
@ -138,9 +137,10 @@ impl ErrorBacktrace {
#[cfg(feature = "errors_backtrace")] #[cfg(feature = "errors_backtrace")]
fn display_error_backtrace(f: &mut fmt::Formatter, err: &ErrorBacktrace) -> fmt::Result { fn display_error_backtrace(f: &mut fmt::Formatter, err: &ErrorBacktrace) -> fmt::Result {
write!(f, "\nBacktrace: {:?}", err) write!(f, "\nBacktrace: {err:?}")
} }
#[cfg(not(feature = "errors_backtrace"))] #[cfg(not(feature = "errors_backtrace"))]
#[allow(clippy::unnecessary_wraps)]
fn display_error_backtrace(_f: &mut fmt::Formatter, _err: &ErrorBacktrace) -> fmt::Result { fn display_error_backtrace(_f: &mut fmt::Formatter, _err: &ErrorBacktrace) -> fmt::Result {
fmt::Result::Ok(()) fmt::Result::Ok(())
} }
@ -343,7 +343,7 @@ impl fmt::Display for Error {
/// Stringify the postcard serializer error /// Stringify the postcard serializer error
impl From<postcard::Error> for Error { impl From<postcard::Error> for Error {
fn from(err: postcard::Error) -> Self { fn from(err: postcard::Error) -> Self {
Self::serialize(format!("{:?}", err)) Self::serialize(format!("{err:?}"))
} }
} }
@ -351,14 +351,14 @@ impl From<postcard::Error> for Error {
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl From<serde_json::Error> for Error { impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Self { fn from(err: serde_json::Error) -> Self {
Self::serialize(format!("{:?}", err)) Self::serialize(format!("{err:?}"))
} }
} }
#[cfg(all(unix, feature = "std"))] #[cfg(all(unix, feature = "std"))]
impl From<nix::Error> for Error { impl From<nix::Error> for Error {
fn from(err: nix::Error) -> Self { fn from(err: nix::Error) -> Self {
Self::unknown(format!("Unix error: {:?}", err)) Self::unknown(format!("Unix error: {err:?}"))
} }
} }
@ -372,32 +372,32 @@ impl From<io::Error> for Error {
impl From<FromUtf8Error> for Error { impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Self { fn from(err: FromUtf8Error) -> Self {
Self::unknown(format!("Could not convert byte / utf-8: {:?}", err)) Self::unknown(format!("Could not convert byte / utf-8: {err:?}"))
} }
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl From<VarError> for Error { impl From<VarError> for Error {
fn from(err: VarError) -> Self { fn from(err: VarError) -> Self {
Self::empty(format!("Could not get env var: {:?}", err)) Self::empty(format!("Could not get env var: {err:?}"))
} }
} }
impl From<ParseIntError> for Error { impl From<ParseIntError> for Error {
fn from(err: ParseIntError) -> Self { fn from(err: ParseIntError) -> Self {
Self::unknown(format!("Failed to parse Int: {:?}", err)) Self::unknown(format!("Failed to parse Int: {err:?}"))
} }
} }
impl From<TryFromIntError> for Error { impl From<TryFromIntError> for Error {
fn from(err: TryFromIntError) -> Self { fn from(err: TryFromIntError) -> Self {
Self::illegal_state(format!("Expected conversion failed: {:?}", err)) Self::illegal_state(format!("Expected conversion failed: {err:?}"))
} }
} }
impl From<TryFromSliceError> for Error { impl From<TryFromSliceError> for Error {
fn from(err: TryFromSliceError) -> Self { fn from(err: TryFromSliceError) -> Self {
Self::illegal_argument(format!("Could not convert slice: {:?}", err)) Self::illegal_argument(format!("Could not convert slice: {err:?}"))
} }
} }
@ -418,7 +418,7 @@ impl From<pyo3::PyErr> for Error {
) { ) {
Self::shutting_down() Self::shutting_down()
} else { } else {
Self::illegal_state(format!("Python exception: {:?}", err)) Self::illegal_state(format!("Python exception: {err:?}"))
} }
}) })
} }
@ -487,7 +487,7 @@ mod tests {
.unwrap(); .unwrap();
let monitor = SimpleMonitor::new(|s| { let monitor = SimpleMonitor::new(|s| {
println!("{}", s); println!("{s}");
}); });
let mut event_manager = SimpleEventManager::new(monitor); let mut event_manager = SimpleEventManager::new(monitor);
@ -510,7 +510,7 @@ mod tests {
for i in 0..1000 { for i in 0..1000 {
fuzzer fuzzer
.fuzz_one(&mut stages, &mut executor, &mut state, &mut event_manager) .fuzz_one(&mut stages, &mut executor, &mut state, &mut event_manager)
.unwrap_or_else(|_| panic!("Error in iter {}", i)); .unwrap_or_else(|_| panic!("Error in iter {i}"));
} }
let state_serialized = postcard::to_allocvec(&state).unwrap(); let state_serialized = postcard::to_allocvec(&state).unwrap();

View File

@ -99,7 +99,7 @@ exec_sec = {}
.map(|c| if c.is_whitespace() { '_' } else { c }) .map(|c| if c.is_whitespace() { '_' } else { c })
.filter(|c| c.is_alphanumeric() || *c == '_') .filter(|c| c.is_alphanumeric() || *c == '_')
.collect(); .collect();
writeln!(&mut file, "{} = \"{}\"", k, val) writeln!(&mut file, "{k} = \"{val}\"")
.expect("Failed to write to the TOML file"); .expect("Failed to write to the TOML file");
} }
} }
@ -207,7 +207,7 @@ where
"exec_sec": self.base.execs_per_sec(), "exec_sec": self.base.execs_per_sec(),
"clients": &self.client_stats()[1..] "clients": &self.client_stats()[1..]
}); });
writeln!(&file, "{}", line).expect("Unable to write JSON to file"); writeln!(&file, "{line}").expect("Unable to write JSON to file");
} }
self.base.display(event_msg, sender_id); self.base.display(event_msg, sender_id);
} }

View File

@ -39,14 +39,14 @@ pub enum UserStats {
impl fmt::Display for UserStats { impl fmt::Display for UserStats {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
UserStats::Number(n) => write!(f, "{}", n), UserStats::Number(n) => write!(f, "{n}"),
UserStats::Float(n) => write!(f, "{}", n), UserStats::Float(n) => write!(f, "{n}"),
UserStats::String(s) => write!(f, "{}", s), UserStats::String(s) => write!(f, "{s}"),
UserStats::Ratio(a, b) => { UserStats::Ratio(a, b) => {
if *b == 0 { if *b == 0 {
write!(f, "{}/{}", a, b) write!(f, "{a}/{b}")
} else { } else {
write!(f, "{}/{} ({}%)", a, b, a * 100 / b) write!(f, "{a}/{b} ({}%)", a * 100 / b)
} }
} }
} }
@ -513,7 +513,7 @@ impl From<usize> for PerfFeature {
7 => PerfFeature::PostExecObservers, 7 => PerfFeature::PostExecObservers,
8 => PerfFeature::GetFeedbackInterestingAll, 8 => PerfFeature::GetFeedbackInterestingAll,
9 => PerfFeature::GetObjectivesInterestingAll, 9 => PerfFeature::GetObjectivesInterestingAll,
_ => panic!("Unknown PerfFeature: {}", val), _ => panic!("Unknown PerfFeature: {val}"),
} }
} }
} }
@ -773,7 +773,7 @@ impl core::fmt::Display for ClientPerfMonitor {
// Make sure we only iterate over used stages // Make sure we only iterate over used stages
for (stage_index, features) in self.used_stages() { for (stage_index, features) in self.used_stages() {
// Write the stage header // Write the stage header
writeln!(f, " Stage {}:", stage_index)?; writeln!(f, " Stage {stage_index}:")?;
for (feature_index, feature) in features.iter().enumerate() { for (feature_index, feature) in features.iter().enumerate() {
// Calculate this current stage's percentage // Calculate this current stage's percentage
@ -791,7 +791,7 @@ impl core::fmt::Display for ClientPerfMonitor {
let feature: PerfFeature = feature_index.into(); let feature: PerfFeature = feature_index.into();
// Write the percentage for this feature // Write the percentage for this feature
writeln!(f, " {:6.4}: {:?}", feature_percent, feature)?; writeln!(f, " {feature_percent:6.4}: {feature:?}")?;
} }
} }
@ -810,10 +810,10 @@ impl core::fmt::Display for ClientPerfMonitor {
other_percent -= feedback_percent; other_percent -= feedback_percent;
// Write the percentage for this feedback // Write the percentage for this feedback
writeln!(f, " {:6.4}: {}", feedback_percent, feedback_name)?; writeln!(f, " {feedback_percent:6.4}: {feedback_name}")?;
} }
write!(f, " {:6.4}: Not Measured", other_percent)?; write!(f, " {other_percent:6.4}: Not Measured")?;
Ok(()) Ok(())
} }

View File

@ -41,13 +41,13 @@ where
} }
fn display(&mut self, event_msg: String, sender_id: u32) { fn display(&mut self, event_msg: String, sender_id: u32) {
let sender = format!("#{}", sender_id); let sender = format!("#{sender_id}");
let pad = if event_msg.len() + sender.len() < 13 { let pad = if event_msg.len() + sender.len() < 13 {
" ".repeat(13 - event_msg.len() - sender.len()) " ".repeat(13 - event_msg.len() - sender.len())
} else { } else {
String::new() String::new()
}; };
let head = format!("{}{} {}", event_msg, pad, sender); let head = format!("{event_msg}{pad} {sender}");
let global_fmt = format!( let global_fmt = format!(
"[{}] (GLOBAL) run time: {}, clients: {}, corpus: {}, objectives: {}, executions: {}, exec/sec: {}", "[{}] (GLOBAL) run time: {}, clients: {}, corpus: {}, objectives: {}, executions: {}, exec/sec: {}",
head, head,
@ -70,7 +70,7 @@ where
pad, client.corpus_size, client.objective_size, client.executions, exec_sec pad, client.corpus_size, client.objective_size, client.executions, exec_sec
); );
for (key, val) in &client.user_monitor { for (key, val) in &client.user_monitor {
write!(fmt, ", {}: {}", key, val).unwrap(); write!(fmt, ", {key}: {val}").unwrap();
} }
(self.print_fn)(fmt); (self.print_fn)(fmt);

View File

@ -136,7 +136,7 @@ impl PerfTuiContext {
// Get the actual feature from the feature index for printing its name // Get the actual feature from the feature index for printing its name
let feature: PerfFeature = feature_index.into(); let feature: PerfFeature = feature_index.into();
features_percentages.push((format!("{:?}", feature), feature_percent)); features_percentages.push((format!("{feature:?}"), feature_percent));
} }
self.stages.push(features_percentages); self.stages.push(features_percentages);
@ -276,19 +276,19 @@ impl Monitor for TuiMonitor {
let client = self.client_stats_mut_for(sender_id); let client = self.client_stats_mut_for(sender_id);
let exec_sec = client.execs_per_sec(cur_time); let exec_sec = client.execs_per_sec(cur_time);
let sender = format!("#{}", sender_id); let sender = format!("#{sender_id}");
let pad = if event_msg.len() + sender.len() < 13 { let pad = if event_msg.len() + sender.len() < 13 {
" ".repeat(13 - event_msg.len() - sender.len()) " ".repeat(13 - event_msg.len() - sender.len())
} else { } else {
String::new() String::new()
}; };
let head = format!("{}{} {}", event_msg, pad, sender); let head = format!("{event_msg}{pad} {sender}");
let mut fmt = format!( let mut fmt = format!(
"[{}] corpus: {}, objectives: {}, executions: {}, exec/sec: {}", "[{}] corpus: {}, objectives: {}, executions: {}, exec/sec: {}",
head, client.corpus_size, client.objective_size, client.executions, exec_sec head, client.corpus_size, client.objective_size, client.executions, exec_sec
); );
for (key, val) in &client.user_monitor { for (key, val) in &client.user_monitor {
write!(fmt, ", {}: {}", key, val).unwrap(); write!(fmt, ", {key}: {val}").unwrap();
} }
{ {

View File

@ -305,12 +305,12 @@ impl TuiUI {
.bounds([min_y as f64, max_y as f64]) .bounds([min_y as f64, max_y as f64])
.labels(vec![ .labels(vec![
Span::styled( Span::styled(
format!("{}", min_y), format!("{min_y}"),
Style::default().add_modifier(Modifier::BOLD), Style::default().add_modifier(Modifier::BOLD),
), ),
Span::raw(format!("{}", (max_y - min_y) / 2)), Span::raw(format!("{}", (max_y - min_y) / 2)),
Span::styled( Span::styled(
format!("{}", max_y), format!("{max_y}"),
Style::default().add_modifier(Modifier::BOLD), Style::default().add_modifier(Modifier::BOLD),
), ),
]), ]),
@ -452,7 +452,7 @@ impl TuiUI {
])); ]));
for i in 0..client.stages.len() { for i in 0..client.stages.len() {
items.push(Row::new(vec![ items.push(Row::new(vec![
Cell::from(Span::raw(format!("stage {}", i))), Cell::from(Span::raw(format!("stage {i}"))),
Cell::from(Span::raw("")), Cell::from(Span::raw("")),
])); ]));

View File

@ -216,11 +216,7 @@ impl MOpt {
* (self.g_best[i] - self.x_now[swarm][i]); * (self.g_best[i] - self.x_now[swarm][i]);
self.x_now[swarm][i] += self.v_now[swarm][i]; self.x_now[swarm][i] += self.v_now[swarm][i];
if self.x_now[swarm][i] > V_MAX { self.x_now[swarm][i] = self.x_now[swarm][i].clamp(V_MIN, V_MAX);
self.x_now[swarm][i] = V_MAX;
} else if self.x_now[swarm][i] < V_MIN {
self.x_now[swarm][i] = V_MIN;
}
x_sum += self.x_now[swarm][i]; x_sum += self.x_now[swarm][i];
} }
@ -287,11 +283,8 @@ impl MOpt {
* (self.g_best[i] - self.x_now[swarm][i]); * (self.g_best[i] - self.x_now[swarm][i]);
self.x_now[swarm][i] += self.v_now[swarm][i]; self.x_now[swarm][i] += self.v_now[swarm][i];
if self.x_now[swarm][i] > V_MAX { self.x_now[swarm][i] = self.x_now[swarm][i].clamp(V_MIN, V_MAX);
self.x_now[swarm][i] = V_MAX;
} else if self.x_now[swarm][i] < V_MIN {
self.x_now[swarm][i] = V_MIN;
}
x_sum += self.x_now[swarm][i]; x_sum += self.x_now[swarm][i];
} }

View File

@ -171,16 +171,16 @@ impl Tokens {
} }
let pos_quote = match line.find('\"') { let pos_quote = match line.find('\"') {
Some(x) => x, Some(x) => x,
None => return Err(Error::illegal_argument(format!("Illegal line: {}", line))), None => return Err(Error::illegal_argument(format!("Illegal line: {line}"))),
}; };
if line.chars().nth(line.len() - 1) != Some('"') { if line.chars().nth(line.len() - 1) != Some('"') {
return Err(Error::illegal_argument(format!("Illegal line: {}", line))); return Err(Error::illegal_argument(format!("Illegal line: {line}")));
} }
// extract item // extract item
let item = match line.get(pos_quote + 1..line.len() - 1) { let item = match line.get(pos_quote + 1..line.len() - 1) {
Some(x) => x, Some(x) => x,
None => return Err(Error::illegal_argument(format!("Illegal line: {}", line))), None => return Err(Error::illegal_argument(format!("Illegal line: {line}"))),
}; };
if item.is_empty() { if item.is_empty() {
continue; continue;

View File

@ -1082,7 +1082,7 @@ mod tests {
StdMapObserver::new("map", unsafe { &mut MAP }) StdMapObserver::new("map", unsafe { &mut MAP })
); );
let vec = postcard::to_allocvec(&obv).unwrap(); let vec = postcard::to_allocvec(&obv).unwrap();
println!("{:?}", vec); println!("{vec:?}");
let obv2: tuple_list_type!(TimeObserver, StdMapObserver<u32>) = let obv2: tuple_list_type!(TimeObserver, StdMapObserver<u32>) =
postcard::from_bytes(&vec).unwrap(); postcard::from_bytes(&vec).unwrap();
assert_eq!(obv.0.name(), obv2.0.name()); assert_eq!(obv.0.name(), obv2.0.name());

View File

@ -193,7 +193,7 @@ impl ASANBacktraceObserver {
/// read ASAN output from the log file and parse it. /// read ASAN output from the log file and parse it.
pub fn parse_asan_output_from_asan_log_file(&mut self, pid: i32) -> Result<(), Error> { pub fn parse_asan_output_from_asan_log_file(&mut self, pid: i32) -> Result<(), Error> {
let log_path = format!("{}.{}", ASAN_LOG_PATH, pid); let log_path = format!("{ASAN_LOG_PATH}.{pid}");
let mut asan_output = File::open(Path::new(&log_path))?; let mut asan_output = File::open(Path::new(&log_path))?;
let mut buf = String::new(); let mut buf = String::new();

View File

@ -512,7 +512,7 @@ where
self, self,
Event::Log { Event::Log {
severity_level: LogSeverity::Debug, severity_level: LogSeverity::Debug,
message: format!("Loaded {} over {} initial testcases", added, num), message: format!("Loaded {added} over {num} initial testcases"),
phantom: PhantomData, phantom: PhantomData,
}, },
)?; )?;

View File

@ -33,9 +33,9 @@ fn find_llvm_config_brew() -> Result<PathBuf, String> {
if brew_cellar_location.is_empty() { if brew_cellar_location.is_empty() {
return Err("Empty return from brew --cellar".to_string()); return Err("Empty return from brew --cellar".to_string());
} }
let cellar_glob = format!("{}/llvm/*/bin/llvm-config", brew_cellar_location); let cellar_glob = format!("{brew_cellar_location}/llvm/*/bin/llvm-config");
let glob_results = glob(&cellar_glob).unwrap_or_else(|err| { let glob_results = glob(&cellar_glob).unwrap_or_else(|err| {
panic!("Could not read glob path {} ({})", &cellar_glob, err); panic!("Could not read glob path {} ({err})", &cellar_glob);
}); });
match glob_results.last() { match glob_results.last() {
Some(path) => Ok(path.unwrap()), Some(path) => Ok(path.unwrap()),
@ -45,7 +45,7 @@ fn find_llvm_config_brew() -> Result<PathBuf, String> {
)), )),
} }
} }
Err(err) => Err(format!("Could not execute brew --cellar: {:?}", err)), Err(err) => Err(format!("Could not execute brew --cellar: {err:?}")),
} }
} }
@ -59,13 +59,13 @@ fn find_llvm_config() -> Result<String, String> {
match find_llvm_config_brew() { match find_llvm_config_brew() {
Ok(llvm_dir) => return Ok(llvm_dir.to_str().unwrap().to_string()), Ok(llvm_dir) => return Ok(llvm_dir.to_str().unwrap().to_string()),
Err(err) => { Err(err) => {
println!("cargo:warning={}", err); println!("cargo:warning={err}");
} }
}; };
#[cfg(not(target_vendor = "apple"))] #[cfg(not(target_vendor = "apple"))]
for version in (LLVM_VERSION_MIN..=LLVM_VERSION_MAX).rev() { for version in (LLVM_VERSION_MIN..=LLVM_VERSION_MAX).rev() {
let llvm_config_name: String = format!("llvm-config-{}", version); let llvm_config_name: String = format!("llvm-config-{version}");
if which(&llvm_config_name).is_ok() { if which(&llvm_config_name).is_ok() {
return Ok(llvm_config_name); return Ok(llvm_config_name);
} }
@ -85,7 +85,7 @@ fn exec_llvm_config(args: &[&str]) -> String {
.expect("Unexpected llvm-config output") .expect("Unexpected llvm-config output")
.trim() .trim()
.to_string(), .to_string(),
Err(e) => panic!("Could not execute llvm-config: {}", e), Err(e) => panic!("Could not execute llvm-config: {e}"),
} }
} }
@ -122,7 +122,7 @@ fn build_pass(
let dot_offset = src_file.rfind('.').unwrap(); let dot_offset = src_file.rfind('.').unwrap();
let src_stub = &src_file[..dot_offset]; let src_stub = &src_file[..dot_offset];
println!("cargo:rerun-if-changed=src/{}", src_file); println!("cargo:rerun-if-changed=src/{src_file}");
if cfg!(unix) { if cfg!(unix) {
assert!(Command::new(bindir_path.join("clang++")) assert!(Command::new(bindir_path.join("clang++"))
.arg("-v") .arg("-v")
@ -130,12 +130,12 @@ fn build_pass(
.arg(src_dir.join(src_file)) .arg(src_dir.join(src_file))
.args(ldflags) .args(ldflags)
.arg("-o") .arg("-o")
.arg(out_dir.join(format!("{}.{}", src_stub, dll_extension()))) .arg(out_dir.join(format!("{src_stub}.{}", dll_extension())))
.status() .status()
.unwrap_or_else(|_| panic!("Failed to compile {}", src_file)) .unwrap_or_else(|_| panic!("Failed to compile {src_file}"))
.success()); .success());
} else if cfg!(windows) { } else if cfg!(windows) {
println!("{:?}", cxxflags); println!("{cxxflags:?}");
assert!(Command::new(bindir_path.join("clang-cl")) assert!(Command::new(bindir_path.join("clang-cl"))
.arg("-v") .arg("-v")
.args(cxxflags) .args(cxxflags)
@ -145,11 +145,11 @@ fn build_pass(
.arg(format!( .arg(format!(
"/OUT:{}", "/OUT:{}",
out_dir out_dir
.join(format!("{}.{}", src_stub, dll_extension())) .join(format!("{src_stub}.{}", dll_extension()))
.display() .display()
)) ))
.status() .status()
.unwrap_or_else(|_| panic!("Failed to compile {}", src_file)) .unwrap_or_else(|_| panic!("Failed to compile {src_file}"))
.success()); .success());
} }
} }
@ -197,12 +197,12 @@ pub const LIBAFL_CC_LLVM_VERSION: Option<usize> = None;
let edges_map_size: usize = option_env!("LIBAFL_EDGES_MAP_SIZE") let edges_map_size: usize = option_env!("LIBAFL_EDGES_MAP_SIZE")
.map_or(Ok(65536), str::parse) .map_or(Ok(65536), str::parse)
.expect("Could not parse LIBAFL_EDGES_MAP_SIZE"); .expect("Could not parse LIBAFL_EDGES_MAP_SIZE");
cxxflags.push(format!("-DLIBAFL_EDGES_MAP_SIZE={}", edges_map_size)); cxxflags.push(format!("-DLIBAFL_EDGES_MAP_SIZE={edges_map_size}"));
let acc_map_size: usize = option_env!("LIBAFL_ACCOUNTING_MAP_SIZE") let acc_map_size: usize = option_env!("LIBAFL_ACCOUNTING_MAP_SIZE")
.map_or(Ok(65536), str::parse) .map_or(Ok(65536), str::parse)
.expect("Could not parse LIBAFL_ACCOUNTING_MAP_SIZE"); .expect("Could not parse LIBAFL_ACCOUNTING_MAP_SIZE");
cxxflags.push(format!("-DLIBAFL_ACCOUNTING_MAP_SIZE={}", acc_map_size)); cxxflags.push(format!("-DLIBAFL_ACCOUNTING_MAP_SIZE={acc_map_size}"));
let llvm_version = find_llvm_version(); let llvm_version = find_llvm_version();

View File

@ -190,7 +190,7 @@ impl CompilerWrapper for ClangWrapper {
linking = false; linking = false;
new_args.push( new_args.push(
PathBuf::from(env!("OUT_DIR")) PathBuf::from(env!("OUT_DIR"))
.join(format!("{}no-link-rt.{}", LIB_PREFIX, LIB_EXT)) .join(format!("{LIB_PREFIX}no-link-rt.{LIB_EXT}"))
.into_os_string() .into_os_string()
.into_string() .into_string()
.unwrap(), .unwrap(),
@ -261,7 +261,7 @@ impl CompilerWrapper for ClangWrapper {
S: AsRef<str>, S: AsRef<str>,
{ {
let lib_file = dir let lib_file = dir
.join(format!("{}{}.{}", LIB_PREFIX, name.as_ref(), LIB_EXT)) .join(format!("{LIB_PREFIX}{}.{LIB_EXT}", name.as_ref()))
.into_os_string() .into_os_string()
.into_string() .into_string()
.unwrap(); .unwrap();
@ -278,7 +278,7 @@ impl CompilerWrapper for ClangWrapper {
.add_link_arg("-Wl,--no-whole-archive") .add_link_arg("-Wl,--no-whole-archive")
} }
} else { } else {
self.add_link_arg(format!("-Wl,-wholearchive:{}", lib_file)) self.add_link_arg(format!("-Wl,-wholearchive:{lib_file}"))
} }
} }
@ -469,7 +469,7 @@ mod tests {
.unwrap() .unwrap()
.run() .run()
{ {
println!("Ignored error {:?} - clang is probably not installed.", res); println!("Ignored error {res:?} - clang is probably not installed.");
} }
} }
} }

View File

@ -41,7 +41,6 @@
test, test,
deny( deny(
bad_style, bad_style,
const_err,
dead_code, dead_code,
improper_ctypes, improper_ctypes,
non_shorthand_field_patterns, non_shorthand_field_patterns,

View File

@ -187,7 +187,7 @@ fn write_symcc_runtime_bindings_file(out_path: &Path, cpp_bindings: &bindgen::Bi
) )
.unwrap(); .unwrap();
} }
writeln!(bindings_file, "{}", l).unwrap(); writeln!(bindings_file, "{l}").unwrap();
}); });
} }
@ -208,8 +208,8 @@ fn write_symcc_rename_header(rename_header_path: &Path, cpp_bindings: &bindgen::
.for_each(|val| { .for_each(|val| {
writeln!( writeln!(
rename_header_file, rename_header_file,
"#define {} {}{}", "#define {} {SYMCC_RUNTIME_FUNCTION_NAME_PREFIX}{}",
&val, SYMCC_RUNTIME_FUNCTION_NAME_PREFIX, &val &val, &val
) )
.unwrap(); .unwrap();
}); });
@ -245,12 +245,12 @@ fn link_with_cpp_stdlib() {
fn build_dep_check(tools: &[&str]) { fn build_dep_check(tools: &[&str]) {
for tool in tools { for tool in tools {
println!("Checking for build tool {}...", tool); println!("Checking for build tool {tool}...");
if let Ok(path) = which::which(tool) { if let Ok(path) = which::which(tool) {
println!("Found build tool {}", path.to_str().unwrap()); println!("Found build tool {}", path.to_str().unwrap());
} else { } else {
println!("ERROR: missing build tool {}", tool); println!("ERROR: missing build tool {tool}");
exit(1); exit(1);
}; };
} }

View File

@ -112,7 +112,7 @@ fn main() {
.enumerate() .enumerate()
.filter(|(_, &v)| v != 0) .filter(|(_, &v)| v != 0)
{ {
writeln!(f, "{}\t{}", index, count).expect("failed to write coverage file"); writeln!(f, "{index}\t{count}").expect("failed to write coverage file");
} }
} }
@ -125,7 +125,7 @@ fn main() {
if opt.plain_text { if opt.plain_text {
while let Some(message) = reader.next_message() { while let Some(message) = reader.next_message() {
if let Ok((id, message)) = message { if let Ok((id, message)) = message {
writeln!(output_file, "{}\t{:?}", id, message) writeln!(output_file, "{id}\t{message:?}")
.expect("failed to write to output file"); .expect("failed to write to output file");
} else { } else {
break; break;

View File

@ -42,7 +42,6 @@
test, test,
deny( deny(
bad_style, bad_style,
const_err,
dead_code, dead_code,
improper_ctypes, improper_ctypes,
non_shorthand_field_patterns, non_shorthand_field_patterns,

View File

@ -169,7 +169,7 @@ impl Allocator {
for (start, end) in &occupied_ranges { for (start, end) in &occupied_ranges {
if (shadow_start <= *end) && (*start <= shadow_end) { if (shadow_start <= *end) && (*start <= shadow_end) {
// println!("{:x} {:x}, {:x} {:x}",shadow_start,shadow_end,start,end); // println!("{:x} {:x}, {:x} {:x}",shadow_start,shadow_end,start,end);
println!("shadow_bit {:x} is not suitable", try_shadow_bit); println!("shadow_bit {try_shadow_bit:x} is not suitable");
break; break;
} }
} }
@ -195,7 +195,7 @@ impl Allocator {
} }
} }
println!("shadow_bit {:x} is suitable", shadow_bit); println!("shadow_bit {shadow_bit:x} is suitable");
assert!(shadow_bit != 0); assert!(shadow_bit != 0);
// attempt to pre-map the entire shadow-memory space // attempt to pre-map the entire shadow-memory space
@ -275,7 +275,7 @@ impl Allocator {
if size > self.options.max_allocation { if size > self.options.max_allocation {
#[allow(clippy::manual_assert)] #[allow(clippy::manual_assert)]
if self.options.max_allocation_panics { if self.options.max_allocation_panics {
panic!("ASAN: Allocation is too large: 0x{:x}", size); panic!("ASAN: Allocation is too large: 0x{size:x}");
} }
return std::ptr::null_mut(); return std::ptr::null_mut();
@ -310,7 +310,7 @@ impl Allocator {
) { ) {
Ok(mapping) => mapping as usize, Ok(mapping) => mapping as usize,
Err(err) => { Err(err) => {
println!("An error occurred while mapping memory: {:?}", err); println!("An error occurred while mapping memory: {err:?}");
return std::ptr::null_mut(); return std::ptr::null_mut();
} }
}; };

View File

@ -913,7 +913,7 @@ impl AsanRuntime {
.expect("Failed to disassmeble"); .expect("Failed to disassmeble");
let insn = instructions.as_ref().first().unwrap(); // This is the very instruction that has triggered fault let insn = instructions.as_ref().first().unwrap(); // This is the very instruction that has triggered fault
println!("{:#?}", insn); println!("{insn:#?}");
let operands = cs.insn_detail(insn).unwrap().arch_detail().operands(); let operands = cs.insn_detail(insn).unwrap().arch_detail().operands();
let mut access_type: Option<RegAccessType> = None; let mut access_type: Option<RegAccessType> = None;
@ -2564,7 +2564,7 @@ impl AsanRuntime {
.to_le_bytes(), .to_le_bytes(),
); );
} else { } else {
panic!("extender: {:?}, shift: {:?}", extender, shift); panic!("extender: {extender:?}, shift: {shift:?}");
} }
}; };
} }

View File

@ -176,8 +176,8 @@ impl AsanErrors {
} else { } else {
writeln!( writeln!(
output, output,
" at 0x{:x}, faulting address 0x{:x}", " at 0x{:x}, faulting address 0x{fault_address:x}",
error.pc, fault_address error.pc
) )
.unwrap(); .unwrap();
} }
@ -196,7 +196,7 @@ impl AsanErrors {
.set_color(ColorSpec::new().set_fg(Some(Color::Yellow))) .set_color(ColorSpec::new().set_fg(Some(Color::Yellow)))
.unwrap(); .unwrap();
} }
write!(output, "x{:02}: 0x{:016x} ", reg, error.registers[reg]).unwrap(); write!(output, "x{reg:02}: 0x{:016x} ", error.registers[reg]).unwrap();
output.reset().unwrap(); output.reset().unwrap();
if reg % 4 == 3 { if reg % 4 == 3 {
writeln!(output).unwrap(); writeln!(output).unwrap();
@ -220,7 +220,7 @@ impl AsanErrors {
.set_color(ColorSpec::new().set_fg(Some(Color::Yellow))) .set_color(ColorSpec::new().set_fg(Some(Color::Yellow)))
.unwrap(); .unwrap();
} }
write!(output, "{}: 0x{:016x} ", name, error.registers[reg]).unwrap(); write!(output, "{name}: 0x{:016x} ", error.registers[reg]).unwrap();
output.reset().unwrap(); output.reset().unwrap();
if reg % 4 == 3 { if reg % 4 == 3 {
writeln!(output).unwrap(); writeln!(output).unwrap();
@ -264,10 +264,10 @@ impl AsanErrors {
output output
.set_color(ColorSpec::new().set_fg(Some(Color::Red))) .set_color(ColorSpec::new().set_fg(Some(Color::Red)))
.unwrap(); .unwrap();
writeln!(output, "\t => {}", insn).unwrap(); writeln!(output, "\t => {insn}").unwrap();
output.reset().unwrap(); output.reset().unwrap();
} else { } else {
writeln!(output, "\t {}", insn).unwrap(); writeln!(output, "\t {insn}").unwrap();
} }
} }
backtrace_printer backtrace_printer
@ -332,7 +332,7 @@ impl AsanErrors {
) )
.unwrap(); .unwrap();
} else { } else {
writeln!(output, " at 0x{:x}", _pc).unwrap(); writeln!(output, " at 0x{_pc:x}").unwrap();
} }
#[allow(clippy::non_ascii_literal)] #[allow(clippy::non_ascii_literal)]
@ -344,7 +344,7 @@ impl AsanErrors {
.set_color(ColorSpec::new().set_fg(Some(Color::Red))) .set_color(ColorSpec::new().set_fg(Some(Color::Red)))
.unwrap(); .unwrap();
} }
write!(output, "x{:02}: 0x{:016x} ", reg, val).unwrap(); write!(output, "x{reg:02}: 0x{val:016x} ").unwrap();
output.reset().unwrap(); output.reset().unwrap();
if reg % 4 == 3 { if reg % 4 == 3 {
writeln!(output).unwrap(); writeln!(output).unwrap();
@ -358,7 +358,7 @@ impl AsanErrors {
backtrace_printer.print_trace(&backtrace, output).unwrap(); backtrace_printer.print_trace(&backtrace, output).unwrap();
} }
AsanError::DoubleFree((ptr, mut metadata, backtrace)) => { AsanError::DoubleFree((ptr, mut metadata, backtrace)) => {
writeln!(output, " of {:?}", ptr).unwrap(); writeln!(output, " of {ptr:?}").unwrap();
output.reset().unwrap(); output.reset().unwrap();
backtrace_printer.print_trace(&backtrace, output).unwrap(); backtrace_printer.print_trace(&backtrace, output).unwrap();
@ -389,12 +389,12 @@ impl AsanErrors {
} }
} }
AsanError::UnallocatedFree((ptr, backtrace)) => { AsanError::UnallocatedFree((ptr, backtrace)) => {
writeln!(output, " of {:#016x}", ptr).unwrap(); writeln!(output, " of {ptr:#016x}").unwrap();
output.reset().unwrap(); output.reset().unwrap();
backtrace_printer.print_trace(&backtrace, output).unwrap(); backtrace_printer.print_trace(&backtrace, output).unwrap();
} }
AsanError::Leak((ptr, mut metadata)) => { AsanError::Leak((ptr, mut metadata)) => {
writeln!(output, " of {:#016x}", ptr).unwrap(); writeln!(output, " of {ptr:#016x}").unwrap();
output.reset().unwrap(); output.reset().unwrap();
#[allow(clippy::non_ascii_literal)] #[allow(clippy::non_ascii_literal)]
@ -455,14 +455,14 @@ impl AsanErrors {
.set_color(ColorSpec::new().set_fg(Some(Color::Yellow))) .set_color(ColorSpec::new().set_fg(Some(Color::Yellow)))
.unwrap(); .unwrap();
} }
write!(output, "x{:02}: 0x{:016x} ", reg, val).unwrap(); write!(output, "x{reg:02}: 0x{val:016x} ").unwrap();
output.reset().unwrap(); output.reset().unwrap();
if reg % 4 == 3 { if reg % 4 == 3 {
writeln!(output).unwrap(); writeln!(output).unwrap();
} }
} }
#[cfg(target_arch = "aarch64")] #[cfg(target_arch = "aarch64")]
writeln!(output, "pc : 0x{:016x} ", pc).unwrap(); writeln!(output, "pc : 0x{pc:016x} ").unwrap();
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
for reg in 0..ASAN_SAVE_REGISTER_COUNT { for reg in 0..ASAN_SAVE_REGISTER_COUNT {
@ -488,7 +488,7 @@ impl AsanErrors {
} }
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
writeln!(output, "Rip: 0x{:016x}", pc).unwrap(); writeln!(output, "Rip: 0x{pc:016x}").unwrap();
#[allow(clippy::non_ascii_literal)] #[allow(clippy::non_ascii_literal)]
writeln!(output, "{:━^100}", " CODE ").unwrap(); writeln!(output, "{:━^100}", " CODE ").unwrap();
@ -524,10 +524,10 @@ impl AsanErrors {
output output
.set_color(ColorSpec::new().set_fg(Some(Color::Red))) .set_color(ColorSpec::new().set_fg(Some(Color::Red)))
.unwrap(); .unwrap();
writeln!(output, "\t => {}", insn).unwrap(); writeln!(output, "\t => {insn}").unwrap();
output.reset().unwrap(); output.reset().unwrap();
} else { } else {
writeln!(output, "\t {}", insn).unwrap(); writeln!(output, "\t {insn}").unwrap();
} }
} }
backtrace_printer.print_trace(&backtrace, output).unwrap(); backtrace_printer.print_trace(&backtrace, output).unwrap();

View File

@ -44,7 +44,6 @@ It can report coverage and, on supported architecutres, even reports memory acce
test, test,
deny( deny(
bad_style, bad_style,
const_err,
dead_code, dead_code,
improper_ctypes, improper_ctypes,
non_shorthand_field_patterns, non_shorthand_field_patterns,
@ -203,7 +202,7 @@ impl FridaOptions {
cmplog_cores = Cores::from_cmdline(value).ok(); cmplog_cores = Cores::from_cmdline(value).ok();
} }
_ => { _ => {
panic!("unknown FRIDA option: '{}'", option); panic!("unknown FRIDA option: '{option}'");
} }
} }
} // end of for loop } // end of for loop

View File

@ -7,7 +7,7 @@ const QEMU_REVISION: &str = "ebda58f3e94a82f769890814339295b467f16680";
fn build_dep_check(tools: &[&str]) { fn build_dep_check(tools: &[&str]) {
for tool in tools { for tool in tools {
which(tool).unwrap_or_else(|_| panic!("Build tool {} not found", tool)); which(tool).unwrap_or_else(|_| panic!("Build tool {tool} not found"));
} }
} }
@ -62,11 +62,11 @@ pub fn build() {
#[cfg(feature = "usermode")] #[cfg(feature = "usermode")]
let cross_cc = env::var("CROSS_CC").unwrap_or_else(|_| { let cross_cc = env::var("CROSS_CC").unwrap_or_else(|_| {
println!("cargo:warning=CROSS_CC is not set, default to cc (things can go wrong if the selected cpu target ({}) is not the host arch ({}))", cpu_target, env::consts::ARCH); println!("cargo:warning=CROSS_CC is not set, default to cc (things can go wrong if the selected cpu target ({cpu_target}) is not the host arch ({}))", env::consts::ARCH);
"cc".to_owned() "cc".to_owned()
}); });
println!("cargo:rustc-cfg=cpu_target=\"{}\"", cpu_target); println!("cargo:rustc-cfg=cpu_target=\"{cpu_target}\"");
// qemu-system-arm supports both big and little endian configurations and so // qemu-system-arm supports both big and little endian configurations and so
// therefore the "be" feature should ignored in this configuration. Also // therefore the "be" feature should ignored in this configuration. Also
@ -164,7 +164,7 @@ pub fn build() {
} }
#[cfg(feature = "usermode")] #[cfg(feature = "usermode")]
let output_lib = build_dir.join(&format!("libqemu-{}.so", cpu_target)); let output_lib = build_dir.join(&format!("libqemu-{cpu_target}.so"));
#[cfg(not(feature = "usermode"))] #[cfg(not(feature = "usermode"))]
let output_lib = build_dir.join(&format!("libqemu-system-{}.so", cpu_target)); let output_lib = build_dir.join(&format!("libqemu-system-{}.so", cpu_target));
@ -184,7 +184,7 @@ pub fn build() {
.current_dir(&build_dir) .current_dir(&build_dir)
//.arg("--as-static-lib") //.arg("--as-static-lib")
.arg("--as-shared-lib") .arg("--as-shared-lib")
.arg(&format!("--target-list={}-{}", cpu_target, target_suffix)) .arg(&format!("--target-list={cpu_target}-{target_suffix}"))
.args(["--disable-blobs", "--disable-bsd-user", "--disable-fdt"]) .args(["--disable-blobs", "--disable-bsd-user", "--disable-fdt"])
.status() .status()
.expect("Configure failed"); .expect("Configure failed");
@ -215,7 +215,7 @@ pub fn build() {
let mut objects = vec![]; let mut objects = vec![];
for dir in &[ for dir in &[
build_dir.join("libcommon.fa.p"), build_dir.join("libcommon.fa.p"),
build_dir.join(&format!("libqemu-{}-{}.fa.p", cpu_target, target_suffix)), build_dir.join(&format!("libqemu-{cpu_target}-{target_suffix}.fa.p")),
] { ] {
for path in fs::read_dir(dir).unwrap() { for path in fs::read_dir(dir).unwrap() {
let path = path.unwrap().path(); let path = path.unwrap().path();
@ -316,7 +316,7 @@ pub fn build() {
.status() .status()
.expect("Ar creation"); .expect("Ar creation");
println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-link-search=native={out_dir}");
println!("cargo:rustc-link-lib=static=qemu-partially-linked"); println!("cargo:rustc-link-lib=static=qemu-partially-linked");
#[cfg(not(feature = "usermode"))] #[cfg(not(feature = "usermode"))]

View File

@ -108,7 +108,7 @@ extern "C" fn asan_giovese_printaddr(_addr: u64) -> *const u8 {
#[no_mangle] #[no_mangle]
unsafe extern "C" fn asan_giovese_populate_context(ctx: *mut CallContext, _pc: u64) { unsafe extern "C" fn asan_giovese_populate_context(ctx: *mut CallContext, _pc: u64) {
let ctx = ctx.as_mut().unwrap(); let ctx = ctx.as_mut().unwrap();
ctx.tid = libc::gettid() as i32; ctx.tid = libc::gettid();
ctx.size = 0; ctx.size = 0;
} }

View File

@ -194,6 +194,8 @@ where
unsafe { unsafe {
MAX_EDGES_NUM = meta.current_id as usize; MAX_EDGES_NUM = meta.current_id as usize;
} }
// GuestAddress is u32 for 32 bit guests
#[allow(clippy::unnecessary_cast)]
Some(id as u64) Some(id as u64)
} }
} }
@ -229,6 +231,8 @@ where
return None; return None;
} }
} }
// GuestAddress is u32 for 32 bit guests
#[allow(clippy::unnecessary_cast)]
Some((hash_me(src as u64) ^ hash_me(dest as u64)) & (unsafe { EDGES_MAP_PTR_SIZE } as u64 - 1)) Some((hash_me(src as u64) ^ hash_me(dest as u64)) & (unsafe { EDGES_MAP_PTR_SIZE } as u64 - 1))
} }
@ -255,6 +259,8 @@ where
I: Input, I: Input,
QT: QemuHelperTuple<I, S>, QT: QemuHelperTuple<I, S>,
{ {
// GuestAddress is u32 for 32 bit guests
#[allow(clippy::unnecessary_cast)]
Some(pc as u64) Some(pc as u64)
} }
@ -267,6 +273,8 @@ where
I: Input, I: Input,
QT: QemuHelperTuple<I, S>, QT: QemuHelperTuple<I, S>,
{ {
// GuestAddress is u32 for 32 bit guests
#[allow(clippy::unnecessary_cast)]
Some(hash_me(pc as u64)) Some(hash_me(pc as u64))
} }

View File

@ -19,13 +19,13 @@ impl<'a> EasyElf<'a> {
let elf = { let elf = {
let mut binary_file = File::open(path)?; let mut binary_file = File::open(path)?;
binary_file.read_to_end(buffer)?; binary_file.read_to_end(buffer)?;
Elf::parse(buffer).map_err(|e| Error::unknown(format!("{}", e))) Elf::parse(buffer).map_err(|e| Error::unknown(format!("{e}")))
}?; }?;
Ok(Self { elf }) Ok(Self { elf })
} }
pub fn from_slice(buffer: &'a [u8]) -> Result<Self, Error> { pub fn from_slice(buffer: &'a [u8]) -> Result<Self, Error> {
let elf = Elf::parse(buffer).map_err(|e| Error::unknown(format!("{}", e)))?; let elf = Elf::parse(buffer).map_err(|e| Error::unknown(format!("{e}")))?;
Ok(Self { elf }) Ok(Self { elf })
} }

View File

@ -519,7 +519,7 @@ impl CPU {
let reg = reg.into(); let reg = reg.into();
let success = unsafe { libafl_qemu_write_reg(self.ptr, reg, addr_of!(val) as *const u8) }; let success = unsafe { libafl_qemu_write_reg(self.ptr, reg, addr_of!(val) as *const u8) };
if success == 0 { if success == 0 {
Err(format!("Failed to write to register {}", reg)) Err(format!("Failed to write to register {reg}"))
} else { } else {
Ok(()) Ok(())
} }
@ -534,7 +534,7 @@ impl CPU {
let mut val = T::zero(); let mut val = T::zero();
let success = unsafe { libafl_qemu_read_reg(self.ptr, reg, addr_of_mut!(val) as *mut u8) }; let success = unsafe { libafl_qemu_read_reg(self.ptr, reg, addr_of_mut!(val) as *mut u8) };
if success == 0 { if success == 0 {
Err(format!("Failed to read register {}", reg)) Err(format!("Failed to read register {reg}"))
} else { } else {
Ok(val) Ok(val)
} }
@ -775,7 +775,7 @@ impl Emulator {
perms: MmapPerms, perms: MmapPerms,
) -> Result<GuestAddr, String> { ) -> Result<GuestAddr, String> {
self.mmap(addr, size, perms, libc::MAP_PRIVATE | libc::MAP_ANONYMOUS) self.mmap(addr, size, perms, libc::MAP_PRIVATE | libc::MAP_ANONYMOUS)
.map_err(|_| format!("Failed to map {}", addr)) .map_err(|_| format!("Failed to map {addr}"))
.map(|addr| addr as GuestAddr) .map(|addr| addr as GuestAddr)
} }
@ -792,7 +792,7 @@ impl Emulator {
perms, perms,
libc::MAP_FIXED | libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, libc::MAP_FIXED | libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
) )
.map_err(|_| format!("Failed to map {}", addr)) .map_err(|_| format!("Failed to map {addr}"))
.map(|addr| addr as GuestAddr) .map(|addr| addr as GuestAddr)
} }
@ -802,7 +802,7 @@ impl Emulator {
if res == 0 { if res == 0 {
Ok(()) Ok(())
} else { } else {
Err(format!("Failed to mprotect {}", addr)) Err(format!("Failed to mprotect {addr}"))
} }
} }
@ -811,7 +811,7 @@ impl Emulator {
if unsafe { target_munmap(addr.into(), size as u64) } == 0 { if unsafe { target_munmap(addr.into(), size as u64) } == 0 {
Ok(()) Ok(())
} else { } else {
Err(format!("Failed to unmap {}", addr)) Err(format!("Failed to unmap {addr}"))
} }
} }

View File

@ -97,14 +97,14 @@ pub fn python_module(py: Python, m: &PyModule) -> PyResult<()> {
let regsm = PyModule::new(py, "regs")?; let regsm = PyModule::new(py, "regs")?;
for r in Regs::iter() { for r in Regs::iter() {
let v: i32 = r.into(); let v: i32 = r.into();
regsm.add(&format!("{:?}", r), v)?; regsm.add(&format!("{r:?}"), v)?;
} }
m.add_submodule(regsm)?; m.add_submodule(regsm)?;
let mmapm = PyModule::new(py, "mmap")?; let mmapm = PyModule::new(py, "mmap")?;
for r in emu::MmapPerms::iter() { for r in emu::MmapPerms::iter() {
let v: i32 = r.into(); let v: i32 = r.into();
mmapm.add(&format!("{:?}", r), v)?; mmapm.add(&format!("{r:?}"), v)?;
} }
m.add_submodule(mmapm)?; m.add_submodule(mmapm)?;

View File

@ -111,7 +111,7 @@ impl<'a, const MAP_SIZE: usize> ForkserverBytesCoverageSugar<'a, MAP_SIZE> {
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
let mut shmem_provider_client = shmem_provider.clone(); let mut shmem_provider_client = shmem_provider.clone();
let monitor = MultiMonitor::new(|s| println!("{}", s)); let monitor = MultiMonitor::new(|s| println!("{s}"));
let mut run_client = |state: Option<_>, let mut run_client = |state: Option<_>,
mut mgr: LlmpRestartingEventManager<_, _, _, _>, mut mgr: LlmpRestartingEventManager<_, _, _, _>,
@ -287,7 +287,7 @@ impl<'a, const MAP_SIZE: usize> ForkserverBytesCoverageSugar<'a, MAP_SIZE> {
match launcher.build().launch() { match launcher.build().launch() {
Ok(()) => (), Ok(()) => (),
Err(Error::ShuttingDown) => println!("\nFuzzing stopped by user. Good Bye."), Err(Error::ShuttingDown) => println!("\nFuzzing stopped by user. Good Bye."),
Err(err) => panic!("Fuzzingg failed {:?}", err), Err(err) => panic!("Fuzzingg failed {err:?}"),
} }
} }
} }

View File

@ -137,7 +137,7 @@ where
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
let monitor = MultiMonitor::new(|s| println!("{}", s)); let monitor = MultiMonitor::new(|s| println!("{s}"));
let mut run_client = |state: Option<_>, let mut run_client = |state: Option<_>,
mut mgr: LlmpRestartingEventManager<_, _, _, _>, mut mgr: LlmpRestartingEventManager<_, _, _, _>,
@ -348,7 +348,7 @@ where
match launcher.build().launch() { match launcher.build().launch() {
Ok(()) => (), Ok(()) => (),
Err(Error::ShuttingDown) => println!("\nFuzzing stopped by user. Good Bye."), Err(Error::ShuttingDown) => println!("\nFuzzing stopped by user. Good Bye."),
Err(err) => panic!("Fuzzingg failed {:?}", err), Err(err) => panic!("Fuzzingg failed {err:?}"),
} }
} }
} }

View File

@ -41,7 +41,6 @@
test, test,
deny( deny(
bad_style, bad_style,
const_err,
dead_code, dead_code,
improper_ctypes, improper_ctypes,
non_shorthand_field_patterns, non_shorthand_field_patterns,

View File

@ -141,7 +141,7 @@ where
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
let monitor = MultiMonitor::new(|s| println!("{}", s)); let monitor = MultiMonitor::new(|s| println!("{s}"));
let mut run_client = |state: Option<_>, let mut run_client = |state: Option<_>,
mut mgr: LlmpRestartingEventManager<_, _, _, _>, mut mgr: LlmpRestartingEventManager<_, _, _, _>,

View File

@ -73,9 +73,9 @@ fn main() {
} }
sancov_cmp sancov_cmp
.define("CMP_MAP_SIZE", Some(&*format!("{}", cmp_map_size))) .define("CMP_MAP_SIZE", Some(&*format!("{cmp_map_size}")))
.define("CMPLOG_MAP_W", Some(&*format!("{}", cmplog_map_w))) .define("CMPLOG_MAP_W", Some(&*format!("{cmplog_map_w}")))
.define("CMPLOG_MAP_H", Some(&*format!("{}", cmplog_map_h))) .define("CMPLOG_MAP_H", Some(&*format!("{cmplog_map_h}")))
.file(src_dir.join("sancov_cmp.c")) .file(src_dir.join("sancov_cmp.c"))
.compile("sancov_cmp"); .compile("sancov_cmp");
} }
@ -105,16 +105,16 @@ fn main() {
cc::Build::new() cc::Build::new()
.file(src_dir.join("coverage.c")) .file(src_dir.join("coverage.c"))
.define("EDGES_MAP_SIZE", Some(&*format!("{}", edges_map_size))) .define("EDGES_MAP_SIZE", Some(&*format!("{edges_map_size}")))
.define("ACCOUNTING_MAP_SIZE", Some(&*format!("{}", acc_map_size))) .define("ACCOUNTING_MAP_SIZE", Some(&*format!("{acc_map_size}")))
.compile("coverage"); .compile("coverage");
println!("cargo:rerun-if-changed=src/cmplog.h"); println!("cargo:rerun-if-changed=src/cmplog.h");
println!("cargo:rerun-if-changed=src/cmplog.c"); println!("cargo:rerun-if-changed=src/cmplog.c");
cc::Build::new() cc::Build::new()
.define("CMPLOG_MAP_W", Some(&*format!("{}", cmplog_map_w))) .define("CMPLOG_MAP_W", Some(&*format!("{cmplog_map_w}")))
.define("CMPLOG_MAP_H", Some(&*format!("{}", cmplog_map_h))) .define("CMPLOG_MAP_H", Some(&*format!("{cmplog_map_h}")))
.file(src_dir.join("cmplog.c")) .file(src_dir.join("cmplog.c"))
.compile("cmplog"); .compile("cmplog");

View File

@ -43,7 +43,6 @@
test, test,
deny( deny(
bad_style, bad_style,
const_err,
dead_code, dead_code,
improper_ctypes, improper_ctypes,
non_shorthand_field_patterns, non_shorthand_field_patterns,

View File

@ -9,7 +9,7 @@ extern "C" {
/// Hooked `exit` function /// Hooked `exit` function
#[no_mangle] #[no_mangle]
pub extern "C" fn exit(status: i32) { pub extern "C" fn exit(status: i32) {
println!("DeExit: The target called exit with status code {}", status); println!("DeExit: The target called exit with status code {status}");
unsafe { unsafe {
abort(); abort();
} }