Sanitizers in Mixed Rust and C Code

I have a binary, that contains Rust and C Code and is built using Cargo. In the debug build I want to enable ASAN, especially for the C code. At the moment I do not have any unsafe Rust code, so I do not care that much about instrumenting the Rust code.

How would you do that? I see two ways to do this:

  1. via RUSTFLAGS:
    I can set RUSTFLAGS="-Z sanitizer=address" manually when building with Cargo, but then I have to detect this in the build.rs and set the -fsanitize=address accordingly. I do not know how to achieve this.

  2. only in the C code:
    I can set -fsanitize=address for all C files, and skip the rust code. Then I would need to pass a flag to the linker. How would I do that in the build.rs?

cc @Shnatsel

Here's a recipe: https://github.com/rust-lang/rust/issues/39610#issuecomment-573391197

Replace memory with address and you should be good to go.

2 Likes

That sounds perfect. Something on my system is wrong with the crate serde_derive:

error: /home/.../target/debug/deps/libserde_derive-3efc794075ed84d6.so: undefined symbol: __asan_option_detect_stack_use_after_return

Do you know what the reason for this could be? Maybe my clang version does not match Rust's?

I tried it with this command:

CC=clang CFLAGS=-fsanitize=address RUSTFLAGS="-Zsanitizer=address -Clink-arg=-fuse-ld=lld" cargo +nightly build

Throw in an explicit --target specification so that proc macros would not be sanitized.

e.g. --target=x86_64-unknown-linux-gnu for me on Linux

1 Like