Use the log facade instead of println (#1060)

* switched a couple of println / dbg statements to use log crate
* Use pyo3-log for logging in python bindings
This commit is contained in:
Fabian Freyer 2023-02-14 10:01:51 +01:00 committed by GitHub
parent 30b51bb810
commit 53dba5f49d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
57 changed files with 362 additions and 360 deletions

View File

@ -159,7 +159,7 @@ jobs:
- name: Run a maturin build - name: Run a maturin build
run: cd ./bindings/pylibafl && python3 -m venv .env && . .env/bin/activate && maturin develop && ./test.sh run: cd ./bindings/pylibafl && python3 -m venv .env && . .env/bin/activate && maturin develop && ./test.sh
- name: Run python test - name: Run python test
run: . ./bindings/pylibafl/.env/bin/activate && cd ./fuzzers/baby_fuzzer && python3 baby_fuzzer.py | grep "Bye" run: . ./bindings/pylibafl/.env/bin/activate && cd ./fuzzers/baby_fuzzer && python3 baby_fuzzer.py 2>&1 | grep "Bye"
fuzzers: fuzzers:
strategy: strategy:

View File

@ -5,6 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
pyo3 = { version = "0.17", features = ["extension-module"] } pyo3 = { version = "0.17", features = ["extension-module"] }
pyo3-log = "0.8.1"
libafl_qemu = { path = "../../libafl_qemu", version = "0.9.0", features = ["python"] } libafl_qemu = { path = "../../libafl_qemu", version = "0.9.0", features = ["python"] }
libafl_sugar = { path = "../../libafl_sugar", version = "0.9.0", features = ["python"] } libafl_sugar = { path = "../../libafl_sugar", version = "0.9.0", features = ["python"] }
libafl = { path = "../../libafl", version = "0.9.0", features = ["python"] } libafl = { path = "../../libafl", version = "0.9.0", features = ["python"] }

View File

@ -84,6 +84,8 @@ def feedback_or_fast(a, b):
#[pymodule] #[pymodule]
#[pyo3(name = "pylibafl")] #[pyo3(name = "pylibafl")]
pub fn python_module(py: Python, m: &PyModule) -> PyResult<()> { pub fn python_module(py: Python, m: &PyModule) -> PyResult<()> {
pyo3_log::init();
let modules = py.import("sys")?.getattr("modules")?; let modules = py.import("sys")?.getattr("modules")?;
let sugar_module = PyModule::new(py, "sugar")?; let sugar_module = PyModule::new(py, "sugar")?;

View File

@ -39,6 +39,8 @@ def stage_wrapper(stage):
return libafl.Stage.new_std_mutational(stage) return libafl.Stage.new_std_mutational(stage)
# CODE WRITTEN BY USER # CODE WRITTEN BY USER
import logging
logging.basicConfig(level=logging.INFO)
map_observer = libafl.OwnedMapObserverI32("signals", [0] * 16) map_observer = libafl.OwnedMapObserverI32("signals", [0] * 16)

View File

@ -91,6 +91,7 @@ prometheus-client = { version= "0.19", optional = true}
tide = { version = "0.16.0", optional = true } tide = { version = "0.16.0", optional = true }
async-std = { version = "1.8.0", features = ["attributes"], optional = true } async-std = { version = "1.8.0", features = ["attributes"], optional = true }
futures = { version = "0.3.24", optional = true } futures = { version = "0.3.24", optional = true }
log = "0.4.17"
wait-timeout = { version = "0.2", optional = true } # used by CommandExecutor to wait for child process wait-timeout = { version = "0.2", optional = true } # used by CommandExecutor to wait for child process

View File

@ -23,7 +23,7 @@
//! fuzz(parsed); //! fuzz(parsed);
//! } //! }
//! //!
//! println!("{:?}", parsed); //! log::info!("{:?}", parsed);
//! } //! }
//! ``` //! ```
//! //!
@ -59,7 +59,7 @@
//! fuzz_with_qemu(parsed); //! fuzz_with_qemu(parsed);
//! } //! }
//! //!
//! println!("{:?}", parsed); //! log::info!("{:?}", parsed);
//! } //! }
//!``` //!```
@ -342,7 +342,7 @@ impl FuzzerOptions {
/// custom_func(sub_matches.get_one::<String>("bar").unwrap()) /// custom_func(sub_matches.get_one::<String>("bar").unwrap())
/// } /// }
/// ///
/// println!("{:?}", matches); /// log::info!("{:?}", matches);
/// } /// }
/// ``` /// ```
#[must_use] #[must_use]

View File

@ -368,7 +368,7 @@ mod windows {
cpu_group = total_cores / 64; cpu_group = total_cores / 64;
cpu_id = id - (cpu_group * 64); cpu_id = id - (cpu_group * 64);
} }
// println!("Setting affinity to group {} and id {}", cpu_group, cpu_id); // log::info!("Setting affinity to group {} and id {}", cpu_group, cpu_id);
// Convert id to mask // Convert id to mask
let mask: usize = 1 << cpu_id; let mask: usize = 1 << cpu_id;

View File

@ -131,7 +131,7 @@ where
let num_cores = core_ids.len(); let num_cores = core_ids.len();
let mut handles = vec![]; let mut handles = vec![];
println!("spawning on cores: {:?}", self.cores); log::info!("spawning on cores: {:?}", self.cores);
#[cfg(feature = "std")] #[cfg(feature = "std")]
let stdout_file = self let stdout_file = self
@ -152,10 +152,10 @@ where
self.shmem_provider.post_fork(false)?; self.shmem_provider.post_fork(false)?;
handles.push(child.pid); handles.push(child.pid);
#[cfg(feature = "std")] #[cfg(feature = "std")]
println!("child spawned and bound to core {id}"); log::info!("child spawned and bound to core {id}");
} }
ForkResult::Child => { ForkResult::Child => {
println!("{:?} PostFork", unsafe { libc::getpid() }); log::info!("{:?} PostFork", unsafe { libc::getpid() });
self.shmem_provider.post_fork(true)?; self.shmem_provider.post_fork(true)?;
#[cfg(feature = "std")] #[cfg(feature = "std")]
@ -188,7 +188,7 @@ where
if self.spawn_broker { if self.spawn_broker {
#[cfg(feature = "std")] #[cfg(feature = "std")]
println!("I am broker!!."); log::info!("I am broker!!.");
// TODO we don't want always a broker here, think about using different laucher process to spawn different configurations // TODO we don't want always a broker here, think about using different laucher process to spawn different configurations
RestartingMgr::<MT, S, SP>::builder() RestartingMgr::<MT, S, SP>::builder()
@ -210,11 +210,11 @@ where
} else { } else {
for handle in &handles { for handle in &handles {
let mut status = 0; let mut status = 0;
println!("Not spawning broker (spawn_broker is false). Waiting for fuzzer children to exit..."); log::info!("Not spawning broker (spawn_broker is false). Waiting for fuzzer children to exit...");
unsafe { unsafe {
libc::waitpid(*handle, &mut status, 0); libc::waitpid(*handle, &mut status, 0);
if status != 0 { if status != 0 {
println!("Client with pid {handle} exited with status {status}"); log::info!("Client with pid {handle} exited with status {status}");
} }
} }
} }
@ -256,14 +256,14 @@ where
#[cfg(windows)] #[cfg(windows)]
if self.stdout_file.is_some() { if self.stdout_file.is_some() {
println!("Child process file stdio is not supported on Windows yet. Dumping to stdout instead..."); log::info!("Child process file stdio is not supported on Windows yet. Dumping to stdout instead...");
} }
let core_ids = core_affinity::get_core_ids().unwrap(); let core_ids = core_affinity::get_core_ids().unwrap();
let num_cores = core_ids.len(); let num_cores = core_ids.len();
let mut handles = vec![]; let mut handles = vec![];
println!("spawning on cores: {:?}", self.cores); log::info!("spawning on cores: {:?}", self.cores);
//spawn clients //spawn clients
for (id, _) in core_ids.iter().enumerate().take(num_cores) { for (id, _) in core_ids.iter().enumerate().take(num_cores) {
@ -287,7 +287,7 @@ where
if self.spawn_broker { if self.spawn_broker {
#[cfg(feature = "std")] #[cfg(feature = "std")]
println!("I am broker!!."); log::info!("I am broker!!.");
RestartingMgr::<MT, S, SP>::builder() RestartingMgr::<MT, S, SP>::builder()
.shmem_provider(self.shmem_provider.clone()) .shmem_provider(self.shmem_provider.clone())
@ -304,11 +304,11 @@ where
handle.kill()?; handle.kill()?;
} }
} else { } else {
println!("Not spawning broker (spawn_broker is false). Waiting for fuzzer children to exit..."); log::info!("Not spawning broker (spawn_broker is false). Waiting for fuzzer children to exit...");
for handle in &mut handles { for handle in &mut handles {
let ecode = handle.wait()?; let ecode = handle.wait()?;
if !ecode.success() { if !ecode.success() {
println!("Client with handle {handle:?} exited with {ecode:?}"); log::info!("Client with handle {handle:?} exited with {ecode:?}");
} }
} }
} }

View File

@ -315,7 +315,7 @@ impl Listener {
Listener::Tcp(inner) => match inner.accept() { Listener::Tcp(inner) => match inner.accept() {
Ok(res) => ListenerStream::Tcp(res.0, res.1), Ok(res) => ListenerStream::Tcp(res.0, res.1),
Err(err) => { Err(err) => {
println!("Ignoring failed accept: {err:?}"); log::warn!("Ignoring failed accept: {err:?}");
ListenerStream::Empty() ListenerStream::Empty()
} }
}, },
@ -403,14 +403,14 @@ where
} }
#[cfg(feature = "llmp_debug")] #[cfg(feature = "llmp_debug")]
println!("LLMP TCP: Sending {} bytes", msg.len()); log::trace!("LLMP TCP: Sending {} bytes", msg.len());
let size_bytes = (msg.len() as u32).to_be_bytes(); let size_bytes = (msg.len() as u32).to_be_bytes();
stream.write_all(&size_bytes)?; stream.write_all(&size_bytes)?;
stream.write_all(&msg)?; stream.write_all(&msg)?;
#[cfg(feature = "llmp_debug")] #[cfg(feature = "llmp_debug")]
println!("LLMP TCP: Sending {} bytes finished.", msg.len()); log::trace!("LLMP TCP: Sending {} bytes finished.", msg.len());
Ok(()) Ok(())
} }
@ -421,7 +421,7 @@ fn recv_tcp_msg(stream: &mut TcpStream) -> Result<Vec<u8>, Error> {
// Always receive one be u32 of size, then the command. // Always receive one be u32 of size, then the command.
#[cfg(feature = "llmp_debug")] #[cfg(feature = "llmp_debug")]
println!( log::trace!(
"LLMP TCP: Waiting for packet... (Timeout: {:?})", "LLMP TCP: Waiting for packet... (Timeout: {:?})",
stream.read_timeout().unwrap_or(None) stream.read_timeout().unwrap_or(None)
); );
@ -433,7 +433,7 @@ fn recv_tcp_msg(stream: &mut TcpStream) -> Result<Vec<u8>, Error> {
bytes.resize(size as usize, 0_u8); bytes.resize(size as usize, 0_u8);
#[cfg(feature = "llmp_debug")] #[cfg(feature = "llmp_debug")]
println!("LLMP TCP: Receiving payload of size {size}"); log::trace!("LLMP TCP: Receiving payload of size {size}");
stream stream
.read_exact(&mut bytes) .read_exact(&mut bytes)
@ -456,12 +456,12 @@ fn next_shmem_size(max_alloc: usize) -> usize {
/// Initialize a new `llmp_page`. The size should be relative to /// Initialize a new `llmp_page`. The size should be relative to
/// `llmp_page->messages` /// `llmp_page->messages`
unsafe fn _llmp_page_init<SHM: ShMem>(shmem: &mut SHM, sender_id: ClientId, allow_reinit: bool) { unsafe fn _llmp_page_init<SHM: ShMem>(shmem: &mut SHM, sender_id: ClientId, allow_reinit: bool) {
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("_llmp_page_init: shmem {:?}", &shmem); log::trace!("_llmp_page_init: shmem {:?}", &shmem);
let map_size = shmem.len(); let map_size = shmem.len();
let page = shmem2page_mut(shmem); let page = shmem2page_mut(shmem);
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("_llmp_page_init: page {:?}", &(*page)); log::trace!("_llmp_page_init: page {:?}", &(*page));
if !allow_reinit { if !allow_reinit {
assert!( assert!(
@ -631,7 +631,7 @@ where
match tcp_bind(port) { match tcp_bind(port) {
Ok(listener) => { Ok(listener) => {
// We got the port. We are the broker! :) // We got the port. We are the broker! :)
println!("We're the broker"); log::info!("We're the broker");
let mut broker = LlmpBroker::new(shmem_provider)?; let mut broker = LlmpBroker::new(shmem_provider)?;
let _listener_thread = broker.launch_listener(Listener::Tcp(listener))?; let _listener_thread = broker.launch_listener(Listener::Tcp(listener))?;
@ -639,12 +639,15 @@ where
} }
Err(Error::File(e, _)) if e.kind() == ErrorKind::AddrInUse => { Err(Error::File(e, _)) if e.kind() == ErrorKind::AddrInUse => {
// We are the client :) // We are the client :)
println!("We're the client (internal port already bound by broker, {e:#?})"); log::info!("We're the client (internal port already bound by broker, {e:#?})");
Ok(LlmpConnection::IsClient { Ok(LlmpConnection::IsClient {
client: LlmpClient::create_attach_to_tcp(shmem_provider, port)?, client: LlmpClient::create_attach_to_tcp(shmem_provider, port)?,
}) })
} }
Err(e) => Err(dbg!(e)), Err(e) => {
log::error!("{e:?}");
Err(e)
}
} }
} }
@ -865,7 +868,7 @@ where
{ {
ctr = ctr.wrapping_add(1); ctr = ctr.wrapping_add(1);
if ctr == 0 { if ctr == 0 {
println!("Awaiting safe_to_unmap_blocking"); log::info!("Awaiting safe_to_unmap_blocking");
} }
} }
} }
@ -875,7 +878,7 @@ where
pub fn safe_to_unmap(&self) -> bool { pub fn safe_to_unmap(&self) -> bool {
let current_out_shmem = self.out_shmems.last().unwrap(); let current_out_shmem = self.out_shmems.last().unwrap();
unsafe { unsafe {
// println!("Reading safe_to_unmap from {:?}", current_out_shmem.page() as *const _); // log::info!("Reading safe_to_unmap from {:?}", current_out_shmem.page() as *const _);
(*current_out_shmem.page()) (*current_out_shmem.page())
.safe_to_unmap .safe_to_unmap
.load(Ordering::Relaxed) .load(Ordering::Relaxed)
@ -991,10 +994,13 @@ where
"Called alloc without calling send inbetween" "Called alloc without calling send inbetween"
); );
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!( log::info!(
"Allocating {} bytes on page {:?} / map {:?} (last msg: {:?})", "Allocating {} bytes on page {:?} / map {:?} (last msg: {:?})",
buf_len, page, &map, last_msg buf_len,
page,
&map,
last_msg
); );
let msg_start = (*page).messages.as_mut_ptr() as usize + (*page).size_used; let msg_start = (*page).messages.as_mut_ptr() as usize + (*page).size_used;
@ -1004,9 +1010,9 @@ where
- msg_start - msg_start
- size_of::<LlmpMsg>(); - size_of::<LlmpMsg>();
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
dbg!( log::trace!(
page, "{page:?} {:?} size_used={:x} buf_len_padded={:x} EOP_MSG_SIZE={:x} size_total={}",
&(*page), &(*page),
(*page).size_used, (*page).size_used,
buf_len_padded, buf_len_padded,
@ -1018,8 +1024,8 @@ where
if (*page).size_used + size_of::<LlmpMsg>() + buf_len_padded + EOP_MSG_SIZE if (*page).size_used + size_of::<LlmpMsg>() + buf_len_padded + EOP_MSG_SIZE
> (*page).size_total > (*page).size_total
{ {
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("LLMP: Page full."); log::info!("LLMP: Page full.");
/* We're full. */ /* We're full. */
return None; return None;
@ -1062,7 +1068,7 @@ where
/// If `overwrite_client_id` is `false`, the message's `sender` won't be touched (for broker forwarding) /// If `overwrite_client_id` is `false`, the message's `sender` won't be touched (for broker forwarding)
#[inline(never)] // Not inlined to make cpu-level reodering (hopefully?) improbable #[inline(never)] // Not inlined to make cpu-level reodering (hopefully?) improbable
unsafe fn send(&mut self, msg: *mut LlmpMsg, overwrite_client_id: bool) -> Result<(), Error> { unsafe fn send(&mut self, msg: *mut LlmpMsg, overwrite_client_id: bool) -> Result<(), Error> {
// dbg!("Sending msg {:?}", msg); // log::info!("Sending msg {:?}", msg);
assert!(self.last_msg_sent != msg, "Message sent twice!"); assert!(self.last_msg_sent != msg, "Message sent twice!");
assert!( assert!(
@ -1102,7 +1108,7 @@ where
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
let bt = "<n/a (release)>"; let bt = "<n/a (release)>";
let shm = self.out_shmems.last().unwrap(); let shm = self.out_shmems.last().unwrap();
println!( log::info!(
"LLMP_DEBUG: End of page reached for map {} with len {}, sending EOP, bt: {:?}", "LLMP_DEBUG: End of page reached for map {} with len {}, sending EOP, bt: {:?}",
shm.shmem.id(), shm.shmem.id(),
shm.shmem.len(), shm.shmem.len(),
@ -1112,8 +1118,8 @@ where
let old_map = self.out_shmems.last_mut().unwrap().page_mut(); let old_map = self.out_shmems.last_mut().unwrap().page_mut();
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!( log::info!(
"Next ShMem Size {}", "Next ShMem Size {}",
next_shmem_size((*old_map).max_alloc_size) next_shmem_size((*old_map).max_alloc_size)
); );
@ -1126,16 +1132,16 @@ where
); );
let mut new_map = new_map_shmem.page_mut(); let mut new_map = new_map_shmem.page_mut();
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("got new map at: {new_map:?}"); log::info!("got new map at: {new_map:?}");
(*new_map).current_msg_id.store( (*new_map).current_msg_id.store(
(*old_map).current_msg_id.load(Ordering::Relaxed), (*old_map).current_msg_id.load(Ordering::Relaxed),
Ordering::Relaxed, Ordering::Relaxed,
); );
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("Setting max alloc size: {:?}", (*old_map).max_alloc_size); log::info!("Setting max alloc size: {:?}", (*old_map).max_alloc_size);
(*new_map).max_alloc_size = (*old_map).max_alloc_size; (*new_map).max_alloc_size = (*old_map).max_alloc_size;
@ -1158,8 +1164,8 @@ where
// If we want to get red if old pages, (client to broker), do that now // If we want to get red if old pages, (client to broker), do that now
if !self.keep_pages_forever { if !self.keep_pages_forever {
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("pruning"); log::info!("pruning");
self.prune_old_pages(); self.prune_old_pages();
} }
@ -1177,8 +1183,8 @@ where
self.handle_out_eop()?; self.handle_out_eop()?;
} }
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("Handled out eop"); log::info!("Handled out eop");
match unsafe { self.alloc_next_if_space(buf_len) } { match unsafe { self.alloc_next_if_space(buf_len) } {
Some(msg) => Ok(msg), Some(msg) => Ok(msg),
@ -1442,8 +1448,7 @@ where
return Err(Error::shutting_down()); return Err(Error::shutting_down());
} }
LLMP_TAG_END_OF_PAGE => { LLMP_TAG_END_OF_PAGE => {
#[cfg(feature = "std")] log::info!("Received end of page, allocating next");
println!("Received end of page, allocating next");
// Handle end of page // Handle end of page
assert!( assert!(
(*msg).buf_len >= size_of::<LlmpPayloadSharedMapInfo>() as u64, (*msg).buf_len >= size_of::<LlmpPayloadSharedMapInfo>() as u64,
@ -1477,8 +1482,8 @@ where
// Mark the new page save to unmap also (it's mapped by us, the broker now) // Mark the new page save to unmap also (it's mapped by us, the broker now)
(*page).safe_to_unmap.store(1, Ordering::Relaxed); (*page).safe_to_unmap.store(1, Ordering::Relaxed);
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!( log::info!(
"LLMP_DEBUG: Got a new recv map {} with len {:?}", "LLMP_DEBUG: Got a new recv map {} with len {:?}",
self.current_recv_shmem.shmem.id(), self.current_recv_shmem.shmem.id(),
self.current_recv_shmem.shmem.len() self.current_recv_shmem.shmem.len()
@ -1610,8 +1615,8 @@ where
{ {
/// Creates a new page, initializing the passed shared mem struct /// Creates a new page, initializing the passed shared mem struct
pub fn new(sender: ClientId, mut new_shmem: SHM) -> Self { pub fn new(sender: ClientId, mut new_shmem: SHM) -> Self {
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!( log::info!(
"LLMP_DEBUG: Initializing map on {} with size {}", "LLMP_DEBUG: Initializing map on {} with size {}",
new_shmem.id(), new_shmem.id(),
new_shmem.len() new_shmem.len()
@ -1625,13 +1630,13 @@ where
/// Maps and wraps an existing /// Maps and wraps an existing
pub fn existing(existing_shmem: SHM) -> Self { pub fn existing(existing_shmem: SHM) -> Self {
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
//{ //{
//#[cfg(debug_assertions)] //#[cfg(debug_assertions)]
//let bt = Backtrace::new(); //let bt = Backtrace::new();
//#[cfg(not(debug_assertions))] //#[cfg(not(debug_assertions))]
//let bt = "<n/a (release)>"; //let bt = "<n/a (release)>";
println!( log::info!(
"LLMP_DEBUG: Using existing map {} with size {}", "LLMP_DEBUG: Using existing map {} with size {}",
existing_shmem.id(), existing_shmem.id(),
existing_shmem.len(), existing_shmem.len(),
@ -1648,8 +1653,8 @@ where
"Map was not priviously initialized at {:?}", "Map was not priviously initialized at {:?}",
&ret.shmem &ret.shmem
); );
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("PAGE: {:?}", &(*ret.page())); log::info!("PAGE: {:?}", &(*ret.page()));
} }
ret ret
} }
@ -1847,13 +1852,13 @@ where
A: ToSocketAddrs, A: ToSocketAddrs,
{ {
let mut stream = TcpStream::connect(addr)?; let mut stream = TcpStream::connect(addr)?;
println!("B2B: Connected to {stream:?}"); log::info!("B2B: Connected to {stream:?}");
match recv_tcp_msg(&mut stream)?.try_into()? { match recv_tcp_msg(&mut stream)?.try_into()? {
TcpResponse::BrokerConnectHello { TcpResponse::BrokerConnectHello {
broker_shmem_description: _, broker_shmem_description: _,
hostname, hostname,
} => println!("B2B: Connected to {hostname}"), } => log::info!("B2B: Connected to {hostname}"),
_ => { _ => {
return Err(Error::illegal_state( return Err(Error::illegal_state(
"Unexpected response from B2B server received.".to_string(), "Unexpected response from B2B server received.".to_string(),
@ -1870,7 +1875,7 @@ where
let broker_id = match recv_tcp_msg(&mut stream)?.try_into()? { let broker_id = match recv_tcp_msg(&mut stream)?.try_into()? {
TcpResponse::RemoteBrokerAccepted { broker_id } => { TcpResponse::RemoteBrokerAccepted { broker_id } => {
println!("B2B: Got Connection Ack, broker_id {broker_id}"); log::info!("B2B: Got Connection Ack, broker_id {broker_id}");
broker_id broker_id
} }
_ => { _ => {
@ -1881,7 +1886,7 @@ where
}; };
// TODO: use broker ids! // TODO: use broker ids!
println!("B2B: We are broker {broker_id}"); log::info!("B2B: We are broker {broker_id}");
// TODO: handle broker_ids properly/at all. // TODO: handle broker_ids properly/at all.
let map_description = Self::b2b_thread_on( let map_description = Self::b2b_thread_on(
@ -1978,8 +1983,7 @@ where
#[cfg(unix)] #[cfg(unix)]
if let Err(_e) = unsafe { setup_signal_handler(&mut LLMP_SIGHANDLER_STATE) } { if let Err(_e) = unsafe { setup_signal_handler(&mut LLMP_SIGHANDLER_STATE) } {
// We can live without a proper ctrl+c signal handler. Print and ignore. // We can live without a proper ctrl+c signal handler. Print and ignore.
#[cfg(feature = "std")] log::info!("Failed to setup signal handlers: {_e}");
println!("Failed to setup signal handlers: {_e}");
} }
let timeout = timeout.as_millis() as u64; let timeout = timeout.as_millis() as u64;
@ -2026,8 +2030,7 @@ where
#[cfg(unix)] #[cfg(unix)]
if let Err(_e) = unsafe { setup_signal_handler(&mut LLMP_SIGHANDLER_STATE) } { if let Err(_e) = unsafe { setup_signal_handler(&mut LLMP_SIGHANDLER_STATE) } {
// We can live without a proper ctrl+c signal handler. Print and ignore. // We can live without a proper ctrl+c signal handler. Print and ignore.
#[cfg(feature = "std")] log::info!("Failed to setup signal handlers: {_e}");
println!("Failed to setup signal handlers: {_e}");
} }
while !self.is_shutting_down() { while !self.is_shutting_down() {
@ -2065,7 +2068,7 @@ where
pub fn launch_tcp_listener_on(&mut self, port: u16) -> Result<thread::JoinHandle<()>, Error> { pub fn launch_tcp_listener_on(&mut self, port: u16) -> Result<thread::JoinHandle<()>, Error> {
let listener = tcp_bind(port)?; let listener = tcp_bind(port)?;
// accept connections and process them, spawning a new thread for each one // accept connections and process them, spawning a new thread for each one
println!("Server listening on port {port}"); log::info!("Server listening on port {port}");
self.launch_listener(Listener::Tcp(listener)) self.launch_listener(Listener::Tcp(listener))
} }
@ -2113,7 +2116,7 @@ where
let shmem_provider_bg = SP::new().unwrap(); let shmem_provider_bg = SP::new().unwrap();
#[cfg(fature = "llmp_debug")] #[cfg(fature = "llmp_debug")]
println!("B2b: Spawned proxy thread"); log::info!("B2b: Spawned proxy thread");
// The background thread blocks on the incoming connection for 15 seconds (if no data is available), then checks if it should forward own messages, then blocks some more. // The background thread blocks on the incoming connection for 15 seconds (if no data is available), then checks if it should forward own messages, then blocks some more.
stream stream
@ -2141,8 +2144,8 @@ where
) )
.expect("Failed to map local page in broker 2 broker thread!"); .expect("Failed to map local page in broker 2 broker thread!");
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("B2B: Starting proxy loop :)"); log::info!("B2B: Starting proxy loop :)");
let peer_address = stream.peer_addr().unwrap(); let peer_address = stream.peer_addr().unwrap();
@ -2153,14 +2156,14 @@ where
Ok(None) => break, // no more data to forward Ok(None) => break, // no more data to forward
Ok(Some((client_id, tag, flags, payload))) => { Ok(Some((client_id, tag, flags, payload))) => {
if client_id == b2b_client_id { if client_id == b2b_client_id {
println!( log::info!(
"Ignored message we probably sent earlier (same id), TAG: {tag:x}" "Ignored message we probably sent earlier (same id), TAG: {tag:x}"
); );
continue; continue;
} }
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!( log::info!(
"Fowarding message ({} bytes) via broker2broker connection", "Fowarding message ({} bytes) via broker2broker connection",
payload.len() payload.len()
); );
@ -2174,12 +2177,12 @@ where
payload: payload.to_vec(), payload: payload.to_vec(),
}, },
) { ) {
println!("Got error {e} while trying to forward a message to broker {peer_address}, exiting thread"); log::info!("Got error {e} while trying to forward a message to broker {peer_address}, exiting thread");
return; return;
} }
} }
Err(Error::ShuttingDown) => { Err(Error::ShuttingDown) => {
println!("Local broker is shutting down, exiting thread"); log::info!("Local broker is shutting down, exiting thread");
return; return;
} }
Err(e) => panic!("Error reading from local page! {e}"), Err(e) => panic!("Error reading from local page! {e}"),
@ -2198,8 +2201,8 @@ where
"Illegal message received from broker 2 broker connection - shutting down.", "Illegal message received from broker 2 broker connection - shutting down.",
); );
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!( log::info!(
"Fowarding incoming message ({} bytes) from broker2broker connection", "Fowarding incoming message ({} bytes) from broker2broker connection",
msg.payload.len() msg.payload.len()
); );
@ -2217,15 +2220,15 @@ where
Err(e) => { Err(e) => {
if let Error::File(e, _) = e { if let Error::File(e, _) = e {
if e.kind() == ErrorKind::UnexpectedEof { if e.kind() == ErrorKind::UnexpectedEof {
println!( log::info!(
"Broker {peer_address} seems to have disconnected, exiting" "Broker {peer_address} seems to have disconnected, exiting"
); );
return; return;
} }
} }
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("Received no input, timeout or closed. Looping back up :)"); log::info!("Received no input, timeout or closed. Looping back up :)");
} }
} }
} }
@ -2235,8 +2238,8 @@ where
Error::unknown("Error launching background thread for b2b communcation".to_string()) Error::unknown("Error launching background thread for b2b communcation".to_string())
}); });
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(feature = "llmp_debug")]
println!("B2B: returning from loop. Success: {}", ret.is_ok()); log::info!("B2B: returning from loop. Success: {}", ret.is_ok());
ret ret
} }
@ -2254,7 +2257,7 @@ where
TcpRequest::LocalClientHello { shmem_description } => { TcpRequest::LocalClientHello { shmem_description } => {
match Self::announce_new_client(sender, shmem_description) { match Self::announce_new_client(sender, shmem_description) {
Ok(()) => (), Ok(()) => (),
Err(e) => println!("Error forwarding client on map: {e:?}"), Err(e) => log::info!("Error forwarding client on map: {e:?}"),
}; };
if let Err(e) = send_tcp_msg( if let Err(e) = send_tcp_msg(
@ -2263,12 +2266,12 @@ where
client_id: *current_client_id, client_id: *current_client_id,
}, },
) { ) {
println!("An error occurred sending via tcp {e}"); log::info!("An error occurred sending via tcp {e}");
}; };
*current_client_id += 1; *current_client_id += 1;
} }
TcpRequest::RemoteBrokerHello { hostname } => { TcpRequest::RemoteBrokerHello { hostname } => {
println!("B2B new client: {hostname}"); log::info!("B2B new client: {hostname}");
// TODO: Clean up broker ids. // TODO: Clean up broker ids.
if send_tcp_msg( if send_tcp_msg(
@ -2279,7 +2282,7 @@ where
) )
.is_err() .is_err()
{ {
println!("Error accepting broker, ignoring."); log::info!("Error accepting broker, ignoring.");
return; return;
} }
@ -2287,7 +2290,7 @@ where
Self::b2b_thread_on(stream, *current_client_id, broker_shmem_description) Self::b2b_thread_on(stream, *current_client_id, broker_shmem_description)
{ {
if Self::announce_new_client(sender, &shmem_description).is_err() { if Self::announce_new_client(sender, &shmem_description).is_err() {
println!("B2B: Error announcing client {shmem_description:?}"); log::info!("B2B: Error announcing client {shmem_description:?}");
}; };
*current_client_id += 1; *current_client_id += 1;
} }
@ -2347,7 +2350,7 @@ where
loop { loop {
match listener.accept() { match listener.accept() {
ListenerStream::Tcp(mut stream, addr) => { ListenerStream::Tcp(mut stream, addr) => {
eprintln!( log::info!(
"New connection: {:?}/{:?}", "New connection: {:?}/{:?}",
addr, addr,
stream.peer_addr().unwrap() stream.peer_addr().unwrap()
@ -2358,7 +2361,7 @@ where
match send_tcp_msg(&mut stream, &broker_hello) { match send_tcp_msg(&mut stream, &broker_hello) {
Ok(()) => {} Ok(()) => {}
Err(e) => { Err(e) => {
eprintln!("Error sending initial hello: {e:?}"); log::error!("Error sending initial hello: {e:?}");
continue; continue;
} }
} }
@ -2366,14 +2369,14 @@ where
let buf = match recv_tcp_msg(&mut stream) { let buf = match recv_tcp_msg(&mut stream) {
Ok(buf) => buf, Ok(buf) => buf,
Err(e) => { Err(e) => {
eprintln!("Error receving from tcp: {e:?}"); log::error!("Error receving from tcp: {e:?}");
continue; continue;
} }
}; };
let req = match buf.try_into() { let req = match buf.try_into() {
Ok(req) => req, Ok(req) => req,
Err(e) => { Err(e) => {
eprintln!("Could not deserialize tcp message: {e:?}"); log::error!("Could not deserialize tcp message: {e:?}");
continue; continue;
} }
}; };
@ -2436,8 +2439,7 @@ where
add it to the list! Also, no need to forward this msg. */ add it to the list! Also, no need to forward this msg. */
let msg_buf_len_padded = (*msg).buf_len_padded; let msg_buf_len_padded = (*msg).buf_len_padded;
if (*msg).buf_len < size_of::<LlmpPayloadSharedMapInfo>() as u64 { if (*msg).buf_len < size_of::<LlmpPayloadSharedMapInfo>() as u64 {
#[cfg(feature = "std")] log::info!("Ignoring broken CLIENT_ADDED msg due to incorrect size. Expected {} but got {}",
println!("Ignoring broken CLIENT_ADDED msg due to incorrect size. Expected {} but got {}",
msg_buf_len_padded, msg_buf_len_padded,
size_of::<LlmpPayloadSharedMapInfo>() size_of::<LlmpPayloadSharedMapInfo>()
); );
@ -2467,8 +2469,7 @@ where
}); });
} }
Err(e) => { Err(e) => {
#[cfg(feature = "std")] log::info!("Error adding client! Ignoring: {e:?}");
println!("Error adding client! Ignoring: {e:?}");
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
return Err(Error::unknown(format!( return Err(Error::unknown(format!(
"Error adding client! PANIC! {e:?}" "Error adding client! PANIC! {e:?}"
@ -2751,7 +2752,7 @@ where
match TcpStream::connect((_LLMP_CONNECT_ADDR, port)) { match TcpStream::connect((_LLMP_CONNECT_ADDR, port)) {
Ok(stream) => break stream, Ok(stream) => break stream,
Err(_) => { Err(_) => {
println!("Connection Refused.. Retrying"); log::info!("Connection Refused.. Retrying");
} }
} }
} }
@ -2760,7 +2761,7 @@ where
} }
} }
}; };
println!("Connected to port {port}"); log::info!("Connected to port {port}");
let TcpResponse::BrokerConnectHello { let TcpResponse::BrokerConnectHello {
broker_shmem_description, broker_shmem_description,
@ -2847,10 +2848,10 @@ mod tests {
client.to_env("_ENV_TEST").unwrap(); client.to_env("_ENV_TEST").unwrap();
#[cfg(all(feature = "llmp_debug", feature = "std"))] #[cfg(all(feature = "llmp_debug", feature = "std"))]
dbg!(std::env::vars()); log::info!("{:?}", std::env::vars());
for (key, value) in std::env::vars_os() { for (key, value) in std::env::vars_os() {
println!("{key:?}: {value:?}"); log::info!("{key:?}: {value:?}");
} }
/* recreate the client from env, check if it still works */ /* recreate the client from env, check if it still works */

View File

@ -122,7 +122,7 @@ where
#[allow(clippy::similar_names)] // id and fd #[allow(clippy::similar_names)] // id and fd
fn send_receive(&mut self, request: ServedShMemRequest) -> Result<(i32, i32), Error> { fn send_receive(&mut self, request: ServedShMemRequest) -> Result<(i32, i32), Error> {
//let bt = Backtrace::new(); //let bt = Backtrace::new();
//println!("Sending {:?} with bt:\n{:?}", request, bt); //log::info!("Sending {:?} with bt:\n{:?}", request, bt);
let body = postcard::to_allocvec(&request)?; let body = postcard::to_allocvec(&request)?;
@ -347,7 +347,7 @@ pub struct ShMemServiceThread {
impl Drop for ShMemServiceThread { impl Drop for ShMemServiceThread {
fn drop(&mut self) { fn drop(&mut self) {
if self.join_handle.is_some() { if self.join_handle.is_some() {
println!("Stopping ShMemService"); log::info!("Stopping ShMemService");
let Ok(mut stream) = UnixStream::connect_to_unix_addr( let Ok(mut stream) = UnixStream::connect_to_unix_addr(
&UnixSocketAddr::new(UNIX_SERVER_NAME).unwrap(), &UnixSocketAddr::new(UNIX_SERVER_NAME).unwrap(),
) else { return }; ) else { return };
@ -404,12 +404,12 @@ where
*lock.lock().unwrap() = ShMemServiceStatus::Failed; *lock.lock().unwrap() = ShMemServiceStatus::Failed;
cvar.notify_one(); cvar.notify_one();
println!("Error creating ShMemService: {e:?}"); log::error!("Error creating ShMemService: {e:?}");
return Err(e); return Err(e);
} }
}; };
if let Err(e) = worker.listen(UNIX_SERVER_NAME, &childsyncpair) { if let Err(e) = worker.listen(UNIX_SERVER_NAME, &childsyncpair) {
println!("Error spawning ShMemService: {e:?}"); log::error!("Error spawning ShMemService: {e:?}");
Err(e) Err(e)
} else { } else {
Ok(()) Ok(())
@ -430,7 +430,7 @@ where
match status { match status {
ShMemServiceStatus::Starting => panic!("Unreachable"), ShMemServiceStatus::Starting => panic!("Unreachable"),
ShMemServiceStatus::Started => { ShMemServiceStatus::Started => {
println!("Started ShMem Service"); log::info!("Started ShMem Service");
// We got a service // We got a service
Self::Started { Self::Started {
bg_thread: Arc::new(Mutex::new(ShMemServiceThread { bg_thread: Arc::new(Mutex::new(ShMemServiceThread {
@ -494,7 +494,7 @@ where
fn handle_request(&mut self, client_id: RawFd) -> Result<ServedShMemResponse<SP>, Error> { fn handle_request(&mut self, client_id: RawFd) -> Result<ServedShMemResponse<SP>, Error> {
let request = self.read_request(client_id)?; let request = self.read_request(client_id)?;
// println!("got ashmem client: {}, request:{:?}", client_id, request); // log::trace!("got ashmem client: {}, request:{:?}", client_id, request);
// Handle the client request // Handle the client request
let response = match request { let response = match request {
@ -572,12 +572,12 @@ where
} }
} }
ServedShMemRequest::Exit => { ServedShMemRequest::Exit => {
println!("ShMemService - Exiting"); log::info!("ShMemService - Exiting");
// stopping the server // stopping the server
return Err(Error::shutting_down()); return Err(Error::shutting_down());
} }
}; };
// println!("send ashmem client: {}, response: {:?}", client_id, &response); // log::info!("send ashmem client: {}, response: {:?}", client_id, &response);
response response
} }
@ -659,7 +659,7 @@ where
Ok(num_fds) if num_fds > 0 => (), Ok(num_fds) if num_fds > 0 => (),
Ok(_) => continue, Ok(_) => continue,
Err(e) => { Err(e) => {
println!("Error polling for activity: {e:?}"); log::error!("Error polling for activity: {e:?}");
continue; continue;
} }
}; };
@ -675,7 +675,7 @@ where
match self.handle_client(raw_polled_fd) { match self.handle_client(raw_polled_fd) {
Ok(()) => (), Ok(()) => (),
Err(e) => { Err(e) => {
dbg!("Ignoring failed read from client", e, poll_fd); log::info!("Ignoring failed read from client {e:?} {poll_fd:?}");
continue; continue;
} }
}; };
@ -683,12 +683,12 @@ where
let (stream, _addr) = match listener.accept_unix_addr() { let (stream, _addr) = match listener.accept_unix_addr() {
Ok(stream_val) => stream_val, Ok(stream_val) => stream_val,
Err(e) => { Err(e) => {
println!("Error accepting client: {e:?}"); log::error!("Error accepting client: {e:?}");
continue; continue;
} }
}; };
println!("Recieved connection from {_addr:?}"); log::info!("Received connection from {_addr:?}");
let pollfd = PollFd::new( let pollfd = PollFd::new(
stream.as_raw_fd(), stream.as_raw_fd(),
PollFlags::POLLIN | PollFlags::POLLRDNORM | PollFlags::POLLRDBAND, PollFlags::POLLIN | PollFlags::POLLRDNORM | PollFlags::POLLRDBAND,
@ -700,16 +700,16 @@ where
match self.handle_client(client_id) { match self.handle_client(client_id) {
Ok(()) => (), Ok(()) => (),
Err(Error::ShuttingDown) => { Err(Error::ShuttingDown) => {
println!("Shutting down"); log::info!("Shutting down");
return Ok(()); return Ok(());
} }
Err(e) => { Err(e) => {
dbg!("Ignoring failed read from client", e); log::info!("Ignoring failed read from client {e:?}");
} }
}; };
} }
} else { } else {
//println!("Unknown revents flags: {:?}", revents); //log::warn!("Unknown revents flags: {:?}", revents);
} }
} }
} }

View File

@ -349,7 +349,7 @@ pub unsafe extern "system" fn handle_exception(
.unwrap() .unwrap()
.ExceptionCode; .ExceptionCode;
let exception_code = ExceptionCode::try_from(code.0).unwrap(); let exception_code = ExceptionCode::try_from(code.0).unwrap();
// println!("Received exception; code: {exception_code}"); // log::info!("Received exception; code: {}", exception_code);
internal_handle_exception(exception_code, exception_pointers) internal_handle_exception(exception_code, exception_pointers)
} }
@ -359,7 +359,7 @@ extern "C" {
} }
unsafe extern "C" fn handle_signal(_signum: i32) { unsafe extern "C" fn handle_signal(_signum: i32) {
// println!("Received signal {}", _signum); // log::info!("Received signal {}", _signum);
internal_handle_exception(ExceptionCode::AssertionFailure, ptr::null_mut()); internal_handle_exception(ExceptionCode::AssertionFailure, ptr::null_mut());
} }

View File

@ -428,7 +428,7 @@ mod tests {
rng: StdRand::with_seed(0), rng: StdRand::with_seed(0),
}; };
println!("random value: {}", mutator.rng.next_u32()); log::info!("random value: {}", mutator.rng.next_u32());
} }
} }

View File

@ -141,7 +141,7 @@ where
))); )));
} }
/*println!( /*log::info!(
"Storing {} bytes to tmpfile {} (larger than map of {} bytes)", "Storing {} bytes to tmpfile {} (larger than map of {} bytes)",
serialized.len(), serialized.len(),
&filename, &filename,
@ -275,7 +275,7 @@ mod tests {
assert!(state_restorer.has_content()); assert!(state_restorer.has_content());
let restored = state_restorer.restore::<String>().unwrap().unwrap(); let restored = state_restorer.restore::<String>().unwrap().unwrap();
println!("Restored {restored}"); log::info!("Restored {restored}");
assert_eq!(restored, "hello world"); assert_eq!(restored, "hello world");
assert!(!state_restorer.content().is_disk); assert!(!state_restorer.content().is_disk);

View File

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

View File

@ -281,8 +281,7 @@ where
} => { } => {
let (_, _) = (severity_level, message); let (_, _) = (severity_level, message);
// TODO rely on Monitor // TODO rely on Monitor
#[cfg(feature = "std")] log::log!((*severity_level).into(), "{message}");
println!("[LOG {severity_level}]: {message}");
Ok(BrokerEventResult::Handled) Ok(BrokerEventResult::Handled)
} }
Event::CustomBuf { .. } => Ok(BrokerEventResult::Forward), Event::CustomBuf { .. } => Ok(BrokerEventResult::Forward),
@ -441,8 +440,7 @@ where
time: _, time: _,
executions: _, executions: _,
} => { } => {
#[cfg(feature = "std")] log::info!("Received new Testcase from {_client_id} ({client_config:?})");
println!("Received new Testcase from {_client_id} ({client_config:?})");
let _res = if client_config.match_with(&self.configuration) let _res = if client_config.match_with(&self.configuration)
&& observers_buf.is_some() && observers_buf.is_some()
@ -455,9 +453,8 @@ where
state, executor, self, input, false, state, executor, self, input, false,
)? )?
}; };
#[cfg(feature = "std")]
if let Some(item) = _res.1 { if let Some(item) = _res.1 {
println!("Added received Testcase as item #{item}"); log::info!("Added received Testcase as item #{item}");
} }
Ok(()) Ok(())
} }
@ -864,7 +861,7 @@ where
let broker_things = |mut broker: LlmpEventBroker<S::Input, MT, SP>, let broker_things = |mut broker: LlmpEventBroker<S::Input, MT, SP>,
remote_broker_addr| { remote_broker_addr| {
if let Some(remote_broker_addr) = remote_broker_addr { if let Some(remote_broker_addr) = remote_broker_addr {
println!("B2b: Connecting to {:?}", &remote_broker_addr); log::info!("B2b: Connecting to {:?}", &remote_broker_addr);
broker.connect_b2b(remote_broker_addr)?; broker.connect_b2b(remote_broker_addr)?;
}; };
@ -884,7 +881,7 @@ where
)?; )?;
// Yep, broker. Just loop here. // Yep, broker. Just loop here.
println!( log::info!(
"Doing broker things. Run this tool again to start fuzzing in a client." "Doing broker things. Run this tool again to start fuzzing in a client."
); );
@ -923,7 +920,7 @@ where
if let Some(core_id) = core_id { if let Some(core_id) = core_id {
let core_id: CoreId = core_id; let core_id: CoreId = core_id;
println!("Setting core affinity to {core_id:?}"); log::info!("Setting core affinity to {core_id:?}");
core_id.set_affinity()?; core_id.set_affinity()?;
} }
@ -957,14 +954,13 @@ where
#[cfg(unix)] #[cfg(unix)]
if let Err(_e) = unsafe { setup_signal_handler(&mut SHUTDOWN_SIGHANDLER_DATA) } { if let Err(_e) = unsafe { setup_signal_handler(&mut SHUTDOWN_SIGHANDLER_DATA) } {
// We can live without a proper ctrl+c signal handler. Print and ignore. // We can live without a proper ctrl+c signal handler. Print and ignore.
#[cfg(feature = "std")] log::error!("Failed to setup signal handlers: {_e}");
println!("Failed to setup signal handlers: {_e}");
} }
let mut ctr: u64 = 0; let mut ctr: u64 = 0;
// Client->parent loop // Client->parent loop
loop { loop {
println!("Spawning next client (id {ctr})"); log::info!("Spawning next client (id {ctr})");
// On Unix, we fork (when fork feature is enabled) // On Unix, we fork (when fork feature is enabled)
#[cfg(all(unix, feature = "fork"))] #[cfg(all(unix, feature = "fork"))]
@ -1035,7 +1031,7 @@ where
), ),
) )
} else { } else {
println!("First run. Let's set it all up"); log::info!("First run. Let's set it all up");
// Mgr to send and receive msgs from/to all other fuzzer instances // Mgr to send and receive msgs from/to all other fuzzer instances
let mgr = LlmpEventManager::<S, SP>::existing_client_from_env( let mgr = LlmpEventManager::<S, SP>::existing_client_from_env(
new_shmem_provider, new_shmem_provider,
@ -1211,8 +1207,7 @@ where
time: _, time: _,
executions: _, executions: _,
} => { } => {
#[cfg(feature = "std")] log::info!("Received new Testcase to convert from {_client_id}");
println!("Received new Testcase to convert from {_client_id}");
let Some(converter) = self.converter_back.as_mut() else { let Some(converter) = self.converter_back.as_mut() else {
return Ok(()); return Ok(());
@ -1225,9 +1220,8 @@ where
converter.convert(input)?, converter.convert(input)?,
false, false,
)?; )?;
#[cfg(feature = "std")]
if let Some(item) = _res.1 { if let Some(item) = _res.1 {
println!("Added received Testcase as item #{item}"); log::info!("Added received Testcase as item #{item}");
} }
Ok(()) Ok(())
} }

View File

@ -71,7 +71,7 @@ pub unsafe fn shutdown_handler<SP>(
) where ) where
SP: ShMemProvider, SP: ShMemProvider,
{ {
println!( log::info!(
"Fuzzer shutdown by Signal: {} Pid: {}", "Fuzzer shutdown by Signal: {} Pid: {}",
signal, signal,
std::process::id() std::process::id()
@ -83,10 +83,10 @@ pub unsafe fn shutdown_handler<SP>(
} else { } else {
// The process allocated the staterestorer map must take care of it // The process allocated the staterestorer map must take care of it
let sr = (ptr as *mut StateRestorer<SP>).as_mut().unwrap(); let sr = (ptr as *mut StateRestorer<SP>).as_mut().unwrap();
// println!("{:#?}", sr); // log::trace!("{:#?}", sr);
std::ptr::drop_in_place(sr); std::ptr::drop_in_place(sr);
} }
println!("Bye!"); log::info!("Bye!");
std::process::exit(0); std::process::exit(0);
} }
@ -132,6 +132,17 @@ pub enum LogSeverity {
Error, Error,
} }
impl From<LogSeverity> for log::Level {
fn from(value: LogSeverity) -> Self {
match value {
LogSeverity::Debug => log::Level::Debug,
LogSeverity::Info => log::Level::Info,
LogSeverity::Warn => log::Level::Trace,
LogSeverity::Error => log::Level::Error,
}
}
}
impl fmt::Display for LogSeverity { impl fmt::Display for LogSeverity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {

View File

@ -273,8 +273,7 @@ where
phantom: _, phantom: _,
} => { } => {
let (_, _) = (message, severity_level); let (_, _) = (message, severity_level);
#[cfg(feature = "std")] log::log!((*severity_level).into(), "{message}");
println!("[LOG {severity_level}]: {message}");
Ok(BrokerEventResult::Handled) Ok(BrokerEventResult::Handled)
} }
Event::CustomBuf { .. } => Ok(BrokerEventResult::Forward), Event::CustomBuf { .. } => Ok(BrokerEventResult::Forward),
@ -470,14 +469,13 @@ where
#[cfg(unix)] #[cfg(unix)]
if let Err(_e) = unsafe { setup_signal_handler(&mut SHUTDOWN_SIGHANDLER_DATA) } { if let Err(_e) = unsafe { setup_signal_handler(&mut SHUTDOWN_SIGHANDLER_DATA) } {
// We can live without a proper ctrl+c signal handler. Print and ignore. // We can live without a proper ctrl+c signal handler. Print and ignore.
#[cfg(feature = "std")] log::error!("Failed to setup signal handlers: {_e}");
println!("Failed to setup signal handlers: {_e}");
} }
let mut ctr: u64 = 0; let mut ctr: u64 = 0;
// Client->parent loop // Client->parent loop
loop { loop {
println!("Spawning next client (id {ctr})"); log::info!("Spawning next client (id {ctr})");
// On Unix, we fork // On Unix, we fork
#[cfg(all(unix, feature = "fork"))] #[cfg(all(unix, feature = "fork"))]
@ -528,7 +526,7 @@ where
// If we're restarting, deserialize the old state. // If we're restarting, deserialize the old state.
let (state, mgr) = match staterestorer.restore::<S>()? { let (state, mgr) = match staterestorer.restore::<S>()? {
None => { None => {
println!("First run. Let's set it all up"); log::info!("First run. Let's set it all up");
// Mgr to send and receive msgs from/to all other fuzzer instances // Mgr to send and receive msgs from/to all other fuzzer instances
( (
None, None,
@ -537,7 +535,7 @@ where
} }
// Restoring from a previous run, deserialize state and corpus. // Restoring from a previous run, deserialize state and corpus.
Some(state) => { Some(state) => {
println!("Subsequent run. Loaded previous state."); log::info!("Subsequent run. Loaded previous state.");
// We reset the staterestorer, the next staterestorer and receiver (after crash) will reuse the page from the initial message. // We reset the staterestorer, the next staterestorer and receiver (after crash) will reuse the page from the initial message.
staterestorer.reset(); staterestorer.reset();

View File

@ -658,7 +658,7 @@ mod tests {
#[cfg(unix)] #[cfg(unix)]
fn test_builder() { fn test_builder() {
let mut mgr = SimpleEventManager::new(SimpleMonitor::new(|status| { let mut mgr = SimpleEventManager::new(SimpleMonitor::new(|status| {
println!("{status}"); log::info!("{status}");
})); }));
let mut executor = CommandExecutor::builder(); let mut executor = CommandExecutor::builder();
@ -684,7 +684,7 @@ mod tests {
use alloc::string::ToString; use alloc::string::ToString;
let mut mgr = SimpleEventManager::new(SimpleMonitor::new(|status| { let mut mgr = SimpleEventManager::new(SimpleMonitor::new(|status| {
println!("{status}"); log::info!("{status}");
})); }));
let mut executor = let mut executor =

View File

@ -617,7 +617,7 @@ impl<'a, SP> ForkserverExecutorBuilder<'a, SP> {
let (forkserver, input_file, map) = self.build_helper()?; let (forkserver, input_file, map) = self.build_helper()?;
let target = self.program.take().unwrap(); let target = self.program.take().unwrap();
println!( log::info!(
"ForkserverExecutor: program: {:?}, arguments: {:?}, use_stdin: {:?}", "ForkserverExecutor: program: {:?}, arguments: {:?}, use_stdin: {:?}",
target, target,
self.arguments.clone(), self.arguments.clone(),
@ -655,7 +655,7 @@ impl<'a, SP> ForkserverExecutorBuilder<'a, SP> {
let (forkserver, input_file, map) = self.build_helper()?; let (forkserver, input_file, map) = self.build_helper()?;
let target = self.program.take().unwrap(); let target = self.program.take().unwrap();
println!( log::info!(
"ForkserverExecutor: program: {:?}, arguments: {:?}, use_stdin: {:?}, map_size: {:?}", "ForkserverExecutor: program: {:?}, arguments: {:?}, use_stdin: {:?}, map_size: {:?}",
target, target,
self.arguments.clone(), self.arguments.clone(),
@ -732,7 +732,7 @@ impl<'a, SP> ForkserverExecutorBuilder<'a, SP> {
if rlen != 4 { if rlen != 4 {
return Err(Error::unknown("Failed to start a forkserver".to_string())); return Err(Error::unknown("Failed to start a forkserver".to_string()));
} }
println!("All right - fork server is up."); log::info!("All right - fork server is up.");
// If forkserver is responding, we then check if there's any option enabled. // If forkserver is responding, we then check if there's any option enabled.
// We'll send 4-bytes message back to the forkserver to tell which features to use // We'll send 4-bytes message back to the forkserver to tell which features to use
// The forkserver is listening to our response if either shmem fuzzing is enabled or auto dict is enabled // The forkserver is listening to our response if either shmem fuzzing is enabled or auto dict is enabled
@ -745,7 +745,7 @@ impl<'a, SP> ForkserverExecutorBuilder<'a, SP> {
let mut send_status = FS_OPT_ENABLED; let mut send_status = FS_OPT_ENABLED;
if (status & FS_OPT_SHDMEM_FUZZ == FS_OPT_SHDMEM_FUZZ) && map.is_some() { if (status & FS_OPT_SHDMEM_FUZZ == FS_OPT_SHDMEM_FUZZ) && map.is_some() {
println!("Using SHARED MEMORY FUZZING feature."); log::info!("Using SHARED MEMORY FUZZING feature.");
send_status |= FS_OPT_SHDMEM_FUZZ; send_status |= FS_OPT_SHDMEM_FUZZ;
self.uses_shmem_testcase = true; self.uses_shmem_testcase = true;
} }
@ -768,7 +768,7 @@ impl<'a, SP> ForkserverExecutorBuilder<'a, SP> {
// TODO set AFL_MAP_SIZE // TODO set AFL_MAP_SIZE
assert!(self.map_size.is_none() || map_size as usize <= self.map_size.unwrap()); assert!(self.map_size.is_none() || map_size as usize <= self.map_size.unwrap());
println!("Target MAP SIZE = {:#x}", self.real_map_size); log::info!("Target MAP SIZE = {:#x}", self.real_map_size);
self.map_size = Some(map_size as usize); self.map_size = Some(map_size as usize);
} }
@ -791,7 +791,7 @@ impl<'a, SP> ForkserverExecutorBuilder<'a, SP> {
)); ));
} }
println!("Autodict size {dict_size:x}"); log::info!("Autodict size {dict_size:x}");
let (rlen, buf) = forkserver.read_st_size(dict_size as usize)?; let (rlen, buf) = forkserver.read_st_size(dict_size as usize)?;
@ -804,7 +804,7 @@ impl<'a, SP> ForkserverExecutorBuilder<'a, SP> {
} }
} }
} else { } else {
println!("Forkserver Options are not available."); log::warn!("Forkserver Options are not available.");
} }
Ok((forkserver, input_file, map)) Ok((forkserver, input_file, map))

View File

@ -578,11 +578,9 @@ pub fn run_observers_and_save_state<E, EM, OF, Z>(
event_mgr.on_restart(state).unwrap(); event_mgr.on_restart(state).unwrap();
#[cfg(feature = "std")] log::info!("Waiting for broker...");
println!("Waiting for broker...");
event_mgr.await_restart_safe(); event_mgr.await_restart_safe();
#[cfg(feature = "std")] log::info!("Bye!");
println!("Bye!");
} }
#[cfg(unix)] #[cfg(unix)]
@ -592,10 +590,7 @@ mod unix_signal_handler {
use alloc::{boxed::Box, string::String}; use alloc::{boxed::Box, string::String};
use core::mem::transmute; use core::mem::transmute;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::{ use std::{io::Write, panic};
io::{stdout, Write},
panic,
};
use libc::siginfo_t; use libc::siginfo_t;
@ -715,8 +710,7 @@ mod unix_signal_handler {
Z: HasObjective<Objective = OF, State = E::State>, Z: HasObjective<Objective = OF, State = E::State>,
{ {
if !data.is_valid() { if !data.is_valid() {
#[cfg(feature = "std")] log::warn!("TIMEOUT or SIGUSR2 happened, but currently not fuzzing.");
println!("TIMEOUT or SIGUSR2 happened, but currently not fuzzing.");
return; return;
} }
@ -726,10 +720,7 @@ mod unix_signal_handler {
let fuzzer = data.fuzzer_mut::<Z>(); let fuzzer = data.fuzzer_mut::<Z>();
let input = data.take_current_input::<<E::State as UsesInput>::Input>(); let input = data.take_current_input::<<E::State as UsesInput>::Input>();
#[cfg(feature = "std")] log::error!("Timeout in fuzz run.");
println!("Timeout in fuzz run.");
#[cfg(feature = "std")]
let _res = stdout().flush();
run_observers_and_save_state::<E, EM, OF, Z>( run_observers_and_save_state::<E, EM, OF, Z>(
executor, executor,
@ -765,8 +756,7 @@ mod unix_signal_handler {
let _context = &mut *(((_context as *mut _ as *mut libc::c_void as usize) + 128) let _context = &mut *(((_context as *mut _ as *mut libc::c_void as usize) + 128)
as *mut libc::c_void as *mut ucontext_t); as *mut libc::c_void as *mut ucontext_t);
#[cfg(feature = "std")] log::error!("Crashed with {signal}");
eprintln!("Crashed with {signal}");
if data.is_valid() { if data.is_valid() {
let executor = data.executor_mut::<E>(); let executor = data.executor_mut::<E>();
// disarms timeout in case of TimeoutExecutor // disarms timeout in case of TimeoutExecutor
@ -776,17 +766,20 @@ mod unix_signal_handler {
let fuzzer = data.fuzzer_mut::<Z>(); let fuzzer = data.fuzzer_mut::<Z>();
let input = data.take_current_input::<<E::State as UsesInput>::Input>(); let input = data.take_current_input::<<E::State as UsesInput>::Input>();
#[cfg(feature = "std")] log::error!("Child crashed!");
eprintln!("Child crashed!");
#[cfg(all(feature = "std", unix))] #[cfg(all(feature = "std", unix))]
{ {
let mut writer = std::io::BufWriter::new(std::io::stderr()); let mut bsod = Vec::new();
{
let mut writer = std::io::BufWriter::new(&mut bsod);
writeln!(writer, "input: {:?}", input.generate_name(0)).unwrap(); writeln!(writer, "input: {:?}", input.generate_name(0)).unwrap();
crate::bolts::minibsod::generate_minibsod(&mut writer, signal, _info, _context) crate::bolts::minibsod::generate_minibsod(&mut writer, signal, _info, _context)
.unwrap(); .unwrap();
writer.flush().unwrap(); writer.flush().unwrap();
} }
log::error!("{}", std::str::from_utf8(&bsod).unwrap());
}
run_observers_and_save_state::<E, EM, OF, Z>( run_observers_and_save_state::<E, EM, OF, Z>(
executor, executor,
@ -797,30 +790,38 @@ mod unix_signal_handler {
ExitKind::Crash, ExitKind::Crash,
); );
} else { } else {
#[cfg(feature = "std")]
{ {
eprintln!("Double crash\n"); log::error!("Double crash\n");
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
let si_addr = (_info._pad[0] as i64) | ((_info._pad[1] as i64) << 32); let si_addr = (_info._pad[0] as i64) | ((_info._pad[1] as i64) << 32);
#[cfg(not(target_os = "android"))] #[cfg(not(target_os = "android"))]
let si_addr = { _info.si_addr() as usize }; let si_addr = { _info.si_addr() as usize };
eprintln!( log::error!(
"We crashed at addr 0x{si_addr:x}, but are not in the target... Bug in the fuzzer? Exiting." "We crashed at addr 0x{si_addr:x}, but are not in the target... Bug in the fuzzer? Exiting."
); );
#[cfg(all(feature = "std", unix))] #[cfg(all(feature = "std", unix))]
{ {
let mut writer = std::io::BufWriter::new(std::io::stderr()); let mut bsod = Vec::new();
crate::bolts::minibsod::generate_minibsod(&mut writer, signal, _info, _context) {
let mut writer = std::io::BufWriter::new(&mut bsod);
crate::bolts::minibsod::generate_minibsod(
&mut writer,
signal,
_info,
_context,
)
.unwrap(); .unwrap();
writer.flush().unwrap(); writer.flush().unwrap();
} }
log::error!("{}", std::str::from_utf8(&bsod).unwrap());
}
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
{ {
eprintln!("Type QUIT to restart the child"); log::error!("Type QUIT to restart the child");
let mut line = String::new(); let mut line = String::new();
while line.trim() != "QUIT" { while line.trim() != "QUIT" {
std::io::stdin().read_line(&mut line).unwrap(); std::io::stdin().read_line(&mut line).unwrap();
@ -842,8 +843,6 @@ pub mod windows_asan_handler {
ptr, ptr,
sync::atomic::{compiler_fence, Ordering}, sync::atomic::{compiler_fence, Ordering},
}; };
#[cfg(feature = "std")]
use std::io::{stdout, Write};
use windows::Win32::System::Threading::{ use windows::Win32::System::Threading::{
EnterCriticalSection, LeaveCriticalSection, RTL_CRITICAL_SECTION, EnterCriticalSection, LeaveCriticalSection, RTL_CRITICAL_SECTION,
@ -888,19 +887,17 @@ pub mod windows_asan_handler {
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
} }
#[cfg(feature = "std")] log::error!("ASAN detected crash!");
eprintln!("ASAN detected crash!");
if data.current_input_ptr.is_null() { if data.current_input_ptr.is_null() {
#[cfg(feature = "std")]
{ {
eprintln!("Double crash\n"); log::error!("Double crash\n");
eprintln!( log::error!(
"ASAN detected crash but we're not in the target... Bug in the fuzzer? Exiting.", "ASAN detected crash but we're not in the target... Bug in the fuzzer? Exiting.",
); );
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
{ {
eprintln!("Type QUIT to restart the child"); log::error!("Type QUIT to restart the child");
let mut line = String::new(); let mut line = String::new();
while line.trim() != "QUIT" { while line.trim() != "QUIT" {
std::io::stdin().read_line(&mut line).unwrap(); std::io::stdin().read_line(&mut line).unwrap();
@ -920,10 +917,7 @@ pub mod windows_asan_handler {
let fuzzer = data.fuzzer_mut::<Z>(); let fuzzer = data.fuzzer_mut::<Z>();
let event_mgr = data.event_mgr_mut::<EM>(); let event_mgr = data.event_mgr_mut::<EM>();
#[cfg(feature = "std")] log::error!("Child crashed!");
eprintln!("Child crashed!");
#[cfg(feature = "std")]
drop(stdout().flush());
// Make sure we don't crash in the crash handler forever. // Make sure we don't crash in the crash handler forever.
let input = data.take_current_input::<<E::State as UsesInput>::Input>(); let input = data.take_current_input::<<E::State as UsesInput>::Input>();
@ -954,10 +948,7 @@ mod windows_exception_handler {
sync::atomic::{compiler_fence, Ordering}, sync::atomic::{compiler_fence, Ordering},
}; };
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::{ use std::panic;
io::{stdout, Write},
panic,
};
use windows::Win32::System::Threading::{ use windows::Win32::System::Threading::{
EnterCriticalSection, ExitProcess, LeaveCriticalSection, RTL_CRITICAL_SECTION, EnterCriticalSection, ExitProcess, LeaveCriticalSection, RTL_CRITICAL_SECTION,
@ -1093,13 +1084,9 @@ mod windows_exception_handler {
let event_mgr = data.event_mgr_mut::<EM>(); let event_mgr = data.event_mgr_mut::<EM>();
if data.timeout_input_ptr.is_null() { if data.timeout_input_ptr.is_null() {
#[cfg(feature = "std")] log::error!("TIMEOUT or SIGUSR2 happened, but currently not fuzzing. Exiting");
dbg!("TIMEOUT or SIGUSR2 happened, but currently not fuzzing. Exiting");
} else { } else {
#[cfg(feature = "std")] log::error!("Timeout in fuzz run.");
eprintln!("Timeout in fuzz run.");
#[cfg(feature = "std")]
let _res = stdout().flush();
let input = (data.timeout_input_ptr as *const <E::State as UsesInput>::Input) let input = (data.timeout_input_ptr as *const <E::State as UsesInput>::Input)
.as_ref() .as_ref()
@ -1127,7 +1114,7 @@ mod windows_exception_handler {
.unwrap(), .unwrap(),
); );
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
// println!("TIMER INVOKED!"); // log::info!("TIMER INVOKED!");
} }
#[allow(clippy::too_many_lines)] #[allow(clippy::too_many_lines)]
@ -1173,19 +1160,18 @@ mod windows_exception_handler {
let exception_list = data.exceptions(); let exception_list = data.exceptions();
if exception_list.contains(&code) { if exception_list.contains(&code) {
eprintln!("Crashed with {code}"); log::error!("Crashed with {code}");
} else { } else {
// eprintln!("Exception code received, but {code} is not in CRASH_EXCEPTIONS"); // log::trace!("Exception code received, but {code} is not in CRASH_EXCEPTIONS");
is_crash = false; is_crash = false;
} }
} else { } else {
eprintln!("Crashed without exception (probably due to SIGABRT)"); log::error!("Crashed without exception (probably due to SIGABRT)");
}; };
if data.current_input_ptr.is_null() { if data.current_input_ptr.is_null() {
#[cfg(feature = "std")]
{ {
eprintln!("Double crash\n"); log::error!("Double crash\n");
let crash_addr = exception_pointers let crash_addr = exception_pointers
.as_mut() .as_mut()
.unwrap() .unwrap()
@ -1194,13 +1180,13 @@ mod windows_exception_handler {
.unwrap() .unwrap()
.ExceptionAddress as usize; .ExceptionAddress as usize;
eprintln!( log::error!(
"We crashed at addr 0x{crash_addr:x}, but are not in the target... Bug in the fuzzer? Exiting." "We crashed at addr 0x{crash_addr:x}, but are not in the target... Bug in the fuzzer? Exiting."
); );
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
{ {
eprintln!("Type QUIT to restart the child"); log::error!("Type QUIT to restart the child");
let mut line = String::new(); let mut line = String::new();
while line.trim() != "QUIT" { while line.trim() != "QUIT" {
std::io::stdin().read_line(&mut line).unwrap(); std::io::stdin().read_line(&mut line).unwrap();
@ -1220,16 +1206,12 @@ mod windows_exception_handler {
let fuzzer = data.fuzzer_mut::<Z>(); let fuzzer = data.fuzzer_mut::<Z>();
let event_mgr = data.event_mgr_mut::<EM>(); let event_mgr = data.event_mgr_mut::<EM>();
#[cfg(feature = "std")]
if is_crash { if is_crash {
eprintln!("Child crashed!"); log::error!("Child crashed!");
} else { } else {
// eprintln!("Exception received!"); // log::info!("Exception received!");
} }
#[cfg(feature = "std")]
drop(stdout().flush());
// Make sure we don't crash in the crash handler forever. // Make sure we don't crash in the crash handler forever.
if is_crash { if is_crash {
let input = data.take_current_input::<<E::State as UsesInput>::Input>(); let input = data.take_current_input::<<E::State as UsesInput>::Input>();
@ -1248,10 +1230,10 @@ mod windows_exception_handler {
} }
if is_crash { if is_crash {
println!("Exiting!"); log::info!("Exiting!");
ExitProcess(1); ExitProcess(1);
} }
// println!("Not Exiting!"); // log::info!("Not Exiting!");
} }
} }
@ -1560,7 +1542,7 @@ where
} }
Ok(ForkResult::Parent { child }) => { Ok(ForkResult::Parent { child }) => {
// Parent // Parent
// println!("from parent {} child is {}", std::process::id(), child); // log::info!("from parent {} child is {}", std::process::id(), child);
self.shmem_provider.post_fork(false)?; self.shmem_provider.post_fork(false)?;
let res = waitpid(child, None)?; let res = waitpid(child, None)?;
@ -1621,10 +1603,10 @@ where
// we can't do this from the parent, timerid is unique to each process. // we can't do this from the parent, timerid is unique to each process.
libc::timer_create(libc::CLOCK_MONOTONIC, null_mut(), addr_of_mut!(timerid)); libc::timer_create(libc::CLOCK_MONOTONIC, null_mut(), addr_of_mut!(timerid));
println!("Set timer! {:#?} {timerid:#?}", self.itimerspec); log::info!("Set timer! {:#?} {timerid:#?}", self.itimerspec);
let v = let v =
libc::timer_settime(timerid, 0, addr_of_mut!(self.itimerspec), null_mut()); libc::timer_settime(timerid, 0, addr_of_mut!(self.itimerspec), null_mut());
println!("{v:#?} {}", nix::errno::errno()); log::trace!("{v:#?} {}", nix::errno::errno());
(self.harness_fn)(input); (self.harness_fn)(input);
self.observers self.observers
@ -1637,11 +1619,11 @@ where
} }
Ok(ForkResult::Parent { child }) => { Ok(ForkResult::Parent { child }) => {
// Parent // Parent
// println!("from parent {} child is {}", std::process::id(), child); // log::trace!("from parent {} child is {}", std::process::id(), child);
self.shmem_provider.post_fork(false)?; self.shmem_provider.post_fork(false)?;
let res = waitpid(child, None)?; let res = waitpid(child, None)?;
println!("{res:#?}"); log::trace!("{res:#?}");
match res { match res {
WaitStatus::Signaled(_, signal, _) => match signal { WaitStatus::Signaled(_, signal, _) => match signal {
nix::sys::signal::Signal::SIGALRM nix::sys::signal::Signal::SIGALRM

View File

@ -69,7 +69,7 @@ impl HashSetState<u64> for NewHashFeedbackMetadata {
fn update_hash_set(&mut self, value: u64) -> Result<bool, Error> { fn update_hash_set(&mut self, value: u64) -> Result<bool, Error> {
let r = self.hash_set.insert(value); let r = self.hash_set.insert(value);
// println!("Got r={}, the hashset is {:?}", r, &self.hash_set); // log::trace!("Got r={}, the hashset is {:?}", r, &self.hash_set);
Ok(r) Ok(r)
} }
} }

View File

@ -693,8 +693,7 @@ impl ClientPerfMonitor {
match self.timer_start { match self.timer_start {
None => { None => {
// Warning message if marking time without starting the timer first // Warning message if marking time without starting the timer first
#[cfg(feature = "std")] log::warn!("Attempted to `mark_time` without starting timer first.");
eprint!("Attempted to `mark_time` without starting timer first.");
// Return 0 for no time marked // Return 0 for no time marked
0 0

View File

@ -15,7 +15,7 @@
// as well as: // as well as:
// ```rust,ignore // ```rust,ignore
// let listener = "127.0.0.1:8080".to_string(); // point prometheus to scrape here in your prometheus.yml // let listener = "127.0.0.1:8080".to_string(); // point prometheus to scrape here in your prometheus.yml
// let mon = PrometheusMonitor::new(listener, |s| println!("{s}")); // let mon = PrometheusMonitor::new(listener, |s| log::info!("{s}"));
// and then like with any other monitor, pass it into the event manager like so: // and then like with any other monitor, pass it into the event manager like so:
// let mut mgr = SimpleEventManager::new(mon); // let mut mgr = SimpleEventManager::new(mon);
// ``` // ```
@ -167,7 +167,7 @@ where
for (key, val) in cur_client_clone.user_monitor { for (key, val) in cur_client_clone.user_monitor {
// Update metrics added to the user_stats hashmap by feedback event-fires // Update metrics added to the user_stats hashmap by feedback event-fires
// You can filter for each custom stat in promQL via labels of both the stat name and client id // You can filter for each custom stat in promQL via labels of both the stat name and client id
println!("{key}: {val}"); log::info!("{key}: {val}");
#[allow(clippy::cast_precision_loss)] #[allow(clippy::cast_precision_loss)]
let value: f64 = match val { let value: f64 = match val {
UserStats::Number(n) => n as f64, UserStats::Number(n) => n as f64,
@ -218,7 +218,7 @@ where
clients_count_clone, clients_count_clone,
custom_stat_clone, custom_stat_clone,
)) ))
.map_err(|err| println!("{err:?}")) .map_err(|err| log::error!("{err:?}"))
.ok(); .ok();
}); });
Self { Self {
@ -262,7 +262,7 @@ where
clients_count_clone, clients_count_clone,
custom_stat_clone, custom_stat_clone,
)) ))
.map_err(|err| println!("{err:?}")) .map_err(|err| log::error!("{err:?}"))
.ok(); .ok();
}); });
Self { Self {

View File

@ -265,7 +265,7 @@ impl TuiUI {
} }
} }
//println!("max_x: {}, len: {}", max_x, self.graph_data.len()); //log::trace!("max_x: {}, len: {}", max_x, self.graph_data.len());
let datasets = vec![Dataset::default() let datasets = vec![Dataset::default()
//.name("data") //.name("data")

View File

@ -462,8 +462,7 @@ mod tests {
let mut splice = SpliceMutator::new(); let mut splice = SpliceMutator::new();
splice.mutate(&mut state, &mut input, 0).unwrap(); splice.mutate(&mut state, &mut input, 0).unwrap();
#[cfg(feature = "std")] log::trace!("{:?}", input.bytes());
println!("{:?}", input.bytes());
// The pre-seeded rand should have spliced at position 2. // The pre-seeded rand should have spliced at position 2.
// TODO: Maybe have a fixed rand for this purpose? // TODO: Maybe have a fixed rand for this purpose?

View File

@ -88,8 +88,7 @@ impl Tokens {
head += 1; head += 1;
if size > 0 { if size > 0 {
self.add_token(&slice[head..head + size].to_vec()); self.add_token(&slice[head..head + size].to_vec());
#[cfg(feature = "std")] log::info!(
println!(
"Token size: {} content: {:x?}", "Token size: {} content: {:x?}",
size, size,
&slice[head..head + size].to_vec() &slice[head..head + size].to_vec()
@ -120,7 +119,7 @@ impl Tokens {
))); )));
} }
let section_size: usize = token_stop.offset_from(token_start).try_into().unwrap(); let section_size: usize = token_stop.offset_from(token_start).try_into().unwrap();
// println!("size: {}", section_size); // log::info!("size: {}", section_size);
let slice = from_raw_parts(token_start, section_size); let slice = from_raw_parts(token_start, section_size);
// Now we know the beginning and the end of the token section.. let's parse them into tokens // Now we know the beginning and the end of the token section.. let's parse them into tokens
@ -157,7 +156,7 @@ impl Tokens {
where where
P: AsRef<Path>, P: AsRef<Path>,
{ {
// println!("Loading tokens file {:?} ...", file); // log::info!("Loading tokens file {:?} ...", file);
let file = File::open(file)?; // panic if not found let file = File::open(file)?; // panic if not found
let reader = BufReader::new(file); let reader = BufReader::new(file);
@ -620,8 +619,7 @@ token2="B"
"###; "###;
fs::write("test.tkns", data).expect("Unable to write test.tkns"); fs::write("test.tkns", data).expect("Unable to write test.tkns");
let tokens = Tokens::from_file("test.tkns").unwrap(); let tokens = Tokens::from_file("test.tkns").unwrap();
#[cfg(feature = "std")] log::info!("Token file entries: {:?}", tokens.tokens());
println!("Token file entries: {:?}", tokens.tokens());
assert_eq!(tokens.tokens().len(), 2); assert_eq!(tokens.tokens().len(), 2);
let _res = fs::remove_file("test.tkns"); let _res = fs::remove_file("test.tkns");
} }

View File

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

View File

@ -36,8 +36,8 @@ pub fn collect_backtrace() -> u64 {
} }
// will use symbols later // will use symbols later
// let trace = format!("{:?}", b); // let trace = format!("{:?}", b);
// eprintln!("{}", trace); // log::trace!("{}", trace);
// println!( // log::info!(
// "backtrace collected with hash={} at pid={}", // "backtrace collected with hash={} at pid={}",
// hash, // hash,
// std::process::id() // std::process::id()

View File

@ -273,7 +273,7 @@ where
testcase.set_exec_time(total_time / (iter as u32)); testcase.set_exec_time(total_time / (iter as u32));
testcase.set_fuzz_level(fuzz_level + 1); testcase.set_fuzz_level(fuzz_level + 1);
// println!("time: {:#?}", testcase.exec_time()); // log::trace!("time: {:#?}", testcase.exec_time());
let data = testcase let data = testcase
.metadata_mut() .metadata_mut()

View File

@ -468,14 +468,14 @@ where
} }
while let Some(path) = self.remaining_initial_files.as_mut().unwrap().pop() { while let Some(path) = self.remaining_initial_files.as_mut().unwrap().pop() {
println!("Loading file {:?} ...", &path); log::info!("Loading file {:?} ...", &path);
let input = loader(fuzzer, self, &path)?; let input = loader(fuzzer, self, &path)?;
if forced { if forced {
let _ = fuzzer.add_input(self, executor, manager, input)?; let _ = fuzzer.add_input(self, executor, manager, input)?;
} else { } else {
let (res, _) = fuzzer.evaluate_input(self, executor, manager, input)?; let (res, _) = fuzzer.evaluate_input(self, executor, manager, input)?;
if res == ExecuteInputResult::None { if res == ExecuteInputResult::None {
println!("File {:?} was not interesting, skipped.", &path); log::warn!("File {:?} was not interesting, skipped.", &path);
} }
} }
} }

View File

@ -22,3 +22,4 @@ glob = "0.3"
[dependencies] [dependencies]
serde = { version = "1.0", default-features = false, features = ["alloc", "derive"] } # serialization lib serde = { version = "1.0", default-features = false, features = ["alloc", "derive"] } # serialization lib
log = "0.4.17"

View File

@ -168,7 +168,7 @@ pub trait CompilerWrapper {
let args = self.command()?; let args = self.command()?;
if !self.is_silent() { if !self.is_silent() {
dbg!(&args); log::info!("{args:?}");
} }
if args.is_empty() { if args.is_empty() {
return Err(Error::InvalidArguments( return Err(Error::InvalidArguments(
@ -180,7 +180,7 @@ pub trait CompilerWrapper {
Err(e) => return Err(Error::Io(e)), Err(e) => return Err(Error::Io(e)),
}; };
if !self.is_silent() { if !self.is_silent() {
dbg!(status); log::info!("{status:?}");
} }
Ok(status.code()) Ok(status.code())
} }

View File

@ -21,3 +21,4 @@ clone = ["which"] # common functionality to check out the symcc repo using git
[dependencies] [dependencies]
which = { version = "4.2", optional = true } which = { version = "4.2", optional = true }
cmake = { version = "0.1", optional = true } cmake = { version = "0.1", optional = true }
log = "0.4.17"

View File

@ -34,7 +34,7 @@ mod clone {
cmd.arg("checkout").arg(commit).current_dir(path); cmd.arg("checkout").arg(commit).current_dir(path);
let output = cmd.output().expect("failed to execute git checkout"); let output = cmd.output().expect("failed to execute git checkout");
if !output.status.success() { if !output.status.success() {
println!("failed to checkout symcc git repository commit:"); log::error!("failed to checkout symcc git repository commit:");
let mut stdout = stdout(); let mut stdout = stdout();
stdout stdout
.write_all(&output.stderr) .write_all(&output.stderr)
@ -42,7 +42,7 @@ mod clone {
panic!(); panic!();
} }
} else { } else {
println!("failed to clone symcc git repository:"); log::error!("failed to clone symcc git repository:");
let mut stdout = stdout(); let mut stdout = stdout();
stdout stdout
.write_all(&output.stderr) .write_all(&output.stderr)

View File

@ -37,6 +37,7 @@ backtrace = { version = "0.3", default-features = false, features = ["std", "ser
num-traits = "0.2" num-traits = "0.2"
ahash = "0.8" ahash = "0.8"
paste = "1.0" paste = "1.0"
log = "0.4.17"
[dev-dependencies] [dev-dependencies]
serial_test = "1" serial_test = "1"

View File

@ -132,7 +132,7 @@ impl Allocator {
let start = details.memory_range().base_address().0 as usize; let start = details.memory_range().base_address().0 as usize;
let end = start + details.memory_range().size(); let end = start + details.memory_range().size();
occupied_ranges.push((start, end)); occupied_ranges.push((start, end));
// println!("{:x} {:x}", start, end); // log::trace!("{:x} {:x}", start, end);
let base: usize = 2; let base: usize = 2;
// On x64, if end > 2**48, then that's in vsyscall or something. // On x64, if end > 2**48, then that's in vsyscall or something.
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
@ -168,8 +168,8 @@ impl Allocator {
// check if the proposed shadow bit overlaps with occupied ranges. // check if the proposed shadow bit overlaps with occupied ranges.
for (start, end) in &occupied_ranges { for (start, end) in &occupied_ranges {
if (shadow_start <= *end) && (*start <= shadow_end) { if (shadow_start <= *end) && (*start <= shadow_end) {
// println!("{:x} {:x}, {:x} {:x}",shadow_start,shadow_end,start,end); // log::trace!("{:x} {:x}, {:x} {:x}",shadow_start,shadow_end,start,end);
println!("shadow_bit {try_shadow_bit:x} is not suitable"); log::warn!("shadow_bit {try_shadow_bit:x} is not suitable");
break; break;
} }
} }
@ -195,7 +195,7 @@ impl Allocator {
} }
} }
println!("shadow_bit {shadow_bit:x} is suitable"); log::warn!("shadow_bit {shadow_bit:x} is suitable");
assert!(shadow_bit != 0); assert!(shadow_bit != 0);
// attempt to pre-map the entire shadow-memory space // attempt to pre-map the entire shadow-memory space
@ -266,7 +266,7 @@ impl Allocator {
pub unsafe fn alloc(&mut self, size: usize, _alignment: usize) -> *mut c_void { pub unsafe fn alloc(&mut self, size: usize, _alignment: usize) -> *mut c_void {
let mut is_malloc_zero = false; let mut is_malloc_zero = false;
let size = if size == 0 { let size = if size == 0 {
// println!("zero-sized allocation!"); // log::warn!("zero-sized allocation!");
is_malloc_zero = true; is_malloc_zero = true;
16 16
} else { } else {
@ -288,7 +288,7 @@ impl Allocator {
self.total_allocation_size += rounded_up_size; self.total_allocation_size += rounded_up_size;
let metadata = if let Some(mut metadata) = self.find_smallest_fit(rounded_up_size) { let metadata = if let Some(mut metadata) = self.find_smallest_fit(rounded_up_size) {
//println!("reusing allocation at {:x}, (actual mapping starts at {:x}) size {:x}", metadata.address, metadata.address - self.page_size, size); //log::trace!("reusing allocation at {:x}, (actual mapping starts at {:x}) size {:x}", metadata.address, metadata.address - self.page_size, size);
metadata.is_malloc_zero = is_malloc_zero; metadata.is_malloc_zero = is_malloc_zero;
metadata.size = size; metadata.size = size;
if self.options.allocation_backtraces { if self.options.allocation_backtraces {
@ -296,7 +296,7 @@ impl Allocator {
} }
metadata metadata
} else { } else {
// println!("{:x}, {:x}", self.current_mapping_addr, rounded_up_size); // log::trace!("{:x}, {:x}", self.current_mapping_addr, rounded_up_size);
let mapping = match mmap( let mapping = match mmap(
NonZeroUsize::new(self.current_mapping_addr), NonZeroUsize::new(self.current_mapping_addr),
NonZeroUsize::new_unchecked(rounded_up_size), NonZeroUsize::new_unchecked(rounded_up_size),
@ -310,7 +310,7 @@ impl Allocator {
) { ) {
Ok(mapping) => mapping as usize, Ok(mapping) => mapping as usize,
Err(err) => { Err(err) => {
println!("An error occurred while mapping memory: {err:?}"); log::error!("An error occurred while mapping memory: {err:?}");
return std::ptr::null_mut(); return std::ptr::null_mut();
} }
}; };
@ -341,14 +341,14 @@ impl Allocator {
self.allocations self.allocations
.insert(metadata.address + self.page_size, metadata); .insert(metadata.address + self.page_size, metadata);
//println!("serving address: {:?}, size: {:x}", address, size); //log::trace!("serving address: {:?}, size: {:x}", address, size);
address address
} }
/// Releases the allocation at the given address. /// Releases the allocation at the given address.
#[allow(clippy::missing_safety_doc)] #[allow(clippy::missing_safety_doc)]
pub unsafe fn release(&mut self, ptr: *mut c_void) { pub unsafe fn release(&mut self, ptr: *mut c_void) {
//println!("freeing address: {:?}", ptr); //log::trace!("freeing address: {:?}", ptr);
let Some(metadata) = self.allocations.get_mut(&(ptr as usize)) else { let Some(metadata) = self.allocations.get_mut(&(ptr as usize)) else {
if !ptr.is_null() { if !ptr.is_null() {
AsanErrors::get_mut() AsanErrors::get_mut()
@ -447,14 +447,14 @@ impl Allocator {
} }
fn unpoison(start: usize, size: usize) { fn unpoison(start: usize, size: usize) {
// println!("unpoisoning {:x} for {:x}", start, size / 8 + 1); // log::trace!("unpoisoning {:x} for {:x}", start, size / 8 + 1);
unsafe { unsafe {
// println!("memset: {:?}", start as *mut c_void); // log::trace!("memset: {:?}", start as *mut c_void);
memset(start as *mut c_void, 0xff, size / 8); memset(start as *mut c_void, 0xff, size / 8);
let remainder = size % 8; let remainder = size % 8;
if remainder > 0 { if remainder > 0 {
// println!("remainder: {:x}, offset: {:x}", remainder, start + size / 8); // log::trace!("remainder: {:x}, offset: {:x}", remainder, start + size / 8);
memset( memset(
(start + size / 8) as *mut c_void, (start + size / 8) as *mut c_void,
(0xff << (8 - remainder)) & 0xff, (0xff << (8 - remainder)) & 0xff,
@ -466,14 +466,14 @@ impl Allocator {
/// Poisonn an area in memory /// Poisonn an area in memory
pub fn poison(start: usize, size: usize) { pub fn poison(start: usize, size: usize) {
// println!("poisoning {:x} for {:x}", start, size / 8 + 1); // log::trace!("poisoning {:x} for {:x}", start, size / 8 + 1);
unsafe { unsafe {
// println!("memset: {:?}", start as *mut c_void); // log::trace!("memset: {:?}", start as *mut c_void);
memset(start as *mut c_void, 0x00, size / 8); memset(start as *mut c_void, 0x00, size / 8);
let remainder = size % 8; let remainder = size % 8;
if remainder > 0 { if remainder > 0 {
// println!("remainder: {:x}, offset: {:x}", remainder, start + size / 8); // log::trace!("remainder: {:x}, offset: {:x}", remainder, start + size / 8);
memset((start + size / 8) as *mut c_void, 0x00, 1); memset((start + size / 8) as *mut c_void, 0x00, 1);
} }
} }
@ -486,7 +486,7 @@ impl Allocator {
end: usize, end: usize,
unpoison: bool, unpoison: bool,
) -> (usize, usize) { ) -> (usize, usize) {
//println!("start: {:x}, end {:x}, size {:x}", start, end, end - start); //log::trace!("start: {:x}, end {:x}, size {:x}", start, end, end - start);
let shadow_mapping_start = map_to_shadow!(self, start); let shadow_mapping_start = map_to_shadow!(self, start);
@ -496,7 +496,7 @@ impl Allocator {
self.round_up_to_page((end - start) / 8) + self.page_size + shadow_start; self.round_up_to_page((end - start) / 8) + self.page_size + shadow_start;
for range in self.shadow_pages.gaps(&(shadow_start..shadow_end)) { for range in self.shadow_pages.gaps(&(shadow_start..shadow_end)) {
/* /*
println!( log::trace!(
"range: {:x}-{:x}, pagesize: {}", "range: {:x}-{:x}, pagesize: {}",
range.start, range.end, self.page_size range.start, range.end, self.page_size
); );
@ -517,7 +517,7 @@ impl Allocator {
self.shadow_pages.insert(shadow_start..shadow_end); self.shadow_pages.insert(shadow_start..shadow_end);
} }
//println!("shadow_mapping_start: {:x}, shadow_size: {:x}", shadow_mapping_start, (end - start) / 8); //log::trace!("shadow_mapping_start: {:x}, shadow_size: {:x}", shadow_mapping_start, (end - start) / 8);
if unpoison { if unpoison {
Self::unpoison(shadow_mapping_start, end - start); Self::unpoison(shadow_mapping_start, end - start);
} }

View File

@ -193,7 +193,7 @@ impl FridaRuntime for AsanRuntime {
ProtFlags::PROT_READ | ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC,
) )
.unwrap(); .unwrap();
println!("Test0"); log::info!("Test0");
/* /*
0x555555916ce9 <libafl_frida::asan_rt::AsanRuntime::init+13033> je libafl_frida::asan_rt::AsanRuntime::init+14852 <libafl_frida::asan_rt::AsanRuntime::init+14852> 0x555555916ce9 <libafl_frida::asan_rt::AsanRuntime::init+13033> je libafl_frida::asan_rt::AsanRuntime::init+14852 <libafl_frida::asan_rt::AsanRuntime::init+14852>
0x555555916cef <libafl_frida::asan_rt::AsanRuntime::init+13039> mov rdi, r15 <0x555558392338> 0x555555916cef <libafl_frida::asan_rt::AsanRuntime::init+13039> mov rdi, r15 <0x555558392338>
@ -202,52 +202,52 @@ impl FridaRuntime for AsanRuntime {
(mem as usize) as *const c_void, (mem as usize) as *const c_void,
0x00 0x00
)); ));
println!("Test1"); log::info!("Test1");
assert!((self.shadow_check_func.unwrap())( assert!((self.shadow_check_func.unwrap())(
(mem as usize) as *const c_void, (mem as usize) as *const c_void,
0xac 0xac
)); ));
println!("Test2"); log::info!("Test2");
assert!((self.shadow_check_func.unwrap())( assert!((self.shadow_check_func.unwrap())(
((mem as usize) + 2) as *const c_void, ((mem as usize) + 2) as *const c_void,
0xac 0xac
)); ));
println!("Test3"); log::info!("Test3");
assert!(!(self.shadow_check_func.unwrap())( assert!(!(self.shadow_check_func.unwrap())(
((mem as usize) + 3) as *const c_void, ((mem as usize) + 3) as *const c_void,
0xac 0xac
)); ));
println!("Test4"); log::info!("Test4");
assert!(!(self.shadow_check_func.unwrap())( assert!(!(self.shadow_check_func.unwrap())(
((mem as isize) + -1) as *const c_void, ((mem as isize) + -1) as *const c_void,
0xac 0xac
)); ));
println!("Test5"); log::info!("Test5");
assert!((self.shadow_check_func.unwrap())( assert!((self.shadow_check_func.unwrap())(
((mem as usize) + 2 + 0xa4) as *const c_void, ((mem as usize) + 2 + 0xa4) as *const c_void,
8 8
)); ));
println!("Test6"); log::info!("Test6");
assert!((self.shadow_check_func.unwrap())( assert!((self.shadow_check_func.unwrap())(
((mem as usize) + 2 + 0xa6) as *const c_void, ((mem as usize) + 2 + 0xa6) as *const c_void,
6 6
)); ));
println!("Test7"); log::info!("Test7");
assert!(!(self.shadow_check_func.unwrap())( assert!(!(self.shadow_check_func.unwrap())(
((mem as usize) + 2 + 0xa8) as *const c_void, ((mem as usize) + 2 + 0xa8) as *const c_void,
6 6
)); ));
println!("Test8"); log::info!("Test8");
assert!(!(self.shadow_check_func.unwrap())( assert!(!(self.shadow_check_func.unwrap())(
((mem as usize) + 2 + 0xa8) as *const c_void, ((mem as usize) + 2 + 0xa8) as *const c_void,
0xac 0xac
)); ));
println!("Test9"); log::info!("Test9");
assert!((self.shadow_check_func.unwrap())( assert!((self.shadow_check_func.unwrap())(
((mem as usize) + 4 + 0xa8) as *const c_void, ((mem as usize) + 4 + 0xa8) as *const c_void,
0x1 0x1
)); ));
println!("FIN"); log::info!("FIN");
for i in 0..0xad { for i in 0..0xad {
assert!((self.shadow_check_func.unwrap())( assert!((self.shadow_check_func.unwrap())(
@ -400,7 +400,7 @@ impl AsanRuntime {
let (tls_start, tls_end) = Self::current_tls(); let (tls_start, tls_end) = Self::current_tls();
self.allocator self.allocator
.map_shadow_for_region(tls_start, tls_end, true); .map_shadow_for_region(tls_start, tls_end, true);
println!( log::info!(
"registering thread with stack {stack_start:x}:{stack_end:x} and tls {tls_start:x}:{tls_end:x}" "registering thread with stack {stack_start:x}:{stack_end:x} and tls {tls_start:x}:{tls_end:x}"
); );
} }
@ -413,7 +413,7 @@ impl AsanRuntime {
self.allocator self.allocator
.map_shadow_for_region(stack_start, stack_end, true); .map_shadow_for_region(stack_start, stack_end, true);
println!("registering thread with stack {stack_start:x}:{stack_end:x}"); log::info!("registering thread with stack {stack_start:x}:{stack_end:x}");
} }
/// Get the maximum stack size for the current stack /// Get the maximum stack size for the current stack
@ -939,7 +939,7 @@ impl AsanRuntime {
.expect("Failed to disassmeble"); .expect("Failed to disassmeble");
let insn = instructions.as_ref().first().unwrap(); // This is the very instruction that has triggered fault let insn = instructions.as_ref().first().unwrap(); // This is the very instruction that has triggered fault
println!("{insn:#?}"); log::info!("{insn:#?}");
let operands = cs.insn_detail(insn).unwrap().arch_detail().operands(); let operands = cs.insn_detail(insn).unwrap().arch_detail().operands();
let mut access_type: Option<RegAccessType> = None; let mut access_type: Option<RegAccessType> = None;
@ -976,7 +976,7 @@ impl AsanRuntime {
_ => None, _ => None,
}; };
// println!("{:x}", base_value); // log::trace!("{:x}", base_value);
#[allow(clippy::option_if_let_else)] #[allow(clippy::option_if_let_else)]
let error = if fault_address >= stack_start && fault_address < stack_end { let error = if fault_address >= stack_start && fault_address < stack_end {
match access_type { match access_type {
@ -1288,25 +1288,25 @@ impl AsanRuntime {
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
fn dump_registers(&self) { fn dump_registers(&self) {
println!("rax: {:x}", self.regs[0]); log::info!("rax: {:x}", self.regs[0]);
println!("rbx: {:x}", self.regs[1]); log::info!("rbx: {:x}", self.regs[1]);
println!("rcx: {:x}", self.regs[2]); log::info!("rcx: {:x}", self.regs[2]);
println!("rdx: {:x}", self.regs[3]); log::info!("rdx: {:x}", self.regs[3]);
println!("rbp: {:x}", self.regs[4]); log::info!("rbp: {:x}", self.regs[4]);
println!("rsp: {:x}", self.regs[5]); log::info!("rsp: {:x}", self.regs[5]);
println!("rsi: {:x}", self.regs[6]); log::info!("rsi: {:x}", self.regs[6]);
println!("rdi: {:x}", self.regs[7]); log::info!("rdi: {:x}", self.regs[7]);
println!("r8: {:x}", self.regs[8]); log::info!("r8: {:x}", self.regs[8]);
println!("r9: {:x}", self.regs[9]); log::info!("r9: {:x}", self.regs[9]);
println!("r10: {:x}", self.regs[10]); log::info!("r10: {:x}", self.regs[10]);
println!("r11: {:x}", self.regs[11]); log::info!("r11: {:x}", self.regs[11]);
println!("r12: {:x}", self.regs[12]); log::info!("r12: {:x}", self.regs[12]);
println!("r13: {:x}", self.regs[13]); log::info!("r13: {:x}", self.regs[13]);
println!("r14: {:x}", self.regs[14]); log::info!("r14: {:x}", self.regs[14]);
println!("r15: {:x}", self.regs[15]); log::info!("r15: {:x}", self.regs[15]);
println!("instrumented rip: {:x}", self.regs[16]); log::info!("instrumented rip: {:x}", self.regs[16]);
println!("fault address: {:x}", self.regs[17]); log::info!("fault address: {:x}", self.regs[17]);
println!("actual rip: {:x}", self.regs[18]); log::info!("actual rip: {:x}", self.regs[18]);
} }
// https://godbolt.org/z/oajhcP5sv // https://godbolt.org/z/oajhcP5sv
@ -2269,7 +2269,7 @@ impl AsanRuntime {
if let X86Operand(x86operand) = operand { if let X86Operand(x86operand) = operand {
if let X86OperandType::Mem(opmem) = x86operand.op_type { if let X86OperandType::Mem(opmem) = x86operand.op_type {
/* /*
println!( log::trace!(
"insn: {:#?} {:#?} width: {}, segment: {:#?}, base: {:#?}, index: {:#?}, scale: {}, disp: {}", "insn: {:#?} {:#?} width: {}, segment: {:#?}, base: {:#?}, index: {:#?}, scale: {}, disp: {}",
insn_id, insn_id,
instr, instr,

View File

@ -116,7 +116,7 @@ impl CmpLogRuntime {
/// Call the external function that populates the `cmplog_map` with the relevant values /// Call the external function that populates the `cmplog_map` with the relevant values
#[allow(clippy::unused_self)] #[allow(clippy::unused_self)]
extern "C" fn populate_lists(&mut self, op1: u64, op2: u64, retaddr: u64) { extern "C" fn populate_lists(&mut self, op1: u64, op2: u64, retaddr: u64) {
// println!( // log::trace!(
// "entered populate_lists with: {:#02x}, {:#02x}, {:#02x}", // "entered populate_lists with: {:#02x}, {:#02x}, {:#02x}",
// op1, op2, retaddr // op1, op2, retaddr
// ); // );

View File

@ -95,7 +95,7 @@ where
#[cfg(unix)] #[cfg(unix)]
unsafe { unsafe {
if ASAN_ERRORS.is_some() && !ASAN_ERRORS.as_ref().unwrap().is_empty() { if ASAN_ERRORS.is_some() && !ASAN_ERRORS.as_ref().unwrap().is_empty() {
println!("Crashing target as it had ASAN errors"); log::error!("Crashing target as it had ASAN errors");
libc::raise(libc::SIGABRT); libc::raise(libc::SIGABRT);
} }
} }
@ -174,7 +174,7 @@ where
if !helper.options().disable_excludes { if !helper.options().disable_excludes {
for range in ranges.gaps(&(0..usize::MAX)) { for range in ranges.gaps(&(0..usize::MAX)) {
println!("excluding range: {:x}-{:x}", range.start, range.end); log::info!("excluding range: {:x}-{:x}", range.start, range.end);
stalker.exclude(&MemoryRange::new( stalker.exclude(&MemoryRange::new(
NativePointer(range.start as *mut c_void), NativePointer(range.start as *mut c_void),
range.end - range.start, range.end - range.start,

View File

@ -228,7 +228,7 @@ where
for (i, module) in helper.module_map.values().iter().enumerate() { for (i, module) in helper.module_map.values().iter().enumerate() {
let range = module.range(); let range = module.range();
let start = range.base_address().0 as usize; let start = range.base_address().0 as usize;
// println!("start: {:x}", start); // log::trace!("start: {:x}", start);
helper helper
.ranges .ranges
.insert(start..(start + range.size()), (i as u16, module.path())); .insert(start..(start + range.size()), (i as u16, module.path()));
@ -237,7 +237,7 @@ where
for (module_name, offset) in options.dont_instrument.clone() { for (module_name, offset) in options.dont_instrument.clone() {
let module_details = ModuleDetails::with_name(module_name).unwrap(); let module_details = ModuleDetails::with_name(module_name).unwrap();
let lib_start = module_details.range().base_address().0 as usize; let lib_start = module_details.range().base_address().0 as usize;
// println!("removing address: {:#x}", lib_start + offset); // log::info!("removing address: {:#x}", lib_start + offset);
helper helper
.ranges .ranges
.remove((lib_start + offset)..(lib_start + offset + 4)); .remove((lib_start + offset)..(lib_start + offset + 4));
@ -262,19 +262,23 @@ where
#[cfg(unix)] #[cfg(unix)]
let instr_size = instr.bytes().len(); let instr_size = instr.bytes().len();
let address = instr.address(); let address = instr.address();
//println!("block @ {:x} transformed to {:x}", address, output.writer().pc()); //log::trace!("block @ {:x} transformed to {:x}", address, output.writer().pc());
//println!( //log::trace!(
//"address: {:x} contains: {:?}", //"address: {:x} contains: {:?}",
//address, //address,
//self.ranges().contains_key(&(address as usize)) //self.ranges().contains_key(&(address as usize))
//); //);
// println!("Ranges: {:#?}", self.ranges()); //log::info!("Ranges: {:#?}", self.ranges());
if helper.ranges().contains_key(&(address as usize)) { if helper.ranges().contains_key(&(address as usize)) {
if first { if first {
first = false; first = false;
//println!("block @ {:x} transformed to {:x}", address, output.writer().pc()); // log::info!(
// "block @ {:x} transformed to {:x}",
// address,
// output.writer().pc()
// );
if let Some(rt) = helper.runtime_mut::<CoverageRuntime>() { if let Some(rt) = helper.runtime_mut::<CoverageRuntime>() {
rt.emit_coverage_mapping(address, &output); rt.emit_coverage_mapping(address, &output);
} }
@ -284,7 +288,7 @@ where
instruction.put_callout(|context| { instruction.put_callout(|context| {
let real_address = rt.real_address_for_stalked(pc(&context)); let real_address = rt.real_address_for_stalked(pc(&context));
//let (range, (id, name)) = helper.ranges.get_key_value(&real_address).unwrap(); //let (range, (id, name)) = helper.ranges.get_key_value(&real_address).unwrap();
//println!("{}:0x{:016x}", name, real_address - range.start); //log::trace!("{}:0x{:016x}", name, real_address - range.start);
rt.drcov_basic_blocks.push(DrCovBasicBlock::new( rt.drcov_basic_blocks.push(DrCovBasicBlock::new(
real_address, real_address,
real_address + instr_size, real_address + instr_size,

View File

@ -139,7 +139,7 @@ impl From<EventType> for libc::c_uint {
///# use std::time::Duration; ///# use std::time::Duration;
///# use std::thread; ///# use std::thread;
/// pthread_hook::install(|event, pthread, addr, size| { /// pthread_hook::install(|event, pthread, addr, size| {
/// println!("thread id=0x{:x} event={:?} addr={:?} size={:x}", pthread, event, addr, size); /// log::trace!("thread id=0x{:x} event={:?} addr={:?} size={:x}", pthread, event, addr, size);
/// }); /// });
///# thread::spawn(|| { ///# thread::spawn(|| {
///# thread::sleep(Duration::from_millis(1)); ///# thread::sleep(Duration::from_millis(1));

View File

@ -52,6 +52,7 @@ capstone = "0.11.0"
#pyo3 = { version = "0.15", features = ["extension-module"], optional = true } #pyo3 = { version = "0.15", features = ["extension-module"], optional = true }
pyo3 = { version = "0.17", features = ["pyproto"], optional = true } pyo3 = { version = "0.17", features = ["pyproto"], optional = true }
rangemap = "1.0" rangemap = "1.0"
log = "0.4.17"
[build-dependencies] [build-dependencies]
pyo3-build-config = { version = "0.15", optional = true } pyo3-build-config = { version = "0.15", optional = true }

View File

@ -106,7 +106,7 @@ where
ret_addr ret_addr
}; };
// eprintln!("RET @ 0x{:#x}", ret_addr); // log::info!("RET @ 0x{:#x}", ret_addr);
if let Some(h) = hooks if let Some(h) = hooks
.helpers_mut() .helpers_mut()

View File

@ -114,7 +114,7 @@ where
*pc as usize + block_len, *pc as usize + block_len,
)); ));
} }
Err(r) => println!("{r:#?}"), Err(r) => log::info!("{r:#?}"),
} }
} }
} }
@ -151,7 +151,7 @@ where
drcov_vec drcov_vec
.push(DrCovBasicBlock::new(*pc as usize, *pc as usize + block_len)); .push(DrCovBasicBlock::new(*pc as usize, *pc as usize + block_len));
} }
Err(r) => println!("{r:#?}"), Err(r) => log::info!("{r:#?}"),
} }
} }

View File

@ -34,6 +34,7 @@ libafl_qemu = { path = "../libafl_qemu", version = "0.9.0" }
typed-builder = "0.12" # Implement the builder pattern at compiletime typed-builder = "0.12" # Implement the builder pattern at compiletime
#pyo3 = { version = "0.17", features = ["extension-module"], optional = true } #pyo3 = { version = "0.17", features = ["extension-module"], optional = true }
pyo3 = { version = "0.17", optional = true } pyo3 = { version = "0.17", optional = true }
log = "0.4.17"
[lib] [lib]
name = "libafl_sugar" name = "libafl_sugar"

View File

@ -90,14 +90,14 @@ impl<'a, const MAP_SIZE: usize> ForkserverBytesCoverageSugar<'a, MAP_SIZE> {
}; };
if self.use_cmplog.unwrap_or(false) { if self.use_cmplog.unwrap_or(false) {
println!("[WARNING] use of cmplog not currently supported, use_cmplog ignored."); log::warn!("use of cmplog not currently supported, use_cmplog ignored.");
} }
let timeout = Duration::from_secs(self.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)); let timeout = Duration::from_secs(self.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS));
let mut out_dir = self.output_dir.clone(); let mut out_dir = self.output_dir.clone();
if fs::create_dir(&out_dir).is_err() { if fs::create_dir(&out_dir).is_err() {
println!("Out dir at {:?} already exists.", &out_dir); log::info!("Out dir at {:?} already exists.", &out_dir);
assert!( assert!(
out_dir.is_dir(), out_dir.is_dir(),
"Out dir at {:?} is not a valid directory!", "Out dir at {:?} is not a valid directory!",
@ -111,7 +111,7 @@ impl<'a, const MAP_SIZE: usize> ForkserverBytesCoverageSugar<'a, MAP_SIZE> {
let shmem_provider = UnixShMemProvider::new().expect("Failed to init shared memory"); let shmem_provider = UnixShMemProvider::new().expect("Failed to init shared memory");
let mut shmem_provider_client = shmem_provider.clone(); let mut shmem_provider_client = shmem_provider.clone();
let monitor = MultiMonitor::new(|s| println!("{s}")); let monitor = MultiMonitor::new(|s| log::info!("{s}"));
let mut run_client = |state: Option<_>, let mut run_client = |state: Option<_>,
mut mgr: LlmpRestartingEventManager<_, _>, mut mgr: LlmpRestartingEventManager<_, _>,
@ -211,19 +211,19 @@ impl<'a, const MAP_SIZE: usize> ForkserverBytesCoverageSugar<'a, MAP_SIZE> {
8, 8,
) )
.expect("Failed to generate the initial corpus"); .expect("Failed to generate the initial corpus");
println!( log::info!(
"We imported {} inputs from the generator.", "We imported {} inputs from the generator.",
state.corpus().count() state.corpus().count()
); );
} else { } else {
println!("Loading from {:?}", &self.input_dirs); log::info!("Loading from {:?}", &self.input_dirs);
// Load from disk // Load from disk
state state
.load_initial_inputs(&mut fuzzer, &mut executor, &mut mgr, self.input_dirs) .load_initial_inputs(&mut fuzzer, &mut executor, &mut mgr, self.input_dirs)
.unwrap_or_else(|_| { .unwrap_or_else(|_| {
panic!("Failed to load initial corpus at {:?}", &self.input_dirs); panic!("Failed to load initial corpus at {:?}", &self.input_dirs);
}); });
println!("We imported {} inputs from disk.", state.corpus().count()); log::info!("We imported {} inputs from disk.", state.corpus().count());
} }
} }
@ -286,7 +286,7 @@ impl<'a, const MAP_SIZE: usize> ForkserverBytesCoverageSugar<'a, MAP_SIZE> {
let launcher = launcher.stdout_file(Some("/dev/null")); let launcher = launcher.stdout_file(Some("/dev/null"));
match launcher.build().launch() { match launcher.build().launch() {
Ok(()) => (), Ok(()) => (),
Err(Error::ShuttingDown) => println!("\nFuzzing stopped by user. Good Bye."), Err(Error::ShuttingDown) => log::info!("\nFuzzing stopped by user. Good Bye."),
Err(err) => panic!("Fuzzingg failed {err:?}"), Err(err) => panic!("Fuzzingg failed {err:?}"),
} }
} }

View File

@ -122,7 +122,7 @@ where
let mut out_dir = self.output_dir.clone(); let mut out_dir = self.output_dir.clone();
if fs::create_dir(&out_dir).is_err() { if fs::create_dir(&out_dir).is_err() {
println!("Out dir at {:?} already exists.", &out_dir); log::info!("Out dir at {:?} already exists.", &out_dir);
assert!( assert!(
out_dir.is_dir(), out_dir.is_dir(),
"Out dir at {:?} is not a valid directory!", "Out dir at {:?} is not a valid directory!",
@ -137,7 +137,7 @@ where
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
let monitor = MultiMonitor::new(|s| println!("{s}")); let monitor = MultiMonitor::new(|s| log::info!("{s}"));
let mut run_client = |state: Option<_>, let mut run_client = |state: Option<_>,
mut mgr: LlmpRestartingEventManager<_, _>, mut mgr: LlmpRestartingEventManager<_, _>,
@ -231,19 +231,19 @@ where
8, 8,
) )
.expect("Failed to generate the initial corpus"); .expect("Failed to generate the initial corpus");
println!( log::info!(
"We imported {} inputs from the generator.", "We imported {} inputs from the generator.",
state.corpus().count() state.corpus().count()
); );
} else { } else {
println!("Loading from {:?}", &self.input_dirs); log::info!("Loading from {:?}", &self.input_dirs);
// Load from disk // Load from disk
state state
.load_initial_inputs(&mut fuzzer, &mut executor, &mut mgr, self.input_dirs) .load_initial_inputs(&mut fuzzer, &mut executor, &mut mgr, self.input_dirs)
.unwrap_or_else(|_| { .unwrap_or_else(|_| {
panic!("Failed to load initial corpus at {:?}", &self.input_dirs); panic!("Failed to load initial corpus at {:?}", &self.input_dirs);
}); });
println!("We imported {} inputs from disk.", state.corpus().count()); log::info!("We imported {} inputs from disk.", state.corpus().count());
} }
} }
@ -346,7 +346,7 @@ where
let launcher = launcher.stdout_file(Some("/dev/null")); let launcher = launcher.stdout_file(Some("/dev/null"));
match launcher.build().launch() { match launcher.build().launch() {
Ok(()) => (), Ok(()) => (),
Err(Error::ShuttingDown) => println!("\nFuzzing stopped by user. Good Bye."), Err(Error::ShuttingDown) => log::info!("\nFuzzing stopped by user. Good Bye."),
Err(err) => panic!("Fuzzingg failed {err:?}"), Err(err) => panic!("Fuzzingg failed {err:?}"),
} }
} }

View File

@ -127,7 +127,7 @@ where
let mut out_dir = self.output_dir.clone(); let mut out_dir = self.output_dir.clone();
if fs::create_dir(&out_dir).is_err() { if fs::create_dir(&out_dir).is_err() {
println!("Out dir at {:?} already exists.", &out_dir); log::info!("Out dir at {:?} already exists.", &out_dir);
assert!( assert!(
out_dir.is_dir(), out_dir.is_dir(),
"Out dir at {:?} is not a valid directory!", "Out dir at {:?} is not a valid directory!",
@ -142,7 +142,7 @@ where
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory"); let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
let monitor = MultiMonitor::new(|s| println!("{s}")); let monitor = MultiMonitor::new(|s| log::info!("{s}"));
let mut run_client = |state: Option<_>, let mut run_client = |state: Option<_>,
mut mgr: LlmpRestartingEventManager<_, _>, mut mgr: LlmpRestartingEventManager<_, _>,
@ -247,12 +247,12 @@ where
8, 8,
) )
.expect("Failed to generate the initial corpus"); .expect("Failed to generate the initial corpus");
println!( log::info!(
"We imported {} inputs from the generator.", "We imported {} inputs from the generator.",
state.corpus().count() state.corpus().count()
); );
} else { } else {
println!("Loading from {:?}", &self.input_dirs); log::info!("Loading from {:?}", &self.input_dirs);
// Load from disk // Load from disk
state state
.load_initial_inputs( .load_initial_inputs(
@ -264,7 +264,7 @@ where
.unwrap_or_else(|_| { .unwrap_or_else(|_| {
panic!("Failed to load initial corpus at {:?}", &self.input_dirs); panic!("Failed to load initial corpus at {:?}", &self.input_dirs);
}); });
println!("We imported {} inputs from disk.", state.corpus().count()); log::info!("We imported {} inputs from disk.", state.corpus().count());
} }
} }
@ -350,12 +350,12 @@ where
8, 8,
) )
.expect("Failed to generate the initial corpus"); .expect("Failed to generate the initial corpus");
println!( log::info!(
"We imported {} inputs from the generator.", "We imported {} inputs from the generator.",
state.corpus().count() state.corpus().count()
); );
} else { } else {
println!("Loading from {:?}", &self.input_dirs); log::info!("Loading from {:?}", &self.input_dirs);
// Load from disk // Load from disk
state state
.load_initial_inputs( .load_initial_inputs(
@ -367,7 +367,7 @@ where
.unwrap_or_else(|_| { .unwrap_or_else(|_| {
panic!("Failed to load initial corpus at {:?}", &self.input_dirs); panic!("Failed to load initial corpus at {:?}", &self.input_dirs);
}); });
println!("We imported {} inputs from disk.", state.corpus().count()); log::info!("We imported {} inputs from disk.", state.corpus().count());
} }
} }

View File

@ -31,6 +31,7 @@ cc = { version = "1.0", features = ["parallel"] }
[dependencies] [dependencies]
libafl = { path = "../libafl", version = "0.9.0", default-features = false, features = [] } libafl = { path = "../libafl", version = "0.9.0", default-features = false, features = [] }
log = "0.4.17"
rangemap = "1.0" rangemap = "1.0"
serde = { version = "1.0", default-features = false, features = ["alloc"] } # serialization lib serde = { version = "1.0", default-features = false, features = ["alloc"] } # serialization lib

View File

@ -18,6 +18,7 @@ libafl = { path = "../libafl", version = "0.9.0", features = [
] } ] }
tinyinst = { git = "https://github.com/AFLplusplus/tinyinst-rs" } tinyinst = { git = "https://github.com/AFLplusplus/tinyinst-rs" }
# tinyinst-rs = { path = "../../tinyinst-rs" } # tinyinst-rs = { path = "../../tinyinst-rs" }
log = "0.4.17"
[build-dependencies] [build-dependencies]
cmake = "0.1" cmake = "0.1"

View File

@ -235,7 +235,7 @@ where
// setup shared memory // setup shared memory
let mut shmem = provider.new_shmem(MAX_FILE + SHMEM_FUZZ_HDR_SIZE)?; let mut shmem = provider.new_shmem(MAX_FILE + SHMEM_FUZZ_HDR_SIZE)?;
let shmem_id = shmem.id(); let shmem_id = shmem.id();
// println!("{:#?}", shmem.id()); // log::trace!("{:#?}", shmem.id());
// shmem.write_to_env("__TINY_SHM_FUZZ_ID")?; // shmem.write_to_env("__TINY_SHM_FUZZ_ID")?;
let size_in_bytes = (MAX_FILE + SHMEM_FUZZ_HDR_SIZE).to_ne_bytes(); let size_in_bytes = (MAX_FILE + SHMEM_FUZZ_HDR_SIZE).to_ne_bytes();
@ -269,7 +269,7 @@ where
"No input file or shmem provided".to_string(), "No input file or shmem provided".to_string(),
)); ));
} }
println!("tinyinst args: {:#?}", &self.tinyinst_args); log::info!("tinyinst args: {:#?}", &self.tinyinst_args);
let cur_input = InputFile::create(INPUTFILE_STD).expect("Unable to create cur_file"); let cur_input = InputFile::create(INPUTFILE_STD).expect("Unable to create cur_file");

View File

@ -12,3 +12,4 @@ categories = ["development-tools::testing"]
[dependencies] [dependencies]
cargo_toml = "0.14" cargo_toml = "0.14"
walkdir = "2" walkdir = "2"
log = "0.4.17"

View File

@ -23,5 +23,5 @@ fn main() {
} }
} }
println!("{}", fuzzers.join("\n")); log::info!("{}", fuzzers.join("\n"));
} }

View File

@ -14,6 +14,7 @@ categories = ["development-tools::testing", "emulators", "embedded", "os", "no-s
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
log = "0.4.17"
[lib] [lib]
name = "deexit" name = "deexit"

View File

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

View File

@ -21,3 +21,4 @@ postcard = "1.0"
lazy_static = "1.4.0" lazy_static = "1.4.0"
libafl = { path = "../../../libafl" } libafl = { path = "../../../libafl" }
clap = { version = "4.0", features = ["derive"] } clap = { version = "4.0", features = ["derive"] }
log = "0.4.17"

View File

@ -110,7 +110,7 @@ fn prepare_transitions(
let (terminal, ss, is_regex) = tokenize(rule); let (terminal, ss, is_regex) = tokenize(rule);
let dest = *state_count; let dest = *state_count;
// println!("Rule \"{}\", {} over {}", &rule, i, rules.len()); // log::trace!("Rule \"{}\", {} over {}", &rule, i, rules.len());
// Creating a state stack for the new state // Creating a state stack for the new state
let mut state_stack = state_stacks let mut state_stack = state_stacks
@ -165,7 +165,7 @@ fn prepare_transitions(
state_stacks.s.insert(dest, state_stack_sorted); state_stacks.s.insert(dest, state_stack_sorted);
pda.push(transition); pda.push(transition);
println!("worklist size: {}", worklist.len()); log::info!("worklist size: {}", worklist.len());
*state_count += 1; *state_count += 1;
// i += 1; // i += 1;
@ -193,10 +193,10 @@ fn postprocess(pda: &[Transition], stack_limit: usize) -> Automaton {
assert!(initial.len() == 1); assert!(initial.len() == 1);
println!("# transitions: {}", pda.len()); log::info!("# transitions: {}", pda.len());
println!("# states: {}", states.len()); log::info!("# states: {}", states.len());
println!("initial state: {:?}", &initial); log::info!("initial state: {:?}", &initial);
println!("final states: {:?}", &finals); log::info!("final states: {:?}", &finals);
let mut memoized = Vec::with_capacity(states.len()); let mut memoized = Vec::with_capacity(states.len());
//let mut memoized_unique = Vec::with_capacity(states.len()); //let mut memoized_unique = Vec::with_capacity(states.len());
@ -218,7 +218,7 @@ fn postprocess(pda: &[Transition], stack_limit: usize) -> Automaton {
} }
} }
// println!("culled_pda size: {} pda size: {}", culled_pda.len(), pda.len()); // log::trace!("culled_pda size: {} pda size: {}", culled_pda.len(), pda.len());
let culled_finals: HashSet<usize> = finals.difference(&blocklist).copied().collect(); let culled_finals: HashSet<usize> = finals.difference(&blocklist).copied().collect();
assert!(culled_finals.len() == 1); assert!(culled_finals.len() == 1);
@ -238,7 +238,7 @@ fn postprocess(pda: &[Transition], stack_limit: usize) -> Automaton {
}); });
if num_transition % 4096 == 0 { if num_transition % 4096 == 0 {
println!( log::info!(
"processed {} transitions over {}", "processed {} transitions over {}",
num_transition, num_transition,
culled_pda.len() culled_pda.len()
@ -279,7 +279,7 @@ fn postprocess(pda: &[Transition], stack_limit: usize) -> Automaton {
}); });
if num_transition % 4096 == 0 { if num_transition % 4096 == 0 {
println!( log::info!(
"processed {} transitions over {}", "processed {} transitions over {}",
num_transition, num_transition,
pda.len() pda.len()