How to detect if building with address sanitizer when building with gcc 4.8?
Asked Answered
P

3

32

I'm working on a program written in C that I occasionally build with address sanitizer, basically to catch bugs. The program prints a banner in the logs when it starts up with info such as: who built it, the branch it was built on, compiler etc. I was thinking it would be nice to also spell out if the binary was built using address sanitizer. I know there's __has_feature(address_sanitizer), but that only works for clang. I tried the following simple program:

#include <stdio.h>

int main()
{
#if defined(__has_feature)
# if __has_feature(address_sanitizer)
    printf ("We has ASAN!\n");
# else
    printf ("We have has_feature, no ASAN!\n");
# endif
#else
    printf ("We got nothing!\n");
#endif

    return 0;
}

When building with gcc -Wall -g -fsanitize=address -o asan asan.c, this yields:

We got nothing!

With clang -Wall -g -fsanitize=address -o asan asan.c I get:

We has ASAN!

Is there a gcc equivalent to __has_feature?

I know there are ways to check, like the huge VSZ value for programs built with address sanitizer, just wondering if there's a compile-time define or something.

Poche answered 15/1, 2016 at 14:36 Comment(1)
Looks like there's a bug for it: gcc.gnu.org/bugzilla/show_bug.cgi?id=60512Snodgrass
A
31

From the GCC 4.8.0 manual:

__SANITIZE_ADDRESS__

This macro is defined, with value 1, when -fsanitize=address is in use.

Afore answered 15/1, 2016 at 15:39 Comment(3)
Thanks! One more question where RTFM helps :).Poche
For the most current version of g++, see gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html -- notice that we also have __SANITIZE_THREAD__ now.Honkytonk
See also this answer, which shows you how to determine such things for oneself, in a pickle.Melmela
M
2

You also can go with:

#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)

You may need to #include <sanitizer/asan_interface.h>.

Meshwork answered 30/5, 2023 at 6:41 Comment(1)
won't work with MS compiler.Vocalic
G
1

Note that GCC doesn't have __has_feature and clang doesn't set __SANITIZE_ADDRESS__.

So this should work for both clang and GCC:

#if defined(__has_feature)
#   if __has_feature(address_sanitizer) // for clang
#       define __SANITIZE_ADDRESS__ // GCC already sets this
#   endif
#endif

#if defined(__SANITIZE_ADDRESS__)
    // ASAN is enabled . . .
#endif
Gallows answered 7/5, 2024 at 19:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.