From c79dd80a8ae7d0c034280a26bb287b4a4d144c97 Mon Sep 17 00:00:00 2001 From: "Larsen, Steffen" Date: Thu, 19 Jun 2025 01:10:00 -0700 Subject: [PATCH] [SYCL] Fix unloading of shared images on Windows After https://github.com/intel/llvm/pull/17869, Windows will not unload images during the runtime of the program. However, this means that shared libraries that are dynamically loaded and unloaded will leave dangling pointers to their images. If somehow these images get picked up, e.g. if another library is loaded with overlapping symbols, the runtime may try to dereference the dangling device image pointers. This commit reenables Windows unloading with the caveat that once the global handler is dead the runtime assumes that shutdown has begun. Signed-off-by: Larsen, Steffen --- sycl/source/detail/global_handler.cpp | 4 ++++ sycl/source/detail/global_handler.hpp | 3 +++ sycl/source/detail/program_manager/program_manager.cpp | 5 ++--- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/sycl/source/detail/global_handler.cpp b/sycl/source/detail/global_handler.cpp index 8c672589f7f59..2bca54251a17b 100644 --- a/sycl/source/detail/global_handler.cpp +++ b/sycl/source/detail/global_handler.cpp @@ -134,6 +134,10 @@ GlobalHandler &GlobalHandler::instance() { return *RTGlobalObjHandler; } +bool GlobalHandler::isInstanceAlive() { + return GlobalHandler::getInstancePtr(); +} + template T &GlobalHandler::getOrCreate(InstWithLock &IWL, Types &&...Args) { const LockGuard Lock{IWL.Lock}; diff --git a/sycl/source/detail/global_handler.hpp b/sycl/source/detail/global_handler.hpp index 8c66f5a8dcd8d..5e4f45e792377 100644 --- a/sycl/source/detail/global_handler.hpp +++ b/sycl/source/detail/global_handler.hpp @@ -52,6 +52,9 @@ class GlobalHandler { /// `__attribute__((destructor))` is called). static GlobalHandler &instance(); + /// \return true if the instance has not been deallocated yet. + static bool isInstanceAlive(); + GlobalHandler(const GlobalHandler &) = delete; GlobalHandler(GlobalHandler &&) = delete; GlobalHandler &operator=(const GlobalHandler &) = delete; diff --git a/sycl/source/detail/program_manager/program_manager.cpp b/sycl/source/detail/program_manager/program_manager.cpp index d5ce791cc443b..01c0ffdfd6db5 100644 --- a/sycl/source/detail/program_manager/program_manager.cpp +++ b/sycl/source/detail/program_manager/program_manager.cpp @@ -3927,9 +3927,8 @@ extern "C" void __sycl_register_lib(sycl_device_binaries desc) { // Executed as a part of current module's (.exe, .dll) static initialization extern "C" void __sycl_unregister_lib(sycl_device_binaries desc) { // Partial cleanup is not necessary at shutdown -#ifndef _WIN32 - if (!sycl::detail::GlobalHandler::instance().isOkToDefer()) + if (!sycl::detail::GlobalHandler::isInstanceAlive() || + !sycl::detail::GlobalHandler::instance().isOkToDefer()) return; sycl::detail::ProgramManager::getInstance().removeImages(desc); -#endif }