Merge upstream main a031883 into system runtime branch

Integrate XADD/CMPXCHG/LOCK memory forms (#198 / #320).

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
Adeeb Rahman committed 2026-11-24 11:00:28 -05:00
commit 2d8cd4579e
12 files changed
+1114 -513

No files matched your search

+10 -4
View File
@@ -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 = []
+20 -2
View File
@@ -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,
})
}
+29
View File
@@ -369,6 +369,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);
File diff suppressed because it is too large. Load diff
-14
View File
@@ -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),
+16 -1
View File
@@ -84,6 +84,15 @@ 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",
@@ -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))
+62
View File
@@ -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
+376
View File
@@ -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);
}
}
}
+24
View File
@@ -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;
+37
View File
@@ -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" }
@@ -674,6 +679,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"
+15 -1
View File
@@ -45,6 +45,20 @@ 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.
## 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.
+12
View File
@@ -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")