diff --git a/CMakeLists.txt b/CMakeLists.txt index 93bd702..6554027 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,14 +43,16 @@ endif (UNIX) add_subdirectory(deps) add_subdirectory(mod_datadog) -enable_testing() -add_subdirectory(test/unit-test) - -add_test( - NAME integration-tests - COMMAND uv run pytest - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/test -) -set_tests_properties(integration-tests PROPERTIES - ENVIRONMENT "HTTPD_MODULE_PATH=${CMAKE_BINARY_DIR}/mod_datadog/mod_datadog.so" -) +include(CTest) +if(BUILD_TESTING) + add_subdirectory(test/unit-test) + + add_test( + NAME integration-tests + COMMAND uv run pytest + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/test + ) + set_tests_properties(integration-tests PROPERTIES + ENVIRONMENT "HTTPD_MODULE_PATH=${CMAKE_BINARY_DIR}/mod_datadog/mod_datadog.so" + ) +endif() diff --git a/cmake/toolchains/aix-gnu-rules.cmake b/cmake/toolchains/aix-gnu-rules.cmake new file mode 100644 index 0000000..fd0e1de --- /dev/null +++ b/cmake/toolchains/aix-gnu-rules.cmake @@ -0,0 +1,12 @@ +# CMake's native AIX helper invokes dump. Use the GNU cross linker. +foreach(language C CXX) + set(CMAKE_${language}_ARCHIVE_CREATE " -X64 qc ") + set(CMAKE_${language}_ARCHIVE_APPEND " -X64 q ") + set(CMAKE_${language}_ARCHIVE_FINISH " -X64 ") + set(CMAKE_${language}_USE_IMPLICIT_LINK_DIRECTORIES_IN_RUNTIME_PATH 0) + set(CMAKE_${language}_LINK_FLAGS "") + set(CMAKE_SHARED_LIBRARY_CREATE_${language}_FLAGS "") + set(CMAKE_${language}_CREATE_SHARED_LIBRARY + " -shared -o ") +endforeach() +set(CMAKE_PLATFORM_REQUIRED_RUNTIME_PATH "") diff --git a/cmake/toolchains/aix.cmake b/cmake/toolchains/aix.cmake new file mode 100644 index 0000000..8d508f8 --- /dev/null +++ b/cmake/toolchains/aix.cmake @@ -0,0 +1,32 @@ +set(CMAKE_SYSTEM_NAME AIX) +set(CMAKE_SYSTEM_VERSION 7.3) +set(CMAKE_SYSTEM_PROCESSOR ppc64) + +set(AIX_TOOLCHAIN_ROOT "$ENV{AIX_TOOLCHAIN_ROOT}" CACHE PATH "AIX compiler and sysroot") +set(AIX_CXX_ROOT "$ENV{AIX_CXX_ROOT}" CACHE PATH "Threaded AIX 7.2 C++ runtime") +if(NOT EXISTS "${AIX_TOOLCHAIN_ROOT}/sysroot/usr/include") + message(FATAL_ERROR "Set AIX_TOOLCHAIN_ROOT to the extracted Datadog toolchain") +endif() +set(AIX_TRIPLE powerpc-ibm-aix7.3.0.0 CACHE STRING "Compiler target triplet") +set(CMAKE_C_COMPILER "${AIX_TOOLCHAIN_ROOT}/compiler/bin/${AIX_TRIPLE}-gcc") +set(CMAKE_CXX_COMPILER "${AIX_TOOLCHAIN_ROOT}/compiler/bin/${AIX_TRIPLE}-g++") +set(CMAKE_AR "${AIX_TOOLCHAIN_ROOT}/compiler/bin/${AIX_TRIPLE}-ar") +set(CMAKE_RANLIB "${AIX_TOOLCHAIN_ROOT}/compiler/bin/${AIX_TRIPLE}-ranlib") +set(CMAKE_NM "${AIX_TOOLCHAIN_ROOT}/compiler/bin/${AIX_TRIPLE}-nm") +set(CMAKE_SYSROOT "${AIX_TOOLCHAIN_ROOT}/sysroot") +set(CMAKE_SKIP_RPATH TRUE) +set(CMAKE_C_FLAGS_INIT "-maix64 -mcpu=powerpc64 -pthread -D_ALL_SOURCE") +set(CMAKE_CXX_FLAGS_INIT "-maix64 -mcpu=powerpc64 -pthread -D_ALL_SOURCE") +if(AIX_CXX_ROOT) + set(AIX_CXX_PLATFORM "${AIX_CXX_ROOT}/include/powerpc-ibm-aix7.2.0.0") + string(APPEND CMAKE_CXX_FLAGS_INIT + " -nostdinc++ -isystem ${AIX_CXX_ROOT}/include -isystem ${AIX_CXX_PLATFORM}/pthread/ppc64 -isystem ${AIX_CXX_PLATFORM}") + set(CMAKE_EXE_LINKER_FLAGS_INIT "-L${AIX_CXX_ROOT}/lib") + set(CMAKE_SHARED_LINKER_FLAGS_INIT "-L${AIX_CXX_ROOT}/lib") +endif() +set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES AIX_TOOLCHAIN_ROOT AIX_TRIPLE AIX_CXX_ROOT) +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) +set(CMAKE_USER_MAKE_RULES_OVERRIDE "${CMAKE_CURRENT_LIST_DIR}/aix-gnu-rules.cmake") diff --git a/deps/dd-trace-cpp b/deps/dd-trace-cpp index be1ce6f..14ee98b 160000 --- a/deps/dd-trace-cpp +++ b/deps/dd-trace-cpp @@ -1 +1 @@ -Subproject commit be1ce6f2d94bd945504b1402df7c2837bf7999e5 +Subproject commit 14ee98b53e78f9bb25c761d35aa06313a9baeb79 diff --git a/doc/aix.md b/doc/aix.md new file mode 100644 index 0000000..c2df9c8 --- /dev/null +++ b/doc/aix.md @@ -0,0 +1,54 @@ +# Experimental AIX cross-build + +This prototype builds the tracing module for 64-bit, big-endian AIX against +stock Apache 2.4.66. RUM is disabled. Loading, HTTP requests and incoming +trace propagation passed on AIX 7.2 TL5 SP11 under QEMU POWER7, with both +prefork and worker MPMs. AIX 7.3 and IBM HTTP Server (IHS) remain untested. + +The prototype used GCC 13.4.0, an AIX 7.3 system sysroot, and IBM GCC 13.3.0 +threaded ppc64 C++ headers and runtime libraries built for AIX 7.2. The +cross-toolchain's default C++ runtime lacked threading support. +The tracer uses pthread keys for its AIX random generators because this +GNU linker's hidden C++ TLS common symbols produce invalid loader metadata. +Native thread-exit and fork-reseed regression tests pass with the workaround. + +Provide these external inputs: + +- `AIX_TOOLCHAIN_ROOT`: a directory containing `compiler/bin/` and + `sysroot/usr/include/`, with a licensed AIX sysroot. +- `AIX_CXX_ROOT`: the threaded runtime under `lib/`, and matching headers + under `include/`. The target headers are under + `include/powerpc-ibm-aix7.2.0.0/pthread/ppc64/`. +- `HTTPD_SRC_DIR`: a writable SDK tree containing `include/`, + `srclib/apr/include/`, `srclib/apr-util/include/`, `httpd.exp`, and + `lib/libapr-1.so.0` plus `lib/libaprutil-1.so.0`. The prototype used IBM's + AIX 7.1 Apache 2.4.66, APR 1.7.4, and APR-util 1.6.3 packages. + +```sh +export AIX_TOOLCHAIN_ROOT=/path/to/aix-cross +export AIX_CXX_ROOT=/path/to/threaded-aix72-cxx +export HTTPD_SRC_DIR=/path/to/apache-aix-sdk +bash scripts/build-aix.sh +``` + +The result is `build-aix/mod_datadog/mod_datadog.so`. The script generates +APR import lists from the SDK's actual exports. The module uses the native +Apache export file and retains APR and APR-util as host dependencies. +Its default loader path includes `/opt/datadog-httpd/lib` and +`/opt/freeware/lib64`; set `LIBPATH` appropriately for a test installation. + +The build verified XCOFF64 output and matched 7 Apache, 6 APR, and 1 APR-util +imports against those SDK binaries. Native testing covers the AIX level and +Apache configuration above. IHS requires matching headers, +module magic, exports, and APR libraries. Rebuild with an AIX 7.2 baseline +and the actual IHS SDK, then test loading, requests, and trace propagation. +Do not reuse AIX 7.3 feature-check caches for an AIX 7.2 sysroot. + +With `bin/httpd_64` in the SDK, the build script also runs the host-side +XCOFF loader check, including TLS relocation targets. The original broken +TLS artifact is rejected by this check. It can be run separately without +executing AIX code: + +```sh +python3 test/aix/check_module.py build-aix/mod_datadog/mod_datadog.so "$HTTPD_SRC_DIR" +``` diff --git a/mod_datadog/CMakeLists.txt b/mod_datadog/CMakeLists.txt index 7281181..056d992 100644 --- a/mod_datadog/CMakeLists.txt +++ b/mod_datadog/CMakeLists.txt @@ -122,6 +122,16 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") set(EXPORTED_SYMBOLS ${CMAKE_CURRENT_LIST_DIR}/symbols.ld-prime) set_target_properties(mod_datadog PROPERTIES LINK_DEPENDS ${EXPORTED_SYMBOLS}) target_link_options(mod_datadog PRIVATE "-Wl,-exported_symbols_list" "-Wl,${EXPORTED_SYMBOLS}") +elseif(CMAKE_SYSTEM_NAME STREQUAL "AIX") + set(EXPORTED_SYMBOLS ${CMAKE_CURRENT_LIST_DIR}/symbols.exp) + set_target_properties(mod_datadog PROPERTIES LINK_DEPENDS + "${EXPORTED_SYMBOLS};${HTTPD_SRC_DIR}/httpd.exp;${HTTPD_SRC_DIR}/apr.exp;${HTTPD_SRC_DIR}/aprutil.exp") + target_link_options(mod_datadog PRIVATE + "-Wl,-bE:${EXPORTED_SYMBOLS}" + "-Wl,-bI:${HTTPD_SRC_DIR}/httpd.exp" + "-Wl,-bI:${HTTPD_SRC_DIR}/apr.exp" + "-Wl,-bI:${HTTPD_SRC_DIR}/aprutil.exp" + "-Wl,-blibpath:/opt/datadog-httpd/lib:/opt/freeware/lib64:/usr/lib:/lib") endif() if(HTTPD_DATADOG_VERIFY_NEEDED) diff --git a/mod_datadog/symbols.exp b/mod_datadog/symbols.exp new file mode 100644 index 0000000..fd6d03f --- /dev/null +++ b/mod_datadog/symbols.exp @@ -0,0 +1,3 @@ +datadog_module +mod_datadog_version +mod_datadog_version_string diff --git a/scripts/build-aix.sh b/scripts/build-aix.sh new file mode 100755 index 0000000..4c0b58a --- /dev/null +++ b/scripts/build-aix.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +source_dir=${HTTPD_DATADOG_SOURCE:-$root} +sdk=${HTTPD_SRC_DIR:?Set HTTPD_SRC_DIR to the extracted native AIX Apache SDK} +toolchain_root=${AIX_TOOLCHAIN_ROOT:?Set AIX_TOOLCHAIN_ROOT to the extracted toolchain} +cxx_root=${AIX_CXX_ROOT:?Set AIX_CXX_ROOT to the threaded AIX 7.2 runtime} +build_dir=${HTTPD_AIX_BUILD_DIR:-$root/build-aix} +cxx_platform="$cxx_root/include/powerpc-ibm-aix7.2.0.0" +cxx_flags="-maix64 -mcpu=powerpc64 -pthread -D_ALL_SOURCE -nostdinc++" +cxx_flags+=" -isystem $cxx_root/include -isystem $cxx_platform/pthread/ppc64 -isystem $cxx_platform" +python3 "$root/scripts/prepare-aix-imports.py" "$sdk" "$toolchain_root" "${AIX_TRIPLE:-powerpc-ibm-aix7.3.0.0}" +cache_args=() +if [[ -n ${AIX_FEATURE_CACHE:-} ]]; then + cache_args=(-C "$AIX_FEATURE_CACHE") +fi +cmake "${cache_args[@]}" -S "$source_dir" -B "$build_dir" \ + -DCMAKE_TOOLCHAIN_FILE="$root/cmake/toolchains/aix.cmake" \ + -DAIX_TOOLCHAIN_ROOT="$toolchain_root" -DAIX_CXX_ROOT="$cxx_root" \ + -DAIX_TRIPLE="${AIX_TRIPLE:-powerpc-ibm-aix7.3.0.0}" \ + -DCMAKE_C_FLAGS="-maix64 -mcpu=powerpc64 -pthread -D_ALL_SOURCE" \ + -DCMAKE_CXX_FLAGS="$cxx_flags" \ + -DCMAKE_EXE_LINKER_FLAGS="-L$cxx_root/lib" \ + -DCMAKE_SHARED_LINKER_FLAGS="-L$cxx_root/lib" \ + -DHTTPD_SRC_DIR="$sdk" -DHTTPD_DATADOG_ENABLE_RUM=OFF \ + -DBUILD_TESTING=OFF -DDD_TRACE_BUILD_TESTING=OFF \ + -DCMAKE_BUILD_TYPE=Release +cmake --build "$build_dir" --parallel "${BUILD_JOBS:-6}" --target mod_datadog +if [[ -f "$sdk/bin/httpd_64" ]]; then + python3 "$root/test/aix/check_module.py" "$build_dir/mod_datadog/mod_datadog.so" "$sdk" +fi diff --git a/scripts/prepare-aix-imports.py b/scripts/prepare-aix-imports.py new file mode 100755 index 0000000..96f6588 --- /dev/null +++ b/scripts/prepare-aix-imports.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Create APR import files from the native AIX SDK's exported symbols.""" + +from pathlib import Path +import subprocess +import sys + +sdk, compiler = map(Path, sys.argv[1:3]) +triple = sys.argv[3] if len(sys.argv) > 3 else "powerpc-ibm-aix7.3.0.0" +nm = compiler / f"compiler/bin/{triple}-nm" +for library, output in (("libapr-1.so.0", "apr.exp"), ("libaprutil-1.so.0", "aprutil.exp")): + text = subprocess.check_output( + [str(nm), "--dynamic", "--extern-only", "--defined-only", str(sdk / "lib" / library)], + text=True, + ) + symbols = {line.split()[-1] for line in text.splitlines() if line and not line.endswith(":")} + names = {name for name in symbols if name.startswith("apr_")} + if not names: + raise SystemExit(f"No APR exports in {library}") + entries = names | {"." + name for name in names} + content = f"#! {library}\n" + "\n".join(sorted(entries)) + "\n" + path = sdk / output + if not path.exists() or path.read_text() != content: + path.write_text(content) diff --git a/test/aix/check_module.py b/test/aix/check_module.py new file mode 100644 index 0000000..92ca3bb --- /dev/null +++ b/test/aix/check_module.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Check the linked AIX module against native Apache and APR loader exports.""" + +from pathlib import Path +import struct +import sys + + +def read_loader(path): + data = path.read_bytes() + magic, sections, _, _, optional, _, _ = struct.unpack_from('>HHIQHHI', data) + assert magic == 0x1f7, 'Expected 64-bit big-endian AIX XCOFF' + section_names = set() + raw = None + for index in range(sections): + section = struct.unpack_from('>8sQQQqqqIII4x', data, 24 + optional + 72 * index) + name = section[0].rstrip(b'\0').decode() + section_names.add(name) + if name == '.loader': + raw = section[4] + assert raw is not None, 'No XCOFF loader section' + header = struct.unpack_from('>6I4q', data, raw) + (_, symbol_count, relocation_count, _, import_count, _, import_offset, + strings_offset, symbols_offset, relocations_offset) = header + cursor = raw + import_offset + imports = [] + for index in range(import_count): + fields = [] + for _ in range(3): + end = data.index(b'\0', cursor) + fields.append(data[cursor:end].decode()) + cursor = end + 1 + imports.append(dict(zip(('path', 'base', 'member'), fields))) + exports = [] + imported_symbols = [] + storage_classes = [] + for index in range(symbol_count): + _, offset, _, kind, storage, file_id, _ = struct.unpack_from( + '>QIHBBII', data, raw + symbols_offset + index * 24 + ) + storage_classes.append(storage) + start = raw + strings_offset + offset + end = data.index(b'\0', start) + name = data[start:end].decode() + if kind & 0x10: + exports.append(name) + if kind & 0x40: + imported_symbols.append({'name': name, 'file_id': file_id}) + relocations = [ + struct.unpack_from('>QHHi', data, raw + relocations_offset + index * 16) + for index in range(relocation_count) + ] + return {"imports": imports, "exports": set(exports), "symbols": imported_symbols, + "sections": section_names, "storage_classes": storage_classes, + "relocations": relocations} + + +def check_tls(module): + for address, kind, _, symbol in module["relocations"]: + if not 0x20 <= kind & 0xff <= 0x25: + continue + message = f"Invalid TLS loader relocation at {address:#x}" + if symbol in (-1, -2): + section = ".tdata" if symbol == -1 else ".tbss" + assert section in module["sections"], message + else: + assert 3 <= symbol < len(module["storage_classes"]) + 3, message + assert module["storage_classes"][symbol - 3] in (20, 21), message + + +def main(): + module_path, sdk = map(Path, sys.argv[1:]) + module = read_loader(module_path) + check_tls(module) + required = {"datadog_module", "mod_datadog_version", "mod_datadog_version_string"} + assert required <= module["exports"], "Missing Apache module exports" + assert all(symbol["file_id"] for symbol in module["symbols"]), "Unbound loader import" + allowed = {"/opt/datadog-httpd/lib", "/opt/freeware/lib64", "/usr/lib", "/lib", ""} + for entry in module["imports"]: + assert set(entry["path"].split(":")) <= allowed, "Unexpected loader path" + providers = { + ".": sdk / "bin/httpd_64", + "libapr-1.so.0": sdk / "lib/libapr-1.so.0", + "libaprutil-1.so.0": sdk / "lib/libaprutil-1.so.0", + } + for name, path in providers.items(): + needed = { + symbol["name"] for symbol in module["symbols"] + if module["imports"][symbol["file_id"]]["base"] == name + } + assert needed, f"No imports from {name}" + missing = needed - read_loader(path)["exports"] + assert not missing, f"{name}: missing exports {sorted(missing)}" + print(f"{name}: {len(needed)} imports verified") + + +if __name__ == "__main__": + main()