From 8d5b734c3082f6702b2b5dead826505776a7996b Mon Sep 17 00:00:00 2001 From: aiwhskruht <217834908+aiwhskruht@users.noreply.github.com> Date: Mon, 7 Jul 2025 11:08:09 -0700 Subject: [PATCH] Add initialized check to protect zluda from cuda driver calls during shutdown (#404) --- Cargo.lock | 16 ++++++++++++++++ zluda/Cargo.toml | 1 + zluda/src/lib.rs | 17 +++++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 4441417..6e5cb87 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -399,6 +399,21 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" +[[package]] +name = "dtor" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97cbdf2ad6846025e8e25df05171abfb30e3ababa12ee0a0e44b9bbe570633a8" +dependencies = [ + "dtor-proc-macro", +] + +[[package]] +name = "dtor-proc-macro" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7454e41ff9012c00d53cf7f475c5e3afa3b91b7c90568495495e8d9bf47a1055" + [[package]] name = "dynasm" version = "1.2.3" @@ -1758,6 +1773,7 @@ dependencies = [ "cuda_base", "cuda_types", "dark_api", + "dtor", "hip_runtime-sys", "lazy_static", "lz4-sys", diff --git a/zluda/Cargo.toml b/zluda/Cargo.toml index da59222..49ebbc4 100644 --- a/zluda/Cargo.toml +++ b/zluda/Cargo.toml @@ -22,6 +22,7 @@ lz4-sys = "1.9" tempfile = "3" paste = "1.0" rustc-hash = "1.1" +dtor = "0.0.6" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["heapapi", "std"] } diff --git a/zluda/src/lib.rs b/zluda/src/lib.rs index 0b8c784..4bc81a7 100644 --- a/zluda/src/lib.rs +++ b/zluda/src/lib.rs @@ -1,5 +1,16 @@ +use cuda_types::cuda::CUerror; +use std::sync::atomic::{AtomicBool, Ordering}; pub(crate) mod r#impl; +static INITIALIZED: AtomicBool = AtomicBool::new(true); +pub(crate) fn initialized() -> bool { + INITIALIZED.load(Ordering::SeqCst) +} +#[dtor::dtor] +fn deinitialize() { + INITIALIZED.store(false, Ordering::SeqCst); +} + macro_rules! unimplemented { ($($abi:literal fn $fn_name:ident( $($arg_id:ident : $arg_type:ty),* ) -> $ret_type:ty;)*) => { $( @@ -20,6 +31,9 @@ macro_rules! implemented { #[allow(improper_ctypes)] #[allow(improper_ctypes_definitions)] pub unsafe extern $abi fn $fn_name ( $( $arg_id : $arg_type),* ) -> $ret_type { + if !initialized() { + return Err(CUerror::DEINITIALIZED); + } cuda_base::cuda_normalize_fn!( crate::r#impl::$fn_name ) ($(crate::r#impl::FromCuda::from_cuda(&$arg_id)?),*)?; Ok(()) } @@ -34,6 +48,9 @@ macro_rules! implemented_in_function { #[allow(improper_ctypes)] #[allow(improper_ctypes_definitions)] pub unsafe extern $abi fn $fn_name ( $( $arg_id : $arg_type),* ) -> $ret_type { + if !initialized() { + return Err(CUerror::DEINITIALIZED); + } cuda_base::cuda_normalize_fn!( crate::r#impl::function::$fn_name ) ($(crate::r#impl::FromCuda::from_cuda(&$arg_id)?),*)?; Ok(()) }