Search code examples
cmakeaddress-sanitizer

How to set ASAN_OPTIONS environment variable in CMake?


As far as I understand, to use ASAN_OPTIONS with clang, the ASAN_OPTIONS environment variable must be set before compiling.

How can I do this within a CMake script without adding a wrapper script?

I need to disable ODR Violation checking for one particular test project only when compiled with clang. So in the CMakeLists.txt file I have:

if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
  # Clange reports ODR Violation errors in mbedtls/library/certs.c.  Need to disable this check.
  set(ENV{ASAN_OPTIONS} detect_odr_violation=0)
endif()

But after running cmake, if I enter echo $ASAN_OPTIONS, it is not set.

After running cmake, if I enter:

export ASAN_OPTIONS=detect_odr_violation=0
make

everything is all good.

Is it possible for cmake to set an environment variable so it persists after cmake runs? Sorry my understanding of environments is limited!


Solution

  • As far as I understand, to use ASAN_OPTIONS with clang, the ASAN_OPTIONS environment variable must be set before compiling.

    Not really, ASAN_OPTIONS does not influence compilation in any way. Instead it controls behavior of compiled code so needs to be set (and exported) before running your test.

    In your case it would be easier to use a different control mechanism: __asan_default_options callback:

    #ifndef __has_feature
    // GCC does not have __has_feature...
    #define __has_feature(feature) 0
    #endif
    
    #if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
    #ifdef __cplusplus
    extern "C"
    #endif
    const char *__asan_default_options() {
      // Clang reports ODR Violation errors in mbedtls/library/certs.c.
      // NEED TO REPORT THIS ISSUE
      return "detect_odr_violation=0";
    }
    #endif