mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 13:30:43 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da16b36499 | ||
|
|
a03188315d | ||
|
|
95f6b52d9f | ||
|
|
7499d6f6c3 | ||
|
|
3a3f0c52af |
No files matched your search
@@ -16,6 +16,7 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Added
|
||||
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
|
||||
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
|
||||
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
|
||||
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
differs. Never writes.
|
||||
|
||||
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
|
||||
forms sharing an opcode, operand constraints that contradict each other, and
|
||||
flags declared both written and undefined. Standard library only (Python 3.11+).
|
||||
forms sharing an opcode, operand constraints that contradict each other, LOCK
|
||||
on a form that cannot write memory, and flags declared both written and
|
||||
undefined. Standard library only (Python 3.11+).
|
||||
"""
|
||||
|
||||
import sys
|
||||
@@ -26,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
|
||||
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
|
||||
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
|
||||
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
|
||||
"memory_only", "register_only", "no_rex_b", "unaligned"}
|
||||
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
|
||||
GROUP_KEYS = {"map", "opcodes", "digits"}
|
||||
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
|
||||
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
|
||||
@@ -63,6 +64,8 @@ ENCS = {
|
||||
"reg_xmm": ("RegXmm", True, {""}),
|
||||
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
|
||||
}
|
||||
# Encodings whose ModRM operand is the destination, so LOCK can apply to it.
|
||||
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl"}
|
||||
# Encodings whose ModRM operand is an XMM register or memory of the source width.
|
||||
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
|
||||
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
|
||||
@@ -171,6 +174,8 @@ def load(text):
|
||||
if (form["size"] == "x") != (form["enc"] in XMM_RM - {"reg_xmm", "reg_xmm_imm"}
|
||||
or form["enc"] == "xmm_gpr_imm"):
|
||||
fail(f"{where}: XMM size does not match the encoding")
|
||||
if form.get("lock") and (form["enc"] not in RM_DESTINATIONS or form.get("register_only")):
|
||||
fail(f"{where}: LOCK needs a memory destination")
|
||||
if form.get("unaligned") and form["src"] != "x":
|
||||
fail(f"{where}: alignment applies only to 16-byte operands")
|
||||
if form["prefix"] and form["map"] != "0f":
|
||||
@@ -266,7 +271,8 @@ def generate(operations, forms):
|
||||
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
|
||||
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
|
||||
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()} }},")
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
|
||||
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
|
||||
out += ["];", ""]
|
||||
|
||||
groups = []
|
||||
|
||||
@@ -123,6 +123,35 @@ impl CpuState {
|
||||
}
|
||||
}
|
||||
|
||||
/// CPUID leaf 1, EDX: CMOVcc.
|
||||
pub const CPUID_CMOV: u32 = 1 << 15;
|
||||
/// CPUID leaf 1, ECX: POPCNT.
|
||||
pub const CPUID_POPCNT: u32 = 1 << 23;
|
||||
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
|
||||
pub const CPUID_LZCNT: u32 = 1 << 5;
|
||||
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
|
||||
pub const CPUID_LONG_MODE: u32 = 1 << 29;
|
||||
|
||||
/// What the guest's CPUID returns in EAX, EBX, ECX and EDX.
|
||||
///
|
||||
/// The table is fixed and never reads the host. It names a synthetic
|
||||
/// processor, not an Intel or AMD product, and sets a feature bit only when
|
||||
/// every instruction of that feature is implemented. A leaf that is not
|
||||
/// listed returns zeros.
|
||||
pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
|
||||
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
|
||||
match leaf {
|
||||
// Highest basic leaf, then "Xenora guest" in EBX, EDX, ECX.
|
||||
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
|
||||
// No family, model or stepping: this is no shipped processor.
|
||||
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
|
||||
// Highest extended leaf.
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
|
||||
_ => [0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// Termination reason for guest execution.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ExitReason {
|
||||
|
||||
@@ -50,6 +50,8 @@ pub struct Form {
|
||||
pub no_rex_b: bool,
|
||||
/// A 16-byte memory operand may have any alignment.
|
||||
pub unaligned: bool,
|
||||
/// The LOCK prefix is accepted when the ModRM operand is memory.
|
||||
pub lockable: bool,
|
||||
}
|
||||
|
||||
/// Opcode table entry.
|
||||
@@ -167,6 +169,9 @@ pub struct Insn {
|
||||
pub imm: u64,
|
||||
/// Condition code for Jcc, CMOVcc and SETcc.
|
||||
pub condition: u8,
|
||||
/// Carries a LOCK prefix. Set only for a lockable form with a memory
|
||||
/// destination.
|
||||
pub lock: bool,
|
||||
}
|
||||
|
||||
impl Insn {
|
||||
@@ -231,8 +236,9 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
|
||||
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
|
||||
/// is called only for bytes that belong to the instruction, in order.
|
||||
///
|
||||
/// Forms the registry does not declare, LOCK, address-size overrides and an
|
||||
/// ignored segment override after FS or GS are rejected rather than approximated.
|
||||
/// Forms the registry does not declare, LOCK anywhere but on a lockable form
|
||||
/// with a memory destination, address-size overrides and an ignored segment
|
||||
/// override after FS or GS are rejected rather than approximated.
|
||||
pub fn decode<E>(
|
||||
rip: u64,
|
||||
fetch: impl FnMut(u64) -> Result<u8, E>,
|
||||
@@ -246,6 +252,7 @@ pub fn decode<E>(
|
||||
let mut operand_size = false;
|
||||
let mut rep = false;
|
||||
let mut repne = false;
|
||||
let mut lock = false;
|
||||
let mut segment = None;
|
||||
let mut byte = cursor.u8()?;
|
||||
loop {
|
||||
@@ -267,6 +274,11 @@ pub fn decode<E>(
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
0xF0 => {
|
||||
lock = true;
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
// CS, DS, ES and SS overrides have no effect in 64-bit mode. After
|
||||
// FS or GS their meaning is not relied on, so it is rejected.
|
||||
0x26 | 0x2E | 0x36 | 0x3E if segment.is_none() => {
|
||||
@@ -413,6 +425,11 @@ pub fn decode<E>(
|
||||
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
|
||||
reg = register(opcode & 7, rex_b, size);
|
||||
}
|
||||
// LOCK is an invalid opcode unless the instruction is lockable and its
|
||||
// destination is memory (Intel SDM Vol. 2, "LOCK").
|
||||
if lock && !(form.lockable && matches!(rm, Some(RmOperand::Mem(_)))) {
|
||||
return Err(DecodeError::Unsupported(0xF0));
|
||||
}
|
||||
|
||||
let mut imm = match form.immediate {
|
||||
Immediate::None => 0,
|
||||
@@ -449,6 +466,7 @@ pub fn decode<E>(
|
||||
reg,
|
||||
imm,
|
||||
condition: opcode & 0xF,
|
||||
lock,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! the state unchanged. Flags that the architecture leaves undefined keep their
|
||||
//! previous value, which is permitted but not something guests may rely on.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register};
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
|
||||
use crate::x86_simd;
|
||||
@@ -19,6 +19,7 @@ use crate::x86_table::Op;
|
||||
const RAX: usize = Register::Rax as usize;
|
||||
const RCX: usize = Register::Rcx as usize;
|
||||
const RDX: usize = Register::Rdx as usize;
|
||||
const RBX: usize = Register::Rbx as usize;
|
||||
const RSP: usize = Register::Rsp as usize;
|
||||
const RBP: usize = Register::Rbp as usize;
|
||||
|
||||
@@ -369,6 +370,35 @@ pub fn execute(
|
||||
write_rm(cpu, memory, insn, b)?;
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
Op::Xadd => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
let (value, flags) = add(a, b, false, size);
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
// The source is loaded before the destination is stored, so a
|
||||
// register added to itself keeps the sum.
|
||||
if insn.rm != Some(RmOperand::Reg(insn.reg)) {
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::Cmpxchg => {
|
||||
let (destination, source) = operands(cpu, memory, insn)?;
|
||||
let expected = cpu.gpr[RAX] & mask(size);
|
||||
let (_, flags) = sub(expected, destination, false, size);
|
||||
// The destination is written whether or not the values match, so a
|
||||
// mismatch on memory that cannot be written still faults.
|
||||
let matched = expected == destination;
|
||||
write_rm(
|
||||
cpu,
|
||||
memory,
|
||||
insn,
|
||||
if matched { source } else { destination },
|
||||
)?;
|
||||
if !matched {
|
||||
write_reg(cpu, accumulator(RAX), size, destination);
|
||||
}
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::Bswap => {
|
||||
let value = read_reg(cpu, insn.reg, size).swap_bytes() >> (64 - 8 * u32::from(size));
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
@@ -544,6 +574,14 @@ pub fn execute(
|
||||
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
|
||||
}
|
||||
Op::Nop => {}
|
||||
Op::Cpuid => {
|
||||
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
|
||||
// register write, so the upper halves are cleared.
|
||||
let values = cpuid(cpu.gpr[RAX] as u32, cpu.gpr[RCX] as u32);
|
||||
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(values) {
|
||||
cpu.gpr[register] = u64::from(value);
|
||||
}
|
||||
}
|
||||
Op::Clc => cpu.flags.cf = false,
|
||||
Op::Stc => cpu.flags.cf = true,
|
||||
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
|
||||
|
||||
+491
-459
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,282 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The guest CPUID contract (issue #130).
|
||||
//!
|
||||
//! CPUID reports a fixed synthetic processor. A feature bit is set only when
|
||||
//! every instruction of that feature is implemented, so each bit that is set
|
||||
//! is checked against instructions that run, and each bit software commonly
|
||||
//! tests that is clear has a witness instruction of that feature which both
|
||||
//! engines refuse. The witness must be removed before its bit can be set.
|
||||
//!
|
||||
//! Bit positions and the feature each instruction belongs to are from the
|
||||
//! Intel SDM Vol. 2, CPUID and the instruction entries. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
|
||||
use xenora_loader::cpu::{
|
||||
CPUID_CMOV, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason, Interpreter,
|
||||
RFlags, cpuid,
|
||||
};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RDX: usize = 2;
|
||||
const RBX: usize = 3;
|
||||
const RSI: usize = 6;
|
||||
|
||||
/// Index of a CPUID result, which come in the order EAX, EBX, ECX, EDX.
|
||||
const EBX: usize = 1;
|
||||
const ECX: usize = 2;
|
||||
const EDX: usize = 3;
|
||||
|
||||
fn image(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
/// Final state and exit reason from the interpreter, then from the DBT.
|
||||
fn both(cpu: &CpuState, code: &[u8], budget: usize) -> [(&'static str, CpuState, ExitReason); 2] {
|
||||
let mut memory = image(code);
|
||||
let interpreted = Interpreter::new(cpu.clone(), &mut memory, budget).run();
|
||||
let mut memory = image(code);
|
||||
let mut state = cpu.clone();
|
||||
let translated = DbtEngine::new(64 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut state, &mut memory, budget);
|
||||
[
|
||||
(
|
||||
"interpreter",
|
||||
interpreted.final_state,
|
||||
interpreted.exit_reason,
|
||||
),
|
||||
("DBT", translated.final_state, translated.exit_reason),
|
||||
]
|
||||
}
|
||||
|
||||
const SET: RFlags = RFlags {
|
||||
cf: true,
|
||||
zf: true,
|
||||
sf: true,
|
||||
of: true,
|
||||
pf: true,
|
||||
af: true,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn every_leaf_returns_its_documented_values() {
|
||||
// (leaf, subleaf, [EAX, EBX, ECX, EDX])
|
||||
let leaves: &[(u32, u32, [u32; 4])] = &[
|
||||
// Highest basic leaf 1, and "Xeno", "uest", "ra g" as little-endian text.
|
||||
(0, 0, [1, 0x6F6E_6558, 0x7473_6575, 0x6720_6172]),
|
||||
// POPCNT is ECX bit 23 and CMOV is EDX bit 15. No signature.
|
||||
(1, 0, [0, 0, 0x0080_0000, 0x0000_8000]),
|
||||
(1, 0xFFFF_FFFF, [0, 0, 0x0080_0000, 0x0000_8000]),
|
||||
// Highest extended leaf.
|
||||
(0x8000_0000, 0, [0x8000_0001, 0, 0, 0]),
|
||||
// LZCNT is ECX bit 5 and long mode is EDX bit 29.
|
||||
(0x8000_0001, 0, [0, 0, 0x0000_0020, 0x2000_0000]),
|
||||
(0x8000_0001, 7, [0, 0, 0x0000_0020, 0x2000_0000]),
|
||||
// Everything else, above or between the highest leaves, is zeros.
|
||||
(2, 0, [0; 4]),
|
||||
(4, 0, [0; 4]),
|
||||
(6, 0, [0; 4]),
|
||||
(7, 0, [0; 4]),
|
||||
(7, 1, [0; 4]),
|
||||
(0xB, 0, [0; 4]),
|
||||
(0xD, 1, [0; 4]),
|
||||
(0x16, 0, [0; 4]),
|
||||
(0x4000_0000, 0, [0; 4]),
|
||||
(0x7FFF_FFFF, 0, [0; 4]),
|
||||
(0x8000_0002, 0, [0; 4]),
|
||||
(0x8000_0008, 0, [0; 4]),
|
||||
(0xFFFF_FFFF, 0, [0; 4]),
|
||||
];
|
||||
for &(leaf, subleaf, wanted) in leaves {
|
||||
// Only EAX and ECX select the leaf: the upper halves are noise.
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
for (index, register) in cpu.gpr.iter_mut().enumerate() {
|
||||
*register = 0xA5A5_0000_1111_0000 + index as u64;
|
||||
}
|
||||
cpu.gpr[RAX] = 0xDEAD_BEEF_0000_0000 | u64::from(leaf);
|
||||
cpu.gpr[RCX] = 0xFEED_FACE_0000_0000 | u64::from(subleaf);
|
||||
cpu.flags = SET;
|
||||
// Each result is a 32-bit register write, so it clears the upper half.
|
||||
// CPUID changes no flag and no other register.
|
||||
let mut expected = cpu.clone();
|
||||
expected.rip = ENTRY + 2;
|
||||
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(wanted) {
|
||||
expected.gpr[register] = u64::from(value);
|
||||
}
|
||||
for (engine, state, exit) in both(&cpu, &[0x0F, 0xA2], 1) {
|
||||
let what = format!("leaf {leaf:#x} subleaf {subleaf:#x} on the {engine}");
|
||||
assert_eq!(exit, ExitReason::StepLimitExceeded, "{what}");
|
||||
assert_eq!(state, expected, "{what}");
|
||||
}
|
||||
// The function a runtime service would read agrees with the instruction.
|
||||
assert_eq!(cpuid(leaf, subleaf), wanted, "leaf {leaf:#x}");
|
||||
}
|
||||
|
||||
let [_, ebx, ecx, edx] = cpuid(0, 0);
|
||||
let vendor: Vec<u8> = [ebx, edx, ecx]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
assert_eq!(vendor, b"Xenora guest");
|
||||
assert_eq!(
|
||||
(CPUID_POPCNT, CPUID_CMOV, CPUID_LZCNT, CPUID_LONG_MODE),
|
||||
(1 << 23, 1 << 15, 1 << 5, 1 << 29)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reported_features_have_all_their_instructions_in_the_fixtures() {
|
||||
// `tests/x86_integer.rs` runs every line of this file through both engines
|
||||
// against an independent reference. Here each reported feature must have
|
||||
// its whole instruction set among those lines.
|
||||
let fixture = include_str!("x86/integer.txt");
|
||||
let decodable = |text: &str| {
|
||||
let line = fixture
|
||||
.lines()
|
||||
.find(|line| line.split_once(" | ").is_some_and(|(_, asm)| asm == text))
|
||||
.unwrap_or_else(|| panic!("no fixture for {text}"));
|
||||
let code: Vec<u8> = line
|
||||
.split_once(" | ")
|
||||
.unwrap()
|
||||
.0
|
||||
.split(' ')
|
||||
.map(|byte| u8::from_str_radix(byte, 16).unwrap())
|
||||
.collect();
|
||||
decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("{text}: {error:?}"));
|
||||
};
|
||||
let memory = |bits: u32| {
|
||||
let width = match bits {
|
||||
16 => "word",
|
||||
32 => "dword",
|
||||
_ => "qword",
|
||||
};
|
||||
format!("{width} ptr [rsi + 4*rdi + 16]")
|
||||
};
|
||||
// 16-, 32- and 64-bit destinations (RBX and R10) from a register and from memory.
|
||||
let sizes = [
|
||||
(16, "bx", "r9w", "r10w"),
|
||||
(32, "ebx", "r9d", "r10d"),
|
||||
(64, "rbx", "r9", "r10"),
|
||||
];
|
||||
|
||||
assert_ne!(cpuid(1, 0)[EDX] & CPUID_CMOV, 0);
|
||||
for condition in "o no b ae e ne be a s ns p np l ge le g".split(' ') {
|
||||
for (bits, low, source, high) in sizes {
|
||||
decodable(&format!("cmov{condition} {low}, {source}"));
|
||||
decodable(&format!("cmov{condition} {high}, {}", memory(bits)));
|
||||
}
|
||||
}
|
||||
for (feature, bit, name) in [
|
||||
(cpuid(1, 0)[ECX], CPUID_POPCNT, "popcnt"),
|
||||
(cpuid(0x8000_0001, 0)[ECX], CPUID_LZCNT, "lzcnt"),
|
||||
] {
|
||||
assert_ne!(feature & bit, 0, "{name}");
|
||||
for (bits, low, source, high) in sizes {
|
||||
decodable(&format!("{name} {low}, {source}"));
|
||||
decodable(&format!("{name} {high}, {}", memory(bits)));
|
||||
}
|
||||
}
|
||||
// Long mode: 64-bit operands and the registers only it has.
|
||||
assert_ne!(cpuid(0x8000_0001, 0)[EDX] & CPUID_LONG_MODE, 0);
|
||||
decodable("add r9, r12");
|
||||
decodable("movabs r15, 0x8877665544332211");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreported_features_each_have_an_instruction_that_is_refused() {
|
||||
// (feature, leaf, result register, bit, an instruction of that feature)
|
||||
let witnesses: &[(&str, u32, usize, u32, &[u8])] = &[
|
||||
("FPU", 1, EDX, 0, &[0xD9, 0xE8]), // fld1
|
||||
("TSC", 1, EDX, 4, &[0x0F, 0x31]), // rdtsc
|
||||
("CX8", 1, EDX, 8, &[0x0F, 0xC7, 0x0E]), // cmpxchg8b [rsi]
|
||||
("CLFSH", 1, EDX, 19, &[0x0F, 0xAE, 0x3E]), // clflush [rsi]
|
||||
("MMX", 1, EDX, 23, &[0x0F, 0x77]), // emms
|
||||
("FXSR", 1, EDX, 24, &[0x0F, 0xAE, 0x06]), // fxsave [rsi]
|
||||
("SSE", 1, EDX, 25, &[0x0F, 0x52, 0xC1]), // rsqrtps xmm0, xmm1
|
||||
("SSE2", 1, EDX, 26, &[0x0F, 0xAE, 0xF0]), // mfence
|
||||
("SSE3", 1, ECX, 0, &[0xF2, 0x0F, 0x7C, 0xC1]), // haddps xmm0, xmm1
|
||||
(
|
||||
"PCLMULQDQ",
|
||||
1,
|
||||
ECX,
|
||||
1,
|
||||
&[0x66, 0x0F, 0x3A, 0x44, 0xC1, 0x00],
|
||||
), // pclmulqdq xmm0, xmm1, 0
|
||||
("SSSE3", 1, ECX, 9, &[0x66, 0x0F, 0x38, 0x00, 0xC1]), // pshufb xmm0, xmm1
|
||||
("FMA", 1, ECX, 12, &[0xC4, 0xE2, 0x71, 0x98, 0xC2]), // vfmadd132ps xmm0, xmm1, xmm2
|
||||
("CMPXCHG16B", 1, ECX, 13, &[0x48, 0x0F, 0xC7, 0x0E]), // cmpxchg16b [rsi]
|
||||
("SSE4.1", 1, ECX, 19, &[0x66, 0x0F, 0x38, 0x40, 0xC1]), // pmulld xmm0, xmm1
|
||||
("SSE4.2", 1, ECX, 20, &[0xF2, 0x0F, 0x38, 0xF1, 0xC1]), // crc32 eax, ecx
|
||||
("MOVBE", 1, ECX, 22, &[0x0F, 0x38, 0xF0, 0x06]), // movbe eax, [rsi]
|
||||
("AESNI", 1, ECX, 25, &[0x66, 0x0F, 0x38, 0xDC, 0xC1]), // aesenc xmm0, xmm1
|
||||
("XSAVE", 1, ECX, 26, &[0x0F, 0x01, 0xD0]), // xgetbv
|
||||
("AVX", 1, ECX, 28, &[0xC5, 0xF4, 0x58, 0xC2]), // vaddps ymm0, ymm1, ymm2
|
||||
("F16C", 1, ECX, 29, &[0xC4, 0xE2, 0x79, 0x13, 0xC1]), // vcvtph2ps xmm0, xmm1
|
||||
("RDRAND", 1, ECX, 30, &[0x0F, 0xC7, 0xF0]), // rdrand eax
|
||||
("BMI1", 7, EBX, 3, &[0xC4, 0xE2, 0x70, 0xF2, 0xC2]), // andn eax, ecx, edx
|
||||
("AVX2", 7, EBX, 5, &[0xC5, 0xF5, 0xFE, 0xC2]), // vpaddd ymm0, ymm1, ymm2
|
||||
("BMI2", 7, EBX, 8, &[0xC4, 0xE2, 0x73, 0xF6, 0xC2]), // mulx eax, ecx, edx
|
||||
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
|
||||
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
|
||||
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
|
||||
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
|
||||
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
|
||||
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
|
||||
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
|
||||
];
|
||||
for &(feature, leaf, register, bit, code) in witnesses {
|
||||
assert_eq!(
|
||||
cpuid(leaf, 0)[register] >> bit & 1,
|
||||
0,
|
||||
"{feature} is reported"
|
||||
);
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = ENTRY;
|
||||
for (engine, state, exit) in both(&cpu, &padded, 1) {
|
||||
assert!(
|
||||
matches!(exit, ExitReason::IllegalInstruction(_)),
|
||||
"{feature}: {code:02X?} ran on the {engine} ({exit:?}); report the feature only \
|
||||
once all of it is implemented"
|
||||
);
|
||||
assert_eq!(state, cpu, "{feature} on the {engine}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guest_can_use_an_instruction_after_testing_its_feature_bit() {
|
||||
// mov eax, 1
|
||||
// cpuid
|
||||
// bt ecx, 23 ; POPCNT
|
||||
// jnc done
|
||||
// popcnt rax, rsi
|
||||
// done: hlt
|
||||
let code = [
|
||||
0xB8, 0x01, 0x00, 0x00, 0x00, 0x0F, 0xA2, 0x0F, 0xBA, 0xE1, 0x17, 0x73, 0x05, 0xF3, 0x48,
|
||||
0x0F, 0xB8, 0xC6, 0xF4,
|
||||
];
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = 0xF0F0_0000_0000_0001;
|
||||
for (engine, state, exit) in both(&cpu, &code, 16) {
|
||||
assert_eq!(exit, ExitReason::Halt, "{engine}");
|
||||
// Nine bits are set in RSI. Leaf 1 leaves EAX zero, so a skipped
|
||||
// POPCNT would show as 0.
|
||||
assert_eq!(state.gpr[RAX], 9, "{engine}");
|
||||
assert_eq!(state.rip, ENTRY + code.len() as u64, "{engine}");
|
||||
}
|
||||
}
|
||||
@@ -2672,15 +2672,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("cmpxchg16b_not_equal", 0),
|
||||
("cmpxchg16b_unaligned_is_gp", 0),
|
||||
("cmpxchg16b_unaligned_without_lock_is_gp", 0),
|
||||
("cmpxchg32_equal", 0),
|
||||
("cmpxchg64_memory_equal_without_lock", 0),
|
||||
("cmpxchg64_memory_not_equal", 0),
|
||||
("cmpxchg64_memory_not_equal_without_lock", 0),
|
||||
("cmpxchg8_not_equal_loads_al", 0),
|
||||
("cmpxchg8b_equal", 0),
|
||||
("cmpxchg8b_equal_without_lock", 0),
|
||||
("cmpxchg8b_not_equal", 0),
|
||||
("cmpxchg_mismatch_still_writes", 0),
|
||||
("crc32c_byte_and_qword_forms_agree", 0),
|
||||
("crc32c_check_string", 0),
|
||||
("dpps_mask", 0),
|
||||
@@ -2689,8 +2683,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("fs_addr32_truncates_before_adding_base", 0),
|
||||
("fs_rep_movsb_overrides_source_only", 0),
|
||||
("fs_rep_movsb_overrides_source_only_df_clear", 0),
|
||||
("gs_lock_xadd", 0),
|
||||
("gs_xadd_without_lock", 0),
|
||||
("haddps_hsubpd_addsubps", 0),
|
||||
("insertps_zero_mask", 0),
|
||||
("jecxz_tests_low_32_bits", 1),
|
||||
@@ -2783,12 +2775,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("shrd32_by8", 0),
|
||||
("shrd64_by1_sign_change", 0),
|
||||
("shrd64_cl64_is_count_zero", 0),
|
||||
("xadd32_reg_reg", 0),
|
||||
("xadd64_memory", 0),
|
||||
("xadd64_memory_without_lock", 0),
|
||||
("xadd64_same_register_doubles", 0),
|
||||
("xadd8_al_ah", 0),
|
||||
("xadd_readonly_page_keeps_register", 0),
|
||||
("xchg_ax_r9w_preserves_both_uppers", 0),
|
||||
("xchg_eax_ebx_clears_both_uppers", 0),
|
||||
("xchg_rax_r8_is_not_nop", 0),
|
||||
|
||||
@@ -84,9 +84,18 @@ def cases():
|
||||
f"mov {mem(bits)}, {reg(2, bits)}", f"mov {reg(14, bits)}, 0x5a",
|
||||
f"mov {mem(bits)}, 0x5a", f"xchg {reg(3, bits)}, {reg(9, bits)}",
|
||||
f"xchg {mem(bits)}, {reg(2, bits)}"]
|
||||
for op in ("xadd", "cmpxchg"):
|
||||
for bits in (8, 16, 32, 64):
|
||||
# Destination RAX always matches the accumulator; a register with
|
||||
# itself keeps the sum. LOCK is valid only with a memory destination.
|
||||
out += [f"{op} {reg(3, bits)}, {reg(1, bits)}", f"{op} {reg(9, bits)}, {reg(12, bits)}",
|
||||
f"{op} {reg(0, bits)}, {reg(2, bits)}", f"{op} {reg(3, bits)}, {reg(3, bits)}",
|
||||
f"{op} {mem(bits)}, {reg(2, bits)}", f"lock {op} {mem(bits)}, {reg(2, bits)}",
|
||||
f"lock {op} {mem(bits)}, {reg(0, bits)}"]
|
||||
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
|
||||
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
|
||||
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop", "cpuid",
|
||||
"nop dword ptr [rax + 8]", "pause", "push r9", "push rbx", "push -5", "push 0x12345678",
|
||||
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
|
||||
return list(dict.fromkeys(out))
|
||||
@@ -163,7 +172,13 @@ def assemble(lines):
|
||||
subprocess.run(["clang", "-target", "x86_64-apple-macos", "-c", source, "-o", obj], check=True)
|
||||
# One line per instruction: objdump never wraps its raw bytes.
|
||||
listing = subprocess.run(["objdump", "-d", obj], check=True, capture_output=True, text=True).stdout
|
||||
rows = [m.group(1).split() for m in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)", listing, re.M)]
|
||||
rows, prefix = [], []
|
||||
for match in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)(.*)$", listing, re.M):
|
||||
row = prefix + match.group(1).split()
|
||||
# objdump lists a leading LOCK prefix on a row of its own.
|
||||
prefix = row if match.group(2).strip() == "lock" else []
|
||||
if not prefix:
|
||||
rows.append(row)
|
||||
if len(rows) != len(lines):
|
||||
sys.exit(f"{len(lines)} instructions assembled to {len(rows)} rows")
|
||||
return "".join(f"{' '.join(row)} | {line}\n" for row, line in zip(rows, lines))
|
||||
|
||||
@@ -953,6 +953,68 @@ c7 44 be 10 5a 00 00 00 | mov dword ptr [rsi + 4*rdi + 16], 0x5a
|
||||
48 c7 44 be 10 5a 00 00 00 | mov qword ptr [rsi + 4*rdi + 16], 0x5a
|
||||
49 87 d9 | xchg rbx, r9
|
||||
48 87 54 be 10 | xchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
0f c0 cb | xadd bl, cl
|
||||
45 0f c0 e1 | xadd r9b, r12b
|
||||
0f c0 d0 | xadd al, dl
|
||||
0f c0 db | xadd bl, bl
|
||||
0f c0 54 be 10 | xadd byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f c0 54 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f c0 44 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], al
|
||||
66 0f c1 cb | xadd bx, cx
|
||||
66 45 0f c1 e1 | xadd r9w, r12w
|
||||
66 0f c1 d0 | xadd ax, dx
|
||||
66 0f c1 db | xadd bx, bx
|
||||
66 0f c1 54 be 10 | xadd word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f c1 54 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f c1 44 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], ax
|
||||
0f c1 cb | xadd ebx, ecx
|
||||
45 0f c1 e1 | xadd r9d, r12d
|
||||
0f c1 d0 | xadd eax, edx
|
||||
0f c1 db | xadd ebx, ebx
|
||||
0f c1 54 be 10 | xadd dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f c1 54 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f c1 44 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], eax
|
||||
48 0f c1 cb | xadd rbx, rcx
|
||||
4d 0f c1 e1 | xadd r9, r12
|
||||
48 0f c1 d0 | xadd rax, rdx
|
||||
48 0f c1 db | xadd rbx, rbx
|
||||
48 0f c1 54 be 10 | xadd qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f c1 54 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f c1 44 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rax
|
||||
0f c0 dc | xadd ah, bl
|
||||
0f c0 f1 | xadd cl, dh
|
||||
0f c0 6c be 10 | xadd byte ptr [rsi + 4*rdi + 16], ch
|
||||
0f b0 cb | cmpxchg bl, cl
|
||||
45 0f b0 e1 | cmpxchg r9b, r12b
|
||||
0f b0 d0 | cmpxchg al, dl
|
||||
0f b0 db | cmpxchg bl, bl
|
||||
0f b0 54 be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f b0 54 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f b0 44 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], al
|
||||
66 0f b1 cb | cmpxchg bx, cx
|
||||
66 45 0f b1 e1 | cmpxchg r9w, r12w
|
||||
66 0f b1 d0 | cmpxchg ax, dx
|
||||
66 0f b1 db | cmpxchg bx, bx
|
||||
66 0f b1 54 be 10 | cmpxchg word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f b1 54 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f b1 44 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], ax
|
||||
0f b1 cb | cmpxchg ebx, ecx
|
||||
45 0f b1 e1 | cmpxchg r9d, r12d
|
||||
0f b1 d0 | cmpxchg eax, edx
|
||||
0f b1 db | cmpxchg ebx, ebx
|
||||
0f b1 54 be 10 | cmpxchg dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f b1 54 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f b1 44 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], eax
|
||||
48 0f b1 cb | cmpxchg rbx, rcx
|
||||
4d 0f b1 e1 | cmpxchg r9, r12
|
||||
48 0f b1 d0 | cmpxchg rax, rdx
|
||||
48 0f b1 db | cmpxchg rbx, rbx
|
||||
48 0f b1 54 be 10 | cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f b1 54 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f b1 44 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rax
|
||||
0f b0 dc | cmpxchg ah, bl
|
||||
0f b0 f1 | cmpxchg cl, dh
|
||||
0f b0 6c be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], ch
|
||||
88 dc | mov ah, bl
|
||||
88 ea | mov dl, ch
|
||||
b7 21 | mov bh, 0x21
|
||||
@@ -972,6 +1034,7 @@ f8 | clc
|
||||
f9 | stc
|
||||
f5 | cmc
|
||||
90 | nop
|
||||
0f a2 | cpuid
|
||||
0f 1f 40 08 | nop dword ptr [rax + 8]
|
||||
f3 90 | pause
|
||||
41 51 | push r9
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! XADD, CMPXCHG and the LOCK prefix (issue #198).
|
||||
//!
|
||||
//! Expected values follow the operation sections of the Intel SDM Vol. 2 for
|
||||
//! XADD, CMPXCHG and LOCK, stated here as literal results. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
//! Nothing was compared with x86 hardware.
|
||||
//!
|
||||
//! Both engines run one guest instruction at a time on one host thread, so
|
||||
//! these tests establish the single-thread results that any later guest
|
||||
//! scheduler has to preserve. They say nothing about concurrent execution.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
/// Two writable pages. Nothing is mapped after them unless a test says so.
|
||||
const DATA: u64 = 0x4000;
|
||||
const PAGE: u64 = 0x1000;
|
||||
const END: u64 = DATA + 2 * PAGE;
|
||||
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RDX: usize = 2;
|
||||
const RBX: usize = 3;
|
||||
const RSI: usize = 6;
|
||||
|
||||
fn image(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(DATA, 2 * PAGE as usize, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn data(memory: &GuestMemory) -> Vec<u8> {
|
||||
let mut out = vec![0; 2 * PAGE as usize];
|
||||
memory.read_bytes(DATA, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
struct Run {
|
||||
name: &'static str,
|
||||
cpu: CpuState,
|
||||
exit: ExitReason,
|
||||
memory: GuestMemory,
|
||||
/// Instructions the DBT ran on the shared semantics.
|
||||
helpers: usize,
|
||||
}
|
||||
|
||||
/// The interpreter and the DBT, each from its own copy of `cpu` and `memory`.
|
||||
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
|
||||
let mut interpreted = memory.clone();
|
||||
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
|
||||
let mut translated = memory.clone();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let mut state = cpu.clone();
|
||||
let native = engine.run(&mut state, &mut translated, budget);
|
||||
[
|
||||
Run {
|
||||
name: "interpreter",
|
||||
cpu: result.final_state,
|
||||
exit: result.exit_reason,
|
||||
memory: interpreted,
|
||||
helpers: 0,
|
||||
},
|
||||
Run {
|
||||
name: "DBT",
|
||||
cpu: native.final_state,
|
||||
exit: native.exit_reason,
|
||||
memory: translated,
|
||||
helpers: engine.metrics.interpreter_fallbacks,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn flags(cf: bool, zf: bool, sf: bool, of: bool, pf: bool, af: bool) -> RFlags {
|
||||
RFlags {
|
||||
cf,
|
||||
zf,
|
||||
sf,
|
||||
of,
|
||||
pf,
|
||||
af,
|
||||
}
|
||||
}
|
||||
|
||||
fn low(bits: u32) -> u64 {
|
||||
u64::MAX >> (64 - bits)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_is_accepted_only_on_xadd_and_cmpxchg_with_a_memory_destination() {
|
||||
let accepted: &[&[u8]] = &[
|
||||
&[0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], ecx
|
||||
&[0xF0, 0x0F, 0xB1, 0x0E], // lock cmpxchg [rsi], ecx
|
||||
&[0x66, 0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], cx, in LLVM's prefix order
|
||||
&[0xF0, 0x66, 0x0F, 0xC1, 0x0E], // the same with LOCK first
|
||||
&[0x65, 0xF0, 0x0F, 0xB0, 0x0E], // lock cmpxchg gs:[rsi], cl
|
||||
&[0xF0, 0x48, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], rcx
|
||||
];
|
||||
for code in accepted {
|
||||
let lock = code.iter().position(|byte| *byte == 0xF0).unwrap();
|
||||
let mut unlocked = code.to_vec();
|
||||
unlocked.remove(lock);
|
||||
let insn = decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(insn.lock && !is_native(&insn), "{code:02X?}");
|
||||
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
|
||||
|
||||
// The accumulator matches the operand, so each exchange stores RCX.
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x2122_2324_2526_2728;
|
||||
cpu.gpr[RCX] = 0x1112_1314_1516_1718;
|
||||
cpu.gpr[RSI] = DATA + 0x40;
|
||||
let mut memory = image(code);
|
||||
memory
|
||||
.write_u64(DATA + 0x40, 0x2122_2324_2526_2728)
|
||||
.unwrap();
|
||||
let mut plain = image(&unlocked);
|
||||
plain.write_u64(DATA + 0x40, 0x2122_2324_2526_2728).unwrap();
|
||||
|
||||
// LOCK changes no result here: only the instruction is a byte longer.
|
||||
for (locked, wanted) in both(&cpu, &memory, 1).iter().zip(both(&cpu, &plain, 1)) {
|
||||
assert_eq!(locked.exit, ExitReason::StepLimitExceeded, "{code:02X?}");
|
||||
assert_eq!(locked.cpu.rip, ENTRY + code.len() as u64, "{code:02X?}");
|
||||
let mut shifted = wanted.cpu.clone();
|
||||
shifted.rip += 1;
|
||||
assert_eq!(locked.cpu, shifted, "{code:02X?} on the {}", locked.name);
|
||||
assert_eq!(data(&locked.memory), data(&wanted.memory), "{code:02X?}");
|
||||
assert_ne!(data(&locked.memory), data(&memory), "{code:02X?}");
|
||||
}
|
||||
}
|
||||
|
||||
let rejected: &[&[u8]] = &[
|
||||
&[0xF0, 0x0F, 0xC1, 0xC8], // lock xadd eax, ecx: register destination
|
||||
&[0xF0, 0x0F, 0xB1, 0xCB], // lock cmpxchg ebx, ecx: register destination
|
||||
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx: outside the locked subset
|
||||
&[0xF0, 0x87, 0x0E], // lock xchg [rsi], ecx: outside the locked subset
|
||||
&[0xF0, 0x0F, 0xC7, 0x0E], // lock cmpxchg8b [rsi]: not implemented
|
||||
&[0xF0, 0x8B, 0x06], // lock mov eax, [rsi]: never lockable
|
||||
&[0xF0, 0x90], // lock nop
|
||||
];
|
||||
for code in rejected {
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = DATA;
|
||||
let memory = image(&padded);
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert!(
|
||||
matches!(run.exit, ExitReason::IllegalInstruction(_)),
|
||||
"{code:02X?} on the {}: {:?}",
|
||||
run.name,
|
||||
run.exit
|
||||
);
|
||||
assert_eq!(run.cpu, cpu, "{code:02X?}");
|
||||
assert_eq!(data(&run.memory), data(&memory), "{code:02X?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_and_exchange_takes_each_branch_at_every_width() {
|
||||
// Destination [rsi] or RBX, source RCX, accumulator RAX.
|
||||
let forms: &[(&[u8], u32, bool)] = &[
|
||||
(&[0xF0, 0x0F, 0xB0, 0x0E], 8, true), // lock cmpxchg [rsi], cl
|
||||
(&[0x66, 0xF0, 0x0F, 0xB1, 0x0E], 16, true), // lock cmpxchg [rsi], cx
|
||||
(&[0xF0, 0x0F, 0xB1, 0x0E], 32, true), // lock cmpxchg [rsi], ecx
|
||||
(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E], 64, true), // lock cmpxchg [rsi], rcx
|
||||
(&[0x0F, 0xB0, 0xCB], 8, false), // cmpxchg bl, cl
|
||||
(&[0x66, 0x0F, 0xB1, 0xCB], 16, false), // cmpxchg bx, cx
|
||||
(&[0x0F, 0xB1, 0xCB], 32, false), // cmpxchg ebx, ecx
|
||||
(&[0x48, 0x0F, 0xB1, 0xCB], 64, false), // cmpxchg rbx, rcx
|
||||
];
|
||||
const ACCUMULATOR: u64 = 0x1111_2222_3333_4444;
|
||||
const SOURCE: u64 = 0xAAAA_BBBB_CCCC_DDDD;
|
||||
const ABOVE: u64 = 0x5555_6666_7777_8888;
|
||||
for &(code, bits, in_memory) in forms {
|
||||
let mask = low(bits);
|
||||
for matches in [true, false] {
|
||||
// The destination holds the accumulator's low bits, or differs in
|
||||
// bit 0, under bits the operation must not read.
|
||||
let old = (ABOVE & !mask) | ((ACCUMULATOR ^ u64::from(!matches)) & mask);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = ACCUMULATOR;
|
||||
cpu.gpr[RCX] = SOURCE;
|
||||
cpu.gpr[RBX] = old;
|
||||
cpu.gpr[RSI] = DATA + 0x80;
|
||||
// accumulator - destination is 0, or -1 when the destination is
|
||||
// one more. Start from the opposite flags so each must be written.
|
||||
let after = if matches {
|
||||
flags(false, true, false, false, true, false)
|
||||
} else {
|
||||
flags(true, false, true, false, true, true)
|
||||
};
|
||||
cpu.flags = flags(
|
||||
!after.cf, !after.zf, !after.sf, !after.of, !after.pf, !after.af,
|
||||
);
|
||||
let mut memory = image(code);
|
||||
memory.write_u64(DATA + 0x80, old).unwrap();
|
||||
|
||||
// A match stores the source. A mismatch stores the old value back
|
||||
// and loads it into the accumulator. An 8- or 16-bit register write
|
||||
// keeps the bits above it, a 32-bit one clears them, and a memory
|
||||
// write touches only its own bytes.
|
||||
let stored = if matches { SOURCE & mask } else { old & mask };
|
||||
let merged = |before: u64, value: u64| match bits {
|
||||
32 => value,
|
||||
_ => (before & !mask) | value,
|
||||
};
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.rip = ENTRY + code.len() as u64;
|
||||
wanted.flags = after;
|
||||
if !matches {
|
||||
wanted.gpr[RAX] = merged(ACCUMULATOR, old & mask);
|
||||
}
|
||||
let wanted_memory = if in_memory {
|
||||
(old & !mask) | stored
|
||||
} else {
|
||||
wanted.gpr[RBX] = merged(old, stored);
|
||||
old
|
||||
};
|
||||
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!("{code:02X?} matches={matches} on the {}", run.name);
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{what}");
|
||||
assert_eq!(run.cpu, wanted, "{what}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(DATA + 0x80).unwrap(),
|
||||
wanted_memory,
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_operands_may_be_unaligned_and_span_two_regions() {
|
||||
// No alignment is required of a locked operand (SDM Vol. 2, "LOCK"). The
|
||||
// last address straddles the data and a second writable region after it.
|
||||
let spanning = |code: &[u8]| {
|
||||
let mut memory = image(code);
|
||||
memory
|
||||
.map_region(END, PAGE as usize, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
};
|
||||
for at in [DATA + 1, DATA + 0x33, DATA + PAGE - 3, END - 8, END - 3] {
|
||||
// lock xadd [rsi], rcx
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 0x0000_0001_0000_0003;
|
||||
cpu.gpr[RSI] = at;
|
||||
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xC1, 0x0E]);
|
||||
memory.write_u64(at, 0xFFFF_FFFF_FFFF_FFFE).unwrap();
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
|
||||
assert_eq!(run.cpu.gpr[RCX], 0xFFFF_FFFF_FFFF_FFFE, "{at:#x}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(at).unwrap(),
|
||||
0x0000_0001_0000_0001,
|
||||
"{at:#x}"
|
||||
);
|
||||
// 0xFFFF_FFFF_FFFF_FFFE + 0x0000_0001_0000_0003 carries out of bit
|
||||
// 63 and bit 3; the sum is positive, nonzero and ends in 0x01.
|
||||
assert_eq!(
|
||||
run.cpu.flags,
|
||||
flags(true, false, false, false, false, true),
|
||||
"{at:#x}"
|
||||
);
|
||||
}
|
||||
|
||||
// lock cmpxchg [rsi], rcx, with a matching accumulator
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x8877_6655_4433_2211;
|
||||
cpu.gpr[RCX] = 0x0102_0304_0506_0708;
|
||||
cpu.gpr[RSI] = at;
|
||||
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E]);
|
||||
memory.write_u64(at, 0x8877_6655_4433_2211).unwrap();
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
|
||||
assert_eq!(run.cpu.gpr[RAX], 0x8877_6655_4433_2211, "{at:#x}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(at).unwrap(),
|
||||
0x0102_0304_0506_0708,
|
||||
"{at:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_on_any_byte_of_the_operand_changes_nothing() {
|
||||
let xadd: &[u8] = &[0xF0, 0x48, 0x0F, 0xC1, 0x0E]; // lock xadd [rsi], rcx
|
||||
let cmpxchg: &[u8] = &[0xF0, 0x48, 0x0F, 0xB1, 0x0E]; // lock cmpxchg [rsi], rcx
|
||||
// The last three bytes of writable memory, then five bytes that are
|
||||
// unmapped or read-only.
|
||||
let at = END - 3;
|
||||
for code in [xadd, cmpxchg] {
|
||||
for read_only_tail in [false, true] {
|
||||
// Accumulators that match and that do not match the operand's
|
||||
// writable bytes: a failed compare needs the write access too.
|
||||
for accumulator in [0x0000_0000_00CC_BBAA_u64, 7] {
|
||||
let mut memory = image(code);
|
||||
memory.write_bytes(at, &[0xAA, 0xBB, 0xCC]).unwrap();
|
||||
if read_only_tail {
|
||||
memory
|
||||
.map_region(END, PAGE as usize, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
}
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = accumulator;
|
||||
cpu.gpr[RCX] = 0x1122_3344_5566_7788;
|
||||
cpu.gpr[RSI] = at;
|
||||
cpu.flags = flags(true, false, true, false, true, false);
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!(
|
||||
"{code:02X?} tail read-only={read_only_tail} rax={accumulator:#x} on the {}",
|
||||
run.name
|
||||
);
|
||||
assert!(
|
||||
matches!(run.exit, ExitReason::MemoryFault(_)),
|
||||
"{what}: {:?}",
|
||||
run.exit
|
||||
);
|
||||
assert_eq!(run.cpu, cpu, "{what}");
|
||||
assert_eq!(data(&run.memory), data(&memory), "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_and_swap_loop_retries_then_fetch_and_add_follows() {
|
||||
// retry: lea rcx, [rax + 1]
|
||||
// lock cmpxchg [rsi], rcx
|
||||
// jne retry
|
||||
// mov edx, 5
|
||||
// lock xadd [rsi], rdx
|
||||
// hlt
|
||||
let code = [
|
||||
0x48, 0x8D, 0x48, 0x01, 0xF0, 0x48, 0x0F, 0xB1, 0x0E, 0x75, 0xF5, 0xBA, 0x05, 0x00, 0x00,
|
||||
0x00, 0xF0, 0x48, 0x0F, 0xC1, 0x16, 0xF4,
|
||||
];
|
||||
const COUNTER: u64 = DATA + 0x100;
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
// A stale expectation: the first exchange fails and reloads RAX, the
|
||||
// second succeeds.
|
||||
cpu.gpr[RAX] = 0xDEAD;
|
||||
cpu.gpr[RSI] = COUNTER;
|
||||
let mut memory = image(&code);
|
||||
memory.write_u64(COUNTER, 41).unwrap();
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
assert_eq!(run.exit, ExitReason::Halt, "{}", run.name);
|
||||
assert_eq!(run.cpu.gpr[RAX], 41, "{}", run.name);
|
||||
assert_eq!(run.cpu.gpr[RCX], 42, "{}", run.name);
|
||||
// XADD returns the value before its addition.
|
||||
assert_eq!(run.cpu.gpr[RDX], 42, "{}", run.name);
|
||||
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 47, "{}", run.name);
|
||||
assert_eq!(run.cpu.rip, ENTRY + code.len() as u64, "{}", run.name);
|
||||
// Two exchanges and one addition, none lowered to ARM64 yet.
|
||||
if run.name == "DBT" {
|
||||
assert_eq!(run.helpers, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -305,6 +305,8 @@ enum Outcome {
|
||||
}
|
||||
|
||||
fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
// LOCK changes no result on a machine that runs one instruction at a time.
|
||||
let text = text.strip_prefix("lock ").unwrap_or(text);
|
||||
let (name, rest) = text.split_once(' ').unwrap_or((text, ""));
|
||||
let places: Vec<Place> = if rest.is_empty() || name == "lea" || name == "nop" {
|
||||
Vec::new()
|
||||
@@ -659,6 +661,28 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
write(m, places[1], a);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"xadd" => {
|
||||
// TEMP := SRC + DEST; SRC := DEST; DEST := TEMP.
|
||||
let (a, b) = (read(m, places[0], bits), read(m, places[1], bits));
|
||||
let sum = arithmetic(m, a, b, false, false, bits);
|
||||
write(m, places[1], a);
|
||||
write(m, places[0], sum);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"cmpxchg" => {
|
||||
// The accumulator is compared with DEST as CMP would. On a match
|
||||
// DEST := SRC; otherwise accumulator := DEST and DEST := DEST.
|
||||
let accumulator = read(m, rax(bits), bits);
|
||||
let (destination, source) = (read(m, places[0], bits), read(m, places[1], bits));
|
||||
arithmetic(m, accumulator, destination, true, false, bits);
|
||||
if accumulator == destination {
|
||||
write(m, places[0], source);
|
||||
} else {
|
||||
write(m, rax(bits), destination);
|
||||
write(m, places[0], destination);
|
||||
}
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"bswap" => {
|
||||
let value = read(m, places[0], bits);
|
||||
let bytes = bits / 8;
|
||||
@@ -705,6 +729,24 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"nop" | "pause" => Outcome::Done(none),
|
||||
"cpuid" => {
|
||||
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
|
||||
// and the four features whose every instruction exists, CMOV and
|
||||
// POPCNT in leaf 1, LZCNT and long mode in leaf 0x8000_0001.
|
||||
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
|
||||
let values = match m.gpr[RAX] as u32 {
|
||||
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
|
||||
1 => [0, 0, 1 << 23, 1 << 15],
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, 1 << 5, 1 << 29],
|
||||
_ => [0; 4],
|
||||
};
|
||||
// EAX, EBX, ECX and EDX, each zero-extended.
|
||||
for (index, value) in [0, 3, 1, 2].into_iter().zip(values) {
|
||||
m.gpr[index] = u64::from(value);
|
||||
}
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"push" => {
|
||||
m.pushed = read(m, places[0], 64) as u64;
|
||||
m.gpr[4] -= 8;
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
# decodable; a form counts as implemented only once its operation has semantics
|
||||
# and independent tests. Forms not listed here are rejected.
|
||||
#
|
||||
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
|
||||
# Every other use of LOCK is rejected, as the architecture's #UD.
|
||||
#
|
||||
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
|
||||
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
|
||||
# A 16-byte memory operand must be aligned unless unaligned = true.
|
||||
@@ -48,6 +51,8 @@ movsx = { ref = "sdm MOVSX/MOVSXD" }
|
||||
movsxd = { ref = "sdm MOVSX/MOVSXD" }
|
||||
lea = { ref = "sdm LEA" }
|
||||
xchg = { ref = "sdm XCHG" }
|
||||
xadd = { writes = "cf zf sf of pf af", ref = "sdm XADD" }
|
||||
cmpxchg = { writes = "cf zf sf of pf af", ref = "sdm CMPXCHG" }
|
||||
bswap = { ref = "sdm BSWAP" }
|
||||
cwde = { ref = "sdm CBW/CWDE/CDQE" }
|
||||
cdq = { ref = "sdm CWD/CDQ/CQO" }
|
||||
@@ -85,6 +90,7 @@ syscall = { terminator = true, ref = "sdm SYSCALL" }
|
||||
clc = { writes = "cf", ref = "sdm CLC" }
|
||||
stc = { writes = "cf", ref = "sdm STC" }
|
||||
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
|
||||
cpuid = { ref = "sdm CPUID" }
|
||||
|
||||
# SSE and SSE2 moves and packed integer operations. None reads or writes RFLAGS.
|
||||
movaps = { ref = "sdm MOVAPS" }
|
||||
@@ -562,6 +568,13 @@ opcode = 0x05
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "cpuid"
|
||||
map = "0f"
|
||||
opcode = 0xA2
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "movzx"
|
||||
map = "0f"
|
||||
@@ -674,6 +687,38 @@ enc = "rm_reg"
|
||||
size = "v"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "cmpxchg"
|
||||
map = "0f"
|
||||
opcode = 0xB0
|
||||
enc = "rm_reg"
|
||||
size = "b"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "cmpxchg"
|
||||
map = "0f"
|
||||
opcode = 0xB1
|
||||
enc = "rm_reg"
|
||||
size = "v"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "xadd"
|
||||
map = "0f"
|
||||
opcode = 0xC0
|
||||
enc = "rm_reg"
|
||||
size = "b"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "xadd"
|
||||
map = "0f"
|
||||
opcode = 0xC1
|
||||
enc = "rm_reg"
|
||||
size = "v"
|
||||
lock = true
|
||||
|
||||
# Groups whose digits select an operation: [opcode, size, immediate, encoding].
|
||||
[[group]]
|
||||
map = "0f"
|
||||
|
||||
@@ -45,6 +45,42 @@ XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `Cpu
|
||||
|
||||
None of it has been compared with x86 hardware.
|
||||
|
||||
## Locked instructions
|
||||
|
||||
XADD and CMPXCHG exist for 8-, 16-, 32- and 64-bit register and memory destinations. The LOCK prefix (F0) is accepted on exactly the forms the registry marks `lock = true`, and only when the destination is memory. Today those are the memory forms of XADD and CMPXCHG. LOCK anywhere else is an illegal instruction, as the Intel SDM (Vol. 2, "LOCK") specifies for a register destination or an instruction that cannot be locked. LOCK on the other instructions the SDM allows (ADD, ADC, AND, BTC, BTR, BTS, DEC, INC, NEG, NOT, OR, SBB, SUB, XOR and XCHG), CMPXCHG8B and CMPXCHG16B are not implemented and stay rejected.
|
||||
|
||||
These rules hold for both engines and are what a guest scheduler has to preserve:
|
||||
|
||||
- **Ordering.** Each engine runs one guest instruction at a time on one host thread, and an instruction either completes or changes nothing. A locked instruction is therefore indivisible and totally ordered with every other guest access, and LOCK changes no result: the locked and unlocked encodings leave identical state. A scheduler that switches guest threads only between instructions keeps this. One that runs guest threads on several host threads does not, and must first make each locked instruction atomic against every access to its operand, with x86's ordering rather than ARM64's weaker one. Nothing here provides or tests that.
|
||||
- **Alignment.** A locked operand may have any alignment and may span two mapped regions.
|
||||
- **Compare failure.** CMPXCHG compares the accumulator with the destination as CMP would and sets all six status flags from it. On a match it stores the source and leaves the accumulator alone. On a mismatch it loads the destination into the accumulator and stores the destination's old value back, so the destination is written either way and a mismatch on memory that cannot be written still faults. With a 32-bit register destination both stores clear the upper half of that register, following the SDM's operation text.
|
||||
- **Faults.** If any byte of the operand cannot be read or written, the instruction faults before memory, registers or flags change.
|
||||
- **Lowering.** The DBT runs these forms on the shared semantics. They are not lowered to ARM64 atomic instructions, which could only be judged against concurrent guest threads.
|
||||
|
||||
The SDM cases for these forms in `tests/cpu_known_answers.rs` were written before this implementation, by another contributor. `tests/x86_atomic.rs` adds the LOCK rules, both compare outcomes at every width, unaligned operands and faults. None of it has been compared with x86 hardware, and nothing here establishes multi-thread behaviour.
|
||||
|
||||
## Guest CPUID
|
||||
|
||||
CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a synthetic processor: the vendor string is `Xenora guest`, not Intel's or AMD's, and leaf 1 reports no family, model or stepping.
|
||||
|
||||
| Leaf (EAX) | EAX | EBX | ECX | EDX |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 0 | 1, the highest basic leaf | `Xeno` | `uest` | `ra g` |
|
||||
| 1 | 0 | 0 | POPCNT (bit 23) | CMOV (bit 15) |
|
||||
| 0x8000_0000 | 0x8000_0001, the highest extended leaf | 0 | 0 | 0 |
|
||||
| 0x8000_0001 | 0 | 0 | LZCNT (bit 5) | long mode (bit 29) |
|
||||
| any other | 0 | 0 | 0 | 0 |
|
||||
|
||||
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
|
||||
|
||||
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MFENCE, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
|
||||
- The table is therefore truthful about Xenora, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
|
||||
- A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first.
|
||||
|
||||
`xenora_loader::cpu::cpuid` is the one copy of the table. A runtime service that reports processor features should read it rather than keep its own list.
|
||||
|
||||
`tests/cpu_features.rs` pins every leaf in both engines. For each reported feature it requires the feature's whole instruction set among the fixtures that `tests/x86_integer.rs` executes. For each feature software commonly tests that is not reported, it holds one instruction of that feature that both engines must refuse. To report a new feature: implement all of its instructions, remove its witness, add its instruction list to the reported set, then set the bit. The pairing of instructions with feature bits follows the Intel SDM; nothing was compared with a processor.
|
||||
|
||||
## Rejected on purpose
|
||||
|
||||
LOCK, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, atomics and fences. The DBT also refuses raw SYSCALL.
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
|
||||
@@ -67,6 +67,18 @@ class GenerateX86(unittest.TestCase):
|
||||
self.rejects(self.form('op = "movq"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "x"\nsrc = "q"\nunaligned = true'), "alignment applies")
|
||||
self.rejects(self.form('op = "nop"\nprefix = "66"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "map 0f")
|
||||
|
||||
def test_lock_needs_a_memory_destination(self):
|
||||
# Not a form without ModRM, not one whose ModRM operand is the source,
|
||||
# and not one that takes only a register.
|
||||
message = "LOCK needs a memory destination"
|
||||
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "n"\nlock = true'), message)
|
||||
self.rejects(self.form('op = "mov"\nopcode = 0xD7\nenc = "reg_rm"\nsize = "v"\nlock = true'), message)
|
||||
self.rejects(self.form('op = "xadd"\nopcode = 0xD7\nenc = "rm_reg"\nsize = "v"\nregister_only = true\nlock = true'), message)
|
||||
|
||||
def test_only_xadd_and_cmpxchg_are_lockable(self):
|
||||
_, forms = generate_x86.load(REGISTRY)
|
||||
self.assertEqual({form["op"] for form in forms if form.get("lock")}, {"cmpxchg", "xadd"})
|
||||
|
||||
def test_unknown_vocabulary_is_rejected(self):
|
||||
self.rejects(self.form('op = "frob"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "unknown op")
|
||||
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "z"'), "unknown size")
|
||||
|
||||
Reference in new issue
Block a user