console_insn.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. //! Instructions the console's CPU (Zen 2) has and an Intel PC's lacks, emulated: the title's
  2. //! code raises STATUS_ILLEGAL_INSTRUCTION on them (the title zeroes memory with a `clzero` loop at
  3. //! its first frames), and the vectored handler steps over them here.
  4. //!
  5. //! Ported from XCL (github.com/ivall/xcl, GPL-2.0-only): `insn.rs` (decoder, as
  6. //! `console_insn_decode.rs`, unchanged) and `eh.rs` `emulate_console_only`.
  7. #[path = "console_insn_decode.rs"]
  8. mod decode;
  9. use decode::ConsoleOnly;
  10. use std::cell::Cell;
  11. use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
  12. use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT;
  13. const CONTINUE_EXECUTION: i32 = -1;
  14. /// Whether what Windows said about memory is remembered per thread (the regions it found
  15. /// writable, the code bytes it found readable) and not asked again at every emulated
  16. /// instruction. A query walks the pages of the region it answers for: asked from outside, it
  17. /// took 2-9 ms in the title's heaps of 0.6-2.2 GB and 89 ms in its 6.2 GB page pool (run 30),
  18. /// and the title zeroes blocks of them with `clzero` loops all through a frame: six of its
  19. /// threads spent 25-78 % of their time inside that query (runs 29 and 30), about 27 s of
  20. /// processor time in Windows per 9 s frame. On by default; `VICTORY_CLZERO_ASK=1` asks every
  21. /// time, as before.
  22. fn remembers() -> bool {
  23. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  24. *ON.get_or_init(|| std::env::var_os("VICTORY_CLZERO_ASK").is_none_or(|v| v != "1"))
  25. }
  26. /// Answers a remembered region gives before Windows is asked about it again: one freed or
  27. /// protected meanwhile is forgotten then.
  28. const ANSWERS: u32 = 4096;
  29. thread_local! {
  30. /// The regions Windows last said are committed and writable (start, end), newest first,
  31. /// and the answers they gave since they were emptied.
  32. static WRITABLE: Cell<([(usize, usize); 4], u32)> = const { Cell::new(([(0, 0); 4], 0)) };
  33. /// Faulting addresses and the code bytes found readable there, newest first.
  34. static CODE: Cell<[(usize, usize); 8]> = const { Cell::new([(0, 0); 8]) };
  35. }
  36. /// Instructions emulated, the times Windows was asked about memory for them, and the bytes
  37. /// `clzero` loops zeroed, since the start.
  38. static EMULATED: AtomicU64 = AtomicU64::new(0);
  39. static ASKED: AtomicU64 = AtomicU64::new(0);
  40. static ZEROED: AtomicU64 = AtomicU64::new(0);
  41. fn readable(va: usize, bytes: usize) -> bool {
  42. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery};
  43. // SAFETY: plain data filled in by the query.
  44. let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  45. // SAFETY: a valid out pointer of the right size.
  46. let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0;
  47. ASKED.fetch_add(1, Relaxed);
  48. found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes
  49. }
  50. fn writable(va: usize, bytes: usize) -> bool {
  51. writable_to(va, va + bytes) == Some(va + bytes)
  52. }
  53. /// Where the committed, writable memory that `va` lies in ends, at most `end`; None if `va`
  54. /// is not in such memory. A region found is remembered ([`remembers`]).
  55. /// shortcut: a remembered region that was freed or protected since is written all the same
  56. /// for up to [`ANSWERS`] answers: the write then faults inside the handler, which the guard
  57. /// on view memory opens as it does any write, and which is a crash otherwise (as the
  58. /// unchecked single-line emulation behind this one already is).
  59. fn writable_to(va: usize, end: usize) -> Option<usize> {
  60. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery};
  61. let remember = remembers();
  62. if remember {
  63. let (regions, answers) = WRITABLE.with(Cell::get);
  64. if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) {
  65. let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) };
  66. WRITABLE.with(|w| w.set(next));
  67. return Some(to.min(end));
  68. }
  69. }
  70. // SAFETY: plain data filled in by the query.
  71. let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  72. // SAFETY: a valid out pointer of the right size.
  73. let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0;
  74. ASKED.fetch_add(1, Relaxed);
  75. if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 {
  76. return None;
  77. }
  78. let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize);
  79. if remember {
  80. WRITABLE.with(|w| {
  81. let (mut regions, answers) = w.get();
  82. regions.rotate_right(1);
  83. regions[0] = (from, to);
  84. w.set((regions, answers));
  85. });
  86. }
  87. Some(to.min(end))
  88. }
  89. /// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over
  90. /// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers
  91. /// see it).
  92. ///
  93. /// # Safety
  94. /// `ctx` is the faulting thread's context, from the exception being dispatched.
  95. pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 {
  96. let rip = ctx.Rip as usize;
  97. // The same few instructions fault again and again: their bytes are asked about once.
  98. let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] };
  99. let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) {
  100. Some(&(_, n)) => n,
  101. None => {
  102. if !readable(rip, 1) {
  103. return 0;
  104. }
  105. let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0);
  106. if remembers() {
  107. let mut known = known;
  108. known.rotate_right(1);
  109. known[0] = (rip, n);
  110. CODE.with(|c| c.set(known));
  111. }
  112. n
  113. }
  114. };
  115. // SAFETY: `n` bytes at `rip` are readable.
  116. let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) };
  117. let Some((what, len)) = decode::decode(code) else { return 0 };
  118. static SEEN: std::sync::Mutex<Vec<std::mem::Discriminant<ConsoleOnly>>> = std::sync::Mutex::new(Vec::new());
  119. if let Ok(mut seen) = SEEN.lock()
  120. && !seen.contains(&std::mem::discriminant(&what))
  121. {
  122. seen.push(std::mem::discriminant(&what));
  123. if what != ConsoleOnly::Ud2 {
  124. tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)");
  125. }
  126. }
  127. match what {
  128. ConsoleOnly::Ud2 => return 0,
  129. ConsoleOnly::Clwb => {
  130. // nothing to write back on the PC: patched to NOPs, no exception next time
  131. use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
  132. let mut old = 0u32;
  133. // SAFETY: the instruction's own bytes, made writable for the patch and restored.
  134. unsafe {
  135. if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 {
  136. std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90);
  137. VirtualProtect(rip as *const _, len, old, &mut old);
  138. }
  139. }
  140. }
  141. ConsoleOnly::Monitorx => {}
  142. ConsoleOnly::Mwaitx => std::hint::spin_loop(),
  143. ConsoleOnly::Clzero => {
  144. // with an address-size prefix (0x67) the line is at EAX, zero-extended
  145. let a32 = code[..len - 3].contains(&0x67);
  146. let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63;
  147. if !writable(line, 64) {
  148. return 0; // the real instruction faults there too
  149. }
  150. // SAFETY: the 64-byte line is committed and writable.
  151. unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) };
  152. }
  153. ConsoleOnly::ClzeroLoop { end_reg } => {
  154. // the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once
  155. let regs: [u64; 16] = [
  156. ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15,
  157. ];
  158. let end = regs[end_reg as usize & 15] as usize;
  159. let start = ctx.Rax as usize;
  160. if end > start && end - start < 2 << 30 {
  161. // Region by region: a block may lie across several (the title's pages are
  162. // mapped one view each), and one answer for all of it was a refusal, after
  163. // which every 64-byte line took an exception of its own.
  164. let mut at = start;
  165. while at < end {
  166. let Some(to) = writable_to(at, end) else { break };
  167. // SAFETY: committed and writable from `at` to `to`.
  168. unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) };
  169. at = to;
  170. }
  171. if at == start {
  172. return 0;
  173. }
  174. ZEROED.fetch_add((at - start) as u64, Relaxed);
  175. if at < end {
  176. // What follows is not writable: the loop goes on there (the same
  177. // instruction again), where the real one faults too.
  178. ctx.Rax = at as u64;
  179. return CONTINUE_EXECUTION;
  180. }
  181. }
  182. ctx.Rax = end as u64;
  183. }
  184. ConsoleOnly::Rdpru => {
  185. let mut v = 0i64;
  186. // SAFETY: a valid out pointer.
  187. unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) };
  188. let v = if ctx.Rcx as u32 <= 1 { v as u64 } else { 0 };
  189. ctx.Rax = v & 0xFFFF_FFFF;
  190. ctx.Rdx = v >> 32;
  191. }
  192. ConsoleOnly::Rdpid(r) => {
  193. // SAFETY: no preconditions.
  194. let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64;
  195. let regs: [&mut u64; 16] = [
  196. &mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13,
  197. &mut ctx.R14, &mut ctx.R15,
  198. ];
  199. *regs[r as usize & 15] = cpu;
  200. }
  201. // the low quadword changes; the high one is zeroed, as a Zen 5 does
  202. ConsoleOnly::Extrq { dst, src, len, idx } => {
  203. // SAFETY: the context's XMM registers (CONTEXT_FLOATING_POINT is captured for exceptions).
  204. let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters };
  205. let (len, idx) = match src {
  206. Some(s) => {
  207. let c = x[s as usize & 15].Low;
  208. (c as u8, (c >> 8) as u8)
  209. }
  210. None => (len, idx),
  211. };
  212. let d = &mut x[dst as usize & 15];
  213. d.Low = decode::extrq(d.Low, len, idx);
  214. d.High = 0;
  215. }
  216. ConsoleOnly::Insertq { dst, src, reg, len, idx } => {
  217. // SAFETY: as above.
  218. let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters };
  219. let s = x[src as usize & 15];
  220. let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) };
  221. let d = &mut x[dst as usize & 15];
  222. d.Low = decode::insertq(d.Low, s.Low, len, idx);
  223. d.High = 0;
  224. }
  225. }
  226. ctx.Rip += len as u64;
  227. // How often this runs at all (each one is an exception: a trip into Windows and back).
  228. let emulated = EMULATED.fetch_add(1, Relaxed) + 1;
  229. if emulated >= 1 << 16 && emulated.is_power_of_two() {
  230. tracing::info!(
  231. emulated,
  232. asked = ASKED.load(Relaxed),
  233. zeroed_mb = ZEROED.load(Relaxed) >> 20,
  234. "console CPU instructions emulated so far, the times Windows was asked about memory for them, and what clzero loops zeroed"
  235. );
  236. }
  237. CONTINUE_EXECUTION
  238. }