diff --git a/crates/xcl/src/tls.rs b/crates/xcl/src/tls.rs index c09e1e295d..5e240f024e 100644 --- a/crates/xcl/src/tls.rs +++ b/crates/xcl/src/tls.rs @@ -248,9 +248,54 @@ unsafe fn fill_block(block: *mut u8, img: &TlsImage) { /// The slot xcl.exe's own TLS moved to when the title's executable took slot 0 (NO_INDEX: not /// moved). static XCL_SLOT: AtomicU32 = AtomicU32::new(NO_INDEX); -/// TEBs of the threads whose slots were exchanged by `take_slot_zero` itself (their TLS -/// callback, if it still comes, leaves them as they are); held during the exchange -static MOVED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +struct ThreadHandle(usize); + +impl ThreadHandle { + fn raw(&self) -> *mut core::ffi::c_void { + self.0 as *mut core::ffi::c_void + } + + unsafe fn is_alive(&self) -> bool { + use windows_sys::Win32::Foundation::WAIT_TIMEOUT; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + self.0 != 0 && WaitForSingleObject(self.raw(), 0) == WAIT_TIMEOUT + } +} + +impl Drop for ThreadHandle { + fn drop(&mut self) { + if self.0 != 0 { + unsafe { windows_sys::Win32::Foundation::CloseHandle(self.raw()) }; + } + } +} + +struct SuspendGuard(*mut core::ffi::c_void); + +impl SuspendGuard { + unsafe fn suspend(handle: *mut core::ffi::c_void) -> Option { + use windows_sys::Win32::System::Threading::SuspendThread; + (SuspendThread(handle) != u32::MAX).then_some(Self(handle)) + } +} + +impl Drop for SuspendGuard { + fn drop(&mut self) { + unsafe { windows_sys::Win32::System::Threading::ResumeThread(self.0) }; + } +} + +struct MovedTeb { + teb: usize, + tid: u32, + // Holding a handle prevents TID reuse while tracked and detects threads killed + // without DLL_THREAD_DETACH (e.g. TerminateThread). + handle: ThreadHandle, +} + +/// Threads whose slots were exchanged by `take_slot_zero` itself (their TLS callback, if it +/// still comes, leaves them as they are); held during the exchange. +static MOVED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); /// xcl.exe's `_tls_index` (its TLS directory's AddressOfIndex) unsafe fn own_tls_index() -> Option<*mut u32> { @@ -269,29 +314,51 @@ unsafe fn own_tls_index() -> Option<*mut u32> { (index != 0).then_some(index as *mut u32) } -/// The TEBs of the process's threads (the current one first). -unsafe fn thread_tebs() -> Vec<*mut u8> { +/// Safely read a pointer-sized word from the current process without faulting if a thread +/// unmapped its TEB concurrently. +unsafe fn read_own_ptr(addr: usize) -> Option { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if addr == 0 { + return None; + } + let mut val = 0usize; + let mut read = 0usize; + let ok = ReadProcessMemory( + GetCurrentProcess(), + addr as *const core::ffi::c_void, + &mut val as *mut usize as *mut core::ffi::c_void, + std::mem::size_of::(), + &mut read, + ); + (ok != 0 && read == std::mem::size_of::()).then_some(val) +} + +/// Open handles to all other threads currently in this process. +unsafe fn other_threads() -> Vec<(u32, ThreadHandle)> { use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; - use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32}; - use windows_sys::Win32::System::Threading::{GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_QUERY_INFORMATION}; - let mut out = vec![current_teb()]; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32, + }; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_QUERY_INFORMATION, + THREAD_SUSPEND_RESUME, THREAD_SYNCHRONIZE, + }; + let mut out = Vec::new(); let (pid, tid) = (GetCurrentProcessId(), GetCurrentThreadId()); let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if snap == INVALID_HANDLE_VALUE { return out; } + let access = THREAD_QUERY_INFORMATION | THREAD_SUSPEND_RESUME | THREAD_SYNCHRONIZE; let mut te: THREADENTRY32 = std::mem::zeroed(); te.dwSize = std::mem::size_of::() as u32; let mut ok = Thread32First(snap, &mut te) != 0; while ok { if te.th32OwnerProcessID == pid && te.th32ThreadID != tid { - let h = OpenThread(THREAD_QUERY_INFORMATION, 0, te.th32ThreadID); + let h = OpenThread(access, 0, te.th32ThreadID); if !h.is_null() { - let mut tbi: ThreadBasicInformation = std::mem::zeroed(); - if NtQueryInformationThread(h, 0, &mut tbi as *mut _ as *mut _, std::mem::size_of::() as u32, std::ptr::null_mut()) >= 0 && !tbi.teb.is_null() { - out.push(tbi.teb); - } - CloseHandle(h); + out.push((te.th32ThreadID, ThreadHandle(h as usize))); } } ok = Thread32Next(snap, &mut te) != 0; @@ -300,6 +367,14 @@ unsafe fn thread_tebs() -> Vec<*mut u8> { out } +struct PendingSwap { + tid: u32, + teb: usize, + xcl_block: usize, + carrier_block: *mut u8, + handle: ThreadHandle, +} + /// The title's executable gets TLS slot 0, as on Windows (and the console) the process's /// executable has it: code built with /GA reads `ThreadLocalStoragePointer[0]` directly, without /// `_tls_index` (Fortnite: the guard of its thread-safe statics, so its allocator was never @@ -314,25 +389,100 @@ pub unsafe fn take_slot_zero(img_name: &str, title_index: *mut u32, k: u32) -> R return Err(format!("xcl.exe's TLS index is {}, not 0", *own)); } let mut moved = MOVED.lock().map_err(|_| "TLS lock poisoned")?; - let tebs = thread_tebs(); - // 1. slot k = slot 0 (xcl.exe's block) in every thread; the carrier blocks kept - let mut carriers: Vec<(*mut *mut u8, *mut u8)> = Vec::new(); - for &teb in &tebs { - let arr = *(teb.add(0x58) as *const *mut *mut u8); - if arr.is_null() { - continue; + // Publish XCL_SLOT before snapshotting threads so threads attaching or detaching + // concurrently serialize on `MOVED` instead of racing the exchange. + XCL_SLOT.store(k, Ordering::SeqCst); + + let others = other_threads(); + let mut pending: Vec = Vec::with_capacity(others.len()); + + // 1. slot k = slot 0 (xcl.exe's block) in every live thread; keep carrier blocks for phase 2. + // Suspend each peer only across raw syscalls and pointer reads/writes (no allocs or locks). + for (tid, handle) in others { + let info = { + let Some(_guard) = SuspendGuard::suspend(handle.raw()) else { + continue; + }; + if !handle.is_alive() { + None + } else { + let mut tbi: ThreadBasicInformation = std::mem::zeroed(); + let st = NtQueryInformationThread( + handle.raw(), + 0, + &mut tbi as *mut _ as *mut _, + std::mem::size_of::() as u32, + std::ptr::null_mut(), + ); + if st >= 0 && !tbi.teb.is_null() { + let teb = tbi.teb as usize; + read_own_ptr(teb + 0x58).and_then(|arr_addr| { + if arr_addr == 0 { + return None; + } + let arr = arr_addr as *mut *mut u8; + let xcl_block = read_own_ptr(arr as usize)?; + let carrier_block = read_own_ptr(arr.add(k as usize) as usize)?; + // Skip threads mid-LdrpAllocateTls whose slot blocks are not populated yet; + // their upcoming on_thread_attach will perform the swap once ready. + if xcl_block == 0 || carrier_block == 0 { + return None; + } + *arr.add(k as usize) = xcl_block as *mut u8; + Some((teb, xcl_block, carrier_block as *mut u8)) + }) + } else { + None + } + } + }; + if let Some((teb, xcl_block, carrier_block)) = info { + pending.push(PendingSwap { tid, teb, xcl_block, carrier_block, handle }); } - carriers.push((arr, *arr.add(k as usize))); - *arr.add(k as usize) = *arr; - moved.push(teb as usize); } + + let cur_arr = *(current_teb().add(0x58) as *const *mut *mut u8); + let cur_carrier = if !cur_arr.is_null() { + let b = *cur_arr.add(k as usize); + *cur_arr.add(k as usize) = *cur_arr; + Some((cur_arr, b)) + } else { + None + }; + fence(Ordering::SeqCst); - XCL_SLOT.store(k, Ordering::Release); std::ptr::write_volatile(own, k); fence(Ordering::SeqCst); - // 2. accesses that read index 0 before finish, then slot 0 = the title's block + + // 2. accesses that read index 0 before finish, then slot 0 = the title's block. windows_sys::Win32::System::Threading::Sleep(20); - for (arr, block) in carriers { + + let mut swapped_others = 0usize; + for slot in pending { + let swapped = { + let Some(_guard) = SuspendGuard::suspend(slot.handle.raw()) else { + continue; + }; + if !slot.handle.is_alive() { + false + } else if let Some(arr_addr) = read_own_ptr(slot.teb + 0x58) { + if arr_addr != 0 && read_own_ptr(arr_addr) == Some(slot.xcl_block) { + *(arr_addr as *mut *mut u8) = slot.carrier_block; + true + } else { + false + } + } else { + false + } + }; + if swapped { + moved.push(MovedTeb { teb: slot.teb, tid: slot.tid, handle: slot.handle }); + swapped_others += 1; + } + } + + if let Some((arr, block)) = cur_carrier { *arr = block; } if !title_index.is_null() { @@ -343,8 +493,9 @@ pub unsafe fn take_slot_zero(img_name: &str, title_index: *mut u32, k: u32) -> R img.index.store(0, Ordering::Release); } } + let total_threads = usize::from(cur_carrier.is_some()) + swapped_others; drop(moved); - crate::xlog_info!("TLS: {img_name} has slot 0 (as a process's executable); xcl.exe's own TLS is in slot {k} – {} threads", tebs.len()); + crate::xlog_info!("TLS: {img_name} has slot 0 (as a process's executable); xcl.exe's own TLS is in slot {k} – {total_threads} threads"); Ok(()) } @@ -356,7 +507,11 @@ unsafe fn exchange_for_new_thread(teb: *mut u8) { return; } let Ok(mut moved) = MOVED.lock() else { return }; - if let Some(i) = moved.iter().position(|&t| t == teb as usize) { + let cur_tid = windows_sys::Win32::System::Threading::GetCurrentThreadId(); + // Prune entries for threads that exited without DLL_THREAD_DETACH (e.g. TerminateThread) + // so a recycled TEB address cannot skip the slot exchange for a new thread. + moved.retain(|e| e.handle.is_alive()); + if let Some(i) = moved.iter().position(|e| e.teb == teb as usize && e.tid == cur_tid) { // exchanged by take_slot_zero before it ran: done (and the TEB may come back later) moved.swap_remove(i); return; @@ -376,8 +531,9 @@ pub fn on_thread_detach() { return; } let teb = unsafe { current_teb() } as usize; + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; if let Ok(mut moved) = MOVED.lock() { - moved.retain(|&t| t != teb); + moved.retain(|e| !(e.teb == teb && e.tid == tid) && unsafe { e.handle.is_alive() }); } } diff --git a/crates/xcl/tests/tls_slot_zero.rs b/crates/xcl/tests/tls_slot_zero.rs new file mode 100644 index 0000000000..1267f38883 --- /dev/null +++ b/crates/xcl/tests/tls_slot_zero.rs @@ -0,0 +1,247 @@ +//! Process-isolated tests for `xcl::tls::take_slot_zero` and `MOVED` tracking. +//! +//! Each test spawns a child copy of this binary so `_tls_index` starts at 0 and +//! `.CRT$XLY` receives real OS `DLL_THREAD_ATTACH` / `DLL_THREAD_DETACH` callbacks. + +use std::cell::Cell; +use std::collections::HashSet; +use std::ffi::c_void; +use std::process::Command; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Barrier}; +use std::time::Duration; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0}; +use windows_sys::Win32::System::Memory::{GetProcessHeap, HeapValidate}; +use windows_sys::Win32::System::Threading::{ + CreateThread, Sleep, TerminateThread, WaitForSingleObject, INFINITE, +}; + +const CHILD_ENV: &str = "XCL_TLS_SLOT_ZERO_CHILD"; +const HOST_MAGIC: u64 = 0x1122_3344_5566_7788; +const HOST_MUTATED: u64 = 0xCAFE_BABE_DEAD_BEEF; + +static CALLBACK_ACTIVE: AtomicBool = AtomicBool::new(false); + +thread_local! { + static HOST_SENTINEL: Cell = const { Cell::new(HOST_MAGIC) }; +} + +unsafe extern "system" fn test_tls_callback(_h: *mut c_void, reason: u32, _r: *mut c_void) { + if !CALLBACK_ACTIVE.load(Ordering::Acquire) { + return; + } + match reason { + 2 => xcl::tls::on_thread_attach(), + 3 => xcl::tls::on_thread_detach(), + _ => {} + } +} + +#[used] +#[link_section = ".CRT$XLY"] +static TEST_TLS_CALLBACK: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = + test_tls_callback; + +unsafe fn read_slot_zero_ptr() -> *mut u8 { + let teb = xcl::tls::current_teb(); + assert!(!teb.is_null()); + let arr = *(teb.add(0x58) as *const *mut *mut u8); + assert!(!arr.is_null()); + *arr +} + +fn run_in_child_process(test_name: &str, body: impl FnOnce()) { + unsafe { std::ptr::read_volatile(&TEST_TLS_CALLBACK) }; + if std::env::var_os(CHILD_ENV).is_some() { + CALLBACK_ACTIVE.store(true, Ordering::Release); + body(); + return; + } + let out = Command::new(std::env::current_exe().expect("current_exe")) + .args(["--exact", test_name, "--nocapture"]) + .env(CHILD_ENV, "1") + .output() + .expect("spawn child test process"); + assert!( + out.status.success(), + "child test `{test_name}` failed (status {:?})\nstdout:\n{}\nstderr:\n{}", + out.status, + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); +} + +struct SleeperArg { + teb: AtomicUsize, + ready: AtomicBool, +} + +unsafe extern "system" fn park_forever(param: *mut c_void) -> u32 { + let arg = &*(param as *const SleeperArg); + assert_eq!(HOST_SENTINEL.with(|c| c.get()), HOST_MAGIC); + arg.teb.store(xcl::tls::current_teb() as usize, Ordering::Release); + arg.ready.store(true, Ordering::Release); + Sleep(INFINITE); + 0 +} + +unsafe fn spawn_parked_threads(n: usize) -> (Vec>, Vec) { + let mut args = Vec::with_capacity(n); + let mut handles = Vec::with_capacity(n); + for _ in 0..n { + let arg = Box::new(SleeperArg { teb: AtomicUsize::new(0), ready: AtomicBool::new(false) }); + let ptr = (&*arg as *const SleeperArg) as *mut c_void; + let h = CreateThread(std::ptr::null(), 0, Some(park_forever), ptr, 0, std::ptr::null_mut()); + assert!(!h.is_null(), "CreateThread failed"); + args.push(arg); + handles.push(h as usize); + } + for arg in &args { + while !arg.ready.load(Ordering::Acquire) { + std::thread::yield_now(); + } + } + (args, handles) +} + +#[test] +fn reused_teb_after_terminate_thread_still_exchanges_slots() { + run_in_child_process("reused_teb_after_terminate_thread_still_exchanges_slots", || unsafe { + let dir = std::env::temp_dir().join(format!("xcl_tls_s0_reuse_{}", std::process::id())); + let template: &'static [u8; 64] = Box::leak(Box::new([0xA5u8; 64])); + let mut title_index = u32::MAX; + + // 1. Spawn threads recorded in `MOVED` by `take_slot_zero`, then terminate them + // without DLL_THREAD_DETACH. + let (args, handles) = spawn_parked_threads(16); + let victim_tebs: HashSet = args.iter().map(|a| a.teb.load(Ordering::Acquire)).collect(); + assert_eq!(victim_tebs.len(), 16); + + // 2. Install carrier and take slot 0 for the title. + let k = xcl::tls::install("reuse_test.exe", template.as_ptr() as usize, 64, 0x2000, &mut title_index, &dir) + .expect("tls::install"); + xcl::tls::take_slot_zero("reuse_test.exe", &mut title_index, k).expect("tls::take_slot_zero"); + assert_eq!(title_index, 0); + assert_eq!(HOST_SENTINEL.with(|c| c.get()), HOST_MAGIC); + assert_eq!(std::slice::from_raw_parts(read_slot_zero_ptr(), 64), &template[..]); + + // 3. Kill all victims via TerminateThread and close our handles so Windows recycles TEBs. + for h_raw in handles { + let h = h_raw as HANDLE; + assert_ne!(TerminateThread(h, 0), 0, "TerminateThread failed"); + assert_eq!(WaitForSingleObject(h, 5_000), WAIT_OBJECT_0); + CloseHandle(h); + } + drop(args); + + // 4. Spawn fresh threads until Windows reuses victim TEBs; every thread must still swap. + let mut reused = 0usize; + for i in 0..2048 { + let (teb, host_ok, title_ok, isolated_ok) = std::thread::spawn(|| { + let teb = xcl::tls::current_teb() as usize; + let host_before = HOST_SENTINEL.with(|c| c.get()); + let s0 = read_slot_zero_ptr(); + let title_bytes_ok = std::slice::from_raw_parts(s0, 64) == &[0xA5u8; 64]; + HOST_SENTINEL.with(|c| c.set(HOST_MUTATED)); + std::ptr::write_bytes(s0, 0x55, 64); + let host_after = HOST_SENTINEL.with(|c| c.get()); + (teb, host_before == HOST_MAGIC, title_bytes_ok, host_after == HOST_MUTATED) + }) + .join() + .expect("fresh thread panicked"); + if victim_tebs.contains(&teb) { + reused += 1; + } + assert!(host_ok, "host TLS corrupted on new thread (teb={teb:#x}, iter={i}, reused={reused})"); + assert!(title_ok, "slot 0 missing title template (teb={teb:#x}, iter={i}, reused={reused})"); + assert!(isolated_ok, "slot 0 and host slot overlapped (teb={teb:#x}, iter={i}, reused={reused})"); + if reused >= 4 { + break; + } + } + assert!(reused > 0, "expected Windows to reuse at least one terminated TEB"); + assert_ne!(HeapValidate(GetProcessHeap(), 0, std::ptr::null()), 0); + let _ = std::fs::remove_dir_all(&dir); + }); +} + +#[test] +fn take_slot_zero_survives_concurrent_thread_exit_and_termination() { + run_in_child_process("take_slot_zero_survives_concurrent_thread_exit_and_termination", || unsafe { + let dir = std::env::temp_dir().join(format!("xcl_tls_s0_churn_{}", std::process::id())); + let template: &'static [u8; 64] = Box::leak(Box::new([0x3Cu8; 64])); + let mut title_index = u32::MAX; + + let k = xcl::tls::install("churn_test.exe", template.as_ptr() as usize, 64, 0x2000, &mut title_index, &dir) + .expect("tls::install"); + + const N_CHURNERS: usize = 4; + let start = Arc::new(Barrier::new(N_CHURNERS + 3)); + let done_swap = Arc::new(AtomicBool::new(false)); + let stop_churn = Arc::new(AtomicBool::new(false)); + + let (surv_start, surv_done) = (start.clone(), done_swap.clone()); + let survivor = std::thread::spawn(move || { + assert_eq!(HOST_SENTINEL.with(|c| c.get()), HOST_MAGIC); + surv_start.wait(); + while !surv_done.load(Ordering::Acquire) { + std::thread::sleep(Duration::from_millis(1)); + } + assert_eq!(HOST_SENTINEL.with(|c| c.get()), HOST_MAGIC); + HOST_SENTINEL.with(|c| c.set(HOST_MUTATED)); + let s0 = read_slot_zero_ptr(); + assert_eq!(std::slice::from_raw_parts(s0, 64), &[0x3Cu8; 64]); + std::ptr::write_bytes(s0, 0x77, 64); + assert_eq!(HOST_SENTINEL.with(|c| c.get()), HOST_MUTATED); + }); + + let mut churners = Vec::with_capacity(N_CHURNERS); + for _ in 0..N_CHURNERS { + let (b, stop) = (start.clone(), stop_churn.clone()); + churners.push(std::thread::spawn(move || { + b.wait(); + while !stop.load(Ordering::Acquire) { + let _ = std::thread::spawn(|| { + assert_eq!(HOST_SENTINEL.with(|c| c.get()), HOST_MAGIC); + }) + .join(); + } + })); + } + + let (victim_args, victim_handles) = spawn_parked_threads(16); + let killer_start = start.clone(); + let killer = std::thread::spawn(move || { + killer_start.wait(); + for (i, h_raw) in victim_handles.into_iter().enumerate() { + if i % 2 == 1 { + std::thread::sleep(Duration::from_millis(2)); + } + let h = h_raw as HANDLE; + let _ = TerminateThread(h, 0); + let _ = WaitForSingleObject(h, 5_000); + CloseHandle(h); + } + }); + + start.wait(); + std::thread::sleep(Duration::from_millis(2)); + xcl::tls::take_slot_zero("churn_test.exe", &mut title_index, k).expect("tls::take_slot_zero"); + assert_eq!(title_index, 0); + done_swap.store(true, Ordering::Release); + stop_churn.store(true, Ordering::Release); + + survivor.join().expect("survivor thread panicked"); + killer.join().expect("killer thread panicked"); + for j in churners { + j.join().expect("churner thread panicked"); + } + drop(victim_args); + + assert_eq!(HOST_SENTINEL.with(|c| c.get()), HOST_MAGIC); + assert_eq!(std::slice::from_raw_parts(read_slot_zero_ptr(), 64), &template[..]); + assert_ne!(HeapValidate(GetProcessHeap(), 0, std::ptr::null()), 0); + let _ = std::fs::remove_dir_all(&dir); + }); +}