crash.rs 60 KB

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