crash.rs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  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` (see [`clzero`] for the loops around it);
  125. /// `monitorx`/`mwaitx` (`0f 01 fa`/`fb`) are wait hints, so a spin loop
  126. /// around them works with mwaitx as a yield; `rdpru` (`0f 01 fd`) reads
  127. /// MPERF (`ecx` 0) or APERF (1), cycles at the nominal and the actual
  128. /// frequency, and gets the time-stamp counter for both: a core that never
  129. /// changes frequency.
  130. unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool {
  131. // SAFETY: the system passes valid exception pointers; the faulting
  132. // instruction's bytes are readable, as the CPU just fetched them.
  133. unsafe {
  134. let record = &*(*info).ExceptionRecord;
  135. let context = &mut *(*info).ContextRecord;
  136. if record.ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION {
  137. return false;
  138. }
  139. let code = context.Rip as *const u8;
  140. match code.cast::<[u8; 3]>().read_unaligned() {
  141. [0x0f, 0x01, 0xfc] => return clzero(context),
  142. [0x0f, 0x01, 0xfa] => {}
  143. [0x0f, 0x01, 0xfb] => std::thread::yield_now(),
  144. [0x0f, 0x01, 0xfd] => {
  145. // Flags are left as they are: a Zen 3 changes none, for
  146. // known counters or not (measured in user mode).
  147. let known = context.Rcx as u32 <= 1;
  148. let cycles = if known { std::arch::x86_64::_rdtsc() } else { 0 };
  149. context.Rax = cycles & 0xffff_ffff;
  150. context.Rdx = cycles >> 32;
  151. }
  152. _ => {
  153. // Only bytes inside the faulting instruction's page are read: the next page may
  154. // not be mapped.
  155. let room = 0x1000 - (context.Rip as usize & 0xfff);
  156. let mut bytes = [0u8; 32];
  157. let n = room.min(bytes.len());
  158. std::ptr::copy_nonoverlapping(code, bytes.as_mut_ptr(), n);
  159. if let Some(pass) = clwb_loop(&bytes[..n]) {
  160. // A whole write-back loop in one exception (see `clwb_loop`).
  161. let limit = *gpr(context, pass.limit);
  162. let base = gpr(context, pass.base);
  163. *base = if *base <= limit {
  164. base.wrapping_add(((limit - *base) / 64 + 1) * 64)
  165. } else {
  166. base.wrapping_add(64)
  167. };
  168. let flags = cmp_flags(*base, limit);
  169. context.EFlags = context.EFlags & !CMP_FLAGS | flags;
  170. context.Rip += pass.len as u64;
  171. return true;
  172. }
  173. if n >= 15
  174. && let Some(len) = clwb_len(bytes[..15].try_into().unwrap_or([0; 15]))
  175. {
  176. // A write-back hint: the PC's memory is coherent, so it has nothing to do.
  177. context.Rip += len as u64;
  178. return true;
  179. }
  180. let Some(len) = sse4a(code, &mut context.Anonymous.FltSave.XmmRegisters) else {
  181. return false;
  182. };
  183. context.Rip += len as u64;
  184. return true;
  185. }
  186. }
  187. context.Rip += 3;
  188. }
  189. true
  190. }
  191. /// `clwb m8` (`66 [rex] 0f ae /6`, a memory operand), which Intel CPUs before
  192. /// Ice Lake lack: its length, or `None` for any other instruction.
  193. fn clwb_len(code: [u8; 15]) -> Option<usize> {
  194. let at = if code[1] & 0xf0 == 0x40 { 2 } else { 1 };
  195. if code[0] != 0x66 || code[at] != 0x0f || code[at + 1] != 0xae {
  196. return None;
  197. }
  198. let modrm = code[at + 2];
  199. let (mode, rm) = (modrm >> 6, modrm & 7);
  200. if mode == 3 || (modrm >> 3) & 7 != 6 {
  201. return None;
  202. }
  203. let mut len = at + 3;
  204. let mut base = rm;
  205. if rm == 4 {
  206. base = code[len] & 7;
  207. len += 1;
  208. }
  209. len += match mode {
  210. 0 if rm == 5 || (rm == 4 && base == 5) => 4,
  211. 1 => 1,
  212. 2 => 4,
  213. _ => 0,
  214. };
  215. Some(len)
  216. }
  217. /// A `clwb` write-back loop as the title's compilers build it, one cache line a
  218. /// pass (`base` and `limit` any registers):
  219. ///
  220. /// ```text
  221. /// top: clwb [base]
  222. /// add base, 0x40
  223. /// cmp base, limit
  224. /// jbe top
  225. /// ```
  226. ///
  227. /// An exception costs about a microsecond and the title writes back whole
  228. /// buffers this way while it loads, so the loop is done in one: `clwb` has
  229. /// nothing to do on the PC, `base` ends past `limit` as the last pass leaves it.
  230. struct ClwbLoop {
  231. base: u8,
  232. limit: u8,
  233. /// Bytes from `clwb` to the instruction after `jbe`.
  234. len: usize,
  235. }
  236. fn clwb_loop(code: &[u8]) -> Option<ClwbLoop> {
  237. // clwb [base]: 66 [40|41] 0f ae, ModRM mod 00, reg 6, no SIB or displacement.
  238. let (rex, at) = match code.get(1)? {
  239. 0x40 | 0x41 => (code[1], 2),
  240. _ => (0, 1),
  241. };
  242. if *code.first()? != 0x66 || code.get(at..at + 2)? != [0x0f, 0xae] {
  243. return None;
  244. }
  245. let modrm = *code.get(at + 2)?;
  246. let rm = modrm & 7;
  247. if modrm >> 6 != 0 || (modrm >> 3) & 7 != 6 || rm == 4 || rm == 5 {
  248. return None;
  249. }
  250. let base = rm | (rex & 1) << 3;
  251. // add base, 0x40: REX.W(+B) 83 /0 ib.
  252. let add = at + 3;
  253. if *code.get(add..add + 4)? != [0x48 | base >> 3, 0x83, 0xc0 | (base & 7), 0x40] {
  254. return None;
  255. }
  256. // cmp base, limit: REX.W 39 /r with base in r/m.
  257. let cmp = add + 4;
  258. let &[cmp_rex @ 0x48..=0x4f, 0x39, cmp_modrm] = code.get(cmp..cmp + 3)? else {
  259. return None;
  260. };
  261. if cmp_modrm >> 6 != 3 || (cmp_modrm & 7 | (cmp_rex & 1) << 3) != base {
  262. return None;
  263. }
  264. let limit = (cmp_modrm >> 3) & 7 | (cmp_rex & 4) << 1;
  265. // jbe top.
  266. let jump = cmp + 3;
  267. let len = jump + 2;
  268. if *code.get(jump)? != 0x76 || i64::from(*code.get(jump + 1)? as i8) != -(len as i64) {
  269. return None;
  270. }
  271. (limit != base).then_some(ClwbLoop { base, limit, len })
  272. }
  273. /// `clzero` at `context.Rip`. An exception costs about a microsecond and
  274. /// titles clear tens of kilobytes at a time, a line per pass, so the two
  275. /// loops compilers build around the instruction are done whole in one
  276. /// exception, leaving registers and flags as their last pass would (`a`
  277. /// and `b` any registers but `rax`):
  278. ///
  279. /// ```text
  280. /// top: clzero top: mov rax, a
  281. /// add rax, 0x40 add a, 0x40
  282. /// cmp rax, b clzero
  283. /// jb top cmp a, b
  284. /// jb top
  285. /// ```
  286. ///
  287. /// Anything else around it is one line and the next instruction.
  288. ///
  289. /// # Safety
  290. /// `context` is the state of a thread that faulted at a `clzero`; the
  291. /// lines its registers name are the title's to zero.
  292. unsafe fn clzero(context: &mut CONTEXT) -> bool {
  293. // SAFETY: (every use) a line the title asked to zero.
  294. let zero = |rax: u64| unsafe { ((rax & !63) as *mut u8).write_bytes(0, 64) };
  295. let at = context.Rip as usize;
  296. // The loops' other instructions are read only where that stays inside
  297. // the faulting instruction's page (the next one may not be mapped).
  298. let page = at & 0xfff;
  299. if page + 12 <= 0x1000 {
  300. // SAFETY: inside the page the CPU fetched the instruction from.
  301. let after = unsafe { &*((at + 3) as *const [u8; 9]) };
  302. if let [0x48, 0x83, 0xc0, 0x40, cmp @ .., 0x72, 0xf4] = after
  303. && let Some((0, limit)) = compare_registers(cmp)
  304. && limit != 0
  305. {
  306. let limit = *gpr(context, limit);
  307. loop {
  308. zero(context.Rax);
  309. context.Rax = context.Rax.wrapping_add(0x40);
  310. if context.Rax >= limit {
  311. break;
  312. }
  313. }
  314. context.EFlags = context.EFlags & !CMP_FLAGS | cmp_flags(context.Rax, limit);
  315. context.Rip += 12;
  316. return true;
  317. }
  318. }
  319. if (7..=0x1000 - 8).contains(&page) {
  320. // SAFETY: inside the page the CPU fetched the instruction from.
  321. let (before, after) =
  322. unsafe { (&*((at - 7) as *const [u8; 7]), &*((at + 3) as *const [u8; 5])) };
  323. if let [rex @ (0x48 | 0x4c), 0x89, load, add_rex @ (0x48 | 0x49), 0x83, add, 0x40] = *before
  324. && let [cmp @ .., 0x72, 0xf1] = after
  325. && let Some((a, b)) = compare_registers(cmp)
  326. && load & 0xc7 == 0xc0
  327. && a == (load >> 3) & 7 | (rex & 4) << 1
  328. && add & 0xf8 == 0xc0
  329. && a == add & 7 | (add_rex & 1) << 3
  330. && a != 0
  331. && b != 0
  332. {
  333. let limit = *gpr(context, b);
  334. loop {
  335. zero(context.Rax);
  336. let next = *gpr(context, a);
  337. if next >= limit {
  338. break;
  339. }
  340. context.Rax = next;
  341. *gpr(context, a) = next.wrapping_add(0x40);
  342. }
  343. context.EFlags =
  344. context.EFlags & !CMP_FLAGS | cmp_flags(*gpr(context, a), limit);
  345. context.Rip += 8;
  346. return true;
  347. }
  348. }
  349. zero(context.Rax);
  350. context.Rip += 3;
  351. true
  352. }
  353. /// `cmp rm, reg` between 64-bit registers (`REX.W 39 /r`): (`rm`, `reg`).
  354. fn compare_registers(code: &[u8]) -> Option<(u8, u8)> {
  355. let &[rex @ 0x48..=0x4f, 0x39, modrm] = code else {
  356. return None;
  357. };
  358. (modrm >> 6 == 3).then_some((modrm & 7 | (rex & 1) << 3, (modrm >> 3) & 7 | (rex & 4) << 1))
  359. }
  360. /// The general register numbered `n` as instructions encode it.
  361. fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 {
  362. match n & 15 {
  363. 0 => &mut context.Rax,
  364. 1 => &mut context.Rcx,
  365. 2 => &mut context.Rdx,
  366. 3 => &mut context.Rbx,
  367. 4 => &mut context.Rsp,
  368. 5 => &mut context.Rbp,
  369. 6 => &mut context.Rsi,
  370. 7 => &mut context.Rdi,
  371. 8 => &mut context.R8,
  372. 9 => &mut context.R9,
  373. 10 => &mut context.R10,
  374. 11 => &mut context.R11,
  375. 12 => &mut context.R12,
  376. 13 => &mut context.R13,
  377. 14 => &mut context.R14,
  378. _ => &mut context.R15,
  379. }
  380. }
  381. /// The status flags `cmp a, b` leaves (CF, PF, AF, ZF, SF, OF) as `EFLAGS` bits.
  382. fn cmp_flags(a: u64, b: u64) -> u32 {
  383. let r = a.wrapping_sub(b);
  384. u32::from(a < b)
  385. | u32::from((r as u8).count_ones().is_multiple_of(2)) << 2
  386. | (((a ^ b ^ r) >> 4) as u32 & 1) << 4
  387. | u32::from(r == 0) << 6
  388. | ((r >> 63) as u32) << 7
  389. | ((((a ^ b) & (a ^ r)) >> 63) as u32) << 11
  390. }
  391. const CMP_FLAGS: u32 = 0x8d5;
  392. /// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on
  393. /// the saved XMM registers; returns the instruction's length.
  394. unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option<usize> {
  395. // SAFETY: the caller's code bytes are readable up to the instruction's end.
  396. let b = |i: usize| unsafe { code.add(i).read() };
  397. let prefix = b(0);
  398. let (rex, at) = if b(1) & 0xf0 == 0x40 {
  399. (b(1), 2)
  400. } else {
  401. (0, 1)
  402. };
  403. if !matches!(prefix, 0x66 | 0xf2) || b(at) != 0x0f || !matches!(b(at + 1), 0x78 | 0x79) {
  404. return None;
  405. }
  406. let modrm = b(at + 2);
  407. if modrm >> 6 != 3 {
  408. return None;
  409. }
  410. let dst = usize::from((modrm >> 3) & 7 | (rex & 4) << 1);
  411. let src = usize::from(modrm & 7 | (rex & 1) << 3);
  412. let immediate = b(at + 1) == 0x78;
  413. let (fields, len) = if immediate {
  414. ((b(at + 3), b(at + 4)), at + 5)
  415. } else {
  416. // extrq reads its fields from src's low half, insertq from its high.
  417. let f = if prefix == 0x66 { xmm[src].Low } else { xmm[src].High as u64 };
  418. ((f as u8, (f >> 8) as u8), at + 3)
  419. };
  420. let (n, at_bit) = (u32::from(fields.0 & 63), u32::from(fields.1 & 63));
  421. let bits = if n == 0 { 64 } else { n };
  422. let mask = if bits == 64 { u64::MAX } else { (1u64 << bits) - 1 };
  423. if prefix == 0x66 {
  424. // extrq: register form takes its fields from src, works on dst.
  425. if immediate && (modrm >> 3) & 7 != 0 {
  426. return None;
  427. }
  428. let target = if immediate { src } else { dst };
  429. xmm[target].Low = (xmm[target].Low >> at_bit) & mask;
  430. } else {
  431. let value = (xmm[src].Low & mask) << at_bit;
  432. xmm[dst].Low = xmm[dst].Low & !(mask << at_bit) | value;
  433. }
  434. Some(len)
  435. }
  436. unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
  437. // an instruction of the console's CPU this one lacks: emulated, the title goes on
  438. // SAFETY: the system passes valid exception pointers.
  439. if unsafe { (*(*info).ExceptionRecord).ExceptionCode } == EXCEPTION_ILLEGAL_INSTRUCTION {
  440. // SAFETY: the faulting thread's context, for the exception being dispatched.
  441. let r = unsafe { crate::console_insn::emulate(&mut *(*info).ContextRecord) };
  442. if r != 0 {
  443. return r;
  444. }
  445. }
  446. // SAFETY: the system passes valid exception pointers.
  447. if unsafe { emulate_amd_only(info) } {
  448. return -1; // EXCEPTION_CONTINUE_EXECUTION
  449. }
  450. // SAFETY: as above.
  451. if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) {
  452. // SAFETY: as above.
  453. unsafe { report("first-chance exception", info, false) };
  454. }
  455. EXCEPTION_CONTINUE_SEARCH
  456. }
  457. /// For an unhandled-exception filter: reports the exception that is about
  458. /// to end the process, and appends it to the crash log.
  459. ///
  460. /// # Safety
  461. /// `info` comes from the system, for an exception being dispatched.
  462. pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) {
  463. // SAFETY: forwarded from the caller.
  464. unsafe { report("unhandled exception", info, true) };
  465. }
  466. /// The bytes at `at` as hex, as many as the longest x86 instruction (15),
  467. /// but none past the end of `at`'s page: the next page may not be mapped.
  468. /// For an instruction the CPU refused, they name it (`0f 01 fd` is
  469. /// `rdpru`), which the address alone does not.
  470. ///
  471. /// # Safety
  472. /// `at`'s page is readable.
  473. unsafe fn instruction_bytes(at: usize) -> String {
  474. let n = (0x1000 - (at & 0xfff)).min(15);
  475. // SAFETY: `n` bytes from `at` stay inside its page, which the caller
  476. // says is readable.
  477. let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, n) };
  478. let hex: Vec<_> = bytes.iter().map(|b| format!("{b:02x}")).collect();
  479. hex.join(" ")
  480. }
  481. /// MSVC's code for a C++ `throw`, and its magic first parameter.
  482. const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32;
  483. const CPP_MAGIC: usize = 0x1993_0520;
  484. /// What a C++ throw threw: the decorated name of its type, then its value
  485. /// where that names the cause (an integer, e.g. an HRESULT; a standard
  486. /// exception's message).
  487. ///
  488. /// # Safety
  489. /// `p` are the parameters of a live MSVC throw (`p[0]` the magic).
  490. unsafe fn thrown(p: &[usize]) -> String {
  491. // SAFETY: the throw's ThrowInfo, its RVAs relative to `p[3]`: catchable
  492. // type array at +12 (count, then type RVAs), each type's descriptor at
  493. // +4, whose decorated name starts at +16; the object is at `p[1]`.
  494. unsafe {
  495. let rva = |at: usize| (at as *const u32).read_unaligned() as usize;
  496. let types = p[3] + rva(p[2] + 12);
  497. let name = |i: usize| {
  498. let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4);
  499. std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char)
  500. .to_string_lossy()
  501. };
  502. let first = name(0);
  503. let value = match &*first {
  504. // int, unsigned, long (HRESULT), unsigned long
  505. ".H" | ".I" | ".J" | ".K" if p[1] != 0 => {
  506. format!(" = {:#010x}", (p[1] as *const u32).read_unaligned())
  507. }
  508. // std::exception keeps its message after the table pointer.
  509. _ if (0..rva(types)).any(|i| name(i) == ".?AVexception@std@@") => {
  510. let message = (p[1] as *const *const std::ffi::c_char).add(1).read();
  511. if message.is_null() {
  512. String::new()
  513. } else {
  514. format!(": {}", std::ffi::CStr::from_ptr(message).to_string_lossy())
  515. }
  516. }
  517. _ => String::new(),
  518. };
  519. format!("{first}{value}")
  520. }
  521. }
  522. /// # Safety
  523. /// See [`report_unhandled`].
  524. unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
  525. // SAFETY: the system passes valid exception pointers.
  526. let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) };
  527. let code = record.ExceptionCode;
  528. let at = record.ExceptionAddress as usize;
  529. let p = record.ExceptionInformation;
  530. let detail = if code == EXCEPTION_ACCESS_VIOLATION {
  531. let kind = match p[0] {
  532. 0 => "read",
  533. 1 => "write",
  534. _ => "execute",
  535. };
  536. format!(" ({kind} {:#x}: {})", p[1], memory_at(p[1]))
  537. } else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC {
  538. // SAFETY: a live MSVC throw.
  539. format!(" (C++ {} thrown)", unsafe { thrown(&p) })
  540. } else if code == EXCEPTION_ILLEGAL_INSTRUCTION || code == EXCEPTION_PRIV_INSTRUCTION {
  541. // SAFETY: the CPU refused the instruction at `at`, so it fetched it.
  542. format!(" (code {})", unsafe { instruction_bytes(at) })
  543. } else {
  544. String::new()
  545. };
  546. // Printed line by line (a fault while unwinding must not lose the
  547. // lines before it), and kept for the file.
  548. let mut text = String::new();
  549. let mut line = |l: String| {
  550. eprintln!("{l}");
  551. text.push_str(&l);
  552. text.push('\n');
  553. };
  554. line(format!(
  555. "VIctory: {what} {:#010x} at {}{detail}",
  556. code as u32,
  557. locate(at)
  558. ));
  559. line(format!(
  560. " rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}",
  561. context.Rax,
  562. context.Rbx,
  563. context.Rcx,
  564. context.Rdx,
  565. context.Rsi,
  566. context.Rdi,
  567. context.Rsp,
  568. context.Rbp
  569. ));
  570. line(format!(
  571. " r8 {:#x} r9 {:#x} r10 {:#x} r11 {:#x} r12 {:#x} r13 {:#x} r14 {:#x} r15 {:#x}",
  572. context.R8,
  573. context.R9,
  574. context.R10,
  575. context.R11,
  576. context.R12,
  577. context.R13,
  578. context.R14,
  579. context.R15
  580. ));
  581. for (i, pc) in unwind(*context).into_iter().enumerate() {
  582. line(format!(" #{i:<2} {}", locate(pc as usize)));
  583. }
  584. if to_file {
  585. let said = title_output();
  586. eprint!("{said}");
  587. text.push_str(&said);
  588. append_to_log(&text);
  589. }
  590. #[cfg(feature = "diagnostics")]
  591. for (address, len, file) in SAVE.get().into_iter().flatten() {
  592. // SAFETY: the caller of `save_on_crash` named readable memory.
  593. let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) };
  594. let saved = std::fs::write(file, bytes);
  595. eprintln!(
  596. " saved {address:#x}+{len:#x} to {} ({saved:?})",
  597. file.display()
  598. );
  599. }
  600. }
  601. /// Return addresses of the faulting thread's frames, from the faulting
  602. /// instruction up, by the unwind data of each image (the Windows loader
  603. /// registered it for title images too). Code without unwind data (our
  604. /// thunks, leaf functions) is taken to have its return address at `rsp`.
  605. fn unwind(context: CONTEXT) -> Vec<u64> {
  606. let (mut low, mut high) = (0, 0);
  607. // SAFETY: writes the current thread's stack bounds.
  608. unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };
  609. let mut frames = Vec::with_capacity(MAX_FRAMES);
  610. unwind_into(context, low, high, &mut frames);
  611. frames
  612. }
  613. /// A `CONTEXT` at the 16-byte alignment the unwind and capture functions need.
  614. #[repr(C, align(16))]
  615. pub(crate) struct Aligned16(pub(crate) CONTEXT);
  616. /// [`unwind`] for any thread of the process, its stack being `low..high`;
  617. /// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames`
  618. /// has that capacity (another thread may be suspended holding the heap).
  619. pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) {
  620. // `RtlVirtualUnwind` writes the context with 16-byte aligned stores, and
  621. // windows-sys declares `CONTEXT` without that alignment: a by-value copy on
  622. // the stack can land 8 bytes off and fault (seen in a debug build).
  623. let mut aligned = Aligned16(context);
  624. let context = &mut aligned.0;
  625. frames.push(context.Rip);
  626. while frames.len() < MAX_FRAMES {
  627. // Stop where reading the stack would fault inside this handler.
  628. let rsp = context.Rsp as usize;
  629. if rsp < low || rsp + 8 > high {
  630. break;
  631. }
  632. let mut image = 0;
  633. // SAFETY: looks up the function table entry covering `Rip`, if any.
  634. let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) };
  635. if entry.is_null() {
  636. // SAFETY: `rsp` is inside this thread's stack.
  637. context.Rip = unsafe { (rsp as *const u64).read() };
  638. context.Rsp += 8;
  639. } else {
  640. let (mut data, mut frame) = (null_mut(), 0);
  641. // SAFETY: `entry` belongs to `image`; the context is our copy.
  642. unsafe {
  643. RtlVirtualUnwind(
  644. UNW_FLAG_NHANDLER,
  645. image,
  646. context.Rip,
  647. entry,
  648. context,
  649. &mut data,
  650. &mut frame,
  651. null_mut(),
  652. )
  653. };
  654. }
  655. if context.Rip == 0 {
  656. break;
  657. }
  658. frames.push(context.Rip);
  659. }
  660. }
  661. /// `module+rva`, or the bare address.
  662. pub fn locate(address: usize) -> String {
  663. module_of(address).unwrap_or_else(|| format!("{address:#x}"))
  664. }
  665. fn module_of(address: usize) -> Option<String> {
  666. let mut module: HMODULE = std::ptr::null_mut();
  667. // SAFETY: looks up the module containing `address`; no reference taken.
  668. let found = unsafe {
  669. GetModuleHandleExW(
  670. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
  671. address as *const u16,
  672. &mut module,
  673. )
  674. };
  675. if found == 0 {
  676. return None;
  677. }
  678. let mut path = [0u16; 260];
  679. // SAFETY: `module` is a loaded module; the buffer length is passed.
  680. let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) };
  681. let path = String::from_utf16_lossy(&path[..len as usize]);
  682. let name = path.rsplit('\\').next().unwrap_or(&path);
  683. Some(format!("{name}+{:#x}", address - module as usize))
  684. }
  685. /// What is at `address`, for an access violation there: nothing, memory
  686. /// reserved but never committed, a guard page, or the protection the access
  687. /// broke (with the module, for an image's pages). Each points at a different
  688. /// cause: a wild pointer, an allocation whose commit failed, a stack
  689. /// overrun, a write to code or constants.
  690. fn memory_at(address: usize) -> String {
  691. use windows_sys::Win32::System::Memory::{
  692. MEM_FREE, MEM_IMAGE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE,
  693. PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD,
  694. PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, VirtualQuery,
  695. };
  696. // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid.
  697. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  698. // SAFETY: reads the address space's bookkeeping, not `address` itself.
  699. let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) };
  700. if n == 0 {
  701. // Above the process's address space: Windows reports a
  702. // non-canonical address as all ones.
  703. return "outside the address space".into();
  704. }
  705. let protect = match info.State {
  706. MEM_FREE => return "nothing mapped there".into(),
  707. MEM_RESERVE => return "reserved, never committed".into(),
  708. _ if info.Protect & PAGE_GUARD != 0 => return "a guard page".into(),
  709. _ => match info.Protect & 0xff {
  710. PAGE_NOACCESS => "no access".into(),
  711. PAGE_READONLY => "read-only".into(),
  712. PAGE_READWRITE => "read-write".into(),
  713. PAGE_WRITECOPY => "copy-on-write".into(),
  714. PAGE_EXECUTE => "execute-only".into(),
  715. PAGE_EXECUTE_READ => "read-execute".into(),
  716. PAGE_EXECUTE_READWRITE => "read-write-execute".into(),
  717. PAGE_EXECUTE_WRITECOPY => "copy-on-write, executable".into(),
  718. _ => format!("protection {:#x}", info.Protect),
  719. },
  720. };
  721. match module_of(address) {
  722. Some(module) if info.Type == MEM_IMAGE => format!("{protect}, in {module}"),
  723. _ => protect,
  724. }
  725. }
  726. #[cfg(test)]
  727. mod tests {
  728. use super::*;
  729. use windows_sys::Win32::System::Diagnostics::Debug::{
  730. EXCEPTION_RECORD, RtlCaptureContext, RtlCaptureStackBackTrace,
  731. };
  732. /// What [`capture_frames`] saw: our [`unwind`], then the system's walk.
  733. type Captured = (Vec<u64>, Vec<usize>);
  734. /// A frame we expect [`unwind`] to report: the helper it is in, and the
  735. /// helper's name for the message.
  736. type Expected = (&'static str, fn() -> Captured);
  737. /// The runtime function entry start covering `at`: the image base the
  738. /// lookup writes, plus the entry's `BeginAddress`. Asking the system for
  739. /// both sides of the comparison means a thunk or an incremental-link jump
  740. /// is not mistaken for a different function.
  741. fn entry_start_at(at: u64) -> Option<u64> {
  742. let mut image = 0;
  743. // SAFETY: looks up the function table entry covering `at`; nothing
  744. // keeps a reference to the entry past this call.
  745. let entry = unsafe { RtlLookupFunctionEntry(at, &mut image, null_mut()) };
  746. if entry.is_null() {
  747. return None;
  748. }
  749. // SAFETY: a non-null entry belongs to `image`, which the lookup wrote,
  750. // and `BeginAddress` is an offset into that image.
  751. Some(image + u64::from(unsafe { (*entry).BeginAddress }))
  752. }
  753. #[test]
  754. fn unwinds_like_the_system_walk() {
  755. // Asking the system's own walk whether the stack looks right is not
  756. // reliable: on Windows 10 x64 debug builds `RtlCaptureStackBackTrace`
  757. // returns no frames about half the time. The frames above us are
  758. // known instead (see `level_a`), so check those first.
  759. let (frames, walked) = level_a();
  760. // Frame 0 is in `capture_frames`, which took the context; then its
  761. // callers in call order, each named by its runtime function entry.
  762. let helpers: [Expected; 4] = [
  763. ("capture_frames", capture_frames),
  764. ("level_c", level_c),
  765. ("level_b", level_b),
  766. ("level_a", level_a),
  767. ];
  768. assert!(frames.len() >= helpers.len(), "{frames:?}");
  769. for (i, (name, helper)) in helpers.iter().enumerate() {
  770. let want = entry_start_at(*helper as usize as u64)
  771. .unwrap_or_else(|| panic!("no unwind data for {name}"));
  772. let got = entry_start_at(frames[i])
  773. .unwrap_or_else(|| panic!("no unwind data for frame {i} at {:#x}", frames[i]));
  774. assert_eq!(got, want, "frame {i} should be {name}: {frames:?}");
  775. }
  776. // A walk that repeats an address is not a walk.
  777. let mut distinct = frames[..helpers.len()].to_vec();
  778. distinct.sort_unstable();
  779. distinct.dedup();
  780. assert_eq!(distinct.len(), helpers.len(), "repeated: {frames:?}");
  781. // Where the system's walk does return frames, it must still agree with
  782. // ours: frame 0 differs (both are in `capture_frames`, at different
  783. // call sites), and the callers above are the same.
  784. if walked.len() >= helpers.len() {
  785. assert!(frames.len() >= walked.len(), "{frames:?} vs {walked:?}");
  786. let ours: Vec<usize> = frames[1..walked.len()]
  787. .iter()
  788. .map(|&f| f as usize)
  789. .collect();
  790. assert_eq!(ours.as_slice(), &walked[1..]);
  791. }
  792. }
  793. /// The frames of this call, both ways: our [`unwind`], and the system's
  794. /// walk, which Windows 10 can come up empty on.
  795. #[inline(never)]
  796. fn capture_frames() -> Captured {
  797. // SAFETY: a zeroed CONTEXT is valid and both calls write buffers of
  798. // ours; `RtlCaptureContext` wants the context 16-byte aligned too.
  799. unsafe {
  800. let mut context = Aligned16(std::mem::zeroed());
  801. RtlCaptureContext(&mut context.0);
  802. let mut walked = [null_mut(); 8];
  803. let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut());
  804. let frames = unwind(context.0);
  805. let walked = walked[..usize::from(n)]
  806. .iter()
  807. .map(|&f| f as usize)
  808. .collect();
  809. (frames, walked)
  810. }
  811. }
  812. /// `level_a` → `level_b` → `level_c` → [`capture_frames`]: three known
  813. /// callers above the capture. `black_box` after each call keeps it from
  814. /// becoming a tail call, which would erase the caller's frame.
  815. #[inline(never)]
  816. fn level_a() -> Captured {
  817. let captured = level_b();
  818. std::hint::black_box(&captured);
  819. captured
  820. }
  821. /// See [`level_a`].
  822. #[inline(never)]
  823. fn level_b() -> Captured {
  824. let captured = level_c();
  825. std::hint::black_box(&captured);
  826. captured
  827. }
  828. /// See [`level_a`].
  829. #[inline(never)]
  830. fn level_c() -> Captured {
  831. let captured = capture_frames();
  832. std::hint::black_box(&captured);
  833. captured
  834. }
  835. #[test]
  836. fn memory_at_names_what_an_access_hit() {
  837. use windows_sys::Win32::System::Memory::{
  838. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY,
  839. PAGE_READWRITE, VirtualAlloc, VirtualFree,
  840. };
  841. // SAFETY: reserves four pages of ours and commits three of them;
  842. // nothing reads or writes them.
  843. let base = unsafe {
  844. let base = VirtualAlloc(std::ptr::null(), 0x4000, MEM_RESERVE, PAGE_NOACCESS);
  845. assert!(!base.is_null());
  846. let page = |i: usize, protect| {
  847. let at = base.cast::<u8>().add(i * 0x1000).cast();
  848. assert!(!VirtualAlloc(at, 0x1000, MEM_COMMIT, protect).is_null());
  849. };
  850. page(1, PAGE_READONLY);
  851. page(2, PAGE_READWRITE | PAGE_GUARD);
  852. page(3, PAGE_NOACCESS);
  853. base as usize
  854. };
  855. assert_eq!(memory_at(base + 8), "reserved, never committed");
  856. assert_eq!(memory_at(base + 0x1008), "read-only");
  857. assert_eq!(memory_at(base + 0x2008), "a guard page");
  858. assert_eq!(memory_at(base + 0x3008), "no access");
  859. // SAFETY: releases the reservation made above.
  860. unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) };
  861. assert_eq!(memory_at(base + 8), "nothing mapped there");
  862. assert_eq!(memory_at(0), "nothing mapped there");
  863. assert_eq!(memory_at(usize::MAX), "outside the address space");
  864. // This test's own code: an image page, named by its module.
  865. let code = memory_at(memory_at_names_what_an_access_hit as *const () as usize);
  866. let named = code.starts_with("read-execute, in victory_loader-");
  867. assert!(named, "{code}");
  868. }
  869. /// On an Intel CPU, the real instructions go through the vectored
  870. /// handler. On an AMD CPU they run natively, and the tests below test
  871. /// the emulation.
  872. #[test]
  873. fn clwb_loops() {
  874. // clwb [rcx]; add rcx, 0x40; cmp rcx, rax; jbe top
  875. let a = clwb_loop(&[
  876. 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf3,
  877. ])
  878. .expect("rcx loop");
  879. assert_eq!((a.base, a.limit, a.len), (1, 0, 13));
  880. // clwb [r9]; add r9, 0x40; cmp r9, rax; jbe top
  881. let b = clwb_loop(&[
  882. 0x66, 0x41, 0x0f, 0xae, 0x31, 0x49, 0x83, 0xc1, 0x40, 0x49, 0x39, 0xc1, 0x76, 0xf2,
  883. ])
  884. .expect("r9 loop");
  885. assert_eq!((b.base, b.limit, b.len), (9, 0, 14));
  886. // A different stride, a jump elsewhere, or a cut-off loop is not one.
  887. assert!(
  888. clwb_loop(&[
  889. 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x20, 0x48, 0x39, 0xc1, 0x76, 0xf3
  890. ])
  891. .is_none()
  892. );
  893. assert!(
  894. clwb_loop(&[
  895. 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf0
  896. ])
  897. .is_none()
  898. );
  899. assert!(clwb_loop(&[0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40]).is_none());
  900. // The flags the last cmp leaves: base just past limit.
  901. assert_eq!(cmp_flags(0x1040, 0x1000) & 0x41, 0); // CF and ZF clear: the loop ends
  902. assert_eq!(cmp_flags(0x1000, 0x1000) & 0x40, 0x40);
  903. }
  904. #[test]
  905. fn clwb_lengths() {
  906. let pad = |b: &[u8]| {
  907. let mut c = [0u8; 15];
  908. c[..b.len()].copy_from_slice(b);
  909. c
  910. };
  911. assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9]
  912. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax]
  913. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40]
  914. assert_eq!(
  915. clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])),
  916. Some(8)
  917. ); // [rax+disp32]
  918. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp]
  919. assert_eq!(
  920. clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])),
  921. Some(8)
  922. ); // [rip+disp32]
  923. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7
  924. assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66
  925. assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form
  926. }
  927. #[test]
  928. fn clzero_zeroes_its_line_on_any_cpu() {
  929. report_crashes();
  930. #[repr(align(64))]
  931. struct Line([u8; 128]);
  932. let mut line = Line([0xff; 128]);
  933. let at = line.0.as_mut_ptr().wrapping_add(5); // inside the first line
  934. // SAFETY: clzero writes only the 64-byte line holding `at`, ours.
  935. unsafe { std::arch::asm!(".byte 0x0f, 0x01, 0xfc", in("rax") at) };
  936. assert!(line.0[..64].iter().all(|&b| b == 0));
  937. assert!(line.0[64..].iter().all(|&b| b == 0xff));
  938. // insertq xmm0, xmm1, len 16, at 16; then extrq xmm0, len 8, at 20.
  939. let out: u64;
  940. // SAFETY: touches only the named registers.
  941. unsafe {
  942. std::arch::asm!(
  943. "movq xmm0, {a}", "movq xmm1, {b}",
  944. ".byte 0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10",
  945. "movq {a}, xmm0",
  946. ".byte 0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14",
  947. "movq {b}, xmm0",
  948. a = inout(reg) 0x1111_2222_3333_4444u64 => _, b = inout(reg) 0xabcdu64 => out,
  949. out("xmm0") _, out("xmm1") _)
  950. };
  951. assert_eq!(out, 0xbc); // 0x1111_2222_abcd_4444 >> 20, 8 bits
  952. // SAFETY: monitorx/mwaitx are wait hints that write no memory.
  953. unsafe {
  954. std::arch::asm!(".byte 0x0f, 0x01, 0xfa", ".byte 0x0f, 0x01, 0xfb",
  955. in("rax") at, in("ecx") 0, in("edx") 0)
  956. };
  957. // rdpru of MPERF: a count in edx:eax, their high halves clear.
  958. let (low, high): (u64, u64);
  959. // SAFETY: touches only the named registers.
  960. unsafe {
  961. std::arch::asm!(".byte 0x0f, 0x01, 0xfd",
  962. out("rax") low, inout("rcx") 0u64 => _, out("rdx") high)
  963. };
  964. assert_ne!(high << 32 | low, 0);
  965. assert!(high >> 32 == 0 && low >> 32 == 0);
  966. }
  967. /// The flags a native `cmp a, b` leaves.
  968. fn native_compare(a: u64, b: u64) -> u32 {
  969. let flags: u64;
  970. // SAFETY: compares two registers and reads the flags.
  971. unsafe {
  972. std::arch::asm!("cmp {a}, {b}", "pushfq", "pop {f}",
  973. a = in(reg) a, b = in(reg) b, f = out(reg) flags)
  974. };
  975. flags as u32 & CMP_FLAGS
  976. }
  977. #[test]
  978. fn compare_sets_flags_like_the_cpu() {
  979. let values = [0, 1, 0x40, 0x7f, 0x80, 0xff, 1 << 63, (1 << 63) - 1, !0, !0 - 0x40];
  980. for a in values {
  981. for b in values {
  982. assert_eq!(cmp_flags(a, b), native_compare(a, b), "cmp {a:#x}, {b:#x}");
  983. }
  984. }
  985. }
  986. #[test]
  987. fn clzero_loops_end_like_their_last_pass() {
  988. report_crashes();
  989. #[repr(align(64))]
  990. struct Lines([u8; 192]);
  991. let zeroed = |l: &Lines| [l.0[0] == 0, l.0[64] == 0, l.0[128] == 0];
  992. // clzero; add rax, 0x40; cmp rax, r10; jb
  993. let mut mem = Lines([0xff; 192]);
  994. let start = mem.0.as_mut_ptr() as u64;
  995. let (end, flags): (u64, u64);
  996. // SAFETY: zeroes the first two lines of `mem`.
  997. unsafe {
  998. std::arch::asm!(
  999. ".byte 0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x4c, 0x39, 0xd0, 0x72, 0xf4",
  1000. "pushfq", "pop {f}",
  1001. inout("rax") start => end, in("r10") start + 100, f = out(reg) flags)
  1002. };
  1003. assert_eq!(end, start + 128);
  1004. assert_eq!(flags as u32 & CMP_FLAGS, native_compare(end, start + 100));
  1005. assert_eq!(zeroed(&mem), [true, true, false]);
  1006. // mov rax, rdx; add rdx, 0x40; clzero; cmp rdx, r8; jb
  1007. let mut mem = Lines([0xff; 192]);
  1008. let start = mem.0.as_mut_ptr() as u64;
  1009. let (last, next, flags): (u64, u64, u64);
  1010. // SAFETY: zeroes the last two lines of `mem`.
  1011. unsafe {
  1012. std::arch::asm!(
  1013. ".byte 0x48, 0x89, 0xd0, 0x48, 0x83, 0xc2, 0x40, 0x0f, 0x01, 0xfc",
  1014. ".byte 0x4c, 0x39, 0xc2, 0x72, 0xf1",
  1015. "pushfq", "pop {f}",
  1016. out("rax") last, inout("rdx") start + 64 => next, in("r8") start + 192,
  1017. f = out(reg) flags)
  1018. };
  1019. assert_eq!((last, next), (start + 128, start + 192));
  1020. assert_eq!(flags as u32 & CMP_FLAGS, native_compare(next, start + 192));
  1021. assert_eq!(zeroed(&mem), [false, true, true]);
  1022. }
  1023. fn reg(low: u64, high: u64) -> M128A {
  1024. M128A {
  1025. Low: low,
  1026. High: high as i64,
  1027. }
  1028. }
  1029. /// Gives `code` to the emulation as if it faulted with `exception` at
  1030. /// its first byte, with `rax` and `xmm` as the saved registers. The
  1031. /// emulation does not execute `code`, so this works on any CPU. Returns
  1032. /// the number of bytes that the emulation skipped, or `None` if it did
  1033. /// not emulate the instruction. `xmm` gets the saved registers after.
  1034. fn emulate_as(exception: i32, code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option<u64> {
  1035. // `int3` after the instruction, so that a decoder that reads too
  1036. // far sees no valid bytes.
  1037. let mut bytes = [0xcc_u8; 16];
  1038. bytes[..code.len()].copy_from_slice(code);
  1039. let start = bytes.as_ptr() as u64;
  1040. // SAFETY: a zeroed record and context are valid; the emulation
  1041. // reads only `bytes` and writes only `context` (and memory at
  1042. // `rax` for clzero, which the caller owns).
  1043. unsafe {
  1044. let mut record: EXCEPTION_RECORD = std::mem::zeroed();
  1045. record.ExceptionCode = exception;
  1046. let mut context: CONTEXT = std::mem::zeroed();
  1047. context.Rip = start;
  1048. context.Rax = rax;
  1049. context.Anonymous.FltSave.XmmRegisters = *xmm;
  1050. let mut pointers = EXCEPTION_POINTERS {
  1051. ExceptionRecord: &mut record,
  1052. ContextRecord: &mut context,
  1053. };
  1054. let emulated = emulate_amd_only(&mut pointers);
  1055. *xmm = context.Anonymous.FltSave.XmmRegisters;
  1056. emulated.then(|| context.Rip - start)
  1057. }
  1058. }
  1059. fn emulate(code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option<u64> {
  1060. emulate_as(EXCEPTION_ILLEGAL_INSTRUCTION, code, rax, xmm)
  1061. }
  1062. fn low(xmm: &[M128A; 16], i: usize) -> u64 {
  1063. xmm[i].Low
  1064. }
  1065. #[test]
  1066. fn emulated_clzero_zeroes_its_line() {
  1067. #[repr(align(64))]
  1068. struct Line([u8; 128]);
  1069. let mut line = Line([0xff; 128]);
  1070. let at = line.0.as_mut_ptr().wrapping_add(5) as u64; // inside the first line
  1071. let mut xmm = [reg(0, 0); 16];
  1072. assert_eq!(emulate(&[0x0f, 0x01, 0xfc], at, &mut xmm), Some(3));
  1073. assert!(line.0[..64].iter().all(|&b| b == 0));
  1074. assert!(line.0[64..].iter().all(|&b| b == 0xff));
  1075. }
  1076. /// Gives `code` to the emulation as if it faulted at `code[at]` with
  1077. /// `context` as the saved state, on any CPU; returns whether it
  1078. /// emulated and leaves the state after in `context`.
  1079. fn emulate_in(code: &[u8], at: usize, context: &mut CONTEXT) -> bool {
  1080. // At a fixed place in a page, so the loops' neighbours are always
  1081. // read (they are not near a page's edges).
  1082. #[repr(align(4096))]
  1083. struct Page([u8; 4096]);
  1084. let mut page = Box::new(Page([0xcc; 4096]));
  1085. let bytes = &mut page.0[0x800..];
  1086. bytes[..code.len()].copy_from_slice(code);
  1087. context.Rip = bytes.as_ptr() as u64 + at as u64;
  1088. // SAFETY: a zeroed record is valid; the emulation reads only
  1089. // `bytes` and writes `context` and the lines the caller owns.
  1090. unsafe {
  1091. let mut record: EXCEPTION_RECORD = std::mem::zeroed();
  1092. record.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
  1093. let mut pointers = EXCEPTION_POINTERS {
  1094. ExceptionRecord: &mut record,
  1095. ContextRecord: context,
  1096. };
  1097. let emulated = emulate_amd_only(&mut pointers);
  1098. context.Rip -= bytes.as_ptr() as u64;
  1099. emulated
  1100. }
  1101. }
  1102. #[test]
  1103. fn emulated_clzero_loops_end_like_their_last_pass() {
  1104. #[repr(align(64))]
  1105. struct Lines([u8; 192]);
  1106. let zeroed = |l: &Lines| [l.0[0] == 0, l.0[64] == 0, l.0[128] == 0];
  1107. // clzero; add rax, 0x40; cmp rax, r10; jb
  1108. let mut mem = Lines([0xff; 192]);
  1109. let start = mem.0.as_mut_ptr() as u64;
  1110. // SAFETY: an all-zero context is valid.
  1111. let mut context: CONTEXT = unsafe { std::mem::zeroed() };
  1112. context.Rax = start;
  1113. context.R10 = start + 100;
  1114. context.EFlags = 0x202 | CMP_FLAGS;
  1115. let code = [0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x4c, 0x39, 0xd0, 0x72, 0xf4];
  1116. assert!(emulate_in(&code, 0, &mut context));
  1117. assert_eq!((context.Rip, context.Rax), (12, start + 128));
  1118. assert_eq!(context.EFlags, 0x202 | native_compare(start + 128, start + 100));
  1119. assert_eq!(zeroed(&mem), [true, true, false]);
  1120. // mov rax, rdx; add rdx, 0x40; clzero; cmp rdx, r8; jb (faults at clzero,
  1121. // after the first pass's mov and add)
  1122. let mut mem = Lines([0xff; 192]);
  1123. let start = mem.0.as_mut_ptr() as u64;
  1124. // SAFETY: an all-zero context is valid.
  1125. let mut context: CONTEXT = unsafe { std::mem::zeroed() };
  1126. context.Rax = start + 64;
  1127. context.Rdx = start + 128;
  1128. context.R8 = start + 192;
  1129. let code = [
  1130. 0x48, 0x89, 0xd0, 0x48, 0x83, 0xc2, 0x40, 0x0f, 0x01, 0xfc, 0x4c, 0x39, 0xc2, 0x72,
  1131. 0xf1,
  1132. ];
  1133. assert!(emulate_in(&code, 7, &mut context));
  1134. assert_eq!((context.Rip, context.Rax, context.Rdx), (15, start + 128, start + 192));
  1135. assert_eq!(context.EFlags, native_compare(start + 192, start + 192));
  1136. assert_eq!(zeroed(&mem), [false, true, true]);
  1137. // cmp rax, rax is not the loop (the limit would move with rax): one
  1138. // line, flags untouched.
  1139. let mut mem = Lines([0xff; 192]);
  1140. // SAFETY: an all-zero context is valid.
  1141. let mut context: CONTEXT = unsafe { std::mem::zeroed() };
  1142. context.Rax = mem.0.as_mut_ptr() as u64;
  1143. context.EFlags = 0x202;
  1144. let code = [0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x48, 0x39, 0xc0, 0x72, 0xf4];
  1145. assert!(emulate_in(&code, 0, &mut context));
  1146. assert_eq!((context.Rip, context.EFlags), (3, 0x202));
  1147. assert_eq!(zeroed(&mem), [true, false, false]);
  1148. // Any other neighbours: one line, then the next instruction.
  1149. let mut mem = Lines([0xff; 192]);
  1150. // SAFETY: an all-zero context is valid.
  1151. let mut context: CONTEXT = unsafe { std::mem::zeroed() };
  1152. context.Rax = mem.0.as_mut_ptr() as u64 + 70;
  1153. context.R10 = !0;
  1154. let code = [0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x20, 0x4c, 0x39, 0xd0, 0x72, 0xf4];
  1155. assert!(emulate_in(&code, 0, &mut context));
  1156. assert_eq!(context.Rip, 3);
  1157. assert_eq!(zeroed(&mem), [false, true, false]);
  1158. }
  1159. #[test]
  1160. fn emulated_rdpru_reads_known_counters_and_keeps_flags() {
  1161. let cases = [(0, true), (1, true), (2, false), (0x1_0000_0000, true)];
  1162. let starts = [0x202, 0x202 | CMP_FLAGS];
  1163. for ((ecx, known), flags) in cases.into_iter().flat_map(|c| starts.map(|f| (c, f))) {
  1164. // SAFETY: an all-zero context is valid.
  1165. let mut context: CONTEXT = unsafe { std::mem::zeroed() };
  1166. context.Rcx = ecx;
  1167. context.Rax = !0;
  1168. context.Rdx = !0;
  1169. context.EFlags = flags;
  1170. assert!(emulate_in(&[0x0f, 0x01, 0xfd], 0, &mut context));
  1171. assert_eq!(context.Rip, 3);
  1172. assert_eq!(context.EFlags, flags, "ecx {ecx:#x}");
  1173. let count = context.Rdx << 32 | context.Rax;
  1174. assert!(context.Rax >> 32 == 0 && context.Rdx >> 32 == 0);
  1175. assert_eq!(count != 0, known, "ecx {ecx:#x}");
  1176. }
  1177. }
  1178. #[test]
  1179. fn emulated_monitorx_and_mwaitx_are_skipped() {
  1180. let mut xmm = [reg(1, 2); 16];
  1181. assert_eq!(emulate(&[0x0f, 0x01, 0xfa], 0, &mut xmm), Some(3));
  1182. assert_eq!(emulate(&[0x0f, 0x01, 0xfb], 0, &mut xmm), Some(3));
  1183. assert!(xmm.iter().all(|r| r.Low == 1 && r.High == 2));
  1184. }
  1185. #[test]
  1186. fn emulated_insertq_and_extrq_with_immediates() {
  1187. let mut xmm = [reg(0, 0); 16];
  1188. xmm[0] = reg(0x1111_2222_3333_4444, 0x5555);
  1189. xmm[1] = reg(0xabcd, 0x6666);
  1190. // insertq xmm0, xmm1, length 16, index 16
  1191. let insertq = [0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10];
  1192. assert_eq!(emulate(&insertq, 0, &mut xmm), Some(6));
  1193. assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444);
  1194. assert_eq!((low(&xmm, 1), xmm[1].High), (0xabcd, 0x6666));
  1195. // extrq xmm0, length 8, index 20
  1196. let extrq = [0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14];
  1197. assert_eq!(emulate(&extrq, 0, &mut xmm), Some(6));
  1198. assert_eq!(low(&xmm, 0), 0xbc);
  1199. }
  1200. #[test]
  1201. fn emulated_insertq_and_extrq_with_fields_in_a_register() {
  1202. let mut xmm = [reg(0, 0); 16];
  1203. // insertq xmm0, xmm1: length and index in xmm1's high half.
  1204. xmm[0] = reg(0x1111_2222_3333_4444, 0);
  1205. xmm[1] = reg(0xabcd, 0x10_10);
  1206. assert_eq!(emulate(&[0xf2, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4));
  1207. assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444);
  1208. // extrq xmm0, xmm1: length and index in xmm1's low half.
  1209. xmm[1] = reg(0x14_08, 0);
  1210. assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4));
  1211. assert_eq!(low(&xmm, 0), 0xbc);
  1212. }
  1213. #[test]
  1214. fn emulated_sse4a_reaches_xmm8_to_xmm15() {
  1215. let mut xmm = [reg(0, 0); 16];
  1216. xmm[8] = reg(0x1111_2222_3333_4444, 0);
  1217. xmm[9] = reg(0xabcd, 0);
  1218. // insertq xmm8, xmm9, length 16, index 16 (REX.R and REX.B)
  1219. let insertq = [0xf2, 0x45, 0x0f, 0x78, 0xc1, 0x10, 0x10];
  1220. assert_eq!(emulate(&insertq, 0, &mut xmm), Some(7));
  1221. assert_eq!(low(&xmm, 8), 0x1111_2222_abcd_4444);
  1222. assert_eq!((low(&xmm, 0), low(&xmm, 1)), (0, 0));
  1223. // extrq xmm9, length 8, index 4 (REX.B)
  1224. let extrq = [0x66, 0x41, 0x0f, 0x78, 0xc1, 0x08, 0x04];
  1225. assert_eq!(emulate(&extrq, 0, &mut xmm), Some(7));
  1226. assert_eq!(low(&xmm, 9), 0xbc);
  1227. assert_eq!(low(&xmm, 1), 0);
  1228. }
  1229. #[test]
  1230. fn emulated_sse4a_length_0_is_64_bits() {
  1231. let mut xmm = [reg(0, 0); 16];
  1232. xmm[0] = reg(0x1122_3344_5566_7788, 0);
  1233. // extrq xmm0, length 0 (64), index 0. A non-zero index with
  1234. // length 64 goes past bit 63, and AMD leaves that result undefined.
  1235. assert_eq!(
  1236. emulate(&[0x66, 0x0f, 0x78, 0xc0, 0x00, 0x00], 0, &mut xmm),
  1237. Some(6)
  1238. );
  1239. assert_eq!(low(&xmm, 0), 0x1122_3344_5566_7788);
  1240. // insertq xmm0, xmm1, length 0 (64), index 0
  1241. xmm[1] = reg(0xdead_beef_cafe_f00d, 0);
  1242. assert_eq!(
  1243. emulate(&[0xf2, 0x0f, 0x78, 0xc1, 0x00, 0x00], 0, &mut xmm),
  1244. Some(6)
  1245. );
  1246. assert_eq!(low(&xmm, 0), 0xdead_beef_cafe_f00d);
  1247. }
  1248. #[test]
  1249. fn other_instructions_and_exceptions_are_not_emulated() {
  1250. let mut xmm = [reg(0, 0); 16];
  1251. assert_eq!(emulate(&[0x0f, 0x0b], 0, &mut xmm), None); // ud2
  1252. // extrq with a memory operand, which does not exist
  1253. assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0x00], 0, &mut xmm), None);
  1254. // extrq with immediates needs ModRM.reg 0
  1255. let bad_extrq = [0x66, 0x0f, 0x78, 0xc8, 0x08, 0x14];
  1256. assert_eq!(emulate(&bad_extrq, 0, &mut xmm), None);
  1257. // a clzero that did not cause an illegal instruction
  1258. let clzero = [0x0f, 0x01, 0xfc];
  1259. assert_eq!(
  1260. emulate_as(EXCEPTION_ACCESS_VIOLATION, &clzero, 0, &mut xmm),
  1261. None
  1262. );
  1263. }
  1264. #[test]
  1265. fn instruction_bytes_stop_at_the_end_of_their_page() {
  1266. use windows_sys::Win32::System::Memory::{
  1267. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc,
  1268. VirtualFree, VirtualProtect,
  1269. };
  1270. // rdpru, then the next instruction (mov rcx, rax) and padding.
  1271. let mut code = [0x90_u8; 16];
  1272. code[..6].copy_from_slice(&[0x0f, 0x01, 0xfd, 0x48, 0x89, 0xc1]);
  1273. // SAFETY: two fresh pages of ours, the second made unreadable, so a
  1274. // read past the end of the first faults.
  1275. unsafe {
  1276. let page = VirtualAlloc(
  1277. std::ptr::null(),
  1278. 0x2000,
  1279. MEM_RESERVE | MEM_COMMIT,
  1280. PAGE_READWRITE,
  1281. )
  1282. .cast::<u8>();
  1283. assert!(!page.is_null());
  1284. let mut old = 0;
  1285. let guard = page.add(0x1000).cast();
  1286. assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0);
  1287. page.copy_from_nonoverlapping(code.as_ptr(), code.len());
  1288. let whole = "0f 01 fd 48 89 c1 90 90 90 90 90 90 90 90 90";
  1289. assert_eq!(instruction_bytes(page as usize), whole);
  1290. // The page's last three bytes: rdpru, and nothing read after it.
  1291. let end = page.add(0x1000 - 3);
  1292. end.copy_from_nonoverlapping(code.as_ptr(), 3);
  1293. assert_eq!(instruction_bytes(end as usize), "0f 01 fd");
  1294. VirtualFree(page.cast(), 0, MEM_RELEASE);
  1295. }
  1296. }
  1297. }