From fbbaecb9a341051598ed27423e651ec3cd18f48f Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Wed, 11 Sep 2019 22:00:23 +0200 Subject: cmake: Add macro to add compiler flag only if supported --- CMakeLists.txt | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e75f2a..dc61886 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ ################################################################################ PROJECT(dnbd3 C) -CMAKE_MINIMUM_REQUIRED(VERSION 2.6.2) +CMAKE_MINIMUM_REQUIRED(VERSION 2.8.12) IF (CMAKE_BUILD_TYPE STREQUAL "") SET(CMAKE_BUILD_TYPE Debug) ENDIF() @@ -33,18 +33,36 @@ ELSE() OPTION(BUILD_KERNEL_MODULE "Build the dnbd3 Linux kernel module" ON) ENDIF() +INCLUDE(CheckCCompilerFlag) +macro (TRY_ADD_FLAG _FLAG) + UNSET(TMP_TEST CACHE) + CHECK_C_COMPILER_FLAG("${_FLAG}" TMP_TEST) + if (TMP_TEST) + message(":-) Compiler supports ${_FLAG}") + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_FLAG}") + else() + message(":-( Compiler does not support ${_FLAG}") + endif() + +endmacro() + # Common for gcc and clang -SET(CMAKE_EXE_LINKER_FLAGS "-Wl,-z,relro,-z,now -pie") -SET(CMAKE_C_FLAGS "-fPIE -std=c11 -fstack-protector -Wno-multichar -fno-strict-aliasing -D_GNU_SOURCE ${EXTRA_C_FLAGS}") +SET(CMAKE_EXE_LINKER_FLAGS "-Wl,-z,relro,-z,now,-z,defs -pie") +SET(CMAKE_C_FLAGS "-fPIE -std=c11 -Wno-multichar -fno-strict-aliasing -D_GNU_SOURCE -D_FORTIFY_SOURCE=2 ${EXTRA_C_FLAGS}") +SET(CMAKE_C_FLAGS_RELEASE " -O3 -Wno-unused-result -DNDEBUG") +# Hardening. Try as much as is possible. +TRY_ADD_FLAG("-mmitigate-rop") +TRY_ADD_FLAG("-fstack-protector-strong") +TRY_ADD_FLAG("-fstack-clash-protection") +TRY_ADD_FLAG("-Wformat") +TRY_ADD_FLAG("-Wformat-security") +TRY_ADD_FLAG("-Werror=format-security") if(CMAKE_C_COMPILER MATCHES "clang") message( "Using clang flags." ) SET(CMAKE_C_FLAGS_DEBUG " -O1 -fno-omit-frame-pointer -g -Wall -Wextra -Wpedantic -Wno-unused-result -D_DEBUG") - SET(CMAKE_C_FLAGS_RELEASE " -O3 -Wno-unused-result -DNDEBUG") elseif (CMAKE_C_COMPILER MATCHES "(cc-)|(cc$)") message( "Using (g)cc flags." ) - SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mmitigate-rop") SET(CMAKE_C_FLAGS_DEBUG " -O0 -g -Wall -Wextra -Wpedantic -Wconversion -Wno-sign-conversion -D_DEBUG") - SET(CMAKE_C_FLAGS_RELEASE " -O3 -Wno-unused-result -DNDEBUG") else() message( FATAL_ERROR "Could not determine compiler type." ) endif() -- cgit v1.2.3-55-g7522