stacks.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 mut times: Vec<f64> = list
  27. .split(',')
  28. .filter_map(|t| t.trim().parse().ok())
  29. .collect();
  30. times.sort_by(f64::total_cmp);
  31. let start = std::time::Instant::now();
  32. std::thread::spawn(move || {
  33. for t in times {
  34. let at = std::time::Duration::from_secs_f64(t.max(0.0));
  35. std::thread::sleep(at.saturating_sub(start.elapsed()));
  36. dump_stacks();
  37. }
  38. });
  39. }
  40. /// `THREAD_BASIC_INFORMATION` (ntddk).
  41. #[repr(C)]
  42. struct BasicInfo {
  43. exit_status: i32,
  44. teb: *const usize,
  45. client_id: [usize; 2],
  46. affinity: usize,
  47. priority: i32,
  48. base_priority: i32,
  49. }
  50. /// `GetThreadContext` wants a 16-byte aligned context.
  51. #[repr(C, align(16))]
  52. struct Aligned(CONTEXT);
  53. /// Prints every other thread's stack to stderr. Each thread is suspended
  54. /// only while its context is read and unwound into a buffer allocated
  55. /// beforehand (it may hold the heap lock).
  56. pub fn dump_stacks() {
  57. // SAFETY: plain queries and a snapshot of this process's threads.
  58. let (me, process, snapshot) = unsafe {
  59. (
  60. GetCurrentThreadId(),
  61. GetCurrentProcessId(),
  62. CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0),
  63. )
  64. };
  65. if snapshot == INVALID_HANDLE_VALUE {
  66. return;
  67. }
  68. let mut ids = Vec::new();
  69. // SAFETY: zeroed is a valid THREADENTRY32; its size is set before use.
  70. let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
  71. entry.dwSize = size_of::<THREADENTRY32>() as u32;
  72. // SAFETY: `snapshot` is open; `entry` is sized.
  73. let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0;
  74. while more {
  75. if entry.th32OwnerProcessID == process && entry.th32ThreadID != me {
  76. ids.push(entry.th32ThreadID);
  77. }
  78. // SAFETY: as above.
  79. more = unsafe { Thread32Next(snapshot, &mut entry) } != 0;
  80. }
  81. // SAFETY: we opened it.
  82. unsafe { CloseHandle(snapshot) };
  83. eprintln!("VIctory: stacks of {} threads", ids.len());
  84. for id in ids {
  85. // SAFETY: opens a thread of our own process.
  86. let thread = unsafe {
  87. OpenThread(
  88. THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
  89. 0,
  90. id,
  91. )
  92. };
  93. if thread.is_null() {
  94. continue;
  95. }
  96. let (frames, (priority, base)) = frames_of(thread);
  97. eprintln!(
  98. " thread {id} \"{}\" start {} priority {priority} (base {base})",
  99. name_of(thread),
  100. locate(start_of(thread))
  101. );
  102. for (i, pc) in frames.into_iter().enumerate() {
  103. eprintln!(" #{i:<2} {}", locate(pc as usize));
  104. }
  105. // SAFETY: we opened it.
  106. unsafe { CloseHandle(thread) };
  107. }
  108. }
  109. /// The thread's frames and its current and base scheduling priority (0-31).
  110. fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32)) {
  111. let mut frames = Vec::with_capacity(MAX_FRAMES);
  112. let mut info: BasicInfo = BasicInfo {
  113. exit_status: 0,
  114. teb: std::ptr::null(),
  115. client_id: [0; 2],
  116. affinity: 0,
  117. priority: 0,
  118. base_priority: 0,
  119. };
  120. // SAFETY: writes `info`, whose layout and size are the system's.
  121. let status = unsafe {
  122. NtQueryInformationThread(
  123. thread,
  124. ThreadBasicInformation,
  125. (&raw mut info).cast(),
  126. size_of::<BasicInfo>() as u32,
  127. std::ptr::null_mut(),
  128. )
  129. };
  130. if status != 0 || info.teb.is_null() {
  131. return (frames, (0, 0));
  132. }
  133. // SAFETY: the TEB of a live thread of this process: its NT_TIB holds
  134. // the stack base at +8 and the stack limit at +0x10.
  135. let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) };
  136. // SAFETY: zeroed is a valid CONTEXT.
  137. let mut context = Aligned(unsafe { std::mem::zeroed() });
  138. context.0.ContextFlags = CONTEXT_FULL_AMD64;
  139. // SAFETY: suspends, reads and resumes a thread that is not this one;
  140. // nothing between suspend and resume allocates or takes a lock the
  141. // thread could hold besides the unwinder's own.
  142. unsafe {
  143. if SuspendThread(thread) == u32::MAX {
  144. return (frames, (info.priority, info.base_priority));
  145. }
  146. if GetThreadContext(thread, &mut context.0) != 0 {
  147. unwind_into(context.0, low, high, &mut frames);
  148. }
  149. ResumeThread(thread);
  150. }
  151. (frames, (info.priority, info.base_priority))
  152. }
  153. fn start_of(thread: HANDLE) -> usize {
  154. let mut start = 0usize;
  155. // SAFETY: writes one pointer-sized start address.
  156. unsafe {
  157. NtQueryInformationThread(
  158. thread,
  159. ThreadQuerySetWin32StartAddress,
  160. (&raw mut start).cast(),
  161. size_of::<usize>() as u32,
  162. std::ptr::null_mut(),
  163. )
  164. };
  165. start
  166. }
  167. fn name_of(thread: HANDLE) -> String {
  168. let mut name = std::ptr::null_mut();
  169. // SAFETY: the system allocates the string; we free it with LocalFree.
  170. unsafe {
  171. if GetThreadDescription(thread, &mut name) < 0 || name.is_null() {
  172. return String::new();
  173. }
  174. let len = (0..).take_while(|&i| *name.add(i) != 0).count();
  175. let text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len));
  176. LocalFree(name.cast::<c_void>());
  177. text
  178. }
  179. }
  180. #[cfg(test)]
  181. mod tests {
  182. use super::*;
  183. #[test]
  184. fn another_threads_stack_unwinds_to_its_start() {
  185. let (tx, rx) = std::sync::mpsc::channel();
  186. let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
  187. let parked = std::thread::spawn(move || {
  188. // SAFETY: plain query.
  189. tx.send(unsafe { GetCurrentThreadId() }).unwrap();
  190. stop_rx.recv().ok();
  191. });
  192. let id = rx.recv().unwrap();
  193. // SAFETY: a thread of this process.
  194. let thread = unsafe {
  195. OpenThread(
  196. THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
  197. 0,
  198. id,
  199. )
  200. };
  201. assert!(!thread.is_null());
  202. let (frames, _) = frames_of(thread);
  203. // Waiting in the kernel, several frames down from the thread start.
  204. assert!(frames.len() >= 3, "{frames:?}");
  205. assert!(start_of(thread) != 0);
  206. // SAFETY: opened above.
  207. unsafe { CloseHandle(thread) };
  208. dump_stacks();
  209. stop_tx.send(()).unwrap();
  210. parked.join().unwrap();
  211. }
  212. }