Commit d630887bb6ab91a55e72fddc65db93ee6abcd984

Patrick Steinhardt 2017-08-30T21:47:12

cmake: enable reproducible static linking By default, both ar(1) and ranlib(1) will insert additional information like timestamps into generated static archives and indices. As a consequence, generated static archives are not deterministic when created with default parameters. Both programs do support a deterministic mode, which will simply zero out undeterministic information with `ar D` and `ranlib -D`. Unfortunately, CMake does not provide an easy knob to add these command line parameters. Instead, we have to redefine the complete command definitons stored in the variables CMAKE_C_ARCHIVE_CREATE, CMAKE_C_ARCHIVE_APPEND and CMAKE_C_ARCHIVE_FINISH. Introduce a new build option `ENABLE_REPRODUCIBLE_BUILDS`. This option is available on Unix-like systems with the exception of macOS, which does not have support for the required flags. If the option is being enabled, we add those flags to the invocation of both `ar` and `ranlib` to enable deterministically building the static archive.

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4c03aa0..4c411ab 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -50,6 +50,9 @@ OPTION( CURL			"Use curl for HTTP if available" ON)
 OPTION( USE_EXT_HTTP_PARSER		"Use system HTTP_Parser if available" ON)
 OPTION( DEBUG_POOL			"Enable debug pool allocator"			OFF )
 OPTION( ENABLE_WERROR			"Enable compilation with -Werror"		OFF )
+IF (UNIX AND NOT APPLE)
+	OPTION( ENABLE_REPRODUCIBLE_BUILDS	"Enable reproducible builds" 			OFF )
+ENDIF()
 
 IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
 	SET( USE_ICONV ON )
@@ -222,6 +225,12 @@ IF (MSVC)
 	SET(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO}")
 	SET(CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL}")
 ELSE ()
+	IF (ENABLE_REPRODUCIBLE_BUILDS)
+		SET(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> Dqc <TARGET> <LINK_FLAGS> <OBJECTS>")
+		SET(CMAKE_C_ARCHIVE_APPEND "<CMAKE_AR> Dq  <TARGET> <LINK_FLAGS> <OBJECTS>")
+		SET(CMAKE_C_ARCHIVE_FINISH "<CMAKE_RANLIB> -D <TARGET>")
+	ENDIF()
+
 	SET(CMAKE_C_FLAGS "-D_GNU_SOURCE ${CMAKE_C_FLAGS}")
 
 	MACRO(ENABLE_WARNINGS flag)