crash.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. //! Names the faulting code when title code crashes.
  2. //!
  3. //! A vectored handler sees every exception first, so it only prints the
  4. //! kinds that end a process (access violations and the like, and
  5. //! breakpoints: titles assert with `int3`, fatal without a debugger) as
  6. //! first-chance, since a handler may still take them (ntdll's loader does
  7. //! with its own probes). What nobody handles, of any kind (an uncaught C++
  8. //! exception too), is reported from the unhandled-exception filter
  9. //! (`report_unhandled`, which the runtime calls ahead of the title's own)
  10. //! and appended to the crash log, with the title's last debug output, which
  11. //! often states the reason. Panics of ours go to the crash log too.
  12. use std::ptr::null_mut;
  13. use windows_sys::Win32::Foundation::{
  14. EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, EXCEPTION_ILLEGAL_INSTRUCTION,
  15. EXCEPTION_INT_DIVIDE_BY_ZERO, EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE,
  16. };
  17. use windows_sys::Win32::System::Diagnostics::Debug::{
  18. AddVectoredExceptionHandler, CONTEXT, EXCEPTION_POINTERS, M128A, RtlLookupFunctionEntry,
  19. RtlVirtualUnwind, SetUnhandledExceptionFilter, UNW_FLAG_NHANDLER,
  20. };
  21. use windows_sys::Win32::System::LibraryLoader::{
  22. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
  23. GetModuleFileNameW, GetModuleHandleExW,
  24. };
  25. use windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits;
  26. const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
  27. /// Frames listed per report.
  28. pub(crate) const MAX_FRAMES: usize = 40;
  29. /// Memory saved to files when a crash is reported: (address, length, file).
  30. #[cfg(feature = "diagnostics")]
  31. static SAVE: std::sync::OnceLock<Vec<(usize, usize, std::path::PathBuf)>> =
  32. std::sync::OnceLock::new();
  33. /// Debugging aid: on a reported crash, also write each `[address, address
  34. /// + len)` (readable title memory, e.g. an engine table) to its file.
  35. #[cfg(feature = "diagnostics")]
  36. pub fn save_on_crash(ranges: Vec<(usize, usize, std::path::PathBuf)>) {
  37. let _ = SAVE.set(ranges);
  38. }
  39. /// The file crash reports are appended to, besides being printed.
  40. static LOG: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
  41. /// Also appends every unhandled-exception report and panic to `file`, so a
  42. /// crash can be read after the console is gone.
  43. pub fn log_crashes_to(file: std::path::PathBuf) {
  44. if LOG.set(file).is_ok() {
  45. let print = std::panic::take_hook();
  46. std::panic::set_hook(Box::new(move |info| {
  47. print(info);
  48. append_to_log(&format!(
  49. "VIctory: panic on thread {:?}: {info}\n{}",
  50. std::thread::current().name().unwrap_or("?"),
  51. title_output()
  52. ));
  53. }));
  54. }
  55. }
  56. /// Appends a failure that is not an exception (the host GPU's) to the crash
  57. /// log, with the title's last debug output, and prints it.
  58. pub fn log_crash(text: &str) {
  59. let text = format!("{text}
  60. {}", title_output());
  61. eprint!("{text}");
  62. append_to_log(&text);
  63. }
  64. fn append_to_log(text: &str) {
  65. use std::io::Write;
  66. let Some(file) = LOG.get() else { return };
  67. let now = std::time::SystemTime::now()
  68. .duration_since(std::time::UNIX_EPOCH)
  69. .map_or(0, |d| d.as_secs());
  70. let opened = std::fs::OpenOptions::new().create(true).append(true).open(file);
  71. if let Ok(mut f) = opened {
  72. let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id());
  73. }
  74. }
  75. /// The title's last lines of debug output, kept for crash reports.
  76. static SAID: std::sync::Mutex<std::collections::VecDeque<String>> =
  77. std::sync::Mutex::new(std::collections::VecDeque::new());
  78. const SAID_LINES: usize = 8;
  79. /// Keeps a line of the title's debug output for the next crash report.
  80. pub fn note_title_output(line: &str) {
  81. if line.is_empty() {
  82. return;
  83. }
  84. let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
  85. if said.len() == SAID_LINES {
  86. said.pop_front();
  87. }
  88. said.push_back(line.to_owned());
  89. }
  90. /// The kept lines, one per report line; nothing if another thread holds
  91. /// them (it may be the one that faulted).
  92. fn title_output() -> String {
  93. let Ok(said) = SAID.try_lock() else {
  94. return String::new();
  95. };
  96. said.iter().map(|l| format!(" title said: {l}\n")).collect()
  97. }
  98. /// Installs the handlers; call once before running title code.
  99. pub fn report_crashes() {
  100. unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 {
  101. // SAFETY: the system passes the exception being dispatched.
  102. unsafe { report_unhandled(info) };
  103. EXCEPTION_CONTINUE_SEARCH
  104. }
  105. // SAFETY: registers handlers that only read the exception they are
  106. // given; the title's own filter, once it sets one, takes the place of
  107. // ours and calls `report_unhandled` first.
  108. unsafe {
  109. AddVectoredExceptionHandler(0, Some(handler));
  110. SetUnhandledExceptionFilter(Some(filter));
  111. }
  112. }
  113. /// What the vectored handler reports as it happens.
  114. const FATAL: [i32; 6] = [
  115. EXCEPTION_ACCESS_VIOLATION,
  116. EXCEPTION_ILLEGAL_INSTRUCTION,
  117. EXCEPTION_PRIV_INSTRUCTION,
  118. EXCEPTION_INT_DIVIDE_BY_ZERO,
  119. EXCEPTION_STACK_OVERFLOW,
  120. EXCEPTION_BREAKPOINT,
  121. ];
  122. /// Console CPUs are Zen 2: titles use AMD-only instructions Intel CPUs
  123. /// lack. Does their job instead: `clzero` (`0f 01 fc`) zeroes the 64-byte
  124. /// line at `rax`; `monitorx`/`mwaitx` (`0f 01 fa`/`fb`) are wait hints, so
  125. /// a spin loop around them works with mwaitx as a yield.
  126. unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool {
  127. // SAFETY: the system passes valid exception pointers; the faulting
  128. // instruction's bytes are readable, as the CPU just fetched them.
  129. unsafe {
  130. let record = &*(*info).ExceptionRecord;
  131. let context = &mut *(*info).ContextRecord;
  132. if record.ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION {
  133. return false;
  134. }
  135. let code = context.Rip as *const u8;
  136. match code.cast::<[u8; 3]>().read_unaligned() {
  137. [0x0f, 0x01, 0xfc] => ((context.Rax & !63) as *mut u8).write_bytes(0, 64),
  138. [0x0f, 0x01, 0xfa] => {}
  139. [0x0f, 0x01, 0xfb] => std::thread::yield_now(),
  140. _ => {
  141. // Only bytes inside the faulting instruction's page are read: the next page may
  142. // not be mapped.
  143. let room = 0x1000 - (context.Rip as usize & 0xfff);
  144. let mut bytes = [0u8; 32];
  145. let n = room.min(bytes.len());
  146. std::ptr::copy_nonoverlapping(code, bytes.as_mut_ptr(), n);
  147. if let Some(pass) = clwb_loop(&bytes[..n]) {
  148. // A whole write-back loop in one exception (see `clwb_loop`).
  149. let limit = *gpr(context, pass.limit);
  150. let base = gpr(context, pass.base);
  151. *base = if *base <= limit {
  152. base.wrapping_add(((limit - *base) / 64 + 1) * 64)
  153. } else {
  154. base.wrapping_add(64)
  155. };
  156. let flags = cmp_flags(*base, limit);
  157. context.EFlags = context.EFlags & !CMP_FLAGS | flags;
  158. context.Rip += pass.len as u64;
  159. return true;
  160. }
  161. if n >= 15
  162. && let Some(len) = clwb_len(bytes[..15].try_into().unwrap_or([0; 15]))
  163. {
  164. // A write-back hint: the PC's memory is coherent, so it has nothing to do.
  165. context.Rip += len as u64;
  166. return true;
  167. }
  168. let Some(len) = sse4a(code, &mut context.Anonymous.FltSave.XmmRegisters) else {
  169. return false;
  170. };
  171. context.Rip += len as u64;
  172. return true;
  173. }
  174. }
  175. context.Rip += 3;
  176. }
  177. true
  178. }
  179. /// `clwb m8` (`66 [rex] 0f ae /6`, a memory operand), which Intel CPUs before
  180. /// Ice Lake lack: its length, or `None` for any other instruction.
  181. fn clwb_len(code: [u8; 15]) -> Option<usize> {
  182. let at = if code[1] & 0xf0 == 0x40 { 2 } else { 1 };
  183. if code[0] != 0x66 || code[at] != 0x0f || code[at + 1] != 0xae {
  184. return None;
  185. }
  186. let modrm = code[at + 2];
  187. let (mode, rm) = (modrm >> 6, modrm & 7);
  188. if mode == 3 || (modrm >> 3) & 7 != 6 {
  189. return None;
  190. }
  191. let mut len = at + 3;
  192. let mut base = rm;
  193. if rm == 4 {
  194. base = code[len] & 7;
  195. len += 1;
  196. }
  197. len += match mode {
  198. 0 if rm == 5 || (rm == 4 && base == 5) => 4,
  199. 1 => 1,
  200. 2 => 4,
  201. _ => 0,
  202. };
  203. Some(len)
  204. }
  205. /// A `clwb` write-back loop as the title's compilers build it, one cache line a
  206. /// pass (`base` and `limit` any registers):
  207. ///
  208. /// ```text
  209. /// top: clwb [base]
  210. /// add base, 0x40
  211. /// cmp base, limit
  212. /// jbe top
  213. /// ```
  214. ///
  215. /// An exception costs about a microsecond and the title writes back whole
  216. /// buffers this way while it loads, so the loop is done in one: `clwb` has
  217. /// nothing to do on the PC, `base` ends past `limit` as the last pass leaves it.
  218. struct ClwbLoop {
  219. base: u8,
  220. limit: u8,
  221. /// Bytes from `clwb` to the instruction after `jbe`.
  222. len: usize,
  223. }
  224. fn clwb_loop(code: &[u8]) -> Option<ClwbLoop> {
  225. // clwb [base]: 66 [40|41] 0f ae, ModRM mod 00, reg 6, no SIB or displacement.
  226. let (rex, at) = match code.get(1)? {
  227. 0x40 | 0x41 => (code[1], 2),
  228. _ => (0, 1),
  229. };
  230. if *code.first()? != 0x66 || code.get(at..at + 2)? != [0x0f, 0xae] {
  231. return None;
  232. }
  233. let modrm = *code.get(at + 2)?;
  234. let rm = modrm & 7;
  235. if modrm >> 6 != 0 || (modrm >> 3) & 7 != 6 || rm == 4 || rm == 5 {
  236. return None;
  237. }
  238. let base = rm | (rex & 1) << 3;
  239. // add base, 0x40: REX.W(+B) 83 /0 ib.
  240. let add = at + 3;
  241. if *code.get(add..add + 4)? != [0x48 | base >> 3, 0x83, 0xc0 | (base & 7), 0x40] {
  242. return None;
  243. }
  244. // cmp base, limit: REX.W 39 /r with base in r/m.
  245. let cmp = add + 4;
  246. let &[cmp_rex @ 0x48..=0x4f, 0x39, cmp_modrm] = code.get(cmp..cmp + 3)? else {
  247. return None;
  248. };
  249. if cmp_modrm >> 6 != 3 || (cmp_modrm & 7 | (cmp_rex & 1) << 3) != base {
  250. return None;
  251. }
  252. let limit = (cmp_modrm >> 3) & 7 | (cmp_rex & 4) << 1;
  253. // jbe top.
  254. let jump = cmp + 3;
  255. let len = jump + 2;
  256. if *code.get(jump)? != 0x76 || i64::from(*code.get(jump + 1)? as i8) != -(len as i64) {
  257. return None;
  258. }
  259. (limit != base).then_some(ClwbLoop { base, limit, len })
  260. }
  261. /// The general register numbered `n` as instructions encode it.
  262. fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 {
  263. match n & 15 {
  264. 0 => &mut context.Rax,
  265. 1 => &mut context.Rcx,
  266. 2 => &mut context.Rdx,
  267. 3 => &mut context.Rbx,
  268. 4 => &mut context.Rsp,
  269. 5 => &mut context.Rbp,
  270. 6 => &mut context.Rsi,
  271. 7 => &mut context.Rdi,
  272. 8 => &mut context.R8,
  273. 9 => &mut context.R9,
  274. 10 => &mut context.R10,
  275. 11 => &mut context.R11,
  276. 12 => &mut context.R12,
  277. 13 => &mut context.R13,
  278. 14 => &mut context.R14,
  279. _ => &mut context.R15,
  280. }
  281. }
  282. /// The status flags `cmp a, b` leaves (CF, PF, AF, ZF, SF, OF) as `EFLAGS` bits.
  283. fn cmp_flags(a: u64, b: u64) -> u32 {
  284. let r = a.wrapping_sub(b);
  285. u32::from(a < b)
  286. | u32::from((r as u8).count_ones().is_multiple_of(2)) << 2
  287. | (((a ^ b ^ r) >> 4) as u32 & 1) << 4
  288. | u32::from(r == 0) << 6
  289. | ((r >> 63) as u32) << 7
  290. | ((((a ^ b) & (a ^ r)) >> 63) as u32) << 11
  291. }
  292. const CMP_FLAGS: u32 = 0x8d5;
  293. /// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on
  294. /// the saved XMM registers; returns the instruction's length.
  295. unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option<usize> {
  296. // SAFETY: the caller's code bytes are readable up to the instruction's end.
  297. let b = |i: usize| unsafe { code.add(i).read() };
  298. let prefix = b(0);
  299. let (rex, at) = if b(1) & 0xf0 == 0x40 {
  300. (b(1), 2)
  301. } else {
  302. (0, 1)
  303. };
  304. if !matches!(prefix, 0x66 | 0xf2) || b(at) != 0x0f || !matches!(b(at + 1), 0x78 | 0x79) {
  305. return None;
  306. }
  307. let modrm = b(at + 2);
  308. if modrm >> 6 != 3 {
  309. return None;
  310. }
  311. let dst = usize::from((modrm >> 3) & 7 | (rex & 4) << 1);
  312. let src = usize::from(modrm & 7 | (rex & 1) << 3);
  313. let immediate = b(at + 1) == 0x78;
  314. let (fields, len) = if immediate {
  315. ((b(at + 3), b(at + 4)), at + 5)
  316. } else {
  317. // extrq reads its fields from src's low half, insertq from its high.
  318. let f = if prefix == 0x66 { xmm[src].Low } else { xmm[src].High as u64 };
  319. ((f as u8, (f >> 8) as u8), at + 3)
  320. };
  321. let (n, at_bit) = (u32::from(fields.0 & 63), u32::from(fields.1 & 63));
  322. let bits = if n == 0 { 64 } else { n };
  323. let mask = if bits == 64 { u64::MAX } else { (1u64 << bits) - 1 };
  324. if prefix == 0x66 {
  325. // extrq: register form takes its fields from src, works on dst.
  326. if immediate && (modrm >> 3) & 7 != 0 {
  327. return None;
  328. }
  329. let target = if immediate { src } else { dst };
  330. xmm[target].Low = (xmm[target].Low >> at_bit) & mask;
  331. } else {
  332. let value = (xmm[src].Low & mask) << at_bit;
  333. xmm[dst].Low = xmm[dst].Low & !(mask << at_bit) | value;
  334. }
  335. Some(len)
  336. }
  337. unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
  338. // SAFETY: the system passes valid exception pointers.
  339. if unsafe { emulate_amd_only(info) } {
  340. return -1; // EXCEPTION_CONTINUE_EXECUTION
  341. }
  342. // SAFETY: as above.
  343. if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) {
  344. // SAFETY: as above.
  345. unsafe { report("first-chance exception", info, false) };
  346. }
  347. EXCEPTION_CONTINUE_SEARCH
  348. }
  349. /// For an unhandled-exception filter: reports the exception that is about
  350. /// to end the process, and appends it to the crash log.
  351. ///
  352. /// # Safety
  353. /// `info` comes from the system, for an exception being dispatched.
  354. pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) {
  355. // SAFETY: forwarded from the caller.
  356. unsafe { report("unhandled exception", info, true) };
  357. }
  358. /// MSVC's code for a C++ `throw`, and its magic first parameter.
  359. const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32;
  360. const CPP_MAGIC: usize = 0x1993_0520;
  361. /// What a C++ throw threw: the decorated name of its type, then its value
  362. /// where that names the cause (an integer, e.g. an HRESULT; a standard
  363. /// exception's message).
  364. ///
  365. /// # Safety
  366. /// `p` are the parameters of a live MSVC throw (`p[0]` the magic).
  367. unsafe fn thrown(p: &[usize]) -> String {
  368. // SAFETY: the throw's ThrowInfo, its RVAs relative to `p[3]`: catchable
  369. // type array at +12 (count, then type RVAs), each type's descriptor at
  370. // +4, whose decorated name starts at +16; the object is at `p[1]`.
  371. unsafe {
  372. let rva = |at: usize| (at as *const u32).read_unaligned() as usize;
  373. let types = p[3] + rva(p[2] + 12);
  374. let name = |i: usize| {
  375. let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4);
  376. std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char)
  377. .to_string_lossy()
  378. };
  379. let first = name(0);
  380. let value = match &*first {
  381. // int, unsigned, long (HRESULT), unsigned long
  382. ".H" | ".I" | ".J" | ".K" if p[1] != 0 => {
  383. format!(" = {:#010x}", (p[1] as *const u32).read_unaligned())
  384. }
  385. // std::exception keeps its message after the table pointer.
  386. _ if (0..rva(types)).any(|i| name(i) == ".?AVexception@std@@") => {
  387. let message = (p[1] as *const *const std::ffi::c_char).add(1).read();
  388. if message.is_null() {
  389. String::new()
  390. } else {
  391. format!(": {}", std::ffi::CStr::from_ptr(message).to_string_lossy())
  392. }
  393. }
  394. _ => String::new(),
  395. };
  396. format!("{first}{value}")
  397. }
  398. }
  399. /// # Safety
  400. /// See [`report_unhandled`].
  401. unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
  402. // SAFETY: the system passes valid exception pointers.
  403. let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) };
  404. let code = record.ExceptionCode;
  405. let at = record.ExceptionAddress as usize;
  406. let p = record.ExceptionInformation;
  407. let detail = if code == EXCEPTION_ACCESS_VIOLATION {
  408. let kind = match p[0] {
  409. 0 => "read",
  410. 1 => "write",
  411. _ => "execute",
  412. };
  413. format!(" ({kind} {:#x})", p[1])
  414. } else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC {
  415. // SAFETY: a live MSVC throw.
  416. format!(" (C++ {} thrown)", unsafe { thrown(&p) })
  417. } else {
  418. String::new()
  419. };
  420. // Printed line by line (a fault while unwinding must not lose the
  421. // lines before it), and kept for the file.
  422. let mut text = String::new();
  423. let mut line = |l: String| {
  424. eprintln!("{l}");
  425. text.push_str(&l);
  426. text.push('\n');
  427. };
  428. line(format!(
  429. "VIctory: {what} {:#010x} at {}{detail}",
  430. code as u32,
  431. locate(at)
  432. ));
  433. line(format!(
  434. " rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}",
  435. context.Rax,
  436. context.Rbx,
  437. context.Rcx,
  438. context.Rdx,
  439. context.Rsi,
  440. context.Rdi,
  441. context.Rsp,
  442. context.Rbp
  443. ));
  444. line(format!(
  445. " r8 {:#x} r9 {:#x} r10 {:#x} r11 {:#x} r12 {:#x} r13 {:#x} r14 {:#x} r15 {:#x}",
  446. context.R8,
  447. context.R9,
  448. context.R10,
  449. context.R11,
  450. context.R12,
  451. context.R13,
  452. context.R14,
  453. context.R15
  454. ));
  455. for (i, pc) in unwind(*context).into_iter().enumerate() {
  456. line(format!(" #{i:<2} {}", locate(pc as usize)));
  457. }
  458. if to_file {
  459. let said = title_output();
  460. eprint!("{said}");
  461. text.push_str(&said);
  462. append_to_log(&text);
  463. }
  464. #[cfg(feature = "diagnostics")]
  465. for (address, len, file) in SAVE.get().into_iter().flatten() {
  466. // SAFETY: the caller of `save_on_crash` named readable memory.
  467. let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) };
  468. let saved = std::fs::write(file, bytes);
  469. eprintln!(
  470. " saved {address:#x}+{len:#x} to {} ({saved:?})",
  471. file.display()
  472. );
  473. }
  474. }
  475. /// Return addresses of the faulting thread's frames, from the faulting
  476. /// instruction up, by the unwind data of each image (the Windows loader
  477. /// registered it for title images too). Code without unwind data (our
  478. /// thunks, leaf functions) is taken to have its return address at `rsp`.
  479. fn unwind(context: CONTEXT) -> Vec<u64> {
  480. let (mut low, mut high) = (0, 0);
  481. // SAFETY: writes the current thread's stack bounds.
  482. unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };
  483. let mut frames = Vec::with_capacity(MAX_FRAMES);
  484. unwind_into(context, low, high, &mut frames);
  485. frames
  486. }
  487. /// [`unwind`] for any thread of the process, its stack being `low..high`;
  488. /// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames`
  489. /// has that capacity (another thread may be suspended holding the heap).
  490. pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) {
  491. frames.push(context.Rip);
  492. while frames.len() < MAX_FRAMES {
  493. // Stop where reading the stack would fault inside this handler.
  494. let rsp = context.Rsp as usize;
  495. if rsp < low || rsp + 8 > high {
  496. break;
  497. }
  498. let mut image = 0;
  499. // SAFETY: looks up the function table entry covering `Rip`, if any.
  500. let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) };
  501. if entry.is_null() {
  502. // SAFETY: `rsp` is inside this thread's stack.
  503. context.Rip = unsafe { (rsp as *const u64).read() };
  504. context.Rsp += 8;
  505. } else {
  506. let (mut data, mut frame) = (null_mut(), 0);
  507. // SAFETY: `entry` belongs to `image`; the context is our copy.
  508. unsafe {
  509. RtlVirtualUnwind(
  510. UNW_FLAG_NHANDLER,
  511. image,
  512. context.Rip,
  513. entry,
  514. &mut context,
  515. &mut data,
  516. &mut frame,
  517. null_mut(),
  518. )
  519. };
  520. }
  521. if context.Rip == 0 {
  522. break;
  523. }
  524. frames.push(context.Rip);
  525. }
  526. }
  527. /// `module+rva`, or the bare address.
  528. pub fn locate(address: usize) -> String {
  529. module_of(address).unwrap_or_else(|| format!("{address:#x}"))
  530. }
  531. fn module_of(address: usize) -> Option<String> {
  532. let mut module: HMODULE = std::ptr::null_mut();
  533. // SAFETY: looks up the module containing `address`; no reference taken.
  534. let found = unsafe {
  535. GetModuleHandleExW(
  536. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
  537. address as *const u16,
  538. &mut module,
  539. )
  540. };
  541. if found == 0 {
  542. return None;
  543. }
  544. let mut path = [0u16; 260];
  545. // SAFETY: `module` is a loaded module; the buffer length is passed.
  546. let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) };
  547. let path = String::from_utf16_lossy(&path[..len as usize]);
  548. let name = path.rsplit('\\').next().unwrap_or(&path);
  549. Some(format!("{name}+{:#x}", address - module as usize))
  550. }
  551. #[cfg(test)]
  552. mod tests {
  553. use super::*;
  554. use windows_sys::Win32::System::Diagnostics::Debug::{
  555. EXCEPTION_RECORD, RtlCaptureContext, RtlCaptureStackBackTrace,
  556. };
  557. #[test]
  558. #[inline(never)]
  559. fn unwinds_like_the_system_walk() {
  560. // SAFETY: zeroed CONTEXT is valid; both calls write our buffers.
  561. let (frames, walked) = unsafe {
  562. let mut context: CONTEXT = std::mem::zeroed();
  563. RtlCaptureContext(&mut context);
  564. let mut walked = [null_mut(); 8];
  565. let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut());
  566. (unwind(context), walked[..usize::from(n)].to_vec())
  567. };
  568. // Frame 0 differs (two call sites in this function); callers agree.
  569. assert!(walked.len() >= 4, "{walked:?}");
  570. let ours: Vec<_> = frames[1..walked.len()]
  571. .iter()
  572. .map(|&f| f as usize)
  573. .collect();
  574. let system: Vec<_> = walked[1..].iter().map(|&f| f as usize).collect();
  575. assert_eq!(ours, system);
  576. }
  577. /// On an Intel CPU, the real instructions go through the vectored
  578. /// handler. On an AMD CPU they run natively, and the tests below test
  579. /// the emulation.
  580. #[test]
  581. fn clwb_loops() {
  582. // clwb [rcx]; add rcx, 0x40; cmp rcx, rax; jbe top
  583. let a = clwb_loop(&[
  584. 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf3,
  585. ])
  586. .expect("rcx loop");
  587. assert_eq!((a.base, a.limit, a.len), (1, 0, 13));
  588. // clwb [r9]; add r9, 0x40; cmp r9, rax; jbe top
  589. let b = clwb_loop(&[
  590. 0x66, 0x41, 0x0f, 0xae, 0x31, 0x49, 0x83, 0xc1, 0x40, 0x49, 0x39, 0xc1, 0x76, 0xf2,
  591. ])
  592. .expect("r9 loop");
  593. assert_eq!((b.base, b.limit, b.len), (9, 0, 14));
  594. // A different stride, a jump elsewhere, or a cut-off loop is not one.
  595. assert!(
  596. clwb_loop(&[
  597. 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x20, 0x48, 0x39, 0xc1, 0x76, 0xf3
  598. ])
  599. .is_none()
  600. );
  601. assert!(
  602. clwb_loop(&[
  603. 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf0
  604. ])
  605. .is_none()
  606. );
  607. assert!(clwb_loop(&[0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40]).is_none());
  608. // The flags the last cmp leaves: base just past limit.
  609. assert_eq!(cmp_flags(0x1040, 0x1000) & 0x41, 0); // CF and ZF clear: the loop ends
  610. assert_eq!(cmp_flags(0x1000, 0x1000) & 0x40, 0x40);
  611. }
  612. #[test]
  613. fn clwb_lengths() {
  614. let pad = |b: &[u8]| {
  615. let mut c = [0u8; 15];
  616. c[..b.len()].copy_from_slice(b);
  617. c
  618. };
  619. assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9]
  620. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax]
  621. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40]
  622. assert_eq!(
  623. clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])),
  624. Some(8)
  625. ); // [rax+disp32]
  626. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp]
  627. assert_eq!(
  628. clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])),
  629. Some(8)
  630. ); // [rip+disp32]
  631. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7
  632. assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66
  633. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form
  634. }
  635. #[test]
  636. fn clzero_zeroes_its_line_on_any_cpu() {
  637. report_crashes();
  638. #[repr(align(64))]
  639. struct Line([u8; 128]);
  640. let mut line = Line([0xff; 128]);
  641. let at = line.0.as_mut_ptr().wrapping_add(5); // inside the first line
  642. // SAFETY: clzero writes only the 64-byte line holding `at`, ours.
  643. unsafe { std::arch::asm!(".byte 0x0f, 0x01, 0xfc", in("rax") at) };
  644. assert!(line.0[..64].iter().all(|&b| b == 0));
  645. assert!(line.0[64..].iter().all(|&b| b == 0xff));
  646. // insertq xmm0, xmm1, len 16, at 16; then extrq xmm0, len 8, at 20.
  647. let out: u64;
  648. // SAFETY: touches only the named registers.
  649. unsafe {
  650. std::arch::asm!(
  651. "movq xmm0, {a}", "movq xmm1, {b}",
  652. ".byte 0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10",
  653. "movq {a}, xmm0",
  654. ".byte 0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14",
  655. "movq {b}, xmm0",
  656. a = inout(reg) 0x1111_2222_3333_4444u64 => _, b = inout(reg) 0xabcdu64 => out,
  657. out("xmm0") _, out("xmm1") _)
  658. };
  659. assert_eq!(out, 0xbc); // 0x1111_2222_abcd_4444 >> 20, 8 bits
  660. // SAFETY: monitorx/mwaitx are wait hints that write no memory.
  661. unsafe {
  662. std::arch::asm!(".byte 0x0f, 0x01, 0xfa", ".byte 0x0f, 0x01, 0xfb",
  663. in("rax") at, in("ecx") 0, in("edx") 0)
  664. };
  665. }
  666. fn reg(low: u64, high: u64) -> M128A {
  667. M128A {
  668. Low: low,
  669. High: high as i64,
  670. }
  671. }
  672. /// Gives `code` to the emulation as if it faulted with `exception` at
  673. /// its first byte, with `rax` and `xmm` as the saved registers. The
  674. /// emulation does not execute `code`, so this works on any CPU. Returns
  675. /// the number of bytes that the emulation skipped, or `None` if it did
  676. /// not emulate the instruction. `xmm` gets the saved registers after.
  677. fn emulate_as(exception: i32, code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option<u64> {
  678. // `int3` after the instruction, so that a decoder that reads too
  679. // far sees no valid bytes.
  680. let mut bytes = [0xcc_u8; 16];
  681. bytes[..code.len()].copy_from_slice(code);
  682. let start = bytes.as_ptr() as u64;
  683. // SAFETY: a zeroed record and context are valid; the emulation
  684. // reads only `bytes` and writes only `context` (and memory at
  685. // `rax` for clzero, which the caller owns).
  686. unsafe {
  687. let mut record: EXCEPTION_RECORD = std::mem::zeroed();
  688. record.ExceptionCode = exception;
  689. let mut context: CONTEXT = std::mem::zeroed();
  690. context.Rip = start;
  691. context.Rax = rax;
  692. context.Anonymous.FltSave.XmmRegisters = *xmm;
  693. let mut pointers = EXCEPTION_POINTERS {
  694. ExceptionRecord: &mut record,
  695. ContextRecord: &mut context,
  696. };
  697. let emulated = emulate_amd_only(&mut pointers);
  698. *xmm = context.Anonymous.FltSave.XmmRegisters;
  699. emulated.then(|| context.Rip - start)
  700. }
  701. }
  702. fn emulate(code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option<u64> {
  703. emulate_as(EXCEPTION_ILLEGAL_INSTRUCTION, code, rax, xmm)
  704. }
  705. fn low(xmm: &[M128A; 16], i: usize) -> u64 {
  706. xmm[i].Low
  707. }
  708. #[test]
  709. fn emulated_clzero_zeroes_its_line() {
  710. #[repr(align(64))]
  711. struct Line([u8; 128]);
  712. let mut line = Line([0xff; 128]);
  713. let at = line.0.as_mut_ptr().wrapping_add(5) as u64; // inside the first line
  714. let mut xmm = [reg(0, 0); 16];
  715. assert_eq!(emulate(&[0x0f, 0x01, 0xfc], at, &mut xmm), Some(3));
  716. assert!(line.0[..64].iter().all(|&b| b == 0));
  717. assert!(line.0[64..].iter().all(|&b| b == 0xff));
  718. }
  719. #[test]
  720. fn emulated_monitorx_and_mwaitx_are_skipped() {
  721. let mut xmm = [reg(1, 2); 16];
  722. assert_eq!(emulate(&[0x0f, 0x01, 0xfa], 0, &mut xmm), Some(3));
  723. assert_eq!(emulate(&[0x0f, 0x01, 0xfb], 0, &mut xmm), Some(3));
  724. assert!(xmm.iter().all(|r| r.Low == 1 && r.High == 2));
  725. }
  726. #[test]
  727. fn emulated_insertq_and_extrq_with_immediates() {
  728. let mut xmm = [reg(0, 0); 16];
  729. xmm[0] = reg(0x1111_2222_3333_4444, 0x5555);
  730. xmm[1] = reg(0xabcd, 0x6666);
  731. // insertq xmm0, xmm1, length 16, index 16
  732. let insertq = [0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10];
  733. assert_eq!(emulate(&insertq, 0, &mut xmm), Some(6));
  734. assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444);
  735. assert_eq!((low(&xmm, 1), xmm[1].High), (0xabcd, 0x6666));
  736. // extrq xmm0, length 8, index 20
  737. let extrq = [0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14];
  738. assert_eq!(emulate(&extrq, 0, &mut xmm), Some(6));
  739. assert_eq!(low(&xmm, 0), 0xbc);
  740. }
  741. #[test]
  742. fn emulated_insertq_and_extrq_with_fields_in_a_register() {
  743. let mut xmm = [reg(0, 0); 16];
  744. // insertq xmm0, xmm1: length and index in xmm1's high half.
  745. xmm[0] = reg(0x1111_2222_3333_4444, 0);
  746. xmm[1] = reg(0xabcd, 0x10_10);
  747. assert_eq!(emulate(&[0xf2, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4));
  748. assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444);
  749. // extrq xmm0, xmm1: length and index in xmm1's low half.
  750. xmm[1] = reg(0x14_08, 0);
  751. assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4));
  752. assert_eq!(low(&xmm, 0), 0xbc);
  753. }
  754. #[test]
  755. fn emulated_sse4a_reaches_xmm8_to_xmm15() {
  756. let mut xmm = [reg(0, 0); 16];
  757. xmm[8] = reg(0x1111_2222_3333_4444, 0);
  758. xmm[9] = reg(0xabcd, 0);
  759. // insertq xmm8, xmm9, length 16, index 16 (REX.R and REX.B)
  760. let insertq = [0xf2, 0x45, 0x0f, 0x78, 0xc1, 0x10, 0x10];
  761. assert_eq!(emulate(&insertq, 0, &mut xmm), Some(7));
  762. assert_eq!(low(&xmm, 8), 0x1111_2222_abcd_4444);
  763. assert_eq!((low(&xmm, 0), low(&xmm, 1)), (0, 0));
  764. // extrq xmm9, length 8, index 4 (REX.B)
  765. let extrq = [0x66, 0x41, 0x0f, 0x78, 0xc1, 0x08, 0x04];
  766. assert_eq!(emulate(&extrq, 0, &mut xmm), Some(7));
  767. assert_eq!(low(&xmm, 9), 0xbc);
  768. assert_eq!(low(&xmm, 1), 0);
  769. }
  770. #[test]
  771. fn emulated_sse4a_length_0_is_64_bits() {
  772. let mut xmm = [reg(0, 0); 16];
  773. xmm[0] = reg(0x1122_3344_5566_7788, 0);
  774. // extrq xmm0, length 0 (64), index 0. A non-zero index with
  775. // length 64 goes past bit 63, and AMD leaves that result undefined.
  776. assert_eq!(
  777. emulate(&[0x66, 0x0f, 0x78, 0xc0, 0x00, 0x00], 0, &mut xmm),
  778. Some(6)
  779. );
  780. assert_eq!(low(&xmm, 0), 0x1122_3344_5566_7788);
  781. // insertq xmm0, xmm1, length 0 (64), index 0
  782. xmm[1] = reg(0xdead_beef_cafe_f00d, 0);
  783. assert_eq!(
  784. emulate(&[0xf2, 0x0f, 0x78, 0xc1, 0x00, 0x00], 0, &mut xmm),
  785. Some(6)
  786. );
  787. assert_eq!(low(&xmm, 0), 0xdead_beef_cafe_f00d);
  788. }
  789. #[test]
  790. fn other_instructions_and_exceptions_are_not_emulated() {
  791. let mut xmm = [reg(0, 0); 16];
  792. assert_eq!(emulate(&[0x0f, 0x0b], 0, &mut xmm), None); // ud2
  793. // extrq with a memory operand, which does not exist
  794. assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0x00], 0, &mut xmm), None);
  795. // extrq with immediates needs ModRM.reg 0
  796. let bad_extrq = [0x66, 0x0f, 0x78, 0xc8, 0x08, 0x14];
  797. assert_eq!(emulate(&bad_extrq, 0, &mut xmm), None);
  798. // a clzero that did not cause an illegal instruction
  799. let clzero = [0x0f, 0x01, 0xfc];
  800. assert_eq!(
  801. emulate_as(EXCEPTION_ACCESS_VIOLATION, &clzero, 0, &mut xmm),
  802. None
  803. );
  804. }
  805. }