include(CheckCXXCompilerFlag)
include(CMakePushCheckState)

function(findsaninternal_export_sanitizer flag name)
	cmake_push_check_state()
	set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${flag}")
	check_cxx_compiler_flag(${flag} HAS_${name}_SANITIZER)
	if(HAS_${name}_SANITIZER)
		set(HAS_${name}_SANITIZER true CACHE BOOL "")
		add_library(${name}_Sanitizer INTERFACE)
		add_library(Sanitizer::${name} ALIAS ${name}_Sanitizer)
		target_compile_options(${name}_Sanitizer INTERFACE ${flag})
		target_link_libraries(${name}_Sanitizer INTERFACE ${flag})
	endif()
	cmake_pop_check_state()
endfunction()

findsaninternal_export_sanitizer("-fsanitize=address" "Address")
findsaninternal_export_sanitizer("-fsanitize=thread" "Thread")
findsaninternal_export_sanitizer("-fsanitize=memory" "Memory")
findsaninternal_export_sanitizer("-fsanitize=leak" "Leak")
findsaninternal_export_sanitizer("-fsanitize=undefined" "Undefined")

# Fuzzer does not allow a main function
add_library(Fuzzer_Sanitizer INTERFACE)
add_library(Sanitizer::Fuzzer ALIAS Fuzzer_Sanitizer)
target_compile_options(Fuzzer_Sanitizer INTERFACE "-fsanitize=fuzzer")
target_link_libraries(Fuzzer_Sanitizer INTERFACE "-fsanitize=fuzzer")
set(HAS_Fuzzer_SANITIZER true CACHE BOOL "")
