Fix Clippy (#926)

* Fix clippy

* undo comment fmt

* add unstracked nyx files to gitignore

* fix

* windows, no_std

* fix

* fix

* more

* macos

* remove doctest

Co-authored-by: Dongjia "toka" Zhang <tokazerkje@outlook.com>
This commit is contained in:
Dominik Maier 2022-12-05 16:05:42 +01:00 committed by GitHub
parent ee58375ac5
commit 68fbfc8914
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 86 additions and 142 deletions

3
.gitignore vendored
View File

@ -51,3 +51,6 @@ __pycache__
**/libxml2
**/corpus_discovered
**/libxml2-*.tar.gz
libafl_nyx/QEMU-Nyx
libafl_nyx/packer

View File

@ -48,10 +48,7 @@ fn adder_loop(port: u16) -> ! {
}
if current_result != last_result {
println!(
"Adder handled {} messages, reporting {} to broker",
msg_counter, current_result
);
println!("Adder handled {msg_counter} messages, reporting {current_result} to broker");
client
.send_buf(_TAG_MATH_RESULT_V1, &current_result.to_le_bytes())

View File

@ -132,8 +132,7 @@ impl Cores {
if cores.is_empty() {
return Err(Error::illegal_argument(format!(
"No cores specified! parsed: {}",
args
"No cores specified! parsed: {args}"
)));
}
@ -591,8 +590,7 @@ mod apple {
Ok(())
} else {
Err(Error::unknown(format!(
"Failed to set_for_current {:?}",
result
"Failed to set_for_current {result:?}"
)))
}
}
@ -615,8 +613,7 @@ mod apple {
Ok(())
} else {
Err(Error::unknown(format!(
"Failed to set_for_current {:?}",
result
"Failed to set_for_current {result:?}"
)))
}
}

View File

@ -466,9 +466,7 @@ unsafe fn _llmp_page_init<SHM: ShMem>(shmem: &mut SHM, sender_id: ClientId, allo
if !allow_reinit {
assert!(
(*page).magic != PAGE_INITIALIZED_MAGIC,
"Tried to initialize page {:?} twice (for shmem {:?})",
page,
shmem
"Tried to initialize page {page:?} twice (for shmem {shmem:?})"
);
}
@ -641,10 +639,7 @@ where
}
Err(Error::File(e, _)) if e.kind() == ErrorKind::AddrInUse => {
// We are the client :)
println!(
"We're the client (internal port already bound by broker, {:#?})",
e
);
println!("We're the client (internal port already bound by broker, {e:#?})");
Ok(LlmpConnection::IsClient {
client: LlmpClient::create_attach_to_tcp(shmem_provider, port)?,
})
@ -1082,8 +1077,7 @@ where
let page = self.out_shmems.last_mut().unwrap().page_mut();
if msg.is_null() || !llmp_msg_in_page(page, msg) {
return Err(Error::unknown(format!(
"Llmp Message {:?} is null or not in current page",
msg
"Llmp Message {msg:?} is null or not in current page"
)));
}
@ -1189,8 +1183,7 @@ where
match unsafe { self.alloc_next_if_space(buf_len) } {
Some(msg) => Ok(msg),
None => Err(Error::unknown(format!(
"Error allocating {} bytes in shmap",
buf_len
"Error allocating {buf_len} bytes in shmap"
))),
}
}
@ -1258,8 +1251,7 @@ where
|| tag == LLMP_TAG_UNSET
{
return Err(Error::unknown(format!(
"Reserved tag supplied to send_buf ({:#X})",
tag
"Reserved tag supplied to send_buf ({tag:#X})"
)));
}
@ -1282,8 +1274,7 @@ where
|| tag == LLMP_TAG_UNSET
{
return Err(Error::unknown(format!(
"Reserved tag supplied to send_buf ({:#X})",
tag
"Reserved tag supplied to send_buf ({tag:#X})"
)));
}
@ -1742,8 +1733,7 @@ where
let page_size = self.shmem.as_slice().len() - size_of::<LlmpPage>();
if offset > page_size {
Err(Error::illegal_argument(format!(
"Msg offset out of bounds (size: {}, requested offset: {})",
page_size, offset
"Msg offset out of bounds (size: {page_size}, requested offset: {offset})"
)))
} else {
unsafe { Ok(((*page).messages.as_mut_ptr() as *mut u8).add(offset) as *mut LlmpMsg) }
@ -2048,7 +2038,7 @@ where
/// This function returns the [`ShMemDescription`] the client uses to place incoming messages.
/// The thread exits, when the remote broker disconnects.
#[cfg(feature = "std")]
#[allow(clippy::let_and_return)]
#[allow(clippy::let_and_return, clippy::too_many_lines)]
fn b2b_thread_on(
mut stream: TcpStream,
b2b_client_id: ClientId,
@ -2106,8 +2096,7 @@ where
Ok(Some((client_id, tag, flags, payload))) => {
if client_id == b2b_client_id {
println!(
"Ignored message we probably sent earlier (same id), TAG: {:x}",
tag
"Ignored message we probably sent earlier (same id), TAG: {tag:x}"
);
continue;
}
@ -2127,7 +2116,7 @@ where
payload: payload.to_vec(),
},
) {
println!("Got error {} while trying to forward a message to broker {}, exiting thread", e, peer_address);
println!("Got error {e} while trying to forward a message to broker {peer_address}, exiting thread");
return;
}
}
@ -2135,7 +2124,7 @@ where
println!("Local broker is shutting down, exiting thread");
return;
}
Err(e) => panic!("Error reading from local page! {}", e),
Err(e) => panic!("Error reading from local page! {e}"),
}
}
@ -2171,8 +2160,7 @@ where
if let Error::File(e, _) = e {
if e.kind() == ErrorKind::UnexpectedEof {
println!(
"Broker {} seems to have disconnected, exiting",
peer_address
"Broker {peer_address} seems to have disconnected, exiting"
);
return;
}
@ -2417,8 +2405,7 @@ where
println!("Error adding client! Ignoring: {e:?}");
#[cfg(not(feature = "std"))]
return Err(Error::unknown(format!(
"Error adding client! PANIC! {:?}",
e
"Error adding client! PANIC! {e:?}"
)));
}
};

View File

@ -391,8 +391,7 @@ pub unsafe fn setup_signal_handler<T: 'static + Handler>(handler: &mut T) -> Res
// Rust always panics on OOM, so we will, too.
assert!(
!SIGNAL_STACK_PTR.is_null(),
"Failed to allocate signal stack with {} bytes!",
SIGNAL_STACK_SIZE
"Failed to allocate signal stack with {SIGNAL_STACK_SIZE} bytes!"
);
}
let mut ss: stack_t = mem::zeroed();

View File

@ -468,8 +468,7 @@ where
Ok(())
} else {
Err(Error::unknown(format!(
"Wrong result read from pipe! Expected 0, got {:?}",
ret
"Wrong result read from pipe! Expected 0, got {ret:?}"
)))
}
}
@ -630,8 +629,7 @@ pub mod unix_shmem {
if shm_fd == -1 {
perror(b"shm_open\0".as_ptr() as *const _);
return Err(Error::unknown(format!(
"Failed to shm_open map with id {:?}",
shmem_ctr
"Failed to shm_open map with id {shmem_ctr:?}"
)));
}
@ -640,8 +638,7 @@ pub mod unix_shmem {
perror(b"ftruncate\0".as_ptr() as *const _);
shm_unlink(filename_path.as_ptr() as *const _);
return Err(Error::unknown(format!(
"setup_shm(): ftruncate() failed for map with id {:?}",
shmem_ctr
"setup_shm(): ftruncate() failed for map with id {shmem_ctr:?}"
)));
}
@ -659,8 +656,7 @@ pub mod unix_shmem {
close(shm_fd);
shm_unlink(filename_path.as_ptr() as *const _);
return Err(Error::unknown(format!(
"mmap() failed for map with id {:?}",
shmem_ctr
"mmap() failed for map with id {shmem_ctr:?}"
)));
}
@ -691,8 +687,7 @@ pub mod unix_shmem {
perror(b"mmap\0".as_ptr() as *const _);
close(shm_fd);
return Err(Error::unknown(format!(
"mmap() failed for map with fd {:?}",
shm_fd
"mmap() failed for map with fd {shm_fd:?}"
)));
}
@ -997,8 +992,7 @@ pub mod unix_shmem {
let fd = open(device_path.as_ptr(), O_RDWR);
if fd == -1 {
return Err(Error::unknown(format!(
"Failed to open the ashmem device at {:?}",
device_path
"Failed to open the ashmem device at {device_path:?}"
)));
}

View File

@ -398,10 +398,7 @@ where
executions: _,
} => {
#[cfg(feature = "std")]
println!(
"Received new Testcase from {} ({:?})",
_client_id, client_config
);
println!("Received new Testcase from {_client_id} ({client_config:?})");
let _res = if client_config.match_with(&self.configuration)
&& observers_buf.is_some()
@ -890,8 +887,13 @@ where
mgr.to_env(_ENV_FUZZER_BROKER_CLIENT_INITIAL);
// First, create a channel from the current fuzzer to the next to store state between restarts.
#[cfg(unix)]
let mut staterestorer: StateRestorer<SP> =
StateRestorer::new(self.shmem_provider.new_shmem(256 * 1024 * 1024)?);
#[cfg(not(unix))]
let staterestorer: StateRestorer<SP> =
StateRestorer::new(self.shmem_provider.new_shmem(256 * 1024 * 1024)?);
// Store the information to a map.
staterestorer.write_to_env(_ENV_FUZZER_SENDER)?;

View File

@ -41,8 +41,8 @@ pub static mut SHUTDOWN_SIGHANDLER_DATA: ShutdownSignalData = ShutdownSignalData
shutdown_handler: core::ptr::null(),
};
/// A signal handler for releasing staterestore shmem
/// This struct holds a pointer to StateRestore and clean up the shmem segment used by it.
/// A signal handler for releasing `StateRestore` `ShMem`
/// This struct holds a pointer to `StateRestore` and clean up the `ShMem` segment used by it.
#[cfg(all(unix, feature = "std"))]
#[derive(Debug, Clone)]
pub struct ShutdownSignalData {
@ -58,6 +58,10 @@ pub type ShutdownFuncPtr =
/// Shutdown handler. `SigTerm`, `SigInterrupt`, `SigQuit` call this
/// We can't handle SIGKILL in the signal handler, this means that you shouldn't kill your fuzzer with `kill -9` because then the shmem segments are never freed
///
/// # Safety
///
/// This will acceess `data` and write to the global `data.staterestorer_ptr` if it's not null.
#[cfg(all(unix, feature = "std"))]
pub unsafe fn shutdown_handler<SP>(
signal: Signal,

View File

@ -292,8 +292,7 @@ where
Ok(())
} else {
Err(Error::unknown(format!(
"Received illegal message that message should not have arrived: {:?}.",
event
"Received illegal message that message should not have arrived: {event:?}."
)))
}
}
@ -445,8 +444,13 @@ where
// We start ourself as child process to actually fuzz
let mut staterestorer = if std::env::var(_ENV_FUZZER_SENDER).is_err() {
// First, create a place to store state in, for restarts.
#[cfg(unix)]
let mut staterestorer: StateRestorer<SP> =
StateRestorer::new(shmem_provider.new_shmem(256 * 1024 * 1024)?);
#[cfg(not(unix))]
let staterestorer: StateRestorer<SP> =
StateRestorer::new(shmem_provider.new_shmem(256 * 1024 * 1024)?);
//let staterestorer = { LlmpSender::new(shmem_provider.clone(), 0, false)? };
staterestorer.write_to_env(_ENV_FUZZER_SENDER)?;

View File

@ -249,8 +249,7 @@ impl Forkserver {
Ok(_) => (),
Err(err) => {
return Err(Error::illegal_state(format!(
"Could not spawn the forkserver: {:#?}",
err
"Could not spawn the forkserver: {err:#?}"
)))
}
};

View File

@ -845,8 +845,7 @@ mod unix_signal_handler {
let si_addr = { _info.si_addr() as usize };
eprintln!(
"We crashed at addr 0x{:x}, but are not in the target... Bug in the fuzzer? Exiting.",
si_addr
"We crashed at addr 0x{si_addr:x}, but are not in the target... Bug in the fuzzer? Exiting."
);
#[cfg(all(feature = "std", unix))]

View File

@ -75,8 +75,7 @@ where
let o2_name = o2.name().to_string();
if o1_name == o2_name {
Err(Error::illegal_argument(format!(
"DiffFeedback: observer names must be different (both were {})",
o1_name
"DiffFeedback: observer names must be different (both were {o1_name})"
)))
} else {
Ok(Self {

View File

@ -832,8 +832,7 @@ impl core::fmt::Display for ClientPerfMonitor {
// Create the formatted string
writeln!(
f,
" {:6.4}: Scheduler\n {:6.4}: Manager",
scheduler_percent, manager_percent
" {scheduler_percent:6.4}: Scheduler\n {manager_percent:6.4}: Manager"
)?;
// Calculate each stage

View File

@ -113,8 +113,7 @@ impl Tokens {
}
if token_stop < token_start {
return Err(Error::illegal_argument(format!(
"Tried to create tokens from illegal section: stop < start ({:?} < {:?})",
token_stop, token_start
"Tried to create tokens from illegal section: stop < start ({token_stop:?} < {token_start:?})"
)));
}
let section_size: usize = token_stop.offset_from(token_start).try_into().unwrap();
@ -185,8 +184,7 @@ impl Tokens {
Ok(val) => val,
Err(_) => {
return Err(Error::illegal_argument(format!(
"Illegal line (hex decoding): {}",
line
"Illegal line (hex decoding): {line}"
)))
}
};

View File

@ -19,14 +19,11 @@ pub use stacktrace::*;
pub mod concolic;
pub mod value;
pub use value::*;
// Rust is breaking this with 'error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `type_id`' and so we disable this component for the moment
//#[cfg(unstable_feature)]
//pub mod owned;
//#[cfg(unstable_feature)]
//pub use owned::*;
use alloc::{
string::{String, ToString},
vec::Vec,
@ -34,6 +31,7 @@ use alloc::{
use core::{fmt::Debug, time::Duration};
use serde::{Deserialize, Serialize};
pub use value::*;
use crate::{
bolts::{

View File

@ -1,19 +1,20 @@
//! A simple observer with a single value.
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::{
boxed::Box,
string::{String, ToString},
};
use core::fmt::Debug;
use serde::{Deserialize, Serialize};
use super::Observer;
use crate::{
bolts::{ownedref::OwnedRef, tuples::Named},
inputs::UsesInput,
Error,
};
use super::Observer;
/// A simple observer with a single value.
///
/// The intent is that the value is something with interior mutability (e.g., a
@ -45,36 +46,17 @@ where
}
/// Get a reference to the underlying value.
///
/// ```
/// # use libafl::observers::value::ValueObserver;
/// let mut obs = ValueObserver::new("example", &2);
/// assert_eq!(&2, obs.get_ref());
/// ```
#[must_use]
pub fn get_ref(&self) -> &T {
self.value.as_ref()
}
/// Set the value.
///
/// ```
/// # use libafl::observers::value::ValueObserver;
/// let mut obs = ValueObserver::new("example", &2);
/// obs.set(3);
/// assert_eq!(3, obs.take());
/// ```
pub fn set(&mut self, new_value: T) {
self.value = OwnedRef::Owned(Box::new(new_value));
}
/// Clone or move the current value out of this object.
///
/// ```
/// # use libafl::observers::value::ValueObserver;
/// let mut obs = ValueObserver::new("example", &2);
/// assert_eq!(2, obs.take());
/// ```
#[must_use]
pub fn take(self) -> T
where

View File

@ -210,8 +210,7 @@ where
let must_remove = {
let old_meta = old.metadata_mut().get_mut::<AccountingIndexesMetadata>().ok_or_else(|| {
Error::key_not_found(format!(
"AccountingIndexesMetadata, needed by CoverageAccountingScheduler, not found in testcase #{}",
old_idx
"AccountingIndexesMetadata, needed by CoverageAccountingScheduler, not found in testcase #{old_idx}"
))
})?;
*old_meta.refcnt_mut() -= 1;

View File

@ -209,8 +209,7 @@ where
let factor = F::compute(&mut *entry, state)?;
let meta = entry.metadata_mut().get_mut::<M>().ok_or_else(|| {
Error::key_not_found(format!(
"Metadata needed for MinimizerScheduler not found in testcase #{}",
idx
"Metadata needed for MinimizerScheduler not found in testcase #{idx}"
))
})?;
for elem in meta.as_slice() {
@ -229,8 +228,7 @@ where
let must_remove = {
let old_meta = old.metadata_mut().get_mut::<M>().ok_or_else(|| {
Error::key_not_found(format!(
"Metadata needed for MinimizerScheduler not found in testcase #{}",
old_idx
"Metadata needed for MinimizerScheduler not found in testcase #{old_idx}"
))
})?;
*old_meta.refcnt_mut() -= 1;
@ -283,8 +281,7 @@ where
let mut entry = state.corpus().get(*idx)?.borrow_mut();
let meta = entry.metadata().get::<M>().ok_or_else(|| {
Error::key_not_found(format!(
"Metadata needed for MinimizerScheduler not found in testcase #{}",
idx
"Metadata needed for MinimizerScheduler not found in testcase #{idx}"
))
})?;
for elem in meta.as_slice() {

View File

@ -127,8 +127,7 @@ where
let original = input.clone();
let meta = entry.metadata().get::<MapNoveltiesMetadata>().ok_or_else(|| {
Error::key_not_found(format!(
"MapNoveltiesMetadata needed for GeneralizationStage not found in testcase #{} (check the arguments of MapFeedback::new(...))",
corpus_idx
"MapNoveltiesMetadata needed for GeneralizationStage not found in testcase #{corpus_idx} (check the arguments of MapFeedback::new(...))"
))
})?;
(payload, original, meta.as_slice().to_vec())

View File

@ -46,8 +46,7 @@ fn find_llvm_config_brew() -> Result<PathBuf, String> {
match glob_results.last() {
Some(path) => Ok(path.unwrap()),
None => Err(format!(
"No llvm-config found in brew cellar with pattern {}",
cellar_glob
"No llvm-config found in brew cellar with pattern {cellar_glob}"
)),
}
}

View File

@ -182,8 +182,7 @@ fn write_symcc_runtime_bindings_file(out_path: &Path, cpp_bindings: &bindgen::Bi
let function_name = &captures[1];
writeln!(
bindings_file,
"#[link_name=\"{}{}\"]",
SYMCC_RUNTIME_FUNCTION_NAME_PREFIX, function_name
"#[link_name=\"{SYMCC_RUNTIME_FUNCTION_NAME_PREFIX}{function_name}\"]"
)
.unwrap();
}

View File

@ -440,8 +440,7 @@ impl Allocator {
Some(metadata) => metadata.size,
None => {
panic!(
"Attempted to get_usable_size on a pointer ({:?}) which was not allocated!",
ptr
"Attempted to get_usable_size on a pointer ({ptr:?}) which was not allocated!"
);
}
}

View File

@ -399,8 +399,7 @@ impl AsanRuntime {
self.allocator
.map_shadow_for_region(tls_start, tls_end, true);
println!(
"registering thread with stack {:x}:{:x} and tls {:x}:{:x}",
stack_start, stack_end, tls_start, tls_end
"registering thread with stack {stack_start:x}:{stack_end:x} and tls {tls_start:x}:{tls_end:x}"
);
}
@ -1547,7 +1546,8 @@ impl AsanRuntime {
}
#[cfg(target_arch = "aarch64")]
#[allow(clippy::unused_self, clippy::identity_op)] // identity_op appears to be a false positive in ubfx
// identity_op appears to be a false positive in ubfx
#[allow(clippy::unused_self, clippy::identity_op, clippy::too_many_lines)]
fn generate_shadow_check_function(&mut self) {
let shadow_bit = self.allocator.shadow_bit();
let mut ops = dynasmrt::VecAssembler::<dynasmrt::aarch64::Aarch64Relocation>::new(0);
@ -1657,8 +1657,9 @@ impl AsanRuntime {
let mut map_flags = MapFlags::MAP_ANON | MapFlags::MAP_PRIVATE;
// apple aarch64 requires MAP_JIT to allocates WX pages
#[cfg(all(target_vendor = "apple", target_arch = "aarch64"))]
map_flags |= MapFlags::MAP_JIT;
if cfg!(all(target_vendor = "apple", target_arch = "aarch64")) {
map_flags |= MapFlags::MAP_JIT;
}
unsafe {
let mapping = mmap(
@ -1678,7 +1679,7 @@ impl AsanRuntime {
blob.as_ptr()
.copy_to_nonoverlapping(mapping as *mut u8, blob.len());
#[cfg(all(target_vendor = "apple", target_arch = "aarch64"))]
libc::pthread_jit_write_protect_np(1);
self.shadow_check_func = Some(std::mem::transmute(mapping as *mut u8));
@ -2047,19 +2048,19 @@ impl AsanRuntime {
; .qword addr_of_mut!(self.eh_frame) as i64
);
self.eh_frame = [
0x14, 0, 0x00527a01, 0x011e7c01, 0x001f0c1b,
0x14, 0, 0x00527a01, 0x011e7c01, 0x001f0c1b, //
// eh_frame_fde
0x14, 0x18,
0x14, 0x18, //
// fde_address
0, // <-- address offset goes here
0x104,
0x104,
// advance_loc 12
// def_cfa r29 (x29) at offset 16
// offset r30 (x30) at cfa-8
// offset r29 (x29) at cfa-16
0x1d0c4c00, 0x9d029e10, 0x4,
0x1d0c4c00, 0x9d029e10, 0x4, //
// empty next FDE:
0, 0
0, 0,
];
self.blob_report = Some(ops_report.finalize().unwrap().into_boxed_slice());

View File

@ -312,8 +312,7 @@ impl AsanErrors {
| AsanError::BadFuncArgWrite((name, _pc, address, size, backtrace)) => {
writeln!(
output,
" in call to {}, argument {:#016x}, size: {:#x}",
name, address, size
" in call to {name}, argument {address:#016x}, size: {size:#x}"
)
.unwrap();
output.reset().unwrap();
@ -432,12 +431,7 @@ impl AsanErrors {
)
.unwrap();
} else {
writeln!(
output,
" at 0x{:x}, faulting address 0x{:x}",
pc, fault_address
)
.unwrap();
writeln!(output, " at 0x{pc:x}, faulting address 0x{fault_address:x}").unwrap();
}
output.reset().unwrap();

View File

@ -69,10 +69,7 @@ pub fn build(
}
if !qemu_path.is_dir() {
println!(
"cargo:warning=Qemu not found, cloning with git ({})...",
QEMU_REVISION
);
println!("cargo:warning=Qemu not found, cloning with git ({QEMU_REVISION})...");
fs::create_dir_all(&qemu_path).unwrap();
Command::new("git")
.current_dir(&qemu_path)

View File

@ -33,17 +33,16 @@ fn main() {
"// These constants are autogenerated by build.rs
/// The size of the edges map
pub const EDGES_MAP_SIZE: usize = {};
pub const EDGES_MAP_SIZE: usize = {edges_map_size};
/// The size of the cmps map
pub const CMP_MAP_SIZE: usize = {};
pub const CMP_MAP_SIZE: usize = {cmp_map_size};
/// The width of the `CmpLog` map
pub const CMPLOG_MAP_W: usize = {};
pub const CMPLOG_MAP_W: usize = {cmplog_map_w};
/// The height of the `CmpLog` map
pub const CMPLOG_MAP_H: usize = {};
pub const CMPLOG_MAP_H: usize = {cmplog_map_h};
/// The size of the accounting maps
pub const ACCOUNTING_MAP_SIZE: usize = {};
",
edges_map_size, cmp_map_size, cmplog_map_w, cmplog_map_h, acc_map_size
pub const ACCOUNTING_MAP_SIZE: usize = {acc_map_size};
"
)
.expect("Could not write file");