From dcf03e6cdb26b9a095c9663130665650ca66f6fa Mon Sep 17 00:00:00 2001 From: Gregor Jasny Date: Mon, 16 Oct 2023 14:43:38 +0200 Subject: [PATCH] feat: use CMake to control symbol visibility (#574) In contrast to #572 this solution does not need any extra headers. But it is also limited to GCC-like compilers. Fix By: Gregor Jasny (@gjasny) --- CMakeLists.txt | 16 ++++++++++++++++ src/lib/CMakeLists.txt | 7 +++++++ src/lib/ares_config.h.cmake | 4 ++-- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a8f9340..ac2b5fb1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,6 +42,7 @@ OPTION (CARES_STATIC_PIC "Build the static library as PIC (position independent) OPTION (CARES_BUILD_TESTS "Build and run tests" OFF) OPTION (CARES_BUILD_CONTAINER_TESTS "Build and run container tests (implies CARES_BUILD_TESTS, Linux only)" OFF) OPTION (CARES_BUILD_TOOLS "Build tools" ON) +OPTION (CARES_SYMBOL_HIDING "Hide private symbols in shared libraries" OFF) SET (CARES_RANDOM_FILE "/dev/urandom" CACHE STRING "Suitable File / Device Path for entropy, such as /dev/urandom") @@ -74,6 +75,21 @@ IF (MSVC) ENDIF () ENDIF () +IF (CARES_SYMBOL_HIDING) + IF (CMAKE_VERSION VERSION_LESS 3.12) + MESSAGE (FATAL_ERROR "Hiding symbols requires CMake 3.12") + ENDIF () + CMAKE_POLICY (SET CMP0063 NEW) + SET (CARES_SYMBOL_SCOPE_EXTERN [=[__attribute__ ((visibility("default")))]=]) + CHECK_C_SOURCE_COMPILES (" + ${CARES_SYMBOL_SCOPE_EXTERN} int somefunc() { return 0; } + int main() { return somefunc(); } + " HAVE_VISIBILITY_ATTRIBUTE) + IF (NOT HAVE_VISIBILITY_ATTRIBUTE) + MESSAGE (FATAL_ERROR "C compiler does not accept visibility attribute") + ENDIF () +ENDIF () + # Keep build organized. SET (CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") SET (CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") diff --git a/src/lib/CMakeLists.txt b/src/lib/CMakeLists.txt index 235a96ba..7cb37f16 100644 --- a/src/lib/CMakeLists.txt +++ b/src/lib/CMakeLists.txt @@ -37,6 +37,13 @@ IF (CARES_SHARED) C_STANDARD 90 ) + IF (CARES_SYMBOL_HIDING) + SET_TARGET_PROPERTIES (${PROJECT_NAME} PROPERTIES + C_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN YES + ) + ENDIF () + TARGET_INCLUDE_DIRECTORIES (${PROJECT_NAME} PUBLIC "$" "$" diff --git a/src/lib/ares_config.h.cmake b/src/lib/ares_config.h.cmake index a33eb9ca..caca5f74 100644 --- a/src/lib/ares_config.h.cmake +++ b/src/lib/ares_config.h.cmake @@ -17,10 +17,10 @@ #undef CARES_EXPOSE_STATICS /* Defined for build with symbol hiding. */ -#undef CARES_SYMBOL_HIDING +#cmakedefine CARES_SYMBOL_HIDING /* Definition to make a library symbol externally visible. */ -#undef CARES_SYMBOL_SCOPE_EXTERN +#define CARES_SYMBOL_SCOPE_EXTERN @CARES_SYMBOL_SCOPE_EXTERN@ /* Use resolver library to configure cares */ #cmakedefine CARES_USE_LIBRESOLV