
macro(SETUP_MEMORY_DEBUGGER)
if (DEFINED ENV{HIFI_MEMORY_DEBUGGING})
  SET( HIFI_MEMORY_DEBUGGING $ENV{HIFI_MEMORY_DEBUGGING} )
endif ()

if (HIFI_MEMORY_DEBUGGING)
  if (UNIX)
    if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
        # for clang on Linux
        if (HIFI_MEMORY_DEBUGGING STREQUAL "tsan")
            SET(SAN_ARGS "-fsanitize=thread")
            MESSAGE(STATUS "Memory debugging is enabled: tsan")
        elseif (HIFI_MEMORY_DEBUGGING STREQUAL "coverage")
            SET(SAN_ARGS "-fprofile-instr-generate -fcoverage-mapping")
            MESSAGE(STATUS "Code coverage checking enabled.")
        else ()
            SET(SAN_ARGS "-shared-libasan -fsanitize=undefined -fsanitize=address -fsanitize-recover=address")
            MESSAGE(STATUS "Memory debugging is enabled: asan+ubsan")
        endif ()
        SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-omit-frame-pointer ${SAN_ARGS}")
        SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SAN_ARGS}")
        SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${SAN_ARGS}")
    else ()
        # for gcc on Linux
        SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined -fsanitize=address -U_FORTIFY_SOURCE -fno-stack-protector -fno-omit-frame-pointer")
        SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libasan -static-libstdc++ -fsanitize=undefined -fsanitize=address")
        SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libasan -static-libstdc++ -fsanitize=undefined -fsanitize=address")
        MESSAGE(STATUS "Memory debugging is enabled: asan+ubsan")
    endif()
  endif (UNIX)
endif ()

endmacro(SETUP_MEMORY_DEBUGGER)
