Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 63 additions & 4 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ endif()

project(msquic)

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

# Set a default build type if none was specified
set(default_build_type "Release")

Expand Down Expand Up @@ -113,7 +115,28 @@ option(QUIC_USE_SYSTEM_LIBCRYPTO "Use system libcrypto if quictls TLS" OFF)
option(QUIC_USE_EXTERNAL_OPENSSL "Use external OpenSSL instead of building from submodules" OFF)
set(QUIC_OPENSSL_INCLUDE_DIR "" CACHE PATH "Path to OpenSSL include directory")
set(QUIC_OPENSSL_LIB_DIR "" CACHE PATH "Path to OpenSSL library directory")
set(QUIC_OPENSSL_SYMBOL_PREFIX "" CACHE STRING "If non-empty, namespace-prefix every symbol in the bundled OpenSSL static archives (Linux only) so the resulting binary can coexist in the same process with another OpenSSL copy. See docs/OpenSSLSymbolPrefix.md")
set(QUIC_OPENSSL_ROOT_DIR "" CACHE PATH "Path to OpenSSL root directory")

# Outer-most validation for QUIC_OPENSSL_SYMBOL_PREFIX so a value combined with
# a non-quictls/openssl TLS_LIB (e.g. schannel) errors loudly instead of being
# silently ignored, and so the prefix value is rejected before it is
# interpolated into objcopy --redefine-syms map lines or build-tree paths.
if(NOT "${QUIC_OPENSSL_SYMBOL_PREFIX}" STREQUAL "")
if(NOT (QUIC_TLS_LIB STREQUAL "quictls" OR QUIC_TLS_LIB STREQUAL "openssl"))
message(FATAL_ERROR
"QUIC_OPENSSL_SYMBOL_PREFIX requires QUIC_TLS_LIB=quictls or openssl "
"(got QUIC_TLS_LIB='${QUIC_TLS_LIB}'). The prefix only applies to the "
"bundled OpenSSL build path.")
endif()
if(NOT QUIC_OPENSSL_SYMBOL_PREFIX MATCHES "^[A-Za-z_][A-Za-z0-9_]*$")
message(FATAL_ERROR
"QUIC_OPENSSL_SYMBOL_PREFIX must match ^[A-Za-z_][A-Za-z0-9_]*$ "
"(got '${QUIC_OPENSSL_SYMBOL_PREFIX}'). The prefix is interpolated into "
"objcopy --redefine-syms map lines and into the build-tree path; "
"whitespace, '#', '/', leading digits, and shell metacharacters are unsafe.")
endif()
endif()
option(QUIC_HIGH_RES_TIMERS "Configure the system to use high resolution timers" OFF)
option(QUIC_OFFICIAL_RELEASE "Configured the build for an official release" OFF)
set(QUIC_FOLDER_PREFIX "" CACHE STRING "Optional prefix for source group folders when using an IDE generator")
Expand Down Expand Up @@ -811,10 +834,46 @@ if(QUIC_TLS_LIB STREQUAL "quictls" OR QUIC_TLS_LIB STREQUAL "openssl")
FetchContent_MakeAvailable(OpenSSLQuic)
endif()

target_link_libraries(OpenSSL
INTERFACE
MsQuic::OpenSSL
)
# Optional: namespace-prefix the bundled OpenSSL symbols so the resulting
# binary can coexist with another OpenSSL copy loaded into the same
# process. See docs/OpenSSLSymbolPrefix.md for motivation and caveats.
if(NOT "${QUIC_OPENSSL_SYMBOL_PREFIX}" STREQUAL "")
if(NOT CX_PLATFORM STREQUAL "linux")
message(FATAL_ERROR "QUIC_OPENSSL_SYMBOL_PREFIX is only supported on Linux today (got CX_PLATFORM=${CX_PLATFORM}).")
endif()
if(QUIC_USE_EXTERNAL_OPENSSL OR QUIC_OPENSSL_INCLUDE_DIR OR QUIC_OPENSSL_LIB_DIR OR QUIC_OPENSSL_ROOT_DIR)
message(FATAL_ERROR "QUIC_OPENSSL_SYMBOL_PREFIX requires the bundled OpenSSL build; do not combine with QUIC_USE_EXTERNAL_OPENSSL / QUIC_OPENSSL_INCLUDE_DIR / QUIC_OPENSSL_LIB_DIR / QUIC_OPENSSL_ROOT_DIR.")
endif()
if(QUIC_USE_SYSTEM_LIBCRYPTO)
message(FATAL_ERROR "QUIC_OPENSSL_SYMBOL_PREFIX is incompatible with QUIC_USE_SYSTEM_LIBCRYPTO; the system libcrypto cannot be renamed.")
endif()
# Block the shared-lib install path until the prefixed archives are
# wired into install(EXPORT). The prefixed target is INTERFACE IMPORTED
# GLOBAL and cannot be installed via install(TARGETS); a shared-lib
# install would either fail or produce a package that references
# build-tree-only paths under ${CMAKE_BINARY_DIR}/openssl-prefixed/.
# Static-lib consumers (the primary use case) are unaffected.
if(BUILD_SHARED_LIBS)
message(FATAL_ERROR "QUIC_OPENSSL_SYMBOL_PREFIX is currently only supported with BUILD_SHARED_LIBS=OFF (the shared-lib install path does not yet handle the prefixed imported target).")
endif()

include(PrefixOpenSSLArchives)
prefix_openssl_archives(
PREFIX "${QUIC_OPENSSL_SYMBOL_PREFIX}"
INPUT_TARGET OpenSSLQuic
OUTPUT_TARGET OpenSSLQuicPrefixed
)

target_link_libraries(OpenSSL
INTERFACE
OpenSSLQuicPrefixed
)
else()
target_link_libraries(OpenSSL
INTERFACE
MsQuic::OpenSSL
)
endif()
endif()

if (QUIC_USE_SYSTEM_LIBCRYPTO)
Expand Down
165 changes: 165 additions & 0 deletions cmake/PrefixOpenSSLArchives.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

#
# PrefixOpenSSLArchives
#
# Produce namespace-prefixed copies of the bundled OpenSSL static archives so
# the resulting MsQuic binary can coexist in the same process with a different
# copy of OpenSSL (e.g. a system `libcrypto.so.3` pulled in by an unrelated
# transitive dependency) without colliding on global C symbols.
#
# Mechanism: extract every globally-defined external symbol from the input
# archives and use `objcopy --redefine-syms` to rewrite the symbol table so
# both definitions and undefined references carry a `${QUIC_OPENSSL_SYMBOL_PREFIX}`
# prefix. The rename is applied to:
# - The bundled `libssl.a` and `libcrypto.a` (their *defined* symbols).
# - Any consumer's static archive that references OpenSSL (the *undefined*
# references inside, so they resolve against the prefixed archives at the
# final link step). For MsQuic this is `libmsquic_platform.a`, handled in
# `src/platform/CMakeLists.txt`.
#
# This is a Linux-only feature today. Honoring `${CMAKE_NM}` / `${CMAKE_OBJCOPY}`
# makes the rename step cross-compile-safe. macOS support would require
# `llvm-objcopy` >= 13 (untested); PE/COFF lacks a flat-namespace symbol table
# and would need a fundamentally different approach.
#
# Function:
# prefix_openssl_archives(
# PREFIX <symbol_prefix> # e.g. "msquic_"
# INPUT_TARGET <bundled-openssl-target> # INTERFACE target whose
# # INTERFACE_LINK_LIBRARIES
# # contains the .a paths
# OUTPUT_TARGET <new-interface-target> # name of the renamed target
# # to create
# )
#
# After the call:
# - INTERFACE IMPORTED target `<OUTPUT_TARGET>` exists with include dirs
# copied from `<INPUT_TARGET>` and link libs pointing at the renamed
# archives.
# - Two target properties carry the artifacts a consumer needs to apply the
# same rename to its own archive (e.g. `libmsquic_platform.a`):
# `PREFIX_RENAME_SYMS_FILE` absolute path to the redefine-syms file
# `PREFIX_RENAME_SCRIPT` absolute path to
# `cmake/openssl-prefix-rename.sh`
# Read them at the consumer site with `get_target_property()`.
#

# Capture this module's directory at parse time so the script-path lookup is
# independent of the parent build's `CMAKE_SOURCE_DIR` (which may not be
# msquic's own root when msquic is consumed via `add_subdirectory`).
set(_PREFIX_OPENSSL_SCRIPT "${CMAKE_CURRENT_LIST_DIR}/openssl-prefix-rename.sh")

function(prefix_openssl_archives)
set(options)
set(oneValueArgs PREFIX INPUT_TARGET OUTPUT_TARGET)
set(multiValueArgs)
cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

if(NOT ARG_PREFIX OR NOT ARG_INPUT_TARGET OR NOT ARG_OUTPUT_TARGET)
message(FATAL_ERROR "prefix_openssl_archives requires PREFIX, INPUT_TARGET, and OUTPUT_TARGET")
endif()

if(NOT TARGET ${ARG_INPUT_TARGET})
message(FATAL_ERROR "prefix_openssl_archives: INPUT_TARGET '${ARG_INPUT_TARGET}' does not exist")
endif()

# Pull the original archive paths off the INPUT_TARGET INTERFACE properties.
get_target_property(_openssl_libs ${ARG_INPUT_TARGET} INTERFACE_LINK_LIBRARIES)
get_target_property(_openssl_inc ${ARG_INPUT_TARGET} INTERFACE_INCLUDE_DIRECTORIES)

set(_orig_libssl)
set(_orig_libcrypto)
foreach(_lib IN LISTS _openssl_libs)
if(_lib MATCHES "libssl\\.a$")
set(_orig_libssl "${_lib}")
elseif(_lib MATCHES "libcrypto\\.a$")
set(_orig_libcrypto "${_lib}")
endif()
endforeach()

if(NOT _orig_libssl OR NOT _orig_libcrypto)
message(FATAL_ERROR
"prefix_openssl_archives: ${ARG_INPUT_TARGET} does not expose both libssl.a and libcrypto.a as plain archive paths on its INTERFACE_LINK_LIBRARIES. "
"Got INTERFACE_LINK_LIBRARIES='${_openssl_libs}', found libssl.a='${_orig_libssl}' libcrypto.a='${_orig_libcrypto}'. "
"This helper only handles bundled OpenSSL configurations whose interface points directly at the two static archives; "
"generator-expression-wrapped or target-name link items are not supported.")
endif()

set(_out_dir "${CMAKE_BINARY_DIR}/openssl-prefixed/${ARG_PREFIX}")
set(_syms_file "${_out_dir}/redefine.syms")
set(_renamed_libssl "${_out_dir}/libssl.a")
set(_renamed_libcrypto "${_out_dir}/libcrypto.a")
set(_script "${_PREFIX_OPENSSL_SCRIPT}")
Comment thread
leikong marked this conversation as resolved.

file(MAKE_DIRECTORY "${_out_dir}")

# Forward the cross-compile-aware nm/objcopy to the helper script. If
# ${CMAKE_NM} / ${CMAKE_OBJCOPY} are unset, the script falls back to its
# own defaults (plain `nm` / `objcopy`).
set(_env_args)
if(CMAKE_NM)
list(APPEND _env_args "NM=${CMAKE_NM}")
endif()
if(CMAKE_OBJCOPY)
list(APPEND _env_args "OBJCOPY=${CMAKE_OBJCOPY}")
endif()

add_custom_command(
OUTPUT "${_syms_file}"
DEPENDS "${_orig_libssl}" "${_orig_libcrypto}" "${_script}"
COMMAND ${CMAKE_COMMAND} -E env ${_env_args}
"${_script}" gen-syms "${ARG_PREFIX}" "${_syms_file}"
"${_orig_libssl}" "${_orig_libcrypto}"
COMMENT "Generating OpenSSL symbol prefix-map (prefix=${ARG_PREFIX})"
VERBATIM
)

add_custom_command(
OUTPUT "${_renamed_libssl}"
DEPENDS "${_orig_libssl}" "${_syms_file}" "${_script}"
COMMAND ${CMAKE_COMMAND} -E env ${_env_args}
"${_script}" apply "${_syms_file}" "${_orig_libssl}" "${_renamed_libssl}"
COMMENT "Prefix-renaming libssl.a (prefix=${ARG_PREFIX})"
VERBATIM
)

add_custom_command(
OUTPUT "${_renamed_libcrypto}"
DEPENDS "${_orig_libcrypto}" "${_syms_file}" "${_script}"
COMMAND ${CMAKE_COMMAND} -E env ${_env_args}
"${_script}" apply "${_syms_file}" "${_orig_libcrypto}" "${_renamed_libcrypto}"
COMMENT "Prefix-renaming libcrypto.a (prefix=${ARG_PREFIX})"
VERBATIM
)

add_custom_target(
${ARG_OUTPUT_TARGET}_Build
DEPENDS "${_renamed_libssl}" "${_renamed_libcrypto}" "${_syms_file}"
)

add_library(${ARG_OUTPUT_TARGET} INTERFACE IMPORTED GLOBAL)
Comment thread
leikong marked this conversation as resolved.
add_dependencies(${ARG_OUTPUT_TARGET} ${ARG_OUTPUT_TARGET}_Build)
set_target_properties(
${ARG_OUTPUT_TARGET}
PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${_openssl_inc}"
)
target_link_libraries(
${ARG_OUTPUT_TARGET}
INTERFACE "${_renamed_libssl}" "${_renamed_libcrypto}"
)

# Carry the syms file and helper-script paths on the output target itself
# (rather than as cache variables) so consumers retrieve them via
# get_target_property() at the call site, which keeps the dependency
# explicit and avoids polluting the cache.
set_property(TARGET ${ARG_OUTPUT_TARGET} PROPERTY PREFIX_RENAME_SYMS_FILE "${_syms_file}")
set_property(TARGET ${ARG_OUTPUT_TARGET} PROPERTY PREFIX_RENAME_SCRIPT "${_script}")

message(STATUS "Configured prefixed OpenSSL archives (${ARG_OUTPUT_TARGET}):")
message(STATUS " Prefix: ${ARG_PREFIX}")
message(STATUS " Syms file: ${_syms_file}")
message(STATUS " libssl.a: ${_renamed_libssl}")
message(STATUS " libcrypto.a: ${_renamed_libcrypto}")
endfunction()
112 changes: 112 additions & 0 deletions cmake/openssl-prefix-rename.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#!/bin/bash
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

# openssl-prefix-rename.sh
#
# Generate a symbol-prefix map from one or more static archives and apply it
# via `objcopy --redefine-syms` to produce renamed copies.
#
# Used by `cmake/PrefixOpenSSLArchives.cmake` to namespace-prefix the bundled
# OpenSSL static archives (and any consuming archive's undefined references)
# when `QUIC_OPENSSL_SYMBOL_PREFIX` is set. This lets the resulting binary
# coexist with another copy of OpenSSL loaded into the same process (e.g. a
# system `libcrypto.so.3` pulled in by a transitive dependency) without
# global-symbol collisions.
#
# Modes:
# gen-syms PREFIX OUT_SYMS_FILE INPUT_AR [INPUT_AR ...]
# Extract all defined external globals (nm types T/D/R/B/W/V/C) from the
# input archives, sort+unique, and emit `<sym> <PREFIX><sym>` lines.
#
# apply SYMS_FILE INPUT_AR OUTPUT_AR
# Copy INPUT_AR to OUTPUT_AR (skipped if same path) and run
# `objcopy --redefine-syms=SYMS_FILE` on the copy. The rename touches both
# definitions and undefined references inside the archive's member objects.
#
# Environment overrides (honored for cross-compilation):
# NM path to the binutils `nm` matching the target architecture
# (defaults to `nm`; host BFD multi-target usually works but
# `${CMAKE_NM}` is the safe choice)
# OBJCOPY path to the binutils `objcopy` matching the target architecture
# (defaults to `objcopy`)

set -euo pipefail

NM=${NM:-nm}
OBJCOPY=${OBJCOPY:-objcopy}

# Surface unusable tools as a clear configuration error instead of a generic
# "no such file or directory" from the underlying exec.
command -v "$NM" >/dev/null 2>&1 || { echo "$0: NM='$NM' not found" >&2; exit 1; }
command -v "$OBJCOPY" >/dev/null 2>&1 || { echo "$0: OBJCOPY='$OBJCOPY' not found" >&2; exit 1; }

usage() {
cat >&2 <<EOF
usage:
$0 gen-syms PREFIX OUT_SYMS_FILE INPUT_AR [INPUT_AR ...]
$0 apply SYMS_FILE INPUT_AR OUTPUT_AR

env (optional, for cross-compile):
NM (default: nm)
OBJCOPY (default: objcopy)
EOF
exit 2
}

cmd=${1:-}
shift || usage

case "$cmd" in
gen-syms)
[[ $# -ge 3 ]] || usage
prefix=$1
out_syms=$2
shift 2
# Defined-extern symbol-type filter:
# T/D/R/B = text / data / read-only / bss globals
# W/V/C = weak (func / object) and common
# I = STT_GNU_IFUNC (e.g. AES-NI/SHA-NI dispatch resolvers OpenSSL
# 3.x emits on x86_64); these are externally-visible defined
# symbols, so they must end up in the rename map or MsQuic's
# undefs to them won't get prefixed and unprefixed OpenSSL
# symbols will still leak through the consumer archive.
# Do NOT pipe nm's stderr to /dev/null: an unreadable archive, a wrong
# cross-compile nm, or a corrupt input file should surface its real error
# message in the custom-command log.
"$NM" --defined-only --extern-only "$@" \
| awk 'NF==3 && $2 ~ /^[TDRBWVCI]$/ {print $3}' \
| LC_ALL=C sort -u \
| awk -v p="$prefix" '{print $1 " " p $1}' \
> "$out_syms"
# A 0-line syms file would make `objcopy --redefine-syms` a no-op, leaving
# the build green with unprefixed symbols. Fail loudly instead.
[[ -s "$out_syms" ]] || {
echo "$0: gen-syms produced an empty syms file from: $*" >&2
echo "$0: (check that nm '$NM' supports the input archives and emits defined-extern globals)" >&2
exit 1
}
;;

apply)
[[ $# -eq 3 ]] || usage
syms=$1
in_ar=$2
out_ar=$3
# Always go through a temp file + atomic rename, even when in_ar and out_ar
# resolve to the same path (the POST_BUILD step on libmsquic_platform.a).
# POSIX rename(2) over an existing file is atomic, so an interrupted run
# cannot leave out_ar in a partially-rewritten (or un-renamed but
# fresh-mtime) state that the next build would mistake for up-to-date.
tmp="${out_ar}.tmp.$$"
trap 'rm -f -- "$tmp"' EXIT
cp -- "$in_ar" "$tmp"
"$OBJCOPY" --redefine-syms="$syms" "$tmp"
mv -- "$tmp" "$out_ar"
trap - EXIT
;;

*)
usage
Comment thread
leikong marked this conversation as resolved.
;;
esac
Loading
Loading