console_insn_decode.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. //! Instructions the console's CPU (Zen 2) has and a PC's may lack – a title raises
  2. //! STATUS_ILLEGAL_INSTRUCTION on them on an Intel CPU before Ice Lake / Alder Lake (CLWB,
  3. //! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ,
  4. //! which are AMD's). The exception handler (`eh`) emulates the ones decoded here and steps over
  5. //! them.
  6. /// A console-only instruction at the faulting address.
  7. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  8. pub enum ConsoleOnly {
  9. /// `clwb m8`: write a cache line back – nothing to do, the PC's memory is coherent
  10. Clwb,
  11. /// `clzero`: zero the 64-byte cache line at rAX
  12. Clzero,
  13. /// `clzero` loop: `clzero; add rax, 0x40; cmp rax, <reg>; jb -12` – zero `[rax..reg)`
  14. ClzeroLoop { end_reg: u8 },
  15. /// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter)
  16. Rdpru,
  17. /// `monitorx` / `mwaitx`: a wait the emulation skips
  18. Monitorx,
  19. Mwaitx,
  20. /// `rdpid r64`: TSC_AUX (the processor number) into the register (CONTEXT order: rax, rcx,
  21. /// rdx, rbx, rsp, rbp, rsi, rdi, r8..r15)
  22. Rdpid(u8),
  23. /// SSE4a `extrq xmm, imm8 (length), imm8 (index)` / `extrq xmm1, xmm2` (`src` Some: the
  24. /// length and index in xmm2's bits 5:0 and 13:8): a bit field of the low quadword, moved
  25. /// down and zero-extended (the high quadword zeroed). Registers are XMM numbers 0..15.
  26. Extrq { dst: u8, src: Option<u8>, len: u8, idx: u8 },
  27. /// SSE4a `insertq xmm1, xmm2, imm8 (length), imm8 (index)` / `insertq xmm1, xmm2` (`reg`:
  28. /// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a
  29. /// bit field of xmm1's low quadword.
  30. Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 },
  31. /// `ud2`: the title's own trap (not emulated)
  32. Ud2,
  33. }
  34. /// A field length of SSE4a's six bits: 0 is 64.
  35. fn field_len(len: u8) -> u32 {
  36. match len & 63 {
  37. 0 => 64,
  38. n => n as u32,
  39. }
  40. }
  41. /// EXTRQ on a low quadword: `len` bits from bit `idx`, zero-extended (a field past bit 63 is
  42. /// undefined on the console; here it is what a shift gives).
  43. pub fn extrq(v: u64, len: u8, idx: u8) -> u64 {
  44. let (len, idx) = (field_len(len), (idx & 63) as u32);
  45. let field = v.checked_shr(idx).unwrap_or(0);
  46. if len >= 64 {
  47. field
  48. } else {
  49. field & ((1u64 << len) - 1)
  50. }
  51. }
  52. /// INSERTQ on a low quadword: the low `len` bits of `src` put at bit `idx` of `dst`.
  53. pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 {
  54. let (len, idx) = (field_len(len), (idx & 63) as u32);
  55. let ones = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 };
  56. let mask = ones.checked_shl(idx).unwrap_or(0);
  57. (dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask)
  58. }
  59. /// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the
  60. /// bytes run out.
  61. fn modrm_len(b: &[u8]) -> Option<usize> {
  62. let modrm = *b.first()?;
  63. let (md, rm) = (modrm >> 6, modrm & 7);
  64. if md == 3 {
  65. return Some(1);
  66. }
  67. let mut len = 1;
  68. let mut base = rm;
  69. if rm == 4 {
  70. base = *b.get(1)? & 7;
  71. len += 1;
  72. }
  73. len += match md {
  74. 0 if base == 5 => 4, // disp32 (rip-relative, or a SIB without a base)
  75. 0 => 0,
  76. 1 => 1,
  77. _ => 4,
  78. };
  79. (b.len() >= len).then_some(len)
  80. }
  81. /// The console-only instruction at the start of `code` and its length.
  82. pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> {
  83. let mut i = 0;
  84. // `rep`: the last of F2 / F3, which decides between them (and over 66) for SSE4a
  85. let (mut p66, mut pf3, mut rep, mut rex) = (false, false, 0u8, 0u8);
  86. while let Some(&b) = code.get(i) {
  87. match b {
  88. 0x66 => p66 = true,
  89. 0xF2 => rep = 0xF2,
  90. 0xF3 => {
  91. pf3 = true;
  92. rep = 0xF3;
  93. }
  94. 0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {}
  95. // REX counts only right before the opcode: one before a legacy prefix is ignored
  96. 0x40..=0x4F => {
  97. rex = b;
  98. i += 1;
  99. continue;
  100. }
  101. _ => break,
  102. }
  103. rex = 0;
  104. i += 1;
  105. }
  106. if *code.get(i)? != 0x0F {
  107. return None;
  108. }
  109. match (*code.get(i + 1)?, code.get(i + 2).copied()) {
  110. (0x01, Some(0xFC)) => {
  111. // clzero (0F 01 FC); add rax, 0x40 (48 83 C0 40); cmp rax, <reg> ([48|4C] 39 modrm); jb -12 (72 F4)
  112. // (not after an 0x67: that CLZERO is at EAX, and the jb goes back to the 0F, past the
  113. // prefix – it is stepped alone, the loop is taken from the next one)
  114. if code.len() >= i + 12
  115. && !code[..i].contains(&0x67)
  116. && code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40]
  117. && (code[i + 7] == 0x48 || code[i + 7] == 0x4C)
  118. && code[i + 8] == 0x39
  119. && code[i + 10..i + 12] == [0x72, 0xF4]
  120. {
  121. let rex_r = code[i + 7] == 0x4C;
  122. let modrm = code[i + 9];
  123. let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 };
  124. Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12))
  125. } else {
  126. Some((ConsoleOnly::Clzero, i + 3))
  127. }
  128. }
  129. (0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)),
  130. (0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)),
  131. (0x01, Some(0xFB)) => Some((ConsoleOnly::Mwaitx, i + 3)),
  132. (0x0B, _) => Some((ConsoleOnly::Ud2, i + 2)),
  133. // SSE4a: register operands only (ModRM mod 3); REX.R extends reg, REX.B rm
  134. // (the last of F2 / F3 decides: F2 INSERTQ, F3 #UD; neither with 66: EXTRQ)
  135. (0x78 | 0x79, Some(m)) if (rep == 0xF2 || (rep == 0 && p66)) && m >> 6 == 3 => {
  136. let reg = ((m >> 3) & 7) | (rex & 4) << 1;
  137. let rm = (m & 7) | (rex & 1) << 3;
  138. let imm = |k: usize| code.get(i + 3 + k).copied();
  139. match (code[i + 1], rep == 0xF2) {
  140. // extrq xmm(rm), imm8, imm8 – the ModRM reg field is /0
  141. (0x78, false) if (m >> 3) & 7 == 0 => Some((ConsoleOnly::Extrq { dst: rm, src: None, len: imm(0)?, idx: imm(1)? }, i + 5)),
  142. (0x79, false) => Some((ConsoleOnly::Extrq { dst: reg, src: Some(rm), len: 0, idx: 0 }, i + 3)),
  143. (0x78, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: false, len: imm(0)?, idx: imm(1)? }, i + 5)),
  144. (0x79, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: true, len: 0, idx: 0 }, i + 3)),
  145. _ => None,
  146. }
  147. }
  148. // 66 0F AE /6 with a memory operand (without 66 it is xsaveopt)
  149. (0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)),
  150. // F3 0F C7 /7 with a register operand
  151. (0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)),
  152. _ => None,
  153. }
  154. }
  155. #[cfg(test)]
  156. mod tests {
  157. use super::*;
  158. /// EXTRQ / INSERTQ as AMD's manual gives them: a length of 0 is 64.
  159. #[test]
  160. fn sse4a_bit_fields() {
  161. assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 8, 16), 0xBC);
  162. assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 0, 0), 0x1234_5678_9ABC_DEF0);
  163. assert_eq!(extrq(0x8000_0000_0000_0000, 1, 63), 1);
  164. assert_eq!(insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), 0xFFFF_FFFF_FFFF_ABFF);
  165. assert_eq!(insertq(0, 0x1FF, 4, 60), 0xF000_0000_0000_0000);
  166. assert_eq!(insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), 0xDEAD_BEEF_0000_0000);
  167. for (v, len, idx) in [(0x0123_4567_89AB_CDEFu64, 12u8, 20u8), (u64::MAX, 63, 1), (0x55, 3, 0)] {
  168. assert_eq!(extrq(insertq(0, v, len, idx), len, idx), extrq(v, len, 0));
  169. }
  170. }
  171. #[test]
  172. fn decodes_the_console_only_instructions() {
  173. assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3)));
  174. // clzero loop against r10 (4C 39 D0 = cmp rax, r10)
  175. assert_eq!(
  176. decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4]),
  177. Some((ConsoleOnly::ClzeroLoop { end_reg: 10 }, 12))
  178. );
  179. // clzero loop against rdx (48 39 D0 = cmp rax, rdx)
  180. assert_eq!(
  181. decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]),
  182. Some((ConsoleOnly::ClzeroLoop { end_reg: 2 }, 12))
  183. );
  184. // the same loop after an address-size prefix: that one CLZERO alone
  185. assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4)));
  186. assert_eq!(decode(&[0x0F, 0x01, 0xFD]), Some((ConsoleOnly::Rdpru, 3)));
  187. assert_eq!(decode(&[0x0F, 0x01, 0xFA]), Some((ConsoleOnly::Monitorx, 3)));
  188. assert_eq!(decode(&[0x0F, 0x01, 0xFB]), Some((ConsoleOnly::Mwaitx, 3)));
  189. assert_eq!(decode(&[0x0F, 0x0B]), Some((ConsoleOnly::Ud2, 2)));
  190. // clwb [rax]; clwb [rcx+0x40]; clwb [rsp+8]; clwb [rip+disp32]; clwb [r8]
  191. assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 4)));
  192. assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), Some((ConsoleOnly::Clwb, 5)));
  193. assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), Some((ConsoleOnly::Clwb, 6)));
  194. assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), Some((ConsoleOnly::Clwb, 8)));
  195. assert_eq!(decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 5)));
  196. // rdpid rax; rdpid r9
  197. assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), Some((ConsoleOnly::Rdpid(0), 4)));
  198. assert_eq!(decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), Some((ConsoleOnly::Rdpid(9), 5)));
  199. // not console-only: clflushopt (/7), xsaveopt (no 66), a plain mov, truncated bytes
  200. // SSE4a, as a retail game has it (#216: insertq xmm0, xmm1 with length / index bytes)
  201. assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 8, idx: 16 }, 6)));
  202. assert_eq!(decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), Some((ConsoleOnly::Insertq { dst: 8, src: 9, reg: true, len: 0, idx: 0 }, 5)));
  203. assert_eq!(decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), Some((ConsoleOnly::Extrq { dst: 2, src: None, len: 4, idx: 8 }, 6)));
  204. assert_eq!(decode(&[0x66, 0x0F, 0x79, 0xCA]), Some((ConsoleOnly::Extrq { dst: 1, src: Some(2), len: 0, idx: 0 }, 4)));
  205. assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), None, "an immediate missing");
  206. assert_eq!(decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), None, "VMREAD without a prefix is not SSE4a");
  207. // prefixes as a Zen 5 runs them (Kalmarv on #209): the last of F2 / F3 decides, 66 next
  208. // to them does not; 0x67 and a REX before a legacy prefix are ignored
  209. let insertq = Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 16, idx: 16 }, 7));
  210. for code in [[0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10]] {
  211. assert_eq!(decode(&code), insertq, "{code:02x?}");
  212. }
  213. for code in [[0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10]] {
  214. assert_eq!(decode(&code), None, "#UD on the CPU: {code:02x?}");
  215. }
  216. assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 4)));
  217. assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x38]), None);
  218. assert_eq!(decode(&[0x0F, 0xAE, 0x30]), None);
  219. assert_eq!(decode(&[0x48, 0x8B, 0x01]), None);
  220. assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None);
  221. assert_eq!(decode(&[0x0F]), None);
  222. }
  223. }