diff --git a/spark_transport/libsircl/CMakeLists.txt b/spark_transport/libsircl/CMakeLists.txt index 0584dba4..b3b79b96 100644 --- a/spark_transport/libsircl/CMakeLists.txt +++ b/spark_transport/libsircl/CMakeLists.txt @@ -123,8 +123,9 @@ target_link_options(sircl PRIVATE -Wl,-soname,libnccl.so.2 -Wl,-Bsymbolic-functi ${LIBSIRCL_HARDENING_LINK}) add_dependencies(sircl vendored_sources_guard) -# Companion SIRCL-EP shared library: strictly isolated from libnccl.so.2, linked against libsircl via the -# generic sirclP2pChannelExec bridge and exporting only sirclEp* symbols (exports_ep.map). +# Companion SIRCL-EP shared library: strictly isolated from libnccl.so.2, resolving the generic +# sirclP2pChannelExec bridge dynamically (no DT_NEEDED libnccl.so.2 edge that could collide with +# stock NVIDIA libnccl.so.2) and exporting only sirclEp* symbols (exports_ep.map). add_library(sircl_ep SHARED src/ep.c src/ep_pack.c src/cuda_api.c $) target_compile_features(sircl_ep PRIVATE c_std_11) target_compile_definitions(sircl_ep PUBLIC LIBSIRCL_CPU_ONLY NCCL_OS_LINUX @@ -132,7 +133,8 @@ target_compile_definitions(sircl_ep PUBLIC LIBSIRCL_CPU_ONLY NCCL_OS_LINUX SCCL_PACK_ARCHITECTURES="${LIBSIRCL_PACK_ARCHITECTURES}") target_include_directories(sircl_ep PUBLIC include PRIVATE src) target_compile_options(sircl_ep PRIVATE -Wall -Wextra -Werror -Wno-format-truncation ${LIBSIRCL_HARDENING_COMPILE}) -target_link_libraries(sircl_ep PRIVATE sircl Threads::Threads ${CMAKE_DL_LIBS}) +target_link_libraries(sircl_ep PRIVATE Threads::Threads ${CMAKE_DL_LIBS}) +add_dependencies(sircl_ep sircl) set_target_properties(sircl_ep PROPERTIES NO_SONAME TRUE SUFFIX ".so.${PROJECT_VERSION}" BUILD_RPATH "$ORIGIN") target_link_options(sircl_ep PRIVATE -Wl,-soname,libsircl_ep.so.0 -Wl,-Bsymbolic-functions -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/exports_ep.map ${LIBSIRCL_HARDENING_LINK}) diff --git a/spark_transport/libsircl/Makefile b/spark_transport/libsircl/Makefile index 3836901f..54299e29 100644 --- a/spark_transport/libsircl/Makefile +++ b/spark_transport/libsircl/Makefile @@ -161,12 +161,13 @@ $(BUILD)/libsircl.so: $(BUILD)/libsircl.so.$(VERSION) $(filter $(BUILD)/transport/%.o,$(OBJECTS)): Makefile $(BUILD)/libsircl.so.$(VERSION): $(OBJECTS) exports.map $(BUILD)/entries.ok Makefile $(CC) -shared -pthread $(LDFLAGS) $(HARDENING_LDFLAGS) -Wl,-soname,libnccl.so.2 -Wl,-Bsymbolic-functions -Wl,--version-script=exports.map -o $@ $(OBJECTS) -ldl -# Companion SIRCL-EP shared library: strictly isolated from libnccl.so.2, linked against libnccl.so.2 via -# the generic sirclP2pChannelExec bridge and exporting only sirclEp* symbols (exports_ep.map). +# Companion SIRCL-EP shared library: strictly isolated from libnccl.so.2, resolving the +# generic sirclP2pChannelExec bridge dynamically (no DT_NEEDED libnccl.so.2 edge that could +# collide with NVIDIA's stock libnccl.so.2) and exporting only sirclEp* symbols (exports_ep.map). $(BUILD)/libsircl_ep.so: $(BUILD)/libsircl_ep.so.$(VERSION) ln -sf libsircl_ep.so.$(VERSION) $@ $(BUILD)/libsircl_ep.so.$(VERSION): $(EP_OBJECTS) $(BUILD)/libsircl.so.$(VERSION) exports_ep.map $(BUILD)/entries.ok Makefile - $(CC) -shared -pthread $(LDFLAGS) $(HARDENING_LDFLAGS) -Wl,-soname,libsircl_ep.so.0 -Wl,-Bsymbolic-functions -Wl,--version-script=exports_ep.map -Wl,-rpath,'$$ORIGIN' -o $@ $(EP_OBJECTS) $(BUILD)/libsircl.so.$(VERSION) -ldl + $(CC) -shared -pthread $(LDFLAGS) $(HARDENING_LDFLAGS) -Wl,-soname,libsircl_ep.so.0 -Wl,-Bsymbolic-functions -Wl,--version-script=exports_ep.map -Wl,-rpath,'$$ORIGIN' -o $@ $(EP_OBJECTS) -ldl # The kernel-entry check (tests/check_entries.c): the library's pack loader runs on the embedded fatbins # through a stand-in CUDA driver (tests/fake_cuda.c) that reads their cubins offline, so every entry the diff --git a/spark_transport/libsircl/src/ep.c b/spark_transport/libsircl/src/ep.c index f9c0420f..1faa51da 100644 --- a/spark_transport/libsircl/src/ep.c +++ b/spark_transport/libsircl/src/ep.c @@ -3,10 +3,13 @@ * (sirclP2pChannelExec). */ #define _GNU_SOURCE +#include #include #include +#include #include #include +#include #include #include #include @@ -44,6 +47,92 @@ static pthread_mutex_t ep_coop_lock = PTHREAD_MUTEX_INITIALIZER; static ep_coop_entry ep_coop_cache[EP_COOP_CACHE_SLOTS]; static int ep_coop_count; +typedef ncclResult_t (*ep_p2p_exec_fn)(ncclComm_t, cudaStream_t, const char *, ncclDataType_t, int, int, unsigned, + sircl_p2p_channel_fn, void *); + +static pthread_mutex_t ep_bridge_lock = PTHREAD_MUTEX_INITIALIZER; +static _Atomic uintptr_t ep_p2p_exec_cached; + +static int ep_find_bridge_phdr(struct dl_phdr_info *info, size_t size, void *data) { + (void)size; + void **out = (void **)data; + if (!info->dlpi_name || !info->dlpi_name[0]) return 0; + /* Skip our own shared object and virtual kernel objects. */ + if (strstr(info->dlpi_name, "libsircl_ep") || info->dlpi_name[0] == '[') return 0; + void *h = dlopen(info->dlpi_name, RTLD_LAZY | RTLD_NOLOAD | RTLD_LOCAL); + if (!h) return 0; + void *sym = dlsym(h, "sirclP2pChannelExec"); + if (sym) { + /* Keep handle reference alive so libsircl cannot be unloaded beneath libsircl_ep. */ + *out = sym; + return 1; + } + dlclose(h); + return 0; +} + +/* Resolve sirclP2pChannelExec without a DT_NEEDED edge to libnccl.so.2. + * + * libsircl.so intentionally carries SONAME=libnccl.so.2; linking libsircl_ep.so + * directly against it records DT_NEEDED libnccl.so.2, which collides with NVIDIA's + * stock libnccl.so.2 whenever a process (such as `import torch` or a serving + * container's default LD_PRELOAD) maps stock NCCL before ctypes loads libsircl.so. + * Resolving via RTLD_DEFAULT first, then scanning already-loaded shared objects + * via dl_iterate_phdr (matching RTLD_LOCAL loads of any filename), and finally + * opening sibling libsircl.so avoids that SONAME collision cleanly. */ +static ep_p2p_exec_fn ep_resolve_p2p_exec(void) { + uintptr_t cached = atomic_load_explicit(&ep_p2p_exec_cached, memory_order_acquire); + if (cached) { + ep_p2p_exec_fn fn; + memcpy(&fn, &cached, sizeof fn); + return fn; + } + + pthread_mutex_lock(&ep_bridge_lock); + cached = atomic_load_explicit(&ep_p2p_exec_cached, memory_order_relaxed); + if (cached) { + pthread_mutex_unlock(&ep_bridge_lock); + ep_p2p_exec_fn fn; + memcpy(&fn, &cached, sizeof fn); + return fn; + } + + void *sym = dlsym(RTLD_DEFAULT, "sirclP2pChannelExec"); + if (!sym) dl_iterate_phdr(ep_find_bridge_phdr, &sym); + if (!sym) { + Dl_info dli; + if (dladdr((const void *)&sirclEpWorkspaceBytes, &dli) && dli.dli_fname && dli.dli_fname[0]) { + const char *slash = strrchr(dli.dli_fname, '/'); + size_t dir_len = slash ? (size_t)(slash - dli.dli_fname) : 0; + const char *names[] = { + "libsircl.so", +#ifdef LIBSIRCL_VERSION + "libsircl.so." LIBSIRCL_VERSION, +#endif + }; + for (size_t n = 0; n < sizeof(names) / sizeof(names[0]) && !sym; ++n) { + char path[PATH_MAX]; + int written = dir_len > 0 ? snprintf(path, sizeof path, "%.*s/%s", (int)dir_len, dli.dli_fname, names[n]) + : snprintf(path, sizeof path, "%s", names[n]); + if (written <= 0 || (size_t)written >= sizeof path) continue; + void *h = dlopen(path, RTLD_LAZY | RTLD_LOCAL); + if (!h) continue; + sym = dlsym(h, "sirclP2pChannelExec"); + if (!sym) dlclose(h); + } + } + } + + ep_p2p_exec_fn fn = NULL; + if (sym) { + uintptr_t raw = (uintptr_t)sym; + memcpy(&fn, &raw, sizeof fn); + atomic_store_explicit(&ep_p2p_exec_cached, raw, memory_order_release); + } + pthread_mutex_unlock(&ep_bridge_lock); + return fn; +} + /* Ensure the EP kernel pack is loaded for info->cuda_ctx and verify cooperative * launch co-residency for 2 * world CTAs once per (ctx, device, world). */ static ncclResult_t ep_prepare_kernels(const sircl_p2p_channel_info *info, const char *what, ep_coop_entry *out, @@ -271,8 +360,9 @@ ncclResult_t sirclEpDispatch(const void *hidden_in, const int *topk_ids_in, cons recv_counts_out, workspace, workspace_bytes, num_tokens, max_tokens, hidden_bytes, top_k, num_experts, (sccl_CUstream)stream, }; - return sirclP2pChannelExec(comm, stream, "sirclEpDispatch", ncclUint8, 3, 1, SIRCL_P2P_EXT_OP_0, ep_dispatch_cb, - &ctx); + ep_p2p_exec_fn exec = ep_resolve_p2p_exec(); + if (!exec) return ncclSystemError; + return exec(comm, stream, "sirclEpDispatch", ncclUint8, 3, 1, SIRCL_P2P_EXT_OP_0, ep_dispatch_cb, &ctx); } typedef struct { @@ -374,5 +464,7 @@ ncclResult_t sirclEpCombine(const void *expert_out_in, void *hidden_out, void *w expert_out_in, hidden_out, workspace, workspace_bytes, num_tokens, max_tokens, hidden_dim, datatype, (sccl_CUstream)stream, }; - return sirclP2pChannelExec(comm, stream, "sirclEpCombine", datatype, 3, 1, SIRCL_P2P_EXT_OP_1, ep_combine_cb, &ctx); + ep_p2p_exec_fn exec = ep_resolve_p2p_exec(); + if (!exec) return ncclSystemError; + return exec(comm, stream, "sirclEpCombine", datatype, 3, 1, SIRCL_P2P_EXT_OP_1, ep_combine_cb, &ctx); } diff --git a/spark_transport/libsircl/tests/test_abi.py b/spark_transport/libsircl/tests/test_abi.py index dce29b51..73bce0de 100644 --- a/spark_transport/libsircl/tests/test_abi.py +++ b/spark_transport/libsircl/tests/test_abi.py @@ -81,7 +81,9 @@ def test_companion_ep_library_exported_symbol_set(self): self.assertEqual(exported, {"sirclEpWorkspaceBytes", "sirclEpDispatch", "sirclEpCombine"}) dynamic = run("readelf", "-d", str(ep_lib)) self.assertRegex(dynamic, r"\(SONAME\).*\[libsircl_ep\.so\.0\]") - self.assertRegex(dynamic, r"\(NEEDED\).*\[libnccl\.so\.2\]") + # Resolve sirclP2pChannelExec dynamically so libsircl_ep.so never binds against a + # stock NVIDIA libnccl.so.2 mapped by import torch or container LD_PRELOAD. + self.assertNotRegex(dynamic, r"\(NEEDED\).*\[libnccl\.so\.2\]") def test_soname_and_runtime_dependencies(self): dynamic = run("readelf", "-d", str(LIBRARY)) diff --git a/spark_transport/libsircl/tests/test_libsircl_hardening.py b/spark_transport/libsircl/tests/test_libsircl_hardening.py index 27a2bb1c..b3cb3a4e 100644 --- a/spark_transport/libsircl/tests/test_libsircl_hardening.py +++ b/spark_transport/libsircl/tests/test_libsircl_hardening.py @@ -17,6 +17,7 @@ from __future__ import annotations import os +import re import subprocess import sys import tempfile @@ -486,7 +487,17 @@ def setUpClass(cls): [cc, "-shared", "-pthread", "-Wl,-soname,libsircl_ep.so.0", f"-Wl,--version-script={ROOT / 'exports_ep.map'}", "-Wl,-rpath,$ORIGIN", - "-o", str(cls.ep_lib), *ep_objs, str(cls.lib), "-ldl"], + "-o", str(cls.ep_lib), *ep_objs, "-ldl"], + check=True, + ) + + # Dummy competing libnccl.so.2 (without sirclP2pChannelExec) simulating NVIDIA stock NCCL. + cls.dummy_nccl = tmp / "libnccl_stock_stub.so" + dummy_nccl_c = tmp / "dummy_nccl.c" + dummy_nccl_c.write_text("int ncclGetVersion(int *v) { if (v) *v = 23203; return 0; }\n", encoding="utf-8") + subprocess.run( + [cc, "-std=c11", "-O2", "-fPIC", "-shared", "-Wl,-soname,libnccl.so.2", + "-o", str(cls.dummy_nccl), str(dummy_nccl_c)], check=True, ) @@ -500,12 +511,27 @@ def _run_group(self, mode: str, world: int, extra_env: dict[str, str] | None = N uid_file = Path(d) / "uid.bin" fabric = f"/sircl-emu-hard-{os.getpid()}-{mode}" base_env = dict(os.environ) + # Keep only ASan runtime in LD_PRELOAD (matching test_abi.py / test_engine_cpu.py) + # so serving containers that preload stock NVIDIA libnccl.so.2 do not pollute workers. + preloads = [ + entry for entry in re.split(r"[:\s]+", base_env.get("LD_PRELOAD", "")) + if entry and re.fullmatch(r"libasan\.so(?:\.\d+)*|libclang_rt\.asan.*\.so", Path(entry).name) + ] + if preloads: + base_env["LD_PRELOAD"] = ":".join(preloads) + else: + base_env.pop("LD_PRELOAD", None) base_env["LD_LIBRARY_PATH"] = f"{self.fake_cuda_dir}:{base_env.get('LD_LIBRARY_PATH', '')}" base_env["LIBSIRCL_TRANSPORT"] = "emulation" base_env["SIRCL_EMU_FABRIC"] = fabric base_env["SIRCL_BOOTSTRAP_ADDR"] = "127.0.0.1" if extra_env: - base_env.update(extra_env) + if "LD_PRELOAD" in extra_env and preloads: + merged = ":".join([*preloads, extra_env["LD_PRELOAD"]]) + base_env.update(extra_env) + base_env["LD_PRELOAD"] = merged + else: + base_env.update(extra_env) procs = [ subprocess.Popen( [sys.executable, str(self.worker), mode, str(world), str(rank), @@ -539,6 +565,25 @@ def test_ep_symbols_isolated_to_companion_library(self): ep_syms = subprocess.check_output(["nm", "-D", "--defined-only", str(self.ep_lib)], text=True) ep_exported = {line.split()[-1].split("@")[0] for line in ep_syms.splitlines() if line.split()} self.assertEqual(ep_exported, {"sirclEpWorkspaceBytes", "sirclEpDispatch", "sirclEpCombine"}) + ep_dyn = subprocess.check_output(["readelf", "-dW", str(self.ep_lib)], text=True) + self.assertNotIn("[libnccl.so.2]", ep_dyn, + "libsircl_ep.so must not carry DT_NEEDED libnccl.so.2 (collides with stock NCCL)") + + def test_ep_library_survives_competing_stock_libnccl_preload(self): + """Regression: libsircl_ep.so resolves sibling libsircl.so even when stock libnccl.so.2 is preloaded.""" + outputs = self._run_group( + "ep_coop_ok", + world=3, + extra_env={ + "LD_PRELOAD": str(self.dummy_nccl), + "LIBSIRCL_P2P_CHANNELS": "on", + "FAKE_CUDA_COOPERATIVE_LAUNCH": "1", + "FAKE_CUDA_SM_COUNT": "48", + "FAKE_CUDA_MAX_ACTIVE_BLOCKS": "2", + }, + ) + for out in outputs: + self.assertIn("ep_coop_ok ok (coop_delta=2)", out) def test_captured_communicator_abort_quarantines_memory(self): outputs = self._run_group("capture_abort", world=2)