6

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!

yugr
  • 19,769
  • 3
  • 51
  • 96
Ashley Duncan
  • 825
  • 1
  • 8
  • 22

2 Answers2

8

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
yugr
  • 19,769
  • 3
  • 51
  • 96
1

Is it possible for cmake to set an environment variable so it persists after cmake runs?

No. This is not possible. You cannot set an environment variable in the parent process from CMake. The documentation for the set command even cautions you about this.

From here:

This command affects only the current CMake process, not the process from which CMake was called, nor the system environment at large, nor the environment of subsequent build or test processes.


However, you might be able to work around this particular issue via the CMAKE_CXX_COMPILER_LAUNCHER variable:

set(CMAKE_CXX_COMPILER_LAUNCHER ${CMAKE_COMMAND} -E env ASAN_OPTIONS=detect_odr_violation=0 ${CMAKE_CXX_COMPILER_LAUNCHER})

This will call the compiler with the relevant environment variable set. See the docs here: https://cmake.org/cmake/help/latest/prop_tgt/LANG_COMPILER_LAUNCHER.html

Alex Reinking
  • 16,724
  • 5
  • 52
  • 86
  • Thanks for the explanation on the environment variable. According to the following answer, I actually don't want to pass this variable to the compiler but need it set before the compiled application runs which does make some sense now. – Ashley Duncan May 13 '21 at 04:18