Basic Fuzzing of Native Programs

Introduction to LibAFL

LibAFL is a modern, high-performance fuzzing framework written in Rust. Instead of being a single “one size fits all” tool like AFL++ or libFuzzer, it’s built as a set of reusable components (Rust crates) that you can mix and match.Because of that modular design, security researchers can assemble fuzzers that fit a specific target and workflow whether that means snapshot-based fuzzing, custom coverage or crash feedback, or even combining fuzzing with symbolic execution without needing to fork and heavily modify a huge C codebase.

https://github.com/AFLplusplus/LibAFL

Please follow below url for installing Dependencies for Libafl
https://github.com/AFLplusplus/LibAFL?tab=readme-ov-file#building-and-installing

Here is a high-level overview of how the architecture interacts:

Learn it hands-on
Android + iOS Userland Fuzzing & Exploitation
Go beyond the blog: master AFL++ and LibAFL fuzzing techniques end-to-end — from crash to working exploit on real Android ARM64 and iOS targets.
Explore the course →

What are the advantages of using LibAFL?

  • Extreme Customizability:You build your fuzzer out of blocks (fuzzer, Schedulers, Observers, Feedbacks). If you need a custom mutation strategy, you simply write a Rust function and plug it in. https://docs.rs/libafl/0.15.3/libafl/#modules
  • Speed:  Written in Rust with minimal overhead, allowing for execution speeds that often beat traditional C fuzzers.
  • Rust Safety: Fuzzer development is prone to bugs. Rust's memory safety guarantees eliminate a huge class of common errors when building custom fuzzing harnesses.
  • Multi-Platform / Multi-Architecture: Out-of-the-box support for Windows, Linux, Android, and macOS, alongside powerful dynamic binary instrumentation (DBI) backends like Frida and QEMU

What is LibAFL QEMU Mode?

LibAFL QEMU mode integrates the legendary QEMU emulation engine natively within LibAFL. Specifically, using QEMU User-Mode emulation, it allows you to run binaries compiled for a different architecture (e.g., AArch64 Android) directly on your host machine
The big win is speed and feedback: instead of launching a fresh QEMU process for every single test case (which is painfully slow), LibAFL keeps the emulator running and drives executions from within the fuzzing loop. Under the hood, QEMU’s dynamic translation engine (TCG) tracks which blocks/edges run, and LibAFL hooks that coverage directly into its observer maps so your fuzzer can make smart, coverage-guided decisions.

Overview

You’ll usually see three chunks in a LibAFL QEMU setup:

  • Target library (libfuzzkit.so): the thing you want to fuzz  
  • Harness(AArch64 ELF): calls into the library and exports `LLVMFuzzerTestOneInput`  
  • Host fuzzer (Rust, native on Linux): drives QEMU user‑mode + coverage feedback

The Target Library

For this blogpost , we will be fuzzing a custom library called libfuzzkit.so. Written in C++, this library parses structured Run-Length Encoded (RLE) payloads using the exposed function: 

cint process_blob(const uint8_t *data, size_t size);

A common issue in C++ data parsers are Heap Buffer Overflows. To demonstrate a successful fuzzer, our library contains an intentional classic vulnerability: when a specific sequence occurs, it allocates a fixed 4-byte buffer but copies up to 127 bytes into it without bounds checking. Because this is an Android target, we compile this library to a native AArch64 shared object (`.so`) using the Android NDK.
↓ Download libfuzzkit.sotarget library · AArch64 shared object

Creating the Harness

A "harness" is a small wrapper program that takes input from the fuzzer and feeds it to our target library function.
We will write a C harness (`harness.c`) that exposes the standard `LLVMFuzzerTestOneInput` function. LibAFL will dynamically locate this symbol and hook it.

c#include <stddef.h>
#include <stdint.h>
#include <signal.h>  

extern int process_blob(const uint8_t *data, size_t size);


__attribute__((visibility("default"), used, noinline))
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
process_blob(data, size);
return 0;
}


// Dummy main so the binary links into an executable

int main(void) {
const uint8_t dummy[] = {0};
LLVMFuzzerTestOneInput(dummy, sizeof(dummy));
return 0;
}

The fuzzer doesn't actually use `main` to loop. Instead, LibAFL will use QEMU to execute up to `LLVMFuzzerTestOneInput`, place a hook there, and repeatedly inject mutated inputs directly into guest memory!


  Build the harness

bashaarch64-linux-android31-clang -DLIBAFL_QEMU_HARNESS \
    $ASAN_FLAGS -rdynamic -L. -lfuzzkit \
    harness.c -o harness_aarch64

Implementing the Fuzzer, Step-by-Step

Here is structure of code 
host_fuzzer/src/main.rs    → small Linux-only entrypointhost_fuzzer/src/fuzzer_impl.rs → the real fuzzer logic
host_fuzzer/cargo.toml → crates and dependencies

The fuzzer entrypoint (main.rs): 

main.rs is intentionally minimal:

rust#[cfg(target_os = "linux")]
mod fuzzer_impl;

#[cfg(target_os = "linux")]
fn main() {
    env_logger::init();
    if let Err(e) = fuzzer_impl::run() {
        eprintln!("[!] Fatal: {e}");
        std::process::exit(1);
    }
}

#[cfg(not(target_os = "linux"))]
fn main() {
    eprintln!("libafl_qemu only works on Linux");
    std::process::exit(1);
}

This does two things:

  • ensures we only run this on Linux (QEMU backend expectation)
  • moves everything “interesting” into `fuzzer_impl.rs`

The real fuzzer: walking through `fuzzer_impl.rs`

This section follows the code structure in `fuzzer_impl.rs`. If you’re new to LibAFL, don’t worry about the names focus on the roles:

  • Observer = “what we measure”
  • Feedback = “how we decide an input is interesting”
  • Objective = “what we save as a special finding (crash/hang)”
  • Scheduler = “which input do we mutate next”
  • Stage = “how we mutate / execute”
  • Executor = “how we run the target”
  • Fuzzer = "Main Fuzzing Engine"

Standard Rust utilities

rustuse std::path::PathBuf;
use std::process;
use std::time::Duration;

  • PathBuf: a convenient, owned file path type (used for --seeds, --out, --target, etc.).
  • process: typically used for process::exit(1) on fatal errors.
  • Duration: used to set timeouts like Duration::from_millis(1000) for each fuzz iteration.

CLI parsing

rustuse clap::Parser;

This enables #[derive(Parser)] on a struct like Opts, so your fuzzer can accept flags like:

  • --target ./harness_aarch64
  • --seeds ./seeds
  • --out ./findings
  • --timeout-ms 1000

LibAFL core (the fuzzing framework “engine”)

rustuse libafl::{
    corpus::{Corpus, InMemoryOnDiskCorpus, OnDiskCorpus},
    events::SimpleEventManager,
    feedback_or, feedback_or_fast,
    feedbacks::{CrashFeedback, MaxMapFeedback, TimeFeedback, TimeoutFeedback},
    fuzzer::{Fuzzer, StdFuzzer},
    inputs::{BytesInput, HasTargetBytes},
    monitors::SimpleMonitor,
    mutators::{havoc_mutations, HavocScheduledMutator},
    observers::{CanTrack, HitcountsMapObserver, TimeObserver, VariableMapObserver},
    schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler},
    stages::StdMutationalStage,
    state::{HasCorpus, StdState},
    Error,
};

Think of this as: corpus + mutation + coverage feedback + scheduling + fuzz loop.
Corpus (where inputs are stored)

  • Corpus: trait for “a place to store testcases”.
  • InMemoryOnDiskCorpus: keeps metadata in RAM but stores actual inputs on disk (fast + persistent).
  • OnDiskCorpus: pure on-disk storage (commonly used for crashes/).

Events + monitor output
  • SimpleEventManager: handles communication between fuzzer components; for single-process fuzzing it’s the simplest option.
  • SimpleMonitor: prints stats (execs/sec, corpus size, crashes).

Inputs
  • BytesInput: the common “raw bytes” input type (like a file).
  • HasTargetBytes: a trait to access the bytes inside an input (so your harness can read them).

Observers (what you measure during execution)
  • VariableMapObserver: wraps a raw coverage map buffer (“edges map”).
  • HitcountsMapObserver: converts a raw bitmap into hitcount buckets (better feedback).
  • TimeObserver: measures execution time of each run.
  • CanTrack: allows tracking changed indices in a map (useful for minimization/scheduling).

Feedbacks (how you decide an input is “interesting”)
  • MaxMapFeedback: classic coverage feedback (“did this input increase coverage?”).
  • TimeFeedback: treats slower inputs as interesting (optional, helps explore deep paths).
  • CrashFeedback: marks crashes as objectives.
  • TimeoutFeedback: marks hangs/timeouts as objectives.
  • feedback_or / feedback_or_fast: combine feedbacks (e.g., coverage OR time; crash OR timeout).

Scheduling + stages + mutators
  • QueueScheduler: basic FIFO scheduling.
  • IndexesLenTimeMinimizerScheduler: wrapper that tends to prefer smaller/faster inputs when coverage is comparable (helps keep corpus efficient).
  • havoc_mutations: the standard mutation set (bit flips, byte flips, insert/delete, etc.).
  • HavocScheduledMutator: applies those mutations.
  • StdMutationalStage: a “stage” that mutates and executes inputs.

State + fuzzer wrapper
  • StdState: stores RNG, corpus, solutions, and feedback state.
  • HasCorpus: trait to access corpus from state.
  • StdFuzzer: a ready-made fuzzer pipeline built from scheduler + feedback + objective.
  • Fuzzer: trait implemented by fuzzers (so you can call fuzz_loop).
  • Error: LibAFL’s error type.

libafl_bolts (utility toolbox)

rustuse libafl_bolts::{
    current_nanos,
    ownedref::OwnedMutSlice,
    rands::StdRand,
    tuples::{tuple_list, MatchFirstType},
    AsSlice,
};

These are “support tools” used everywhere

  • current_nanos: used to seed RNG (StdRand::with_seed(current_nanos())).
  • OwnedMutSlice: wraps a raw pointer into a mutable slice safely-ish; used for coverage maps.
  • StdRand: LibAFL’s RNG (fast, deterministic when seeded).
  • tuple_list!: LibAFL uses type-level tuples for “lists” of observers/modules/stages.
  • MatchFirstType: helper when picking items out of these tuple lists.
  • AsSlice: trait used to view input bytes as &[u8].

libafl_qemu (the QEMU backend)

rustuse libafl_qemu::{
    elf::EasyElf,
    modules::{
        edges::EdgeCoverageFullVariant,
        utils::filters::{NopAddressFilter, NopPageFilter},
        EdgeCoverageModule, StdEdgeCoverageModule,
    },
    ArchExtras, Emulator, GuestAddr, GuestReg, MmapPerms, Qemu, QemuExecutor, QemuExitReason,
    Regs, TargetSignalHandling,
};

This is the part that makes “QEMU mode fuzzing” happen.
ELF symbol resolution

  • EasyElf: parses the target ELF so you can resolve symbols like LLVMFuzzerTestOneInput and compute addresses correctly (often with load base).

Coverage modules
  • EdgeCoverageModule / StdEdgeCoverageModule: QEMU-side coverage instrumentation that fills your edges map.
  • EdgeCoverageFullVariant: the “flavor” of edge coverage you’re using (full variant usually means richer coverage tracking).

Filters (optional optimization)
  • NopAddressFilter / NopPageFilter: “no filtering” filters (instrument everything).
  • Later you can swap these for real filters to ignore library code or reduce noise.

Core QEMU types
  • Emulator: constructs and configures the QEMU instance + modules.
  • Qemu: handle to the running QEMU engine (read/write memory, set breakpoints, run).
  • QemuExecutor: the LibAFL “executor” that bridges harness execution into LibAFL.
  • QemuExitReason: why execution stopped (breakpoint, crash, etc.).
  • TargetSignalHandling: how QEMU treats signals/crashes (e.g., return to harness).
  • Regs: register identifiers (PC/SP/LR/args depending on arch).
  • GuestAddr / GuestReg: types for guest addresses and registers.
  • MmapPerms: memory permissions for guest mappings (RWX).

Arch helpers
  • ArchExtras: architecture-specific conveniences (AArch64 calling conventions, etc.).

Bootstrapping QEMU and Finding Entry Points

First, we initialize the QEMU emulator with the correct arguments. Because we are fuzzing an Android binary, we must tell QEMU where to find the Android `rootfs` (the interpreter `linker64` and `libc.so`) and our target library.

rustlet mut qemu_args: Vec<String> = vec![program];

// -L specifies the sysroot containing the Android linker/libc

qemu_args.push("-L".to_string());
qemu_args.push("/path/to/android/rootfs".to_string());

// Inject ASAN_OPTIONS and LD_LIBRARY_PATH into the guest env
qemu_args.push("-E".to_string());
qemu_args.push("LD_LIBRARY_PATH=/path/to/our/libs,ASAN_OPTIONS=abort_on_error=1".to_string());

qemu_args.push(target_path);
let mut emulator = Emulator::empty()
.qemu_parameters(qemu_args)
.modules(tuple_list!(edge_coverage_module))
.build()?; 

let qemu: Qemu = emulator.qemu();

What's Happening:

  • "-L ": QEMU user-mode sysroot. For Android, this should point at your rootfs-like directory so QEMU can find the guest loader and libs.
  • "-E VAR=...": guest environment variables.
  •  "ASAN_OPTIONS=abort_on_error=1": if you’re using ASan in the guest, this makes ASan *_crash_* rather than exiting politely (polite exits are invisible to crash feedback).
  • final arg is the harness path (what QEMU should execute)

When debugging: print qemu_args and try running an equivalent command manually.

Resolving LLVMFuzzerTestOneInput

Next, we parse the loaded ELF to locate `LLVMFuzzerTestOneInput`. This is where we will inject our fuzzing data. We place a breakpoint at the function's return address so the emulator hands control back to LibAFL after every execution.

rustlet elf = EasyElf::from_file(&opts.target)?;

let target_func = elf.resolve_symbol("LLVMFuzzerTestOneInput", qemu.load_addr())?;

// A fast QEMU executor lets us set a breakpoint on the target function

Setting up edge coverage

rustlet mut edges_observer = unsafe {
    HitcountsMapObserver::new(VariableMapObserver::from_mut_slice(
        "edges",
        OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE),
        &raw mut MAX_EDGES_FOUND,
    ))
    .track_indices()
};
This line looks scary but conceptually it’s simple: “make an observer that watches the global edges map”.

  • edges_map_mut_ptr() points to a shared coverage map (from libafl_targets)
  • VariableMapObserver wraps a raw slice into an observer
  • HitcountsMapObserver turns raw hits into “hitcounts” (useful for feedback)
  • .track_indices() allows the scheduler to reason about which edges changed (helps minimization)
You can think of the edges map as “a giant bitmap of where we’ve been”.

Installing the EdgeCoverageModule

rustlet edge_coverage_module = StdEdgeCoverageModule::builder()
    .map_observer(edges_observer.as_mut())
    .build()?;
This is the QEMU side: it tells libafl_qemu, “when you translate/execute blocks, update _this_ observer’s map".
Then we build the emulator:
rustlet mut emulator = Emulator::empty()
    .qemu_parameters(qemu_args)
    .modules(tuple_list!(edge_coverage_module))
    .build()?;
  
let qemu: Qemu = emulator.qemu();

At this point:

  • QEMU is ready
  • the coverage module is installed
  • we can start poking the guest

Breakpoints: the “return-to-harness”

We do two important things:

  • stop when we reach LLVMFuzzerTestOneInput  
  • stop when it returns, so one “run” == one input

rustqemu.entry_break(start_pc);
unsafe { qemu.set_target_crash_handling(&TargetSignalHandling::ReturnToHarness) };  
let ret_addr: GuestAddr = qemu.read_return_address()?;
qemu.set_breakpoint(ret_addr);
Conceptually:
  • entry break gives QEMU a start stop-point
  • return address breakpoint gives QEMU an end stop-point
Now every fuzz iteration can be:
  • reset regs
  • set args
  • run until return breakpoint or crash

Mapping guest memory for inputs

Instead of allocating a new buffer each time, we map a fixed chunk once:

rustlet input_addr = qemu.map_private(0, MAX_INPUT_SIZE, MmapPerms::ReadWrite)?;

  • Then for each input, we overwrite that memory with new bytes.
  • This is fast and avoids fragmentation inside the guest.

Snapshotting registers (so each input starts clean)

rustlet saved_pc: GuestReg = qemu.read_reg(Regs::Pc)?;
let saved_sp: GuestAddr = qemu.read_reg(Regs::Sp)?;
let saved_ret: GuestAddr = qemu.read_return_address()?;
This is basically your “checkpoint”.  Before every run you restore PC/SP/LR (return address), then set function arguments.

The harness closure

rustlet mut harness = |_emu, _state, input: &BytesInput| {
    let target = input.target_bytes();
    let mut buf = target.as_slice();
    let mut len = buf.len();
    if len > MAX_INPUT_SIZE {
        buf = &buf[..MAX_INPUT_SIZE];
        len = MAX_INPUT_SIZE;
    }

    qemu.write_mem(input_addr, buf).expect("write guest memory");
    qemu.write_reg(Regs::Pc, saved_pc).expect("write PC");
    qemu.write_reg(Regs::Sp, saved_sp).expect("write SP");
    qemu.write_return_address(saved_ret).expect("write RA");
    qemu.write_function_argument(0, input_addr).expect("arg0");
    qemu.write_function_argument(1, len as GuestReg).expect("arg1");

    let exit_kind = unsafe {
        match qemu.run() {
            Ok(QemuExitReason::Breakpoint(_)) => ExitKind::Ok,
            Ok(QemuExitReason::Crash) => ExitKind::Crash,
            _ => ExitKind::Ok,
        }
    };
    exit_kind
};

This is the most important block in the whole fuzzer, because it’s where your mutated bytes become “guest execution”.

  • cap the input size (1 MiB) so you don’t write past the mapped buffer
  • write bytes to guest memory
  • restore execution context (PC/SP/RA)
  • set `arg0=data_ptr`, `arg1=size` following the guest ABI
  • run QEMU until:
  •   we hit the return breakpoint → OK
  •   we crash → Crash
  •   anything else → treat as OK (you can refine this later)

If your fuzzing loop “doesn’t do anything”, this is the first place I look:
  • are we writing input to the right place?
  • are we setting PC correctly?
  • are we actually stopping at the right return address?

Feedback vs Objective (coverage vs “findings”)

rustlet time_observer = TimeObserver::new("time");
let map_feedback = MaxMapFeedback::new(&edges_observer);
let mut feedback = feedback_or!(map_feedback, TimeFeedback::new(&time_observer));
let mut objective = feedback_or_fast!(CrashFeedback::new(), TimeoutFeedback::new());

Feedback decides what goes into the evolving corpus. Objective decides what’s “special”.

  • MaxMapFeedback: “did this input increase any edge hitcount?”
  • TimeFeedback: optional secondary signal (useful for slow paths)
  • CrashFeedback: “did the executor return ExitKind::Crash?”
  • TimeoutFeedback: “did we exceed the per-run timeout?”

State + corpus

rustlet mut state = StdState::new(
    StdRand::with_seed(current_nanos()),
    InMemoryOnDiskCorpus::<BytesInput>::no_meta(&corpus_dir)?,
    OnDiskCorpus::new(&crashes_dir)?,
    &mut feedback,
    &mut objective,
)?;

This setup is a pragmatic middle ground:

  • keep hot corpus metadata in memory
  • store testcases on disk (so you don’t lose them)
  • store crashes on disk as a separate corpus

Executor: the QEMU bridge into LibAFL

rustlet mut executor = QemuExecutor::new(
    emulator,
    &mut harness,
    tuple_list!(edges_observer, time_observer),
    &mut fuzzer,
    &mut state,
    &mut mgr,
    timeout,
)?;

The executor:

  • calls your harness closure each run
  • updates observers (edges/time)
  • reports `ExitKind` (Ok/Crash/Timeout)
  • integrates with the event manager for progress reporting

Mutation stage: “havoc” is the classic starter

rustlet mutator = HavocScheduledMutator::new(havoc_mutations());
let mut stages = tuple_list!(StdMutationalStage::new(mutator));

Havoc mutations are a good baseline:

  • bit flips
  • byte flips
  • insert/delete
  • interesting values
Once your loop is stable, you can layer structured mutations, dictionary mutations, cmp-log, etc.

Fuzz loop: the part that’s almost boring (in a good way)

rustfuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)?;

If everything above is correct, this should:

  • keep running
  • grow the corpus when new coverage appears
  • save crashes/timeouts into the findings directory

fuzzer_impl.rs

rustuse std::path::PathBuf;
use std::process;
use std::time::Duration;

use clap::Parser;

use libafl::{
    corpus::{Corpus, InMemoryOnDiskCorpus, OnDiskCorpus},
    events::SimpleEventManager,
    feedback_or, feedback_or_fast,
    feedbacks::{CrashFeedback, MaxMapFeedback, TimeFeedback, TimeoutFeedback},
    fuzzer::{Fuzzer, StdFuzzer},
    inputs::{BytesInput, HasTargetBytes},
    monitors::SimpleMonitor,
    mutators::{havoc_mutations, HavocScheduledMutator},
    observers::{CanTrack, HitcountsMapObserver, TimeObserver, VariableMapObserver},
    schedulers::{IndexesLenTimeMinimizerScheduler, QueueScheduler},
    stages::StdMutationalStage,
    state::{HasCorpus, StdState},
    Error,
};

use libafl_bolts::{
    current_nanos,
    ownedref::OwnedMutSlice,
    rands::StdRand,
    tuples::{tuple_list, MatchFirstType},
    AsSlice,
};

use libafl_qemu::{
    elf::EasyElf,
    modules::{
        edges::EdgeCoverageFullVariant,
        utils::filters::{NopAddressFilter, NopPageFilter},
        EdgeCoverageModule, StdEdgeCoverageModule,
    },
    ArchExtras, Emulator, GuestAddr, GuestReg, MmapPerms, Qemu, QemuExecutor, QemuExitReason,
    Regs, TargetSignalHandling,
};

use libafl_targets::{edges_map_mut_ptr, EDGES_MAP_DEFAULT_SIZE, MAX_EDGES_FOUND};

/// Maximum input size the fuzzer will write into guest memory.
const MAX_INPUT_SIZE: usize = 1_048_576; // 1 MiB

// ── CLI ──────────────────────────────────────────────────────────────
#[derive(Parser, Debug)]
#[command(name = "host_fuzzer", about = "LibAFL QEMU-mode fuzzer for AArch64")]
struct Opts {
    
    #[arg(long)]
    target: PathBuf,

    /// Seed corpus directory.
    #[arg(long, default_value = "../seeds")]
    seeds: PathBuf,

    /// Output directory for corpus / crashes / hangs.
    #[arg(long, default_value = "../findings")]
    out: PathBuf,

   
    #[arg(long, default_value = "1000")]
    timeout_ms: u64,

    /// QEMU_LD_PREFIX (sysroot) for Android dynamic linking.
    /// For Android targets, this should point to the rootfs.
    #[arg(long)]
    ld_prefix: Option<PathBuf>,

    /// Directory containing libfuzzkit.so (passed as LD_LIBRARY_PATH to QEMU guest).
    #[arg(long)]
    lib_dir: Option<PathBuf>,
}

// ── ENTRY ────────────────────────────────────────────────────────────
pub fn run() -> Result<(), Error> {
    let opts = Opts::parse();

    // Validate target exists
    if !opts.target.exists() {
        return Err(Error::illegal_argument(format!(
            "Target binary not found: {:?}",
            opts.target
        )));
    }

    // Create output directories
    let corpus_dir = opts.out.join("corpus");
    let crashes_dir = opts.out.join("crashes");
    std::fs::create_dir_all(&corpus_dir).map_err(|e| Error::unknown(format!("{e}")))?;
    std::fs::create_dir_all(&crashes_dir).map_err(|e| Error::unknown(format!("{e}")))?;

    // ── Build QEMU command line ──
    //
    // libafl_qemu's Emulator takes args much like qemu-user would.
    // argv[0] = our program name, then the target + its args.
    let program = std::env::args()
        .next()
        .unwrap_or_else(|| "host_fuzzer".to_string());

    let mut qemu_args: Vec<String> = vec![program];

    // Sysroot for Android dynamic linking (linker64, libc.so, etc.)
    if let Some(ref ld) = opts.ld_prefix {
        qemu_args.push("-L".to_string());
        qemu_args.push(ld.display().to_string());
    }

    // Set LD_LIBRARY_PATH in the guest environment so the Android linker
    // can find libfuzzkit.so (and any other shared libs beside the harness).
    if let Some(ref lib_dir) = opts.lib_dir {
        qemu_args.push("-E".to_string());
        qemu_args.push(format!("LD_LIBRARY_PATH={}", lib_dir.display()));
    }

    // Crucial for ASan: make it abort (SIGABRT) on memory errors instead of calling
    // exit(1), so that LibAFL intercepts the crash signal and logs a finding.
    qemu_args.push("-E".to_string());
    qemu_args.push("ASAN_OPTIONS=abort_on_error=1".to_string());

    qemu_args.push(opts.target.display().to_string());

    log::info!("QEMU args: {:?}", qemu_args);

    // ── Build the edge-coverage observer ──
    let mut edges_observer = unsafe {
        HitcountsMapObserver::new(VariableMapObserver::from_mut_slice(
            "edges",
            OwnedMutSlice::from_raw_parts_mut(edges_map_mut_ptr(), EDGES_MAP_DEFAULT_SIZE),
            &raw mut MAX_EDGES_FOUND,
        ))
        .track_indices()
    };

    // ── Build the EdgeCoverageModule and Emulator ──
    let edge_coverage_module = StdEdgeCoverageModule::builder()
        .map_observer(edges_observer.as_mut())
        .build()?;

    let mut emulator = Emulator::empty()
        .qemu_parameters(qemu_args)
        .modules(tuple_list!(edge_coverage_module))
        .build()?;

    let qemu: Qemu = emulator.qemu();

    // ── Resolve LLVMFuzzerTestOneInput in the target ELF ──
    let mut elf_buffer = Vec::new();
    let elf = EasyElf::from_file(qemu.binary_path(), &mut elf_buffer)?;
    let load_addr = qemu.load_addr();

    let start_pc = elf
        .resolve_symbol("LLVMFuzzerTestOneInput", load_addr)
        .ok_or_else(|| {
            Error::empty_optional("Symbol 'LLVMFuzzerTestOneInput' not found in target ELF")
        })?;
    log::info!("LLVMFuzzerTestOneInput @ {start_pc:#x}");

    // Run the target until it reaches LLVMFuzzerTestOneInput
    qemu.entry_break(start_pc);

    // Enable crash detection: guest SIGSEGVs will be returned as
    // QemuExitReason::Crash instead of killing the host process.
    unsafe { qemu.set_target_crash_handling(&TargetSignalHandling::ReturnToHarness) };

    // Read the return address (set up by the caller / _start → main → LFTOI)
    let ret_addr: GuestAddr = qemu
        .read_return_address()
        .map_err(|e| Error::unknown(format!("Failed to read return address: {e:?}")))?;
    log::info!("Return address = {ret_addr:#x}");
    qemu.set_breakpoint(ret_addr);

    // Allocate a guest-memory buffer for fuzzing input
    let input_addr = qemu
        .map_private(0, MAX_INPUT_SIZE, MmapPerms::ReadWrite)
        .map_err(|e| Error::unknown(format!("Failed to mmap guest input buffer: {e}")))?;
    log::info!("Guest input buffer @ {input_addr:#x}");

    // Snapshot register state
    let saved_pc: GuestReg = qemu
        .read_reg(Regs::Pc)
        .map_err(|e| Error::unknown(format!("Failed to read PC: {e:?}")))?;
    let saved_sp: GuestAddr = qemu
        .read_reg(Regs::Sp)
        .map_err(|e| Error::unknown(format!("Failed to read SP: {e:?}")))?;
    let saved_ret: GuestAddr = qemu
        .read_return_address()
        .map_err(|e| Error::unknown(format!("Failed to read RA: {e:?}")))?;

    // Note: EdgeCoverageModule uses NopAddressFilter (covers all addresses).
    // For a small target like ours, full coverage is fine.
    if let Ok(range) = elf
        .get_section(".text", qemu.load_addr())
        .ok_or_else(|| Error::key_not_found(".text"))
    {
        log::info!(".text range: {:#x?}", range);
    }

    // ── Harness closure ──
    //
    // Called by QemuExecutor for every input. Writes fuzz data into guest
    // memory, sets up registers, and runs until the breakpoint at ret_addr.
    let mut harness = |_emu: &mut Emulator<_, _, _, _, _, _, _>,
                       _state: &mut _,
                       input: &BytesInput| {
        let target = input.target_bytes();
        let mut buf = target.as_slice();
        let mut len = buf.len();
        if len > MAX_INPUT_SIZE {
            buf = &buf[..MAX_INPUT_SIZE];
            len = MAX_INPUT_SIZE;
        }
        let len = len as GuestReg;

        // Write input to guest memory
        qemu.write_mem(input_addr, buf)
            .expect("write guest memory");

        // Restore registers
        qemu.write_reg(Regs::Pc, saved_pc).expect("write PC");
        qemu.write_reg(Regs::Sp, saved_sp).expect("write SP");
        qemu.write_return_address(saved_ret)
            .expect("write RA");

        // Set function arguments: arg0 = data ptr, arg1 = size
        qemu.write_function_argument(0, input_addr)
            .expect("write arg0");
        qemu.write_function_argument(1, len)
            .expect("write arg1");

        // Run until breakpoint at ret_addr (or crash/timeout)
        let exit_kind = unsafe {
            match qemu.run() {
                Ok(QemuExitReason::Breakpoint(_)) => libafl::executors::ExitKind::Ok,
                Ok(QemuExitReason::Crash) => libafl::executors::ExitKind::Crash,
                _ => libafl::executors::ExitKind::Ok,
            }
        };
        exit_kind
    };

    // ── Feedback / objectives ──
    let time_observer = TimeObserver::new("time");
    let map_feedback = MaxMapFeedback::new(&edges_observer);

    let mut feedback = feedback_or!(map_feedback, TimeFeedback::new(&time_observer));

    let mut objective =
        feedback_or_fast!(CrashFeedback::new(), TimeoutFeedback::new());

    // ── State ──
    let mut state = StdState::new(
        StdRand::with_seed(current_nanos()),
        InMemoryOnDiskCorpus::<BytesInput>::no_meta(&corpus_dir)?,
        OnDiskCorpus::new(&crashes_dir)?,
        &mut feedback,
        &mut objective,
    )?;

    // ── Monitor + event manager ──
    let monitor = SimpleMonitor::new(|s| {
        println!("{s}");
    });
    let mut mgr = SimpleEventManager::new(monitor);

    // ── Scheduler ──
    let scheduler = IndexesLenTimeMinimizerScheduler::new(
        &edges_observer,
        QueueScheduler::new(),
    );

    // ── Fuzzer ──
    let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);

    // ── Executor ──
    let timeout = Duration::from_millis(opts.timeout_ms);
    let mut executor = QemuExecutor::new(
        emulator,
        &mut harness,
        tuple_list!(edges_observer, time_observer),
        &mut fuzzer,
        &mut state,
        &mut mgr,
        timeout,
    )?;

    // ── Load initial corpus ──
    if state.must_load_initial_inputs() {
        state
            .load_initial_inputs(&mut fuzzer, &mut executor, &mut mgr, &[opts.seeds.clone()])
            .unwrap_or_else(|e| {
                eprintln!("Failed to load initial corpus from {:?}: {e}", opts.seeds);
                process::exit(1);
            });
        println!(
            "[*] Imported {} inputs from {:?}",
            state.corpus().count(),
            opts.seeds
        );
    }

    // ── Mutation stage ──
    let mutator = HavocScheduledMutator::new(havoc_mutations());
    let mut stages = tuple_list!(StdMutationalStage::new(mutator));

    // ── Fuzz forever ──
    println!("[*] Starting fuzzing loop…");
    fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)?;

    Ok(())
}

Cargo.toml: Crates and Dependencies 

toml[package]
name = "host_fuzzer"
version = "0.1.0"

[features]
default = ["aarch64"]
# Architecture feature — must match target arch (aarch64 for Android ARM64).
aarch64 = ["libafl_qemu/aarch64"]

[profile.release]
lto = true
codegen-units = 1
opt-level = 3
debug = true

[dependencies]
clap = { version = "4.5", features = ["derive"] }
env_logger = "0.11"
log = { version = "0.4", features = ["release_max_level_info"] }

# Use local LibAFL path dependencies.
# These paths are relative to this Cargo.toml and assume the LibAFL repo
libafl = { path = "../../Research/Libafl/LibAFL/crates/libafl" }
libafl_bolts = { path = "../../Research/Libafl/LibAFL/crates/libafl_bolts", features = ["errors_backtrace"] }
libafl_qemu = { path = "../../Research/Libafl/LibAFL/crates/libafl_qemu", features = ["usermode"] }
libafl_targets = { path = "../../Research/Libafl/LibAFL/crates/libafl_targets" }

In Cargo.toml, the Crates and Dependencies section defines the core building blocks used by the fuzzer. clap (with the derive feature) is used to create a clean command-line interface for options like target path, corpus directories, and timeouts. log and env_logger provide lightweight logging so you can enable useful runtime output with RUST_LOG=info without hardcoding print statements. The main fuzzing logic comes from libafl, which provides the framework pieces like corpus management, schedulers, mutators, observers, feedback, and the fuzz loop itself. libafl_bolts adds shared utilities (randomness, tuple helpers, safe-ish map wrappers, and better backtraces via errors_backtrace) that LibAFL uses across components. libafl_qemu (enabled with usermode) is the key dependency that embeds QEMU user-mode emulation into LibAFL so the fuzzer can execute foreign-architecture binaries while collecting coverage. Finally, libafl_targets provides the standard shared coverage map layouts and target-side helpers that integrate neatly with LibAFL’s observers and feedback system.

Build the fuzzer

bashcd ~/libafl_qemu_fuzz/host_fuzzer
cargo build --release --features aarch64

After the fuzzer builds successfully, you’ll find the compiled binary in your project’s target/release/ directory

Run the Fuzzer

Before running the fuzzer, we need to copy the custom library that the harness depends on, because it isn’t included in the root filesystem. In my case, I created a target/build directory inside the project and copied the required files there.

bash./host_fuzzer/target/release/host_fuzzer \
    --target target/build/harness_aarch64 \
    --seeds seeds \
    --out output \
    --timeout-ms 1000 \
    --ld-prefix /home/mhl/Desktop/samsungs25/rootfs \
    --lib-dir target/build

After some time, our fuzzer discovered about 36 objectives.

Analyse Crashes

To analyze the crash properly, we need to rebuild the harness with a couple of changes: make it read the input file path from a command-line argument, and compile it with AddressSanitizer enabled.

c#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

/* Provided by libfuzzkit */
extern int process_blob(const uint8_t *data, size_t size);

int main(int argc, char **argv) {
  if (argc < 2) {
    fprintf(stderr, "usage: %s <input-file>\n", argv[0]);
    return 1;
  }

  FILE *f = fopen(argv[1], "rb");
  if (!f)
    return 1;

  fseek(f, 0, SEEK_END);
  long len = ftell(f);
  if (len <= 0) {
    fclose(f);
    return 1;
  }
  fseek(f, 0, SEEK_SET);

  uint8_t *buf = (uint8_t *)malloc((size_t)len);
  if (!buf) {
    fclose(f);
    return 1;
  }

  size_t n = fread(buf, 1, (size_t)len, f);
  fclose(f);

  int rc = process_blob(buf, n);
  free(buf);
  return rc;
}
bashaarch64-linux-android31-clang -fsanitize=address -DLIBAFL_QEMU_HARNESS \
    $ASAN_FLAGS -rdynamic -L. -lfuzzkit \
    harness.c -o harness_file

Now we’ll run the harness under QEMU user-mode to emulate the AArch64 binary and reproduce/check all the crashes.

bashexport QEMU_LD_PREFIX=/home/mhl/Desktop/samsungs25/rootfs/
export QEMU_SET_ENV="LD_LIBRARY_PATH=/home/mhl/libafl_qemu_fuzz/target/build,ASAN_OPTIONS=abort_on_error=1"
qemu-aarch64 ~/libafl_qemu_fuzz/target/build/harness_file <crashfile>
bashqemu-aarch64 ~/libafl_qemu_fuzz/target/build/harness_file ~/libafl_qemu_fuzz/output/crashes/411b9e6f2b455413

After reviewing the crashes one by one, we found a few real, reproducible crashes that actually hit the target vulnerability in our custom library.


Conclusion

In this blog post, we built a simple and practical workflow for fuzzing AArch64 Android binaries using LibAFL in QEMU user-mode. We started by understanding how LibAFL works with its modular design and how QEMU helps us run binaries from a different architecture while still getting useful coverage feedback. Then we brought everything together—writing a basic harness, targeting a custom native library, and connecting the core LibAFL components that make the fuzzing loop run.
After getting the fuzzer running, we focused on what really matters: analyzing the results. By going through the objectives and replaying crashes using the harness, we were able to verify and better understand the issues we found. This gives us a complete, end-to-end setup—from taking an Android .so file to actually finding and confirming crashes—without needing to run a full Android system.
In the next blog post, we’ll go one step further by fuzzing a real-world Android library using LibAFL in Frida mode, where we can work directly with live processes and explore deeper, more realistic execution paths.

Go further — full chain, hands-on
This post is one slice of our fuzzing-to-exploit curriculum. Learn the complete chain in these courses:

  • Android Userland Fuzzing and Exploitation — AFL++/LibAFL on ARM64, real targets all the way to a working RCE PoC.
  • Android Kernel Fuzzing and Exploitation — Syzkaller-driven kernel fuzzing, userland to ring 0.
  • Advanced Android Hacking — Road to Pwn2Own — chain AppSec bugs into remote code execution.
Limited-time bundle — 67% off
Get Android + iOS Userland Fuzzing & Exploitation together for €1,500 (was €4,574 — save €3,074) with code EARLY67. Offer ends Sunday 8 November, 23:59 CET.
Claim the bundle deal →