From e1a4d08d1ecb8df8d967b40a8fb5c2814128ad8f Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Thu, 20 Aug 2026 11:26:24 -0700 Subject: [PATCH 1/2] fix(c_abi): drive futures off the foreign caller thread to avoid Windows TLS-teardown corruption MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `block_on_ffi` called `Runtime::block_on` on the calling thread. `block_on` *enters* the process-wide runtime on that thread, registering tokio's runtime-context thread-local on it. When the caller is a native OS thread the kernel does not own — the intended ODBC / Go usage, e.g. the ODBC driver's result-prefetch thread — and that thread is later torn down on Windows/MSVC, tokio's context guard and the `LAST_ERROR` `CString` thread-local are dropped during TLS teardown in an order that trips tokio's "EnterGuard dropped out of order" panic or the "System allocator may not use TLS with destructors" abort (#276). Instead, spawn the future onto the runtime's own worker threads and block the caller on a plain `std` channel. The caller thread never enters the runtime, so no runtime-context TLS is ever registered on it and there is nothing to corrupt at teardown. The `Handle::try_current()` reentrancy guard stays: it only reads (empty-initialises) the caller's context, never enters the runtime. Because the future now runs on worker threads it must be `Send` (and its output `Send`). The metadata entry points previously marshalled their raw C-string pointers inside the spawned async block; move that marshalling onto the caller thread (before the async block) so only `Send` borrows cross onto the workers, never the `!Send` raw pointers. Closes #276 Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- src/c_abi/metadata.rs | 136 +++++++++++++++++++++++++--------- src/c_abi/mod.rs | 165 +++++++++++++++++++++++++++++++++++------- 2 files changed, 239 insertions(+), 62 deletions(-) diff --git a/src/c_abi/metadata.rs b/src/c_abi/metadata.rs index 64a017ae..fd49d5f7 100644 --- a/src/c_abi/metadata.rs +++ b/src/c_abi/metadata.rs @@ -106,8 +106,9 @@ unsafe fn run_metadata( where F: FnOnce( &Session, - ) - -> std::pin::Pin> + '_>>, + ) -> std::pin::Pin< + Box> + Send + '_>, + >, { crate::c_abi::error::clear_error(); let Some(session) = (session as *const Session).as_ref() else { @@ -120,10 +121,18 @@ where // itself is handed to the owned handle and driven lazily (one batch // per `kernel_result_stream_next_batch`), so a large metadata result // (e.g. cross-catalog column listing) is not buffered up front. - let result = block_on_ffi(move || async move { - let stream = build(session).await?; - let schema = stream.schema(); - Ok((schema, stream)) + // Build the stream future on THIS (caller) thread — so `build` (which may + // capture raw C-string pointers, `!Send`) is consumed here and only the + // resulting `Send` future crosses onto the runtime's worker threads via + // `block_on_ffi`. See `block_on_ffi` for why the work must not run on the + // caller thread (#276). + let result = block_on_ffi(move || { + let stream_fut = build(session); + async move { + let stream = stream_fut.await?; + let schema = stream.schema(); + Ok((schema, stream)) + } }); match result { Ok((schema, stream)) => { @@ -162,9 +171,17 @@ pub unsafe extern "C" fn kernel_metadata_list_schemas( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { run_metadata(session, out, |session| { + // Marshal the raw C-string pointers on the caller thread (before the + // async block) so the spawned future captures only `Send` borrows, + // never the `!Send` raw pointers. See `block_on_ffi` (#276). + let args = (|| -> Result<_> { + Ok(( + opt_ident(catalog, "catalog")?, + opt_pattern(schema_pattern, "schema_pattern")?, + )) + })(); Box::pin(async move { - let catalog = opt_ident(catalog, "catalog")?; - let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; + let (catalog, schema_pattern) = args?; session .metadata() .list_schemas(catalog, schema_pattern) @@ -244,11 +261,17 @@ pub unsafe extern "C" fn kernel_metadata_list_tables( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { run_metadata(session, out, |session| { + // Marshal raw C-string pointers on the caller thread (see #276). + let args = (|| -> Result<_> { + Ok(( + opt_pattern(catalog, "catalog")?, + opt_pattern(schema_pattern, "schema_pattern")?, + opt_pattern(table_pattern, "table_pattern")?, + opt_str(table_types_csv, "table_types")?, + )) + })(); Box::pin(async move { - let catalog = opt_pattern(catalog, "catalog")?; - let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; - let table_pattern = opt_pattern(table_pattern, "table_pattern")?; - let types_csv = opt_str(table_types_csv, "table_types")?; + let (catalog, schema_pattern, table_pattern, types_csv) = args?; let types_owned = parse_table_types_filter(types_csv); session .metadata() @@ -279,11 +302,17 @@ pub unsafe extern "C" fn kernel_metadata_list_columns( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { run_metadata(session, out, |session| { + // Marshal raw C-string pointers on the caller thread (see #276). + let args = (|| -> Result<_> { + Ok(( + opt_ident(catalog, "catalog")?, + opt_pattern(schema_pattern, "schema_pattern")?, + opt_pattern(table_pattern, "table_pattern")?, + opt_pattern(column_pattern, "column_pattern")?, + )) + })(); Box::pin(async move { - let catalog = opt_ident(catalog, "catalog")?; - let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; - let table_pattern = opt_pattern(table_pattern, "table_pattern")?; - let column_pattern = opt_pattern(column_pattern, "column_pattern")?; + let (catalog, schema_pattern, table_pattern, column_pattern) = args?; session .metadata() .list_columns(catalog, schema_pattern, table_pattern, column_pattern) @@ -307,10 +336,16 @@ pub unsafe extern "C" fn kernel_metadata_primary_keys( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { run_metadata(session, out, |session| { + // Marshal raw C-string pointers on the caller thread (see #276). + let args = (|| -> Result<_> { + Ok(( + opt_ident(catalog, "catalog")?, + opt_ident(schema, "schema")?, + Identifier::new(req_str(table, "table")?)?, + )) + })(); Box::pin(async move { - let catalog = opt_ident(catalog, "catalog")?; - let schema = opt_ident(schema, "schema")?; - let table = Identifier::new(req_str(table, "table")?)?; + let (catalog, schema, table) = args?; session .metadata() .primary_keys(catalog, schema, table) @@ -349,13 +384,26 @@ pub unsafe extern "C" fn kernel_metadata_foreign_keys( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { run_metadata(session, out, |session| { + // Marshal raw C-string pointers on the caller thread (see #276). + let args = (|| -> Result<_> { + Ok(( + opt_ident(parent_catalog, "parent_catalog")?, + opt_ident(parent_schema, "parent_schema")?, + opt_ident(parent_table, "parent_table")?, + opt_ident(foreign_catalog, "foreign_catalog")?, + opt_ident(foreign_schema, "foreign_schema")?, + opt_ident(foreign_table, "foreign_table")?, + )) + })(); Box::pin(async move { - let parent_catalog = opt_ident(parent_catalog, "parent_catalog")?; - let parent_schema = opt_ident(parent_schema, "parent_schema")?; - let parent_table = opt_ident(parent_table, "parent_table")?; - let foreign_catalog = opt_ident(foreign_catalog, "foreign_catalog")?; - let foreign_schema = opt_ident(foreign_schema, "foreign_schema")?; - let foreign_table = opt_ident(foreign_table, "foreign_table")?; + let ( + parent_catalog, + parent_schema, + parent_table, + foreign_catalog, + foreign_schema, + foreign_table, + ) = args?; session .metadata() .foreign_keys( @@ -407,10 +455,16 @@ pub unsafe extern "C" fn kernel_metadata_procedures( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { run_metadata(session, out, |session| { + // Marshal raw C-string pointers on the caller thread (see #276). + let args = (|| -> Result<_> { + Ok(( + opt_ident(catalog, "catalog")?, + opt_pattern(schema_pattern, "schema_pattern")?, + opt_pattern(procedure_pattern, "procedure_pattern")?, + )) + })(); Box::pin(async move { - let catalog = opt_ident(catalog, "catalog")?; - let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; - let procedure_pattern = opt_pattern(procedure_pattern, "procedure_pattern")?; + let (catalog, schema_pattern, procedure_pattern) = args?; session .metadata() .procedures(catalog, schema_pattern, procedure_pattern) @@ -435,10 +489,16 @@ pub unsafe extern "C" fn kernel_metadata_functions( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { run_metadata(session, out, |session| { + // Marshal raw C-string pointers on the caller thread (see #276). + let args = (|| -> Result<_> { + Ok(( + opt_ident(catalog, "catalog")?, + opt_pattern(schema_pattern, "schema_pattern")?, + opt_pattern(function_pattern, "function_pattern")?, + )) + })(); Box::pin(async move { - let catalog = opt_ident(catalog, "catalog")?; - let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; - let function_pattern = opt_pattern(function_pattern, "function_pattern")?; + let (catalog, schema_pattern, function_pattern) = args?; session .metadata() .functions(catalog, schema_pattern, function_pattern) @@ -466,11 +526,17 @@ pub unsafe extern "C" fn kernel_metadata_procedure_columns( out: *mut *mut kernel_result_stream_t, ) -> KernelStatusCode { run_metadata(session, out, |session| { + // Marshal raw C-string pointers on the caller thread (see #276). + let args = (|| -> Result<_> { + Ok(( + opt_ident(catalog, "catalog")?, + opt_pattern(schema_pattern, "schema_pattern")?, + opt_pattern(procedure_pattern, "procedure_pattern")?, + opt_pattern(column_pattern, "column_pattern")?, + )) + })(); Box::pin(async move { - let catalog = opt_ident(catalog, "catalog")?; - let schema_pattern = opt_pattern(schema_pattern, "schema_pattern")?; - let procedure_pattern = opt_pattern(procedure_pattern, "procedure_pattern")?; - let column_pattern = opt_pattern(column_pattern, "column_pattern")?; + let (catalog, schema_pattern, procedure_pattern, column_pattern) = args?; session .metadata() .procedure_columns(catalog, schema_pattern, procedure_pattern, column_pattern) diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index bdb54a4c..ade51982 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -57,10 +57,11 @@ use std::sync::OnceLock; /// /// Rust-crate consumers (PyO3 / napi-rs) own their own runtime and call /// the async surface directly; the C ABI has no caller-owned runtime to -/// borrow, so it owns one here and `block_on`s every entry point through -/// it. Initialised lazily on the first `kernel_session_open` and shared -/// by every session for the life of the process (matches the -/// migration-plan §5.2 contract). +/// borrow, so it owns one here and drives every entry point through it +/// (see [`block_on_ffi`], which spawns onto this runtime rather than +/// blocking the caller thread on it). Initialised lazily on the first +/// `kernel_session_open` and shared by every session for the life of the +/// process (matches the migration-plan §5.2 contract). static RUNTIME: OnceLock = OnceLock::new(); /// Fetch (initialising on first use) the process-wide C-ABI runtime. @@ -100,32 +101,56 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime:: /// typed [`Error`] in the thread-local last-error buffer on failure. /// /// Every `extern "C"` entry point that drives async work funnels through -/// here so the runtime-fetch, `block_on`, error-store, and status-map -/// steps stay in exactly one place. A panic inside the future is caught -/// at the `block_on` edge and surfaced as `Internal` rather than -/// unwinding across the FFI boundary (which is UB). +/// here so the runtime-fetch, spawn, error-store, and status-map steps +/// stay in exactly one place. A panic inside the future is caught and +/// surfaced as `Internal` rather than unwinding across the FFI boundary +/// (which is UB). +/// +/// **How the work is driven (and why it isn't `block_on`):** the future is +/// `spawn`ed onto the runtime's own worker threads and this thread blocks on +/// a plain `std` channel for the result. It deliberately does NOT call +/// `Runtime::block_on` on the caller thread. `block_on` *enters* the runtime +/// on the calling thread, registering tokio's runtime-context thread-local +/// there; if that thread is a native OS thread the kernel does not own (the +/// intended ODBC / Go usage — e.g. the ODBC driver's result-prefetch thread) +/// and is later torn down on Windows/MSVC, that context guard plus the +/// `LAST_ERROR` `CString` thread-local are dropped during TLS teardown in an +/// order that trips tokio's "EnterGuard dropped out of order" panic or the +/// "System allocator may not use TLS with destructors" abort +/// (databricks/databricks-sql-kernel#276). Spawning-and-blocking keeps the +/// caller thread entirely outside the runtime, so no runtime-context TLS is +/// registered on it and there is nothing to tear down. +/// +/// Because the future is moved onto worker threads it must be `Send` (and its +/// output `Send`); every kernel entry point's future already is. /// /// **Threading contract:** the C ABI must be driven from threads that are -/// NOT already running inside a Tokio runtime. `Runtime::block_on` panics -/// ("Cannot start a runtime from within a runtime") if called from a -/// worker of any runtime — including this one — so a reentrant C-ABI call -/// (e.g. a consumer that invokes a `kernel_*` entry point from a callback -/// executing on a runtime worker) is rejected up front with a clear -/// `Internal` error instead of the opaque caught-panic path. Native -/// (non-runtime) caller threads — the intended ODBC / Go usage — are -/// unaffected. +/// NOT already running inside a Tokio runtime. A reentrant C-ABI call (a +/// consumer that invokes a `kernel_*` entry point from a callback executing +/// on a runtime worker) would block that worker on the result channel and can +/// deadlock a single-threaded runtime, so it is rejected up front with a +/// clear `Internal` error. Native (non-runtime) caller threads — the intended +/// ODBC / Go usage — are unaffected. /// /// [`KernelStatusCode`]: crate::c_abi::KernelStatusCode /// [`Error`]: crate::kernel_error::Error pub(crate) fn block_on_ffi(fut_builder: F) -> Result where F: FnOnce() -> Fut, - Fut: std::future::Future>, + Fut: std::future::Future> + Send, + T: Send, { + use futures::future::FutureExt as _; + error::clear_error(); - // Reject reentrancy explicitly: calling `block_on` from within any - // Tokio runtime would panic. Surface a typed, actionable error rather - // than a caught panic mapped to a generic `Internal`. + // Reject reentrancy explicitly: a consumer that invokes a `kernel_*` + // entry point from a thread already running inside a Tokio runtime would + // otherwise have this thread block (on the channel below) waiting for a + // task that shares its runtime — a deadlock risk on a single-threaded + // runtime. Surface a typed, actionable error instead. `Handle::try_current` + // only reads (initialising it empty) the caller thread's Tokio context; it + // never *enters* the runtime, so it leaves no runtime-context state that + // could outlive into the thread's TLS teardown (the #276 hazard). if tokio::runtime::Handle::try_current().is_ok() { let e = crate::kernel_error::Error::new( crate::kernel_error::ErrorCode::Internal, @@ -144,17 +169,72 @@ where return Err(code); } }; - // Catch panics so a kernel bug can't unwind across `extern "C"`. - let result = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rt.block_on(fut_builder()))); - match result { - Ok(Ok(value)) => Ok(value), - Ok(Err(e)) => { + + // Drive the future on the runtime's OWN worker threads and block this + // (foreign) caller thread on a plain `std` channel — instead of calling + // `rt.block_on` here. This is the fix for #276: `Runtime::block_on` + // *enters* the runtime on the calling thread, registering tokio's + // runtime-context thread-local on it. When that thread is a native OS + // thread the kernel does not own (e.g. the ODBC driver's prefetch + // thread) and is later torn down on Windows/MSVC, tokio's context guard + // and the `LAST_ERROR` `CString` thread-local are dropped during TLS + // teardown in an order that trips tokio's "EnterGuard dropped out of + // order" panic or the "System allocator may not use TLS with destructors" + // abort. Spawning the work onto the runtime and blocking on a channel + // means the caller thread NEVER enters the runtime, so no runtime-context + // TLS is ever registered on it. + // + // A panic inside the future is caught here (rather than at a `block_on` + // edge) so it can't unwind across the `extern "C"` boundary (UB) and is + // surfaced as `Internal`. + type PanicPayload = Box; + let (tx, rx) = + std::sync::mpsc::sync_channel::, PanicPayload>>(1); + let future = fut_builder(); + let task = async move { + let outcome = std::panic::AssertUnwindSafe(future).catch_unwind().await; + // `future` (and any borrows it held) is fully dropped by the time + // `.catch_unwind().await` resolves, i.e. before we signal completion. + let _ = tx.send(outcome); + }; + // SAFETY: `future` may borrow data owned by the caller (e.g. a + // `&mut Statement` reached through a raw pointer at the entry points). + // We extend the task's lifetime to `'static` only so it can be spawned, + // and then BLOCK on `rx.recv()` below until the task has produced its + // outcome — at which point the future, and every borrow it held, has + // already been dropped. The borrows therefore never outlive their owner, + // and the extended lifetime is not observable past this call. (Even if + // the runtime were torn down and dropped the task without running it, the + // drop releases the borrows before `rx.recv()` observes the closed + // channel.) The process-wide runtime is a `'static` that never shuts down. + let task: std::pin::Pin + Send + 'static>> = unsafe { + std::mem::transmute::< + std::pin::Pin + Send + '_>>, + std::pin::Pin + Send + 'static>>, + >(Box::pin(task)) + }; + rt.spawn(task); + + match rx.recv() { + Ok(Ok(Ok(value))) => Ok(value), + Ok(Ok(Err(e))) => { + let code = KernelStatusCode::from(e.code); + error::store_error(e); + Err(code) + } + Ok(Err(panic)) => Err(handle_panic(panic)), + Err(_) => { + // The channel closed without a value — only reachable if the + // runtime dropped the task before it ran (never happens for the + // process-wide runtime). The future is dropped by then, so this is + // sound; report it as `Internal`. + let e = crate::kernel_error::Error::internal() + .message("kernel C ABI runtime task was dropped before completion") + .location(concat!(file!(), ":", line!())); let code = KernelStatusCode::from(e.code); error::store_error(e); Err(code) } - Err(panic) => Err(handle_panic(panic)), } } @@ -302,4 +382,35 @@ mod tests { ); }); } + + /// `block_on_ffi` must drive the future on a runtime **worker** thread, not + /// on the calling thread — the core of the #276 fix. `Runtime::block_on` + /// (the pre-fix behaviour) drives the future on the *caller* thread, which + /// registers tokio's runtime-context thread-local there; when the caller is + /// a native OS thread the kernel does not own (the ODBC driver's prefetch + /// thread) and is later torn down on Windows/MSVC, that TLS teardown + /// corrupts the tokio context ("EnterGuard dropped out of order" panic / + /// "System allocator may not use TLS with destructors" abort). Asserting + /// the future ran on a *different* thread than the caller guards that the + /// work is spawned onto the runtime, not `block_on`'d on the caller — so no + /// runtime-context TLS is ever registered on a foreign caller thread. + /// + /// This is the portable regression guard for the fix; the end-to-end crash + /// only manifests through the ODBC driver's driver-manager e2e suite + /// (databricks-odbc#283), which skips the affected tests until the kernel + /// pin carrying this fix is bumped. + #[test] + fn block_on_ffi_runs_future_off_the_caller_thread() { + let caller = std::thread::current().id(); + let ran_on: std::thread::ThreadId = block_on_ffi(|| async move { + Ok::<_, crate::kernel_error::Error>(std::thread::current().id()) + }) + .expect("trivial future completes successfully"); + assert_ne!( + ran_on, caller, + "block_on_ffi must spawn the future onto a runtime worker (never `block_on` it \ + on the caller thread), so no runtime-context TLS is registered on a foreign \ + caller thread — see #276", + ); + } } From b617d5ff77cec20ea46a3685fd729ef3fe4df884 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Fri, 21 Aug 2026 14:58:40 -0700 Subject: [PATCH 2/2] fix(c_abi): pin the kernel's module on Windows so DriverManager unload can't dangle its worker threads (#276) The spawn-not-block_on change alone is insufficient: it keeps the foreign caller thread out of the runtime, but the process-wide multi-thread runtime still leaves detached `kernel-c-abi` worker threads alive across the ODBC DriverManager's load/unload of the driver DLL. When FreeLibrary unmaps the DLL while those workers run, they execute freed code (Access Violation) and tokio's per-thread context guard is dropped after its thread-local CONTEXT is gone -> "EnterGuard values dropped out of order" panic; the in-flight block_on_ffi task never completes and the caller deadlocks (confirmed via a cdb-symbolicated Windows CI repro). Pin the containing module (GetModuleHandleExW FROM_ADDRESS|PIN) at runtime init so the DLL is never unloaded while its worker threads live. Windows-only; inline kernel32 decl to avoid a new windows-sys dependency + deny review. Signed-off-by: Vikrant Puppala --- src/c_abi/mod.rs | 59 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index ade51982..8ee10802 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -90,12 +90,71 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime:: .message(format!("failed to build the C-ABI tokio runtime: {e}")) .location(concat!(file!(), ":", line!())) })?; + // On Windows, pin the module that contains the kernel into the process so + // it can never be unloaded while these worker threads are alive (#276). + // Must happen once the runtime — and therefore its detached `kernel-c-abi` + // worker threads — exists. + #[cfg(windows)] + pin_containing_module(); // If another thread installed one between our `get` and here, keep // theirs and drop ours. let _ = RUNTIME.set(built); Ok(RUNTIME.get().expect("runtime just set")) } +/// Pin the module containing the kernel so the ODBC / Go host cannot unload it +/// while the C-ABI runtime's worker threads are still running. +/// +/// The process-wide runtime (see [`runtime`]) is multi-thread and is never shut +/// down: it spawns detached `kernel-c-abi` OS worker threads that outlive any +/// single ODBC connection. The ODBC DriverManager, however, loads **and +/// unloads** the driver DLL (which statically links this kernel) across +/// connections. If `FreeLibrary` unmaps the DLL while those worker threads are +/// still alive, they end up executing freed code — an Access Violation — and +/// tokio's per-thread runtime-context guard is dropped after its thread-local +/// `CONTEXT` has already been torn down, tripping the "EnterGuard values +/// dropped out of order" panic (databricks/databricks-sql-kernel#276). The +/// in-flight [`block_on_ffi`] task then never completes and the caller +/// deadlocks on its result channel. +/// +/// `GetModuleHandleExW` with `FROM_ADDRESS` resolves the module that contains a +/// given code address, and `PIN` raises that module's reference count so it is +/// never unloaded for the life of the process. We pass the address of this +/// function itself (which lives in the kernel's statically-linked code), so the +/// pinned module is whatever the kernel is linked into — the ODBC driver DLL +/// for C-ABI consumers. Pinning is idempotent, so a lost runtime-build race +/// calling it twice is harmless. This is the Windows-only complement to the +/// spawn-not-`block_on` change in [`block_on_ffi`]: that keeps *foreign caller* +/// threads out of the runtime; this keeps the runtime's *own* threads from +/// being unmapped underneath themselves. +#[cfg(windows)] +fn pin_containing_module() { + const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x0000_0004; + const GET_MODULE_HANDLE_EX_FLAG_PIN: u32 = 0x0000_0001; + // Declared inline rather than via a `windows-sys` dependency: `kernel32` is + // always linked on the MSVC target, and this avoids a new crate + its + // cargo-deny license review for a single call. + extern "system" { + fn GetModuleHandleExW( + dw_flags: u32, + lp_module_name: *const u16, + ph_module: *mut *mut core::ffi::c_void, + ) -> i32; + } + let mut module: *mut core::ffi::c_void = core::ptr::null_mut(); + // SAFETY: with `FROM_ADDRESS`, `lp_module_name` is interpreted as an + // address, not a wide string; we pass a valid code address (this function) + // and a writable out-pointer. The returned handle is intentionally not + // released — pinning is meant to be permanent. + unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + pin_containing_module as usize as *const u16, + &mut module, + ); + } +} + /// Run a fallible async block to completion on the process-wide runtime, /// translating the outcome into a [`KernelStatusCode`] and storing the /// typed [`Error`] in the thread-local last-error buffer on failure.