Debian Codegraph @

crt/s2n/CMakeLists.txt

raw
1 cmake_minimum_required (VERSION 3.10)
2 project (s2n C)
3
4 if(POLICY CMP0077)
5 cmake_policy(SET CMP0077 NEW) #option does nothing when a normal variable of the same name exists.
6 endif()
7
8 set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
9 set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
10 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
11 set(INSTALL_LIB_DIR lib CACHE PATH "Installation directory for libraries")
12 set(INSTALL_INCLUDE_DIR include CACHE PATH "Installation directory for header files")
13 set(INSTALL_CMAKE_DIR lib/cmake CACHE PATH "Installation directory for cmake files")
14
15 set(CMAKE_FIND_PACKAGE_PREFER_CONFIG TRUE)
16
17 # These Version numbers are for major updates only- we won't track minor/patch updates here.
18 set(VERSION_MAJOR 1)
19 set(VERSION_MINOR 0)
20 set(VERSION_PATCH 0)
21
22 option(SEARCH_LIBCRYPTO "Set this if you want to let S2N search libcrypto for you,
23 otherwise a crypto target needs to be defined." ON)
24 option(UNSAFE_TREAT_WARNINGS_AS_ERRORS "Compiler warnings are treated as errors. Warnings may
25 indicate danger points where you should verify with the S2N-TLS developers that the security of
26 the library is not compromised. Turn this OFF to ignore warnings." ON)
27 option(S2N_WERROR_ALL "This option will cause all artifacts linked to libs2n to use the
28 -Werror setting." OFF)
29 option(S2N_INTERN_LIBCRYPTO "This ensures that s2n-tls is compiled and deployed with a specific
30 version of libcrypto by interning the code and hiding symbols. This also enables s2n-tls to be
31 loaded in an application with an otherwise conflicting libcrypto version." OFF)
32 option(S2N_LTO, "Enables link time optimizations when building s2n-tls." OFF)
33 option(S2N_STACKTRACE "Enables stacktrace functionality in s2n-tls. Note that this functionality is
34 only available on platforms that support execinfo." ON)
35 option(S2N_OVERRIDE_LIBCRYPTO_RAND_ENGINE "No-op, retained for backwards compatibility. The custom RAND engine was removed
36 as part of the DRBG deprecation." ON)
37 option(S2N_ENFORCE_PROPER_LIBCRYPTO_FEATURE_PROBE "Assert that the feature probes are able to link to the libcrypto and
38 properly probe for feature support. If the feature probes are unable to properly probe for support, the build will
39 fail. This option ensures that s2n-tls doesn't silently build without properly probing for the support of important
40 features, such as TLS 1.3 support." OFF)
41 option(COVERAGE "Enable profiling collection for code coverage calculation" OFF)
42 option(BUILD_TESTING "Build tests for s2n-tls. By default only unit tests are built." ON)
43 option(S2N_INTEG_TESTS "Enable the integrationv2 tests" OFF)
44 option(S2N_FAST_INTEG_TESTS "Enable the integrationv2 with more parallelism, only has effect if S2N_INTEG_TESTS=ON" ON)
45 option(S2N_INSTALL_S2NC_S2ND "Install the binaries s2nc and s2nd" OFF)
46 option(S2N_USE_CRYPTO_SHARED_LIBS "For S2N to use shared libs in Findcrypto" OFF)
47 option(TSAN "Enable ThreadSanitizer to test thread safety" OFF)
48 option(ASAN "Enable AddressSanitizer to test memory safety" OFF)
49 option(SECCOMP "Link with seccomp and run seccomp tests" OFF)
50
51 file(GLOB API_HEADERS "api/*.h")
52 file(GLOB API_UNSTABLE_HEADERS "api/unstable/*.h")
53
54 file(GLOB CRYPTO_HEADERS "crypto/*.h")
55 file(GLOB CRYPTO_SRC "crypto/*.c")
56
57 file(GLOB ERROR_HEADERS "error/*.h")
58 file(GLOB ERROR_SRC "error/*.c")
59
60 file(GLOB STUFFER_HEADERS "stuffer/*.h")
61 file(GLOB STUFFER_SRC "stuffer/*.c")
62
63 file(GLOB_RECURSE TLS_HEADERS "tls/*.h")
64 file(GLOB_RECURSE TLS_SRC "tls/*.c")
65
66 file(GLOB UTILS_HEADERS "utils/*.h")
67 file(GLOB UTILS_SRC "utils/*.c")
68
69 message(STATUS "Detected CMAKE_SYSTEM_PROCESSOR as ${CMAKE_SYSTEM_PROCESSOR}")
70
71 if(CMAKE_SIZEOF_VOID_P EQUAL 4)
72 message(STATUS "Detected 32-Bit system")
73 else()
74 message(STATUS "Detected 64-Bit system")
75 endif()
76
77 ##be nice to visual studio users
78 if(MSVC)
79 source_group("Header Files\\s2n\\api" FILES ${API_HEADERS} ${API_UNSTABLE_HEADERS})
80 source_group("Header Files\\s2n\\crypto" FILES ${CRYPTO_HEADERS})
81 source_group("Header Files\\s2n\\error" FILES ${ERROR_HEADERS})
82 source_group("Header Files\\s2n\\stuffer" FILES ${STUFFER_HEADERS})
83 source_group("Header Files\\s2n\\tls" FILES ${TLS_HEADERS})
84 source_group("Header Files\\s2n\\utils" FILES ${UTILS_HEADERS})
85
86 source_group("Source Files\\crypto" FILES ${CRYPTO_SRC})
87 source_group("Source Files\\error" FILES ${ERROR_SRC})
88 source_group("Source Files\\stuffer" FILES ${STUFFER_SRC})
89 source_group("Source Files\\tls" FILES ${TLS_SRC})
90 source_group("Source Files\\utils" FILES ${UTILS_SRC})
91 else()
92 set(THREADS_PREFER_PTHREAD_FLAG ON)
93 find_package(Threads REQUIRED)
94 endif()
95
96 if(APPLE)
97 set(OS_LIBS c Threads::Threads)
98 elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
99 set(OS_LIBS thr execinfo)
100 elseif(CMAKE_SYSTEM_NAME STREQUAL "NetBSD")
101 set(OS_LIBS Threads::Threads)
102 elseif(CMAKE_SYSTEM_NAME STREQUAL "OpenBSD")
103 set(OS_LIBS Threads::Threads kvm)
104 elseif(CMAKE_SYSTEM_NAME STREQUAL "Android")
105 set(OS_LIBS Threads::Threads dl)
106 elseif(WIN32)
107 set(OS_LIBS Threads::Threads)
108 else()
109 set(OS_LIBS Threads::Threads dl rt)
110 endif()
111
112 file(GLOB S2N_HEADERS
113 ${API_HEADERS}
114 ${API_UNSTABLE_HEADERS}
115 ${CRYPTO_HEADERS}
116 ${ERROR_HEADERS}
117 ${STUFFER_HEADERS}
118 ${TLS_HEADERS}
119 ${UTILS_HEADERS}
120 )
121
122 file(GLOB S2N_SRC
123 ${CRYPTO_SRC}
124 ${ERROR_SRC}
125 ${STUFFER_SRC}
126 ${TLS_SRC}
127 ${UTILS_SRC}
128 )
129
130 add_library(${PROJECT_NAME} ${S2N_HEADERS} ${S2N_SRC})
131 set_target_properties(${PROJECT_NAME} PROPERTIES LINKER_LANGUAGE C)
132
133 # Version numbers are for major updates only- we won't track minor/patch updates here.
134 set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH})
135 set_target_properties(${PROJECT_NAME} PROPERTIES SOVERSION ${VERSION_MAJOR})
136
137 set(CMAKE_C_FLAGS_DEBUGOPT "")
138
139 target_compile_options(${PROJECT_NAME} PRIVATE
140 -pedantic
141 -std=gnu99
142 -Wall
143 -Wcast-align
144 -Wcast-qual
145 -Wchar-subscripts
146 -Wcomment
147 -Wformat-security
148 -Wimplicit
149 -Wshadow
150 -Wsign-compare
151 -Wuninitialized
152 -Wunused
153 -Wwrite-strings
154
155 # Assembler Options
156 -Wa,--noexecstack
157
158 # Suppressed Warnings
159 -Wno-deprecated-declarations
160 # GCC 4 fails to parse our macros with a "missing-braces" error
161 -Wno-missing-braces
162 -Wno-strict-prototypes
163 -Wno-unknown-pragmas
164 )
165
166 if (S2N_WERROR_ALL)
167 target_compile_options(${PROJECT_NAME} PUBLIC -Werror)
168 elseif (UNSAFE_TREAT_WARNINGS_AS_ERRORS)
169 target_compile_options(${PROJECT_NAME} PRIVATE -Werror )
170 endif ()
171
172 if(BUILD_TESTING AND BUILD_SHARED_LIBS OR S2N_FUZZ_TEST)
173 target_compile_options(${PROJECT_NAME} PRIVATE -fvisibility=default)
174 else()
175 target_compile_options(${PROJECT_NAME} PRIVATE -fvisibility=hidden -DS2N_EXPORTS=1)
176 endif()
177
178 if(S2N_LTO)
179 target_compile_options(${PROJECT_NAME} PRIVATE -flto)
180 # if we're building a static lib, make it easier for consuming applications to also perform LTO
181 if(NOT BUILD_SHARED_LIBS)
182 target_compile_options(${PROJECT_NAME} PRIVATE -ffunction-sections -fdata-sections)
183 endif()
184 endif()
185
186 if(NOT APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "AIX")
187 set(CMAKE_SHARED_LINKER_FLAGS -Wl,-z,noexecstack,-z,relro,-z,now)
188 endif()
189
190 # Whether to fail the build when compiling s2n's portable C code with non-portable assembly optimizations. Doing this
191 # can lead to runtime crashes if build artifacts are built on modern hardware, but deployed to older hardware without
192 # newer CPU instructions. s2n, by default, should be backwards compatible with older CPU types so this flag should be
193 # enabled in s2n's CI builds and tests, but other consumers of s2n may have stronger control of what CPU types they
194 # deploy to, and can enable more CPU optimizations.
195 if(S2N_BLOCK_NONPORTABLE_OPTIMIZATIONS)
196 target_compile_options(${PROJECT_NAME} PUBLIC -DS2N_BLOCK_NONPORTABLE_OPTIMIZATIONS=1)
197 endif()
198
199 target_compile_options(${PROJECT_NAME} PRIVATE -fPIC)
200
201 set(S2N_PRELUDE "${CMAKE_CURRENT_LIST_DIR}/utils/s2n_prelude.h")
202 target_compile_options(${PROJECT_NAME} PRIVATE -include "${S2N_PRELUDE}")
203
204 # Match on Release, RelWithDebInfo and MinSizeRel
205 # See: https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html#variable:CMAKE_BUILD_TYPE
206 if(CMAKE_BUILD_TYPE MATCHES Rel)
207 add_definitions(-DS2N_BUILD_RELEASE=1)
208 endif()
209
210 if(NO_STACK_PROTECTOR)
211 target_compile_options(${PROJECT_NAME} PRIVATE -Wstack-protector -fstack-protector-all)
212 endif()
213
214 if(S2N_FUZZ_TEST)
215 target_compile_definitions(${PROJECT_NAME} PUBLIC S2N_FUZZ_TESTING=1)
216 target_compile_options(${PROJECT_NAME} PUBLIC -fsanitize=fuzzer-no-link,leak,address,undefined)
217 target_link_libraries(${PROJECT_NAME} PUBLIC -fsanitize=fuzzer-no-link,leak,address,undefined)
218 endif()
219
220 if(TSAN)
221 target_compile_options(${PROJECT_NAME} PUBLIC -fsanitize=thread -DS2N_THREAD_SANITIZER=1)
222 target_link_options(${PROJECT_NAME} PUBLIC -fsanitize=thread)
223 endif()
224
225 if(ASAN)
226 target_compile_options(${PROJECT_NAME} PUBLIC -fsanitize=address -DS2N_ADDRESS_SANITIZER=1)
227 target_link_options(${PROJECT_NAME} PUBLIC -fsanitize=address)
228 endif()
229
230 if (UBSAN)
231 target_compile_options(${PROJECT_NAME} PUBLIC -fsanitize=undefined -fno-sanitize-recover=all)
232 target_link_options(${PROJECT_NAME} PUBLIC -fsanitize=undefined -fno-sanitize-recover=all)
233 endif()
234
235 if(TSAN OR ASAN OR UBSAN)
236 # no-omit-frame-pointer and no-optimize-sibling-calls provide better stack traces
237 target_compile_options(${PROJECT_NAME} PUBLIC -fno-omit-frame-pointer -fno-optimize-sibling-calls)
238 endif()
239
240 list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules")
241
242 if (COVERAGE)
243 # https://cmake.org/cmake/help/latest/variable/CMAKE_LANG_COMPILER_ID.html
244 # Coverage is done using LLVM source based coverage. This is only supported
245 # on LLVM compilers. GCC would fail with "unrecognized compile options"
246 # on -fprofile-instr-generate -fcoverage-mapping flags.
247 if (NOT ${CMAKE_C_COMPILER_ID} MATCHES Clang)
248 message(FATAL_ERROR "This project requires clang for coverage support. You are currently using " ${CMAKE_C_COMPILER_ID})
249 endif()
250 target_compile_options(${PROJECT_NAME} PUBLIC -fprofile-instr-generate -fcoverage-mapping)
251 target_link_options(${PROJECT_NAME} PUBLIC -fprofile-instr-generate -fcoverage-mapping)
252 endif()
253
254 if (NOT S2N_OVERRIDE_LIBCRYPTO_RAND_ENGINE)
255 # No-op: the custom RAND engine was removed as part of the DRBG
256 # deprecation. This option is retained so that existing builds
257 # setting S2N_OVERRIDE_LIBCRYPTO_RAND_ENGINE=0 continue to succeed.
258 message(STATUS "S2N_OVERRIDE_LIBCRYPTO_RAND_ENGINE=OFF (no-op, custom RAND engine was removed)")
259 endif()
260
261 # For interning, we need to find the static libcrypto library. Cmake configs
262 # can branch on the variable BUILD_SHARED_LIBS to e.g. avoid having to define
263 # multiple targets. An example is AWS-LC:
264 # https://github.com/awslabs/aws-lc/blob/main/crypto/cmake/crypto-config.cmake#L5
265 if (S2N_INTERN_LIBCRYPTO)
266 set(BUILD_SHARED_LIBS_BACKUP ${BUILD_SHARED_LIBS})
267 set(BUILD_SHARED_LIBS OFF)
268 endif()
269
270 # Work around target differences
271 if (TARGET crypto)
272 message(STATUS "S2N found target: crypto")
273 set(LINK_LIB "crypto")
274 else()
275 find_package(crypto REQUIRED)
276 message(STATUS "Using libcrypto from the cmake path")
277 set(LINK_LIB "AWS::crypto")
278 endif()
279
280 if (S2N_INTERN_LIBCRYPTO)
281 # Restore the old BUILD_SHARED_LIBS value
282 set(BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS_BACKUP})
283 message(STATUS "Enabling libcrypto interning")
284 endif()
285
286 if (NOT DEFINED CMAKE_AR)
287 message(STATUS "CMAKE_AR undefined, setting to `ar` by default")
288 SET(CMAKE_AR ar)
289 else()
290 message(STATUS "CMAKE_AR found: ${CMAKE_AR}")
291 endif()
292
293 if (NOT DEFINED CMAKE_RANLIB)
294 message(STATUS "CMAKE_RANLIB undefined, setting to `ranlib` by default")
295 SET(CMAKE_RANLIB ranlib)
296 else()
297 message(STATUS "CMAKE_RANLIB found: ${CMAKE_RANLIB}")
298 endif()
299
300 if (NOT DEFINED CMAKE_OBJCOPY)
301 message(STATUS "CMAKE_OBJCOPY undefined, setting to `objcopy` by default")
302 SET(CMAKE_OBJCOPY objcopy)
303 else()
304 message(STATUS "CMAKE_OBJCOPY found: ${CMAKE_OBJCOPY}")
305 endif()
306
307 # Sets the result of the feature probe to `IS_AVAILABLE`
308 function(feature_probe_result PROBE_NAME IS_AVAILABLE)
309 # normalize the boolean value
310 if(IS_AVAILABLE)
311 set(NORMALIZED TRUE)
312 else()
313 set(NORMALIZED FALSE)
314 endif()
315
316 # indicate the status of the probe
317 message(STATUS "feature ${PROBE_NAME}: ${NORMALIZED}")
318 # set the probe result in the parent scope for other probes
319 set(${PROBE_NAME} ${NORMALIZED} PARENT_SCOPE)
320
321 # define the probe if available
322 if(NORMALIZED)
323 add_definitions(-D${PROBE_NAME}=1)
324 endif()
325 endfunction()
326
327 # Tries to compile a feature probe and initializes the corresponding flags
328 function(feature_probe PROBE_NAME)
329 # Load the global probe flags
330 file(READ "${CMAKE_CURRENT_LIST_DIR}/tests/features/GLOBAL.flags" GLOBAL_FILE)
331 string(REPLACE "\n" "" GLOBAL_FLAGS "${GLOBAL_FILE}")
332
333 # Load the probe's flags
334 file(READ "${CMAKE_CURRENT_LIST_DIR}/tests/features/${PROBE_NAME}.flags" PROBE_FILE)
335 string(REPLACE "\n" "" PROBE_FLAGS "${PROBE_FILE}")
336
337 # On macOS, NO_SYSTEM_FROM_IMPORTED forces imported target (aws-lc) includes
338 # to use -I instead of -isystem, so they outrank the baked-in /usr/local/include.
339 set(PROBE_CMAKE_FLAGS ${ADDITIONAL_FLAGS})
340 if (APPLE)
341 list(APPEND PROBE_CMAKE_FLAGS "-DCMAKE_NO_SYSTEM_FROM_IMPORTED=ON")
342 endif()
343
344 # Try to compile the probe with the given flags
345 try_compile(
346 IS_AVAILABLE
347 ${CMAKE_BINARY_DIR}
348 SOURCES "${CMAKE_CURRENT_LIST_DIR}/tests/features/${PROBE_NAME}.c"
349 LINK_LIBRARIES ${LINK_LIB} ${OS_LIBS}
350 CMAKE_FLAGS ${PROBE_CMAKE_FLAGS}
351 COMPILE_DEFINITIONS -I "${CMAKE_CURRENT_LIST_DIR}" -include "${CMAKE_CURRENT_LIST_DIR}/utils/s2n_prelude.h" -c ${GLOBAL_FLAGS} ${PROBE_FLAGS}
352 ${ARGN}
353 OUTPUT_VARIABLE TRY_COMPILE_OUTPUT
354 )
355 # Uncomment the line below to get the output of the try_compile command
356 #message(STATUS "Output of try_compile: ${TRY_COMPILE_OUTPUT}")
357
358 # Set the result of the probe
359 feature_probe_result(${PROBE_NAME} ${IS_AVAILABLE})
360
361 # Make sure the variable is set in the parent scope
362 set(${PROBE_NAME} ${IS_AVAILABLE} PARENT_SCOPE)
363
364 # Set the flags that we used for the probe
365 set(${PROBE_NAME}_FLAGS ${PROBE_FLAGS} PARENT_SCOPE)
366
367 set(${PROBE_NAME}_OUTPUT "${TRY_COMPILE_OUTPUT}" PARENT_SCOPE)
368 endfunction()
369
370 # Iterate over all of the features and try to compile them
371 FILE(GLOB FEATURE_SRCS "${CMAKE_CURRENT_LIST_DIR}/tests/features/*.c")
372 list(SORT FEATURE_SRCS)
373 foreach(file ${FEATURE_SRCS})
374 get_filename_component(feature_name ${file} NAME_WE)
375 feature_probe(${feature_name})
376 endforeach()
377
378 # Ensure that the feature probes were able to properly link to the libcrypto.
379 if(S2N_ENFORCE_PROPER_LIBCRYPTO_FEATURE_PROBE AND NOT S2N_LIBCRYPTO_SANITY_PROBE)
380 message(FATAL_ERROR "A sanity-check libcrypto feature probe failed, which indicates that other
381 feature probes were likely unable to probe the libcrypto for its supported features:
382 ${S2N_LIBCRYPTO_SANITY_PROBE_OUTPUT}")
383 endif()
384
385 # FreeBSD might need to link to execinfo explicitly
386 if(NOT S2N_EXECINFO_AVAILABLE AND CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
387 feature_probe(S2N_EXECINFO_AVAILABLE LINK_LIBRARIES execinfo)
388 endif()
389
390 # Stack traces are only available if execinfo is
391 if (NOT S2N_EXECINFO_AVAILABLE)
392 set(S2N_STACKTRACE FALSE)
393 endif()
394 feature_probe_result(S2N_STACKTRACE ${S2N_STACKTRACE})
395
396 if (S2N_COMPILER_SUPPORTS_BRANCH_ALIGN AND NOT S2N_FUZZ_TEST)
397 target_compile_options(${PROJECT_NAME} PRIVATE "-Wa,-mbranches-within-32B-boundaries")
398 endif()
399
400 if (S2N_INTERN_LIBCRYPTO)
401
402 # Check if the AWS::crypto target has been added and handle it
403 if (TARGET AWS::crypto)
404 # Get the target library type (shared or static)
405 get_target_property(target_type AWS::crypto TYPE)
406 message(STATUS "AWS::crypto target type: ${target_type}")
407
408 # If we didn't find the a target with static library type, fallback to
409 # existing crypto_STATIC_LIBRARY and crypto_INCLUDE_DIR
410 if (target_type STREQUAL STATIC_LIBRARY)
411 # We need an path to the include directory and libcrypto.a archive.
412 # The finder module defines these appropriately, but if we go through
413 # the target config we need to query this information from the target
414 # first.
415 get_target_property(crypto_STATIC_LIBRARY AWS::crypto LOCATION)
416 get_target_property(crypto_INCLUDE_DIR AWS::crypto INTERFACE_INCLUDE_DIRECTORIES)
417 endif()
418 endif()
419
420 if (NOT crypto_STATIC_LIBRARY)
421 message(FATAL_ERROR "libcrypto interning requires a static build of libcrypto.a to be available")
422 endif()
423
424 message(STATUS "crypto_STATIC_LIBRARY: ${crypto_STATIC_LIBRARY}")
425 message(STATUS "crypto_INCLUDE_DIR: ${crypto_INCLUDE_DIR}")
426
427 # Don't call link_target_libraries here, just make sure the libcrypto include dir is in the path
428 include_directories("${crypto_INCLUDE_DIR}")
429
430 add_custom_command(
431 OUTPUT libcrypto.symbols
432 COMMAND
433 # copy the static version of libcrypto
434 cp ${crypto_STATIC_LIBRARY} s2n_libcrypto.a &&
435 # dump all of the symbols and prefix them with `s2n$`
436 bash -c "${CMAKE_NM} s2n_libcrypto.a | awk '/ [A-Z] /{if ($3) print $3\" s2n$\"$3}' | sort | uniq > libcrypto.symbols" &&
437 # redefine the libcrypto library symbols
438 ${CMAKE_OBJCOPY} --redefine-syms libcrypto.symbols s2n_libcrypto.a &&
439 rm -rf s2n_libcrypto &&
440 mkdir s2n_libcrypto &&
441 cd s2n_libcrypto &&
442 # extract libcrypto objects from the archive
443 ${CMAKE_AR} x ../s2n_libcrypto.a &&
444 # rename all of the object files so we don't have any object name collisions
445 bash -c "find . -name '*.o' -type f -print0 | xargs -0 -n1 -- basename | xargs -I{} mv {} s2n_crypto__{}"
446 VERBATIM
447 )
448
449 add_custom_target(s2n_libcrypto ALL
450 DEPENDS libcrypto.symbols
451 )
452 add_dependencies(${PROJECT_NAME} s2n_libcrypto)
453 add_definitions(-DS2N_INTERN_LIBCRYPTO=1)
454
455 if ((BUILD_SHARED_LIBS AND BUILD_TESTING) OR NOT BUILD_SHARED_LIBS)
456 # if libcrypto needs to be interned, rewrite libcrypto references so use of internal functions will link correctly
457 add_custom_command(
458 TARGET ${PROJECT_NAME} PRE_LINK
459 COMMAND
460 find "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}.dir" -name '*.c.o' -exec objcopy --redefine-syms libcrypto.symbols --preserve-dates {} \\\;
461 )
462 endif()
463
464 # copy the static libcrypto into the final artifact
465 if (BUILD_SHARED_LIBS)
466 if (BUILD_TESTING)
467 # if we're building tests, we export the prefixed symbols so tests can link to them
468 set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS
469 "-Wl,--whole-archive s2n_libcrypto.a -Wl,--no-whole-archive")
470 else()
471 # if we're not building tests, then just copy the original archive, unmodified
472 set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS
473 "-Wl,--whole-archive ${crypto_STATIC_LIBRARY} -Wl,--no-whole-archive -Wl,--exclude-libs=ALL")
474 endif()
475 else()
476 # add all of the prefixed symbols to the archive
477 add_custom_command(
478 TARGET ${PROJECT_NAME} POST_BUILD
479 COMMAND
480 bash -c "${CMAKE_AR} -r $<TARGET_FILE:${PROJECT_NAME}> s2n_libcrypto/*.o"
481 VERBATIM
482 )
483 endif()
484 else()
485 # LINK_LIB is set above after checking targets. It handles the find_package craziness.
486 target_link_libraries(${PROJECT_NAME} PUBLIC ${LINK_LIB})
487 endif()
488
489 # On macOS x64, XCode's Clang has -I/usr/local/include baked in, which can
490 # shadow libcrypto headers from imported targets (propagated with -isystem).
491 # Force -I for imported target includes so aws-lc headers take priority.
492 if (APPLE)
493 set_target_properties(${PROJECT_NAME} PROPERTIES NO_SYSTEM_FROM_IMPORTED ON)
494 endif()
495
496 target_link_libraries(${PROJECT_NAME} PUBLIC ${OS_LIBS})
497 if (NOT WIN32)
498 # On Windows, math functions are part of the C runtime; no separate libm exists.
499 target_link_libraries(${PROJECT_NAME} PUBLIC m)
500 endif()
501
502 target_include_directories(${PROJECT_NAME} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>)
503 target_include_directories(${PROJECT_NAME} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/api> $<INSTALL_INTERFACE:include>)
504
505 if (BUILD_TESTING)
506 enable_testing()
507
508 ############################################################################
509 ################### build testlib (utility library) ########################
510 ############################################################################
511
512 file(GLOB TESTLIB_SRC "tests/testlib/*.c")
513 file(GLOB EXAMPLES_SRC "docs/examples/*.c")
514
515 add_library(testss2n STATIC ${TESTLIB_SRC} ${EXAMPLES_SRC})
516 target_include_directories(testss2n PUBLIC tests)
517 target_compile_options(testss2n PRIVATE -std=gnu99)
518 # make sure all linked tests include the prelude
519 target_compile_options(testss2n PUBLIC -include "${S2N_PRELUDE}" -fPIC)
520 target_link_libraries(testss2n PUBLIC ${PROJECT_NAME})
521 if (WIN32)
522 # Test utilities use sockets for self-talk tests
523 target_link_libraries(testss2n PUBLIC ws2_32)
524 endif()
525 if (SECCOMP)
526 message(STATUS "Linking tests with seccomp")
527 target_link_libraries(testss2n PRIVATE seccomp)
528 target_compile_definitions(testss2n PRIVATE SECCOMP)
529 endif()
530
531 if (S2N_INTERN_LIBCRYPTO)
532 # if libcrypto was interned, rewrite libcrypto symbols so use of internal
533 # functions will link correctly
534 add_custom_command(
535 TARGET testss2n POST_BUILD
536 COMMAND
537 objcopy --redefine-syms libcrypto.symbols lib/libtestss2n.a
538 )
539 endif()
540
541 ############################################################################
542 ########################## configure unit tests ############################
543 ############################################################################
544
545 # CTest configuration variables need to be set before include(CTest) is called
546 set(VALGRIND_DEFAULT " \
547 --leak-check=full \
548 --leak-resolution=high \
549 --trace-children=yes \
550 -q --error-exitcode=123 \
551 --error-limit=no \
552 --num-callers=40 \
553 --undef-value-errors=no \
554 --track-fds=yes \
555 --log-fd=2 \
556 --suppressions=valgrind.suppressions")
557
558 # "pedantic valgrind" will error on memory that is "Still Reachable".
559 # We only run this on OpenSSL 1.1.1 because there are hundreds of false positives in other libcryptos.
560 # Tracking issue: https://github.com/aws/s2n-tls/issues/4777
561 if ($ENV{S2N_LIBCRYPTO} MATCHES "openssl-1.1.1")
562 set(MEMORYCHECK_COMMAND_OPTIONS "${VALGRIND_DEFAULT} --run-libc-freeres=yes --errors-for-leak-kinds=all --show-leak-kinds=all")
563 else()
564 set(MEMORYCHECK_COMMAND_OPTIONS "${VALGRIND_DEFAULT} --run-libc-freeres=no")
565 endif()
566
567 set(MEMORYCHECK_TYPE "Valgrind")
568
569 set(UNIT_TEST_ENVS S2N_DONT_MLOCK=1)
570 if (TSAN OR ASAN)
571 set(UNIT_TEST_ENVS ${UNIT_TEST_ENVS} S2N_ADDRESS_SANITIZER=1)
572 endif()
573 if(TSAN)
574 set(TSAN_SUPPRESSIONS_FILE ${CMAKE_SOURCE_DIR}/tests/.tsan_suppressions)
575 if(NOT EXISTS ${TSAN_SUPPRESSIONS_FILE})
576 message(FATAL_ERROR "TSAN suppression file ${TSAN_SUPPRESSIONS_FILE} missing")
577 endif()
578 set(TSAN_OPTIONS suppressions=${TSAN_SUPPRESSIONS_FILE})
579 if(DEFINED ENV{TSAN_OPTIONS})
580 set(TSAN_OPTIONS "${TSAN_OPTIONS} $ENV{TSAN_OPTIONS}")
581 endif()
582 set(UNIT_TEST_ENVS ${UNIT_TEST_ENVS} TSAN_OPTIONS=${TSAN_OPTIONS})
583 endif()
584 if(ASAN)
585 # "detect_odr_violation" detects violations of the "one definition rule",
586 # ensuring that symbols are only defined once.
587 # But some of our unit tests intentionally include *.c files for testing,
588 # resulting in duplicate global values.
589 set(ASAN_OPTIONS detect_odr_violation=0)
590 if(DEFINED ENV{ASAN_OPTIONS})
591 set(ASAN_OPTIONS "${ASAN_OPTIONS} $ENV{ASAN_OPTIONS}")
592 endif()
593 set(UNIT_TEST_ENVS ${UNIT_TEST_ENVS} ASAN_OPTIONS=${ASAN_OPTIONS})
594 endif()
595 message(STATUS "Running tests with environment: ${UNIT_TEST_ENVS}")
596
597 include(CTest)
598
599 ############################################################################
600 ############################ build unit tests ##############################
601 ############################################################################
602
603 file(GLOB UNITTESTS_SRC "tests/unit/*.c")
604 if (WIN32)
605 set(S2N_WINDOWS_EXCLUDE_TESTS
606 # Tests that require kTLS
607 s2n_ktls_io_sendfile_test
608 s2n_ktls_io_test
609 s2n_ktls_test
610 s2n_ktls_test_utils_test
611 s2n_self_talk_ktls_test
612
613 # Tests that depend on POSIX socket close behavior: on Windows,
614 # closesocket() abruptly resets the connection and discards unread
615 # data, so the peer sees an I/O error instead of the buffered alert.
616 s2n_drain_alert_test
617
618 # Tests that require seccomp which is only available on Linux
619 s2n_seccomp_failure_test
620
621 # Tests that measure memory via /proc/self/statm and getrlimit() which are not
622 # available on Windows
623 s2n_mem_usage_test
624
625 # Tests that use fork()
626 s2n_examples_test
627 s2n_fragmentation_coalescing_test
628 s2n_handshake_test
629 s2n_init_test
630 s2n_io_test
631 s2n_key_update_threads_test
632 s2n_malformed_handshake_test
633 s2n_random_test
634 s2n_self_talk_alerts_test
635 s2n_self_talk_broken_pipe_test
636 s2n_self_talk_client_hello_cb_test
637 s2n_self_talk_nonblocking_test
638 s2n_self_talk_session_id_test
639 )
640 foreach(excluded ${S2N_WINDOWS_EXCLUDE_TESTS})
641 list(REMOVE_ITEM UNITTESTS_SRC
642 "${CMAKE_CURRENT_SOURCE_DIR}/tests/unit/${excluded}.c")
643 endforeach()
644 endif()
645 foreach(test_case ${UNITTESTS_SRC})
646 # NAME_WE: name without extension
647 get_filename_component(test_case_name ${test_case} NAME_WE)
648
649 add_executable(${test_case_name} ${test_case})
650 target_link_libraries(${test_case_name} PRIVATE testss2n)
651 if (S2N_INTERN_LIBCRYPTO)
652 # if libcrypto was interned, rewrite libcrypto symbols so use of internal functions will link correctly
653 add_custom_command(
654 TARGET ${test_case_name} PRE_LINK
655 COMMAND
656 find . -name '${test_case_name}.c.o' -exec objcopy --redefine-syms libcrypto.symbols {} \\\;
657 )
658 endif()
659 target_compile_options(${test_case_name} PRIVATE
660 -Wall -Wimplicit -Wunused -Wcomment -Wchar-subscripts -Wuninitialized
661 -Wshadow -Wcast-align -Wwrite-strings -Wformat-security
662 -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-deprecated -std=gnu99 -Wno-missing-braces
663 )
664 if (UNSAFE_TREAT_WARNINGS_AS_ERRORS)
665 target_compile_options(${test_case_name} PRIVATE -Werror)
666 endif()
667 if (S2N_LTO)
668 target_compile_options(${test_case_name} PRIVATE -flto)
669 endif()
670
671 add_test(
672 NAME ${test_case_name}
673 COMMAND $<TARGET_FILE:${test_case_name}>
674 WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/tests/unit
675 )
676 set_property(TEST ${test_case_name} PROPERTY LABELS "unit")
677 set_property(TEST ${test_case_name} PROPERTY ENVIRONMENT ${UNIT_TEST_ENVS})
678
679 endforeach(test_case)
680
681 ############################################################################
682 ######################### build utility binaries ###########################
683 ############################################################################
684
685 # s2nc/s2nd can't be built on Windows yet
686 if (NOT WIN32)
687 add_executable(s2nc "bin/s2nc.c" "bin/echo.c" "bin/https.c" "bin/common.c")
688 target_link_libraries(s2nc ${PROJECT_NAME})
689 target_compile_options(s2nc PRIVATE -std=gnu99)
690
691 add_executable(s2nd "bin/s2nd.c" "bin/echo.c" "bin/https.c" "bin/common.c")
692 target_link_libraries(s2nd ${PROJECT_NAME})
693 target_compile_options(s2nd PRIVATE -std=gnu99)
694
695 add_executable(policy "bin/policy.c")
696 target_link_libraries(policy ${PROJECT_NAME})
697 target_compile_options(policy PRIVATE -std=gnu99)
698
699 if(S2N_LTO)
700 target_compile_options(s2nc PRIVATE -flto)
701 target_compile_options(s2nd PRIVATE -flto)
702 endif()
703 endif()
704
705 if (S2N_INTEG_TESTS)
706 find_package (Python3 COMPONENTS Interpreter Development)
707 file(GLOB integv2_test_files "${PROJECT_SOURCE_DIR}/tests/integrationv2/test_*.py")
708 set(N 1)
709 if (S2N_FAST_INTEG_TESTS)
710 set(N auto)
711 endif()
712 foreach(test_file_path ${integv2_test_files})
713 get_filename_component(test_filename ${test_file_path} NAME_WE)
714 string(REGEX REPLACE "^test_" "integrationv2_" test_target ${test_filename})
715 if (S2N_INTEG_NIX)
716 # For Nix and environments where LD_LIBRARY_PATH is already correct.
717 # We're also dropping tox and calling pytest directly, because
718 # Nix is already handling all of the python setup.
719 if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" AND ${test_target} STREQUAL "integrationv2_sslyze" )
720 # sslyze/nassl is not available on aarch64.
721 message(WARNING "Skipping ${test_target} due to missing tools on ${CMAKE_SYSTEM_PROCESSOR}")
722 continue()
723 endif()
724 message(STATUS "Adding integ test ${test_target}")
725 add_test(NAME ${test_target}
726 COMMAND
727 pytest
728 -x -n=${N} --reruns=2 --durations=10 --cache-clear -rpfsq
729 --junitxml=../../build/junit/${test_target}.xml
730 -o log_cli=true --log-cli-level=DEBUG --provider-version=$ENV{S2N_LIBCRYPTO}
731 ${test_file_path}
732 WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/tests/integrationv2
733 )
734 else()
735 # For use with libcryptos built into test-deps, and not in LD_LIBRARY_PATH.
736 # This is a duplication of tests/integrationv2/Makefile and
737 # can go away once all the Nix porting is finished.
738 add_test(NAME ${test_target}
739 COMMAND
740 ${CMAKE_COMMAND} -E env
741 DYLD_LIBRARY_PATH=${PROJECT_SOURCE_DIR}/libcrypto-root/lib:$ENV{DYLD_LIBRARY_PATH}
742 LD_LIBRARY_PATH=${PROJECT_SOURCE_DIR}/libcrypto-root/lib:${PROJECT_SOURCE_DIR}/test-deps/openssl-1.1.1/lib:${PROJECT_SOURCE_DIR}/test-deps/gnutls37/nettle/lib:$ENV{LD_LIBRARY_PATH}
743 PATH=${PROJECT_SOURCE_DIR}/bin:${PROJECT_SOURCE_DIR}/test-deps/openssl-1.1.1/bin:${PROJECT_SOURCE_DIR}/test-deps/gnutls37/bin:$ENV{PATH}
744 PYTHONNOUSERSITE=1
745 S2N_INTEG_TEST=1
746 TOX_TEST_NAME=${test_file_path}
747 ${Python3_EXECUTABLE} -m tox
748 WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/tests/integrationv2)
749 endif()
750 set_property(TEST ${test_target} PROPERTY LABELS "integrationv2")
751 set_property(TEST ${test_target} PROPERTY TIMEOUT 7200)
752 endforeach()
753 endif()
754
755 if(S2N_FUZZ_TEST)
756 message(STATUS "Fuzz build enabled")
757 set(SCRIPT_PATH "${CMAKE_CURRENT_SOURCE_DIR}/tests/fuzz/runFuzzTest.sh")
758 file(GLOB FUZZ_TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/tests/fuzz/*.c")
759
760 file(GLOB TESTLIB_SRC "tests/testlib/*.c")
761 file(GLOB TESTLIB_HEADERS "tests/testlib/*.h" "tests/s2n_test.h")
762
763 # This must be a shared object so that symbols can be overridden by the
764 # fuzz test specific LD_PRELOAD libraries.
765 add_library(fuzztest SHARED ${TESTLIB_SRC})
766 target_include_directories(fuzztest PUBLIC tests)
767 target_compile_options(fuzztest PUBLIC -include "${S2N_PRELUDE}" -fPIC)
768 target_link_libraries(fuzztest PUBLIC ${PROJECT_NAME})
769
770 # Set default values for fuzzing
771 if(DEFINED ENV{FUZZ_TIMEOUT_SEC})
772 set(FUZZ_TIMEOUT_SEC $ENV{FUZZ_TIMEOUT_SEC})
773 else()
774 set(FUZZ_TIMEOUT_SEC 60)
775 endif()
776
777 # Build LD_PRELOAD shared libraries
778 file(GLOB LIBRARY_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/tests/fuzz/LD_PRELOAD/*.c")
779 foreach(SRC ${LIBRARY_SRCS})
780 get_filename_component(LIB_NAME ${SRC} NAME_WE)
781 add_library(${LIB_NAME} SHARED ${SRC})
782 target_include_directories(${LIB_NAME} PRIVATE
783 ${CMAKE_CURRENT_SOURCE_DIR}
784 ${CMAKE_CURRENT_SOURCE_DIR}/api
785 )
786 endforeach()
787
788 set(CMAKE_C_COMPILER clang)
789
790 foreach(src ${FUZZ_TEST_SRCS})
791 get_filename_component(TEST_NAME ${src} NAME_WE)
792
793 add_executable(${TEST_NAME} ${src})
794
795 target_compile_options(${TEST_NAME} PRIVATE
796 -g -Wno-unknown-pragmas -Wno-unused-result
797 )
798 target_link_options(${TEST_NAME} PRIVATE
799 -fsanitize=fuzzer -lstdc++
800 )
801 target_link_libraries(${TEST_NAME} PRIVATE
802 fuzztest
803 )
804
805 add_test(NAME ${TEST_NAME}
806 COMMAND ${CMAKE_COMMAND} -E env
807 bash ${SCRIPT_PATH}
808 ${TEST_NAME}
809 ${FUZZ_TIMEOUT_SEC}
810 ${CMAKE_CURRENT_SOURCE_DIR}
811 WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/tests/fuzz
812 )
813 set_property(TEST ${TEST_NAME} PROPERTY LABELS "fuzz")
814 endforeach()
815 endif()
816 endif()
817
818 #install the s2n files
819 install(FILES ${API_HEADERS} DESTINATION "include/" COMPONENT Development)
820 install(FILES ${API_UNSTABLE_HEADERS} DESTINATION "include/s2n/unstable" COMPONENT Development)
821
822 if (UNIX AND NOT APPLE)
823 include(GNUInstallDirs)
824 elseif(NOT DEFINED CMAKE_INSTALL_LIBDIR)
825 set(CMAKE_INSTALL_LIBDIR "lib")
826 endif()
827
828 if (S2N_INSTALL_S2NC_S2ND)
829 install(
830 TARGETS s2nc s2nd RUNTIME DESTINATION bin
831 )
832 endif()
833
834 install(
835 TARGETS ${PROJECT_NAME}
836 EXPORT ${PROJECT_NAME}-targets
837 ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT Development
838 LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT Runtime
839 RUNTIME DESTINATION bin COMPONENT Runtime
840 )
841
842 configure_file("cmake/${PROJECT_NAME}-config.cmake"
843 "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config.cmake"
844 @ONLY)
845
846 if (BUILD_SHARED_LIBS)
847 set (TARGET_DIR "shared")
848 else()
849 set (TARGET_DIR "static")
850 endif()
851
852 install(EXPORT "${PROJECT_NAME}-targets"
853 DESTINATION "${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}/cmake/${TARGET_DIR}"
854 NAMESPACE AWS::
855 COMPONENT Development)
856
857 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config.cmake"
858 DESTINATION "${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}/cmake/"
859 COMPONENT Development)
860
861 install(FILES "cmake/modules/Findcrypto.cmake"
862 DESTINATION "${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}/cmake/modules/"
863 COMPONENT Development)