How can I tell if the Sanitizer leak is enabled at compile time?

The GCC and Clang compilers support LeakSanitizer to help you find memory leaks in C programs. Sometimes a memory leak is inevitable (because it is being tested, for example, on a test suite).

Such memory can be annotated using the Leak Sanitizer interface :

#include <sanitizer/lsan_interface.h>

void *p = create_new_object();
__lsan_ignore_object(p);

      

However, this will crash compilers that do not support LSan. In the Address Sanitizer, this construct can be used to detect the availability of an ASAN:

/* __has_feature(address_sanitizer) is used later for Clang, this is for
 * compatibility with other compilers (such as GCC and MSVC) */
#ifndef __has_feature
#   define __has_feature(x) 0
#endif

#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
    /* ASAN-aware code here. */
#endif

      

No __has_feature(leak_sanitizer)

, to discover only the existence of LSan in Clang, and for CCC does not exist __SANITIZE_LEAKS__

. How can I detect if ASAN is available anyway? Note that LSan can be enabled independently of AddressSanitizer and ThreadSanitizer.

+3


source to share


1 answer


Since the compiler does not define the preprocessor for itself, you need to do it for yourself.

Compile with -fsanitize=leak -DMYLEAKSAN=1

LeakSanitizer or without LeakSanitizer, compile with -DMYLEAKSAN=0

. If you forget to define MYLEAKSAN

, the compiler has stopped.



#ifndef MYLEAKSAN
#   error: MYLEAKSAN must be either 0 or 1
#endif
#include <stdio.h>
#include <stdlib.h>
#if MYLEAKSAN
#   include <sanitizer/lsan_interface.h>
#endif

int main(void)
{
    void *p = malloc(5);
#if MYLEAKSAN
    __lsan_ignore_object(p);
#endif
}

      

+3


source







All Articles