diff --git a/fuzzers/baby_fuzzer/src/main.rs b/fuzzers/baby_fuzzer/src/main.rs index 4ad453ea29..e600afcfb7 100644 --- a/fuzzers/baby_fuzzer/src/main.rs +++ b/fuzzers/baby_fuzzer/src/main.rs @@ -1,5 +1,4 @@ use std::path::PathBuf; - #[cfg(windows)] use std::ptr::write_volatile; diff --git a/fuzzers/baby_fuzzer_gramatron/src/main.rs b/fuzzers/baby_fuzzer_gramatron/src/main.rs index 4361bbc000..b1f3f2a7e9 100644 --- a/fuzzers/baby_fuzzer_gramatron/src/main.rs +++ b/fuzzers/baby_fuzzer_gramatron/src/main.rs @@ -1,13 +1,11 @@ -use std::io::Read; +#[cfg(windows)] +use std::ptr::write_volatile; use std::{ fs, - io::BufReader, + io::{BufReader, Read}, path::{Path, PathBuf}, }; -#[cfg(windows)] -use std::ptr::write_volatile; - use libafl::{ bolts::{current_nanos, rands::StdRand, tuples::tuple_list}, corpus::{InMemoryCorpus, OnDiskCorpus}, diff --git a/fuzzers/baby_fuzzer_grimoire/src/main.rs b/fuzzers/baby_fuzzer_grimoire/src/main.rs index b96c812735..c28c3f6641 100644 --- a/fuzzers/baby_fuzzer_grimoire/src/main.rs +++ b/fuzzers/baby_fuzzer_grimoire/src/main.rs @@ -1,8 +1,6 @@ -use std::io::Read; -use std::{fs, path::PathBuf}; - #[cfg(windows)] use std::ptr::write_volatile; +use std::{fs, io::Read, path::PathBuf}; use libafl::{ bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice}, diff --git a/fuzzers/baby_fuzzer_nautilus/src/main.rs b/fuzzers/baby_fuzzer_nautilus/src/main.rs index f16a944dca..078451d8b1 100644 --- a/fuzzers/baby_fuzzer_nautilus/src/main.rs +++ b/fuzzers/baby_fuzzer_nautilus/src/main.rs @@ -1,5 +1,4 @@ use std::path::PathBuf; - #[cfg(windows)] use std::ptr::write_volatile; diff --git a/fuzzers/baby_fuzzer_tokens/src/main.rs b/fuzzers/baby_fuzzer_tokens/src/main.rs index 0cb1c0e040..2f8beea6e6 100644 --- a/fuzzers/baby_fuzzer_tokens/src/main.rs +++ b/fuzzers/baby_fuzzer_tokens/src/main.rs @@ -1,8 +1,6 @@ -use std::io::Read; -use std::{fs, path::PathBuf}; - #[cfg(windows)] use std::ptr::write_volatile; +use std::{fs, io::Read, path::PathBuf}; use libafl::{ bolts::{current_nanos, rands::StdRand, tuples::tuple_list}, diff --git a/fuzzers/baby_fuzzer_with_forkexecutor/src/main.rs b/fuzzers/baby_fuzzer_with_forkexecutor/src/main.rs index d11b63f869..396a7d210a 100644 --- a/fuzzers/baby_fuzzer_with_forkexecutor/src/main.rs +++ b/fuzzers/baby_fuzzer_with_forkexecutor/src/main.rs @@ -1,5 +1,4 @@ use std::path::PathBuf; - #[cfg(windows)] use std::ptr::write_volatile; diff --git a/fuzzers/baby_no_std/src/main.rs b/fuzzers/baby_no_std/src/main.rs index d6422de7b0..797de2837d 100644 --- a/fuzzers/baby_no_std/src/main.rs +++ b/fuzzers/baby_no_std/src/main.rs @@ -4,6 +4,11 @@ // Embedded needs alloc error handlers which only work on nightly right now... #![cfg_attr(not(any(windows, unix)), feature(default_alloc_error_handler))] +#[cfg(not(any(windows, unix)))] +use core::panic::PanicInfo; + +#[cfg(any(windows, unix))] +use cstr_core::CString; use libafl::{ bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice}, corpus::InMemoryCorpus, @@ -20,14 +25,8 @@ use libafl::{ stages::mutational::StdMutationalStage, state::StdState, }; - -#[cfg(any(windows, unix))] -use cstr_core::CString; #[cfg(any(windows, unix))] use libc::{c_char, printf}; - -#[cfg(not(any(windows, unix)))] -use core::panic::PanicInfo; use static_alloc::Bump; #[global_allocator] diff --git a/fuzzers/backtrace_baby_fuzzers/c_code_with_fork_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/c_code_with_fork_executor/src/main.rs index 3bd2b70379..a6b370f231 100644 --- a/fuzzers/backtrace_baby_fuzzers/c_code_with_fork_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/c_code_with_fork_executor/src/main.rs @@ -1,14 +1,12 @@ use std::path::PathBuf; -use libafl::bolts::shmem::ShMemProvider; -use libafl::bolts::AsSlice; -use libafl::observers::ConstMapObserver; use libafl::{ bolts::{ current_nanos, rands::StdRand, - shmem::{ShMem, StdShMemProvider}, + shmem::{ShMem, ShMemProvider, StdShMemProvider}, tuples::tuple_list, + AsSlice, }, corpus::{InMemoryCorpus, OnDiskCorpus}, events::SimpleEventManager, @@ -20,13 +18,12 @@ use libafl::{ inputs::{BytesInput, HasTargetBytes}, monitors::SimpleMonitor, mutators::scheduled::{havoc_mutations, StdScheduledMutator}, - observers::BacktraceObserver, + observers::{BacktraceObserver, ConstMapObserver}, schedulers::QueueScheduler, stages::mutational::StdMutationalStage, state::StdState, }; -use libc::c_int; -use libc::c_uchar; +use libc::{c_int, c_uchar}; extern crate libc; extern "C" { diff --git a/fuzzers/backtrace_baby_fuzzers/c_code_with_inprocess_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/c_code_with_inprocess_executor/src/main.rs index 21048f1c45..9886af04f2 100644 --- a/fuzzers/backtrace_baby_fuzzers/c_code_with_inprocess_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/c_code_with_inprocess_executor/src/main.rs @@ -1,12 +1,10 @@ use std::path::PathBuf; -use libafl::bolts::AsSlice; -use libafl::executors::InProcessExecutor; -use libafl::observers::ConstMapObserver; use libafl::{ - bolts::{current_nanos, rands::StdRand, tuples::tuple_list}, + bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice}, corpus::{InMemoryCorpus, OnDiskCorpus}, events::SimpleEventManager, + executors::InProcessExecutor, feedback_and, feedbacks::{CrashFeedback, MaxMapFeedback, NewHashFeedback}, fuzzer::{Fuzzer, StdFuzzer}, @@ -14,7 +12,7 @@ use libafl::{ inputs::{BytesInput, HasTargetBytes}, monitors::SimpleMonitor, mutators::scheduled::{havoc_mutations, StdScheduledMutator}, - observers::BacktraceObserver, + observers::{BacktraceObserver, ConstMapObserver}, schedulers::QueueScheduler, stages::mutational::StdMutationalStage, state::StdState, diff --git a/fuzzers/backtrace_baby_fuzzers/command_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/command_executor/src/main.rs index bb03d8cfb4..f3b6065e95 100644 --- a/fuzzers/backtrace_baby_fuzzers/command_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/command_executor/src/main.rs @@ -1,3 +1,11 @@ +#[cfg(windows)] +use std::ptr::write_volatile; +use std::{ + io::Write, + path::PathBuf, + process::{Child, Command, Stdio}, +}; + use libafl::{ bolts::{ current_nanos, @@ -22,13 +30,6 @@ use libafl::{ state::StdState, Error, }; -#[cfg(windows)] -use std::ptr::write_volatile; -use std::{ - io::Write, - path::PathBuf, - process::{Child, Command, Stdio}, -}; #[allow(clippy::similar_names)] pub fn main() { diff --git a/fuzzers/backtrace_baby_fuzzers/forkserver_executor/build.rs b/fuzzers/backtrace_baby_fuzzers/forkserver_executor/build.rs index ac8973e5dc..6212fe81ca 100644 --- a/fuzzers/backtrace_baby_fuzzers/forkserver_executor/build.rs +++ b/fuzzers/backtrace_baby_fuzzers/forkserver_executor/build.rs @@ -1,6 +1,8 @@ -use std::env; -use std::path::Path; -use std::process::{exit, Command}; +use std::{ + env, + path::Path, + process::{exit, Command}, +}; const AFL_URL: &str = "https://github.com/AFLplusplus/AFLplusplus"; diff --git a/fuzzers/backtrace_baby_fuzzers/forkserver_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/forkserver_executor/src/main.rs index 772b206e1c..335e479667 100644 --- a/fuzzers/backtrace_baby_fuzzers/forkserver_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/forkserver_executor/src/main.rs @@ -1,3 +1,9 @@ +use std::path::PathBuf; + +#[cfg(not(target_vendor = "apple"))] +use libafl::bolts::shmem::StdShMemProvider; +#[cfg(target_vendor = "apple")] +use libafl::bolts::shmem::UnixShMemProvider; use libafl::{ bolts::{ current_nanos, @@ -21,12 +27,6 @@ use libafl::{ stages::mutational::StdMutationalStage, state::StdState, }; -use std::path::PathBuf; - -#[cfg(not(target_vendor = "apple"))] -use libafl::bolts::shmem::StdShMemProvider; -#[cfg(target_vendor = "apple")] -use libafl::bolts::shmem::UnixShMemProvider; #[allow(clippy::similar_names)] pub fn main() { diff --git a/fuzzers/backtrace_baby_fuzzers/rust_code_with_fork_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/rust_code_with_fork_executor/src/main.rs index 5534e21453..1fa7f1dc82 100644 --- a/fuzzers/backtrace_baby_fuzzers/rust_code_with_fork_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/rust_code_with_fork_executor/src/main.rs @@ -1,5 +1,4 @@ use std::path::PathBuf; - #[cfg(windows)] use std::ptr::write_volatile; diff --git a/fuzzers/backtrace_baby_fuzzers/rust_code_with_inprocess_executor/src/main.rs b/fuzzers/backtrace_baby_fuzzers/rust_code_with_inprocess_executor/src/main.rs index 30f6548387..f8cb55913e 100644 --- a/fuzzers/backtrace_baby_fuzzers/rust_code_with_inprocess_executor/src/main.rs +++ b/fuzzers/backtrace_baby_fuzzers/rust_code_with_inprocess_executor/src/main.rs @@ -1,5 +1,4 @@ use std::path::PathBuf; - #[cfg(windows)] use std::ptr::write_volatile; diff --git a/fuzzers/forkserver_simple/build.rs b/fuzzers/forkserver_simple/build.rs index 9a9eddf30c..fcbde46935 100644 --- a/fuzzers/forkserver_simple/build.rs +++ b/fuzzers/forkserver_simple/build.rs @@ -1,6 +1,8 @@ -use std::env; -use std::path::Path; -use std::process::{exit, Command}; +use std::{ + env, + path::Path, + process::{exit, Command}, +}; const AFL_URL: &str = "https://github.com/AFLplusplus/AFLplusplus"; diff --git a/fuzzers/forkserver_simple/src/main.rs b/fuzzers/forkserver_simple/src/main.rs index 9f23de321e..faa617b3d2 100644 --- a/fuzzers/forkserver_simple/src/main.rs +++ b/fuzzers/forkserver_simple/src/main.rs @@ -1,5 +1,11 @@ -use clap::{Arg, Command}; use core::time::Duration; +use std::path::PathBuf; + +use clap::{Arg, Command}; +#[cfg(not(target_vendor = "apple"))] +use libafl::bolts::shmem::StdShMemProvider; +#[cfg(target_vendor = "apple")] +use libafl::bolts::shmem::UnixShMemProvider; use libafl::{ bolts::{ current_nanos, @@ -23,13 +29,6 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, }; use nix::sys::signal::Signal; -use std::path::PathBuf; - -#[cfg(target_vendor = "apple")] -use libafl::bolts::shmem::UnixShMemProvider; - -#[cfg(not(target_vendor = "apple"))] -use libafl::bolts::shmem::StdShMemProvider; #[allow(clippy::similar_names)] pub fn main() { diff --git a/fuzzers/frida_libpng/src/fuzzer.rs b/fuzzers/frida_libpng/src/fuzzer.rs index e756f70e8e..11c092edc7 100644 --- a/fuzzers/frida_libpng/src/fuzzer.rs +++ b/fuzzers/frida_libpng/src/fuzzer.rs @@ -4,9 +4,9 @@ use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; -use frida_gum::Gum; use std::path::PathBuf; +use frida_gum::Gum; use libafl::{ bolts::{ cli::{parse_args, FuzzerOptions}, @@ -27,8 +27,7 @@ use libafl::{ monitors::MultiMonitor, mutators::{ scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - token_mutations::I2SRandReplace, - token_mutations::Tokens, + token_mutations::{I2SRandReplace, Tokens}, }, observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, @@ -36,19 +35,17 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; - -use libafl_frida::{ - coverage_rt::CoverageRuntime, coverage_rt::MAP_SIZE, executor::FridaInProcessExecutor, - helper::FridaInstrumentationHelper, -}; - #[cfg(unix)] use libafl_frida::asan::asan_rt::AsanRuntime; -use libafl_targets::cmplog::{CmpLogObserver, CMPLOG_MAP}; - #[cfg(unix)] use libafl_frida::asan::errors::{AsanErrorsFeedback, AsanErrorsObserver, ASAN_ERRORS}; -use libafl_frida::cmplog_rt::CmpLogRuntime; +use libafl_frida::{ + cmplog_rt::CmpLogRuntime, + coverage_rt::{CoverageRuntime, MAP_SIZE}, + executor::FridaInProcessExecutor, + helper::FridaInstrumentationHelper, +}; +use libafl_targets::cmplog::{CmpLogObserver, CMPLOG_MAP}; /// The main fn, usually parsing parameters, and starting the fuzzer pub fn main() { diff --git a/fuzzers/fuzzbench/src/bin/libafl_cc.rs b/fuzzers/fuzzbench/src/bin/libafl_cc.rs index 96644865ea..01af782ec8 100644 --- a/fuzzers/fuzzbench/src/bin/libafl_cc.rs +++ b/fuzzers/fuzzbench/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; + pub fn main() { let mut args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/fuzzbench/src/lib.rs b/fuzzers/fuzzbench/src/lib.rs index 9321244d95..0eccd70dbc 100644 --- a/fuzzers/fuzzbench/src/lib.rs +++ b/fuzzers/fuzzbench/src/lib.rs @@ -3,11 +3,8 @@ use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; -use clap::{Arg, Command}; use core::{cell::RefCell, time::Duration}; #[cfg(unix)] -use nix::{self, unistd::dup}; -#[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd}; use std::{ env, @@ -17,6 +14,7 @@ use std::{ process, }; +use clap::{Arg, Command}; use libafl::{ bolts::{ current_nanos, current_time, @@ -49,13 +47,14 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; +#[cfg(target_os = "linux")] +use libafl_targets::autotokens; use libafl_targets::{ libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, MAX_EDGES_NUM, }; - -#[cfg(target_os = "linux")] -use libafl_targets::autotokens; +#[cfg(unix)] +use nix::{self, unistd::dup}; /// The fuzzer main (as `no_mangle` C function) #[no_mangle] diff --git a/fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs b/fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs index c53ee43df9..9bb81fb662 100644 --- a/fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs +++ b/fuzzers/fuzzbench_fork_qemu/src/fuzzer.rs @@ -1,10 +1,7 @@ //! A singlethreaded QEMU fuzzer that can auto-restart. -use clap::{Arg, Command}; use core::cell::RefCell; #[cfg(unix)] -use nix::{self, unistd::dup}; -#[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd}; use std::{ env, @@ -14,6 +11,7 @@ use std::{ process, }; +use clap::{Arg, Command}; use libafl::{ bolts::{ current_nanos, current_time, @@ -55,6 +53,8 @@ use libafl_qemu::{ hooks::QemuHooks, MmapPerms, QemuForkExecutor, Regs, }; +#[cfg(unix)] +use nix::{self, unistd::dup}; /// The fuzzer main pub fn main() { diff --git a/fuzzers/fuzzbench_qemu/src/fuzzer.rs b/fuzzers/fuzzbench_qemu/src/fuzzer.rs index 1dd5eae6e0..c4e27c6559 100644 --- a/fuzzers/fuzzbench_qemu/src/fuzzer.rs +++ b/fuzzers/fuzzbench_qemu/src/fuzzer.rs @@ -1,10 +1,7 @@ //! A singlethreaded QEMU fuzzer that can auto-restart. -use clap::{Arg, Command}; use core::{cell::RefCell, time::Duration}; #[cfg(unix)] -use nix::{self, unistd::dup}; -#[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd}; use std::{ env, @@ -14,6 +11,7 @@ use std::{ process, }; +use clap::{Arg, Command}; use libafl::{ bolts::{ current_nanos, current_time, @@ -61,6 +59,8 @@ use libafl_qemu::{ QemuExecutor, Regs, }; +#[cfg(unix)] +use nix::{self, unistd::dup}; /// The fuzzer main pub fn main() { diff --git a/fuzzers/fuzzbench_text/src/bin/libafl_cc.rs b/fuzzers/fuzzbench_text/src/bin/libafl_cc.rs index 68a84b0333..d0fded4e68 100644 --- a/fuzzers/fuzzbench_text/src/bin/libafl_cc.rs +++ b/fuzzers/fuzzbench_text/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; + pub fn main() { let args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/fuzzbench_text/src/lib.rs b/fuzzers/fuzzbench_text/src/lib.rs index c45afecb49..e21ff8d11d 100644 --- a/fuzzers/fuzzbench_text/src/lib.rs +++ b/fuzzers/fuzzbench_text/src/lib.rs @@ -3,12 +3,8 @@ use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; -use clap::{Arg, Command}; -use content_inspector::inspect; use core::{cell::RefCell, time::Duration}; #[cfg(unix)] -use nix::{self, unistd::dup}; -#[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd}; use std::{ env, @@ -18,6 +14,8 @@ use std::{ process, }; +use clap::{Arg, Command}; +use content_inspector::inspect; use libafl::{ bolts::{ current_nanos, current_time, @@ -55,13 +53,14 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; +#[cfg(target_os = "linux")] +use libafl_targets::autotokens; use libafl_targets::{ libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, MAX_EDGES_NUM, }; - -#[cfg(target_os = "linux")] -use libafl_targets::autotokens; +#[cfg(unix)] +use nix::{self, unistd::dup}; /// The fuzzer main (as `no_mangle` C function) #[no_mangle] diff --git a/fuzzers/fuzzbench_weighted/src/bin/libafl_cc.rs b/fuzzers/fuzzbench_weighted/src/bin/libafl_cc.rs index 96644865ea..01af782ec8 100644 --- a/fuzzers/fuzzbench_weighted/src/bin/libafl_cc.rs +++ b/fuzzers/fuzzbench_weighted/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; + pub fn main() { let mut args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/fuzzbench_weighted/src/lib.rs b/fuzzers/fuzzbench_weighted/src/lib.rs index 48e5012ee6..7188e022c2 100644 --- a/fuzzers/fuzzbench_weighted/src/lib.rs +++ b/fuzzers/fuzzbench_weighted/src/lib.rs @@ -3,11 +3,8 @@ use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; -use clap::{Arg, Command}; use core::{cell::RefCell, time::Duration}; #[cfg(unix)] -use nix::{self, unistd::dup}; -#[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd}; use std::{ env, @@ -17,6 +14,7 @@ use std::{ process, }; +use clap::{Arg, Command}; use libafl::{ bolts::{ current_nanos, current_time, @@ -49,13 +47,14 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; +#[cfg(target_os = "linux")] +use libafl_targets::autotokens; use libafl_targets::{ libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, MAX_EDGES_NUM, }; - -#[cfg(target_os = "linux")] -use libafl_targets::autotokens; +#[cfg(unix)] +use nix::{self, unistd::dup}; /// The fuzzer main (as `no_mangle` C function) #[no_mangle] diff --git a/fuzzers/libafl_atheris/src/lib.rs b/fuzzers/libafl_atheris/src/lib.rs index 1079c0f263..82ebfb808f 100644 --- a/fuzzers/libafl_atheris/src/lib.rs +++ b/fuzzers/libafl_atheris/src/lib.rs @@ -3,7 +3,6 @@ //! This is the drop-in replacement for libfuzzer, to be used together with [`Atheris`](https://github.com/google/atheris) //! for python instrumentation and fuzzing. -use clap::{AppSettings, Arg, Command}; use core::{convert::TryInto, ffi::c_void, slice, time::Duration}; use std::{ env, @@ -11,6 +10,7 @@ use std::{ path::PathBuf, }; +use clap::{AppSettings, Arg, Command}; use libafl::{ bolts::{ core_affinity::Cores, @@ -30,8 +30,10 @@ use libafl::{ generators::RandBytesGenerator, inputs::{BytesInput, HasTargetBytes}, monitors::MultiMonitor, - mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - mutators::token_mutations::{I2SRandReplace, Tokens}, + mutators::{ + scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + token_mutations::{I2SRandReplace, Tokens}, + }, observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::{StdMutationalStage, TracingStage}, diff --git a/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cc.rs index 359ad30eab..0178cf96fc 100644 --- a/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libmozjpeg/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper}; + pub fn main() { let args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/libfuzzer_libmozjpeg/src/lib.rs b/fuzzers/libfuzzer_libmozjpeg/src/lib.rs index 49b90c7749..e4193fab57 100644 --- a/fuzzers/libfuzzer_libmozjpeg/src/lib.rs +++ b/fuzzers/libfuzzer_libmozjpeg/src/lib.rs @@ -21,15 +21,16 @@ use libafl::{ fuzzer::{Fuzzer, StdFuzzer}, inputs::{BytesInput, HasTargetBytes}, monitors::SimpleMonitor, - mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - mutators::token_mutations::Tokens, + mutators::{ + scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + token_mutations::Tokens, + }, observers::StdMapObserver, schedulers::RandScheduler, stages::mutational::StdMutationalStage, state::{HasCorpus, HasMetadata, StdState}, Error, }; - use libafl_targets::{ libfuzzer_initialize, libfuzzer_test_one_input, CMP_MAP, EDGES_MAP, MAX_EDGES_NUM, }; diff --git a/fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs index 3c00818ff1..c4c13ab101 100644 --- a/fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libpng/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper}; + pub fn main() { let args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/libfuzzer_libpng/src/lib.rs b/fuzzers/libfuzzer_libpng/src/lib.rs index b08e60f656..bfb4d2c91c 100644 --- a/fuzzers/libfuzzer_libpng/src/lib.rs +++ b/fuzzers/libfuzzer_libpng/src/lib.rs @@ -24,8 +24,10 @@ use libafl::{ fuzzer::{Fuzzer, StdFuzzer}, inputs::{BytesInput, HasTargetBytes}, monitors::MultiMonitor, - mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - mutators::token_mutations::Tokens, + mutators::{ + scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + token_mutations::Tokens, + }, observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, schedulers::{ powersched::PowerSchedule, IndexesLenTimeMinimizerScheduler, StdWeightedScheduler, @@ -34,7 +36,6 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; - use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; /// The main fn, `no_mangle` as it is a C main diff --git a/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cc.rs index 3cb501ba57..6b23261d89 100644 --- a/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libpng_accounting/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; + const GRANULARITY: &str = "FUNC"; pub fn main() { diff --git a/fuzzers/libfuzzer_libpng_accounting/src/lib.rs b/fuzzers/libfuzzer_libpng_accounting/src/lib.rs index 51962bbbe2..18aa43ef42 100644 --- a/fuzzers/libfuzzer_libpng_accounting/src/lib.rs +++ b/fuzzers/libfuzzer_libpng_accounting/src/lib.rs @@ -6,10 +6,10 @@ use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; -use clap::{self, StructOpt}; use core::time::Duration; use std::{env, net::SocketAddr, path::PathBuf}; +use clap::{self, StructOpt}; use libafl::{ bolts::{ core_affinity::Cores, @@ -28,15 +28,16 @@ use libafl::{ fuzzer::{Fuzzer, StdFuzzer}, inputs::{BytesInput, HasTargetBytes}, monitors::MultiMonitor, - mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - mutators::token_mutations::Tokens, + mutators::{ + scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + token_mutations::Tokens, + }, observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, schedulers::{CoverageAccountingScheduler, QueueScheduler}, stages::mutational::StdMutationalStage, state::{HasCorpus, HasMetadata, StdState}, Error, }; - use libafl_targets::{ libfuzzer_initialize, libfuzzer_test_one_input, ACCOUNTING_MEMOP_MAP, EDGES_MAP, MAX_EDGES_NUM, }; diff --git a/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cc.rs index f7d7244c11..96abb9ef70 100644 --- a/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libpng_ctx/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper, LLVMPasses}; + pub fn main() { let args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/libfuzzer_libpng_ctx/src/lib.rs b/fuzzers/libfuzzer_libpng_ctx/src/lib.rs index efcbfad8d9..a27e128e3a 100644 --- a/fuzzers/libfuzzer_libpng_ctx/src/lib.rs +++ b/fuzzers/libfuzzer_libpng_ctx/src/lib.rs @@ -6,10 +6,10 @@ use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; -use clap::{self, StructOpt}; use core::time::Duration; use std::{env, net::SocketAddr, path::PathBuf}; +use clap::{self, StructOpt}; use libafl::{ bolts::{ core_affinity::Cores, @@ -38,7 +38,6 @@ use libafl::{ state::{HasCorpus, HasMetadata, StdState}, Error, }; - use libafl_targets::{edges_map_from_ptr, libfuzzer_initialize, libfuzzer_test_one_input}; fn timeout_from_millis_str(time: &str) -> Result { diff --git a/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cc.rs index 3c00818ff1..c4c13ab101 100644 --- a/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_libpng_launcher/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper}; + pub fn main() { let args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/libfuzzer_libpng_launcher/src/lib.rs b/fuzzers/libfuzzer_libpng_launcher/src/lib.rs index 13511a7834..8ec6fa64ff 100644 --- a/fuzzers/libfuzzer_libpng_launcher/src/lib.rs +++ b/fuzzers/libfuzzer_libpng_launcher/src/lib.rs @@ -6,10 +6,10 @@ use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; -use clap::{self, StructOpt}; use core::time::Duration; use std::{env, net::SocketAddr, path::PathBuf}; +use clap::{self, StructOpt}; use libafl::{ bolts::{ core_affinity::Cores, @@ -28,15 +28,16 @@ use libafl::{ fuzzer::{Fuzzer, StdFuzzer}, inputs::{BytesInput, HasTargetBytes}, monitors::{MultiMonitor, OnDiskTOMLMonitor}, - mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - mutators::token_mutations::Tokens, + mutators::{ + scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + token_mutations::Tokens, + }, observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::mutational::StdMutationalStage, state::{HasCorpus, HasMetadata, StdState}, Error, }; - use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; /// Parse a millis string to a [`Duration`]. Used for arg parsing. diff --git a/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs b/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs index 36df36d368..4cbaa83517 100644 --- a/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs +++ b/fuzzers/libfuzzer_reachability/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper}; + pub fn main() { let args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/libfuzzer_stb_image/src/main.rs b/fuzzers/libfuzzer_stb_image/src/main.rs index 35a4a093e7..caab113e4a 100644 --- a/fuzzers/libfuzzer_stb_image/src/main.rs +++ b/fuzzers/libfuzzer_stb_image/src/main.rs @@ -16,15 +16,16 @@ use libafl::{ fuzzer::{Fuzzer, StdFuzzer}, inputs::{BytesInput, HasTargetBytes}, monitors::MultiMonitor, - mutators::scheduled::{havoc_mutations, StdScheduledMutator}, - mutators::token_mutations::I2SRandReplace, + mutators::{ + scheduled::{havoc_mutations, StdScheduledMutator}, + token_mutations::I2SRandReplace, + }, observers::{StdMapObserver, TimeObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::{ShadowTracingStage, StdMutationalStage}, state::{HasCorpus, StdState}, Error, }; - use libafl_targets::{ libfuzzer_initialize, libfuzzer_test_one_input, CmpLogObserver, CMPLOG_MAP, EDGES_MAP, MAX_EDGES_NUM, diff --git a/fuzzers/push_harness/src/main.rs b/fuzzers/push_harness/src/main.rs index 137e687815..78bdd7dd7d 100644 --- a/fuzzers/push_harness/src/main.rs +++ b/fuzzers/push_harness/src/main.rs @@ -1,7 +1,8 @@ //! [`Klo-routines`](https://github.com/andreafioraldi/klo-routines/) based fuzzer. //! The target loops and the harness pulls inputs out of `LibAFL`, instead of being called by `LibAFL`. +use std::path::PathBuf; + use klo_routines::*; -use libafl::inputs::{BytesInput, HasTargetBytes}; use libafl::{ bolts::{current_nanos, rands::StdRand, tuples::tuple_list, AsSlice}, corpus::{InMemoryCorpus, OnDiskCorpus}, @@ -10,6 +11,7 @@ use libafl::{ feedbacks::{CrashFeedback, MaxMapFeedback}, fuzzer::{Fuzzer, StdFuzzer}, generators::RandPrintablesGenerator, + inputs::{BytesInput, HasTargetBytes}, monitors::SimpleMonitor, mutators::scheduled::{havoc_mutations, StdScheduledMutator}, observers::StdMapObserver, @@ -17,7 +19,6 @@ use libafl::{ stages::mutational::StdMutationalStage, state::StdState, }; -use std::path::PathBuf; /// Coverage map with explicit assignments due to the lack of instrumentation static mut SIGNALS: [u8; 16] = [0; 16]; diff --git a/fuzzers/tutorial/src/bin/libafl_cc.rs b/fuzzers/tutorial/src/bin/libafl_cc.rs index f7ccaabae3..66ae8719d8 100644 --- a/fuzzers/tutorial/src/bin/libafl_cc.rs +++ b/fuzzers/tutorial/src/bin/libafl_cc.rs @@ -1,6 +1,7 @@ -use libafl_cc::{ClangWrapper, CompilerWrapper}; use std::env; +use libafl_cc::{ClangWrapper, CompilerWrapper}; + pub fn main() { let args: Vec = env::args().collect(); if args.len() > 1 { diff --git a/fuzzers/tutorial/src/input.rs b/fuzzers/tutorial/src/input.rs index f2f7f423f1..d0d79cf122 100644 --- a/fuzzers/tutorial/src/input.rs +++ b/fuzzers/tutorial/src/input.rs @@ -1,12 +1,11 @@ +use std::hash::Hash; + +use lain::prelude::*; use libafl::{ bolts::{ownedref::OwnedSlice, HasLen}, inputs::{HasTargetBytes, Input}, }; - -use lain::prelude::*; - use serde::{Deserialize, Serialize}; -use std::hash::Hash; #[derive( Serialize, diff --git a/fuzzers/tutorial/src/lib.rs b/fuzzers/tutorial/src/lib.rs index dab8a8b8e5..17ba5f82f5 100644 --- a/fuzzers/tutorial/src/lib.rs +++ b/fuzzers/tutorial/src/lib.rs @@ -22,7 +22,6 @@ use libafl::{ state::{HasCorpus, StdState}, Error, Fuzzer, }; - use libafl_targets::{libfuzzer_initialize, libfuzzer_test_one_input, EDGES_MAP, MAX_EDGES_NUM}; mod input; diff --git a/fuzzers/tutorial/src/metadata.rs b/fuzzers/tutorial/src/metadata.rs index 177b4647a0..03fb8c58c6 100644 --- a/fuzzers/tutorial/src/metadata.rs +++ b/fuzzers/tutorial/src/metadata.rs @@ -9,11 +9,10 @@ use libafl::{ state::{HasClientPerfMonitor, HasCorpus, HasMetadata}, Error, SerdeAny, }; +use serde::{Deserialize, Serialize}; use crate::input::PacketData; -use serde::{Deserialize, Serialize}; - #[derive(Debug, SerdeAny, Serialize, Deserialize)] pub struct PacketLenMetadata { pub length: u64, diff --git a/fuzzers/tutorial/src/mutator.rs b/fuzzers/tutorial/src/mutator.rs index 836edd8f57..8d5e0a0c53 100644 --- a/fuzzers/tutorial/src/mutator.rs +++ b/fuzzers/tutorial/src/mutator.rs @@ -1,3 +1,4 @@ +use lain::traits::Mutatable; use libafl::{ bolts::{ rands::{Rand, StdRand}, @@ -10,8 +11,6 @@ use libafl::{ use crate::input::PacketData; -use lain::traits::Mutatable; - pub struct LainMutator { inner: lain::mutator::Mutator, } diff --git a/libafl/src/bolts/build_id.rs b/libafl/src/bolts/build_id.rs index 29a751dcfe..d45986a075 100644 --- a/libafl/src/bolts/build_id.rs +++ b/libafl/src/bolts/build_id.rs @@ -1,7 +1,6 @@ //! Based on //! (C) Alec Mocatta under license MIT or Apache 2 -use once_cell::sync::Lazy; use std::{ any::TypeId, env, @@ -9,6 +8,8 @@ use std::{ hash::{Hash, Hasher}, io, }; + +use once_cell::sync::Lazy; use uuid::Uuid; static BUILD_ID: Lazy = Lazy::new(calculate); diff --git a/libafl/src/bolts/cli.rs b/libafl/src/bolts/cli.rs index c2463eb2be..7e1698513f 100644 --- a/libafl/src/bolts/cli.rs +++ b/libafl/src/bolts/cli.rs @@ -69,15 +69,15 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; -use clap::{Command, CommandFactory, Parser}; -use serde::{Deserialize, Serialize}; #[cfg(feature = "frida_cli")] use std::error; use std::{net::SocketAddr, path::PathBuf, time::Duration}; -use crate::Error; +use clap::{Command, CommandFactory, Parser}; +use serde::{Deserialize, Serialize}; use super::core_affinity::Cores; +use crate::Error; /// helper function to go from a parsed cli string to a `Duration` fn parse_timeout(src: &str) -> Result { @@ -371,10 +371,11 @@ pub fn parse_args() -> FuzzerOptions { any(feature = "cli", feature = "qemu_cli", feature = "frida_cli") ))] mod tests { - use super::*; #[cfg(feature = "frida_cli")] use alloc::string::String; + use super::*; + /// pass a standard option and `--` followed by some options that `FuzzerOptions` doesn't know /// about; expect the standard option to work normally, and everything after `--` to be /// collected into `qemu_args` diff --git a/libafl/src/bolts/compress.rs b/libafl/src/bolts/compress.rs index 9d2fcb2399..1a9ca4cc98 100644 --- a/libafl/src/bolts/compress.rs +++ b/libafl/src/bolts/compress.rs @@ -1,13 +1,16 @@ //! Compression of events passed between a broker and clients. //! Currently we use the gzip compression algorithm for its fast decompression performance. -use crate::Error; use alloc::vec::Vec; use core::fmt::Debug; + use miniz_oxide::{ - deflate::compress_to_vec, deflate::CompressionLevel, inflate::decompress_to_vec, + deflate::{compress_to_vec, CompressionLevel}, + inflate::decompress_to_vec, }; +use crate::Error; + /// Compression for your stream compression needs. #[derive(Debug)] pub struct GzipCompressor { diff --git a/libafl/src/bolts/core_affinity.rs b/libafl/src/bolts/core_affinity.rs index 2dcbc98bf7..85575929a8 100644 --- a/libafl/src/bolts/core_affinity.rs +++ b/libafl/src/bolts/core_affinity.rs @@ -33,6 +33,7 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; + use serde::{Deserialize, Serialize}; use crate::Error; @@ -206,11 +207,12 @@ fn set_for_current_helper(core_id: CoreId) -> Result<(), Error> { #[cfg(any(target_os = "android", target_os = "linux"))] mod linux { - use super::CoreId; use alloc::{string::ToString, vec::Vec}; - use libc::{cpu_set_t, sched_getaffinity, sched_setaffinity, CPU_ISSET, CPU_SET, CPU_SETSIZE}; use std::mem; + use libc::{cpu_set_t, sched_getaffinity, sched_setaffinity, CPU_ISSET, CPU_SET, CPU_SETSIZE}; + + use super::CoreId; use crate::Error; #[allow(trivial_numeric_casts)] @@ -331,10 +333,14 @@ fn set_for_current_helper(core_id: CoreId) -> Result<(), Error> { #[cfg(target_os = "windows")] mod windows { - use crate::bolts::core_affinity::{CoreId, Error}; use alloc::vec::Vec; - use windows::Win32::System::SystemInformation::GROUP_AFFINITY; - use windows::Win32::System::Threading::{GetCurrentThread, SetThreadGroupAffinity}; + + use windows::Win32::System::{ + SystemInformation::GROUP_AFFINITY, + Threading::{GetCurrentThread, SetThreadGroupAffinity}, + }; + + use crate::bolts::core_affinity::{CoreId, Error}; pub fn get_core_ids() -> Result, Error> { let mut core_ids: Vec = Vec::new(); @@ -386,8 +392,7 @@ mod windows { #[allow(clippy::cast_ptr_alignment)] #[allow(clippy::cast_possible_wrap)] pub fn get_num_logical_cpus_ex_windows() -> Option { - use std::ptr; - use std::slice; + use std::{ptr, slice}; #[allow(non_upper_case_globals)] const RelationProcessorCore: u32 = 0; @@ -517,19 +522,19 @@ fn set_for_current_helper(core_id: CoreId) -> Result<(), Error> { #[cfg(target_vendor = "apple")] mod apple { + use alloc::vec::Vec; use core::ptr::addr_of_mut; use std::thread::available_parallelism; - use crate::Error; - - use super::CoreId; - use alloc::vec::Vec; use libc::{ integer_t, kern_return_t, mach_msg_type_number_t, pthread_mach_thread_np, pthread_self, thread_policy_flavor_t, thread_policy_t, thread_t, KERN_NOT_SUPPORTED, KERN_SUCCESS, THREAD_AFFINITY_POLICY, THREAD_AFFINITY_POLICY_COUNT, }; + use super::CoreId; + use crate::Error; + #[repr(C)] struct thread_affinity_policy_data_t { affinity_tag: integer_t, diff --git a/libafl/src/bolts/fs.rs b/libafl/src/bolts/fs.rs index 2064b81c47..27911b2a30 100644 --- a/libafl/src/bolts/fs.rs +++ b/libafl/src/bolts/fs.rs @@ -147,9 +147,10 @@ impl Drop for InputFile { #[cfg(test)] mod test { - use crate::bolts::fs::{write_file_atomic, InputFile}; use std::fs; + use crate::bolts::fs::{write_file_atomic, InputFile}; + #[test] fn test_atomic_file_write() { let path = "test_atomic_file_write.tmp"; diff --git a/libafl/src/bolts/launcher.rs b/libafl/src/bolts/launcher.rs index 14505456bb..a56aa483f9 100644 --- a/libafl/src/bolts/launcher.rs +++ b/libafl/src/bolts/launcher.rs @@ -10,38 +10,39 @@ //! On `Unix` systems, the [`Launcher`] will use `fork` if the `fork` feature is used for `LibAFL`. //! Else, it will start subsequent nodes with the same commandline, and will set special `env` variables accordingly. -#[cfg(all(feature = "std", any(windows, not(feature = "fork"))))] -use crate::bolts::os::startable_self; -#[cfg(all(unix, feature = "std", feature = "fork"))] -use crate::bolts::os::{dup2, fork, ForkResult}; -#[cfg(feature = "std")] -use crate::{ - bolts::{core_affinity::Cores, shmem::ShMemProvider}, - events::{EventConfig, LlmpRestartingEventManager, ManagerKind, RestartingMgr}, - inputs::Input, - monitors::Monitor, - observers::ObserversTuple, - Error, -}; - -#[cfg(all(feature = "std", any(windows, not(feature = "fork"))))] -use crate::bolts::core_affinity::CoreId; #[cfg(all(feature = "std"))] use alloc::string::ToString; use core::fmt::{self, Debug, Formatter}; #[cfg(feature = "std")] use core::marker::PhantomData; #[cfg(feature = "std")] -use serde::de::DeserializeOwned; -#[cfg(feature = "std")] use std::net::SocketAddr; #[cfg(all(feature = "std", any(windows, not(feature = "fork"))))] use std::process::Stdio; #[cfg(all(unix, feature = "std", feature = "fork"))] use std::{fs::File, os::unix::io::AsRawFd}; + +#[cfg(feature = "std")] +use serde::de::DeserializeOwned; #[cfg(feature = "std")] use typed_builder::TypedBuilder; +#[cfg(all(feature = "std", any(windows, not(feature = "fork"))))] +use crate::bolts::core_affinity::CoreId; +#[cfg(all(feature = "std", any(windows, not(feature = "fork"))))] +use crate::bolts::os::startable_self; +#[cfg(all(unix, feature = "std", feature = "fork"))] +use crate::bolts::os::{dup2, fork, ForkResult}; +#[cfg(feature = "std")] +use crate::{ + bolts::{core_affinity::Cores, shmem::ShMemProvider}, + events::{EventConfig, LlmpRestartingEventManager, ManagerKind, RestartingMgr}, + inputs::Input, + monitors::Monitor, + observers::ObserversTuple, + Error, +}; + /// The (internal) `env` that indicates we're running as client. const _AFL_LAUNCHER_CLIENT: &str = "AFL_LAUNCHER_CLIENT"; /// Provides a Launcher, which can be used to launch a fuzzing run on a specified list of cores diff --git a/libafl/src/bolts/llmp.rs b/libafl/src/bolts/llmp.rs index e89c70eaf0..b4bb3644ea 100644 --- a/libafl/src/bolts/llmp.rs +++ b/libafl/src/bolts/llmp.rs @@ -57,6 +57,8 @@ Check out the `llmp_test` example in ./examples, or build it with `cargo run --e */ +#[cfg(feature = "std")] +use alloc::string::ToString; use alloc::{string::String, vec::Vec}; #[cfg(not(target_pointer_width = "64"))] use core::sync::atomic::AtomicU32; @@ -71,10 +73,8 @@ use core::{ sync::atomic::{fence, AtomicU16, Ordering}, time::Duration, }; -use serde::{Deserialize, Serialize}; - -#[cfg(feature = "std")] -use alloc::string::ToString; +#[cfg(all(unix, feature = "std"))] +use std::os::unix::io::AsRawFd; #[cfg(feature = "std")] use std::{ env, @@ -86,6 +86,9 @@ use std::{ #[cfg(all(debug_assertions, feature = "llmp_debug", feature = "std"))] use backtrace::Backtrace; +#[cfg(all(unix, feature = "std"))] +use nix::sys::socket::{self, sockopt::ReusePort}; +use serde::{Deserialize, Serialize}; #[cfg(unix)] use crate::bolts::os::unix_signals::{ @@ -95,10 +98,6 @@ use crate::{ bolts::shmem::{ShMem, ShMemDescription, ShMemId, ShMemProvider}, Error, }; -#[cfg(all(unix, feature = "std"))] -use nix::sys::socket::{self, sockopt::ReusePort}; -#[cfg(all(unix, feature = "std"))] -use std::os::unix::io::AsRawFd; /// The max number of pages a [`client`] may have mapped that were not yet read by the [`broker`] /// Usually, this value should not exceed `1`, else the broker cannot keep up with the amount of incoming messages. @@ -2740,7 +2739,6 @@ mod tests { LlmpMsgHookResult::ForwardToClients, Tag, }; - use crate::bolts::shmem::{ShMemProvider, StdShMemProvider}; #[test] diff --git a/libafl/src/bolts/minibsod.rs b/libafl/src/bolts/minibsod.rs index e5a100df76..e0cd949a52 100644 --- a/libafl/src/bolts/minibsod.rs +++ b/libafl/src/bolts/minibsod.rs @@ -3,9 +3,10 @@ //! You may use the [`crate::bolts::os::unix_signals::ucontext`] //! function to get a [`ucontext_t`]. -use libc::siginfo_t; use std::io::{BufWriter, Write}; +use libc::siginfo_t; + use crate::bolts::os::unix_signals::{ucontext_t, Signal}; /// Write the content of all important registers diff --git a/libafl/src/bolts/mod.rs b/libafl/src/bolts/mod.rs index 6db7559ba7..aa8fbd4b4d 100644 --- a/libafl/src/bolts/mod.rs +++ b/libafl/src/bolts/mod.rs @@ -154,7 +154,6 @@ pub fn format_duration_hms(duration: &time::Duration) -> String { /// The purpose of this module is to alleviate imports of the bolts by adding a glob import. pub mod bolts_prelude { - pub use super::anymap::*; #[cfg(feature = "std")] pub use super::build_id::*; #[cfg(all( @@ -166,20 +165,15 @@ pub mod bolts_prelude { pub use super::compress::*; #[cfg(feature = "std")] pub use super::core_affinity::*; - pub use super::cpu::*; #[cfg(feature = "std")] pub use super::fs::*; #[cfg(feature = "std")] pub use super::launcher::*; - pub use super::llmp::*; #[cfg(all(feature = "std", unix))] pub use super::minibsod::*; - pub use super::os::*; - pub use super::ownedref::*; - pub use super::rands::*; - pub use super::serdeany::*; - pub use super::shmem::*; #[cfg(feature = "std")] pub use super::staterestore::*; - pub use super::tuples::*; + pub use super::{ + anymap::*, cpu::*, llmp::*, os::*, ownedref::*, rands::*, serdeany::*, shmem::*, tuples::*, + }; } diff --git a/libafl/src/bolts/os/mod.rs b/libafl/src/bolts/os/mod.rs index a7079d1ebf..2a9c5d9bcf 100644 --- a/libafl/src/bolts/os/mod.rs +++ b/libafl/src/bolts/os/mod.rs @@ -1,12 +1,12 @@ //! Operating System specific abstractions //! -#[cfg(any(unix, all(windows, feature = "std")))] -use crate::Error; - #[cfg(feature = "std")] use std::{env, process::Command}; +#[cfg(any(unix, all(windows, feature = "std")))] +use crate::Error; + #[cfg(all(unix, feature = "std"))] pub mod unix_shmem_server; diff --git a/libafl/src/bolts/os/pipes.rs b/libafl/src/bolts/os/pipes.rs index 486e5a65d4..c5a88e029e 100644 --- a/libafl/src/bolts/os/pipes.rs +++ b/libafl/src/bolts/os/pipes.rs @@ -1,13 +1,15 @@ //! Unix `pipe` wrapper for `LibAFL` -use crate::Error; -#[cfg(feature = "std")] -use nix::unistd::{close, pipe, read, write}; #[cfg(feature = "std")] use std::{ io::{self, ErrorKind, Read, Write}, os::unix::io::RawFd, }; +#[cfg(feature = "std")] +use nix::unistd::{close, pipe, read, write}; + +use crate::Error; + /// A unix pipe wrapper for `LibAFL` #[cfg(feature = "std")] #[derive(Debug, Clone)] diff --git a/libafl/src/bolts/os/unix_shmem_server.rs b/libafl/src/bolts/os/unix_shmem_server.rs index 755dfc8857..d630e71888 100644 --- a/libafl/src/bolts/os/unix_shmem_server.rs +++ b/libafl/src/bolts/os/unix_shmem_server.rs @@ -5,22 +5,14 @@ Hence, the `unix_shmem_server` keeps track of existing maps, creates new maps fo and forwards them over unix domain sockets. */ -use crate::{ - bolts::{ - shmem::{ShMem, ShMemDescription, ShMemId, ShMemProvider}, - AsMutSlice, AsSlice, - }, - Error, -}; - #[cfg(feature = "std")] use alloc::{ string::{String, ToString}, vec::Vec, }; use core::{mem::ManuallyDrop, ptr::addr_of}; -use hashbrown::HashMap; -use serde::{Deserialize, Serialize}; +#[cfg(target_vendor = "apple")] +use std::fs; use std::{ borrow::BorrowMut, cell::RefCell, @@ -31,13 +23,6 @@ use std::{ sync::{Arc, Condvar, Mutex}, thread::JoinHandle, }; - -#[cfg(target_vendor = "apple")] -use std::fs; - -#[cfg(all(feature = "std", unix))] -use nix::poll::{poll, PollFd, PollFlags}; - #[cfg(all(feature = "std", unix))] use std::{ os::unix::{ @@ -47,9 +32,21 @@ use std::{ thread, }; +use hashbrown::HashMap; +#[cfg(all(feature = "std", unix))] +use nix::poll::{poll, PollFd, PollFlags}; +use serde::{Deserialize, Serialize}; #[cfg(all(unix, feature = "std"))] use uds::{UnixListenerExt, UnixSocketAddr, UnixStreamExt}; +use crate::{ + bolts::{ + shmem::{ShMem, ShMemDescription, ShMemId, ShMemProvider}, + AsMutSlice, AsSlice, + }, + Error, +}; + /// The default server name for our abstract shmem server #[cfg(all(unix, not(target_vendor = "apple")))] const UNIX_SERVER_NAME: &str = "@libafl_unix_shmem_server"; diff --git a/libafl/src/bolts/os/unix_signals.rs b/libafl/src/bolts/os/unix_signals.rs index 1dd39649a2..1bc172c692 100644 --- a/libafl/src/bolts/os/unix_signals.rs +++ b/libafl/src/bolts/os/unix_signals.rs @@ -7,15 +7,14 @@ use core::{ ptr::{addr_of_mut, write_volatile}, sync::atomic::{compiler_fence, Ordering}, }; - -#[cfg(feature = "std")] -use nix::errno::{errno, Errno}; #[cfg(feature = "std")] use std::ffi::CString; /// armv7 `libc` does not feature a `uncontext_t` implementation #[cfg(target_arch = "arm")] pub use libc::c_ulong; +#[cfg(feature = "std")] +use nix::errno::{errno, Errno}; /// ARMv7-specific representation of a saved context #[cfg(target_arch = "arm")] @@ -234,21 +233,19 @@ pub struct ucontext_t { pub mcontext_data: mcontext64, } -pub use libc::{c_void, siginfo_t}; - +#[cfg(all(target_vendor = "apple", target_arch = "aarch64"))] +use libc::ssize_t; #[cfg(not(any( all(target_os = "linux", target_arch = "arm"), all(target_vendor = "apple", target_arch = "aarch64") )))] pub use libc::ucontext_t; - -#[cfg(all(target_vendor = "apple", target_arch = "aarch64"))] -use libc::ssize_t; use libc::{ c_int, malloc, sigaction, sigaddset, sigaltstack, sigemptyset, stack_t, SA_NODEFER, SA_ONSTACK, SA_SIGINFO, SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGHUP, SIGILL, SIGINT, SIGKILL, SIGPIPE, SIGQUIT, SIGSEGV, SIGTERM, SIGTRAP, SIGUSR2, }; +pub use libc::{c_void, siginfo_t}; use num_enum::{IntoPrimitive, TryFromPrimitive}; use crate::Error; diff --git a/libafl/src/bolts/os/windows_exceptions.rs b/libafl/src/bolts/os/windows_exceptions.rs index e50152bc21..7c41a8ba69 100644 --- a/libafl/src/bolts/os/windows_exceptions.rs +++ b/libafl/src/bolts/os/windows_exceptions.rs @@ -1,14 +1,5 @@ //! Exception handling for Windows -pub use windows::Win32::System::Diagnostics::Debug::{ - AddVectoredExceptionHandler, EXCEPTION_POINTERS, -}; - -pub use windows::Win32::Foundation::NTSTATUS; - -use crate::Error; -use std::os::raw::{c_long, c_void}; - use alloc::vec::Vec; use core::{ cell::UnsafeCell, @@ -17,8 +8,15 @@ use core::{ ptr::write_volatile, sync::atomic::{compiler_fence, Ordering}, }; +use std::os::raw::{c_long, c_void}; use num_enum::TryFromPrimitive; +pub use windows::Win32::{ + Foundation::NTSTATUS, + System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}, +}; + +use crate::Error; //const EXCEPTION_CONTINUE_EXECUTION: c_long = -1; //const EXCEPTION_CONTINUE_SEARCH: c_long = 0; diff --git a/libafl/src/bolts/ownedref.rs b/libafl/src/bolts/ownedref.rs index 4aa2c34f6e..1fbe45865b 100644 --- a/libafl/src/bolts/ownedref.rs +++ b/libafl/src/bolts/ownedref.rs @@ -1,15 +1,17 @@ //! Wrappers that abstracts references (or pointers) and owned data accesses. // The serialization is towards owned, allowing to serialize pointers without troubles. -use crate::bolts::{AsMutSlice, AsSlice}; use alloc::{ boxed::Box, slice::{Iter, IterMut}, vec::Vec, }; use core::{clone::Clone, fmt::Debug, slice}; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use crate::bolts::{AsMutSlice, AsSlice}; + /// Trait to convert into an Owned type pub trait IntoOwned { /// Returns if the current type is an owned type. diff --git a/libafl/src/bolts/rands.rs b/libafl/src/bolts/rands.rs index c0474e6815..d3027497bf 100644 --- a/libafl/src/bolts/rands.rs +++ b/libafl/src/bolts/rands.rs @@ -1,14 +1,14 @@ //! The random number generators of `LibAFL` use core::{debug_assert, fmt::Debug}; + +#[cfg(feature = "rand_trait")] +use rand_core::{self, impls::fill_bytes_via_next, RngCore}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use xxhash_rust::xxh3::xxh3_64_with_seed; #[cfg(feature = "std")] use crate::bolts::current_nanos; -#[cfg(feature = "rand_trait")] -use rand_core::{self, impls::fill_bytes_via_next, RngCore}; - const HASH_CONST: u64 = 0xa5b35705; /// The standard rand implementation for `LibAFL`. @@ -417,8 +417,9 @@ mod tests { #[test] #[cfg(feature = "rand_trait")] fn test_rgn_core_support() { - use crate::bolts::rands::StdRand; use rand_core::RngCore; + + use crate::bolts::rands::StdRand; pub struct Mutator { rng: R, } @@ -435,11 +436,12 @@ mod tests { #[allow(missing_docs)] /// `Rand` Python bindings pub mod pybind { - use super::Rand; - use crate::bolts::{current_nanos, rands::StdRand}; use pyo3::prelude::*; use serde::{Deserialize, Serialize}; + use super::Rand; + use crate::bolts::{current_nanos, rands::StdRand}; + #[pyclass(unsendable, name = "StdRand")] #[derive(Serialize, Deserialize, Debug, Clone)] /// Python class for StdRand diff --git a/libafl/src/bolts/serdeany.rs b/libafl/src/bolts/serdeany.rs index 6803949870..60d6bee70a 100644 --- a/libafl/src/bolts/serdeany.rs +++ b/libafl/src/bolts/serdeany.rs @@ -1,10 +1,10 @@ //! Poor-rust-man's downcasts for stuff we send over the wire (or shared maps) -use serde::{de::DeserializeSeed, Deserialize, Deserializer, Serialize, Serializer}; - use alloc::boxed::Box; use core::{any::Any, fmt::Debug}; +use serde::{de::DeserializeSeed, Deserialize, Deserializer, Serialize, Serializer}; + /// A (de)serializable Any trait pub trait SerdeAny: Any + erased_serde::Serialize + Debug { /// returns this as Any trait @@ -69,19 +69,21 @@ macro_rules! create_serde_registry_for_trait { pub mod $mod_name { use alloc::boxed::Box; - use core::any::TypeId; - use core::fmt; + use core::{any::TypeId, fmt}; + + use hashbrown::{ + hash_map::{Keys, Values, ValuesMut}, + HashMap, + }; use postcard; use serde::{Deserialize, Serialize}; - - use hashbrown::hash_map::{Keys, Values, ValuesMut}; - use hashbrown::HashMap; - - use $crate::bolts::{ - anymap::{pack_type_id, unpack_type_id}, - serdeany::{DeserializeCallback, DeserializeCallbackSeed}, + use $crate::{ + bolts::{ + anymap::{pack_type_id, unpack_type_id}, + serdeany::{DeserializeCallback, DeserializeCallbackSeed}, + }, + Error, }; - use $crate::Error; /// Visitor object used internally for the [`SerdeAny`] registry. #[derive(Debug)] diff --git a/libafl/src/bolts/shmem.rs b/libafl/src/bolts/shmem.rs index 88f89856ad..f5b9881584 100644 --- a/libafl/src/bolts/shmem.rs +++ b/libafl/src/bolts/shmem.rs @@ -1,19 +1,12 @@ //! A generic shared memory region to be used by any functions (queues or feedbacks //! too.) -#[cfg(all(unix, feature = "std"))] -use crate::bolts::os::pipes::Pipe; -use crate::{ - bolts::{AsMutSlice, AsSlice}, - Error, -}; use alloc::{rc::Rc, string::ToString}; use core::{ cell::RefCell, fmt::{self, Debug, Display}, mem::ManuallyDrop, }; -use serde::{Deserialize, Serialize}; #[cfg(feature = "std")] use std::env; #[cfg(all(unix, feature = "std"))] @@ -21,17 +14,22 @@ use std::io::Read; #[cfg(feature = "std")] use std::io::Write; +use serde::{Deserialize, Serialize}; #[cfg(all(feature = "std", unix, not(target_os = "android")))] pub use unix_shmem::{MmapShMem, MmapShMemProvider}; - #[cfg(all(feature = "std", unix))] pub use unix_shmem::{UnixShMem, UnixShMemProvider}; - #[cfg(all(windows, feature = "std"))] pub use win32_shmem::{Win32ShMem, Win32ShMemProvider}; +#[cfg(all(unix, feature = "std"))] +use crate::bolts::os::pipes::Pipe; #[cfg(all(feature = "std", unix))] pub use crate::bolts::os::unix_shmem_server::{ServedShMemProvider, ShMemService}; +use crate::{ + bolts::{AsMutSlice, AsSlice}, + Error, +}; /// The standard sharedmem provider #[cfg(all(windows, feature = "std"))] @@ -541,11 +539,12 @@ pub mod unix_shmem { use alloc::string::ToString; use core::{ptr, slice}; + use std::{io::Write, process}; + use libc::{ c_int, c_long, c_uchar, c_uint, c_ulong, c_ushort, close, ftruncate, mmap, munmap, perror, shm_open, shm_unlink, shmat, shmctl, shmget, }; - use std::{io::Write, process}; use crate::{ bolts::{ @@ -922,11 +921,12 @@ pub mod unix_shmem { pub mod ashmem { use alloc::string::ToString; use core::{ptr, slice}; + use std::ffi::CString; + use libc::{ c_uint, c_ulong, c_void, close, ioctl, mmap, open, MAP_SHARED, O_RDWR, PROT_READ, PROT_WRITE, }; - use std::ffi::CString; use crate::{ bolts::{ @@ -1146,30 +1146,33 @@ pub mod unix_shmem { #[cfg(all(feature = "std", windows))] pub mod win32_shmem { - use crate::{ - bolts::{ - shmem::{ShMem, ShMemId, ShMemProvider}, - AsMutSlice, AsSlice, - }, - Error, - }; - use alloc::string::String; use core::{ ffi::c_void, fmt::{self, Debug, Formatter}, ptr, slice, }; + use uuid::Uuid; + use crate::{ + bolts::{ + shmem::{ShMem, ShMemId, ShMemProvider}, + AsMutSlice, AsSlice, + }, + Error, + }; + const INVALID_HANDLE_VALUE: isize = -1; use windows::{ core::PCSTR, - Win32::Foundation::{CloseHandle, BOOL, HANDLE}, - Win32::System::Memory::{ - CreateFileMappingA, MapViewOfFile, OpenFileMappingA, UnmapViewOfFile, - FILE_MAP_ALL_ACCESS, PAGE_READWRITE, + Win32::{ + Foundation::{CloseHandle, BOOL, HANDLE}, + System::Memory::{ + CreateFileMappingA, MapViewOfFile, OpenFileMappingA, UnmapViewOfFile, + FILE_MAP_ALL_ACCESS, PAGE_READWRITE, + }, }, }; diff --git a/libafl/src/bolts/staterestore.rs b/libafl/src/bolts/staterestore.rs index 6392c5391c..102e466572 100644 --- a/libafl/src/bolts/staterestore.rs +++ b/libafl/src/bolts/staterestore.rs @@ -1,9 +1,7 @@ //! Stores and restores state when a client needs to relaunch. //! Uses a [`ShMem`] up to a threshold, then write to disk. -use ahash::AHasher; use alloc::string::{String, ToString}; use core::{hash::Hasher, marker::PhantomData, mem::size_of, ptr, slice}; -use serde::{de::DeserializeOwned, Serialize}; use std::{ env::temp_dir, fs::{self, File}, @@ -12,6 +10,9 @@ use std::{ ptr::read_volatile, }; +use ahash::AHasher; +use serde::{de::DeserializeOwned, Serialize}; + use crate::{ bolts::{ shmem::{ShMem, ShMemProvider}, @@ -246,6 +247,7 @@ mod tests { string::{String, ToString}, vec::Vec, }; + use serial_test::serial; use crate::bolts::{ diff --git a/libafl/src/bolts/tuples.rs b/libafl/src/bolts/tuples.rs index 2dc59ed63a..1896f8f7ac 100644 --- a/libafl/src/bolts/tuples.rs +++ b/libafl/src/bolts/tuples.rs @@ -1,12 +1,11 @@ //! Compiletime lists/tuples used throughout the `LibAFL` universe -pub use tuple_list::{tuple_list, tuple_list_type, TupleList}; - use core::{ any::TypeId, ptr::{addr_of, addr_of_mut}, }; +pub use tuple_list::{tuple_list, tuple_list_type, TupleList}; use xxhash_rust::xxh3::xxh3_64; /// Returns if the type `T` is equal to `U` diff --git a/libafl/src/corpus/cached.rs b/libafl/src/corpus/cached.rs index e100dcd139..8ebbc5555c 100644 --- a/libafl/src/corpus/cached.rs +++ b/libafl/src/corpus/cached.rs @@ -2,9 +2,10 @@ use alloc::collections::vec_deque::VecDeque; use core::cell::RefCell; -use serde::{Deserialize, Serialize}; use std::path::PathBuf; +use serde::{Deserialize, Serialize}; + use crate::{ corpus::{ ondisk::{OnDiskCorpus, OnDiskMetadataFormat}, @@ -137,11 +138,16 @@ where /// ``CachedOnDiskCorpus`` Python bindings #[cfg(feature = "python")] pub mod pybind { - use crate::{corpus::pybind::PythonCorpus, corpus::CachedOnDiskCorpus, inputs::BytesInput}; use alloc::string::String; + use std::path::PathBuf; + use pyo3::prelude::*; use serde::{Deserialize, Serialize}; - use std::path::PathBuf; + + use crate::{ + corpus::{pybind::PythonCorpus, CachedOnDiskCorpus}, + inputs::BytesInput, + }; #[pyclass(unsendable, name = "CachedOnDiskCorpus")] #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/libafl/src/corpus/inmemory.rs b/libafl/src/corpus/inmemory.rs index d353b9984f..d020b4e9fc 100644 --- a/libafl/src/corpus/inmemory.rs +++ b/libafl/src/corpus/inmemory.rs @@ -2,9 +2,14 @@ use alloc::vec::Vec; use core::cell::RefCell; + use serde::{Deserialize, Serialize}; -use crate::{corpus::Corpus, corpus::Testcase, inputs::Input, Error}; +use crate::{ + corpus::{Corpus, Testcase}, + inputs::Input, + Error, +}; /// A corpus handling all in memory. #[derive(Default, Serialize, Deserialize, Clone, Debug)] @@ -91,12 +96,13 @@ where /// `InMemoryCorpus` Python bindings #[cfg(feature = "python")] pub mod pybind { + use pyo3::prelude::*; + use serde::{Deserialize, Serialize}; + use crate::{ corpus::{pybind::PythonCorpus, InMemoryCorpus}, inputs::BytesInput, }; - use pyo3::prelude::*; - use serde::{Deserialize, Serialize}; #[pyclass(unsendable, name = "InMemoryCorpus")] #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/libafl/src/corpus/mod.rs b/libafl/src/corpus/mod.rs index 892e0feb95..6d7744db4e 100644 --- a/libafl/src/corpus/mod.rs +++ b/libafl/src/corpus/mod.rs @@ -13,11 +13,11 @@ pub use ondisk::OnDiskCorpus; #[cfg(feature = "std")] pub mod cached; +use core::cell::RefCell; + #[cfg(feature = "std")] pub use cached::CachedOnDiskCorpus; -use core::cell::RefCell; - use crate::{inputs::Input, Error}; /// Corpus with all current testcases @@ -56,6 +56,11 @@ where #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { + use std::cell::RefCell; + + use pyo3::prelude::*; + use serde::{Deserialize, Serialize}; + use crate::{ corpus::{ cached::pybind::PythonCachedOnDiskCorpus, inmemory::pybind::PythonInMemoryCorpus, @@ -65,9 +70,6 @@ pub mod pybind { inputs::BytesInput, Error, }; - use pyo3::prelude::*; - use serde::{Deserialize, Serialize}; - use std::cell::RefCell; #[derive(Serialize, Deserialize, Debug, Clone)] enum PythonCorpusWrapper { diff --git a/libafl/src/corpus/ondisk.rs b/libafl/src/corpus/ondisk.rs index 8126bade8a..882478f462 100644 --- a/libafl/src/corpus/ondisk.rs +++ b/libafl/src/corpus/ondisk.rs @@ -2,18 +2,21 @@ use alloc::vec::Vec; use core::{cell::RefCell, time::Duration}; -use serde::{Deserialize, Serialize}; +#[cfg(feature = "std")] +use std::{fs, fs::File, io::Write}; use std::{ fs::OpenOptions, path::{Path, PathBuf}, }; -#[cfg(feature = "std")] -use std::{fs, fs::File, io::Write}; +use serde::{Deserialize, Serialize}; use crate::{ - bolts::serdeany::SerdeAnyMap, corpus::Corpus, corpus::Testcase, inputs::Input, - state::HasMetadata, Error, + bolts::serdeany::SerdeAnyMap, + corpus::{Corpus, Testcase}, + inputs::Input, + state::HasMetadata, + Error, }; /// Options for the the format of the on-disk metadata @@ -208,14 +211,16 @@ where #[cfg(feature = "python")] /// `OnDiskCorpus` Python bindings pub mod pybind { + use alloc::string::String; + use std::path::PathBuf; + + use pyo3::prelude::*; + use serde::{Deserialize, Serialize}; + use crate::{ corpus::{pybind::PythonCorpus, OnDiskCorpus}, inputs::BytesInput, }; - use alloc::string::String; - use pyo3::prelude::*; - use serde::{Deserialize, Serialize}; - use std::path::PathBuf; #[pyclass(unsendable, name = "OnDiskCorpus")] #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/libafl/src/corpus/testcase.rs b/libafl/src/corpus/testcase.rs index d01d5d6044..c9ae06883f 100644 --- a/libafl/src/corpus/testcase.rs +++ b/libafl/src/corpus/testcase.rs @@ -3,6 +3,7 @@ use alloc::string::String; use core::{convert::Into, default::Default, option::Option, time::Duration}; + use serde::{Deserialize, Serialize}; use crate::{ @@ -350,14 +351,16 @@ crate::impl_serdeany!(SchedulerTestcaseMetaData); #[allow(missing_docs)] /// `Testcase` Python bindings pub mod pybind { + use alloc::{boxed::Box, vec::Vec}; + + use pyo3::{prelude::*, types::PyDict}; + use super::{HasMetadata, Testcase}; use crate::{ bolts::ownedref::OwnedPtrMut, inputs::{BytesInput, HasBytesVec}, pybind::PythonMetadata, }; - use alloc::{boxed::Box, vec::Vec}; - use pyo3::{prelude::*, types::PyDict}; /// `PythonTestcase` with fixed generics pub type PythonTestcase = Testcase; diff --git a/libafl/src/events/llmp.rs b/libafl/src/events/llmp.rs index c108ad87be..dc0a294b09 100644 --- a/libafl/src/events/llmp.rs +++ b/libafl/src/events/llmp.rs @@ -1,5 +1,23 @@ //! LLMP-backed event manager for scalable multi-processed fuzzing +use alloc::{ + boxed::Box, + string::{String, ToString}, + vec::Vec, +}; +#[cfg(feature = "std")] +use core::sync::atomic::{compiler_fence, Ordering}; +use core::{marker::PhantomData, time::Duration}; +#[cfg(feature = "std")] +use std::net::{SocketAddr, ToSocketAddrs}; + +use serde::de::DeserializeOwned; +#[cfg(feature = "std")] +use serde::Serialize; +#[cfg(feature = "std")] +use typed_builder::TypedBuilder; + +use super::{CustomBufEventResult, CustomBufHandlerFn}; #[cfg(feature = "std")] use crate::bolts::core_affinity::CoreId; #[cfg(all(feature = "std", any(windows, not(feature = "fork"))))] @@ -29,23 +47,6 @@ use crate::{ observers::ObserversTuple, Error, }; -use alloc::{ - boxed::Box, - string::{String, ToString}, - vec::Vec, -}; -#[cfg(feature = "std")] -use core::sync::atomic::{compiler_fence, Ordering}; -use core::{marker::PhantomData, time::Duration}; -use serde::de::DeserializeOwned; -#[cfg(feature = "std")] -use serde::Serialize; -#[cfg(feature = "std")] -use std::net::{SocketAddr, ToSocketAddrs}; -#[cfg(feature = "std")] -use typed_builder::TypedBuilder; - -use super::{CustomBufEventResult, CustomBufHandlerFn}; /// Forward this to the client const _LLMP_TAG_EVENT_TO_CLIENT: Tag = 0x2C11E471; @@ -990,6 +991,8 @@ where #[cfg(test)] #[cfg(feature = "std")] mod tests { + use core::sync::atomic::{compiler_fence, Ordering}; + use serial_test::serial; use crate::{ @@ -1010,7 +1013,6 @@ mod tests { state::StdState, Fuzzer, StdFuzzer, }; - use core::sync::atomic::{compiler_fence, Ordering}; #[test] #[serial] diff --git a/libafl/src/events/mod.rs b/libafl/src/events/mod.rs index 545473752c..cc883d9ee9 100644 --- a/libafl/src/events/mod.rs +++ b/libafl/src/events/mod.rs @@ -3,17 +3,16 @@ pub mod simple; pub use simple::*; pub mod llmp; -pub use llmp::*; - -use ahash::AHasher; use alloc::{ boxed::Box, string::{String, ToString}, vec::Vec, }; use core::{fmt, hash::Hasher, marker::PhantomData, time::Duration}; -use serde::{Deserialize, Serialize}; +use ahash::AHasher; +pub use llmp::*; +use serde::{Deserialize, Serialize}; #[cfg(feature = "std")] use uuid::Uuid; @@ -582,6 +581,8 @@ mod tests { #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { + use pyo3::prelude::*; + use crate::{ events::{ simple::pybind::PythonSimpleEventManager, Event, EventFirer, EventManager, @@ -593,7 +594,6 @@ pub mod pybind { state::pybind::PythonStdState, Error, }; - use pyo3::prelude::*; #[derive(Debug, Clone)] pub enum PythonEventManagerWrapper { diff --git a/libafl/src/events/simple.rs b/libafl/src/events/simple.rs index 03fdc42945..4c1d6b4732 100644 --- a/libafl/src/events/simple.rs +++ b/libafl/src/events/simple.rs @@ -1,14 +1,5 @@ //! A very simple event manager, that just supports log outputs, but no multiprocessing -use crate::{ - events::{ - BrokerEventResult, Event, EventFirer, EventManager, EventManagerId, EventProcessor, - EventRestarter, HasEventManagerId, - }, - inputs::Input, - monitors::Monitor, - Error, -}; use alloc::{ boxed::Box, string::{String, ToString}, @@ -17,9 +8,11 @@ use alloc::{ #[cfg(feature = "std")] use core::sync::atomic::{compiler_fence, Ordering}; use core::{fmt::Debug, marker::PhantomData}; + #[cfg(feature = "std")] use serde::{de::DeserializeOwned, Serialize}; +use super::{CustomBufEventResult, CustomBufHandlerFn, HasCustomBufHandlers, ProgressReporter}; #[cfg(all(feature = "std", any(windows, not(feature = "fork"))))] use crate::bolts::os::startable_self; #[cfg(all(feature = "std", feature = "fork", unix))] @@ -31,8 +24,15 @@ use crate::{ executors::Executor, state::{HasCorpus, HasSolutions}, }; - -use super::{CustomBufEventResult, CustomBufHandlerFn, HasCustomBufHandlers, ProgressReporter}; +use crate::{ + events::{ + BrokerEventResult, Event, EventFirer, EventManager, EventManagerId, EventProcessor, + EventRestarter, HasEventManagerId, + }, + inputs::Input, + monitors::Monitor, + Error, +}; /// The llmp connection from the actual fuzzer to the process supervising it const _ENV_FUZZER_SENDER: &str = "_AFL_ENV_FUZZER_SENDER"; @@ -494,11 +494,14 @@ where #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { + use pyo3::prelude::*; + use crate::{ - events::pybind::PythonEventManager, events::SimpleEventManager, inputs::BytesInput, - monitors::pybind::PythonMonitor, state::pybind::PythonStdState, + events::{pybind::PythonEventManager, SimpleEventManager}, + inputs::BytesInput, + monitors::pybind::PythonMonitor, + state::pybind::PythonStdState, }; - use pyo3::prelude::*; #[pyclass(unsendable, name = "SimpleEventManager")] #[derive(Debug)] diff --git a/libafl/src/executors/combined.rs b/libafl/src/executors/combined.rs index ba68356a42..d41f83040b 100644 --- a/libafl/src/executors/combined.rs +++ b/libafl/src/executors/combined.rs @@ -1,13 +1,14 @@ //! A `CombinedExecutor` wraps a primary executor and a secondary one //! In comparison to the [`crate::executors::DiffExecutor`] it does not run the secondary executor in `run_target`. +use core::fmt::Debug; + use crate::{ executors::{Executor, ExitKind, HasObservers}, inputs::Input, observers::ObserversTuple, Error, }; -use core::fmt::Debug; /// A [`CombinedExecutor`] wraps a primary executor, forwarding its methods, and a secondary one #[derive(Debug)] diff --git a/libafl/src/executors/command.rs b/libafl/src/executors/command.rs index 2db7822f3d..d3662dcb49 100644 --- a/libafl/src/executors/command.rs +++ b/libafl/src/executors/command.rs @@ -1,15 +1,16 @@ //! The command executor executes a sub program for each run +#[cfg(feature = "std")] +use alloc::{borrow::ToOwned, string::String, vec::Vec}; use core::{ fmt::{self, Debug, Formatter}, marker::PhantomData, }; - -#[cfg(feature = "std")] -use alloc::{borrow::ToOwned, string::String, vec::Vec}; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; #[cfg(feature = "std")] use std::process::Child; +#[cfg(all(feature = "std", unix))] +use std::time::Duration; use std::{ ffi::{OsStr, OsString}, io::{Read, Write}, @@ -17,6 +18,9 @@ use std::{ process::{Command, Stdio}, }; +use super::HasObservers; +#[cfg(all(feature = "std", unix))] +use crate::executors::{Executor, ExitKind}; use crate::{ bolts::{ fs::{InputFile, INPUTFILE_STD}, @@ -29,14 +33,6 @@ use crate::{ #[cfg(feature = "std")] use crate::{inputs::Input, Error}; -#[cfg(all(feature = "std", unix))] -use crate::executors::{Executor, ExitKind}; - -#[cfg(all(feature = "std", unix))] -use std::time::Duration; - -use super::HasObservers; - /// How to deliver input to an external program /// `StdIn`: The traget reads from stdin /// `File`: The target reads from the specified [`InputFile`] @@ -320,6 +316,7 @@ where input: &I, ) -> Result { use std::os::unix::prelude::ExitStatusExt; + use wait_timeout::ChildExt; let mut child = self.configurer.spawn_child(input)?; diff --git a/libafl/src/executors/differential.rs b/libafl/src/executors/differential.rs index 61af045523..feae0af1fd 100644 --- a/libafl/src/executors/differential.rs +++ b/libafl/src/executors/differential.rs @@ -2,13 +2,14 @@ //! It wraps two exeutors that will be run after each other with the same input. //! In comparison to the [`crate::executors::CombinedExecutor`] it also runs the secondary executor in `run_target`. //! +use core::fmt::Debug; + use crate::{ executors::{Executor, ExitKind, HasObservers}, inputs::Input, observers::ObserversTuple, Error, }; -use core::fmt::Debug; /// A [`DiffExecutor`] wraps a primary executor, forwarding its methods, and a secondary one #[derive(Debug)] diff --git a/libafl/src/executors/forkserver.rs b/libafl/src/executors/forkserver.rs index a3d9fdedc8..641aca1905 100644 --- a/libafl/src/executors/forkserver.rs +++ b/libafl/src/executors/forkserver.rs @@ -1,5 +1,6 @@ //! Expose an `Executor` based on a `Forkserver` in order to execute AFL/AFL++ binaries +use alloc::{borrow::ToOwned, string::ToString, vec::Vec}; use core::{ fmt::{self, Debug, Formatter}, marker::PhantomData, @@ -13,6 +14,15 @@ use std::{ process::{Command, Stdio}, }; +use nix::{ + sys::{ + select::{pselect, FdSet}, + signal::{kill, SigSet, Signal}, + time::{TimeSpec, TimeValLike}, + }, + unistd::Pid, +}; + use crate::{ bolts::{ fs::{InputFile, INPUTFILE_STD}, @@ -27,16 +37,6 @@ use crate::{ Error, }; -use alloc::{borrow::ToOwned, string::ToString, vec::Vec}; -use nix::{ - sys::{ - select::{pselect, FdSet}, - signal::{kill, SigSet, Signal}, - time::{TimeSpec, TimeValLike}, - }, - unistd::Pid, -}; - const FORKSRV_FD: i32 = 198; #[allow(clippy::cast_possible_wrap)] const FS_OPT_ENABLED: i32 = 0x80000001_u32 as i32; @@ -1011,6 +1011,10 @@ where #[cfg(test)] mod tests { + use std::ffi::OsString; + + use serial_test::serial; + use crate::{ bolts::{ shmem::{ShMem, ShMemProvider, StdShMemProvider}, @@ -1022,8 +1026,6 @@ mod tests { observers::{ConstMapObserver, HitcountsMapObserver}, Error, }; - use serial_test::serial; - use std::ffi::OsString; #[test] #[serial] fn test_forkserver() { diff --git a/libafl/src/executors/inprocess.rs b/libafl/src/executors/inprocess.rs index 49c2d60a7f..242ba2ce54 100644 --- a/libafl/src/executors/inprocess.rs +++ b/libafl/src/executors/inprocess.rs @@ -3,6 +3,9 @@ //! //! Needs the `fork` feature flag. +use alloc::boxed::Box; +#[cfg(all(unix, feature = "std"))] +use alloc::vec::Vec; use core::{ borrow::BorrowMut, ffi::c_void, @@ -10,42 +13,32 @@ use core::{ marker::PhantomData, ptr, }; - #[cfg(any(unix, all(windows, feature = "std")))] use core::{ ptr::write_volatile, sync::atomic::{compiler_fence, Ordering}, }; - -use alloc::boxed::Box; -#[cfg(all(unix, feature = "std"))] -use alloc::vec::Vec; - #[cfg(all(feature = "std", unix))] use std::intrinsics::transmute; #[cfg(all(feature = "std", unix))] use libc::siginfo_t; - #[cfg(all(feature = "std", unix))] use nix::{ sys::wait::{waitpid, WaitStatus}, unistd::{fork, ForkResult}, }; +#[cfg(windows)] +use windows::Win32::System::Threading::SetThreadStackGuarantee; #[cfg(unix)] use crate::bolts::os::unix_signals::setup_signal_handler; +#[cfg(all(feature = "std", unix))] +use crate::bolts::os::unix_signals::{ucontext_t, Handler, Signal}; #[cfg(all(windows, feature = "std"))] use crate::bolts::os::windows_exceptions::setup_exception_handler; #[cfg(all(feature = "std", unix))] use crate::bolts::shmem::ShMemProvider; - -#[cfg(windows)] -use windows::Win32::System::Threading::SetThreadStackGuarantee; - -#[cfg(all(feature = "std", unix))] -use crate::bolts::os::unix_signals::{ucontext_t, Handler, Signal}; - use crate::{ events::{EventFirer, EventRestarter}, executors::{Executor, ExitKind, HasObservers}, @@ -512,13 +505,14 @@ mod unix_signal_handler { #[cfg(feature = "std")] use alloc::{boxed::Box, string::String}; use core::mem::transmute; - use libc::siginfo_t; #[cfg(feature = "std")] use std::{ io::{stdout, Write}, panic, }; + use libc::siginfo_t; + use crate::{ bolts::os::unix_signals::{ucontext_t, Handler, Signal}, corpus::{Corpus, Testcase}, @@ -860,16 +854,21 @@ mod unix_signal_handler { mod windows_exception_handler { #[cfg(feature = "std")] use alloc::boxed::Box; - use alloc::string::String; - use alloc::vec::Vec; - use core::ffi::c_void; - use core::{mem::transmute, ptr}; + use alloc::{string::String, vec::Vec}; + use core::{ + ffi::c_void, + mem::transmute, + ptr, + sync::atomic::{compiler_fence, Ordering}, + }; #[cfg(feature = "std")] use std::{ io::{stdout, Write}, panic, }; + use windows::Win32::System::Threading::ExitProcess; + use crate::{ bolts::os::windows_exceptions::{ ExceptionCode, Handler, CRASH_EXCEPTIONS, EXCEPTION_POINTERS, @@ -887,9 +886,6 @@ mod windows_exception_handler { state::{HasClientPerfMonitor, HasMetadata, HasSolutions}, }; - use core::sync::atomic::{compiler_fence, Ordering}; - use windows::Win32::System::Threading::ExitProcess; - pub(crate) type HandlerFuncPtr = unsafe fn(*mut EXCEPTION_POINTERS, &mut InProcessExecutorHandlerData); @@ -1560,12 +1556,11 @@ where #[cfg(all(feature = "std", unix))] pub mod child_signal_handlers { use alloc::boxed::Box; - use libc::siginfo_t; use std::panic; - use super::InProcessForkExecutorGlobalData; + use libc::siginfo_t; - use super::FORK_EXECUTOR_GLOBAL_DATA; + use super::{InProcessForkExecutorGlobalData, FORK_EXECUTOR_GLOBAL_DATA}; use crate::{ bolts::os::unix_signals::{ucontext_t, Signal}, executors::{ExitKind, HasObservers}, @@ -1633,6 +1628,7 @@ pub mod child_signal_handlers { #[cfg(test)] mod tests { use core::marker::PhantomData; + use serial_test::serial; #[cfg(all(feature = "std", feature = "fork", unix))] @@ -1689,6 +1685,10 @@ mod tests { #[allow(missing_docs)] /// `InProcess` Python bindings pub mod pybind { + use alloc::boxed::Box; + + use pyo3::{prelude::*, types::PyBytes}; + use crate::{ events::pybind::PythonEventManager, executors::{inprocess::OwnedInProcessExecutor, pybind::PythonExecutor, ExitKind}, @@ -1697,8 +1697,6 @@ pub mod pybind { observers::pybind::PythonObserversTuple, state::pybind::{PythonStdState, PythonStdStateWrapper}, }; - use alloc::boxed::Box; - use pyo3::{prelude::*, types::PyBytes}; #[pyclass(unsendable, name = "InProcessExecutor")] #[derive(Debug)] diff --git a/libafl/src/executors/mod.rs b/libafl/src/executors/mod.rs index 46b53d6766..37dcf74d37 100644 --- a/libafl/src/executors/mod.rs +++ b/libafl/src/executors/mod.rs @@ -31,8 +31,11 @@ pub use with_observers::WithObservers; #[cfg(all(feature = "std", unix))] pub mod command; +use core::fmt::Debug; + #[cfg(all(feature = "std", unix))] pub use command::CommandExecutor; +use serde::{Deserialize, Serialize}; use crate::{ bolts::AsSlice, @@ -41,9 +44,6 @@ use crate::{ Error, }; -use core::fmt::Debug; -use serde::{Deserialize, Serialize}; - /// How an execution finished. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] pub enum ExitKind { @@ -189,17 +189,21 @@ mod test { #[allow(missing_docs)] /// `Executor` Python bindings pub mod pybind { - use crate::events::pybind::PythonEventManager; - use crate::executors::inprocess::pybind::PythonOwnedInProcessExecutor; - use crate::executors::{Executor, ExitKind, HasObservers}; - use crate::fuzzer::pybind::{PythonStdFuzzer, PythonStdFuzzerWrapper}; - use crate::inputs::{BytesInput, HasBytesVec}; - use crate::observers::pybind::PythonObserversTuple; - use crate::state::pybind::{PythonStdState, PythonStdStateWrapper}; - use crate::Error; use pyo3::prelude::*; use serde::{Deserialize, Serialize}; + use crate::{ + events::pybind::PythonEventManager, + executors::{ + inprocess::pybind::PythonOwnedInProcessExecutor, Executor, ExitKind, HasObservers, + }, + fuzzer::pybind::{PythonStdFuzzer, PythonStdFuzzerWrapper}, + inputs::{BytesInput, HasBytesVec}, + observers::pybind::PythonObserversTuple, + state::pybind::{PythonStdState, PythonStdStateWrapper}, + Error, + }; + #[pyclass(unsendable, name = "ExitKind")] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PythonExitKind { diff --git a/libafl/src/executors/timeout.rs b/libafl/src/executors/timeout.rs index 8db52ec08a..55943d5bbc 100644 --- a/libafl/src/executors/timeout.rs +++ b/libafl/src/executors/timeout.rs @@ -1,30 +1,24 @@ //! A `TimeoutExecutor` sets a timeout before each target run +#[cfg(target_os = "linux")] +use core::ptr::{addr_of, addr_of_mut}; +#[cfg(all(windows, feature = "std"))] +use core::{ffi::c_void, ptr::write_volatile}; #[cfg(any(windows, unix))] use core::{ fmt::{self, Debug, Formatter}, time::Duration, }; - -use crate::{ - executors::{Executor, ExitKind, HasObservers}, - inputs::Input, - observers::ObserversTuple, - Error, -}; - -#[cfg(all(windows, feature = "std"))] -use crate::executors::inprocess::{HasInProcessHandlers, GLOBAL_STATE}; - #[cfg(unix)] use core::{mem::zeroed, ptr::null_mut}; - -#[cfg(target_os = "linux")] -use core::ptr::{addr_of, addr_of_mut}; +#[cfg(windows)] +use core::{ + ptr::addr_of_mut, + sync::atomic::{compiler_fence, Ordering}, +}; #[cfg(all(unix, not(target_os = "linux")))] use libc::c_int; - #[cfg(all(windows, feature = "std"))] use windows::Win32::{ Foundation::FILETIME, @@ -36,12 +30,12 @@ use windows::Win32::{ }; #[cfg(all(windows, feature = "std"))] -use core::{ffi::c_void, ptr::write_volatile}; - -#[cfg(windows)] -use core::{ - ptr::addr_of_mut, - sync::atomic::{compiler_fence, Ordering}, +use crate::executors::inprocess::{HasInProcessHandlers, GLOBAL_STATE}; +use crate::{ + executors::{Executor, ExitKind, HasObservers}, + inputs::Input, + observers::ObserversTuple, + Error, }; #[repr(C)] diff --git a/libafl/src/feedbacks/differential.rs b/libafl/src/feedbacks/differential.rs index b82f91f986..4e385648be 100644 --- a/libafl/src/feedbacks/differential.rs +++ b/libafl/src/feedbacks/differential.rs @@ -6,6 +6,7 @@ use core::{ fmt::{self, Debug, Formatter}, marker::PhantomData, }; + use serde::{Deserialize, Serialize}; use crate::{ @@ -153,6 +154,8 @@ where #[cfg(test)] mod tests { + use alloc::string::{String, ToString}; + use crate::{ bolts::{ serdeany::SerdeAnyMap, @@ -166,7 +169,6 @@ mod tests { observers::Observer, state::{HasClientPerfMonitor, HasMetadata}, }; - use alloc::string::{String, ToString}; #[derive(Debug)] struct NopObserver { diff --git a/libafl/src/feedbacks/map.rs b/libafl/src/feedbacks/map.rs index fb137cc38e..e055244b01 100644 --- a/libafl/src/feedbacks/map.rs +++ b/libafl/src/feedbacks/map.rs @@ -4,8 +4,12 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; -use core::ops::{BitAnd, BitOr}; -use core::{fmt::Debug, marker::PhantomData}; +use core::{ + fmt::Debug, + marker::PhantomData, + ops::{BitAnd, BitOr}, +}; + use num_traits::PrimInt; use serde::{de::DeserializeOwned, Deserialize, Serialize}; @@ -837,13 +841,14 @@ mod tests { #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { - use super::{Debug, HasObserverName, MaxMapFeedback}; - use crate::feedbacks::pybind::PythonFeedback; - use crate::inputs::BytesInput; - use crate::state::pybind::PythonStdState; use concat_idents::concat_idents; use pyo3::prelude::*; + use super::{Debug, HasObserverName, MaxMapFeedback}; + use crate::{ + feedbacks::pybind::PythonFeedback, inputs::BytesInput, state::pybind::PythonStdState, + }; + macro_rules! define_python_map_feedback { ($struct_name:ident, $py_name:tt, $datatype:ty, $map_observer_type_name: ident, $my_std_state_type_name: ident) => { use crate::observers::map::pybind::$map_observer_type_name; diff --git a/libafl/src/feedbacks/mod.rs b/libafl/src/feedbacks/mod.rs index a17dddac1e..00e081e59d 100644 --- a/libafl/src/feedbacks/mod.rs +++ b/libafl/src/feedbacks/mod.rs @@ -20,10 +20,15 @@ pub use new_hash_feedback::NewHashFeedbackMetadata; #[cfg(feature = "nautilus")] pub mod nautilus; +use alloc::string::{String, ToString}; +use core::{ + fmt::{self, Debug, Formatter}, + marker::PhantomData, + time::Duration, +}; + #[cfg(feature = "nautilus")] pub use nautilus::*; - -use alloc::string::{String, ToString}; use serde::{Deserialize, Serialize}; use crate::{ @@ -37,12 +42,6 @@ use crate::{ Error, }; -use core::{ - fmt::{self, Debug, Formatter}, - marker::PhantomData, - time::Duration, -}; - /// Feedbacks evaluate the observers. /// Basically, they reduce the information provided by an observer to a value, /// indicating the "interestingness" of the last run. @@ -1040,27 +1039,32 @@ impl From for ConstFeedback { #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { + use std::cell::UnsafeCell; + + use pyo3::prelude::*; + use super::{ ConstFeedback, CrashFeedback, Debug, EagerAndFeedback, EagerOrFeedback, FastAndFeedback, FastOrFeedback, Feedback, NotFeedback, String, ToString, }; - use crate::corpus::testcase::pybind::{PythonTestcase, PythonTestcaseWrapper}; - use crate::events::pybind::PythonEventManager; - use crate::executors::pybind::PythonExitKind; - use crate::feedbacks::map::pybind::{ - PythonMaxMapFeedbackI16, PythonMaxMapFeedbackI32, PythonMaxMapFeedbackI64, - PythonMaxMapFeedbackI8, PythonMaxMapFeedbackU16, PythonMaxMapFeedbackU32, - PythonMaxMapFeedbackU64, PythonMaxMapFeedbackU8, - }; - use crate::inputs::HasBytesVec; - use crate::observers::pybind::PythonObserversTuple; - use crate::state::pybind::{PythonStdState, PythonStdStateWrapper}; use crate::{ - bolts::tuples::Named, corpus::Testcase, events::EventFirer, executors::ExitKind, - inputs::BytesInput, observers::ObserversTuple, Error, + bolts::tuples::Named, + corpus::{ + testcase::pybind::{PythonTestcase, PythonTestcaseWrapper}, + Testcase, + }, + events::{pybind::PythonEventManager, EventFirer}, + executors::{pybind::PythonExitKind, ExitKind}, + feedbacks::map::pybind::{ + PythonMaxMapFeedbackI16, PythonMaxMapFeedbackI32, PythonMaxMapFeedbackI64, + PythonMaxMapFeedbackI8, PythonMaxMapFeedbackU16, PythonMaxMapFeedbackU32, + PythonMaxMapFeedbackU64, PythonMaxMapFeedbackU8, + }, + inputs::{BytesInput, HasBytesVec}, + observers::{pybind::PythonObserversTuple, ObserversTuple}, + state::pybind::{PythonStdState, PythonStdStateWrapper}, + Error, }; - use pyo3::prelude::*; - use std::cell::UnsafeCell; #[derive(Debug)] pub struct PyObjectFeedback { diff --git a/libafl/src/feedbacks/nautilus.rs b/libafl/src/feedbacks/nautilus.rs index a173bacae0..cef6355a58 100644 --- a/libafl/src/feedbacks/nautilus.rs +++ b/libafl/src/feedbacks/nautilus.rs @@ -1,10 +1,11 @@ //! Nautilus grammar mutator, see use alloc::string::String; use core::fmt::Debug; +use std::fs::create_dir_all; + use grammartec::{chunkstore::ChunkStore, context::Context}; use serde::{Deserialize, Serialize}; use serde_json; -use std::fs::create_dir_all; use crate::{ bolts::tuples::Named, diff --git a/libafl/src/feedbacks/new_hash_feedback.rs b/libafl/src/feedbacks/new_hash_feedback.rs index 6cd1418942..e6dc825fbc 100644 --- a/libafl/src/feedbacks/new_hash_feedback.rs +++ b/libafl/src/feedbacks/new_hash_feedback.rs @@ -1,8 +1,8 @@ //! The ``NewHashFeedback`` uses the backtrace hash and a hashset to only keep novel cases +use alloc::string::{String, ToString}; use std::{fmt::Debug, marker::PhantomData}; -use alloc::string::{String, ToString}; use hashbrown::HashSet; use serde::{Deserialize, Serialize}; diff --git a/libafl/src/fuzzer/mod.rs b/libafl/src/fuzzer/mod.rs index bd1ea133d0..a0e0e3b538 100644 --- a/libafl/src/fuzzer/mod.rs +++ b/libafl/src/fuzzer/mod.rs @@ -1,5 +1,10 @@ //! The `Fuzzer` is the main struct for a fuzz campaign. +use alloc::string::ToString; +use core::{marker::PhantomData, time::Duration}; + +#[cfg(feature = "introspection")] +use crate::monitors::PerfFeature; use crate::{ bolts::current_time, corpus::{Corpus, Testcase}, @@ -16,12 +21,6 @@ use crate::{ Error, }; -#[cfg(feature = "introspection")] -use crate::monitors::PerfFeature; - -use alloc::string::ToString; -use core::{marker::PhantomData, time::Duration}; - /// Send a monitor update all 15 (or more) seconds const STATS_TIMEOUT_DEFAULT: Duration = Duration::from_secs(15); @@ -672,19 +671,23 @@ where #[allow(missing_docs)] /// `Fuzzer` Python bindings pub mod pybind { - use crate::bolts::ownedref::OwnedPtrMut; - use crate::events::pybind::PythonEventManager; - use crate::executors::pybind::PythonExecutor; - use crate::feedbacks::pybind::PythonFeedback; - use crate::fuzzer::{Evaluator, Fuzzer, StdFuzzer}; - use crate::inputs::BytesInput; - use crate::observers::pybind::PythonObserversTuple; - use crate::schedulers::QueueScheduler; - use crate::stages::pybind::PythonStagesTuple; - use crate::state::pybind::{PythonStdState, PythonStdStateWrapper}; use alloc::{boxed::Box, vec::Vec}; + use pyo3::prelude::*; + use crate::{ + bolts::ownedref::OwnedPtrMut, + events::pybind::PythonEventManager, + executors::pybind::PythonExecutor, + feedbacks::pybind::PythonFeedback, + fuzzer::{Evaluator, Fuzzer, StdFuzzer}, + inputs::BytesInput, + observers::pybind::PythonObserversTuple, + schedulers::QueueScheduler, + stages::pybind::PythonStagesTuple, + state::pybind::{PythonStdState, PythonStdStateWrapper}, + }; + /// `StdFuzzer` with fixed generics pub type PythonStdFuzzer = StdFuzzer< QueueScheduler, diff --git a/libafl/src/generators/gramatron.rs b/libafl/src/generators/gramatron.rs index 8da5bd379d..0f7c21e1a8 100644 --- a/libafl/src/generators/gramatron.rs +++ b/libafl/src/generators/gramatron.rs @@ -1,6 +1,7 @@ //! Gramatron generator use alloc::{string::String, vec::Vec}; use core::marker::PhantomData; + use serde::{Deserialize, Serialize}; use crate::{ diff --git a/libafl/src/generators/mod.rs b/libafl/src/generators/mod.rs index d8b8f95b46..6a7dbe1c13 100644 --- a/libafl/src/generators/mod.rs +++ b/libafl/src/generators/mod.rs @@ -130,13 +130,17 @@ where #[allow(missing_docs)] #[cfg(feature = "python")] pub mod pybind { - use crate::generators::{Generator, RandBytesGenerator, RandPrintablesGenerator}; - use crate::inputs::{BytesInput, HasBytesVec}; - use crate::state::pybind::{PythonStdState, PythonStdStateWrapper}; - use crate::Error; use alloc::vec::Vec; + use pyo3::prelude::*; + use crate::{ + generators::{Generator, RandBytesGenerator, RandPrintablesGenerator}, + inputs::{BytesInput, HasBytesVec}, + state::pybind::{PythonStdState, PythonStdStateWrapper}, + Error, + }; + #[derive(Clone, Debug)] pub struct PyObjectGenerator { inner: PyObject, diff --git a/libafl/src/generators/nautilus.rs b/libafl/src/generators/nautilus.rs index 5ce3be8116..65da432c4b 100644 --- a/libafl/src/generators/nautilus.rs +++ b/libafl/src/generators/nautilus.rs @@ -1,15 +1,16 @@ //! Generators for the [`Nautilus`](https://github.com/RUB-SysSec/nautilus) grammar fuzzer -use crate::{generators::Generator, inputs::nautilus::NautilusInput, Error}; use alloc::{ string::{String, ToString}, vec::Vec, }; use core::fmt::Debug; -use grammartec::context::Context; use std::{fs, io::BufReader, path::Path}; +use grammartec::context::Context; pub use grammartec::newtypes::NTermID; +use crate::{generators::Generator, inputs::nautilus::NautilusInput, Error}; + /// The nautilus context for a generator pub struct NautilusContext { /// The nautilus context for a generator diff --git a/libafl/src/inputs/bytes.rs b/libafl/src/inputs/bytes.rs index 8344ee0f8c..2ab274d9fc 100644 --- a/libafl/src/inputs/bytes.rs +++ b/libafl/src/inputs/bytes.rs @@ -1,14 +1,14 @@ //! The `BytesInput` is the "normal" input, a map of bytes, that can be sent directly to the client //! (As opposed to other, more abstract, inputs, like an Grammar-Based AST Input) -use ahash::AHasher; use alloc::{borrow::ToOwned, rc::Rc, string::String, vec::Vec}; -use core::hash::Hasher; -use core::{cell::RefCell, convert::From}; -use serde::{Deserialize, Serialize}; +use core::{cell::RefCell, convert::From, hash::Hasher}; #[cfg(feature = "std")] use std::{fs::File, io::Read, path::Path}; +use ahash::AHasher; +use serde::{Deserialize, Serialize}; + #[cfg(feature = "std")] use crate::{bolts::fs::write_file_atomic, Error}; use crate::{ diff --git a/libafl/src/inputs/encoded.rs b/libafl/src/inputs/encoded.rs index acdbb91ae2..a0d610474d 100644 --- a/libafl/src/inputs/encoded.rs +++ b/libafl/src/inputs/encoded.rs @@ -2,15 +2,14 @@ //! (As opposed to other, more abstract, inputs, like an Grammar-Based AST Input) //! See also [the paper on token-level fuzzing](https://www.usenix.org/system/files/sec21-salls.pdf) -use ahash::AHasher; -use core::hash::Hasher; - #[cfg(feature = "std")] use alloc::string::ToString; use alloc::{borrow::ToOwned, rc::Rc, string::String, vec::Vec}; #[cfg(feature = "std")] use core::str::from_utf8; -use core::{cell::RefCell, convert::From}; +use core::{cell::RefCell, convert::From, hash::Hasher}; + +use ahash::AHasher; use hashbrown::HashMap; #[cfg(feature = "std")] use regex::Regex; @@ -259,11 +258,11 @@ impl EncodedInput { #[cfg(test)] mod tests { use alloc::borrow::ToOwned; + use core::str::from_utf8; use crate::inputs::encoded::{ InputDecoder, InputEncoder, NaiveTokenizer, TokenInputEncoderDecoder, }; - use core::str::from_utf8; #[test] fn test_input() { diff --git a/libafl/src/inputs/generalized.rs b/libafl/src/inputs/generalized.rs index 471cd61e8e..fa0fcccdbd 100644 --- a/libafl/src/inputs/generalized.rs +++ b/libafl/src/inputs/generalized.rs @@ -1,16 +1,15 @@ //! The `GeneralizedInput` is an input that ca be generalized to represent a rule, used by Grimoire -use ahash::AHasher; use alloc::{borrow::ToOwned, rc::Rc, string::String, vec::Vec}; -use core::hash::Hasher; -use core::{cell::RefCell, convert::From}; +use core::{cell::RefCell, convert::From, hash::Hasher}; +#[cfg(feature = "std")] +use std::{fs::File, io::Read, path::Path}; + +use ahash::AHasher; use serde::{Deserialize, Serialize}; #[cfg(feature = "std")] use crate::Error; -#[cfg(feature = "std")] -use std::{fs::File, io::Read, path::Path}; - use crate::{ bolts::{ownedref::OwnedSlice, HasLen}, inputs::{HasBytesVec, HasTargetBytes, Input}, diff --git a/libafl/src/inputs/gramatron.rs b/libafl/src/inputs/gramatron.rs index bd7a26d622..a6c73085e1 100644 --- a/libafl/src/inputs/gramatron.rs +++ b/libafl/src/inputs/gramatron.rs @@ -1,9 +1,8 @@ //! The gramatron grammar fuzzer -use ahash::AHasher; -use core::hash::Hasher; - use alloc::{rc::Rc, string::String, vec::Vec}; -use core::{cell::RefCell, convert::From}; +use core::{cell::RefCell, convert::From, hash::Hasher}; + +use ahash::AHasher; use serde::{Deserialize, Serialize}; use crate::{bolts::HasLen, inputs::Input, Error}; diff --git a/libafl/src/inputs/mod.rs b/libafl/src/inputs/mod.rs index 3a254b8e2d..8ff5fc2963 100644 --- a/libafl/src/inputs/mod.rs +++ b/libafl/src/inputs/mod.rs @@ -14,18 +14,18 @@ pub use generalized::*; #[cfg(feature = "nautilus")] pub mod nautilus; -#[cfg(feature = "nautilus")] -pub use nautilus::*; - use alloc::{ string::{String, ToString}, vec::Vec, }; use core::{clone::Clone, fmt::Debug}; -use serde::{Deserialize, Serialize}; #[cfg(feature = "std")] use std::{fs::File, hash::Hash, io::Read, path::Path}; +#[cfg(feature = "nautilus")] +pub use nautilus::*; +use serde::{Deserialize, Serialize}; + #[cfg(feature = "std")] use crate::bolts::fs::write_file_atomic; use crate::{bolts::ownedref::OwnedSlice, Error}; diff --git a/libafl/src/inputs/nautilus.rs b/libafl/src/inputs/nautilus.rs index 156cbe60fe..ce504a4f72 100644 --- a/libafl/src/inputs/nautilus.rs +++ b/libafl/src/inputs/nautilus.rs @@ -6,17 +6,16 @@ use alloc::{rc::Rc, string::String, vec::Vec}; use core::{cell::RefCell, convert::From}; -use serde::{Deserialize, Serialize}; - -use crate::{bolts::HasLen, generators::nautilus::NautilusContext, inputs::Input}; +use std::hash::{Hash, Hasher}; use grammartec::{ newtypes::NodeID, rule::RuleIDOrCustom, tree::{Tree, TreeLike}, }; +use serde::{Deserialize, Serialize}; -use std::hash::{Hash, Hasher}; +use crate::{bolts::HasLen, generators::nautilus::NautilusContext, inputs::Input}; /// An [`Input`] implementation for `Nautilus` grammar. #[derive(Serialize, Deserialize, Clone, Debug)] diff --git a/libafl/src/lib.rs b/libafl/src/lib.rs index 8dfaeccc50..28c2f31c24 100644 --- a/libafl/src/lib.rs +++ b/libafl/src/lib.rs @@ -109,12 +109,16 @@ pub mod state; pub mod fuzzer; use alloc::string::{FromUtf8Error, String}; -use core::{array::TryFromSliceError, fmt, num::ParseIntError, num::TryFromIntError}; -pub use fuzzer::*; - +use core::{ + array::TryFromSliceError, + fmt, + num::{ParseIntError, TryFromIntError}, +}; #[cfg(feature = "std")] use std::{env::VarError, io}; +pub use fuzzer::*; + #[cfg(feature = "errors_backtrace")] /// Error Backtrace type when `errors_backtrace` feature is enabled (== [`backtrace::Backtrace`]) pub type ErrorBacktrace = backtrace::Backtrace; @@ -425,28 +429,31 @@ impl std::error::Error for Error {} /// The purpose of this module is to alleviate imports of many components by adding a glob import. pub mod prelude { - pub use super::bolts::bolts_prelude::*; - pub use super::bolts::*; - pub use super::corpus::*; - pub use super::events::*; - pub use super::executors::*; - pub use super::feedbacks::*; - pub use super::fuzzer::*; - pub use super::generators::*; - pub use super::inputs::*; - pub use super::monitors::*; - pub use super::mutators::*; - pub use super::observers::*; - pub use super::schedulers::*; - pub use super::stages::*; - pub use super::state::*; - pub use super::*; + pub use super::{ + bolts::{bolts_prelude::*, *}, + corpus::*, + events::*, + executors::*, + feedbacks::*, + fuzzer::*, + generators::*, + inputs::*, + monitors::*, + mutators::*, + observers::*, + schedulers::*, + stages::*, + state::*, + *, + }; } // TODO: no_std test #[cfg(feature = "std")] #[cfg(test)] mod tests { + #[cfg(feature = "std")] + use crate::events::SimpleEventManager; use crate::{ bolts::{rands::StdRand, tuples::tuple_list}, corpus::{Corpus, InMemoryCorpus, Testcase}, @@ -460,9 +467,6 @@ mod tests { Fuzzer, StdFuzzer, }; - #[cfg(feature = "std")] - use crate::events::SimpleEventManager; - #[test] #[allow(clippy::similar_names)] fn test_fuzzer() { @@ -535,11 +539,12 @@ pub extern "C" fn external_current_millis() -> u64 { #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { + use pyo3::prelude::*; + use super::{ bolts, corpus, events, executors, feedbacks, fuzzer, generators, monitors, mutators, observers, stages, state, }; - use pyo3::prelude::*; #[derive(Debug, Clone)] pub struct PythonMetadata { @@ -627,6 +632,7 @@ pub mod pybind { ($struct_name:ident, $inner:tt) => { const _: () = { use alloc::vec::Vec; + use pyo3::prelude::*; use serde::{Deserialize, Deserializer, Serialize, Serializer}; diff --git a/libafl/src/monitors/disk.rs b/libafl/src/monitors/disk.rs index c993f43f5e..c7f795bc98 100644 --- a/libafl/src/monitors/disk.rs +++ b/libafl/src/monitors/disk.rs @@ -2,14 +2,13 @@ use alloc::{string::String, vec::Vec}; use core::time::Duration; +use std::{fs::File, io::Write, path::PathBuf}; use crate::{ bolts::{current_time, format_duration_hms}, monitors::{ClientStats, Monitor, NopMonitor}, }; -use std::{fs::File, io::Write, path::PathBuf}; - /// Wrap a monitor and log the current state of the monitor into a TOML file. #[derive(Debug, Clone)] pub struct OnDiskTOMLMonitor diff --git a/libafl/src/monitors/mod.rs b/libafl/src/monitors/mod.rs index 915963cb45..019e902aec 100644 --- a/libafl/src/monitors/mod.rs +++ b/libafl/src/monitors/mod.rs @@ -9,15 +9,13 @@ pub mod tui; #[cfg(feature = "std")] pub mod disk; -#[cfg(feature = "std")] -pub use disk::OnDiskTOMLMonitor; - -use alloc::{fmt::Debug, string::String, vec::Vec}; - #[cfg(feature = "introspection")] use alloc::string::ToString; - +use alloc::{fmt::Debug, string::String, vec::Vec}; use core::{fmt, time::Duration}; + +#[cfg(feature = "std")] +pub use disk::OnDiskTOMLMonitor; use hashbrown::HashMap; use serde::{Deserialize, Serialize}; @@ -834,14 +832,14 @@ impl Default for ClientPerfMonitor { #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { - use crate::monitors::{Monitor, SimpleMonitor}; - use pyo3::prelude::*; - use pyo3::types::PyUnicode; - - use super::ClientStats; use alloc::{boxed::Box, string::String, vec::Vec}; use core::time::Duration; + use pyo3::{prelude::*, types::PyUnicode}; + + use super::ClientStats; + use crate::monitors::{Monitor, SimpleMonitor}; + // TODO create a PyObjectFnMut to pass, track stabilization of https://github.com/rust-lang/rust/issues/29625 #[pyclass(unsendable, name = "SimpleMonitor")] diff --git a/libafl/src/monitors/multi.rs b/libafl/src/monitors/multi.rs index eaa7768069..39e2cb7afd 100644 --- a/libafl/src/monitors/multi.rs +++ b/libafl/src/monitors/multi.rs @@ -1,10 +1,9 @@ //! Monitor to display both cumulative and per-client monitor -use alloc::{string::String, vec::Vec}; -use core::{fmt::Write, time::Duration}; - #[cfg(feature = "introspection")] use alloc::string::ToString; +use alloc::{string::String, vec::Vec}; +use core::{fmt::Write, time::Duration}; use crate::{ bolts::{current_time, format_duration_hms}, diff --git a/libafl/src/monitors/tui/mod.rs b/libafl/src/monitors/tui/mod.rs index 42eea41b29..2c7ccbaf50 100644 --- a/libafl/src/monitors/tui/mod.rs +++ b/libafl/src/monitors/tui/mod.rs @@ -1,14 +1,6 @@ //! Monitor based on tui-rs -use crossterm::{ - cursor::{EnableBlinking, Show}, - event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode}, - execute, - terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, -}; -use hashbrown::HashMap; -use tui::{backend::CrosstermBackend, Terminal}; - +use alloc::boxed::Box; use std::{ collections::VecDeque, fmt::Write, @@ -21,16 +13,22 @@ use std::{ vec::Vec, }; +use crossterm::{ + cursor::{EnableBlinking, Show}, + event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode}, + execute, + terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, +}; +use hashbrown::HashMap; +use tui::{backend::CrosstermBackend, Terminal}; + #[cfg(feature = "introspection")] use super::{ClientPerfMonitor, PerfFeature}; - use crate::{ bolts::{current_time, format_duration_hms}, monitors::{ClientStats, Monitor, UserStats}, }; -use alloc::boxed::Box; - mod ui; use ui::TuiUI; diff --git a/libafl/src/monitors/tui/ui.rs b/libafl/src/monitors/tui/ui.rs index c668653a1f..8332fa9a53 100644 --- a/libafl/src/monitors/tui/ui.rs +++ b/libafl/src/monitors/tui/ui.rs @@ -1,6 +1,9 @@ -use super::{current_time, format_duration_hms, Duration, String, TimedStats, TuiContext}; - use alloc::vec::Vec; +use std::{ + cmp::{max, min}, + sync::{Arc, RwLock}, +}; + use tui::{ backend::Backend, layout::{Alignment, Constraint, Direction, Layout, Rect}, @@ -13,10 +16,7 @@ use tui::{ Frame, }; -use std::{ - cmp::{max, min}, - sync::{Arc, RwLock}, -}; +use super::{current_time, format_duration_hms, Duration, String, TimedStats, TuiContext}; #[derive(Default)] pub struct TuiUI { diff --git a/libafl/src/mutators/gramatron.rs b/libafl/src/mutators/gramatron.rs index 4d8f98dd46..85c9bd25a0 100644 --- a/libafl/src/mutators/gramatron.rs +++ b/libafl/src/mutators/gramatron.rs @@ -2,6 +2,7 @@ //! See the original gramatron repo [`Gramatron`](https://github.com/HexHive/Gramatron) for more details. use alloc::vec::Vec; use core::cmp::max; + use hashbrown::HashMap; use serde::{Deserialize, Serialize}; diff --git a/libafl/src/mutators/mod.rs b/libafl/src/mutators/mod.rs index 8c9e8079de..e8acd5421c 100644 --- a/libafl/src/mutators/mod.rs +++ b/libafl/src/mutators/mod.rs @@ -212,13 +212,16 @@ where #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { - use super::{MutationResult, Mutator}; - use crate::inputs::{BytesInput, HasBytesVec}; - use crate::mutators::scheduled::pybind::PythonStdHavocMutator; - use crate::state::pybind::{PythonStdState, PythonStdStateWrapper}; - use crate::Error; use pyo3::prelude::*; + use super::{MutationResult, Mutator}; + use crate::{ + inputs::{BytesInput, HasBytesVec}, + mutators::scheduled::pybind::PythonStdHavocMutator, + state::pybind::{PythonStdState, PythonStdStateWrapper}, + Error, + }; + #[derive(Clone, Debug)] pub struct PyObjectMutator { inner: PyObject, diff --git a/libafl/src/mutators/mopt_mutator.rs b/libafl/src/mutators/mopt_mutator.rs index 1891daba7c..3c64e38958 100644 --- a/libafl/src/mutators/mopt_mutator.rs +++ b/libafl/src/mutators/mopt_mutator.rs @@ -1,19 +1,23 @@ //! The `MOpt` mutator scheduler, see and use alloc::{string::ToString, vec::Vec}; +use core::{ + fmt::{self, Debug}, + marker::PhantomData, +}; + +use serde::{Deserialize, Serialize}; use crate::{ - bolts::{current_nanos, rands::Rand, rands::StdRand}, + bolts::{ + current_nanos, + rands::{Rand, StdRand}, + }, corpus::Corpus, inputs::Input, mutators::{ComposedByMutations, MutationResult, Mutator, MutatorsTuple, ScheduledMutator}, state::{HasCorpus, HasMetadata, HasRand, HasSolutions}, Error, }; -use core::{ - fmt::{self, Debug}, - marker::PhantomData, -}; -use serde::{Deserialize, Serialize}; /// A Struct for managing MOpt-mutator parameters. /// There are 2 modes for `MOpt` scheduler, the core fuzzing mode and the pilot fuzzing mode. diff --git a/libafl/src/mutators/mutations.rs b/libafl/src/mutators/mutations.rs index a7242ed6fb..748c7e4b23 100644 --- a/libafl/src/mutators/mutations.rs +++ b/libafl/src/mutators/mutations.rs @@ -1,5 +1,11 @@ //! A wide variety of mutations used during fuzzing. +use alloc::{borrow::ToOwned, vec::Vec}; +use core::{ + cmp::{max, min}, + mem::size_of, +}; + use crate::{ bolts::{rands::Rand, tuples::Named}, corpus::Corpus, @@ -9,12 +15,6 @@ use crate::{ Error, }; -use alloc::{borrow::ToOwned, vec::Vec}; -use core::{ - cmp::{max, min}, - mem::size_of, -}; - /// Mem move in the own vec #[inline] pub fn buffer_self_copy(data: &mut [T], from: usize, to: usize, len: usize) { diff --git a/libafl/src/mutators/nautilus.rs b/libafl/src/mutators/nautilus.rs index 782290189c..640bdb3097 100644 --- a/libafl/src/mutators/nautilus.rs +++ b/libafl/src/mutators/nautilus.rs @@ -1,5 +1,13 @@ //! Mutators for the `Nautilus` grammmar fuzzer +use core::fmt::Debug; + +use grammartec::{ + context::Context, + mutator::Mutator as BackingMutator, + tree::{Tree, TreeMutation}, +}; + use crate::{ bolts::tuples::Named, feedbacks::NautilusChunksMetadata, @@ -10,13 +18,6 @@ use crate::{ Error, }; -use core::fmt::Debug; -use grammartec::mutator::Mutator as BackingMutator; -use grammartec::{ - context::Context, - tree::{Tree, TreeMutation}, -}; - /// The randomic mutator for `Nautilus` grammar. pub struct NautilusRandomMutator<'a> { ctx: &'a Context, diff --git a/libafl/src/mutators/scheduled.rs b/libafl/src/mutators/scheduled.rs index 92d499fd83..359382405d 100644 --- a/libafl/src/mutators/scheduled.rs +++ b/libafl/src/mutators/scheduled.rs @@ -5,8 +5,10 @@ use core::{ fmt::{self, Debug}, marker::PhantomData, }; + use serde::{Deserialize, Serialize}; +pub use crate::mutators::{mutations::*, token_mutations::*}; use crate::{ bolts::{ rands::Rand, @@ -20,9 +22,6 @@ use crate::{ Error, }; -pub use crate::mutators::mutations::*; -pub use crate::mutators::token_mutations::*; - /// The metadata placed in a [`crate::corpus::Testcase`] by a [`LoggerScheduledMutator`]. #[derive(Debug, Serialize, Deserialize)] pub struct LogMutationMetadata { @@ -505,12 +504,13 @@ mod tests { #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { - use super::{havoc_mutations, Debug, HavocMutationsType, StdScheduledMutator}; - use crate::inputs::BytesInput; - use crate::mutators::pybind::PythonMutator; - use crate::state::pybind::PythonStdState; use pyo3::prelude::*; + use super::{havoc_mutations, Debug, HavocMutationsType, StdScheduledMutator}; + use crate::{ + inputs::BytesInput, mutators::pybind::PythonMutator, state::pybind::PythonStdState, + }; + #[pyclass(unsendable, name = "StdHavocMutator")] #[derive(Debug)] /// Python class for StdHavocMutator diff --git a/libafl/src/mutators/token_mutations.rs b/libafl/src/mutators/token_mutations.rs index f2a0807a09..a8ae5a8ae3 100644 --- a/libafl/src/mutators/token_mutations.rs +++ b/libafl/src/mutators/token_mutations.rs @@ -1,17 +1,13 @@ //! Tokens are what AFL calls extras or dictionaries. //! They may be inserted as part of mutations during fuzzing. -#[cfg(feature = "std")] -use crate::mutators::str_decode; use alloc::vec::Vec; #[cfg(target_os = "linux")] use core::slice::from_raw_parts; -use core::slice::Iter; use core::{ mem::size_of, ops::{Add, AddAssign}, + slice::Iter, }; -use hashbrown::HashSet; -use serde::{Deserialize, Serialize}; #[cfg(feature = "std")] use std::{ fs::File, @@ -19,6 +15,11 @@ use std::{ path::Path, }; +use hashbrown::HashSet; +use serde::{Deserialize, Serialize}; + +#[cfg(feature = "std")] +use crate::mutators::str_decode; use crate::{ bolts::{rands::Rand, AsSlice}, inputs::{HasBytesVec, Input}, diff --git a/libafl/src/observers/cmp.rs b/libafl/src/observers/cmp.rs index 2e32f7b484..f40b59cc62 100644 --- a/libafl/src/observers/cmp.rs +++ b/libafl/src/observers/cmp.rs @@ -5,6 +5,7 @@ use alloc::{ vec::Vec, }; use core::fmt::Debug; + use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::{ diff --git a/libafl/src/observers/concolic/metadata.rs b/libafl/src/observers/concolic/metadata.rs index d0605fdb50..b3d045a2af 100644 --- a/libafl/src/observers/concolic/metadata.rs +++ b/libafl/src/observers/concolic/metadata.rs @@ -1,7 +1,9 @@ -use crate::observers::concolic::{serialization_format::MessageFileReader, SymExpr, SymExprRef}; use alloc::vec::Vec; + use serde::{Deserialize, Serialize}; +use crate::observers::concolic::{serialization_format::MessageFileReader, SymExpr, SymExprRef}; + /// A metadata holding a buffer of a concolic trace. #[derive(Default, Serialize, Deserialize, Debug)] pub struct ConcolicMetadata { diff --git a/libafl/src/observers/concolic/mod.rs b/libafl/src/observers/concolic/mod.rs index 1b8cc1ca67..115c39082a 100644 --- a/libafl/src/observers/concolic/mod.rs +++ b/libafl/src/observers/concolic/mod.rs @@ -1,11 +1,11 @@ //! # Concolic Tracing +#[cfg(feature = "std")] +use alloc::vec::Vec; use core::{ fmt::{Debug, Display, Error, Formatter}, num::NonZeroUsize, }; -#[cfg(feature = "std")] -use alloc::vec::Vec; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; diff --git a/libafl/src/observers/concolic/observer.rs b/libafl/src/observers/concolic/observer.rs index cff35262f3..4bc63b36af 100644 --- a/libafl/src/observers/concolic/observer.rs +++ b/libafl/src/observers/concolic/observer.rs @@ -1,3 +1,7 @@ +use alloc::string::String; + +use serde::{Deserialize, Serialize}; + use crate::{ bolts::tuples::Named, observers::{ @@ -5,8 +9,6 @@ use crate::{ Observer, }, }; -use alloc::string::String; -use serde::{Deserialize, Serialize}; /// A standard [`ConcolicObserver`] observer, observing constraints written into a memory buffer. #[derive(Serialize, Deserialize, Debug)] diff --git a/libafl/src/observers/concolic/serialization_format.rs b/libafl/src/observers/concolic/serialization_format.rs index fc71a8773a..4ea6cf1615 100644 --- a/libafl/src/observers/concolic/serialization_format.rs +++ b/libafl/src/observers/concolic/serialization_format.rs @@ -49,11 +49,10 @@ use std::{ }; use bincode::{DefaultOptions, Options}; +pub use bincode::{ErrorKind, Result}; use super::{SymExpr, SymExprRef}; -pub use bincode::{ErrorKind, Result}; - fn serialization_options() -> DefaultOptions { DefaultOptions::new() } @@ -381,9 +380,8 @@ impl MessageFileWriter { #[cfg(test)] mod serialization_tests { - use std::io::Cursor; - use alloc::vec::Vec; + use std::io::Cursor; use super::{MessageFileReader, MessageFileWriter, SymExpr}; diff --git a/libafl/src/observers/map.rs b/libafl/src/observers/map.rs index dba3207ecb..6400b7f181 100644 --- a/libafl/src/observers/map.rs +++ b/libafl/src/observers/map.rs @@ -1,6 +1,5 @@ //! The `MapObserver` provides access a map, usually injected into the target -use ahash::AHasher; use alloc::{ string::{String, ToString}, vec::Vec, @@ -12,6 +11,8 @@ use core::{ marker::PhantomData, slice::{from_raw_parts, Iter, IterMut}, }; + +use ahash::AHasher; use intervaltree::IntervalTree; use num_traits::Bounded; use serde::{Deserialize, Serialize}; @@ -1895,14 +1896,15 @@ where #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { + use concat_idents::concat_idents; + use pyo3::prelude::*; + use serde::{Deserialize, Serialize}; + use super::{ AsIter, AsIterMut, AsMutSlice, AsSlice, Debug, Error, HasLen, Iter, IterMut, MapObserver, Named, Observer, OwnedMapObserver, StdMapObserver, String, Vec, }; use crate::observers::pybind::PythonObserver; - use concat_idents::concat_idents; - use pyo3::prelude::*; - use serde::{Deserialize, Serialize}; #[macro_export] macro_rules! mapob_unwrap_me { diff --git a/libafl/src/observers/mod.rs b/libafl/src/observers/mod.rs index 763b9f3959..a7add150c0 100644 --- a/libafl/src/observers/mod.rs +++ b/libafl/src/observers/mod.rs @@ -20,14 +20,14 @@ pub mod concolic; #[cfg(unstable_feature)] pub mod owned; -#[cfg(unstable_feature)] -pub use owned::*; - use alloc::{ string::{String, ToString}, vec::Vec, }; use core::{fmt::Debug, time::Duration}; + +#[cfg(unstable_feature)] +pub use owned::*; use serde::{Deserialize, Serialize}; use crate::{ @@ -294,24 +294,26 @@ where #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { - use super::{Debug, Observer, ObserversTuple, String, Vec}; - use crate::bolts::tuples::{type_eq, MatchName, Named}; - use crate::executors::pybind::PythonExitKind; - use crate::executors::ExitKind; - use crate::inputs::BytesInput; - use crate::inputs::HasBytesVec; - use crate::observers::map::pybind::{ - PythonMapObserverI16, PythonMapObserverI32, PythonMapObserverI64, PythonMapObserverI8, - PythonMapObserverU16, PythonMapObserverU32, PythonMapObserverU64, PythonMapObserverU8, - PythonMapObserverWrapperI16, PythonMapObserverWrapperI32, PythonMapObserverWrapperI64, - PythonMapObserverWrapperI8, PythonMapObserverWrapperU16, PythonMapObserverWrapperU32, - PythonMapObserverWrapperU64, PythonMapObserverWrapperU8, - }; - use crate::state::pybind::{PythonStdState, PythonStdStateWrapper}; - use crate::Error; + use std::cell::UnsafeCell; + use pyo3::prelude::*; use serde::{Deserialize, Serialize}; - use std::cell::UnsafeCell; + + use super::{Debug, Observer, ObserversTuple, String, Vec}; + use crate::{ + bolts::tuples::{type_eq, MatchName, Named}, + executors::{pybind::PythonExitKind, ExitKind}, + inputs::{BytesInput, HasBytesVec}, + observers::map::pybind::{ + PythonMapObserverI16, PythonMapObserverI32, PythonMapObserverI64, PythonMapObserverI8, + PythonMapObserverU16, PythonMapObserverU32, PythonMapObserverU64, PythonMapObserverU8, + PythonMapObserverWrapperI16, PythonMapObserverWrapperI32, PythonMapObserverWrapperI64, + PythonMapObserverWrapperI8, PythonMapObserverWrapperU16, PythonMapObserverWrapperU32, + PythonMapObserverWrapperU64, PythonMapObserverWrapperU8, + }, + state::pybind::{PythonStdState, PythonStdStateWrapper}, + Error, + }; #[derive(Debug)] pub struct PyObjectObserver { diff --git a/libafl/src/observers/owned.rs b/libafl/src/observers/owned.rs index ab05d9d69e..9b2e8bc331 100644 --- a/libafl/src/observers/owned.rs +++ b/libafl/src/observers/owned.rs @@ -1,6 +1,7 @@ //! A dynamic collection of owned observers, working only with unstable rust use core::{any::Any, fmt::Debug}; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::{ diff --git a/libafl/src/observers/stacktrace.rs b/libafl/src/observers/stacktrace.rs index d17909ed71..4eea5ba915 100644 --- a/libafl/src/observers/stacktrace.rs +++ b/libafl/src/observers/stacktrace.rs @@ -1,17 +1,6 @@ //! the ``StacktraceObserver`` looks up the stacktrace on the execution thread and computes a hash for it for dedupe -use crate::{ - bolts::{ownedref::OwnedRefMut, tuples::Named}, - executors::ExitKind, - inputs::Input, - observers::Observer, - Error, -}; - use alloc::string::{String, ToString}; -use backtrace::Backtrace; -use regex::Regex; -use serde::{Deserialize, Serialize}; use std::{ fmt::Debug, fs::{self, File}, @@ -20,7 +9,18 @@ use std::{ process::ChildStderr, }; +use backtrace::Backtrace; +use regex::Regex; +use serde::{Deserialize, Serialize}; + use super::ObserverWithHashField; +use crate::{ + bolts::{ownedref::OwnedRefMut, tuples::Named}, + executors::ExitKind, + inputs::Input, + observers::Observer, + Error, +}; /// Collects the backtrace via [`Backtrace`] and [`Debug`] /// ([`Debug`] is currently used for dev purposes, symbols hash will be used eventually) diff --git a/libafl/src/schedulers/accounting.rs b/libafl/src/schedulers/accounting.rs index cf3c01c09a..eec2dd0133 100644 --- a/libafl/src/schedulers/accounting.rs +++ b/libafl/src/schedulers/accounting.rs @@ -1,5 +1,10 @@ //! Coverage accounting corpus scheduler, more details at +use alloc::vec::Vec; + +use hashbrown::HashMap; +use serde::{Deserialize, Serialize}; + use crate::{ bolts::{rands::Rand, AsMutSlice, AsSlice, HasLen, HasRefCnt}, corpus::{Corpus, Testcase}, @@ -13,10 +18,6 @@ use crate::{ Error, }; -use alloc::vec::Vec; -use hashbrown::HashMap; -use serde::{Deserialize, Serialize}; - /// A testcase metadata holding a list of indexes of a map #[derive(Debug, Serialize, Deserialize)] pub struct AccountingIndexesMetadata { diff --git a/libafl/src/schedulers/minimizer.rs b/libafl/src/schedulers/minimizer.rs index 69cc414526..cf27d387a3 100644 --- a/libafl/src/schedulers/minimizer.rs +++ b/libafl/src/schedulers/minimizer.rs @@ -1,6 +1,11 @@ //! The Minimizer schedulers are a family of corpus schedulers that feed the fuzzer // with testcases only from a subset of the total corpus. +use core::marker::PhantomData; + +use hashbrown::{HashMap, HashSet}; +use serde::{Deserialize, Serialize}; + use crate::{ bolts::{rands::Rand, serdeany::SerdeAny, AsSlice, HasRefCnt}, corpus::{Corpus, Testcase}, @@ -11,10 +16,6 @@ use crate::{ Error, }; -use core::marker::PhantomData; -use hashbrown::{HashMap, HashSet}; -use serde::{Deserialize, Serialize}; - /// Default probability to skip the non-favored values pub const DEFAULT_SKIP_NON_FAVORED_PROB: u64 = 95; diff --git a/libafl/src/schedulers/mod.rs b/libafl/src/schedulers/mod.rs index 33314a765f..6a9949d575 100644 --- a/libafl/src/schedulers/mod.rs +++ b/libafl/src/schedulers/mod.rs @@ -21,10 +21,10 @@ pub mod weighted; pub use weighted::{StdWeightedScheduler, WeightedScheduler}; pub mod powersched; -pub use powersched::PowerQueueScheduler; - use alloc::borrow::ToOwned; +pub use powersched::PowerQueueScheduler; + use crate::{ bolts::rands::Rand, corpus::{Corpus, Testcase}, diff --git a/libafl/src/schedulers/powersched.rs b/libafl/src/schedulers/powersched.rs index e1b110ba14..7d45413935 100644 --- a/libafl/src/schedulers/powersched.rs +++ b/libafl/src/schedulers/powersched.rs @@ -4,6 +4,9 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; +use core::time::Duration; + +use serde::{Deserialize, Serialize}; use crate::{ corpus::{Corpus, SchedulerTestcaseMetaData}, @@ -12,8 +15,6 @@ use crate::{ state::{HasCorpus, HasMetadata}, Error, }; -use core::time::Duration; -use serde::{Deserialize, Serialize}; /// The n fuzz size pub const N_FUZZ_SIZE: usize = 1 << 21; diff --git a/libafl/src/schedulers/probabilistic_sampling.rs b/libafl/src/schedulers/probabilistic_sampling.rs index 547ec5d73d..7385b04096 100644 --- a/libafl/src/schedulers/probabilistic_sampling.rs +++ b/libafl/src/schedulers/probabilistic_sampling.rs @@ -1,6 +1,12 @@ //! Probabilistic sampling scheduler is a corpus scheduler that feeds the fuzzer //! with sampled item from the corpus. +use alloc::string::String; +use core::marker::PhantomData; + +use hashbrown::HashMap; +use serde::{Deserialize, Serialize}; + use crate::{ bolts::rands::Rand, corpus::Corpus, @@ -9,10 +15,6 @@ use crate::{ state::{HasCorpus, HasMetadata, HasRand}, Error, }; -use alloc::string::String; -use core::marker::PhantomData; -use hashbrown::HashMap; -use serde::{Deserialize, Serialize}; /// Conduct reservoir sampling (probabilistic sampling) over all corpus elements. #[derive(Debug, Clone)] @@ -139,7 +141,7 @@ where #[cfg(test)] #[cfg(feature = "std")] mod tests { - use core::borrow::BorrowMut; + use core::{borrow::BorrowMut, marker::PhantomData}; use crate::{ bolts::rands::StdRand, @@ -149,7 +151,6 @@ mod tests { state::{HasCorpus, HasMetadata, StdState}, Error, }; - use core::marker::PhantomData; const FACTOR: f64 = 1337.0; diff --git a/libafl/src/schedulers/testcase_score.rs b/libafl/src/schedulers/testcase_score.rs index 19bb950960..1c043033f6 100644 --- a/libafl/src/schedulers/testcase_score.rs +++ b/libafl/src/schedulers/testcase_score.rs @@ -1,4 +1,7 @@ //! The `TestcaseScore` is an evaluator providing scores of corpus items. +use alloc::string::{String, ToString}; +use core::marker::PhantomData; + use crate::{ bolts::{HasLen, HasRefCnt}, corpus::{Corpus, SchedulerTestcaseMetaData, Testcase}, @@ -11,9 +14,6 @@ use crate::{ state::{HasCorpus, HasMetadata}, Error, }; -use alloc::string::{String, ToString}; - -use core::marker::PhantomData; /// Compute the favor factor of a [`Testcase`]. Lower is better. pub trait TestcaseScore diff --git a/libafl/src/schedulers/weighted.rs b/libafl/src/schedulers/weighted.rs index d07ce53604..1408cbb1a1 100644 --- a/libafl/src/schedulers/weighted.rs +++ b/libafl/src/schedulers/weighted.rs @@ -5,6 +5,9 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; +use core::marker::PhantomData; + +use serde::{Deserialize, Serialize}; use crate::{ bolts::rands::Rand, @@ -18,8 +21,6 @@ use crate::{ state::{HasCorpus, HasMetadata, HasRand}, Error, }; -use core::marker::PhantomData; -use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug)] diff --git a/libafl/src/stages/calibrate.rs b/libafl/src/stages/calibrate.rs index 456164f6eb..62957d0438 100644 --- a/libafl/src/stages/calibrate.rs +++ b/libafl/src/stages/calibrate.rs @@ -1,5 +1,11 @@ //! The calibration stage. The fuzzer measures the average exec time and the bitmap size. +use alloc::string::{String, ToString}; +use core::{fmt::Debug, marker::PhantomData, time::Duration}; + +use num_traits::Bounded; +use serde::{Deserialize, Serialize}; + use crate::{ bolts::{current_time, tuples::Named, AsIter}, corpus::{Corpus, SchedulerTestcaseMetaData}, @@ -17,10 +23,6 @@ use crate::{ state::{HasClientPerfMonitor, HasCorpus, HasMetadata, HasNamedMetadata}, Error, }; -use alloc::string::{String, ToString}; -use core::{fmt::Debug, marker::PhantomData, time::Duration}; -use num_traits::Bounded; -use serde::{Deserialize, Serialize}; /// The calibration stage will measure the average exec time and the target's stability for this input. #[derive(Clone, Debug)] diff --git a/libafl/src/stages/concolic.rs b/libafl/src/stages/concolic.rs index 980240cd63..7cdb4eb3de 100644 --- a/libafl/src/stages/concolic.rs +++ b/libafl/src/stages/concolic.rs @@ -2,12 +2,12 @@ //! and use the results for fuzzer input and mutations. //! -use core::marker::PhantomData; - use alloc::string::String; #[cfg(feature = "concolic_mutation")] use alloc::{borrow::ToOwned, string::ToString, vec::Vec}; +use core::marker::PhantomData; +use super::{Stage, TracingStage}; use crate::{ corpus::Corpus, executors::{Executor, HasObservers}, @@ -17,8 +17,6 @@ use crate::{ Error, }; -use super::{Stage, TracingStage}; - /// Wraps a [`TracingStage`] to add concolic observing. #[derive(Clone, Debug)] pub struct ConcolicTracingStage @@ -85,6 +83,8 @@ where } } +#[cfg(all(feature = "concolic_mutation", feature = "introspection"))] +use crate::monitors::PerfFeature; #[cfg(feature = "concolic_mutation")] use crate::{ inputs::HasBytesVec, @@ -93,9 +93,6 @@ use crate::{ start_timer, Evaluator, }; -#[cfg(all(feature = "concolic_mutation", feature = "introspection"))] -use crate::monitors::PerfFeature; - #[cfg(feature = "concolic_mutation")] #[allow(clippy::too_many_lines)] fn generate_mutations(iter: impl Iterator) -> Vec> { diff --git a/libafl/src/stages/generalization.rs b/libafl/src/stages/generalization.rs index aa39f3a28a..edd9f6e3ad 100644 --- a/libafl/src/stages/generalization.rs +++ b/libafl/src/stages/generalization.rs @@ -5,9 +5,12 @@ use alloc::{ vec::Vec, }; use core::{fmt::Debug, marker::PhantomData}; + use hashbrown::HashSet; use serde::{Deserialize, Serialize}; +#[cfg(feature = "introspection")] +use crate::monitors::PerfFeature; use crate::{ bolts::AsSlice, corpus::Corpus, @@ -22,9 +25,6 @@ use crate::{ Error, }; -#[cfg(feature = "introspection")] -use crate::monitors::PerfFeature; - const MAX_GENERALIZED_LEN: usize = 8192; /// A state metadata holding the set of indexes related to the generalized corpus entries diff --git a/libafl/src/stages/mod.rs b/libafl/src/stages/mod.rs index d85fc0ab8f..74d0559a08 100644 --- a/libafl/src/stages/mod.rs +++ b/libafl/src/stages/mod.rs @@ -34,23 +34,21 @@ pub use concolic::SimpleConcolicMutationalStage; #[cfg(feature = "std")] pub mod sync; +use core::{convert::From, marker::PhantomData}; + #[cfg(feature = "std")] pub use sync::*; +use self::push::PushStage; use crate::{ events::{EventFirer, EventRestarter, HasEventManagerId, ProgressReporter}, executors::{Executor, HasObservers}, inputs::Input, observers::ObserversTuple, schedulers::Scheduler, - state::{ - HasExecutions, HasRand, {HasClientPerfMonitor, HasCorpus}, - }, + state::{HasClientPerfMonitor, HasCorpus, HasExecutions, HasRand}, Error, EvaluatorObservers, ExecutesInput, ExecutionProcessor, HasScheduler, }; -use core::{convert::From, marker::PhantomData}; - -use self::push::PushStage; /// A stage is one step in the fuzzing process. /// Multiple stages will be scheduled one by one for each input. @@ -261,6 +259,10 @@ where #[cfg(feature = "python")] #[allow(missing_docs)] pub mod pybind { + use alloc::vec::Vec; + + use pyo3::prelude::*; + use crate::{ events::pybind::PythonEventManager, executors::pybind::PythonExecutor, @@ -269,8 +271,6 @@ pub mod pybind { state::pybind::{PythonStdState, PythonStdStateWrapper}, Error, }; - use alloc::vec::Vec; - use pyo3::prelude::*; #[derive(Clone, Debug)] pub struct PyObjectStage { diff --git a/libafl/src/stages/mutational.rs b/libafl/src/stages/mutational.rs index d1e785c798..5f8b9041f3 100644 --- a/libafl/src/stages/mutational.rs +++ b/libafl/src/stages/mutational.rs @@ -3,6 +3,8 @@ use core::marker::PhantomData; +#[cfg(feature = "introspection")] +use crate::monitors::PerfFeature; use crate::{ bolts::rands::Rand, corpus::Corpus, @@ -16,9 +18,6 @@ use crate::{ Error, }; -#[cfg(feature = "introspection")] -use crate::monitors::PerfFeature; - // TODO multi mutators stage /// A Mutational stage is the stage in a fuzzing run that mutates inputs. @@ -166,6 +165,8 @@ where #[allow(missing_docs)] /// `StdMutationalStage` Python bindings pub mod pybind { + use pyo3::prelude::*; + use crate::{ events::pybind::PythonEventManager, executors::pybind::PythonExecutor, @@ -175,7 +176,6 @@ pub mod pybind { stages::{pybind::PythonStage, StdMutationalStage}, state::pybind::PythonStdState, }; - use pyo3::prelude::*; #[pyclass(unsendable, name = "StdMutationalStage")] #[derive(Debug)] diff --git a/libafl/src/stages/push/mod.rs b/libafl/src/stages/push/mod.rs index bb579c0c67..b487e8efff 100644 --- a/libafl/src/stages/push/mod.rs +++ b/libafl/src/stages/push/mod.rs @@ -6,8 +6,6 @@ /// Mutational stage is the normal fuzzing stage. pub mod mutational; -pub use mutational::StdMutationalPushStage; - use alloc::rc::Rc; use core::{ cell::{Cell, RefCell}, @@ -15,6 +13,8 @@ use core::{ time::Duration, }; +pub use mutational::StdMutationalPushStage; + use crate::{ bolts::current_time, events::{EventFirer, EventRestarter, HasEventManagerId, ProgressReporter}, diff --git a/libafl/src/stages/push/mutational.rs b/libafl/src/stages/push/mutational.rs index 55b6f16d58..1efe79c9c2 100644 --- a/libafl/src/stages/push/mutational.rs +++ b/libafl/src/stages/push/mutational.rs @@ -4,6 +4,9 @@ use alloc::rc::Rc; use core::cell::{Cell, RefCell}; +use super::{PushStage, PushStageHelper, PushStageSharedState}; +#[cfg(feature = "introspection")] +use crate::monitors::PerfFeature; use crate::{ bolts::rands::Rand, corpus::Corpus, @@ -19,11 +22,6 @@ use crate::{ Error, EvaluatorObservers, ExecutionProcessor, HasScheduler, }; -#[cfg(feature = "introspection")] -use crate::monitors::PerfFeature; - -use super::{PushStage, PushStageHelper, PushStageSharedState}; - /// The default maximum number of mutations to perform per input. pub static DEFAULT_MUTATIONAL_MAX_ITERATIONS: u64 = 128; /// A Mutational push stage is the stage in a fuzzing run that mutates inputs. diff --git a/libafl/src/stages/sync.rs b/libafl/src/stages/sync.rs index 9fbfa7819e..bb72417abd 100644 --- a/libafl/src/stages/sync.rs +++ b/libafl/src/stages/sync.rs @@ -2,13 +2,14 @@ //! For the current input, it will perform a range of random mutations, and then run them in the executor. use core::marker::PhantomData; -use serde::{Deserialize, Serialize}; use std::{ fs, path::{Path, PathBuf}, time::SystemTime, }; +use serde::{Deserialize, Serialize}; + use crate::{ fuzzer::Evaluator, inputs::Input, diff --git a/libafl/src/stages/tracing.rs b/libafl/src/stages/tracing.rs index 1c3d272c23..e15de9c839 100644 --- a/libafl/src/stages/tracing.rs +++ b/libafl/src/stages/tracing.rs @@ -2,6 +2,8 @@ use core::{fmt::Debug, marker::PhantomData}; +#[cfg(feature = "introspection")] +use crate::monitors::PerfFeature; use crate::{ corpus::Corpus, executors::{Executor, HasObservers, ShadowExecutor}, @@ -14,9 +16,6 @@ use crate::{ Error, }; -#[cfg(feature = "introspection")] -use crate::monitors::PerfFeature; - /// A stage that runs a tracer executor #[derive(Clone, Debug)] pub struct TracingStage diff --git a/libafl/src/state/mod.rs b/libafl/src/state/mod.rs index 366e70d5aa..0bc51ec715 100644 --- a/libafl/src/state/mod.rs +++ b/libafl/src/state/mod.rs @@ -1,13 +1,14 @@ //! The fuzzer, and state are the core pieces of every good fuzzer use core::{fmt::Debug, marker::PhantomData, time::Duration}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[cfg(feature = "std")] use std::{ fs, path::{Path, PathBuf}, }; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; + use crate::{ bolts::{ rands::Rand, @@ -655,6 +656,11 @@ where #[allow(missing_docs)] /// `State` Python bindings pub mod pybind { + use alloc::{boxed::Box, vec::Vec}; + use std::path::PathBuf; + + use pyo3::{prelude::*, types::PyDict}; + use crate::{ bolts::{ownedref::OwnedPtrMut, rands::pybind::PythonRand}, corpus::pybind::PythonCorpus, @@ -669,9 +675,6 @@ pub mod pybind { HasCorpus, HasExecutions, HasMaxSize, HasMetadata, HasRand, HasSolutions, StdState, }, }; - use alloc::{boxed::Box, vec::Vec}; - use pyo3::{prelude::*, types::PyDict}; - use std::path::PathBuf; /// `StdState` with fixed generics pub type PythonStdState = StdState; diff --git a/libafl_cc/build.rs b/libafl_cc/build.rs index 2870c34c67..44ef47a9f2 100644 --- a/libafl_cc/build.rs +++ b/libafl_cc/build.rs @@ -1,8 +1,9 @@ #[cfg(target_vendor = "apple")] -use glob::glob; -#[cfg(target_vendor = "apple")] use std::path::PathBuf; use std::{env, fs::File, io::Write, path::Path, process::Command, str}; + +#[cfg(target_vendor = "apple")] +use glob::glob; #[cfg(not(target_vendor = "apple"))] use which::which; diff --git a/libafl_cc/src/cfg.rs b/libafl_cc/src/cfg.rs index af7cd5537d..55d4b285ff 100644 --- a/libafl_cc/src/cfg.rs +++ b/libafl_cc/src/cfg.rs @@ -1,9 +1,12 @@ //! LLVM style control flow graph with information of AFL-style index of the each //! edges, use together with ``AFLCoverage`` pass having --dump-afl-cfg flag enabled. use core::borrow::Borrow; +use std::{ + collections::{BinaryHeap, HashMap, HashSet}, + marker::PhantomData, +}; + use serde::{Deserialize, Serialize}; -use std::collections::{BinaryHeap, HashMap, HashSet}; -use std::marker::PhantomData; /// Compute the weight of a [`CfgEdge`]. Lower means shorter distance in the graph. pub trait HasWeight { diff --git a/libafl_concolic/test/dump_constraints/src/main.rs b/libafl_concolic/test/dump_constraints/src/main.rs index 17ba3760b7..684dac22f5 100644 --- a/libafl_concolic/test/dump_constraints/src/main.rs +++ b/libafl_concolic/test/dump_constraints/src/main.rs @@ -2,7 +2,6 @@ //! It achieves this by running an instrumented target program with the necessary environment variables set. //! When the program has finished executing, it dumps the traced constraints to a file. -use clap::{self, StructOpt}; use std::{ ffi::OsString, fs::File, @@ -12,6 +11,7 @@ use std::{ string::ToString, }; +use clap::{self, StructOpt}; use libafl::{ bolts::{ shmem::{ShMem, ShMemProvider, StdShMemProvider}, diff --git a/libafl_frida/src/alloc.rs b/libafl_frida/src/alloc.rs index b907ca92d4..bca2ed5c48 100644 --- a/libafl_frida/src/alloc.rs +++ b/libafl_frida/src/alloc.rs @@ -1,27 +1,27 @@ +#[cfg(any( + target_os = "linux", + target_vendor = "apple", + all(target_arch = "aarch64", target_os = "android") +))] +use std::io; +use std::{collections::BTreeMap, ffi::c_void}; + +use backtrace::Backtrace; use frida_gum::{PageProtection, RangeDetails}; use hashbrown::HashMap; use libafl::bolts::cli::FuzzerOptions; -use nix::{ - libc::memset, - sys::mman::{mmap, MapFlags, ProtFlags}, -}; - -use backtrace::Backtrace; #[cfg(any( target_os = "linux", target_vendor = "apple", all(target_arch = "aarch64", target_os = "android") ))] use libc::{sysconf, _SC_PAGESIZE}; +use nix::{ + libc::memset, + sys::mman::{mmap, MapFlags, ProtFlags}, +}; use rangemap::RangeSet; use serde::{Deserialize, Serialize}; -#[cfg(any( - target_os = "linux", - target_vendor = "apple", - all(target_arch = "aarch64", target_os = "android") -))] -use std::io; -use std::{collections::BTreeMap, ffi::c_void}; use crate::asan::errors::{AsanError, AsanErrors}; diff --git a/libafl_frida/src/asan/asan_rt.rs b/libafl_frida/src/asan/asan_rt.rs index 24db4814b8..3cc734810a 100644 --- a/libafl_frida/src/asan/asan_rt.rs +++ b/libafl_frida/src/asan/asan_rt.rs @@ -6,17 +6,18 @@ even if the target would not have crashed under normal conditions. this helps finding mem errors early. */ -use backtrace::Backtrace; use core::{ fmt::{self, Debug, Formatter}, ptr::addr_of_mut, }; -use frida_gum::{ModuleDetails, NativePointer, RangeDetails}; -use hashbrown::HashMap; -use libafl::bolts::{cli::FuzzerOptions, AsSlice}; -use nix::sys::mman::{mmap, MapFlags, ProtFlags}; -use rangemap::RangeMap; +use std::{ffi::c_void, ptr::write_volatile}; +use backtrace::Backtrace; +#[cfg(target_arch = "x86_64")] +use capstone::{ + arch::{self, x86::X86OperandType, ArchOperand::X86Operand, BuildsCapstone}, + Capstone, Insn, RegAccessType, RegId, +}; #[cfg(target_arch = "aarch64")] use capstone::{ arch::{ @@ -26,24 +27,17 @@ use capstone::{ }, Capstone, Insn, }; - -#[cfg(target_arch = "aarch64")] -use frida_gum::instruction_writer::{Aarch64Register, IndexMode}; - -#[cfg(target_arch = "x86_64")] -use capstone::{ - arch::{self, x86::X86OperandType, ArchOperand::X86Operand, BuildsCapstone}, - Capstone, Insn, RegAccessType, RegId, -}; - +use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; #[cfg(target_arch = "x86_64")] use frida_gum::instruction_writer::X86Register; - -use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; -use frida_gum::interceptor::Interceptor; +#[cfg(target_arch = "aarch64")] +use frida_gum::instruction_writer::{Aarch64Register, IndexMode}; use frida_gum::{ - instruction_writer::InstructionWriter, stalker::StalkerOutput, Gum, Module, ModuleMap, + instruction_writer::InstructionWriter, interceptor::Interceptor, stalker::StalkerOutput, Gum, + Module, ModuleDetails, ModuleMap, NativePointer, RangeDetails, }; +use hashbrown::HashMap; +use libafl::bolts::{cli::FuzzerOptions, AsSlice}; #[cfg(unix)] use libc::RLIMIT_STACK; use libc::{c_char, wchar_t}; @@ -51,8 +45,11 @@ use libc::{c_char, wchar_t}; use libc::{getrlimit, rlimit}; #[cfg(all(unix, not(target_vendor = "apple")))] use libc::{getrlimit64, rlimit64}; -use std::{ffi::c_void, ptr::write_volatile}; +use nix::sys::mman::{mmap, MapFlags, ProtFlags}; +use rangemap::RangeMap; +#[cfg(target_arch = "aarch64")] +use crate::utils::instruction_width; use crate::{ alloc::Allocator, asan::errors::{AsanError, AsanErrors, AsanReadWriteError, ASAN_ERRORS}, @@ -60,9 +57,6 @@ use crate::{ utils::writer_register, }; -#[cfg(target_arch = "aarch64")] -use crate::utils::instruction_width; - extern "C" { fn __register_frame(begin: *mut c_void); } diff --git a/libafl_frida/src/asan/errors.rs b/libafl_frida/src/asan/errors.rs index aeafa98474..81d4e19b30 100644 --- a/libafl_frida/src/asan/errors.rs +++ b/libafl_frida/src/asan/errors.rs @@ -1,6 +1,6 @@ //! Errors that can be caught by the `libafl_frida` address sanitizer. -#[cfg(target_arch = "x86_64")] -use crate::asan::asan_rt::ASAN_SAVE_REGISTER_NAMES; +use std::io::Write; + use backtrace::Backtrace; use capstone::{arch::BuildsCapstone, Capstone}; use color_backtrace::{default_output_stream, BacktracePrinter, Verbosity}; @@ -19,9 +19,10 @@ use libafl::{ Error, SerdeAny, }; use serde::{Deserialize, Serialize}; -use std::io::Write; use termcolor::{Color, ColorSpec, WriteColor}; +#[cfg(target_arch = "x86_64")] +use crate::asan::asan_rt::ASAN_SAVE_REGISTER_NAMES; use crate::{alloc::AllocationMetadata, asan::asan_rt::ASAN_SAVE_REGISTER_COUNT}; #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/libafl_frida/src/asan/hook_funcs.rs b/libafl_frida/src/asan/hook_funcs.rs index 18cb8904c9..3f05548ba7 100644 --- a/libafl_frida/src/asan/hook_funcs.rs +++ b/libafl_frida/src/asan/hook_funcs.rs @@ -1,4 +1,10 @@ //! The allocator hooks for address sanitizer. +use std::ffi::c_void; + +use backtrace::Backtrace; +use libc::{c_char, wchar_t}; +use nix::libc::memset; + use crate::{ alloc::Allocator, asan::{ @@ -6,10 +12,6 @@ use crate::{ errors::{AsanError, AsanErrors}, }, }; -use backtrace::Backtrace; -use libc::{c_char, wchar_t}; -use nix::libc::memset; -use std::ffi::c_void; #[allow(clippy::not_unsafe_ptr_arg_deref)] impl AsanRuntime { diff --git a/libafl_frida/src/cmplog_rt.rs b/libafl_frida/src/cmplog_rt.rs index 85e02b387c..b36108a240 100644 --- a/libafl_frida/src/cmplog_rt.rs +++ b/libafl_frida/src/cmplog_rt.rs @@ -3,15 +3,15 @@ //! This allows the fuzzer to potentially solve the compares, if a compare value is directly //! related to the input. //! Read the [`RedQueen`](https://www.ndss-symposium.org/ndss-paper/redqueen-fuzzing-with-input-to-state-correspondence/) paper for the general concepts. +use std::ffi::c_void; + use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; use libafl::{ inputs::{HasTargetBytes, Input}, Error, }; -use libafl_targets; -use libafl_targets::CMPLOG_MAP_W; +use libafl_targets::{self, CMPLOG_MAP_W}; use rangemap::RangeMap; -use std::ffi::c_void; use crate::helper::FridaRuntime; extern "C" { diff --git a/libafl_frida/src/coverage_rt.rs b/libafl_frida/src/coverage_rt.rs index b9d2df51f8..024e826bff 100644 --- a/libafl_frida/src/coverage_rt.rs +++ b/libafl_frida/src/coverage_rt.rs @@ -1,17 +1,16 @@ //! Functionality regarding binary-only coverage collection. use core::ptr::addr_of_mut; -use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; -use rangemap::RangeMap; +use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; #[cfg(target_arch = "x86_64")] use frida_gum::instruction_writer::X86Register; #[cfg(target_arch = "aarch64")] use frida_gum::instruction_writer::{Aarch64Register, IndexMode}; - use frida_gum::{instruction_writer::InstructionWriter, stalker::StalkerOutput}; +use libafl::bolts::xxh3_rrmxmx_mixer; +use rangemap::RangeMap; use crate::helper::FridaRuntime; -use libafl::bolts::xxh3_rrmxmx_mixer; /// (Default) map size for frida coverage reporting pub const MAP_SIZE: usize = 64 * 1024; diff --git a/libafl_frida/src/drcov_rt.rs b/libafl_frida/src/drcov_rt.rs index 1585fdb43d..871aec9843 100644 --- a/libafl_frida/src/drcov_rt.rs +++ b/libafl_frida/src/drcov_rt.rs @@ -1,5 +1,6 @@ //! Generates `DrCov` traces -use crate::helper::FridaRuntime; +use std::{collections::HashMap, hash::Hasher}; + use ahash::AHasher; use libafl::{ bolts::AsSlice, @@ -8,8 +9,8 @@ use libafl::{ }; use libafl_targets::drcov::{DrCovBasicBlock, DrCovWriter}; use rangemap::RangeMap; -use std::collections::HashMap; -use std::hash::Hasher; + +use crate::helper::FridaRuntime; /// Generates `DrCov` traces #[derive(Debug, Clone)] diff --git a/libafl_frida/src/executor.rs b/libafl_frida/src/executor.rs index c145503845..1eceda602e 100644 --- a/libafl_frida/src/executor.rs +++ b/libafl_frida/src/executor.rs @@ -1,12 +1,12 @@ -use crate::helper::{FridaInstrumentationHelper, FridaRuntimeTuple}; - use core::fmt::{self, Debug, Formatter}; +use std::{ffi::c_void, marker::PhantomData}; + use frida_gum::{ stalker::{NoneEventSink, Stalker}, Gum, MemoryRange, NativePointer, }; -use std::{ffi::c_void, marker::PhantomData}; - +#[cfg(windows)] +use libafl::executors::inprocess::{HasInProcessHandlers, InProcessHandlers}; use libafl::{ executors::{Executor, ExitKind, HasObservers, InProcessExecutor}, inputs::{HasTargetBytes, Input}, @@ -16,9 +16,7 @@ use libafl::{ #[cfg(unix)] use crate::asan::errors::ASAN_ERRORS; - -#[cfg(windows)] -use libafl::executors::inprocess::{HasInProcessHandlers, InProcessHandlers}; +use crate::helper::{FridaInstrumentationHelper, FridaRuntimeTuple}; /// The [`FridaInProcessExecutor`] is an [`Executor`] that executes the target in the same process, usinig [`frida`](https://frida.re/) for binary-only instrumentation. pub struct FridaInProcessExecutor<'a, 'b, 'c, H, I, OT, RT, S> diff --git a/libafl_frida/src/helper.rs b/libafl_frida/src/helper.rs index c53d5fe904..bc15998de1 100644 --- a/libafl_frida/src/helper.rs +++ b/libafl_frida/src/helper.rs @@ -1,17 +1,5 @@ -use libafl::{ - bolts::{cli::FuzzerOptions, tuples::MatchFirstType}, - inputs::{HasTargetBytes, Input}, - Error, -}; - -#[cfg(unix)] -use libafl_targets::drcov::DrCovBasicBlock; +use core::fmt::{self, Debug, Formatter}; -#[cfg(all(feature = "cmplog", target_arch = "aarch64"))] -use crate::cmplog_rt::CmpLogRuntime; -use crate::coverage_rt::CoverageRuntime; -#[cfg(unix)] -use crate::{asan::asan_rt::AsanRuntime, drcov_rt::DrCovRuntime}; #[cfg(target_arch = "aarch64")] use capstone::{ arch::{self, BuildsCapstone}, @@ -22,17 +10,28 @@ use capstone::{ arch::{self, BuildsCapstone}, Capstone, }; -use core::fmt::{self, Debug, Formatter}; -#[cfg(unix)] -use frida_gum::CpuContext; - #[cfg(unix)] use frida_gum::instruction_writer::InstructionWriter; +#[cfg(unix)] +use frida_gum::CpuContext; use frida_gum::{stalker::Transformer, Gum, Module, ModuleDetails, ModuleMap, PageProtection}; +use libafl::{ + bolts::{cli::FuzzerOptions, tuples::MatchFirstType}, + inputs::{HasTargetBytes, Input}, + Error, +}; +#[cfg(unix)] +use libafl_targets::drcov::DrCovBasicBlock; #[cfg(unix)] use nix::sys::mman::{mmap, MapFlags, ProtFlags}; use rangemap::RangeMap; +#[cfg(all(feature = "cmplog", target_arch = "aarch64"))] +use crate::cmplog_rt::CmpLogRuntime; +use crate::coverage_rt::CoverageRuntime; +#[cfg(unix)] +use crate::{asan::asan_rt::AsanRuntime, drcov_rt::DrCovRuntime}; + #[cfg(any(target_vendor = "apple"))] const ANONYMOUS_FLAG: MapFlags = MapFlags::MAP_ANON; #[cfg(not(any(target_vendor = "apple", target_os = "windows")))] diff --git a/libafl_frida/src/utils.rs b/libafl_frida/src/utils.rs index 47d88cee51..0ecee44c03 100644 --- a/libafl_frida/src/utils.rs +++ b/libafl_frida/src/utils.rs @@ -1,14 +1,12 @@ -#[cfg(target_arch = "aarch64")] -use frida_gum::instruction_writer::Aarch64Register; -#[cfg(target_arch = "x86_64")] -use frida_gum::instruction_writer::X86Register; - #[cfg(target_arch = "aarch64")] use capstone::{ arch::{self, arm64::Arm64OperandType, ArchOperand::Arm64Operand}, Insn, }; - +#[cfg(target_arch = "aarch64")] +use frida_gum::instruction_writer::Aarch64Register; +#[cfg(target_arch = "x86_64")] +use frida_gum::instruction_writer::X86Register; #[cfg(target_arch = "aarch64")] use num_traits::cast::FromPrimitive; @@ -17,9 +15,7 @@ use num_traits::cast::FromPrimitive; #[inline] #[must_use] pub fn instruction_width(instr: &Insn, operands: &[arch::ArchOperand]) -> u32 { - use capstone::arch::arm64::Arm64Insn as I; - use capstone::arch::arm64::Arm64Reg as R; - use capstone::arch::arm64::Arm64Vas as V; + use capstone::arch::arm64::{Arm64Insn as I, Arm64Reg as R, Arm64Vas as V}; let num_registers = match instr.id().0.into() { I::ARM64_INS_STP diff --git a/libafl_qemu/src/aarch64.rs b/libafl_qemu/src/aarch64.rs index 0963cdcc08..1dd0d39522 100644 --- a/libafl_qemu/src/aarch64.rs +++ b/libafl_qemu/src/aarch64.rs @@ -1,9 +1,7 @@ use num_enum::{IntoPrimitive, TryFromPrimitive}; -pub use strum_macros::EnumIter; - #[cfg(feature = "python")] use pyo3::prelude::*; - +pub use strum_macros::EnumIter; pub use syscall_numbers::aarch64::*; #[derive(IntoPrimitive, TryFromPrimitive, Debug, Clone, Copy, EnumIter)] diff --git a/libafl_qemu/src/arm.rs b/libafl_qemu/src/arm.rs index 5be3a9682f..4381538698 100644 --- a/libafl_qemu/src/arm.rs +++ b/libafl_qemu/src/arm.rs @@ -1,9 +1,7 @@ use num_enum::{IntoPrimitive, TryFromPrimitive}; -pub use strum_macros::EnumIter; - #[cfg(feature = "python")] use pyo3::prelude::*; - +pub use strum_macros::EnumIter; pub use syscall_numbers::arm::*; /// Registers for the ARM instruction set. diff --git a/libafl_qemu/src/asan.rs b/libafl_qemu/src/asan.rs index a9ef619a55..46120e53c4 100644 --- a/libafl_qemu/src/asan.rs +++ b/libafl_qemu/src/asan.rs @@ -1,6 +1,7 @@ +use std::{env, fs, ptr}; + use libafl::{inputs::Input, state::HasMetadata}; use num_enum::{IntoPrimitive, TryFromPrimitive}; -use std::{env, fs, ptr}; use crate::{ emu::{Emulator, SyscallHookResult}, diff --git a/libafl_qemu/src/edges.rs b/libafl_qemu/src/edges.rs index 61c2c3bfd9..e56c755518 100644 --- a/libafl_qemu/src/edges.rs +++ b/libafl_qemu/src/edges.rs @@ -1,10 +1,11 @@ +use std::{cell::UnsafeCell, cmp::max}; + use hashbrown::{hash_map::Entry, HashMap}; use libafl::{inputs::Input, state::HasMetadata}; pub use libafl_targets::{ edges_max_num, EDGES_MAP, EDGES_MAP_PTR, EDGES_MAP_PTR_SIZE, EDGES_MAP_SIZE, MAX_EDGES_NUM, }; use serde::{Deserialize, Serialize}; -use std::{cell::UnsafeCell, cmp::max}; use crate::{ emu::GuestAddr, diff --git a/libafl_qemu/src/elf.rs b/libafl_qemu/src/elf.rs index 916af64022..09daa93686 100644 --- a/libafl_qemu/src/elf.rs +++ b/libafl_qemu/src/elf.rs @@ -1,8 +1,8 @@ //! Utilities to parse and process ELFs -use goblin::elf::{header::ET_DYN, Elf}; use std::{convert::AsRef, fs::File, io::Read, path::Path, str}; +use goblin::elf::{header::ET_DYN, Elf}; use libafl::Error; use crate::GuestAddr; diff --git a/libafl_qemu/src/emu.rs b/libafl_qemu/src/emu.rs index 4194a879d0..a3e5603d48 100644 --- a/libafl_qemu/src/emu.rs +++ b/libafl_qemu/src/emu.rs @@ -7,11 +7,12 @@ use core::{ }; #[cfg(feature = "usermode")] use core::{mem::MaybeUninit, ptr::copy_nonoverlapping}; +use std::{slice::from_raw_parts, str::from_utf8_unchecked}; + #[cfg(feature = "usermode")] use libc::c_int; use num_enum::{IntoPrimitive, TryFromPrimitive}; use num_traits::Num; -use std::{slice::from_raw_parts, str::from_utf8_unchecked}; use strum_macros::EnumIter; #[cfg(not(any(cpu_target = "x86_64", cpu_target = "aarch64")))] @@ -948,11 +949,12 @@ impl Emulator { #[cfg(feature = "python")] pub mod pybind { - use super::{GuestAddr, GuestUsize, MmapPerms, SyscallHookResult}; - use pyo3::exceptions::PyValueError; - use pyo3::{prelude::*, types::PyInt}; use std::convert::TryFrom; + use pyo3::{exceptions::PyValueError, prelude::*, types::PyInt}; + + use super::{GuestAddr, GuestUsize, MmapPerms, SyscallHookResult}; + static mut PY_SYSCALL_HOOK: Option = None; static mut PY_GENERIC_HOOKS: Vec<(GuestAddr, PyObject)> = vec![]; diff --git a/libafl_qemu/src/helper.rs b/libafl_qemu/src/helper.rs index 6d743e477b..8ce48a9ccd 100644 --- a/libafl_qemu/src/helper.rs +++ b/libafl_qemu/src/helper.rs @@ -1,4 +1,5 @@ use core::{fmt::Debug, ops::Range}; + use libafl::{bolts::tuples::MatchFirstType, inputs::Input}; use crate::{emu::Emulator, hooks::QemuHooks}; diff --git a/libafl_qemu/src/i386.rs b/libafl_qemu/src/i386.rs index bdfcc95b53..56ccd3b086 100644 --- a/libafl_qemu/src/i386.rs +++ b/libafl_qemu/src/i386.rs @@ -1,11 +1,8 @@ +use capstone::arch::BuildsCapstone; use num_enum::{IntoPrimitive, TryFromPrimitive}; -pub use strum_macros::EnumIter; - #[cfg(feature = "python")] use pyo3::prelude::*; - -use capstone::arch::BuildsCapstone; - +pub use strum_macros::EnumIter; pub use syscall_numbers::x86::*; #[derive(IntoPrimitive, TryFromPrimitive, Debug, Clone, Copy, EnumIter)] diff --git a/libafl_qemu/src/snapshot.rs b/libafl_qemu/src/snapshot.rs index eae4b2ad8d..89867fcf4b 100644 --- a/libafl_qemu/src/snapshot.rs +++ b/libafl_qemu/src/snapshot.rs @@ -1,10 +1,11 @@ -use bio::data_structures::interval_tree::IntervalTree; -use libafl::{inputs::Input, state::HasMetadata}; use std::{ cell::UnsafeCell, collections::{HashMap, HashSet}, sync::Mutex, }; + +use bio::data_structures::interval_tree::IntervalTree; +use libafl::{inputs::Input, state::HasMetadata}; use thread_local::ThreadLocal; use crate::{ diff --git a/libafl_qemu/src/x86_64.rs b/libafl_qemu/src/x86_64.rs index b92f214780..3537b4fa60 100644 --- a/libafl_qemu/src/x86_64.rs +++ b/libafl_qemu/src/x86_64.rs @@ -1,11 +1,8 @@ +use capstone::arch::BuildsCapstone; use num_enum::{IntoPrimitive, TryFromPrimitive}; -pub use strum_macros::EnumIter; - #[cfg(feature = "python")] use pyo3::prelude::*; - -use capstone::arch::BuildsCapstone; - +pub use strum_macros::EnumIter; pub use syscall_numbers::x86_64::*; #[derive(IntoPrimitive, TryFromPrimitive, Debug, Clone, Copy, EnumIter)] diff --git a/libafl_sugar/src/forkserver.rs b/libafl_sugar/src/forkserver.rs index 3daa29cdbd..08d89158f8 100644 --- a/libafl_sugar/src/forkserver.rs +++ b/libafl_sugar/src/forkserver.rs @@ -1,7 +1,6 @@ //! An `afl`-style forkserver fuzzer. //! Use this if your target has complex state that needs to be reset. use std::{fs, net::SocketAddr, path::PathBuf, time::Duration}; -use typed_builder::TypedBuilder; use libafl::{ bolts::{ @@ -21,14 +20,17 @@ use libafl::{ fuzzer::{Fuzzer, StdFuzzer}, generators::RandBytesGenerator, monitors::MultiMonitor, - mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - mutators::token_mutations::Tokens, + mutators::{ + scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + token_mutations::Tokens, + }, observers::{ConstMapObserver, HitcountsMapObserver, TimeObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::StdMutationalStage, state::{HasCorpus, HasMetadata, StdState}, Error, }; +use typed_builder::TypedBuilder; use crate::{CORPUS_CACHE_SIZE, DEFAULT_TIMEOUT_SECS}; @@ -293,10 +295,12 @@ impl<'a, const MAP_SIZE: usize> ForkserverBytesCoverageSugar<'a, MAP_SIZE> { /// The python bindings for this sugar #[cfg(feature = "python")] pub mod pybind { - use crate::forkserver; + use std::path::PathBuf; + use libafl::bolts::core_affinity::Cores; use pyo3::prelude::*; - use std::path::PathBuf; + + use crate::forkserver; /// Python bindings for the `LibAFL` forkserver sugar #[pyclass(unsendable)] diff --git a/libafl_sugar/src/inmemory.rs b/libafl_sugar/src/inmemory.rs index 4f89dd218c..e51d819a3f 100644 --- a/libafl_sugar/src/inmemory.rs +++ b/libafl_sugar/src/inmemory.rs @@ -3,7 +3,6 @@ use core::fmt::{self, Debug, Formatter}; use std::{fs, net::SocketAddr, path::PathBuf, time::Duration}; -use typed_builder::TypedBuilder; use libafl::{ bolts::{ @@ -24,16 +23,18 @@ use libafl::{ generators::RandBytesGenerator, inputs::{BytesInput, HasTargetBytes}, monitors::MultiMonitor, - mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - mutators::token_mutations::{I2SRandReplace, Tokens}, + mutators::{ + scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + token_mutations::{I2SRandReplace, Tokens}, + }, observers::{HitcountsMapObserver, StdMapObserver, TimeObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::{ShadowTracingStage, StdMutationalStage}, state::{HasCorpus, HasMetadata, StdState}, Error, }; - use libafl_targets::{CmpLogObserver, CMPLOG_MAP, EDGES_MAP, MAX_EDGES_NUM}; +use typed_builder::TypedBuilder; use crate::{CORPUS_CACHE_SIZE, DEFAULT_TIMEOUT_SECS}; @@ -355,12 +356,13 @@ where /// Python bindings for this sugar #[cfg(feature = "python")] pub mod pybind { - use crate::inmemory; - use libafl::bolts::core_affinity::Cores; - use pyo3::prelude::*; - use pyo3::types::PyBytes; use std::path::PathBuf; + use libafl::bolts::core_affinity::Cores; + use pyo3::{prelude::*, types::PyBytes}; + + use crate::inmemory; + /// In-Memory fuzzing made easy. /// Use this sugar for scaling `libfuzzer`-style fuzzers. #[pyclass(unsendable)] diff --git a/libafl_sugar/src/qemu.rs b/libafl_sugar/src/qemu.rs index c2e3e705cf..e93938f468 100644 --- a/libafl_sugar/src/qemu.rs +++ b/libafl_sugar/src/qemu.rs @@ -2,7 +2,6 @@ //! use core::fmt::{self, Debug, Formatter}; use std::{fs, net::SocketAddr, path::PathBuf, time::Duration}; -use typed_builder::TypedBuilder; use libafl::{ bolts::{ @@ -23,19 +22,22 @@ use libafl::{ generators::RandBytesGenerator, inputs::{BytesInput, HasTargetBytes}, monitors::MultiMonitor, - mutators::scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, - mutators::{token_mutations::Tokens, I2SRandReplace}, + mutators::{ + scheduled::{havoc_mutations, tokens_mutations, StdScheduledMutator}, + token_mutations::Tokens, + I2SRandReplace, + }, observers::{HitcountsMapObserver, TimeObserver, VariableMapObserver}, schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler}, stages::{ShadowTracingStage, StdMutationalStage}, state::{HasCorpus, HasMetadata, StdState}, }; - pub use libafl_qemu::emu::Emulator; use libafl_qemu::{ cmplog, edges, QemuCmpLogHelper, QemuEdgeCoverageHelper, QemuExecutor, QemuHooks, }; use libafl_targets::CmpLogObserver; +use typed_builder::TypedBuilder; use crate::{CORPUS_CACHE_SIZE, DEFAULT_TIMEOUT_SECS}; @@ -431,12 +433,13 @@ where /// python bindings for this sugar #[cfg(feature = "python")] pub mod pybind { - use crate::qemu; + use std::path::PathBuf; + use libafl::bolts::core_affinity::Cores; use libafl_qemu::emu::pybind::Emulator; - use pyo3::prelude::*; - use pyo3::types::PyBytes; - use std::path::PathBuf; + use pyo3::{prelude::*, types::PyBytes}; + + use crate::qemu; #[pyclass(unsendable)] struct QemuBytesCoverageSugar { diff --git a/libafl_targets/src/cmplog.rs b/libafl_targets/src/cmplog.rs index c5d093fa65..a85369c9bd 100644 --- a/libafl_targets/src/cmplog.rs +++ b/libafl_targets/src/cmplog.rs @@ -2,9 +2,9 @@ //! The values will then be used in subsequent mutations. //! +use alloc::string::{String, ToString}; use core::fmt::{self, Debug, Formatter}; -use alloc::string::{String, ToString}; use libafl::{ bolts::{ownedref::OwnedRefMut, tuples::Named}, executors::ExitKind, diff --git a/libafl_targets/src/coverage.rs b/libafl_targets/src/coverage.rs index 0f737d2996..8e2e4ca1aa 100644 --- a/libafl_targets/src/coverage.rs +++ b/libafl_targets/src/coverage.rs @@ -1,9 +1,10 @@ //! Coverage maps as static mut array -use crate::{ACCOUNTING_MAP_SIZE, EDGES_MAP_SIZE}; #[cfg(target_os = "linux")] use libafl::{mutators::Tokens, Error}; +use crate::{ACCOUNTING_MAP_SIZE, EDGES_MAP_SIZE}; + /// The map for edges. #[no_mangle] pub static mut __afl_area_ptr_local: [u8; EDGES_MAP_SIZE] = [0; EDGES_MAP_SIZE]; diff --git a/libafl_targets/src/drcov.rs b/libafl_targets/src/drcov.rs index e9953f41c4..fa47d20c7b 100644 --- a/libafl_targets/src/drcov.rs +++ b/libafl_targets/src/drcov.rs @@ -4,14 +4,15 @@ use alloc::{string::String, vec::Vec}; use core::ptr::addr_of; -use libafl::Error; -use rangemap::RangeMap; use std::{ fs::File, io::{BufWriter, Write}, path::Path, }; +use libafl::Error; +use rangemap::RangeMap; + /// A basic block struct #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DrCovBasicBlock { diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000000..44b6aab556 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +group_imports = "StdExternalCrate" +imports_granularity = "Crate" diff --git a/utils/gramatron/construct_automata/src/main.rs b/utils/gramatron/construct_automata/src/main.rs index 7744a045d0..d1615dec33 100644 --- a/utils/gramatron/construct_automata/src/main.rs +++ b/utils/gramatron/construct_automata/src/main.rs @@ -1,17 +1,16 @@ -use clap::{self, StructOpt}; -use lazy_static::lazy_static; -use regex::Regex; -use serde_json::Value; use std::{ collections::{HashMap, HashSet, VecDeque}, fs, io::{BufReader, Write}, - path::Path, - path::PathBuf, + path::{Path, PathBuf}, rc::Rc, }; +use clap::{self, StructOpt}; +use lazy_static::lazy_static; use libafl::generators::gramatron::{Automaton, Trigger}; +use regex::Regex; +use serde_json::Value; #[derive(Debug, StructOpt)] #[clap( diff --git a/utils/libafl_benches/benches/hash_speeds.rs b/utils/libafl_benches/benches/hash_speeds.rs index 6c10255162..04b73a0dc4 100644 --- a/utils/libafl_benches/benches/hash_speeds.rs +++ b/utils/libafl_benches/benches/hash_speeds.rs @@ -1,11 +1,11 @@ //! Compare the speed of rust hash implementations use std::hash::Hasher; -//use xxhash_rust::const_xxh3; -use xxhash_rust::xxh3; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use libafl::bolts::rands::{Rand, StdRand}; +//use xxhash_rust::const_xxh3; +use xxhash_rust::xxh3; fn criterion_benchmark(c: &mut Criterion) { let mut rand = StdRand::with_seed(0);