stacks.rs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. //! Where every thread is: `VICTORY_STACKS=<seconds>[,<seconds>...]` prints
  2. //! each thread's unwound stack as `module+rva` that many seconds after
  3. //! [`dump_stacks_on_schedule`], to find what a title waits on.
  4. use std::ffi::c_void;
  5. use windows_sys::Wdk::System::Threading::{
  6. NtQueryInformationThread, ThreadBasicInformation, ThreadQuerySetWin32StartAddress,
  7. };
  8. use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, LocalFree};
  9. use windows_sys::Win32::System::Diagnostics::Debug::{
  10. CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext,
  11. };
  12. use windows_sys::Win32::System::Diagnostics::ToolHelp::{
  13. CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
  14. };
  15. use windows_sys::Win32::System::Threading::{
  16. GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread,
  17. SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME,
  18. };
  19. use crate::crash::{MAX_FRAMES, locate, unwind_into};
  20. /// Reads `VICTORY_STACKS` and, if set, starts a thread that prints every
  21. /// thread's stack at each listed time (seconds from now).
  22. pub fn dump_stacks_on_schedule() {
  23. let Ok(list) = std::env::var("VICTORY_STACKS") else {
  24. return;
  25. };
  26. let times = schedule(&list);
  27. let start = std::time::Instant::now();
  28. std::thread::spawn(move || {
  29. for at in times {
  30. std::thread::sleep(at.saturating_sub(start.elapsed()));
  31. dump_stacks();
  32. }
  33. });
  34. }
  35. /// The times in a `VICTORY_STACKS` list (seconds, comma-separated), in
  36. /// order. Negative times are now; times no `Duration` holds (`inf`, `NaN`,
  37. /// `1e20`) are left out instead of panicking the dump thread.
  38. fn schedule(list: &str) -> Vec<std::time::Duration> {
  39. let mut times: Vec<_> = list
  40. .split(',')
  41. .filter_map(|t| t.trim().parse::<f64>().ok())
  42. .filter(|t| !t.is_nan())
  43. .filter_map(|t| std::time::Duration::try_from_secs_f64(t.max(0.0)).ok())
  44. .collect();
  45. times.sort();
  46. times
  47. }
  48. /// `THREAD_BASIC_INFORMATION` (ntddk).
  49. #[repr(C)]
  50. struct BasicInfo {
  51. exit_status: i32,
  52. teb: *const usize,
  53. client_id: [usize; 2],
  54. affinity: usize,
  55. priority: i32,
  56. base_priority: i32,
  57. }
  58. /// `GetThreadContext` wants a 16-byte aligned context.
  59. #[repr(C, align(16))]
  60. struct Aligned(CONTEXT);
  61. /// The ids of this process's threads but the caller's.
  62. pub(crate) fn other_threads() -> Vec<u32> {
  63. // SAFETY: plain queries and a snapshot of this process's threads.
  64. let (me, process, snapshot) = unsafe {
  65. (
  66. GetCurrentThreadId(),
  67. GetCurrentProcessId(),
  68. CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0),
  69. )
  70. };
  71. if snapshot == INVALID_HANDLE_VALUE {
  72. return Vec::new();
  73. }
  74. let mut ids = Vec::new();
  75. // SAFETY: zeroed is a valid THREADENTRY32; its size is set before use.
  76. let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
  77. entry.dwSize = size_of::<THREADENTRY32>() as u32;
  78. // SAFETY: `snapshot` is open; `entry` is sized.
  79. let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0;
  80. while more {
  81. if entry.th32OwnerProcessID == process && entry.th32ThreadID != me {
  82. ids.push(entry.th32ThreadID);
  83. }
  84. // SAFETY: as above.
  85. more = unsafe { Thread32Next(snapshot, &mut entry) } != 0;
  86. }
  87. // SAFETY: we opened it.
  88. unsafe { CloseHandle(snapshot) };
  89. ids
  90. }
  91. /// Prints every other thread's stack to stderr. Each thread is suspended
  92. /// only while its context is read and unwound into a buffer allocated
  93. /// beforehand (it may hold the heap lock).
  94. pub fn dump_stacks() {
  95. let ids = other_threads();
  96. eprintln!("VIctory: stacks of {} threads", ids.len());
  97. for id in ids {
  98. // SAFETY: opens a thread of our own process.
  99. let thread = unsafe {
  100. OpenThread(
  101. THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
  102. 0,
  103. id,
  104. )
  105. };
  106. if thread.is_null() {
  107. continue;
  108. }
  109. let (frames, (priority, base, affinity)) = frames_of(thread);
  110. eprintln!(
  111. " thread {id} \"{}\" start {} priority {priority} (base {base}) affinity {affinity:#x}",
  112. name_of(thread),
  113. locate(start_of(thread))
  114. );
  115. for (i, pc) in frames.into_iter().enumerate() {
  116. eprintln!(" #{i:<2} {}", locate(pc as usize));
  117. }
  118. // SAFETY: we opened it.
  119. unsafe { CloseHandle(thread) };
  120. }
  121. }
  122. /// The thread's frames and its current and base scheduling priority (0-31).
  123. pub(crate) fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32, usize)) {
  124. let mut frames = Vec::with_capacity(MAX_FRAMES);
  125. let mut info: BasicInfo = BasicInfo {
  126. exit_status: 0,
  127. teb: std::ptr::null(),
  128. client_id: [0; 2],
  129. affinity: 0,
  130. priority: 0,
  131. base_priority: 0,
  132. };
  133. // Suspended first: a running thread may exit and free its TEB between
  134. // the query and the read below.
  135. // SAFETY: a thread of this process that is not this one.
  136. if unsafe { SuspendThread(thread) } == u32::MAX {
  137. return (frames, (0, 0, 0));
  138. }
  139. // SAFETY: writes `info`, whose layout and size are the system's.
  140. let status = unsafe {
  141. NtQueryInformationThread(
  142. thread,
  143. ThreadBasicInformation,
  144. (&raw mut info).cast(),
  145. size_of::<BasicInfo>() as u32,
  146. std::ptr::null_mut(),
  147. )
  148. };
  149. if status != 0 || info.teb.is_null() {
  150. // SAFETY: suspended above.
  151. unsafe { ResumeThread(thread) };
  152. return (frames, (0, 0, 0));
  153. }
  154. // SAFETY: the TEB of a suspended thread of this process: its NT_TIB
  155. // holds the stack base at +8 and the stack limit at +0x10.
  156. let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) };
  157. // SAFETY: zeroed is a valid CONTEXT.
  158. let mut context = Aligned(unsafe { std::mem::zeroed() });
  159. context.0.ContextFlags = CONTEXT_FULL_AMD64;
  160. // SAFETY: reads and resumes the thread suspended above; nothing until
  161. // the resume allocates or takes a lock the thread could hold besides
  162. // the unwinder's own.
  163. unsafe {
  164. if GetThreadContext(thread, &mut context.0) != 0 {
  165. unwind_into(context.0, low, high, &mut frames);
  166. }
  167. ResumeThread(thread);
  168. }
  169. (frames, (info.priority, info.base_priority, info.affinity))
  170. }
  171. pub(crate) fn start_of(thread: HANDLE) -> usize {
  172. let mut start = 0usize;
  173. // SAFETY: writes one pointer-sized start address.
  174. unsafe {
  175. NtQueryInformationThread(
  176. thread,
  177. ThreadQuerySetWin32StartAddress,
  178. (&raw mut start).cast(),
  179. size_of::<usize>() as u32,
  180. std::ptr::null_mut(),
  181. )
  182. };
  183. start
  184. }
  185. pub(crate) fn name_of(thread: HANDLE) -> String {
  186. let mut name = std::ptr::null_mut();
  187. // SAFETY: the system allocates the string; we free it with LocalFree.
  188. unsafe {
  189. if GetThreadDescription(thread, &mut name) < 0 || name.is_null() {
  190. return String::new();
  191. }
  192. let len = (0..).take_while(|&i| *name.add(i) != 0).count();
  193. let text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len));
  194. LocalFree(name.cast::<c_void>());
  195. text
  196. }
  197. }
  198. #[cfg(test)]
  199. mod tests {
  200. use super::*;
  201. #[test]
  202. fn another_threads_stack_unwinds_to_its_start() {
  203. let (tx, rx) = std::sync::mpsc::channel();
  204. let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
  205. let parked = std::thread::spawn(move || {
  206. // SAFETY: plain query.
  207. tx.send(unsafe { GetCurrentThreadId() }).unwrap();
  208. stop_rx.recv().ok();
  209. });
  210. let id = rx.recv().unwrap();
  211. // SAFETY: a thread of this process.
  212. let thread = unsafe {
  213. OpenThread(
  214. THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
  215. 0,
  216. id,
  217. )
  218. };
  219. assert!(!thread.is_null());
  220. let (frames, _) = frames_of(thread);
  221. // Waiting in the kernel, several frames down from the thread start.
  222. assert!(frames.len() >= 3, "{frames:?}");
  223. assert!(start_of(thread) != 0);
  224. // SAFETY: opened above.
  225. unsafe { CloseHandle(thread) };
  226. dump_stacks();
  227. stop_tx.send(()).unwrap();
  228. parked.join().unwrap();
  229. }
  230. /// Times no `Duration` holds are left out instead of panicking the dump
  231. /// thread (`from_secs_f64` panicked on `inf`); the rest come in order.
  232. #[test]
  233. fn schedules_skip_times_out_of_range() {
  234. let secs = |list| {
  235. schedule(list)
  236. .iter()
  237. .map(|d| d.as_secs_f64())
  238. .collect::<Vec<_>>()
  239. };
  240. assert_eq!(secs("30, 5,x,-2,inf,NaN,1e20"), [0.0, 5.0, 30.0]);
  241. assert!(schedule("").is_empty());
  242. }
  243. }