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 1 commit
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
91 changes: 69 additions & 22 deletions libafl_libfuzzer/runtime/src/fuzz.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
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::io::{Write, os::fd::AsRawFd, stderr, stdout};
use std::{fmt::Debug, fs::File, net::TcpListener, str::FromStr};

#[cfg(feature = "tui_monitor")]
use libafl::monitors::tui::TuiMonitor;
use libafl::{
Error, Fuzzer, HasMetadata,
corpus::Corpus,
Expand All @@ -11,7 +13,7 @@ use libafl::{
SimpleRestartingEventManager, launcher::Launcher,
},
executors::ExitKind,
monitors::{Monitor, MultiMonitor, tui::TuiMonitor},
monitors::{Monitor, MultiMonitor},
stages::StagesTuple,
state::{HasCurrentStageId, HasExecutions, HasLastReportTime, HasSolutions, Stoppable},
};
Expand All @@ -31,10 +33,14 @@ fn destroy_output_fds(options: &LibfuzzerOptions) {
let stdout_fd = stdout().as_raw_fd();
let stderr_fd = stderr().as_raw_fd();

#[cfg(feature = "tui_monitor")]
if options.tui() {
dup2(null_fd, stdout_fd).unwrap();
dup2(null_fd, stderr_fd).unwrap();
} else if options.close_fd_mask() != 0 {
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();
}
Expand Down Expand Up @@ -91,6 +97,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 +128,23 @@ where
})
}

#[cfg(windows)]
fn fuzz_single_forking<M>(
options: &LibfuzzerOptions,
harness: &extern "C" fn(*const u8, usize) -> c_int,
shmem_provider: StdShMemProvider,
monitor: M,
) -> Result<(), Error>
where
M: Monitor + Debug,
{
panic!("Forking not supported on Windows");
}

/// 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 Down Expand Up @@ -170,6 +191,20 @@ where
})
}

#[cfg(windows)]
fn fuzz_many_forking<M>(
options: &LibfuzzerOptions,
harness: &extern "C" fn(*const u8, usize) -> c_int,
shmem_provider: StdShMemProvider,
forks: usize,
monitor: M,
) -> Result<(), Error>
where
M: Monitor + Clone + Debug + 'static,
{
panic!("Forking not supported on Windows");
}

fn create_monitor_closure() -> impl Fn(&str) + Clone {
#[cfg(unix)]
let stderr_fd =
Expand All @@ -196,29 +231,41 @@ pub fn fuzz(
) -> Result<(), Error> {
if let Some(forks) = options.forks() {
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
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());

#[cfg(feature = "tui_monitor")]
{
if options.tui() {
let monitor = TuiMonitor::builder()
.title(options.fuzzer_name())
.enhanced_graphics(true)
.build();
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 {
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)
}
} else 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 {
#[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();
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
destroy_output_fds(options);
fuzz_with!(options, harness, do_fuzz, |fuzz_single| {
let mgr = SimpleEventManager::new(MultiMonitor::new(create_monitor_closure()));
Expand Down
5 changes: 4 additions & 1 deletion libafl_libfuzzer/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@
#![allow(clippy::borrow_deref_ref)]

use core::ffi::{CStr, c_char, c_int};
use std::{fs::File, io::stderr, os::fd::RawFd};
use std::{fs::File, io::stderr};

#[cfg(unix)]
use std::os::fd::RawFd;

use env_logger::Target;
use libafl::{
Expand Down
3 changes: 2 additions & 1 deletion libafl_libfuzzer/runtime/src/merge.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#[cfg(unix)]
use std::os::fd::{AsRawFd, FromRawFd};
use std::{
env::temp_dir,
ffi::c_int,
fs::{File, rename},
io::Write,
os::fd::{AsRawFd, FromRawFd},
};

use libafl::{
Expand Down
4 changes: 4 additions & 0 deletions libafl_libfuzzer/runtime/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,10 @@ impl<'a> LibfuzzerOptionsBuilder<'a> {
"dict" => self.dict = Some(value),
"fork" | "jobs" => {
self.forks = Some(parse_or_bail!(name, value, usize));
#[cfg(windows)]
if self.forks.unwrap() > 1 {
panic!("Error: Windows does not support forking!");
}
}
"ignore_crashes" => {
self.ignore_crashes = Some(parse_or_bail!(name, value, u64) > 0);
Expand Down
17 changes: 16 additions & 1 deletion libafl_libfuzzer/runtime/src/tmin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ use std::{
fs::{read, write},
};

#[cfg(windows)]
use libafl::executors::inprocess::InProcessExecutor;
#[cfg(unix)]
use libafl::executors::inprocess_fork::InProcessForkExecutor;
use libafl::{
Error, ExecutesInput, Fuzzer, StdFuzzer,
corpus::{Corpus, HasTestcase, InMemoryCorpus, Testcase},
events::SimpleEventManager,
executors::{ExitKind, inprocess_fork::InProcessForkExecutor},
executors::ExitKind,
feedbacks::{CrashFeedback, TimeoutFeedback},
inputs::{BytesInput, HasMutatorBytes, HasTargetBytes},
mutators::{Mutator, StdScheduledMutator, havoc_mutations_no_crossover},
Expand Down Expand Up @@ -62,6 +66,7 @@ fn minimize_crash_with_mutator<M: Mutator<BytesInput, TMinState>>(
let mut fuzzer = StdFuzzer::new(QueueScheduler::new(), (), ());

let shmem_provider = StdShMemProvider::new()?;
#[cfg(unix)]
let mut executor = InProcessForkExecutor::new(
&mut harness,
(),
Expand All @@ -72,6 +77,16 @@ fn minimize_crash_with_mutator<M: Mutator<BytesInput, TMinState>>(
shmem_provider,
)?;

#[cfg(windows)]
let mut executor = InProcessExecutor::with_timeout(
&mut harness,
(),
&mut fuzzer,
&mut state,
&mut mgr,
options.timeout(),
)?;

let exit_kind = fuzzer.execute_input(&mut state, &mut executor, &mut mgr, &input)?;

let size = input.len();
Expand Down
83 changes: 83 additions & 0 deletions libafl_libfuzzer_runtime/build.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#!/usr/bin/env pwsh
Copy link
Member

Choose a reason for hiding this comment

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

Maybe call that guy from a justfile?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good idea, I'll add a justfile for libafl_libfuzzer and libafl_libfuzzer_runtime.


$ErrorActionPreference = "Stop"

$SCRIPT_DIR = Split-Path -Parent $MyInvocation.MyCommand.Path

Set-Location $SCRIPT_DIR

if ($args.Count -eq 0) {
$profile = "release"
} else {
$profile = $args[0]
}

try {
$nightly_version = Invoke-Expression "cargo +nightly --version" 2>$null
if (-not $nightly_version) {
Write-Host "You must install a recent Rust nightly to build the libafl_libfuzzer runtime!" -ForegroundColor Red
exit 1
}
} catch {
Write-Host "You must install a recent Rust nightly to build the libafl_libfuzzer runtime!" -ForegroundColor Red
exit 1
}

Write-Host "Building libafl_libfuzzer runtime with profile '$profile'" -ForegroundColor Green
Invoke-Expression "cargo +nightly build --profile $profile"

# target-libdir is e.g. C:\Users\user\.rustup\toolchain\nightly-x86_64-pc-windows-msvc\lib\rustlib\x86_64-pc-windows-msvc\lib
$RUSTC_BIN = Split-Path -Parent (Invoke-Expression "cargo +nightly rustc -Zunstable-options --print target-libdir")
$RUSTC_BIN = Join-Path $RUSTC_BIN "bin"
$RUST_LLD = Join-Path $RUSTC_BIN "rust-lld.exe"
$RUST_AR = Join-Path $RUSTC_BIN "llvm-ar.exe"
$RUST_NM = Join-Path $RUSTC_BIN "llvm-nm.exe"

if (-not (Test-Path $RUST_LLD) -or -not (Test-Path $RUST_AR)) {
Write-Host "You must install the llvm-tools component: 'rustup component add llvm-tools'" -ForegroundColor Red
Write-Host "Could not find $RUST_LLD or $RUST_AR" -ForegroundColor Red
exit 1
}

$tmpdir = Join-Path $env:TEMP ([System.IO.Path]::GetRandomFileName())
New-Item -ItemType Directory -Path $tmpdir | Out-Null

function Cleanup {
if (Test-Path $tmpdir) {
Remove-Item -Recurse -Force $tmpdir
}
}

try {
$targetPath = Join-Path $SCRIPT_DIR "target\$profile\afl_libfuzzer_runtime.lib"
$outputPath = Join-Path $SCRIPT_DIR "libFuzzer.lib"

Write-Host "Creating intermediate object file '$tmpdir\libFuzzer.obj from $targetPath'" -ForegroundColor Green
& $RUST_LLD -flavor link /lib /nologo /out:"$tmpdir\libFuzzer.obj" "$targetPath"

if ($LASTEXITCODE -ne 0) {
throw "Failed to create intermediate object file"
}

Write-Host "Creating final library '$outputPath'" -ForegroundColor Green
& $RUST_AR crs "$outputPath" "$tmpdir\libFuzzer.obj"

if ($LASTEXITCODE -ne 0) {
throw "Failed to create final library"
}

Write-Host "Verifying symbols from '$outputPath'" -ForegroundColor Green
# Symbols that should be present:
# LLVMFuzzerRunDriver
& $RUST_NM "$outputPath" | Select-String "LLVMFuzzerRunDriver" | Out-Null

if ($LASTEXITCODE -ne 0) {
throw "Failed to verify symbols in final library"
}

Write-Host "Done! Wrote the runtime to '$outputPath'" -ForegroundColor Green

}
finally {
Cleanup
}
Loading