diff --git a/CMakeLists.txt b/CMakeLists.txt index f6d230ae..a4146213 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,6 +35,7 @@ project(NIFTI list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake) include(nifti_macros) include(nifti_warnings) +include(nifti_hardening) set_property(GLOBAL PROPERTY nifti_installed_targets) diff --git a/cmake/nifti_hardening.cmake b/cmake/nifti_hardening.cmake new file mode 100644 index 00000000..73c4df22 --- /dev/null +++ b/cmake/nifti_hardening.cmake @@ -0,0 +1,51 @@ +# +# Runtime hardening for optimized builds. +# +# _FORTIFY_SOURCE makes the C library bounds-check the string and memory +# functions wherever the compiler can determine the destination size, and +# abort rather than write past the end. Level 3 (gcc 12+, clang 15+) also +# covers sizes known only at run time, the strlen(x) + n shape this library +# uses throughout its filename construction. +# +# At -O0 the compiler cannot determine object sizes and glibc warns if the +# macro is defined anyway, so it is applied only to optimized builds. +# + +option(NIFTI_ENABLE_FORTIFY_SOURCE + "Enable _FORTIFY_SOURCE buffer checks in optimized builds" ON) +mark_as_advanced(NIFTI_ENABLE_FORTIFY_SOURCE) + +if(NOT NIFTI_ENABLE_FORTIFY_SOURCE) + return() +endif() + +if(NOT CMAKE_C_COMPILER_ID MATCHES "GNU|Clang|AppleClang") + return() +endif() + +include(CheckCSourceCompiles) + +# Both the compiler and the C library must support the level, so compile. +set(_nifti_fortify "") +foreach(_level 3 2) + set(CMAKE_REQUIRED_FLAGS "-O2 -D_FORTIFY_SOURCE=${_level} -Werror") + check_c_source_compiles( + "#include \n#include \nint main(void){char *p=malloc(8);if(!p)return 1;strcpy(p,\"x\");free(p);return 0;}" + NIFTI_HAVE_FORTIFY_${_level}) + unset(CMAKE_REQUIRED_FLAGS) + if(NIFTI_HAVE_FORTIFY_${_level}) + set(_nifti_fortify ${_level}) + break() + endif() +endforeach() + +if(NOT _nifti_fortify) + return() +endif() + +message(STATUS "Using _FORTIFY_SOURCE=${_nifti_fortify} for optimized builds") + +add_compile_options( + "$<$,$,$>:-D_FORTIFY_SOURCE=${_nifti_fortify}>") + +unset(_nifti_fortify)