//! The calling thread's identity, and the room left on its stack, read at any point of the //! thread's life. //! //! A program's exit handlers run on the thread that called `exit`, after the C library destroyed //! that thread's thread-locals (macOS's `exit` and the GNU C library's run their destructors //! first): a thread-local that needs dropping is gone there, read with `with` it panics, and so //! does `std::thread::current` once the thread's handle went with them. In an exit handler, which //! cannot unwind, the panic ends the process. Each thread-local of the runtime's that a program's //! call reaches is read with `try_with` or holds nothing to drop, and the calls ask this module, //! not `std::thread::current`, which thread they run on. use std::cell::Cell; use std::thread::JoinHandle; /// This thread's identity among the live threads: the address of a thread-local of nothing to /// drop, which stays readable to the thread's end. No two live threads share one; a thread that /// starts after another ended may take its address. pub(crate) fn id() -> usize { thread_local! { static HERE: u8 = const { 0 }; } HERE.with(|here| std::ptr::from_ref(here).addr()) } /// The bytes of the calling thread's stack below the caller's frame: `None` where the system does /// not say where the thread's stack ends, or once the thread's thread-locals are gone (an exit /// handler). Where the stack ends is read once a thread, at its first ask. pub(crate) fn stack_room() -> Option { thread_local! { /// The lowest address of this thread's stack, once read; nothing to drop. static LOW: Cell>> = const { Cell::new(None) }; } let low = LOW .try_with(|low| { let read = low.get().unwrap_or_else(stack_low); low.set(Some(read)); read }) .ok()??; let here = 0u8; std::ptr::from_ref(std::hint::black_box(&here)) .addr() .checked_sub(low) } /// The lowest address of the calling thread's stack (`pthread_attr_getstack` of /// `pthread_getattr_np`'s attributes); `None` where the system answers none. #[cfg(any(target_os = "linux", target_os = "android"))] fn stack_low() -> Option { let mut attributes = std::mem::MaybeUninit::::uninit(); // SAFETY: the calling thread's own attributes, read into `attributes`, which are destroyed // once read. unsafe { if libc::pthread_getattr_np(libc::pthread_self(), attributes.as_mut_ptr()) != 0 { return None; } let (mut low, mut size) = (std::ptr::null_mut(), 0); let read = libc::pthread_attr_getstack(attributes.as_ptr(), &mut low, &mut size); libc::pthread_attr_destroy(attributes.as_mut_ptr()); (read == 0).then(|| low.addr()) } } /// The lowest address of the calling thread's stack: its top /// (`pthread_get_stackaddr_np`) less its size (`pthread_get_stacksize_np`). #[cfg(target_vendor = "apple")] fn stack_low() -> Option { // SAFETY: reads of the calling thread's own stack's top and size; no pointer is followed. let (top, size) = unsafe { ( libc::pthread_get_stackaddr_np(libc::pthread_self()), libc::pthread_get_stacksize_np(libc::pthread_self()), ) }; top.addr().checked_sub(size) } /// The lowest address of the calling thread's stack (`GetCurrentThreadStackLimits`). #[cfg(windows)] fn stack_low() -> Option { use windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits; let (mut low, mut high) = (0, 0); // SAFETY: two out-parameters for the calling thread's stack limits. unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; (low != 0).then_some(low) } /// None: no answer here. #[cfg(not(any( target_os = "linux", target_os = "android", target_vendor = "apple", windows )))] fn stack_low() -> Option { None } /// Whether `handle`'s thread is this one: a thread of the runtime's own whose teardown it runs, /// which it does not join. pub(crate) fn runs(handle: &JoinHandle) -> bool { #[cfg(unix)] { use std::os::unix::thread::JoinHandleExt; // SAFETY: reads of two threads' identifiers; `handle`'s thread is neither joined nor // detached while the handle lives. unsafe { libc::pthread_equal(handle.as_pthread_t(), libc::pthread_self()) != 0 } } #[cfg(not(unix))] { handle.thread().id() == std::thread::current().id() } } /// The calling thread's CPU time on Windows, in nanoseconds: its kernel and user times /// (`GetThreadTimes`), each counted in 100 ns units; `None` where the system answers none. #[cfg(windows)] pub(crate) fn cpu_nanos() -> Option { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; let (mut created, mut exited) = (FILETIME::default(), FILETIME::default()); let (mut kernel, mut user) = (FILETIME::default(), FILETIME::default()); // SAFETY: the pseudo-handle of the calling thread, and four valid `FILETIME`s to fill. let read = unsafe { GetThreadTimes( GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user, ) }; if read == 0 { return None; } let ticks = |time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime); ticks(kernel).checked_add(ticks(user))?.checked_mul(100) }