瀏覽代碼

Thread notices: leave out threads Rust's std starts

Their TLS callbacks run before std's start routine records the thread,
and std aborts if anything asks for the current thread first (stdout and
stderr locks do, so title code calling our logging functions would).
Threads starting in our exe (the title's main thread and our runtime's
workers) now get no notices; the probe test starts its thread in title
code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Marvis 4 天之前
父節點
當前提交
bc3070991a
共有 3 個文件被更改,包括 61 次插入 和 2 次删除
  1. 1 0
      crates/victory-loader/Cargo.toml
  2. 43 1
      crates/victory-loader/src/threads.rs
  3. 17 1
      crates/victory-loader/tests/load_probe.rs

+ 1 - 0
crates/victory-loader/Cargo.toml

@@ -17,6 +17,7 @@ blake3.workspace = true
 
 [target.'cfg(windows)'.dependencies]
 windows-sys = { workspace = true, features = [
+    "Wdk_System_Threading",
     "Win32_Foundation",
     "Win32_System_Diagnostics_Debug",
     "Win32_System_Kernel",

+ 43 - 1
crates/victory-loader/src/threads.rs

@@ -71,7 +71,7 @@ pub fn disable_thread_calls(base: usize) -> Option<bool> {
 static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread;
 
 unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) {
-    if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH {
+    if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH || started_by_rust() {
         return;
     }
     // A snapshot: title code may map and attach another DLL from here.
@@ -91,3 +91,45 @@ unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void)
         notify.iter().rev().for_each(notify_one);
     }
 }
+
+/// Whether Rust's std started this thread (its start routine is in our
+/// exe): the title's main thread and our runtime's workers. They get no
+/// notices: std aborts the process if anything on such a thread asks for
+/// the current thread (as stdout and stderr locks do) before its start
+/// routine has run, and title code may call our runtime, which logs.
+// shortcut: title code on our workers (xasync callbacks) runs without
+// thread notices; send them from the worker's start if a title needs them.
+fn started_by_rust() -> bool {
+    use windows_sys::Wdk::System::Threading::{
+        NtQueryInformationThread, ThreadQuerySetWin32StartAddress,
+    };
+    use windows_sys::Win32::System::LibraryLoader::{
+        GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
+        GetModuleHandleExW, GetModuleHandleW,
+    };
+    use windows_sys::Win32::System::Threading::GetCurrentThread;
+
+    let mut start = 0usize;
+    // SAFETY: writes one pointer-sized start address.
+    let status = unsafe {
+        NtQueryInformationThread(
+            GetCurrentThread(),
+            ThreadQuerySetWin32StartAddress,
+            (&raw mut start).cast(),
+            size_of::<usize>() as u32,
+            std::ptr::null_mut(),
+        )
+    };
+    let mut module = std::ptr::null_mut();
+    // SAFETY: looks up the module containing an address, taking no reference.
+    status == 0
+        && unsafe {
+            GetModuleHandleExW(
+                GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
+                start as *const u16,
+                &mut module,
+            )
+        } != 0
+        // SAFETY: our own exe's handle.
+        && module == unsafe { GetModuleHandleW(std::ptr::null()) }
+}

+ 17 - 1
crates/victory-loader/tests/load_probe.rs

@@ -11,7 +11,9 @@ use victory_loader::{
     unimplemented_call_count,
 };
 use victory_pe::ImportSymbol;
+use windows_sys::Win32::Foundation::CloseHandle;
 use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
+use windows_sys::Win32::System::Threading::{CreateThread, INFINITE, WaitForSingleObject};
 
 fn workspace_root() -> PathBuf {
     Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..")
@@ -190,7 +192,21 @@ fn loads_binds_and_calls_probe() {
         image.attach().unwrap();
         let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_thread_starts"));
         let before = f();
-        std::thread::spawn(|| {}).join().unwrap();
+        // Starting in title code, as a title's threads do (ours start in
+        // our exe and are left out); the extra argument is ignored.
+        let start: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 =
+            std::mem::transmute(call("probe_pid"));
+        let thread = CreateThread(
+            std::ptr::null(),
+            0,
+            Some(start),
+            std::ptr::null(),
+            0,
+            std::ptr::null_mut(),
+        );
+        assert!(!thread.is_null());
+        WaitForSingleObject(thread, INFINITE);
+        CloseHandle(thread);
         let after = f();
         assert!(
             after >> 32 > before >> 32,