How can I know if Leak Sanitizer is enabled at compile time?

点点圈 提交于 2019-12-23 15:51:06

问题


The GCC and Clang compilers both have support for LeakSanitizer which helps finding memory leaks in C programs. Sometimes a memory leak is unavoidable (because it is being tested in a test suite for example).

Such memory can be annotated using the Leak Sanitizer interface:

#include <sanitizer/lsan_interface.h>

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

This will however break on compilers that do not support LSan. In Address Sanitizer, this construct can be used to detect the availablity of 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

There is no __has_feature(leak_sanitizer) to detect just the existence of LSan in Clang and neither does __SANITIZE_LEAKS__ exist for GCC. How can I detect ASAN availability anyway? Note that LSan can be enabled independently of AddressSanitizer and ThreadSanitizer.


回答1:


As the compiler does not set a preprocessor define for itself one have to do that for himself.

One compile with -fsanitize=leak -DMYLEAKSAN=1 with LeakSanitizer or without LeakSanitizer one compile with -DMYLEAKSAN=0. If one does forget to define MYLEAKSAN the compiler is halted.

#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
}


来源:https://stackoverflow.com/questions/31273016/how-can-i-know-if-leak-sanitizer-is-enabled-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!