Debian Codegraph @

crt/aws-c-common/cmake/AwsSanitizers.cmake

raw
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 include(CheckCCompilerFlag)
5
6 option(ENABLE_SANITIZERS "Enable sanitizers in debug builds" OFF)
7 set(SANITIZERS "address;undefined" CACHE STRING "List of sanitizers to build with")
8
9 # This function checks if a sanitizer is available
10 # Options:
11 # sanitizer: The sanitizer to check
12 # out_variable: The variable to assign the result to. Defaults to HAS_SANITIZER_${sanitizer}
13 function(aws_check_sanitizer sanitizer)
14 list(LENGTH ARGN extra_count)
15 if(${extra_count} EQUAL 0)
16 set(out_variable HAS_SANITIZER_${sanitizer})
17 # Sanitize the variable name to remove illegal characters
18 string(MAKE_C_IDENTIFIER ${out_variable} out_variable)
19 elseif(${extra_count} EQUAL 1)
20 set(out_variable ${ARGN})
21 else()
22 message(FATAL_ERROR "Error: aws_check_sanitizer() called with multiple out variables")
23 endif()
24
25 if(ENABLE_SANITIZERS)
26 # When testing for libfuzzer, if attempting to link there will be 2 mains
27 if(${sanitizer} STREQUAL "fuzzer")
28 set(sanitizer_test_flag -fsanitize=fuzzer-no-link)
29 else()
30 set(sanitizer_test_flag -fsanitize=${sanitizer})
31 endif()
32
33 # Need to set this here so that the flag is passed to the linker
34 set(CMAKE_REQUIRED_FLAGS ${sanitizer_test_flag})
35 check_c_compiler_flag(${sanitizer_test_flag} ${out_variable})
36 else()
37 set(${out_variable} 0 PARENT_SCOPE)
38 endif()
39 endfunction()
40
41 # This function enables sanitizers on the given target
42 # Options:
43 # SANITIZERS: The list of extra sanitizers to enable
44 function(aws_add_sanitizers target)
45 set(multiValueArgs SANITIZERS)
46 cmake_parse_arguments(SANITIZER "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
47
48 if (NOT ENABLE_SANITIZERS)
49 return()
50 endif()
51
52 list(APPEND SANITIZER_SANITIZERS ${SANITIZERS})
53
54 foreach(sanitizer IN LISTS SANITIZER_SANITIZERS)
55
56 set(sanitizer_variable HAS_SANITIZER_${sanitizer})
57 # Sanitize the variable name to remove illegal characters
58 string(MAKE_C_IDENTIFIER ${sanitizer_variable} sanitizer_variable)
59
60 aws_check_sanitizer(${sanitizer} ${sanitizer_variable})
61 if(${${sanitizer_variable}})
62 if (NOT "${PRESENT_SANITIZERS}" STREQUAL "")
63 set(PRESENT_SANITIZERS "${PRESENT_SANITIZERS},")
64 endif()
65 set(PRESENT_SANITIZERS "${PRESENT_SANITIZERS}${sanitizer}")
66 endif()
67 endforeach()
68
69 if(PRESENT_SANITIZERS)
70 target_compile_options(${target} PRIVATE -fno-omit-frame-pointer -fsanitize=${PRESENT_SANITIZERS})
71 target_link_libraries(${target} PUBLIC "-fno-omit-frame-pointer -fsanitize=${PRESENT_SANITIZERS}")
72
73 string(REPLACE "," ";" PRESENT_SANITIZERS "${PRESENT_SANITIZERS}")
74 set(${target}_SANITIZERS ${PRESENT_SANITIZERS} PARENT_SCOPE)
75 endif()
76 endfunction()