cargo-fuzz icon indicating copy to clipboard operation
cargo-fuzz copied to clipboard

Expose Environment Variables during Build

Open cwshugg opened this issue 4 months ago • 4 comments

Hi - this PR implements a way to expose environment variables during the build command that's executed during exec_build(). This is done with the aim to give dependencies the ability to detect a cargo-fuzz build versus a non-cargo-fuzz build.

I implemented this feature while doing work to get cargo-fuzz working on Windows to build and fuzz a DLL. Certain dependencies may need to use different built settings when being built for production versus for fuzzing. Exposing these environment variables at build-time allow build.rs scripts to detect cargo-fuzz builds.

Currently just two environment variables are exposed, but more could of course be added:

  • CARGO_FUZZ - A flag that's set to 1 when cargo-fuzz is performing a build. Useful for detecting cargo-fuzz without wanting any extra information.
  • CARGO_FUZZ_MANIFEST - Exposes the path to the cargo-fuzz Cargo.toml manifest that was used when cargo fuzz [build/run/etc.] was invoked. Useful in the event a user needs to determine which fuzzing project ran the command.

Use-Case Example

As I mentioned above, a user may need to modify the build flags in a fuzzing dependency, but only when the dependency is being built for fuzzing. A brief example of how this would work:

// build.rs

use std::env;

fn main()
{
    // ...
    if let Ok(_) = env::var("CARGO_FUZZ")
    {
        // we know this dependency is being built for fuzzing!
        println!("cargo:rustc-link-arg=CUSTOM_FUZZING_LINKER_ARG");
        println!("cargo:rustc-flags=CUSTOM_FUZZING_RUSTFLAGS");
        println!("cargo:rustc-cfg=my_experimental_feature=ENABLE");
    }
    // ...
}

cwshugg avatar Oct 07 '24 19:10 cwshugg