crash.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. let Some(len) = sse4a(code, &mut context.Anonymous.FltSave.XmmRegisters) else {
  142. return false;
  143. };
  144. context.Rip += len as u64;
  145. return true;
  146. }
  147. }
  148. context.Rip += 3;
  149. }
  150. true
  151. }
  152. /// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on
  153. /// the saved XMM registers; returns the instruction's length.
  154. unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option<usize> {
  155. // SAFETY: the caller's code bytes are readable up to the instruction's end.
  156. let b = |i: usize| unsafe { code.add(i).read() };
  157. let prefix = b(0);
  158. let (rex, at) = if b(1) & 0xf0 == 0x40 { (b(1), 2) } else { (0, 1) };
  159. if !matches!(prefix, 0x66 | 0xf2) || b(at) != 0x0f || !matches!(b(at + 1), 0x78 | 0x79) {
  160. return None;
  161. }
  162. let modrm = b(at + 2);
  163. if modrm >> 6 != 3 {
  164. return None;
  165. }
  166. let dst = usize::from((modrm >> 3) & 7 | (rex & 4) << 1);
  167. let src = usize::from(modrm & 7 | (rex & 1) << 3);
  168. let immediate = b(at + 1) == 0x78;
  169. let (fields, len) = if immediate {
  170. ((b(at + 3), b(at + 4)), at + 5)
  171. } else {
  172. // extrq reads its fields from src's low half, insertq from its high.
  173. let f = if prefix == 0x66 { xmm[src].Low } else { xmm[src].High as u64 };
  174. ((f as u8, (f >> 8) as u8), at + 3)
  175. };
  176. let (n, at_bit) = (u32::from(fields.0 & 63), u32::from(fields.1 & 63));
  177. let bits = if n == 0 { 64 } else { n };
  178. let mask = if bits == 64 { u64::MAX } else { (1u64 << bits) - 1 };
  179. if prefix == 0x66 {
  180. // extrq: register form takes its fields from src, works on dst.
  181. if immediate && (modrm >> 3) & 7 != 0 {
  182. return None;
  183. }
  184. let target = if immediate { src } else { dst };
  185. xmm[target].Low = (xmm[target].Low >> at_bit) & mask;
  186. } else {
  187. let value = (xmm[src].Low & mask) << at_bit;
  188. xmm[dst].Low = xmm[dst].Low & !(mask << at_bit) | value;
  189. }
  190. Some(len)
  191. }
  192. unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
  193. // SAFETY: the system passes valid exception pointers.
  194. if unsafe { emulate_amd_only(info) } {
  195. return -1; // EXCEPTION_CONTINUE_EXECUTION
  196. }
  197. // SAFETY: as above.
  198. if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) {
  199. // SAFETY: as above.
  200. unsafe { report("first-chance exception", info, false) };
  201. }
  202. EXCEPTION_CONTINUE_SEARCH
  203. }
  204. /// For an unhandled-exception filter: reports the exception that is about
  205. /// to end the process, and appends it to the crash log.
  206. ///
  207. /// # Safety
  208. /// `info` comes from the system, for an exception being dispatched.
  209. pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) {
  210. // SAFETY: forwarded from the caller.
  211. unsafe { report("unhandled exception", info, true) };
  212. }
  213. /// MSVC's code for a C++ `throw`, and its magic first parameter.
  214. const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32;
  215. const CPP_MAGIC: usize = 0x1993_0520;
  216. /// What a C++ throw threw: the decorated name of its type, then its value
  217. /// where that names the cause (an integer, e.g. an HRESULT; a standard
  218. /// exception's message).
  219. ///
  220. /// # Safety
  221. /// `p` are the parameters of a live MSVC throw (`p[0]` the magic).
  222. unsafe fn thrown(p: &[usize]) -> String {
  223. // SAFETY: the throw's ThrowInfo, its RVAs relative to `p[3]`: catchable
  224. // type array at +12 (count, then type RVAs), each type's descriptor at
  225. // +4, whose decorated name starts at +16; the object is at `p[1]`.
  226. unsafe {
  227. let rva = |at: usize| (at as *const u32).read_unaligned() as usize;
  228. let types = p[3] + rva(p[2] + 12);
  229. let name = |i: usize| {
  230. let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4);
  231. std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char)
  232. .to_string_lossy()
  233. };
  234. let first = name(0);
  235. let value = match &*first {
  236. // int, unsigned, long (HRESULT), unsigned long
  237. ".H" | ".I" | ".J" | ".K" if p[1] != 0 => {
  238. format!(" = {:#010x}", (p[1] as *const u32).read_unaligned())
  239. }
  240. // std::exception keeps its message after the table pointer.
  241. _ if (0..rva(types)).any(|i| name(i) == ".?AVexception@std@@") => {
  242. let message = (p[1] as *const *const std::ffi::c_char).add(1).read();
  243. if message.is_null() {
  244. String::new()
  245. } else {
  246. format!(": {}", std::ffi::CStr::from_ptr(message).to_string_lossy())
  247. }
  248. }
  249. _ => String::new(),
  250. };
  251. format!("{first}{value}")
  252. }
  253. }
  254. /// # Safety
  255. /// See [`report_unhandled`].
  256. unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
  257. // SAFETY: the system passes valid exception pointers.
  258. let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) };
  259. let code = record.ExceptionCode;
  260. let at = record.ExceptionAddress as usize;
  261. let p = record.ExceptionInformation;
  262. let detail = if code == EXCEPTION_ACCESS_VIOLATION {
  263. let kind = match p[0] {
  264. 0 => "read",
  265. 1 => "write",
  266. _ => "execute",
  267. };
  268. format!(" ({kind} {:#x})", p[1])
  269. } else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC {
  270. // SAFETY: a live MSVC throw.
  271. format!(" (C++ {} thrown)", unsafe { thrown(&p) })
  272. } else {
  273. String::new()
  274. };
  275. // Printed line by line (a fault while unwinding must not lose the
  276. // lines before it), and kept for the file.
  277. let mut text = String::new();
  278. let mut line = |l: String| {
  279. eprintln!("{l}");
  280. text.push_str(&l);
  281. text.push('\n');
  282. };
  283. line(format!(
  284. "VIctory: {what} {:#010x} at {}{detail}",
  285. code as u32,
  286. locate(at)
  287. ));
  288. line(format!(
  289. " rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}",
  290. context.Rax,
  291. context.Rbx,
  292. context.Rcx,
  293. context.Rdx,
  294. context.Rsi,
  295. context.Rdi,
  296. context.Rsp,
  297. context.Rbp
  298. ));
  299. line(format!(
  300. " r8 {:#x} r9 {:#x} r10 {:#x} r11 {:#x} r12 {:#x} r13 {:#x} r14 {:#x} r15 {:#x}",
  301. context.R8,
  302. context.R9,
  303. context.R10,
  304. context.R11,
  305. context.R12,
  306. context.R13,
  307. context.R14,
  308. context.R15
  309. ));
  310. for (i, pc) in unwind(*context).into_iter().enumerate() {
  311. line(format!(" #{i:<2} {}", locate(pc as usize)));
  312. }
  313. if to_file {
  314. let said = title_output();
  315. eprint!("{said}");
  316. text.push_str(&said);
  317. append_to_log(&text);
  318. }
  319. #[cfg(feature = "diagnostics")]
  320. for (address, len, file) in SAVE.get().into_iter().flatten() {
  321. // SAFETY: the caller of `save_on_crash` named readable memory.
  322. let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) };
  323. let saved = std::fs::write(file, bytes);
  324. eprintln!(
  325. " saved {address:#x}+{len:#x} to {} ({saved:?})",
  326. file.display()
  327. );
  328. }
  329. }
  330. /// Return addresses of the faulting thread's frames, from the faulting
  331. /// instruction up, by the unwind data of each image (the Windows loader
  332. /// registered it for title images too). Code without unwind data (our
  333. /// thunks, leaf functions) is taken to have its return address at `rsp`.
  334. fn unwind(context: CONTEXT) -> Vec<u64> {
  335. let (mut low, mut high) = (0, 0);
  336. // SAFETY: writes the current thread's stack bounds.
  337. unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };
  338. let mut frames = Vec::with_capacity(MAX_FRAMES);
  339. unwind_into(context, low, high, &mut frames);
  340. frames
  341. }
  342. /// [`unwind`] for any thread of the process, its stack being `low..high`;
  343. /// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames`
  344. /// has that capacity (another thread may be suspended holding the heap).
  345. pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) {
  346. frames.push(context.Rip);
  347. while frames.len() < MAX_FRAMES {
  348. // Stop where reading the stack would fault inside this handler.
  349. let rsp = context.Rsp as usize;
  350. if rsp < low || rsp + 8 > high {
  351. break;
  352. }
  353. let mut image = 0;
  354. // SAFETY: looks up the function table entry covering `Rip`, if any.
  355. let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) };
  356. if entry.is_null() {
  357. // SAFETY: `rsp` is inside this thread's stack.
  358. context.Rip = unsafe { (rsp as *const u64).read() };
  359. context.Rsp += 8;
  360. } else {
  361. let (mut data, mut frame) = (null_mut(), 0);
  362. // SAFETY: `entry` belongs to `image`; the context is our copy.
  363. unsafe {
  364. RtlVirtualUnwind(
  365. UNW_FLAG_NHANDLER,
  366. image,
  367. context.Rip,
  368. entry,
  369. &mut context,
  370. &mut data,
  371. &mut frame,
  372. null_mut(),
  373. )
  374. };
  375. }
  376. if context.Rip == 0 {
  377. break;
  378. }
  379. frames.push(context.Rip);
  380. }
  381. }
  382. /// `module+rva`, or the bare address.
  383. pub fn locate(address: usize) -> String {
  384. module_of(address).unwrap_or_else(|| format!("{address:#x}"))
  385. }
  386. fn module_of(address: usize) -> Option<String> {
  387. let mut module: HMODULE = std::ptr::null_mut();
  388. // SAFETY: looks up the module containing `address`; no reference taken.
  389. let found = unsafe {
  390. GetModuleHandleExW(
  391. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
  392. address as *const u16,
  393. &mut module,
  394. )
  395. };
  396. if found == 0 {
  397. return None;
  398. }
  399. let mut path = [0u16; 260];
  400. // SAFETY: `module` is a loaded module; the buffer length is passed.
  401. let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) };
  402. let path = String::from_utf16_lossy(&path[..len as usize]);
  403. let name = path.rsplit('\\').next().unwrap_or(&path);
  404. Some(format!("{name}+{:#x}", address - module as usize))
  405. }
  406. #[cfg(test)]
  407. mod tests {
  408. use super::*;
  409. use windows_sys::Win32::System::Diagnostics::Debug::{
  410. EXCEPTION_RECORD, RtlCaptureContext, RtlCaptureStackBackTrace,
  411. };
  412. #[test]
  413. #[inline(never)]
  414. fn unwinds_like_the_system_walk() {
  415. // SAFETY: zeroed CONTEXT is valid; both calls write our buffers.
  416. let (frames, walked) = unsafe {
  417. let mut context: CONTEXT = std::mem::zeroed();
  418. RtlCaptureContext(&mut context);
  419. let mut walked = [null_mut(); 8];
  420. let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut());
  421. (unwind(context), walked[..usize::from(n)].to_vec())
  422. };
  423. // Frame 0 differs (two call sites in this function); callers agree.
  424. assert!(walked.len() >= 4, "{walked:?}");
  425. let ours: Vec<_> = frames[1..walked.len()]
  426. .iter()
  427. .map(|&f| f as usize)
  428. .collect();
  429. let system: Vec<_> = walked[1..].iter().map(|&f| f as usize).collect();
  430. assert_eq!(ours, system);
  431. }
  432. /// On an Intel CPU, the real instructions go through the vectored
  433. /// handler. On an AMD CPU they run natively, and the tests below test
  434. /// the emulation.
  435. #[test]
  436. fn clzero_zeroes_its_line_on_any_cpu() {
  437. report_crashes();
  438. #[repr(align(64))]
  439. struct Line([u8; 128]);
  440. let mut line = Line([0xff; 128]);
  441. let at = line.0.as_mut_ptr().wrapping_add(5); // inside the first line
  442. // SAFETY: clzero writes only the 64-byte line holding `at`, ours.
  443. unsafe { std::arch::asm!(".byte 0x0f, 0x01, 0xfc", in("rax") at) };
  444. assert!(line.0[..64].iter().all(|&b| b == 0));
  445. assert!(line.0[64..].iter().all(|&b| b == 0xff));
  446. // insertq xmm0, xmm1, len 16, at 16; then extrq xmm0, len 8, at 20.
  447. let out: u64;
  448. // SAFETY: touches only the named registers.
  449. unsafe {
  450. std::arch::asm!(
  451. "movq xmm0, {a}", "movq xmm1, {b}",
  452. ".byte 0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10",
  453. "movq {a}, xmm0",
  454. ".byte 0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14",
  455. "movq {b}, xmm0",
  456. a = inout(reg) 0x1111_2222_3333_4444u64 => _, b = inout(reg) 0xabcdu64 => out,
  457. out("xmm0") _, out("xmm1") _)
  458. };
  459. assert_eq!(out, 0xbc); // 0x1111_2222_abcd_4444 >> 20, 8 bits
  460. // SAFETY: monitorx/mwaitx are wait hints that write no memory.
  461. unsafe {
  462. std::arch::asm!(".byte 0x0f, 0x01, 0xfa", ".byte 0x0f, 0x01, 0xfb",
  463. in("rax") at, in("ecx") 0, in("edx") 0)
  464. };
  465. }
  466. fn reg(low: u64, high: u64) -> M128A {
  467. M128A {
  468. Low: low,
  469. High: high as i64,
  470. }
  471. }
  472. /// Gives `code` to the emulation as if it faulted with `exception` at
  473. /// its first byte, with `rax` and `xmm` as the saved registers. The
  474. /// emulation does not execute `code`, so this works on any CPU. Returns
  475. /// the number of bytes that the emulation skipped, or `None` if it did
  476. /// not emulate the instruction. `xmm` gets the saved registers after.
  477. fn emulate_as(exception: i32, code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option<u64> {
  478. // `int3` after the instruction, so that a decoder that reads too
  479. // far sees no valid bytes.
  480. let mut bytes = [0xcc_u8; 16];
  481. bytes[..code.len()].copy_from_slice(code);
  482. let start = bytes.as_ptr() as u64;
  483. // SAFETY: a zeroed record and context are valid; the emulation
  484. // reads only `bytes` and writes only `context` (and memory at
  485. // `rax` for clzero, which the caller owns).
  486. unsafe {
  487. let mut record: EXCEPTION_RECORD = std::mem::zeroed();
  488. record.ExceptionCode = exception;
  489. let mut context: CONTEXT = std::mem::zeroed();
  490. context.Rip = start;
  491. context.Rax = rax;
  492. context.Anonymous.FltSave.XmmRegisters = *xmm;
  493. let mut pointers = EXCEPTION_POINTERS {
  494. ExceptionRecord: &mut record,
  495. ContextRecord: &mut context,
  496. };
  497. let emulated = emulate_amd_only(&mut pointers);
  498. *xmm = context.Anonymous.FltSave.XmmRegisters;
  499. emulated.then(|| context.Rip - start)
  500. }
  501. }
  502. fn emulate(code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option<u64> {
  503. emulate_as(EXCEPTION_ILLEGAL_INSTRUCTION, code, rax, xmm)
  504. }
  505. fn low(xmm: &[M128A; 16], i: usize) -> u64 {
  506. xmm[i].Low
  507. }
  508. #[test]
  509. fn emulated_clzero_zeroes_its_line() {
  510. #[repr(align(64))]
  511. struct Line([u8; 128]);
  512. let mut line = Line([0xff; 128]);
  513. let at = line.0.as_mut_ptr().wrapping_add(5) as u64; // inside the first line
  514. let mut xmm = [reg(0, 0); 16];
  515. assert_eq!(emulate(&[0x0f, 0x01, 0xfc], at, &mut xmm), Some(3));
  516. assert!(line.0[..64].iter().all(|&b| b == 0));
  517. assert!(line.0[64..].iter().all(|&b| b == 0xff));
  518. }
  519. #[test]
  520. fn emulated_monitorx_and_mwaitx_are_skipped() {
  521. let mut xmm = [reg(1, 2); 16];
  522. assert_eq!(emulate(&[0x0f, 0x01, 0xfa], 0, &mut xmm), Some(3));
  523. assert_eq!(emulate(&[0x0f, 0x01, 0xfb], 0, &mut xmm), Some(3));
  524. assert!(xmm.iter().all(|r| r.Low == 1 && r.High == 2));
  525. }
  526. #[test]
  527. fn emulated_insertq_and_extrq_with_immediates() {
  528. let mut xmm = [reg(0, 0); 16];
  529. xmm[0] = reg(0x1111_2222_3333_4444, 0x5555);
  530. xmm[1] = reg(0xabcd, 0x6666);
  531. // insertq xmm0, xmm1, length 16, index 16
  532. let insertq = [0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10];
  533. assert_eq!(emulate(&insertq, 0, &mut xmm), Some(6));
  534. assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444);
  535. assert_eq!((low(&xmm, 1), xmm[1].High), (0xabcd, 0x6666));
  536. // extrq xmm0, length 8, index 20
  537. let extrq = [0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14];
  538. assert_eq!(emulate(&extrq, 0, &mut xmm), Some(6));
  539. assert_eq!(low(&xmm, 0), 0xbc);
  540. }
  541. #[test]
  542. fn emulated_insertq_and_extrq_with_fields_in_a_register() {
  543. let mut xmm = [reg(0, 0); 16];
  544. // insertq xmm0, xmm1: length and index in xmm1's high half.
  545. xmm[0] = reg(0x1111_2222_3333_4444, 0);
  546. xmm[1] = reg(0xabcd, 0x10_10);
  547. assert_eq!(emulate(&[0xf2, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4));
  548. assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444);
  549. // extrq xmm0, xmm1: length and index in xmm1's low half.
  550. xmm[1] = reg(0x14_08, 0);
  551. assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4));
  552. assert_eq!(low(&xmm, 0), 0xbc);
  553. }
  554. #[test]
  555. fn emulated_sse4a_reaches_xmm8_to_xmm15() {
  556. let mut xmm = [reg(0, 0); 16];
  557. xmm[8] = reg(0x1111_2222_3333_4444, 0);
  558. xmm[9] = reg(0xabcd, 0);
  559. // insertq xmm8, xmm9, length 16, index 16 (REX.R and REX.B)
  560. let insertq = [0xf2, 0x45, 0x0f, 0x78, 0xc1, 0x10, 0x10];
  561. assert_eq!(emulate(&insertq, 0, &mut xmm), Some(7));
  562. assert_eq!(low(&xmm, 8), 0x1111_2222_abcd_4444);
  563. assert_eq!((low(&xmm, 0), low(&xmm, 1)), (0, 0));
  564. // extrq xmm9, length 8, index 4 (REX.B)
  565. let extrq = [0x66, 0x41, 0x0f, 0x78, 0xc1, 0x08, 0x04];
  566. assert_eq!(emulate(&extrq, 0, &mut xmm), Some(7));
  567. assert_eq!(low(&xmm, 9), 0xbc);
  568. assert_eq!(low(&xmm, 1), 0);
  569. }
  570. #[test]
  571. fn emulated_sse4a_length_0_is_64_bits() {
  572. let mut xmm = [reg(0, 0); 16];
  573. xmm[0] = reg(0x1122_3344_5566_7788, 0);
  574. // extrq xmm0, length 0 (64), index 0. A non-zero index with
  575. // length 64 goes past bit 63, and AMD leaves that result undefined.
  576. assert_eq!(
  577. emulate(&[0x66, 0x0f, 0x78, 0xc0, 0x00, 0x00], 0, &mut xmm),
  578. Some(6)
  579. );
  580. assert_eq!(low(&xmm, 0), 0x1122_3344_5566_7788);
  581. // insertq xmm0, xmm1, length 0 (64), index 0
  582. xmm[1] = reg(0xdead_beef_cafe_f00d, 0);
  583. assert_eq!(
  584. emulate(&[0xf2, 0x0f, 0x78, 0xc1, 0x00, 0x00], 0, &mut xmm),
  585. Some(6)
  586. );
  587. assert_eq!(low(&xmm, 0), 0xdead_beef_cafe_f00d);
  588. }
  589. #[test]
  590. fn other_instructions_and_exceptions_are_not_emulated() {
  591. let mut xmm = [reg(0, 0); 16];
  592. assert_eq!(emulate(&[0x0f, 0x0b], 0, &mut xmm), None); // ud2
  593. // extrq with a memory operand, which does not exist
  594. assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0x00], 0, &mut xmm), None);
  595. // extrq with immediates needs ModRM.reg 0
  596. let bad_extrq = [0x66, 0x0f, 0x78, 0xc8, 0x08, 0x14];
  597. assert_eq!(emulate(&bad_extrq, 0, &mut xmm), None);
  598. // a clzero that did not cause an illegal instruction
  599. let clzero = [0x0f, 0x01, 0xfc];
  600. assert_eq!(
  601. emulate_as(EXCEPTION_ACCESS_VIOLATION, &clzero, 0, &mut xmm),
  602. None
  603. );
  604. }
  605. }