titlewrite.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. //! The title's writes into guarded view memory that do not go through a
  2. //! fault that opens the block (`crate::watch`): its bytes are put in through
  3. //! our own view of the same pages (`crate::inplace`), which no guard covers,
  4. //! and the block is told as written (`crate::watch::put_beside`). The block
  5. //! stays read-only, so neither this write nor the block's next taking changes
  6. //! a protection.
  7. //!
  8. //! A change of protection is some 5 us in the game's process, one at a time
  9. //! whoever asks; a frame had 590 write faults, and made as many blocks
  10. //! read-only again (run faults-1). What faults is, by the time spent in it,
  11. //! for a third the title's `memcpy`, and for most of the rest single stores
  12. //! into objects that lie in memory some buffer's copy covers: a flag, a
  13. //! reference count, the link of a free list.
  14. //!
  15. //! - [`import`]: the title's `memcpy`, `memmove` and `memset` are ours
  16. //! (`VICTORY_COPY_BESIDE=1`; off unless asked for). They look at the bits
  17. //! of the blocks they write and go to the runtime's own, but for the parts
  18. //! that lie in guarded blocks.
  19. //! - [`store`]: a store that faults is done here, and the thread goes on
  20. //! behind it (`VICTORY_STORE_BESIDE=1`; off unless asked for). Nothing of
  21. //! the title's code is known ahead: the instruction is read where it
  22. //! faulted, and one that is not understood opens the block as before. So
  23. //! does a block's fifth store since it was taken, and one at a place in the
  24. //! code most of whose blocks come to that ([`SITES`]): code that fills a
  25. //! block would fault at every store.
  26. mod decode;
  27. use crate::watch::Beside;
  28. use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed};
  29. /// Diagnostics, since the start: copies of the title's that put bytes beside
  30. /// the guards, blocks they did so in, blocks they opened instead; stores done
  31. /// beside the guards, faulting stores not understood, and blocks opened
  32. /// because too many came; stores and parts of copies that left the memory as
  33. /// it was, and were not made.
  34. pub(crate) static DONE: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8];
  35. fn add(what: usize) {
  36. DONE[what].fetch_add(1, Relaxed);
  37. }
  38. /// A switch that is off unless its variable is `1` (or `VICTORY_AB` names it:
  39. /// on and off while the title runs).
  40. macro_rules! asked_for {
  41. ($name:literal) => {{
  42. static ASKED: std::sync::OnceLock<Result<bool, u32>> = std::sync::OnceLock::new();
  43. let asked = ASKED.get_or_init(|| {
  44. #[cfg(feature = "diagnostics")]
  45. if let Some(bit) = crate::ab::bit($name) {
  46. return Err(bit);
  47. }
  48. Ok(std::env::var_os($name).is_some_and(|v| v == "1"))
  49. });
  50. match *asked {
  51. Ok(on) => on,
  52. #[cfg(feature = "diagnostics")]
  53. Err(bit) => crate::ab::on(bit),
  54. #[cfg(not(feature = "diagnostics"))]
  55. Err(_) => false,
  56. }
  57. }};
  58. }
  59. fn copies_on() -> bool {
  60. #[cfg(test)]
  61. if ON_IN_TEST.get() {
  62. return true;
  63. }
  64. asked_for!("VICTORY_COPY_BESIDE")
  65. }
  66. fn stores_on() -> bool {
  67. #[cfg(test)]
  68. if ON_IN_TEST.get() {
  69. return true;
  70. }
  71. asked_for!("VICTORY_STORE_BESIDE")
  72. }
  73. #[cfg(test)]
  74. thread_local! {
  75. /// Both, for this thread's writes.
  76. pub(crate) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  77. }
  78. /// The runtime's own `memcpy`, `memmove` and `memset`.
  79. static REAL: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3];
  80. type Copy = unsafe extern "system-unwind" fn(*mut u8, *const u8, usize) -> *mut u8;
  81. type Set = unsafe extern "system-unwind" fn(*mut u8, i32, usize) -> *mut u8;
  82. /// What the title's import of `name`, which the host has at `address`, is
  83. /// bound to.
  84. pub fn import(name: &str, address: usize) -> usize {
  85. let (which, ours) = match name {
  86. "memcpy" => (0, copy as *const () as usize),
  87. "memmove" => (1, shift as *const () as usize),
  88. "memset" => (2, set as *const () as usize),
  89. _ => return address,
  90. };
  91. #[cfg(feature = "diagnostics")]
  92. let on = crate::ab::bit("VICTORY_COPY_BESIDE").is_some() || copies_on();
  93. #[cfg(not(feature = "diagnostics"))]
  94. let on = copies_on();
  95. if !on {
  96. return address;
  97. }
  98. REAL[which].store(address, Relaxed);
  99. ours
  100. }
  101. #[cfg(test)]
  102. pub(crate) fn copy_for_test(real: usize) -> usize {
  103. REAL[0].store(real, Relaxed);
  104. copy as *const () as usize
  105. }
  106. /// The most a block takes of copies beside its guard before it is opened; a
  107. /// store counts as [`A_STORE`].
  108. pub(crate) const MOST: u32 = 32;
  109. const A_STORE: u32 = 8;
  110. unsafe extern "system-unwind" fn copy(to: *mut u8, from: *const u8, n: usize) -> *mut u8 {
  111. // SAFETY: the title's copy, as it asked for it, by the function it asked.
  112. unsafe { copied(to, from, n, REAL[0].load(Relaxed)) }
  113. }
  114. unsafe extern "system-unwind" fn shift(to: *mut u8, from: *const u8, n: usize) -> *mut u8 {
  115. // SAFETY: as above.
  116. unsafe { copied(to, from, n, REAL[1].load(Relaxed)) }
  117. }
  118. /// # Safety
  119. /// `real` copies as `memcpy` (or `memmove`) does, `to`, `from` and `n` are
  120. /// the title's.
  121. #[inline]
  122. unsafe fn copied(to: *mut u8, from: *const u8, n: usize, real: usize) -> *mut u8 {
  123. // SAFETY: the host's function, noted by `import` before the title ran.
  124. let real: Copy = unsafe { std::mem::transmute(real) };
  125. if n == 0 || !crate::watch::guards_any(to as usize, n) || !copies_on() || overlap(to as usize, from as usize, n) {
  126. // SAFETY: by the caller.
  127. return unsafe { real(to, from, n) };
  128. }
  129. let same = |at: usize, offset: usize, len: usize| {
  130. // SAFETY: both are the title's, the one read-only by our hand, the other read by it next.
  131. unsafe { std::slice::from_raw_parts(at as *const u8, len) == std::slice::from_raw_parts(from.add(offset), len) }
  132. };
  133. in_pieces(to as usize, n, same, |at, offset, len| {
  134. // SAFETY: a part of what the title asked for; or the same bytes at
  135. // our view of the pages.
  136. unsafe { real(at as *mut u8, from.add(offset), len) };
  137. });
  138. to
  139. }
  140. unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u8 {
  141. // SAFETY: as in `copied`.
  142. let real: Set = unsafe { std::mem::transmute(REAL[2].load(Relaxed)) };
  143. if n == 0 || !crate::watch::guards_any(to as usize, n) || !copies_on() {
  144. // SAFETY: the title's, as it asked for it.
  145. return unsafe { real(to, byte, n) };
  146. }
  147. let same = |at: usize, _: usize, len: usize| {
  148. // SAFETY: the title's, read-only by our hand.
  149. unsafe { std::slice::from_raw_parts(at as *const u8, len) }.iter().all(|&there| there == byte as u8)
  150. };
  151. in_pieces(to as usize, n, same, |at, _, len| {
  152. // SAFETY: as in `copied`.
  153. unsafe { real(at as *mut u8, byte, len) };
  154. });
  155. to
  156. }
  157. /// Whether the two ranges meet, if only in a block (of which only one might
  158. /// be written at another address).
  159. fn overlap(to: usize, from: usize, n: usize) -> bool {
  160. const BLOCK: usize = crate::watch::PAGE;
  161. let (first, last) = (to / BLOCK * BLOCK, to.saturating_add(n).next_multiple_of(BLOCK));
  162. from < last && first < from.saturating_add(n)
  163. }
  164. /// Does `[to, to + n)` block by block: `put(at, offset, len)` with the
  165. /// address to write at, the title's or ours.
  166. ///
  167. /// What is there already (`same`, of a part in one guarded block) is not
  168. /// written.
  169. fn in_pieces(to: usize, n: usize, same: impl Fn(usize, usize, usize) -> bool, put: impl Fn(usize, usize, usize)) {
  170. const BLOCK: usize = crate::watch::PAGE;
  171. add(0);
  172. let mut offset = 0;
  173. while offset < n {
  174. let at = to + offset;
  175. let len = (BLOCK - at % BLOCK).min(n - offset);
  176. if crate::watch::guards_any(at, len) {
  177. if same(at, offset, len) {
  178. add(7);
  179. offset += len;
  180. continue;
  181. }
  182. match crate::watch::put_beside(at / BLOCK, 1, |delta| put(at.wrapping_add(delta), offset, len)) {
  183. Beside::Done => {
  184. add(1);
  185. offset += len;
  186. continue;
  187. }
  188. // Opened with no fault: the next copies here are plain ones.
  189. _ => crate::watch::opened_for_writing(at),
  190. }
  191. add(2);
  192. }
  193. put(at, offset, len);
  194. offset += len;
  195. }
  196. }
  197. /// Places of the title's code whose stores faulted, by a hash of the address:
  198. /// the stores done beside the guards (the low half) and the blocks that had
  199. /// too many of them (the high half).
  200. static SITES: [AtomicU64; 1 << 10] = [const { AtomicU64::new(0) }; 1 << 10];
  201. fn site(rip: usize) -> &'static AtomicU64 {
  202. &SITES[(rip as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize >> 54 & 1023]
  203. }
  204. /// Whether a site's stores come one to a block, as far as is known.
  205. fn sparse(counts: u64) -> bool {
  206. let (done, full) = (counts & 0xffff_ffff, counts >> 32);
  207. full < 4 || full * 12 < done
  208. }
  209. /// Faulting stores by their place in the title's code: the place, and how
  210. /// many left the memory as it was (the low half) or did not (the high one).
  211. static LEARNED: [(AtomicUsize, AtomicU64); 1 << 9] = [const { (AtomicUsize::new(0), AtomicU64::new(0)) }; 1 << 9];
  212. /// A store at `rip` would leave the memory as it is, or not. With
  213. /// `VICTORY_WRITE_SITES=<file>`, a place that can be made to look first
  214. /// (`can_look`) and mostly left it is written into that file, for the next
  215. /// start (`victory_loader::write_sites`).
  216. fn learn(rip: usize, same: bool, can_look: bool) {
  217. let slot = &LEARNED[(rip as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize >> 55 & 511];
  218. let there = slot.0.compare_exchange(0, rip, Relaxed, Relaxed).unwrap_or_else(|there| there);
  219. if there != 0 && there != rip {
  220. return;
  221. }
  222. let counts = slot.1.fetch_add(if same { 1 } else { 1 << 32 }, Relaxed);
  223. let (stayed, changed) = (counts & 0xffff_ffff, counts >> 32);
  224. if !same || !can_look || stayed != 256 || changed * 4 > stayed {
  225. return;
  226. }
  227. let Some(file) = std::env::var_os("VICTORY_WRITE_SITES") else {
  228. return;
  229. };
  230. // (Not here, under a fault of the title's.)
  231. std::thread::spawn(move || {
  232. let Some((image, offset)) = place(rip) else {
  233. return;
  234. };
  235. use std::io::Write;
  236. let line = format!("{image} {offset:x} or\n");
  237. let known = std::fs::read_to_string(&file).unwrap_or_default();
  238. if known.lines().any(|l| l == line.trim_end()) {
  239. return;
  240. }
  241. if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(&file) {
  242. let _ = file.write_all(line.as_bytes());
  243. }
  244. tracing::info!(image, offset = format_args!("{offset:#x}"), stayed, changed, "a write of the title's that mostly changes nothing, noted");
  245. });
  246. }
  247. /// The file name of the image `address` is in, and where in it.
  248. fn place(address: usize) -> Option<(String, usize)> {
  249. use windows_sys::Win32::System::LibraryLoader::{
  250. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, GetModuleHandleExW,
  251. };
  252. const FLAGS: u32 = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
  253. let mut module = std::ptr::null_mut();
  254. let mut name = [0u16; 1024];
  255. // SAFETY: an address, and room for the answers.
  256. let n = unsafe {
  257. if GetModuleHandleExW(FLAGS, address as *const u16, &mut module) == 0 {
  258. return None;
  259. }
  260. GetModuleFileNameW(module, name.as_mut_ptr(), name.len() as u32)
  261. } as usize;
  262. let path = String::from_utf16_lossy(&name[..n]);
  263. let file = path.rsplit(['\\', '/']).next()?.to_owned();
  264. (!file.is_empty()).then(|| (file, address - module as usize))
  265. }
  266. /// The places with the most faulting stores, for the log: offset in its
  267. /// image, how many left the memory as it was, how many did not.
  268. #[cfg(feature = "diagnostics")]
  269. pub(crate) fn busiest() -> String {
  270. let mut all: Vec<(u64, u64, usize)> = LEARNED
  271. .iter()
  272. .map(|(rip, counts)| (counts.load(Relaxed), rip.load(Relaxed)))
  273. .filter(|s| s.1 != 0)
  274. .map(|(counts, rip)| (counts & 0xffff_ffff, counts >> 32, rip))
  275. .collect();
  276. all.sort_unstable_by_key(|s| std::cmp::Reverse(s.0 + s.1));
  277. let of = |&(stayed, changed, rip): &(u64, u64, usize)| {
  278. let (image, offset) = place(rip).unwrap_or_default();
  279. format!("{}+{offset:x} {stayed}/{changed}", image.chars().skip(14).take(4).collect::<String>())
  280. };
  281. all.iter().take(16).map(of).collect::<Vec<_>>().join(", ")
  282. }
  283. /// Does the store that faulted at `at`, a byte of a guarded block, beside the
  284. /// guards; `false` if it is to open the block (and nothing was done).
  285. pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, at: usize) -> bool {
  286. if !stores_on() {
  287. return false;
  288. }
  289. let rip = context.Rip as usize;
  290. let site = site(rip);
  291. let counts = site.load(Relaxed);
  292. let mut code = [0u8; 15];
  293. // (To the end of the page if the next is not there.)
  294. let left = 4096 - rip % 4096;
  295. let there = crate::host::read_into(rip as *const u8, &mut code) || {
  296. let n = left.min(15);
  297. n < 15 && crate::host::read_into(rip as *const u8, &mut code[..n])
  298. };
  299. let Some(store) = there.then(|| decode::store(&code, context)).flatten() else {
  300. add(4);
  301. return false;
  302. };
  303. const BLOCK: usize = crate::watch::PAGE;
  304. let end = store.at.wrapping_add(store.size);
  305. if !(store.at..end).contains(&at) || store.at / BLOCK != (end - 1) / BLOCK {
  306. add(4);
  307. return false;
  308. }
  309. // SAFETY: a guarded block's, which can be read.
  310. if let Some((same, flags)) = unsafe { store.same(context) } {
  311. learn(rip, same, store.can_look(&code));
  312. if same && crate::watch::nothing_put(store.at / BLOCK) {
  313. context.EFlags = flags;
  314. context.Rip += store.len as u64;
  315. add(6);
  316. return true;
  317. }
  318. }
  319. if !sparse(counts) {
  320. // Looked at anew some time.
  321. if site.fetch_add(1 << 32, Relaxed) >> 32 > 4096 {
  322. site.store(0, Relaxed);
  323. }
  324. return false;
  325. }
  326. let mut done = false;
  327. let put = crate::watch::put_beside(store.at / BLOCK, A_STORE, |delta| {
  328. // SAFETY: the bytes the title is storing to, at our view of them.
  329. done = unsafe { store.run(context, store.at.wrapping_add(delta)) };
  330. });
  331. if put != Beside::Done {
  332. if put == Beside::Full {
  333. site.fetch_add(1 << 32, Relaxed);
  334. add(5);
  335. }
  336. return false;
  337. }
  338. if !done {
  339. // (A locked one that is not aligned: told as written for nothing.)
  340. add(4);
  341. return false;
  342. }
  343. context.Rip += store.len as u64;
  344. site.fetch_add(1, Relaxed);
  345. add(3);
  346. #[cfg(feature = "diagnostics")]
  347. crate::faultbook::note(crate::faultbook::What::Stored, rip, at / BLOCK, 0);
  348. true
  349. }
  350. #[cfg(test)]
  351. mod tests {
  352. use super::*;
  353. #[test]
  354. fn sites_that_fill_blocks_are_told_from_others() {
  355. assert!(sparse(0) && sparse(1000) && sparse(3 << 32));
  356. assert!(!sparse(4 << 32 | 16) && sparse(4 << 32 | 60));
  357. }
  358. #[test]
  359. fn copies_that_meet_are_left_to_the_runtime() {
  360. const B: usize = crate::watch::PAGE;
  361. assert!(overlap(10 * B + 5, 10 * B + 900, 8), "in one block");
  362. assert!(!overlap(10 * B + 5, 12 * B, 8) && !overlap(10 * B, 9 * B, B));
  363. assert!(overlap(10 * B, 9 * B, B + 1));
  364. }
  365. }