`black_box` for cargo fuzz

I am trying to use cargo fuzz run --sanitizer=memory ... to fuzz a function which performs invalid memory access. I don't really care about the result of the function call, I just want to check for invalid memory access.

The problem is that std::hint::black_box does not seem to have the desired effect for this, see `std::hint::black_box` does not work? · Issue #436 · rust-fuzz/cargo-fuzz · GitHub, whereas println! does work but I assume it causes quite some overhead.
Here is the example from that GitHub issue:

#![no_main]

use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    unsafe {
        let a = std::mem::MaybeUninit::<[usize; 4]>::uninit();
        let a = a.assume_init();
        std::hint::black_box(a[2]);
        // // This causes the memory error to be detected
        // println!("{}", a[2]);
    }
});

Are you aware of good alternatives for black_box in this case? I have tried using Copilot suggested alternatives such as writing the result to a AtomicUsize, but that does not seem to help either.

Or is this maybe not actually black_box vs. println!, and rather in both cases invalid memory access occurs but MemorySanitizer is not guaranteed to detect all cases (and somehow the different generated code makes a differences)?

Edit: For this simple example using cargo fuzz run ... --dev helps, but for the actual function I am trying to fuzz it does not seem to help. And using --strip-dead-code false causes an internal compilation error (as noted in cargo fuzz run --help).

1 Like