crash.rs 57 KB

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