27

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.

fencekicker
  • 732
  • 1
  • 8
  • 18

2 Answers2

25

From the GCC 4.8.0 manual:

__SANITIZE_ADDRESS__

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

cremno
  • 4,672
  • 1
  • 16
  • 27
  • Thanks! One more question where RTFM helps :). – fencekicker Jan 18 '16 at 10:12
  • For the most current version of g++, see https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html -- notice that we also have `__SANITIZE_THREAD__` now. – Alexis Wilke Aug 16 '21 at 16:55
  • See also [this answer](https://stackoverflow.com/questions/57499943/how-to-detect-thread-sanitizer-for-gcc-5/57500218#57500218), which shows you how to determine such things for oneself, in a pickle. – jwd Jan 09 '22 at 00:31
2

You also can go with:

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

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

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Anna
  • 21
  • 2