2
0

threads.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //! Thread notices for title images. The prepared copies have no entry point
  2. //! and no TLS callbacks, so the Windows loader tells them nothing when a
  3. //! thread starts or ends. Our own TLS callback, which Windows calls on every
  4. //! thread of the process whoever created it (title, host CRT or our
  5. //! runtime), passes each notice on to every attached image: its TLS
  6. //! callbacks, then a DLL's `DllMain`.
  7. use std::ffi::c_void;
  8. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  9. use std::sync::{Arc, Mutex};
  10. use std::time::{Duration, Instant};
  11. use crate::{DLL_PROCESS_DETACH, LoadedImage};
  12. const DLL_THREAD_ATTACH: u32 = 2;
  13. const DLL_THREAD_DETACH: u32 = 3;
  14. struct Mapped {
  15. image: Arc<LoadedImage>,
  16. /// Its `DLL_PROCESS_ATTACH` is done; only then does it get thread notices.
  17. attached: bool,
  18. /// `DisableThreadLibraryCalls`: no more `DllMain` thread notices.
  19. quiet: bool,
  20. }
  21. /// Every title image we mapped, in load order.
  22. static IMAGES: Mutex<Vec<Mapped>> = Mutex::new(Vec::new());
  23. fn images() -> std::sync::MutexGuard<'static, Vec<Mapped>> {
  24. IMAGES.lock().unwrap_or_else(|e| e.into_inner())
  25. }
  26. pub(crate) fn mapped(image: &LoadedImage) {
  27. // SAFETY: reads our own static, so the linker keeps it (and its section).
  28. unsafe { std::ptr::from_ref(&ON_THREAD).read_volatile() };
  29. let image = Arc::new(image.clone());
  30. let mut images = images();
  31. images.retain(|m| m.image.base() != image.base());
  32. images.push(Mapped {
  33. image,
  34. attached: false,
  35. quiet: false,
  36. });
  37. }
  38. /// Its `DLL_PROCESS_ATTACH` is done. The list keeps attach order, which is
  39. /// the Windows loader's initialisation order.
  40. pub(crate) fn attached(base: usize) {
  41. let mut images = images();
  42. if let Some(i) = images.iter().position(|m| m.image.base() == base) {
  43. let mut m = images.remove(i);
  44. m.attached = true;
  45. images.push(m);
  46. }
  47. static AT_EXIT: std::sync::Once = std::sync::Once::new();
  48. // Registered before the title's own exit functions, so it runs after
  49. // them, as `ExitProcess` follows `exit`'s functions on Windows.
  50. // SAFETY: registers a function with the host CRT's exit table.
  51. AT_EXIT.call_once(|| unsafe {
  52. atexit(detach_all);
  53. });
  54. }
  55. pub(crate) fn detached(base: usize) {
  56. if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) {
  57. m.attached = false;
  58. }
  59. }
  60. unsafe extern "C" {
  61. fn atexit(f: extern "C" fn()) -> i32;
  62. }
  63. /// Set once the process is ending: no more thread notices.
  64. static EXITING: AtomicBool = AtomicBool::new(false);
  65. /// How long title images may take to detach before the process ends anyway
  66. /// (a thread ended while holding a lock their detach code wants).
  67. const DETACH_DEADLINE: Duration = Duration::from_secs(5);
  68. /// Process exit (the CRT's `exit`, which titles call), in `ExitProcess`'s
  69. /// order: the title's exit functions have run; every other thread ends
  70. /// (title threads and ours); every attached image gets
  71. /// `DLL_PROCESS_DETACH`, DLLs in reverse initialisation order, then the
  72. /// exe's TLS callbacks; then the CRT ends the process.
  73. extern "C" fn detach_all() {
  74. let attached: Vec<_> = images()
  75. .iter_mut()
  76. .filter(|m| m.attached)
  77. .map(|m| {
  78. m.attached = false;
  79. m.image.clone()
  80. })
  81. .collect();
  82. let (dlls, exes): (Vec<_>, Vec<_>) =
  83. attached.into_iter().rev().partition(|i| i.info().is_dll());
  84. tracing::info!(
  85. images = dlls.len() + exes.len(),
  86. "process exit: ending other threads, detaching title images"
  87. );
  88. EXITING.store(true, Ordering::SeqCst);
  89. // As on Windows, a lock a thread held when it ended stays taken; detach
  90. // code that waits for one would hang the exit. The watchdog runs before
  91. // the other threads end: a thread that ends can hold the heap lock or
  92. // the loader lock, and a new thread needs both to start. After the
  93. // deadline it only ends the process; it does not log, because logging
  94. // needs the heap and the log writer's lock.
  95. // Its thread id, set when it runs its own code; 0 until then.
  96. static WATCHDOG: AtomicU32 = AtomicU32::new(0);
  97. drop(std::thread::spawn(|| {
  98. // SAFETY: a plain query of the calling thread.
  99. let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
  100. WATCHDOG.store(id, Ordering::SeqCst);
  101. std::thread::sleep(DETACH_DEADLINE);
  102. end_process();
  103. }));
  104. // Its start (loader notices, Rust's thread set-up) is done only when
  105. // it runs its own code. The loader notices need the loader lock. This
  106. // thread can hold it, or a thread that waits for this thread can hold
  107. // it. Then the watchdog does not start, so this wait has the same
  108. // deadline.
  109. let waiting = Instant::now();
  110. let watchdog = loop {
  111. match WATCHDOG.load(Ordering::SeqCst) {
  112. 0 if waiting.elapsed() >= DETACH_DEADLINE => end_process(),
  113. 0 => std::thread::yield_now(),
  114. id => break id,
  115. }
  116. };
  117. end_other_threads(&[watchdog]);
  118. for image in dlls.iter().chain(&exes) {
  119. // SAFETY: attached images are bound. A non-null third argument
  120. // tells the entry points the process is ending.
  121. unsafe {
  122. image.notify(
  123. DLL_PROCESS_DETACH,
  124. true,
  125. std::ptr::without_provenance_mut(1),
  126. )
  127. };
  128. }
  129. }
  130. /// Ends this process when the title images do not detach in time. It does
  131. /// not use the heap or any lock: a thread that ended can hold them.
  132. fn end_process() {
  133. // SAFETY: ends this process, which is exiting anyway.
  134. unsafe {
  135. windows_sys::Win32::System::Threading::TerminateProcess(
  136. windows_sys::Win32::System::Threading::GetCurrentProcess(),
  137. 1,
  138. )
  139. };
  140. }
  141. /// Ends every thread of the process but this one and those in `keep` (and
  142. /// the ones started while doing so), as `ExitProcess` does first; except
  143. /// the system's thread-pool workers, which `TerminateThread` refuses (the
  144. /// process fails fast) and which run no title code (no title image uses
  145. /// that pool).
  146. fn end_other_threads(keep: &[u32]) {
  147. use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
  148. use windows_sys::Win32::System::Diagnostics::ToolHelp::{
  149. CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
  150. };
  151. use windows_sys::Win32::System::Threading::{
  152. GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread,
  153. THREAD_QUERY_INFORMATION,
  154. };
  155. // SAFETY: plain queries of the calling process and thread.
  156. let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) };
  157. let mut ended = std::collections::HashSet::new();
  158. loop {
  159. // SAFETY: a snapshot of every thread, walked with a sized entry.
  160. let others: Vec<u32> = unsafe {
  161. let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
  162. if snapshot == INVALID_HANDLE_VALUE {
  163. break;
  164. }
  165. let mut entry = THREADENTRY32 {
  166. dwSize: size_of::<THREADENTRY32>() as u32,
  167. ..std::mem::zeroed()
  168. };
  169. let mut ids = Vec::new();
  170. let mut more = Thread32First(snapshot, &mut entry) != 0;
  171. while more {
  172. if entry.th32OwnerProcessID == process
  173. && entry.th32ThreadID != me
  174. && !keep.contains(&entry.th32ThreadID)
  175. {
  176. ids.push(entry.th32ThreadID);
  177. }
  178. more = Thread32Next(snapshot, &mut entry) != 0;
  179. }
  180. CloseHandle(snapshot);
  181. ids
  182. };
  183. let new: Vec<u32> = others.into_iter().filter(|id| ended.insert(*id)).collect();
  184. if new.is_empty() {
  185. break;
  186. }
  187. for id in new {
  188. // SAFETY: a thread of this process, which is exiting.
  189. unsafe {
  190. let thread = OpenThread(THREAD_TERMINATE | THREAD_QUERY_INFORMATION, 0, id);
  191. if !thread.is_null() {
  192. if !starts_in(thread, c"ntdll.dll") {
  193. TerminateThread(thread, 0);
  194. }
  195. CloseHandle(thread);
  196. }
  197. }
  198. }
  199. }
  200. }
  201. pub(crate) fn unmapped(base: usize) {
  202. images().retain(|m| m.image.base() != base);
  203. }
  204. /// `DisableThreadLibraryCalls` for a title image; `None` if `base` is not
  205. /// one. Fails, as on Windows, for an image with static TLS.
  206. pub fn disable_thread_calls(base: usize) -> Option<bool> {
  207. let mut images = images();
  208. let m = images.iter_mut().find(|m| m.image.base() == base)?;
  209. if m.image.info().tls.is_some() {
  210. return Some(false);
  211. }
  212. m.quiet = true;
  213. Some(true)
  214. }
  215. /// Windows calls every pointer between the CRT's markers `.CRT$XLA` and
  216. /// `.CRT$XLZ`; `XLAV` sorts ahead of the usual `XLB`, so ours runs before
  217. /// any other callback linked into the exe.
  218. #[used]
  219. #[unsafe(link_section = ".CRT$XLAV")]
  220. static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread;
  221. unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) {
  222. if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH {
  223. return;
  224. }
  225. if EXITING.load(Ordering::SeqCst) {
  226. return; // our exit watchdog, or threads ending with the process
  227. }
  228. // A snapshot: title code may map and attach another DLL from here.
  229. let notify: Vec<_> = images()
  230. .iter()
  231. .filter(|m| m.attached)
  232. .map(|m| (m.image.clone(), !m.quiet))
  233. .collect();
  234. if notify.is_empty() {
  235. return;
  236. }
  237. // Rust's std sets its threads up after this callback and aborts the
  238. // process if their per-thread state was touched first (the current
  239. // thread's id, which our logging asks for when title code calls us).
  240. // That state is put back as the thread started.
  241. let saved = (reason == DLL_THREAD_ATTACH && started_by_rust()).then(OwnTls::save);
  242. // Starts in load order, ends in reverse, as the Windows loader does.
  243. let notify_one = |(image, dll_main): &(Arc<LoadedImage>, bool)| {
  244. // SAFETY: attached images have their imports bound.
  245. unsafe { image.notify(reason, *dll_main, std::ptr::null_mut()) };
  246. };
  247. if reason == DLL_THREAD_ATTACH {
  248. notify.iter().for_each(notify_one);
  249. } else {
  250. notify.iter().rev().for_each(notify_one);
  251. }
  252. if let Some(saved) = saved {
  253. saved.restore();
  254. }
  255. }
  256. /// Our own image's static TLS block on this thread (Rust's std keeps its
  257. /// per-thread state there), as copied before title code ran.
  258. struct OwnTls {
  259. block: *mut u8,
  260. saved: Vec<u8>,
  261. }
  262. /// The TLS directory the linker emits for our image (the CRT's symbol).
  263. #[repr(C)]
  264. struct TlsDirectory {
  265. start: usize,
  266. end: usize,
  267. index: *const u32,
  268. callbacks: usize,
  269. zero_fill: u32,
  270. characteristics: u32,
  271. }
  272. unsafe extern "C" {
  273. static _tls_used: TlsDirectory;
  274. }
  275. impl OwnTls {
  276. fn save() -> OwnTls {
  277. let array: *const *mut u8;
  278. // SAFETY: reads TEB.ThreadLocalStoragePointer; the directory is our
  279. // image's, and Windows set up its block on this thread before
  280. // calling TLS callbacks.
  281. let (block, len) = unsafe {
  282. std::arch::asm!("mov {}, gs:[0x58]", out(reg) array, options(nostack, readonly));
  283. let dir = &raw const _tls_used;
  284. let block = *array.add((*dir).index.read() as usize);
  285. (block, (*dir).end - (*dir).start + (*dir).zero_fill as usize)
  286. };
  287. // SAFETY: the block is `len` bytes, live for the thread's life.
  288. let saved = unsafe { std::slice::from_raw_parts(block, len) }.to_vec();
  289. OwnTls { block, saved }
  290. }
  291. fn restore(self) {
  292. // SAFETY: the same block on the same thread, no reference to it held.
  293. unsafe { std::ptr::copy_nonoverlapping(self.saved.as_ptr(), self.block, self.saved.len()) };
  294. }
  295. }
  296. /// Whether Rust's std started this thread (its start routine is in our
  297. /// exe): the title's main thread and our runtime's workers, which run
  298. /// title callbacks.
  299. fn started_by_rust() -> bool {
  300. // SAFETY: the calling thread's pseudo handle.
  301. starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"")
  302. }
  303. /// Whether `thread`'s start routine lies in the module named `module`
  304. /// (empty: our exe).
  305. fn starts_in(thread: windows_sys::Win32::Foundation::HANDLE, module: &std::ffi::CStr) -> bool {
  306. use windows_sys::Wdk::System::Threading::{
  307. NtQueryInformationThread, ThreadQuerySetWin32StartAddress,
  308. };
  309. use windows_sys::Win32::System::LibraryLoader::{
  310. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
  311. GetModuleHandleA, GetModuleHandleExW,
  312. };
  313. let mut start = 0usize;
  314. // SAFETY: writes one pointer-sized start address.
  315. let status = unsafe {
  316. NtQueryInformationThread(
  317. thread,
  318. ThreadQuerySetWin32StartAddress,
  319. (&raw mut start).cast(),
  320. size_of::<usize>() as u32,
  321. std::ptr::null_mut(),
  322. )
  323. };
  324. let mut found = std::ptr::null_mut();
  325. let name = if module.is_empty() {
  326. std::ptr::null()
  327. } else {
  328. module.as_ptr().cast()
  329. };
  330. // SAFETY: looks up the module containing an address, taking no reference.
  331. status == 0
  332. && unsafe {
  333. GetModuleHandleExW(
  334. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
  335. start as *const u16,
  336. &mut found,
  337. )
  338. } != 0
  339. // SAFETY: a module handle by name (or our exe's); no reference taken.
  340. && found == unsafe { GetModuleHandleA(name) }
  341. }
  342. #[cfg(test)]
  343. mod tests {
  344. use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
  345. use std::time::Duration;
  346. /// A thread that counts in `ticks` until it ends; returns its thread id
  347. /// when it has counted once.
  348. fn busy(ticks: &'static AtomicU64) -> u32 {
  349. static ID: AtomicU32 = AtomicU32::new(0);
  350. ID.store(0, Ordering::SeqCst);
  351. std::thread::spawn(move || {
  352. // SAFETY: a plain query of the calling thread.
  353. let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
  354. ID.store(id, Ordering::SeqCst);
  355. loop {
  356. ticks.fetch_add(1, Ordering::SeqCst);
  357. std::thread::yield_now();
  358. }
  359. });
  360. while ticks.load(Ordering::SeqCst) == 0 {
  361. std::thread::yield_now();
  362. }
  363. ID.load(Ordering::SeqCst)
  364. }
  365. /// Whether `ticks` stays the same for a short time.
  366. fn stopped(ticks: &AtomicU64) -> bool {
  367. let at = ticks.load(Ordering::SeqCst);
  368. std::thread::sleep(Duration::from_millis(50));
  369. ticks.load(Ordering::SeqCst) == at
  370. }
  371. /// In a child process of the next test: ends the other threads but one
  372. /// kept thread, and checks that a busy thread stopped and the kept one
  373. /// did not.
  374. #[test]
  375. fn exit_child() {
  376. if std::env::var_os("VICTORY_EXIT_CHILD").is_none() {
  377. return;
  378. }
  379. static ENDS: AtomicU64 = AtomicU64::new(0);
  380. static KEPT: AtomicU64 = AtomicU64::new(0);
  381. busy(&ENDS);
  382. let kept = busy(&KEPT);
  383. super::end_other_threads(&[kept]);
  384. let ended = stopped(&ENDS);
  385. let still_running = !stopped(&KEPT);
  386. // The test harness's threads are gone too: leave at once.
  387. println!(
  388. "{} {}",
  389. if ended { "ENDED" } else { "STILL RUNNING" },
  390. if still_running { "KEPT" } else { "NOT KEPT" }
  391. );
  392. std::process::exit(0);
  393. }
  394. #[test]
  395. fn exit_ends_the_other_threads_first() {
  396. let out = std::process::Command::new(std::env::current_exe().unwrap())
  397. .args(["--exact", "threads::tests::exit_child", "--nocapture"])
  398. .env("VICTORY_EXIT_CHILD", "1")
  399. .output()
  400. .unwrap();
  401. let text = String::from_utf8_lossy(&out.stdout);
  402. assert!(
  403. out.status.success() && text.contains("ENDED KEPT"),
  404. "{text}"
  405. );
  406. }
  407. }