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 all 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
11 changes: 11 additions & 0 deletions .github/workflows/build_and_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ jobs:
- ./fuzzers/inprocess/libfuzzer_stb_image
# - ./fuzzers/structure_aware/libfuzzer_stb_image_concolic
# - ./fuzzers/inprocess/sqlite_centralized_multi_machine
# - ./fuzzers/inprocess/libafl_libfuzzer_windows

# Fuzz Anything
- ./fuzzers/fuzz_anything/push_harness
Expand Down Expand Up @@ -522,6 +523,16 @@ jobs:
- name: Build fuzzers/binary_only/frida_libpng
run: cd fuzzers/binary_only/frida_libpng/ && just test

windows-libafl-libfuzzer:
runs-on: windows-latest
needs:
- common
steps:
- uses: actions/checkout@v4
- uses: ./.github/workflows/windows-tester-prepare
- name: Build fuzzers/inprocess/libafl_libfuzzer_windows
run: cd fuzzers/inprocess/libafl_libfuzzer_windows && just test

windows-libfuzzer-stb-image:
runs-on: windows-latest
needs:
Expand Down
2 changes: 1 addition & 1 deletion fuzzers/binary_only/frida_libpng/Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ lib2: libpng

[windows]
harness: lib lib2
copy libpng-1.6.37\Release\libpng16.lib . && copy libpng-1.6.37\Release\libpng16.dll . && copy zlib\Release\zlib.lib . && copy zlib\Release\zlib.dll . && copy target\release\frida_fuzzer.exe .
copy libpng-1.6.37\Release\libpng16.lib . && copy libpng-1.6.37\Release\libpng16.dll . && copy zlib\Release\zlib.lib . && copy zlib\Release\zlib.dll .
cl /O2 /c /I .\libpng-1.6.37 harness.cc /Fo:harness.obj && link /DLL /OUT:libpng-harness.dll harness.obj libpng16.lib zlib.lib

[unix]
Expand Down
30 changes: 30 additions & 0 deletions fuzzers/inprocess/libafl_libfuzzer_windows/Justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import "../../../just/libafl.just"

FUZZER_NAME := "libafl_libfuzzer_windows"
FUZZER_NAME_WIN := "libafl_libfuzzer_windows.exe"

set windows-shell := ['cmd.exe', '/c']
set unstable

[windows]
libafl_libfuzzer:
powershell -File ..\..\..\libafl_libfuzzer_runtime\build.ps1

[windows]
harness: libafl_libfuzzer
copy ..\..\..\libafl_libfuzzer_runtime\libFuzzer.lib .
cl /c /O2 /EHsc /std:c++17 /MDd /fsanitize-coverage=inline-8bit-counters /fsanitize-coverage=edge /fsanitize-coverage=trace-cmp /fsanitize-coverage=trace-div /Fo:harness.obj harness.cc
link harness.obj libFuzzer.lib sancov.lib /OUT:libafl_libfuzzer_windows.exe

[windows]
run: harness
if not exist corpus mkdir corpus
{{FUZZER_NAME_WIN}} -use_value_profile=1 corpus

[windows]
[script("cmd.exe", "/c")]
test: harness
if exist corpus rd /s /q corpus
mkdir corpus
{{FUZZER_NAME_WIN}} -use_value_profile=1 -runs=30000 corpus
dir /a-d corpus && (echo Files exist) || (exit /b 1337)
4 changes: 4 additions & 0 deletions fuzzers/inprocess/libafl_libfuzzer_windows/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# LibAFL-LibFuzzer Windows

A simple example demonstrating how to build LibFuzzer harnesses with LibAFL-LibFuzzer
as an alternative runtime on Windows.
33 changes: 33 additions & 0 deletions fuzzers/inprocess/libafl_libfuzzer_windows/harness.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Simple decoder function with an off by one error that is triggered under
// certain conditions.

#include <cstddef>
#include <cstdint>

int DecodeInput(const uint8_t *data, size_t size) {
if (size < 5) {
return -1; // Error: not enough data
}

if (data[0] != 'F' || data[1] != 'U' || data[2] != 'Z' || data[3] == 'Z') {
return -1; // Error: invalid header
}

if (data[4] <= 0) {
return -1; // Error: invalid size
}

int csum = 0;

for (size_t i = 5; i < size; ++i) {
csum += data[i];
}

return csum; // Error: checksum mismatch
}

extern "C" __declspec(dllexport) int LLVMFuzzerTestOneInput(const uint8_t *data,
size_t size) {
DecodeInput(data, size);
return 0;
}
35 changes: 24 additions & 11 deletions libafl_libfuzzer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,22 +86,35 @@ To do so, [ensure a recent nightly version of Rust is installed](https://rustup.
[`libafl_libfuzzer_runtime`](../libafl_libfuzzer_runtime) folder and build the runtime with the following command:

```bash
./build.sh
just build
```

The static library will be available at `libFuzzer.a` in the [`libafl_libfuzzer_runtime`](../libafl_libfuzzer_runtime)
directory.
If you encounter build failures without clear error outputs that help you resolve the issue, please [submit an issue].
Or you can call `build.sh` (Unix) or `build.ps1` (Windows).

This library may now be used in place of libFuzzer.
To do so, change your CFLAGS/CXXFLAGS from `-fsanitize=fuzzer` to:
The static library will be available at `libFuzzer.a` (`libFuzzer.lib` for Windows) in
the [`libafl_libfuzzer_runtime`](../libafl_libfuzzer_runtime) directory. If you
encounter build failures without clear error outputs that help you resolve the issue,
please [submit an issue].

```
-fsanitize=fuzzer-no-link -L/path/to/libafl_libfuzzer_runtime -lFuzzer
```
#### Unix

This library may now be used in place of libFuzzer. To do so, change your
CFLAGS/CXXFLAGS from `-fsanitize=fuzzer` to:

``` -fsanitize=fuzzer-no-link -L/path/to/libafl_libfuzzer_runtime -lFuzzer ```

Alternatively, you may directly overwrite the system libFuzzer library and use
`-fsanitize=fuzzer` as normal. This changes per system, but on my machine is located at
`/usr/lib64/clang/16/lib/linux/libclang_rt.fuzzer-x86_64.a`.

#### Windows

For Windows, change your CFLAGS/CXXFLAGS from `-fsanitize=fuzzer` to:

```/fsanitize-coverage=inline-8bit-counters /fsanitize-coverage=edge /fsanitize-coverage=trace-cmp /fsanitize-coverage=trace-div```

Alternatively, you may directly overwrite the system libFuzzer library and use `-fsanitize=fuzzer` as normal.
This changes per system, but on my machine is located at `/usr/lib64/clang/16/lib/linux/libclang_rt.fuzzer-x86_64.a`.
And then ensure you link with `sancov.lib` when producing your final executable. See
`fuzzers\inprocess\libafl_libfuzzer_windows` for an example.

#### Caveats

Expand Down
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
113 changes: 73 additions & 40 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 @@ -87,10 +100,17 @@ where
return Err(Error::shutting_down());
}
}
fuzzer.fuzz_loop(stages, executor, state, mgr)?;
if options.runs() == 0 {
fuzzer.fuzz_loop(stages, executor, state, mgr)?;
} else {
for _ in 0..options.runs() {
fuzzer.fuzz_one(stages, executor, state, mgr)?;
}
}
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 +141,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 +152,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 +215,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);
}
} else if options.tui() {

// 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);
}

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)
})
}
Loading
Loading