Fix Clippy (#2913)

* clp

* lol

* this is false positive

* a

* clippy all

* aa
This commit is contained in:
Dongjia "toka" Zhang 2025-01-30 11:17:01 +01:00 committed by GitHub
parent fd6271fa35
commit d8df9b4910
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
49 changed files with 91 additions and 84 deletions

View File

@ -25,8 +25,8 @@ members = [
"utils/gramatron/construct_automata",
"utils/libafl_benches",
"utils/libafl_jumper",
"bindings/pylibafl",
]
default-members = [
"libafl",
"libafl_bolts",
@ -36,6 +36,7 @@ default-members = [
]
exclude = [
"bindings/pylibafl",
"fuzzers",
"libafl_libfuzzer_runtime",
"utils/noaslr",

View File

@ -9,7 +9,7 @@ edition = "2021"
categories = ["development-tools::testing", "emulators", "embedded", "os"]
[dependencies]
pyo3 = { workspace = true, features = ["extension-module"] }
pyo3 = { version = "0.23.2", features = ["extension-module"] }
pyo3-log = { version = "0.12.0" }
libafl_sugar = { path = "../../libafl_sugar", version = "0.15.0", features = [
"python",
@ -24,7 +24,7 @@ libafl_qemu = { path = "../../libafl_qemu", version = "0.15.0", features = [
] }
[build-dependencies]
pyo3-build-config = { workspace = true }
pyo3-build-config = "0.23.2"
[lib]
name = "pylibafl"

View File

@ -40,7 +40,7 @@ pub fn parse_envs(opt: &mut Opt) -> Result<(), Error> {
if let Ok(res) = std::env::var("AFL_MAP_SIZE") {
let map_size = validate_map_size(res.parse()?)?;
opt.map_size = Some(map_size);
};
}
if let Ok(res) = std::env::var("AFL_IGNORE_TIMEOUT") {
opt.ignore_timeouts = parse_bool(&res)?;
}

View File

@ -363,7 +363,7 @@ define_run_client!(state, mgr, fuzzer_dir, core_id, opt, is_main_node, {
// Enable autodict if configured
if !opt.no_autodict {
executor_builder = executor_builder.autotokens(&mut tokens);
};
}
// Finalize and build our Executor
SupportedExecutors::Forkserver(

View File

@ -199,7 +199,7 @@ fn main() {
Ok(()) => unreachable!(),
Err(Error::ShuttingDown) => println!("Fuzzing stopped by user. Good bye."),
Err(err) => panic!("Failed to run launcher: {err:?}"),
};
}
}
#[expect(clippy::struct_excessive_bools)]

View File

@ -57,7 +57,7 @@ impl<'data, 'tree: 'data, 'ctx: 'data, W: Write, T: TreeLike> Unparser<'data, 't
Some(UnparseStep::Script(num, expr)) => self.unwrap_script(num, &expr),
Some(UnparseStep::PushBuffer()) => self.push_buffer(),
None => return false,
};
}
true
}

View File

@ -486,7 +486,7 @@ mod tests {
Ok(None) => (),
Ok(_) => panic!("File {path:?} did not exist even though it should have?"),
Err(e) => panic!("An unexpected error occurred: {e}"),
};
}
drop(f);
fs::remove_file(path).unwrap();
}

View File

@ -330,7 +330,7 @@ where
client_description,
);
}
};
}
}
}
}
@ -829,7 +829,7 @@ where
Err(Error::shutting_down())
}
}?,
};
}
}
}
}
@ -902,7 +902,7 @@ where
if let Some(remote_broker_addr) = self.remote_broker_addr {
log::info!("B2b: Connecting to {:?}", &remote_broker_addr);
broker.inner_mut().connect_b2b(remote_broker_addr)?;
};
}
broker.set_exit_after(exit_cleanly_after);

View File

@ -831,7 +831,7 @@ where
if let Some(remote_broker_addr) = remote_broker_addr {
log::info!("B2b: Connecting to {:?}", &remote_broker_addr);
broker.inner_mut().connect_b2b(remote_broker_addr)?;
};
}
if let Some(exit_cleanly_after) = self.exit_cleanly_after {
broker.set_exit_after(exit_cleanly_after);

View File

@ -901,6 +901,6 @@ mod tests {
assert_eq!("test", o.0.name());
}
_ => panic!("mistmatch"),
};
}
}
}

View File

@ -85,7 +85,7 @@ where
match Self::handle_in_broker(&mut self.monitor, &event)? {
BrokerEventResult::Forward => self.events.push(event),
BrokerEventResult::Handled => (),
};
}
Ok(())
}
}

View File

@ -738,10 +738,10 @@ where
let buf = &buf[4..];
#[cfg(feature = "tcp_compression")]
let buf = self.compressor.decompress(buf)?;
let buf = &self.compressor.decompress(buf)?;
// make decompressed vec and slice compatible
let event = postcard::from_bytes(&buf)?;
let event = postcard::from_bytes(buf)?;
self.handle_in_client(fuzzer, executor, state, other_client_id, event)?;
count += 1;

View File

@ -358,7 +358,7 @@ pub mod windows_exception_handler {
}
} else {
log::error!("Crashed without exception (probably due to SIGABRT)");
};
}
if data.current_input_ptr.is_null() {
{

View File

@ -758,7 +758,7 @@ impl TuiUi {
Cell::from(Span::raw("not measured")),
Cell::from(Span::raw(format!("{:.2}%", client.unmeasured * 100.0))),
]));
};
}
}
let table = Table::default()

View File

@ -268,7 +268,7 @@ impl<S: HasRand> Mutator<EncodedInput, S> for EncodedCopyMutator {
let size = input.codes().len();
if size <= 1 {
return Ok(MutationResult::Skipped);
};
}
// # Safety
// it's larger than 1

View File

@ -1742,7 +1742,7 @@ mod tests {
{
MutationResult::Mutated => new_testcases.push(mutant),
MutationResult::Skipped => (),
};
}
}
}
inputs.append(&mut new_testcases);

View File

@ -233,7 +233,7 @@ where
}
let meta = LogMutationMetadata::new(log);
testcase.add_metadata(meta);
};
}
// Always reset the log for each run
self.mutation_log.clear();
Ok(())

View File

@ -2083,7 +2083,7 @@ fn check_if_text(buf: &[u8], max_len: usize) -> TextType {
}
if percent_ascii >= 99 {
return TextType::Ascii(ascii);
};
}
TextType::None
}

View File

@ -163,7 +163,7 @@ where
let reserve = if meta.map.is_empty() {
map_iter.size_hint().0
} else {
(map_iter.size_hint().0 + 1) / 2
map_iter.size_hint().0.div_ceil(2)
};
meta.map.reserve(reserve);

View File

@ -198,8 +198,8 @@ where
if iter < CAL_STAGE_MAX {
iter += 2;
};
};
}
}
total_time += current_time() - start;
@ -234,7 +234,7 @@ where
usize::from(*history == O::Entry::default());
*history = O::Entry::max_value();
unstable_entries.push(idx);
};
}
}
if !unstable_entries.is_empty() && iter < CAL_STAGE_MAX {

View File

@ -289,7 +289,7 @@ where
) {
self.push_stage_helper_mut().end_of_iter(shared_state, true);
return Some(Err(err));
};
}
if let Err(err) = shared_state
.event_mgr
@ -297,7 +297,7 @@ where
{
self.push_stage_helper_mut().end_of_iter(shared_state, true);
return Some(Err(err));
};
}
} else {
self.push_stage_helper_mut().reset_exit_kind();
}

View File

@ -49,7 +49,7 @@ pub(crate) fn extract_metadata(bytes: &[u8]) -> UnicodeIdentificationMetadata {
core::str::from_utf8(&bytes[i..][..e.valid_up_to()]).unwrap()
});
if !s.is_empty() {
let mut entries = bitvec![0; s.bytes().len()];
let mut entries = bitvec![0; s.len()];
for (c_idx, _) in s.char_indices() {
entries.set(c_idx, true);
visited.set(i + c_idx, true);

View File

@ -60,7 +60,7 @@ fn adder_loop(port: u16) -> Result<(), Box<dyn std::error::Error>> {
sender,
buf.len()
),
};
}
}
if current_result != last_result {

View File

@ -1174,7 +1174,7 @@ where
pub fn alloc_next(&mut self, buf_len: usize) -> Result<*mut LlmpMsg, Error> {
if let Some(msg) = unsafe { self.alloc_next_if_space(buf_len) } {
return Ok(msg);
};
}
/* no more space left! We'll have to start a new page */
unsafe {
@ -1767,7 +1767,7 @@ where
// Store the last msg for next time
self.last_msg_recvd = msg;
};
}
Ok(ret)
}
@ -2745,7 +2745,7 @@ where
"Error adding client! PANIC! {e:?}"
)));
}
};
}
}
// handle all other messages
_ => {
@ -2957,7 +2957,7 @@ where
"Unexpected response from B2B server received.".to_string(),
))
}
};
}
let hostname = hostname::get()
.unwrap_or_else(|_| "<unknown>".into())
@ -3282,7 +3282,7 @@ where
match Self::announce_new_client(sender, shmem_description) {
Ok(()) => (),
Err(e) => log::info!("Error forwarding client on map: {e:?}"),
};
}
if let Err(e) = send_tcp_msg(
&mut stream,
@ -3291,7 +3291,7 @@ where
},
) {
log::info!("An error occurred sending via tcp {e}");
};
}
current_client_id.0 += 1;
}
TcpRequest::RemoteBrokerHello { hostname } => {
@ -3315,11 +3315,11 @@ where
{
if Self::announce_new_client(sender, &shmem_description).is_err() {
log::info!("B2B: Error announcing client {shmem_description:?}");
};
}
current_client_id.0 += 1;
}
}
};
}
}
#[cfg(feature = "std")]
@ -3417,7 +3417,7 @@ where
);
}
ListenerStream::Empty() => {}
};
}
}
});

View File

@ -858,7 +858,7 @@ fn write_minibsod<W: Write>(writer: &mut BufWriter<W>) -> Result<(), std::io::Er
match std::fs::read_to_string("/proc/self/maps") {
Ok(maps) => writer.write_all(maps.as_bytes())?,
Err(e) => writeln!(writer, "Couldn't load mappings: {e:?}")?,
};
}
Ok(())
}

View File

@ -666,7 +666,7 @@ where
log::error!("Error polling for activity: {e:?}");
continue;
}
};
}
let copied_poll_fds: Vec<PollFd> = poll_fds.clone();
for poll_fd in copied_poll_fds {
let revents = poll_fd.revents().expect("revents should not be None");
@ -681,7 +681,7 @@ where
Err(e) => {
log::info!("Ignoring failed read from client {e:?} {poll_fd:?}");
}
};
}
} else {
let (stream, _addr) = match listener.accept_unix_addr() {
Ok(stream_val) => stream_val,
@ -716,7 +716,7 @@ where
Err(e) => {
log::info!("Ignoring failed read from client {e:?}");
}
};
}
}
} else {
//log::warn!("Unknown revents flags: {:?}", revents);

View File

@ -381,7 +381,7 @@ impl Display for Signal {
Signal::SigTerm => write!(f, "SIGTERM")?,
Signal::SigInterrupt => write!(f, "SIGINT")?,
Signal::SigTrap => write!(f, "SIGTRAP")?,
};
}
Ok(())
}

View File

@ -1234,7 +1234,7 @@ pub mod unix_shmem {
return Err(Error::unknown(
"Failed to set the ashmem mapping's size".to_string(),
));
};
}
let map = mmap(
ptr::null_mut(),
@ -1269,7 +1269,7 @@ pub mod unix_shmem {
return Err(Error::unknown(
"The mapping's size differs from the requested size".to_string(),
));
};
}
let map = mmap(
ptr::null_mut(),

View File

@ -166,7 +166,7 @@ where
}
shmem_content.buf_len = len;
shmem_content.is_disk = false;
};
}
Ok(())
}

View File

@ -97,7 +97,7 @@ fn find_llvm_config() -> Result<String, String> {
Err(err) => {
println!("cargo:warning={err}");
}
};
}
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
for version in (LLVM_VERSION_MIN..=LLVM_VERSION_MAX).rev() {
@ -459,7 +459,7 @@ pub const LIBAFL_CC_LLVM_VERSION: Option<usize> = None;
// In case the system is configured oddly, we may have trouble finding the SDK. Manually add the linker flag, just in case.
sdk_path = find_macos_sdk_libs();
ldflags.push(&sdk_path);
};
}
#[cfg(feature = "ddg-instr")]
build_pass(

View File

@ -102,7 +102,7 @@ impl ToolWrapper for ArWrapper {
}
}
_ => (),
};
}
new_args.push(args[i].as_ref().to_string());
i += 1;
}

View File

@ -245,7 +245,7 @@ impl ToolWrapper for ClangWrapper {
shared = true;
} // TODO dynamic list?
_ => (),
};
}
new_args.push(args[i].as_ref().to_string());
i += 1;
}

View File

@ -108,7 +108,7 @@ impl ToolWrapper for LibtoolWrapper {
}
}
_ => (),
};
}
new_args.push(args[i].as_ref().to_string());
i += 1;
}

View File

@ -260,6 +260,6 @@ fn build_dep_check(tools: &[&str]) {
} else {
println!("ERROR: missing build tool {tool}");
exit(1);
};
}
}
}

View File

@ -1998,6 +1998,7 @@ impl AsanRuntime {
/// Generate the instrumentation blobs for the current arch.
#[cfg(target_arch = "aarch64")]
#[expect(clippy::cast_possible_wrap)]
#[expect(clippy::unnecessary_semicolon)]
fn generate_instrumentation_blobs(&mut self) {
let mut ops_report = dynasmrt::VecAssembler::<dynasmrt::aarch64::Aarch64Relocation>::new(0);
dynasm!(ops_report
@ -2689,7 +2690,7 @@ impl AsanRuntime {
Aarch64Register::X0,
Aarch64Register::X1,
);
};
}
}
let displacement = displacement

View File

@ -561,7 +561,7 @@ impl AsanErrors {
}
backtrace_printer.print_trace(backtrace, output).unwrap();
}
};
}
self.errors.push(error);

View File

@ -282,12 +282,12 @@ impl IntelPT {
return Err(Error::unknown(
"Intel PT: aux buffer head is behind aux tail.",
));
};
}
if self.previous_decode_head < tail {
return Err(Error::unknown(
"Intel PT: aux previous head is behind aux tail.",
));
};
}
let len = (head - tail) as usize;
if len >= self.perf_aux_buffer_size {
log::warn!(
@ -350,7 +350,7 @@ impl IntelPT {
}
break 'sync;
}
};
}
}
// Advance the trace pointer up to the latest sync point, otherwise next execution's trace
@ -398,7 +398,7 @@ impl IntelPT {
log::trace!("PT error in event {e:?}");
break 'block;
}
};
}
}
match decoder.next() {
@ -432,6 +432,7 @@ impl IntelPT {
/// Get the raw trace used in the last decoding
#[cfg(feature = "export_raw")]
#[must_use]
pub fn last_decode_trace(&self) -> Vec<u8> {
self.last_decode_trace.clone()
}
@ -784,7 +785,7 @@ pub fn availability_in_qemu_kvm() -> Result<(), String> {
"Failed to parse KVM Intel PT mode in {kvm_pt_mode_path}"
)),
}
};
}
}
#[cfg(not(target_os = "linux"))]
reasons.push("Only linux hosts are supported at the moment".to_owned());
@ -854,7 +855,7 @@ fn availability_in_linux() -> Result<(), String> {
}
}
Err(e) => reasons.push(format!("Failed to read linux capabilities: {e}")),
};
}
if reasons.is_empty() {
Ok(())

View File

@ -134,7 +134,7 @@ where
testcase.filename_mut().replace(name);
testcase.file_path_mut().replace(path);
}
};
}
self.touch(id, corpus)?;
Ok(id)
}
@ -156,9 +156,12 @@ where
fn count_all(&self) -> usize {
self.count_disabled().saturating_add(self.count_disabled())
}
#[expect(clippy::used_underscore_items)]
fn add(&mut self, testcase: Testcase<I>) -> Result<CorpusId, Error> {
self._add(RefCell::new(testcase), false)
}
#[expect(clippy::used_underscore_items)]
fn add_disabled(&mut self, testcase: Testcase<I>) -> Result<CorpusId, Error> {
self._add(RefCell::new(testcase), true)
}
@ -171,14 +174,16 @@ where
unimplemented!("It is unsafe to use this corpus variant with replace!");
}
#[expect(clippy::used_underscore_items)]
fn get(&self, id: CorpusId) -> Result<&RefCell<Testcase<I>>, Error> {
self._get(id, &self.mapping.enabled)
}
#[expect(clippy::used_underscore_items)]
fn get_from_all(&self, id: CorpusId) -> Result<&RefCell<Testcase<I>>, Error> {
match self._get(id, &self.mapping.enabled) {
Ok(input) => Ok(input),
Err(Error::KeyNotFound(..)) => return self._get(id, &self.mapping.disabled),
Err(Error::KeyNotFound(..)) => self._get(id, &self.mapping.disabled),
Err(e) => Err(e),
}
}

View File

@ -512,11 +512,9 @@ macro_rules! fuzz_with {
grimoire,
);
#[expect(clippy::unnecessary_mut_passed)] // the functions may not require these many `mut`s
$operation(&$options, &mut fuzzer, &mut stages, &mut executor, &mut state, &mut mgr)
};
#[expect(clippy::redundant_closure_call)]
$and_then(closure)
}};
@ -592,7 +590,7 @@ pub const STDERR_FD_VAR: &str = "_LIBAFL_LIBFUZZER_STDERR_FD";
/// Will dereference all parameters.
/// This will then call the (potentially unsafe) harness.
/// The fuzzer itself should catch any side effects and, hence be reasonably safe, if the `harness_fn` parameter is correct.
#[expect(non_snake_case, clippy::similar_names, clippy::missing_safety_doc)]
#[expect(clippy::similar_names)]
#[no_mangle]
pub unsafe extern "C" fn LLVMFuzzerRunDriver(
argc: *mut c_int,

View File

@ -97,7 +97,7 @@ pub fn merge(
}
}
let edges = unsafe { core::mem::take(&mut *&raw mut COUNTERS_MAPS) };
let edges = unsafe { core::mem::take(&mut COUNTERS_MAPS) };
let edges_observer = MultiMapObserver::new("edges", edges);
let time = TimeObserver::new("time");
@ -236,7 +236,6 @@ pub fn merge(
.on_remove(&mut state, id, &Some(testcase))?;
} else {
// False-positive: file_path is used just below
#[expect(clippy::needless_borrows_for_generic_args)]
rename(&file_path, &new_file_path)?;
*file_path = new_file_path;
}

View File

@ -60,7 +60,7 @@ where
} else if entry.is_file()
&& entry
.extension()
.map_or(true, |ext| ext != "metadata" && ext != "lafl_lock")
.is_none_or(|ext| ext != "metadata" && ext != "lafl_lock")
&& !metadata.checked.contains(&entry)
{
let mut reader = std::io::BufReader::new(std::fs::File::open(&entry)?);

View File

@ -6,7 +6,6 @@ use std::{
};
use libafl::{
corpus::Corpus,
executors::ExitKind,
observers::{MapObserver, Observer, TimeObserver},
state::HasCorpus,

View File

@ -40,7 +40,7 @@ pub enum OptionsParseError<'a> {
OptionValueParseFailed(&'a str, &'a str),
}
impl<'a> Display for OptionsParseError<'a> {
impl Display for OptionsParseError<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
OptionsParseError::MultipleModesSelected => {

View File

@ -38,7 +38,6 @@ libafl_targets = { workspace = true, default-features = true, features = [
nix = { workspace = true, default-features = true, features = ["fs"] }
typed-builder = { workspace = true }
lazy_static = "1.5.0"
regex = "1.11.1"
serde = { version = "1.0.210", default-features = false, features = [
"alloc",

View File

@ -3,7 +3,6 @@
//! Reads and parses the redqueen results written by QEMU-Nyx and adds them to the state as `CmpValuesMetadata`.
use std::borrow::Cow;
use lazy_static::lazy_static;
use libafl::{
executors::ExitKind,
observers::{CmpValues, CmpValuesMetadata, Observer},
@ -107,12 +106,12 @@ struct RedqueenEvent {
impl RedqueenEvent {
fn new(line: &str) -> Result<Self, String> {
lazy_static! {
static ref RE: regex::Regex = regex::Regex::new(
r"([0-9a-fA-F]+)\s+(CMP|SUB|STR)\s+(\d+)\s+([0-9a-fA-F]+)-([0-9a-fA-F]+)(\sIMM)?"
static RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(
r"([0-9a-fA-F]+)\s+(CMP|SUB|STR)\s+(\d+)\s+([0-9a-fA-F]+)-([0-9a-fA-F]+)(\sIMM)?",
)
.expect("Invalid regex pattern");
}
.expect("Invalid regex pattern")
});
let captures = RE
.captures(line)

View File

@ -242,7 +242,7 @@ where
Hook::Function(gen_block_lengths::<ET, F, I, S>),
Hook::Empty,
);
};
}
if self.module_mapping.is_none() {
log::info!("Auto-filling module mapping for DrCov module from QEMU mapping.");

View File

@ -543,7 +543,7 @@ impl Qemu {
.expect("Could not set QEMU Config.");
}
QemuParams::Cli(_) => {}
};
}
let args = params.to_cli();
@ -1049,7 +1049,7 @@ impl QemuMemoryChunk {
.unwrap()
.read_mem_unchecked(vaddr.try_into().unwrap(), output_sliced);
},
};
}
Ok(output_sliced.len().try_into().unwrap())
}
@ -1095,7 +1095,7 @@ impl QemuMemoryChunk {
.unwrap()
.write_mem(vaddr.try_into().unwrap(), input_sliced)?;
}
};
}
Ok(input_sliced.len().try_into().unwrap())
}

View File

@ -182,7 +182,7 @@ where
actual[..target.as_slice().len()].copy_from_slice(target.as_slice());
new_size = target.as_slice().len();
}
};
}
return;
}
}

View File

@ -12,8 +12,9 @@ run_clippy() {
local dir="$1"
local features="$2"
echo "Running Clippy on $dir"
echo "$CLIPPY_CMD ${features:+"$features"} -- $RUSTC_FLAGS"
pushd "$dir" || return 1
eval "$CLIPPY_CMD ${features:+"$features"} -- $RUSTC_FLAGS"
popd || return 1
@ -22,10 +23,14 @@ run_clippy() {
# Define projects based on the operating system
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
ALL_PROJECTS=(
"libafl_bolts"
"libafl_cc"
"libafl_concolic/symcc_runtime"
"libafl_concolic/symcc_libafl"
"libafl_frida"
"libafl_libfuzzer"
"libafl_libfuzzer_runtime"
"libafl_intelpt"
"libafl_nyx"
"libafl_qemu"
"libafl_tinyinst"