Skip to content

Commit 0f56246

Browse files
committed
Add compiler-specific hardening flags for GCC and Clang
1 parent f79a9c2 commit 0f56246

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

CMakeLists.txt

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,43 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
111111
endforeach()
112112
endif()
113113

114+
# Add compiler-specific hardening flags.
115+
if(CMAKE_CXX_COMPILER_ID MATCHES "^(Clang|GNU)$")
116+
add_compile_options(
117+
# Warn about potentially unsafe code.
118+
-Wall
119+
# Warn about implicit conversions that potentially alter a value.
120+
-Wconversion
121+
# Check argument types of format string function calls, e.g., printf.
122+
-Wformat
123+
# Check for potential security issues in format string function calls.
124+
-Wformat-security
125+
# Revert strict aliasing enabled at optimization levels -O2, -O3, -Os.
126+
-fno-strict-aliasing
127+
# Check for buffer overflows such as stack smashing attacks.
128+
-fstack-protector
129+
# Enable fortified wrappers of GNU C library functions.
130+
-D_FORTIFY_SOURCE=2
131+
# Optimize debugging experience, required for _FORTIFY_SOURCE.
132+
# https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-Og
133+
$<$<CONFIG:Debug>:-Og>
134+
)
135+
136+
# We need to support CMake 3.10, add_link_options() was added in CMake 3.13.
137+
# link_libraries() passes flags through as long as they do not contain spaces.
138+
# https://cmake.org/cmake/help/v3.13/command/add_link_options.html
139+
link_libraries(
140+
# Check objects for unresolved symbol references.
141+
-Wl,--no-undefined
142+
# Mark library as not requiring executable stack.
143+
-Wl,-z,noexecstack
144+
# Resolve all symbols when program is started, instead of on first use.
145+
-Wl,-z,now
146+
# Mark Global Offset Table read-only after resolving symbols.
147+
-Wl,-z,relro
148+
)
149+
endif()
150+
114151
# https://clang.llvm.org/docs/AddressSanitizer.html
115152
option(ACL_WITH_ASAN "Build with address sanitizer" OFF)
116153
message(STATUS "Build with address sanitizer: ${ACL_WITH_ASAN}")

0 commit comments

Comments
 (0)