console_insn.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. /// Whether `monitorx` and `mwaitx` are replaced in the title's code the first time they fault
  42. /// (`monitorx` by a 3-byte no-op, `mwaitx` by `pause` and a no-op), so that they never fault
  43. /// again. Emulated, each pass of such a wait loop is two trips into Windows and back, through
  44. /// every vectored handler, and no lighter a wait for it: the emulation does no more than
  45. /// `pause` either, and the loop looks at its value again after it. On by default;
  46. /// `VICTORY_PATCH_WAITS=0` emulates each time, as before.
  47. fn patches_waits() -> bool {
  48. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  49. *ON.get_or_init(|| std::env::var_os("VICTORY_PATCH_WAITS").is_none_or(|v| v != "0"))
  50. }
  51. /// What replaces the 3 bytes of a wait instruction.
  52. fn wait_patch(what: ConsoleOnly) -> Option<[u8; 3]> {
  53. match what {
  54. ConsoleOnly::Monitorx => Some([0x0f, 0x1f, 0x00]),
  55. ConsoleOnly::Mwaitx => Some([0xf3, 0x90, 0x90]),
  56. _ => None,
  57. }
  58. }
  59. /// Whether a `clzero` loop ([`ConsoleOnly::ClzeroLoop`]) is replaced the first time it faults
  60. /// by a jump to the same loop with plain stores ([`clzero_stub`]). Run cpu-5 (the dorm): 25,000
  61. /// exceptions a second, 2,100 a frame, at five such loops of one function of the title, for
  62. /// some kilobytes each; ten times what the wait instructions raised. On by default;
  63. /// `VICTORY_PATCH_CLZERO=0` emulates each time, as before.
  64. fn patches_clzero() -> bool {
  65. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  66. *ON.get_or_init(|| std::env::var_os("VICTORY_PATCH_CLZERO").is_none_or(|v| v != "0"))
  67. }
  68. /// `jmp rel32` at `at` to `to`, if it reaches.
  69. pub(crate) fn jump(at: usize, to: usize) -> Option<[u8; 5]> {
  70. let rel = i32::try_from(to as i64 - (at as i64 + 5)).ok()?;
  71. let [a, b, c, d] = rel.to_le_bytes();
  72. Some([0xe9, a, b, c, d])
  73. }
  74. /// The `clzero` loop of 12 bytes at `at` with plain stores, as code at `stub`: every register
  75. /// and the flags come out as the loop leaves them. `cmp` is its `cmp rax, reg` (3 bytes, the
  76. /// register not `rax`), `None` for another form. (The scratch register is saved on the stack
  77. /// and back before the compare, whose register it may be.)
  78. fn clzero_stub(at: usize, stub: usize, cmp: [u8; 3]) -> Option<Vec<u8>> {
  79. if !matches!(cmp[0], 0x48 | 0x4c) || cmp[1] != 0x39 || cmp[2] & 0xc7 != 0xc0 || (cmp[0] == 0x48 && cmp[2] == 0xc0) {
  80. return None;
  81. }
  82. let mut code = vec![
  83. 0x51, // push rcx
  84. 0x48, 0x89, 0xc1, // mov rcx, rax
  85. 0x48, 0x83, 0xe1, 0xc0, // and rcx, -64
  86. ];
  87. for k in 0..8 {
  88. code.extend([0x48, 0xc7, 0x41, k * 8, 0, 0, 0, 0]); // mov qword [rcx + 8k], 0
  89. }
  90. code.push(0x59); // pop rcx
  91. code.extend([0x48, 0x83, 0xc0, 0x40]); // add rax, 0x40
  92. code.extend(cmp);
  93. let back = -(code.len() as i64 + 2);
  94. code.extend([0x72, i8::try_from(back).ok()? as u8]); // jb the start
  95. let end = stub + code.len();
  96. code.extend(jump(end, at + 12)?);
  97. Some(code)
  98. }
  99. /// Room for [`clzero_stub`]s near the title's code: where it is and the bytes used.
  100. static STUBS: std::sync::Mutex<Option<(usize, usize)>> = std::sync::Mutex::new(None);
  101. pub(crate) const STUBS_LEN: usize = 64 << 10;
  102. /// Memory for code within reach of a `jmp rel32` at `at`.
  103. pub(crate) fn near(at: usize) -> Option<usize> {
  104. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc};
  105. let at = at & !0xffff;
  106. (0x10_0000..0x7000_0000).step_by(0x10_0000).flat_map(|d| [at.checked_sub(d), at.checked_add(d)]).flatten().find_map(|place| {
  107. // SAFETY: reserves free memory at that address or fails.
  108. let got = unsafe { VirtualAlloc(place as *const _, STUBS_LEN, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) } as usize;
  109. (got != 0).then_some(got)
  110. })
  111. }
  112. /// Replaces the `clzero` loop at `at`, whose 12 bytes are `code`: whether it did.
  113. ///
  114. /// No thread is ever inside the loop's other instructions (the emulation does the whole loop
  115. /// in one), so the five bytes of the jump may take the place of two of them.
  116. ///
  117. /// # Safety
  118. /// `at` is in the title's code, which stays mapped.
  119. unsafe fn patch_clzero(at: usize, code: &[u8]) -> bool {
  120. let &[a, b, c, d, e, _, _, x, y, z, 0x72, 0xf4] = code else {
  121. return false;
  122. };
  123. let mut stubs = STUBS.lock().unwrap_or_else(|e| e.into_inner());
  124. if stubs.is_none() {
  125. *stubs = near(at).map(|place| (place, 0));
  126. }
  127. let Some((place, used)) = stubs.as_mut() else {
  128. return false;
  129. };
  130. let stub = *place + *used;
  131. let (Some(body), Some(jump)) = (clzero_stub(at, stub, [x, y, z]), jump(at, stub)) else {
  132. return false;
  133. };
  134. if *used + body.len() > STUBS_LEN || (at & 15) + 5 > 16 {
  135. return false;
  136. }
  137. // SAFETY: inside the memory made for it, which nothing runs yet; then the title's code.
  138. unsafe {
  139. std::ptr::copy_nonoverlapping(body.as_ptr(), stub as *mut u8, body.len());
  140. *used += body.len().next_multiple_of(16);
  141. patch(at, [a, b, c, d, e], jump)
  142. }
  143. }
  144. /// The aligned 16 bytes `word` around address `at` with the bytes at `at` replaced; `None`
  145. /// where they do not all lie in those 16. (16 and not 8: the title's busiest one lies over the
  146. /// end of its 8 and took 28,000 exceptions a second, run cpu-6.)
  147. fn with_patch(word: u128, at: usize, patch: &[u8]) -> Option<u128> {
  148. let offset = at & 15;
  149. if offset + patch.len() > 16 {
  150. return None;
  151. }
  152. let mut bytes = word.to_le_bytes();
  153. bytes[offset..offset + patch.len()].copy_from_slice(patch);
  154. Some(u128::from_le_bytes(bytes))
  155. }
  156. /// One thread at a time changes code: a second one would take the first one's loosened
  157. /// protection for the page's own.
  158. static PATCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
  159. /// Replaces the bytes at `at`, which are `was`, by `patch`, in one store that other threads
  160. /// see whole: whether they are replaced now (not where they cross 16 aligned bytes, or the page
  161. /// cannot be written).
  162. ///
  163. /// # Safety
  164. /// `at` is in code that stays mapped, and `patch` does for it what `was` does.
  165. unsafe fn patch<const N: usize>(at: usize, was: [u8; N], patch: [u8; N]) -> bool {
  166. use std::sync::atomic::Ordering::SeqCst;
  167. use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
  168. use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
  169. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  170. if (at & 15) + N > 16 || !std::is_x86_feature_detected!("cmpxchg16b") {
  171. return false;
  172. }
  173. let _one = PATCHING.lock().unwrap_or_else(|e| e.into_inner());
  174. let word = (at & !15) as *mut u128;
  175. let here = (at & 15)..(at & 15) + N;
  176. let mut old = 0u32;
  177. // SAFETY: the aligned 16 bytes around the instruction lie in one page of mapped code, made
  178. // writable for the store and put back; the processor has the instruction (asked above).
  179. unsafe {
  180. if VirtualProtect(word.cast(), 16, PAGE_EXECUTE_READWRITE, &mut old) == 0 {
  181. return false;
  182. }
  183. // What is there (zeros are replaced by zeros).
  184. let mut now = std::arch::x86_64::cmpxchg16b(word, 0, 0, SeqCst, SeqCst);
  185. let done = loop {
  186. let bytes = &now.to_le_bytes()[here.clone()];
  187. if bytes == patch {
  188. // (Another thread's fault at the same place: done already.)
  189. break true;
  190. }
  191. let Some(new) = (bytes == was).then(|| with_patch(now, at, &patch)).flatten() else {
  192. break false;
  193. };
  194. let there = std::arch::x86_64::cmpxchg16b(word, now, new, SeqCst, SeqCst);
  195. if there == now {
  196. break true;
  197. }
  198. now = there;
  199. };
  200. VirtualProtect(word.cast(), 16, old, &mut old);
  201. FlushInstructionCache(GetCurrentProcess(), word.cast(), 16);
  202. done
  203. }
  204. }
  205. /// Diagnostics: how often each place in the title's code raises one of these exceptions, the
  206. /// busiest logged every five seconds.
  207. #[cfg(feature = "diagnostics")]
  208. mod sites {
  209. use super::{AtomicU64, Relaxed};
  210. use std::sync::atomic::AtomicUsize;
  211. /// Address, what is there (an index into [`NAMES`]), exceptions since the last line.
  212. static SITES: [(AtomicUsize, AtomicUsize, AtomicU64); 512] =
  213. [const { (AtomicUsize::new(0), AtomicUsize::new(0), AtomicU64::new(0)) }; 512];
  214. const NAMES: [&str; 8] = ["other", "clwb", "monitorx", "mwaitx", "clzero", "clzero loop", "rdpru", "extrq/insertq"];
  215. static LAST: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);
  216. static PATCHED: AtomicU64 = AtomicU64::new(0);
  217. pub(super) fn patched() {
  218. PATCHED.fetch_add(1, Relaxed);
  219. }
  220. pub(super) fn count(at: usize, what: super::ConsoleOnly) {
  221. use super::ConsoleOnly as C;
  222. let kind = match what {
  223. C::Clwb => 1,
  224. C::Monitorx => 2,
  225. C::Mwaitx => 3,
  226. C::Clzero => 4,
  227. C::ClzeroLoop { .. } => 5,
  228. C::Rdpru => 6,
  229. C::Extrq { .. } | C::Insertq { .. } => 7,
  230. _ => 0,
  231. };
  232. let mut i = (at ^ at >> 9) % SITES.len();
  233. for _ in 0..8 {
  234. let s = &SITES[i];
  235. let there = s.0.compare_exchange(0, at, Relaxed, Relaxed).unwrap_or_else(|there| there);
  236. if there == 0 || there == at {
  237. s.1.store(kind, Relaxed);
  238. s.2.fetch_add(1, Relaxed);
  239. break;
  240. }
  241. i = (i + 1) % SITES.len();
  242. }
  243. // Now and then: is a line due? Never waited for.
  244. if let Ok(mut last) = LAST.try_lock() {
  245. let since = *last.get_or_insert_with(std::time::Instant::now);
  246. if since.elapsed().as_secs() >= 5 {
  247. let s = since.elapsed().as_secs_f64();
  248. *last = Some(std::time::Instant::now());
  249. drop(last);
  250. line(s);
  251. }
  252. }
  253. }
  254. fn line(seconds: f64) {
  255. let mut all: Vec<(u64, usize, usize)> =
  256. SITES.iter().map(|s| (s.2.swap(0, Relaxed), s.0.load(Relaxed), s.1.load(Relaxed))).filter(|s| s.0 > 0).collect();
  257. all.sort_unstable_by_key(|s| std::cmp::Reverse(s.0));
  258. let mut kinds = [0u64; NAMES.len()];
  259. for s in &all {
  260. kinds[s.2] += s.0;
  261. }
  262. let kinds: Vec<String> = NAMES
  263. .iter()
  264. .zip(kinds)
  265. .filter(|(_, n)| *n > 0)
  266. .map(|(name, n)| format!("{name} {:.0}", n as f64 / seconds))
  267. .collect();
  268. let top: Vec<String> =
  269. all.iter().take(8).map(|s| format!("{:#x} {} {:.0}", s.1, NAMES[s.2], s.0 as f64 / seconds)).collect();
  270. tracing::info!(
  271. "console CPU instructions that fault, a second: {}; places replaced so far: {}; the busiest places: {}",
  272. kinds.join(", "),
  273. PATCHED.load(Relaxed),
  274. top.join(", ")
  275. );
  276. }
  277. }
  278. fn readable(va: usize, bytes: usize) -> bool {
  279. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery};
  280. // SAFETY: plain data filled in by the query.
  281. let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  282. // SAFETY: a valid out pointer of the right size.
  283. let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0;
  284. ASKED.fetch_add(1, Relaxed);
  285. found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes
  286. }
  287. fn writable(va: usize, bytes: usize) -> bool {
  288. writable_to(va, va + bytes) == Some(va + bytes)
  289. }
  290. /// Where the committed, writable memory that `va` lies in ends, at most `end`; None if `va`
  291. /// is not in such memory. A region found is remembered ([`remembers`]).
  292. /// shortcut: a remembered region that was freed or protected since is written all the same
  293. /// for up to [`ANSWERS`] answers: the write then faults inside the handler, which the guard
  294. /// on view memory opens as it does any write, and which is a crash otherwise (as the
  295. /// unchecked single-line emulation behind this one already is).
  296. fn writable_to(va: usize, end: usize) -> Option<usize> {
  297. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery};
  298. let remember = remembers();
  299. if remember {
  300. let (regions, answers) = WRITABLE.with(Cell::get);
  301. if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) {
  302. let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) };
  303. WRITABLE.with(|w| w.set(next));
  304. return Some(to.min(end));
  305. }
  306. }
  307. // SAFETY: plain data filled in by the query.
  308. let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  309. // SAFETY: a valid out pointer of the right size.
  310. let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0;
  311. ASKED.fetch_add(1, Relaxed);
  312. if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 {
  313. return None;
  314. }
  315. let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize);
  316. if remember {
  317. WRITABLE.with(|w| {
  318. let (mut regions, answers) = w.get();
  319. regions.rotate_right(1);
  320. regions[0] = (from, to);
  321. w.set((regions, answers));
  322. });
  323. }
  324. Some(to.min(end))
  325. }
  326. /// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over
  327. /// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers
  328. /// see it).
  329. ///
  330. /// # Safety
  331. /// `ctx` is the faulting thread's context, from the exception being dispatched.
  332. pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 {
  333. let rip = ctx.Rip as usize;
  334. // The same few instructions fault again and again: their bytes are asked about once.
  335. let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] };
  336. let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) {
  337. Some(&(_, n)) => n,
  338. None => {
  339. if !readable(rip, 1) {
  340. return 0;
  341. }
  342. let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0);
  343. if remembers() {
  344. let mut known = known;
  345. known.rotate_right(1);
  346. known[0] = (rip, n);
  347. CODE.with(|c| c.set(known));
  348. }
  349. n
  350. }
  351. };
  352. // SAFETY: `n` bytes at `rip` are readable.
  353. let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) };
  354. let Some((what, len)) = decode::decode(code) else { return 0 };
  355. static SEEN: std::sync::Mutex<Vec<std::mem::Discriminant<ConsoleOnly>>> = std::sync::Mutex::new(Vec::new());
  356. if let Ok(mut seen) = SEEN.lock()
  357. && !seen.contains(&std::mem::discriminant(&what))
  358. {
  359. seen.push(std::mem::discriminant(&what));
  360. if what != ConsoleOnly::Ud2 {
  361. tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)");
  362. }
  363. }
  364. #[cfg(feature = "diagnostics")]
  365. if what != ConsoleOnly::Ud2 {
  366. sites::count(rip, what);
  367. }
  368. match what {
  369. ConsoleOnly::Ud2 => return 0,
  370. ConsoleOnly::Clwb => {
  371. // nothing to write back on the PC: patched to NOPs, no exception next time
  372. use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
  373. let mut old = 0u32;
  374. let _one = PATCHING.lock().unwrap_or_else(|e| e.into_inner());
  375. // SAFETY: the instruction's own bytes, made writable for the patch and restored.
  376. unsafe {
  377. if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 {
  378. std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90);
  379. VirtualProtect(rip as *const _, len, old, &mut old);
  380. }
  381. }
  382. }
  383. ConsoleOnly::Monitorx | ConsoleOnly::Mwaitx => {
  384. // Without a prefix, so 3 bytes: replaced, the next pass does not fault.
  385. if len == 3
  386. && patches_waits()
  387. && let Some(new) = wait_patch(what)
  388. // SAFETY: the title's code, where the instruction just faulted; both
  389. // replacements are waits that wait for nothing, as the emulation is.
  390. && unsafe { patch(rip, [code[0], code[1], code[2]], new) }
  391. {
  392. #[cfg(feature = "diagnostics")]
  393. sites::patched();
  394. }
  395. std::hint::spin_loop();
  396. }
  397. ConsoleOnly::Clzero => {
  398. // with an address-size prefix (0x67) the line is at EAX, zero-extended
  399. let a32 = code[..len - 3].contains(&0x67);
  400. let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63;
  401. if !writable(line, 64) {
  402. return 0; // the real instruction faults there too
  403. }
  404. // SAFETY: the 64-byte line is committed and writable.
  405. unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) };
  406. }
  407. ConsoleOnly::ClzeroLoop { end_reg } => {
  408. // the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once
  409. // (and not again: the next time it is plain stores)
  410. if len == 12
  411. && patches_clzero()
  412. // SAFETY: the title's code, where the loop's first instruction just faulted.
  413. && unsafe { patch_clzero(rip, &code[..12]) }
  414. {
  415. #[cfg(feature = "diagnostics")]
  416. sites::patched();
  417. }
  418. let regs: [u64; 16] = [
  419. 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,
  420. ];
  421. let end = regs[end_reg as usize & 15] as usize;
  422. let start = ctx.Rax as usize;
  423. // A pass zeroes the whole line `rax` is in, wherever in it, and the test comes
  424. // after it: lines are zeroed past an `end` inside one, and one is for an `end`
  425. // not above the start. (The bytes from `start` to `end` were, `rax` came out as
  426. // `end`, and the flags stayed what they were.)
  427. const MOST: usize = (2 << 30) / 64;
  428. let wanted = if end > start { (end - start).div_ceil(64) } else { 1 };
  429. let passes = wanted.min(MOST);
  430. let first = start & !63;
  431. let Some(stop) = first.checked_add(passes * 64) else { return 0 };
  432. // Region by region: a block may lie across several (the title's pages are
  433. // mapped one view each), and one answer for all of it was a refusal, after
  434. // which every 64-byte line took an exception of its own.
  435. let mut at = first;
  436. while at < stop {
  437. let Some(to) = writable_to(at, stop) else { break };
  438. // SAFETY: committed and writable from `at` to `to`.
  439. unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) };
  440. at = to;
  441. }
  442. let done = (at - first) / 64;
  443. if done == 0 {
  444. return 0;
  445. }
  446. ZEROED.fetch_add((done * 64) as u64, Relaxed);
  447. ctx.Rax = ctx.Rax.wrapping_add((done * 64) as u64);
  448. if done < wanted {
  449. // What follows is not writable (or the block is huge): the loop goes on
  450. // there (the same instruction again), where the real one faults too.
  451. return CONTINUE_EXECUTION;
  452. }
  453. ctx.EFlags = ctx.EFlags & !crate::crash::CMP_FLAGS | crate::crash::cmp_flags(ctx.Rax, end as u64);
  454. }
  455. ConsoleOnly::Rdpru => {
  456. let mut v = 0i64;
  457. // SAFETY: a valid out pointer.
  458. unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) };
  459. let v = if ctx.Rcx as u32 <= 1 { v as u64 } else { 0 };
  460. ctx.Rax = v & 0xFFFF_FFFF;
  461. ctx.Rdx = v >> 32;
  462. }
  463. ConsoleOnly::Rdpid(r) => {
  464. // SAFETY: no preconditions.
  465. let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64;
  466. let regs: [&mut u64; 16] = [
  467. &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,
  468. &mut ctx.R14, &mut ctx.R15,
  469. ];
  470. *regs[r as usize & 15] = cpu;
  471. }
  472. // the low quadword changes; the high one is zeroed, as a Zen 5 does
  473. ConsoleOnly::Extrq { dst, src, len, idx } => {
  474. // SAFETY: the context's XMM registers (CONTEXT_FLOATING_POINT is captured for exceptions).
  475. let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters };
  476. let (len, idx) = match src {
  477. Some(s) => {
  478. let c = x[s as usize & 15].Low;
  479. (c as u8, (c >> 8) as u8)
  480. }
  481. None => (len, idx),
  482. };
  483. let d = &mut x[dst as usize & 15];
  484. d.Low = decode::extrq(d.Low, len, idx);
  485. d.High = 0;
  486. }
  487. ConsoleOnly::Insertq { dst, src, reg, len, idx } => {
  488. // SAFETY: as above.
  489. let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters };
  490. let s = x[src as usize & 15];
  491. let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) };
  492. let d = &mut x[dst as usize & 15];
  493. d.Low = decode::insertq(d.Low, s.Low, len, idx);
  494. d.High = 0;
  495. }
  496. }
  497. ctx.Rip += len as u64;
  498. // How often this runs at all (each one is an exception: a trip into Windows and back).
  499. let emulated = EMULATED.fetch_add(1, Relaxed) + 1;
  500. if emulated >= 1 << 16 && emulated.is_power_of_two() {
  501. tracing::info!(
  502. emulated,
  503. asked = ASKED.load(Relaxed),
  504. zeroed_mb = ZEROED.load(Relaxed) >> 20,
  505. "console CPU instructions emulated so far, the times Windows was asked about memory for them, and what clzero loops zeroed"
  506. );
  507. }
  508. CONTINUE_EXECUTION
  509. }
  510. #[cfg(test)]
  511. mod tests {
  512. use super::*;
  513. #[test]
  514. fn wait_instructions_are_replaced_inside_sixteen_aligned_bytes() {
  515. let word = u128::from_le_bytes([1, 2, 3, 4, 5, 6, 7, 0x0f, 0x01, 0xfb, 11, 12, 13, 14, 15, 16]);
  516. let new = with_patch(word, 0x1007, &[0xf3, 0x90, 0x90]).unwrap();
  517. assert_eq!(new.to_le_bytes(), [1, 2, 3, 4, 5, 6, 7, 0xf3, 0x90, 0x90, 11, 12, 13, 14, 15, 16]);
  518. assert!(with_patch(word, 0x100d, &[0; 3]).is_some());
  519. assert!(with_patch(word, 0x100e, &[0; 3]).is_none(), "crosses into the next sixteen");
  520. }
  521. /// `monitorx; mwaitx; ret` in a page of its own: each is replaced at its first fault,
  522. /// and the page is protected as before.
  523. #[test]
  524. fn a_wait_faults_once_and_the_page_keeps_its_protection() {
  525. use windows_sys::Win32::System::Memory::{
  526. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc, VirtualFree,
  527. VirtualProtect, VirtualQuery,
  528. };
  529. // SAFETY: memory of our own, read, written and run within its page.
  530. unsafe {
  531. let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE).cast::<u8>();
  532. assert!(!page.is_null());
  533. let code = [0x0f, 0x01, 0xfa, 0x0f, 0x01, 0xfb, 0xc3];
  534. // The first over the end of its aligned eight bytes, as the title's is; and one
  535. // over the end of its sixteen (at 46), which is left alone.
  536. std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(6), code.len());
  537. std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(46), code.len());
  538. let mut old = 0;
  539. assert_ne!(VirtualProtect(page.cast(), 4096, PAGE_EXECUTE_READ, &mut old), 0);
  540. let at = page as usize;
  541. let mut context: CONTEXT = std::mem::zeroed();
  542. for rip in [at + 6, at + 9, at + 46] {
  543. context.Rip = rip as u64;
  544. assert_eq!(emulate(&mut context), CONTINUE_EXECUTION);
  545. assert_eq!(context.Rip, rip as u64 + 3);
  546. }
  547. if patches_waits() {
  548. let now = std::slice::from_raw_parts(page.add(6), 7);
  549. assert_eq!(now, [0x0f, 0x1f, 0x00, 0xf3, 0x90, 0x90, 0xc3]);
  550. // They run now.
  551. let run: extern "system" fn() = std::mem::transmute(page.add(6));
  552. run();
  553. // A second thread that faulted at the same place meanwhile.
  554. assert!(patch(at + 6, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]));
  555. assert!(!patch(at + 46, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]), "crosses its sixteen bytes");
  556. }
  557. assert_eq!(std::slice::from_raw_parts(page.add(46), 3), [0x0f, 0x01, 0xfa]);
  558. let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
  559. VirtualQuery(page.cast(), &mut m, size_of_val(&m));
  560. assert_eq!(m.Protect, PAGE_EXECUTE_READ);
  561. VirtualFree(page.cast(), 0, MEM_RELEASE);
  562. }
  563. }
  564. /// `clzero` loops run as plain stores: the lines they name are zero and no other byte,
  565. /// and the pointer, the scratch register and the flags come out as from the loop.
  566. #[test]
  567. fn a_clzero_loop_becomes_plain_stores() {
  568. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc, VirtualFree};
  569. // Against rdx (rm rax, reg rdx) and against rcx, the scratch register.
  570. for (cmp, by) in [([0x48, 0x39, 0xd0], 2), ([0x48, 0x39, 0xc8], 1), ([0x4c, 0x39, 0xc0], 8)] {
  571. // SAFETY: memory of our own, written and run inside it.
  572. unsafe {
  573. let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize;
  574. assert_ne!(page, 0);
  575. // A function of (start, end): the start in rax, the end in its register, the
  576. // loop at 16, and what rax became.
  577. let mut head = vec![0x48, 0x89, 0xc8]; // mov rax, rcx
  578. match by {
  579. 1 => head.extend([0x48, 0x89, 0xd1]), // mov rcx, rdx
  580. 8 => head.extend([0x49, 0x89, 0xd0]), // mov r8, rdx
  581. _ => {}
  582. }
  583. head.resize(16, 0x90);
  584. let mut code = head;
  585. code.extend([0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40]);
  586. code.extend(cmp);
  587. code.extend([0x72, 0xf4]);
  588. code.push(0xc3);
  589. std::ptr::copy_nonoverlapping(code.as_ptr(), page as *mut u8, code.len());
  590. let mut context: CONTEXT = std::mem::zeroed();
  591. let mut block = vec![0xaau8; 64 * 8 + 64];
  592. let base = block.as_mut_ptr() as usize;
  593. let first = base.next_multiple_of(64);
  594. // The fault itself: emulated whole, and replaced.
  595. context.Rip = page as u64 + 16;
  596. context.Rax = first as u64;
  597. context.Rdx = first as u64 + 128;
  598. context.Rcx = context.Rdx;
  599. context.R8 = context.Rdx;
  600. assert_eq!(emulate(&mut context), CONTINUE_EXECUTION);
  601. assert_eq!((context.Rip, context.Rax), (page as u64 + 28, first as u64 + 128));
  602. if patches_clzero() {
  603. assert_eq!(*((page + 16) as *const u8), 0xe9, "a jump");
  604. block.fill(0xaa);
  605. let run: extern "system" fn(usize, usize) -> usize = std::mem::transmute(page);
  606. // From inside a line to inside the third: whole lines, one past the end.
  607. assert_eq!(run(first + 8, first + 130), first + 8 + 128);
  608. let at = first - base;
  609. assert!(block[at..at + 128].iter().all(|&b| b == 0));
  610. assert!(block[..at].iter().chain(&block[at + 128..]).all(|&b| b == 0xaa));
  611. // An end at the start: one line.
  612. block.fill(0xaa);
  613. assert_eq!(run(first, first), first + 64);
  614. assert!(block[at..at + 64].iter().all(|&b| b == 0) && block[at + 64] == 0xaa);
  615. }
  616. VirtualFree(page as *mut _, 0, MEM_RELEASE);
  617. }
  618. }
  619. assert!(clzero_stub(0x1000, 0x2000, [0x48, 0x39, 0xc0]).is_none(), "against rax itself");
  620. assert!(jump(0x1000, 0x9000_0000_0000).is_none(), "out of reach");
  621. }
  622. }