Skip to content

Windows Support for LibAFL-LibFuzzer #3130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
May 20, 2025
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions libafl_libfuzzer/runtime/Cargo.toml.template
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@ version = "0.15.2"
edition = "2024"
publish = false

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[features]
default = ["fork"]
default = []
Copy link
Member

@domenukk domenukk May 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think fork as default is good for perf on non-windows, it's a nop on win

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have it set below that on non-windows to keep things explicit and because tui_monitor needs to be default on non-win anyway, but I can change it if wanted.

## Enables forking mode for the LibAFL launcher (instead of starting new processes)
fork = ["libafl/fork"]
track_hit_feedbacks = [
"libafl/track_hit_feedbacks",
"libafl_targets/track_hit_feedbacks",
]
tui_monitor = ["libafl/tui_monitor"]

[target.'cfg(not(windows))'.features]
## Enable the `fork` feature on non-windows platforms
default = ["fork", "tui_monitor"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't think we need tui_monitor on non-win

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have to put in a few libs anyway to get this to work so I'll just revert this part of the changes and make tui_monitor work.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't fully get the tui monitor thing - it's just not working on Win yet?


[profile.release]
lto = true
Expand All @@ -40,7 +43,6 @@ libafl = { path = "../libafl", default-features = false, features = [
"regex",
"errors_backtrace",
"serdeany_autoreg",
"tui_monitor",
"unicode",
] }
libafl_bolts = { path = "../libafl_bolts", default-features = false, features = [
Expand Down
2 changes: 1 addition & 1 deletion libafl_libfuzzer/runtime/src/corpus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ where
}
#[inline]
fn count_all(&self) -> usize {
self.count_disabled().saturating_add(self.count_disabled())
self.count().saturating_add(self.count_disabled())
}

#[expect(clippy::used_underscore_items)]
Expand Down
105 changes: 66 additions & 39 deletions libafl_libfuzzer/runtime/src/fuzz.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,59 @@
use core::ffi::c_int;
#[cfg(unix)]
use std::io::{Write, stderr, stdout};
use std::{fmt::Debug, fs::File, net::TcpListener, os::fd::AsRawFd, str::FromStr};
use std::{
fmt::Debug,
fs::File,
io::{Write, stderr, stdout},
net::TcpListener,
os::fd::AsRawFd,
str::FromStr,
};

#[cfg(feature = "tui_monitor")]
use libafl::monitors::tui::TuiMonitor;
use libafl::{
Error, Fuzzer, HasMetadata,
corpus::Corpus,
events::{
EventConfig, EventReceiver, ProgressReporter, SimpleEventManager,
SimpleRestartingEventManager, launcher::Launcher,
},
events::{EventReceiver, ProgressReporter, SimpleEventManager},
executors::ExitKind,
monitors::{Monitor, MultiMonitor, tui::TuiMonitor},
monitors::MultiMonitor,
stages::StagesTuple,
state::{HasCurrentStageId, HasExecutions, HasLastReportTime, HasSolutions, Stoppable},
};
#[cfg(unix)]
use libafl::{
events::{EventConfig, SimpleRestartingEventManager, launcher::Launcher},
monitors::Monitor,
};
#[cfg(unix)]
use libafl_bolts::{
core_affinity::Cores,
shmem::{ShMemProvider, StdShMemProvider},
};

use crate::{feedbacks::LibfuzzerCrashCauseMetadata, fuzz_with, options::LibfuzzerOptions};

#[cfg(unix)]
fn destroy_output_fds(options: &LibfuzzerOptions) {
#[cfg(unix)]
{
use libafl_bolts::os::{dup2, null_fd};
use libafl_bolts::os::{dup2, null_fd};

let null_fd = null_fd().unwrap();
let stdout_fd = stdout().as_raw_fd();
let stderr_fd = stderr().as_raw_fd();
let null_fd = null_fd().unwrap();
let stdout_fd = stdout().as_raw_fd();
let stderr_fd = stderr().as_raw_fd();

if options.tui() {
#[cfg(feature = "tui_monitor")]
if options.tui() {
dup2(null_fd, stdout_fd).unwrap();
dup2(null_fd, stderr_fd).unwrap();
return;
}

if options.close_fd_mask() != 0 {
if options.close_fd_mask() & u8::try_from(stderr_fd).unwrap() != 0 {
dup2(null_fd, stdout_fd).unwrap();
}
if options.close_fd_mask() & u8::try_from(stderr_fd).unwrap() != 0 {
dup2(null_fd, stderr_fd).unwrap();
} else if options.close_fd_mask() != 0 {
if options.close_fd_mask() & u8::try_from(stderr_fd).unwrap() != 0 {
dup2(null_fd, stdout_fd).unwrap();
}
if options.close_fd_mask() & u8::try_from(stderr_fd).unwrap() != 0 {
dup2(null_fd, stderr_fd).unwrap();
}
}
}
}
Expand Down Expand Up @@ -91,6 +104,7 @@ where
Ok(())
}

#[cfg(unix)]
fn fuzz_single_forking<M>(
options: &LibfuzzerOptions,
harness: &extern "C" fn(*const u8, usize) -> c_int,
Expand Down Expand Up @@ -121,9 +135,7 @@ where
})
}

/// Communicate the selected port to subprocesses
const PORT_PROVIDER_VAR: &str = "_LIBAFL_LIBFUZZER_FORK_PORT";

#[cfg(unix)]
fn fuzz_many_forking<M>(
options: &LibfuzzerOptions,
harness: &extern "C" fn(*const u8, usize) -> c_int,
Expand All @@ -134,6 +146,9 @@ fn fuzz_many_forking<M>(
where
M: Monitor + Clone + Debug + 'static,
{
// Communicate the selected port to subprocesses
const PORT_PROVIDER_VAR: &str = "_LIBAFL_LIBFUZZER_FORK_PORT";

destroy_output_fds(options);
let broker_port = std::env::var(PORT_PROVIDER_VAR)
.map_err(Error::from)
Expand Down Expand Up @@ -194,35 +209,47 @@ pub fn fuzz(
options: &LibfuzzerOptions,
harness: &extern "C" fn(*const u8, usize) -> c_int,
) -> Result<(), Error> {
#[cfg(unix)]
if let Some(forks) = options.forks() {
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");

#[cfg(feature = "tui_monitor")]
if options.tui() {
let monitor = TuiMonitor::builder()
.title(options.fuzzer_name())
.enhanced_graphics(true)
.build();
fuzz_many_forking(options, harness, shmem_provider, forks, monitor)
} else if forks == 1 {
let monitor = MultiMonitor::new(create_monitor_closure());
fuzz_single_forking(options, harness, shmem_provider, monitor)
} else {
let monitor = MultiMonitor::new(create_monitor_closure());
fuzz_many_forking(options, harness, shmem_provider, forks, monitor)
return fuzz_many_forking(options, harness, shmem_provider, forks, monitor);
}

// Non-TUI path or when tui_monitor feature is disabled
let monitor = MultiMonitor::new(create_monitor_closure());

if forks == 1 {
return fuzz_single_forking(options, harness, shmem_provider, monitor);
}
} else if options.tui() {

return fuzz_many_forking(options, harness, shmem_provider, forks, monitor);
}

#[cfg(feature = "tui_monitor")]
if options.tui() {
// if the user specifies TUI, we assume they want to fork; it would not be possible to use
// TUI safely otherwise
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
let monitor = TuiMonitor::builder()
.title(options.fuzzer_name())
.enhanced_graphics(true)
.build();
fuzz_many_forking(options, harness, shmem_provider, 1, monitor)
} else {
destroy_output_fds(options);
fuzz_with!(options, harness, do_fuzz, |fuzz_single| {
let mgr = SimpleEventManager::new(MultiMonitor::new(create_monitor_closure()));
crate::start_fuzzing_single(fuzz_single, None, mgr)
})
return fuzz_many_forking(options, harness, shmem_provider, 1, monitor);
}

// Default path when no forks or TUI are specified, or when tui_monitor feature is disabled
#[cfg(unix)]
destroy_output_fds(options);

fuzz_with!(options, harness, do_fuzz, |fuzz_single| {
let mgr = SimpleEventManager::new(MultiMonitor::new(create_monitor_closure()));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LibAFL_Libfuzzer doesn't support Llmp?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it doesn't right now but no reason we couldn't add it. Could use llmp+multiprocessing on windows where we can't fork

crate::start_fuzzing_single(fuzz_single, None, mgr)
})
}
20 changes: 20 additions & 0 deletions libafl_libfuzzer/runtime/src/harness_wrap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,23 @@ extern "C" int libafl_libfuzzer_test_one_input(
return -2; // custom code for "we died!"
}
}

#ifdef _WIN32
// For Windows API functions used by MiMalloc
#pragma comment(lib, "advapi32.lib")
// For Windows networking functionality used by LibAFL
#pragma comment(lib, "ws2_32.lib")
// For Windows API functions to retrieve user home directory used by Rust STD
#pragma comment(lib, "userenv.lib")
// For base Windows API functions like file reads and writes
#pragma comment(lib, "ntdll.lib")
// For crypto functions called by LibAFL's random utilities
#pragma comment(lib, "bcrypt.lib")
// Required by windows_core
#pragma comment(lib, "ole32.lib")
// For debug facilities used in debug builds
#pragma comment(lib, "dbghelp.lib")

#pragma comment(linker, "/export:LLVMFuzzerRunDriver")
#pragma comment(linker, "/export:__sanitizer_cov_8bit_counters_init")
#endif // _WIN32
16 changes: 15 additions & 1 deletion libafl_libfuzzer/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,13 @@
#![allow(clippy::borrow_deref_ref)]

use core::ffi::{CStr, c_char, c_int};
use std::{fs::File, io::stderr, os::fd::RawFd};
#[cfg(unix)]
use std::{
os::fd::RawFd,
{fs::File, io::stderr},
};

#[cfg(unix)]
use env_logger::Target;
use libafl::{
Error,
Expand Down Expand Up @@ -328,11 +333,20 @@ macro_rules! fuzz_with {

// Attempt to use tokens from libfuzzer dicts
if !state.has_metadata::<Tokens>() {
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
let mut toks = if let Some(tokens) = $options.dict() {
tokens.clone()
} else {
Tokens::default()
};

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
let toks = if let Some(tokens) = $options.dict() {
tokens.clone()
} else {
Tokens::default()
};

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
{
toks += libafl_targets::autotokens()?;
Expand Down
6 changes: 3 additions & 3 deletions libafl_libfuzzer/runtime/src/merge.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{env::temp_dir, ffi::c_int, fs::rename};
#[cfg(unix)]
use std::{
env::temp_dir,
ffi::c_int,
fs::{File, rename},
fs::File,
io::Write,
os::fd::{AsRawFd, FromRawFd},
};
Expand Down
Loading
Loading