cpu: add SSE2 state, moves and packed integer forms

Add XMM0-XMM15 and MXCSR to the guest state and extend the registry with
mandatory prefixes, so the shared decoder covers the SSE and SSE2 moves and
packed integer operations. Reject opcodes where 0x66 could be both an
operand size and a mandatory prefix.

Translate operations with identical NEON lane semantics to ARM64; other
forms call the shared semantics and are counted. Raise a distinct
general-protection exit for misaligned 16-byte operands and reserved MXCSR
bits. Floating-point arithmetic is not implemented.

Verify 374 LLVM-assembled instructions against a byte-array reference that
reads only their assembly text, and mixed sequences between the engines.

Refs #124, #125, #126, #128

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
This commit is contained in:
jelly013 committed 2026-11-24 12:53:35 +01:00
1 parent 70f1793a4c
commit dce37dab18
19 files changed
+4802 -284

No files matched your search

+2
View File
@@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Added XMM0-XMM15 and MXCSR to the guest CPU state, and the SSE and SSE2 moves and packed integer forms: aligned, unaligned, scalar, half and non-temporal moves, MOVD/MOVQ, sign-mask extraction, bitwise operations, wrapping and saturating arithmetic, compares, minimum, maximum, average, multiplies, PSADBW, packs, unpacks, shifts, shuffles, PINSRW, PEXTRW, LDMXCSR and STMXCSR (parts of #124, #125, #126 and #128; awaiting independent review). Operations with identical NEON lane semantics are translated to ARM64; the rest call the shared semantics. Misaligned 16-byte operands and reserved MXCSR bits raise a distinct general-protection exit. MXCSR is state only: floating-point arithmetic is not implemented.
- Added 374 LLVM-assembled vector instructions with a byte-array reference, compared with both engines over 23,936 states, plus alignment, fault, width and mixed-sequence tests.
- Added a declarative x86-64 instruction registry (`crates/loader/x86/instructions.toml`) and its generator, `crates/loader/generate_x86.py`, with `validate`, `generate` and `--check` modes. The static probe, the interpreter and the native DBT now share one decoder driven by its tables, so instruction boundaries, rejected forms and reported support agree. Overlapping encodings, such as a sign extension claiming the MOV-immediate opcodes, fail validation. See `docs/cpu/instruction-registry.md`.
- Added integer instructions for 8-, 16-, 32- and 64-bit register and checked memory operands: the eight ALU operations, TEST, INC, DEC, NEG, NOT, XCHG, ROL, ROR, SHL, SHR, SAR, MUL, IMUL, DIV, IDIV, CMOVcc, SETcc, BT, BTS, BTR, BTC, BSF, BSR, POPCNT, TZCNT, LZCNT, CBW/CWD families, PUSH, POP, LEAVE, RET imm16 and flag instructions, with parity and auxiliary-carry flags and a distinct divide-error exit (parts of #65, #66, #68, #70, #71, #73, #118 to #123, #194 to #196; awaiting independent review). Forms the DBT does not lower to ARM64 call the same Rust semantics and are counted.
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
+41 -10
View File
@@ -26,15 +26,16 @@ 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"}
"memory_only", "register_only", "no_rex_b", "unaligned"}
GROUP_KEYS = {"map", "opcodes", "digits"}
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
PREFIXES = {"", "f3"}
SIZES = {"b": "Byte", "v": "Variable", "q": "Quad", "y": "Wide", "n": "None"}
IMMS = {"": "None", "ib": "SignedByte", "iz": "SignedFull", "iv": "Full", "iw": "Word",
# Two-byte opcode table per mandatory prefix.
PREFIXES = {"": "TWO_BYTE", "66": "TWO_BYTE_66", "f3": "TWO_BYTE_F3", "f2": "TWO_BYTE_F2"}
SIZES = {"b": "Byte", "v": "Variable", "q": "Quad", "y": "Wide", "n": "None", "x": "Xmm"}
IMMS = {"": "None", "ib": "SignedByte", "iz": "SignedFull", "iv": "Full", "iw": "Word", "ub": "Byte",
"rel8": "SignedByte", "rel32": "Signed32"}
SRCS = {"": 0, "b": 1, "w": 2, "d": 4}
SRCS = {"": 0, "b": 1, "w": 2, "d": 4, "q": 8, "x": 16}
# encoding -> (Rust variant, has ModRM, required immediates)
ENCS = {
"none": ("None", False, {""}),
@@ -52,7 +53,18 @@ ENCS = {
"op_reg_imm": ("OpRegImm", False, {"ib", "iv"}),
"imm": ("Imm", False, {"ib", "iz", "iw"}),
"rel": ("Rel", False, {"rel8", "rel32"}),
"xmm_rm": ("XmmRm", True, {""}),
"rm_xmm": ("RmXmm", True, {""}),
"xmm_rm_imm": ("XmmRmImm", True, {"ub"}),
"rm_imm_xmm": ("RmImmXmm", True, {"ub"}),
"xmm_gpr": ("XmmGpr", True, {""}),
"gpr_xmm": ("GprXmm", True, {""}),
"xmm_gpr_imm": ("XmmGprImm", True, {"ub"}),
"reg_xmm": ("RegXmm", True, {""}),
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
}
# 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.
RESERVED = {0x0F, 0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3,
*range(0x40, 0x50)}
@@ -151,8 +163,16 @@ def load(text):
fail(f"{where}: memory_only and register_only contradict")
if (form.get("memory_only") or form.get("register_only")) and not modrm:
fail(f"{where}: operand restriction without ModRM")
if form["src"] and form["enc"] != "reg_rm":
fail(f"{where}: a source size needs reg_rm")
sourced = form["enc"] in XMM_RM or form["enc"] == "xmm_gpr_imm"
if sourced != bool(form["src"]) and form["enc"] not in ("reg_rm", "rm"):
fail(f"{where}: source size does not match the encoding")
if form["src"] and not sourced and form["enc"] == "rm" and form["size"] != "n":
fail(f"{where}: source size does not match the encoding")
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("unaligned") and form["src"] != "x":
fail(f"{where}: alignment applies only to 16-byte operands")
if form["prefix"] and form["map"] != "0f":
fail(f"{where}: mandatory prefixes are only supported in map 0f")
if form["count"] not in (1, 8, 16) or form["opcode"] % form["count"]:
@@ -170,6 +190,14 @@ def load(text):
if form["digit"] in slots or (slots and (None in slots or form["digit"] is None)):
fail(f"{where}: overlapping encoding")
slots[form["digit"]] = form
# 0x66 selects a 16-bit operand for an unprefixed integer form, so a
# 66-prefixed form at the same opcode would be ambiguous.
for other, sized in (("66", form), ("", None)):
if form["map"] == "0f" and form["prefix"] == ("" if other == "66" else "66"):
for rival in claimed.get(("0f", other, opcode), {}).values():
plain = sized or rival
if plain["size"] in ("b", "v"):
fail(f"{where}: 0x66 is both an operand size and a mandatory prefix")
if form["digit"] is not None:
first = next(iter(slots.values()))
if (first["size"] in "bn") != (form["size"] in "bn"):
@@ -225,6 +253,8 @@ def generate(operations, forms):
lambda op, e: str(e["terminator"]).lower())
method("Can raise an arithmetic fault.", "can_fault", "bool",
lambda op, e: str(e["faults"]).lower())
vector = {form["op"] for form in forms if form["size"] == "x" or "xmm" in form["enc"]}
method("Uses an XMM register.", "is_vector", "bool", lambda op, e: str(op in vector).lower())
out[-1:] = ["}", ""]
out.append(f"pub static FORMS: [Form; {len(forms)}] = [")
@@ -235,14 +265,15 @@ def generate(operations, forms):
f"source: {SRCS[form['src']]}, has_modrm: {str(ENCS[form['enc']][1]).lower()}, "
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"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
f"unaligned: {str(bool(form.get('unaligned'))).lower()} }},")
out += ["];", ""]
groups = []
tables = {name: ["Entry::Unsupported"] * 256 for name in ("ONE_BYTE", "TWO_BYTE", "TWO_BYTE_F3")}
tables = {name: ["Entry::Unsupported"] * 256 for name in ("ONE_BYTE", *PREFIXES.values())}
slots = {}
for index, form in enumerate(forms):
table = "TWO_BYTE_F3" if form["prefix"] else MAPS[form["map"]]
table = MAPS[form["map"]] if form["map"] == "1" else PREFIXES[form["prefix"]]
for opcode in range(form["opcode"], form["opcode"] + form["count"]):
slots.setdefault((table, opcode), {})[form["digit"]] = index
for (table, opcode), digits in sorted(slots.items()):
+69
View File
@@ -290,6 +290,75 @@ impl Arm64Assembler {
);
}
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
self.emit(
0x3dc0_0000
| (((offset / 16) & 0xfff) << 10)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(qt) & 0x1f),
);
}
/// STR Qt, [Xn, #offset] (offset a multiple of 16)
pub fn str_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
self.emit(
0x3d80_0000
| (((offset / 16) & 0xfff) << 10)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(qt) & 0x1f),
);
}
/// FMOV Dd, Xn (clears the upper half of Vd)
pub fn fmov_d_from_x(&mut self, vd: u8, xn: u8) {
self.emit(0x9e67_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(vd) & 0x1f));
}
/// MOV Vd.D[1], Xn
pub fn ins_d1_from_x(&mut self, vd: u8, xn: u8) {
self.emit(0x4e18_1c00 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(vd) & 0x1f));
}
/// Three-register vector instruction from its base word
pub fn neon3(&mut self, base: u32, vd: u8, vn: u8, vm: u8) {
self.emit(
base | ((u32::from(vm) & 0x1f) << 16)
| ((u32::from(vn) & 0x1f) << 5)
| (u32::from(vd) & 0x1f),
);
}
/// SHL Vd, Vn, #shift for 0 <= shift < lane
pub fn shl_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
self.emit(
0x4f00_5400
| ((lane + shift) << 16)
| ((u32::from(vn) & 0x1f) << 5)
| (u32::from(vd) & 0x1f),
);
}
/// USHR Vd, Vn, #shift for 1 <= shift <= lane
pub fn ushr_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
self.emit(
0x6f00_0400
| ((2 * lane - shift) << 16)
| ((u32::from(vn) & 0x1f) << 5)
| (u32::from(vd) & 0x1f),
);
}
/// SSHR Vd, Vn, #shift for 1 <= shift <= lane
pub fn sshr_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
self.emit(
0x4f00_0400
| ((2 * lane - shift) << 16)
| ((u32::from(vn) & 0x1f) << 5)
| (u32::from(vd) & 0x1f),
);
}
/// SXTW (64-bit/sign-extended): SXTW Xd, Wn (SBFM Xd, Xn, #0, #31)
pub fn sxtw_64(&mut self, xd: u8, wn: u8) {
self.emit(0x93407c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
+28 -1
View File
@@ -67,6 +67,24 @@ pub struct RFlags {
pub af: bool, // Auxiliary carry flag
}
/// SSE control and status register. Reset state masks every exception and
/// rounds to nearest (Intel SDM Vol. 1, 10.2.3).
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Mxcsr(pub u32);
impl Mxcsr {
pub const RESET: u32 = 0x1F80;
/// Bits that exist; loading any other bit raises #GP.
pub const WRITABLE: u32 = 0xFFFF;
}
impl Default for Mxcsr {
fn default() -> Self {
Self(Self::RESET)
}
}
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
#[repr(C)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -76,6 +94,9 @@ pub struct CpuState {
pub flags: RFlags,
pub gs_base: u64,
pub fs_base: u64,
/// XMM0-XMM15, lane 0 in the low bits.
pub xmm: [u128; 16],
pub mxcsr: Mxcsr,
}
impl CpuState {
@@ -88,6 +109,8 @@ impl CpuState {
flags: RFlags::default(),
gs_base: 0,
fs_base: 0,
xmm: [0; 16],
mxcsr: Mxcsr::default(),
}
}
@@ -112,6 +135,8 @@ pub enum ExitReason {
StackUnderflow,
/// Division by zero or a quotient too large for its destination (#DE).
DivideError,
/// A misaligned 16-byte operand or a reserved MXCSR bit (#GP).
GeneralProtection,
}
impl fmt::Display for ExitReason {
@@ -125,6 +150,7 @@ impl fmt::Display for ExitReason {
Self::IllegalInstruction(op) => write!(f, "illegal or unsupported opcode: 0x{op:02x}"),
Self::StackUnderflow => write!(f, "stack underflow"),
Self::DivideError => write!(f, "guest divide error"),
Self::GeneralProtection => write!(f, "guest general-protection fault"),
}
}
}
@@ -152,7 +178,8 @@ mod layout_tests {
assert_eq!(std::mem::offset_of!(RFlags, of), 3);
assert_eq!(std::mem::offset_of!(RFlags, pf), 4);
assert_eq!(std::mem::offset_of!(RFlags, af), 5);
assert_eq!(std::mem::size_of::<CpuState>(), 16 * 8 + 8 + 8 + 8 + 8);
assert_eq!(std::mem::offset_of!(CpuState, xmm), 160);
assert_eq!(std::mem::offset_of!(CpuState, mxcsr), 160 + 16 * 16);
let cpu = CpuState::default();
let base = std::ptr::addr_of!(cpu) as usize;
+316 -3
View File
@@ -6,15 +6,15 @@
//! executes them in a W^X code cache, and manages host-service dispatch and fallbacks.
use crate::arm64::{
Arm64Assembler, Condition, SP, X0, X1, X2, X4, X5, X6, X9, X10, X11, X12, X13, X14, X15, X19,
X20, X21, X29, X30, XZR,
Arm64Assembler, Condition, SP, X0, X1, X2, X3, X4, X5, X6, X9, X10, X11, X12, X13, X14, X15,
X19, X20, X21, X29, X30, XZR,
};
use crate::cpu::{CpuState, ExecutionResult, ExitReason, RFlags, Register};
use crate::jit::{JitError, JitMemory};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment, decode};
use crate::x86_exec;
use crate::x86_table::Op;
use crate::x86_table::{FORMS, Op};
use std::collections::HashMap;
const MAX_BLOCK_INSTRUCTIONS: usize = 16;
@@ -309,6 +309,12 @@ const PF: u32 = FLAGS_OFFSET + std::mem::offset_of!(RFlags, pf) as u32;
const AF: u32 = FLAGS_OFFSET + std::mem::offset_of!(RFlags, af) as u32;
const ALL_FLAGS: u8 = 0x3F;
const NEON_EOR: u32 = 0x6e20_1c00; // EOR Vd.16B, Vn.16B, Vm.16B
fn xmm_offset(index: u8) -> u32 {
std::mem::offset_of!(CpuState, xmm) as u32 + u32::from(index) * 16
}
fn reg_offset(index: u8) -> u32 {
u32::from(index) * 8
}
@@ -343,10 +349,81 @@ pub fn is_native(insn: &Insn) -> bool {
| Op::Ret
| Op::Nop
| Op::Hlt => true,
Op::Movaps
| Op::Movups
| Op::Movdqa
| Op::Movdqu
| Op::Movntdq
| Op::Movntps
| Op::Movd
| Op::Movq
| Op::Movss
| Op::Movsd
| Op::Movlps
| Op::Movhps => true,
op if insn.encoding == Encoding::XmmRm => neon_operation(op).is_some(),
Op::Psllw
| Op::Pslld
| Op::Psllq
| Op::Psrlw
| Op::Psrld
| Op::Psrlq
| Op::Psraw
| Op::Psrad => insn.encoding == Encoding::RmImmXmm,
_ => false,
}
}
/// NEON base word for a packed operation with identical lane semantics, and
/// whether its sources are swapped (BIC is `Vn & !Vm`, PANDN is `!dst & src`).
#[rustfmt::skip]
fn neon_operation(op: Op) -> Option<(u32, bool)> {
Some(match op {
Op::Pand => (0x4e20_1c00, false), // and.16b
Op::Por => (0x4ea0_1c00, false), // orr.16b
Op::Pxor => (0x6e20_1c00, false), // eor.16b
Op::Pandn => (0x4e60_1c00, true), // bic.16b
Op::Paddb => (0x4e20_8400, false), // add.16b
Op::Paddw => (0x4e60_8400, false), // add.8h
Op::Paddd => (0x4ea0_8400, false), // add.4s
Op::Paddq => (0x4ee0_8400, false), // add.2d
Op::Psubb => (0x6e20_8400, false), // sub.16b
Op::Psubw => (0x6e60_8400, false), // sub.8h
Op::Psubd => (0x6ea0_8400, false), // sub.4s
Op::Psubq => (0x6ee0_8400, false), // sub.2d
Op::Paddsb => (0x4e20_0c00, false), // sqadd.16b
Op::Paddsw => (0x4e60_0c00, false), // sqadd.8h
Op::Psubsb => (0x4e20_2c00, false), // sqsub.16b
Op::Psubsw => (0x4e60_2c00, false), // sqsub.8h
Op::Paddusb => (0x6e20_0c00, false), // uqadd.16b
Op::Paddusw => (0x6e60_0c00, false), // uqadd.8h
Op::Psubusb => (0x6e20_2c00, false), // uqsub.16b
Op::Psubusw => (0x6e60_2c00, false), // uqsub.8h
Op::Pcmpeqb => (0x6e20_8c00, false), // cmeq.16b
Op::Pcmpeqw => (0x6e60_8c00, false), // cmeq.8h
Op::Pcmpeqd => (0x6ea0_8c00, false), // cmeq.4s
Op::Pcmpgtb => (0x4e20_3400, false), // cmgt.16b
Op::Pcmpgtw => (0x4e60_3400, false), // cmgt.8h
Op::Pcmpgtd => (0x4ea0_3400, false), // cmgt.4s
Op::Pminub => (0x6e20_6c00, false), // umin.16b
Op::Pmaxub => (0x6e20_6400, false), // umax.16b
Op::Pminsw => (0x4e60_6c00, false), // smin.8h
Op::Pmaxsw => (0x4e60_6400, false), // smax.8h
Op::Pavgb => (0x6e20_1400, false), // urhadd.16b
Op::Pavgw => (0x6e60_1400, false), // urhadd.8h
Op::Pmullw => (0x4e60_9c00, false), // mul.8h
Op::Punpcklbw => (0x4e00_3800, false), // zip1.16b
Op::Punpcklwd => (0x4e40_3800, false), // zip1.8h
Op::Punpckldq => (0x4e80_3800, false), // zip1.4s
Op::Punpcklqdq => (0x4ec0_3800, false), // zip1.2d
Op::Punpckhbw => (0x4e00_7800, false), // zip2.16b
Op::Punpckhwd => (0x4e40_7800, false), // zip2.8h
Op::Punpckhdq => (0x4e80_7800, false), // zip2.4s
Op::Punpckhqdq => (0x4ec0_7800, false), // zip2.2d
_ => return None,
})
}
/// Whether the flags produced by `insns[index]` can be observed. They cannot if
/// a later instruction in the block overwrites all of them before anything reads
/// them or could leave the block.
@@ -694,10 +771,205 @@ impl Emitter<'_> {
}
}
/// Load a 16-byte memory operand into X0 (low) and X1 (high).
fn load_wide(&mut self, insn: &Insn, operand: &MemOperand, completed: usize) {
self.effective_address(operand, true);
let helper = if FORMS[usize::from(insn.form)].unaligned {
read_u128_helper as *const ()
} else {
read_aligned_u128_helper as *const ()
};
self.call_helper(helper as u64);
self.guard(insn, completed);
}
/// Store both halves of a guest XMM register.
fn store_halves(&mut self, index: u8, low: u8, high: u8) {
self.asm.str_uoff_64(low, X19, xmm_offset(index));
self.asm.str_uoff_64(high, X19, xmm_offset(index) + 8);
}
fn vector(&mut self, insn: &Insn, completed: usize) {
let reg = insn.reg.index;
match (insn.op, insn.encoding) {
(Op::Movd, Encoding::XmmGpr) => {
self.load_rm(X9, insn, completed);
if insn.size == 4 {
self.asm.mov_reg_32(X9, X9);
}
self.store_halves(reg, X9, XZR);
}
(Op::Movd, _) => {
self.asm.ldr_uoff_64(X10, X19, xmm_offset(reg));
self.store_rm(insn, X10, completed);
}
(_, Encoding::RmXmm) => self.vector_store(insn, completed),
(
Op::Movaps
| Op::Movups
| Op::Movdqa
| Op::Movdqu
| Op::Movq
| Op::Movss
| Op::Movsd
| Op::Movlps
| Op::Movhps,
_,
) => self.vector_load(insn, completed),
(op, Encoding::RmImmXmm) => {
let Some(RmOperand::Reg(target)) = insn.rm else {
return;
};
let offset = xmm_offset(target.index);
let lane = match op {
Op::Psllw | Op::Psrlw | Op::Psraw => 16,
Op::Pslld | Op::Psrld | Op::Psrad => 32,
_ => 64,
};
let count = insn.imm.min(u64::from(lane)) as u32;
if count == 0 {
return;
}
let asm = &mut *self.asm;
asm.ldr_q_uoff(0, X19, offset);
match op {
Op::Psllw | Op::Pslld | Op::Psllq if count == lane => {
asm.neon3(NEON_EOR, 0, 0, 0);
}
Op::Psllw | Op::Pslld | Op::Psllq => asm.shl_vector(0, 0, lane, count),
Op::Psraw | Op::Psrad => asm.sshr_vector(0, 0, lane, count),
_ => asm.ushr_vector(0, 0, lane, count),
}
asm.str_q_uoff(0, X19, offset);
}
(op, _) => {
let Some((base, swapped)) = neon_operation(op) else {
return;
};
match insn.rm {
Some(RmOperand::Mem(operand)) => {
self.load_wide(insn, &operand, completed);
self.asm.fmov_d_from_x(1, X0);
self.asm.ins_d1_from_x(1, X1);
}
Some(RmOperand::Reg(source)) => {
self.asm.ldr_q_uoff(1, X19, xmm_offset(source.index));
}
None => return,
}
let asm = &mut *self.asm;
asm.ldr_q_uoff(0, X19, xmm_offset(reg));
if swapped {
asm.neon3(base, 0, 1, 0);
} else {
asm.neon3(base, 0, 0, 1);
}
asm.str_q_uoff(0, X19, xmm_offset(reg));
}
}
}
fn vector_load(&mut self, insn: &Insn, completed: usize) {
let reg = insn.reg.index;
let target = xmm_offset(reg);
match insn.rm {
Some(RmOperand::Mem(operand)) if insn.rm_size == 16 => {
self.load_wide(insn, &operand, completed);
self.store_halves(reg, X0, X1);
}
Some(RmOperand::Mem(_)) => {
self.load_rm(X9, insn, completed);
match insn.op {
Op::Movlps => self.asm.str_uoff_64(X9, X19, target),
Op::Movhps => self.asm.str_uoff_64(X9, X19, target + 8),
_ => self.store_halves(reg, X9, XZR),
}
}
Some(RmOperand::Reg(source)) => {
let from = xmm_offset(source.index);
let asm = &mut *self.asm;
match insn.op {
Op::Movss => {
asm.ldr_uoff_32(X9, X19, from);
asm.str_uoff_32(X9, X19, target);
}
Op::Movsd => {
asm.ldr_uoff_64(X9, X19, from);
asm.str_uoff_64(X9, X19, target);
}
Op::Movq => {
asm.ldr_uoff_64(X9, X19, from);
self.store_halves(reg, X9, XZR);
}
// MOVHLPS and MOVLHPS.
Op::Movlps => {
asm.ldr_uoff_64(X9, X19, from + 8);
asm.str_uoff_64(X9, X19, target);
}
Op::Movhps => {
asm.ldr_uoff_64(X9, X19, from);
asm.str_uoff_64(X9, X19, target + 8);
}
_ => {
asm.ldr_q_uoff(0, X19, from);
asm.str_q_uoff(0, X19, target);
}
}
}
None => {}
}
}
fn vector_store(&mut self, insn: &Insn, completed: usize) {
let from = xmm_offset(insn.reg.index);
match insn.rm {
Some(RmOperand::Mem(operand)) if insn.rm_size == 16 => {
self.asm.ldr_uoff_64(X2, X19, from);
self.asm.ldr_uoff_64(X3, X19, from + 8);
self.effective_address(&operand, true);
let helper = if FORMS[usize::from(insn.form)].unaligned {
write_u128_helper as *const ()
} else {
write_aligned_u128_helper as *const ()
};
self.call_helper(helper as u64);
self.guard(insn, completed);
}
Some(RmOperand::Mem(_)) => {
let half = if insn.op == Op::Movhps { 8 } else { 0 };
self.asm.ldr_uoff_64(X10, X19, from + half);
self.store_rm(insn, X10, completed);
}
Some(RmOperand::Reg(target)) => {
let to = xmm_offset(target.index);
match insn.op {
Op::Movss => {
self.asm.ldr_uoff_32(X9, X19, from);
self.asm.str_uoff_32(X9, X19, to);
}
Op::Movsd => {
self.asm.ldr_uoff_64(X9, X19, from);
self.asm.str_uoff_64(X9, X19, to);
}
Op::Movq => {
self.asm.ldr_uoff_64(X9, X19, from);
self.store_halves(target.index, X9, XZR);
}
_ => {
self.asm.ldr_q_uoff(0, X19, from);
self.asm.str_q_uoff(0, X19, to);
}
}
}
None => {}
}
}
/// Lower an instruction accepted by [`is_native`].
fn lower(&mut self, insn: &Insn, completed: usize, flags: bool) {
match insn.op {
Op::Nop => {}
_ if insn.op.is_vector() => self.vector(insn, completed),
Op::Neg => {
self.load_rm(X10, insn, completed);
self.asm.mov_reg_64(X21, X10);
@@ -909,6 +1181,47 @@ fn load_helper(size: u8) -> u64 {
helper as u64
}
fn fault(ctx: *mut BlockContext, reason: ExitReason) {
unsafe {
(*ctx).faulted = 1;
(*ctx).exit_reason = Some(reason);
}
}
/// Read 16 bytes at any alignment; returned in X0 (low) and X1 (high).
extern "C" fn read_u128_helper(ctx: *mut BlockContext, addr: u64) -> u128 {
let memory = unsafe { &*(*ctx).memory_ptr };
let mut bytes = [0; 16];
if let Err(error) = memory.read_bytes(addr, &mut bytes) {
fault(ctx, ExitReason::MemoryFault(error));
}
u128::from_le_bytes(bytes)
}
extern "C" fn read_aligned_u128_helper(ctx: *mut BlockContext, addr: u64) -> u128 {
if !addr.is_multiple_of(16) {
fault(ctx, ExitReason::GeneralProtection);
return 0;
}
read_u128_helper(ctx, addr)
}
/// Write 16 bytes at any alignment; `value` arrives in X2 (low) and X3 (high).
extern "C" fn write_u128_helper(ctx: *mut BlockContext, addr: u64, value: u128) {
let memory = unsafe { &mut *(*ctx).memory_ptr };
if let Err(error) = memory.write_bytes(addr, &value.to_le_bytes()) {
fault(ctx, ExitReason::MemoryFault(error));
}
}
extern "C" fn write_aligned_u128_helper(ctx: *mut BlockContext, addr: u64, value: u128) {
if !addr.is_multiple_of(16) {
fault(ctx, ExitReason::GeneralProtection);
return;
}
write_u128_helper(ctx, addr, value);
}
/// Execute one decoded instruction through the shared semantics.
extern "C" fn execute_helper(ctx: *mut BlockContext, cpu: *mut CpuState, insn: *const Insn) {
unsafe {
+1
View File
@@ -21,6 +21,7 @@ pub mod tls;
pub mod triage;
pub mod x86_decode;
pub mod x86_exec;
pub mod x86_simd;
#[rustfmt::skip]
pub mod x86_table;
+59 -16
View File
@@ -7,7 +7,9 @@
//! `x86/instructions.toml`, so instruction boundaries, operands and rejected
//! forms agree across them.
use crate::x86_table::{FORMS, GROUPS, ONE_BYTE, Op, TWO_BYTE, TWO_BYTE_F3};
use crate::x86_table::{
FORMS, GROUPS, ONE_BYTE, Op, TWO_BYTE, TWO_BYTE_66, TWO_BYTE_F2, TWO_BYTE_F3,
};
/// Architectural x86-64 instruction length limit, in bytes.
///
@@ -46,6 +48,8 @@ pub struct Form {
pub memory_only: bool,
pub register_only: bool,
pub no_rex_b: bool,
/// A 16-byte memory operand may have any alignment.
pub unaligned: bool,
}
/// Opcode table entry.
@@ -73,6 +77,21 @@ pub enum Encoding {
OpRegImm,
Imm,
Rel,
/// XMM `reg` from XMM or memory.
XmmRm,
/// XMM or memory from XMM `reg`.
RmXmm,
XmmRmImm,
/// XMM `rm` shifted in place by an immediate.
RmImmXmm,
/// XMM `reg` from a general register or memory.
XmmGpr,
/// General register or memory from XMM `reg`.
GprXmm,
XmmGprImm,
/// General `reg` from XMM `rm`.
RegXmm,
RegXmmImm,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -81,6 +100,7 @@ pub enum OperandSize {
Variable,
Wide,
Quad,
Xmm,
None,
}
@@ -92,6 +112,8 @@ pub enum Immediate {
Signed32,
Full,
Word,
/// Zero-extended byte.
Byte,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -100,7 +122,8 @@ pub enum Segment {
Gs,
}
/// A register operand. `high` selects AH, CH, DH or BH of `index`.
/// A general or XMM register operand, as the encoding says. `high` selects AH,
/// CH, DH or BH of `index`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RegOperand {
pub index: u8,
@@ -133,7 +156,7 @@ pub struct Insn {
/// Guest address of the first byte.
pub rip: u64,
pub len: u8,
/// Operand size in bytes: 1, 2, 4 or 8, or 0 when there is none.
/// Operand size in bytes: 1, 2, 4, 8 or 16 (XMM), or 0 when there is none.
pub size: u8,
/// Width of the ModRM operand in bytes.
pub rm_size: u8,
@@ -208,7 +231,7 @@ 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, REPNE, address-size overrides and
/// Forms the registry does not declare, LOCK, address-size overrides and
/// conflicting segment overrides are rejected rather than approximated.
pub fn decode<E>(
rip: u64,
@@ -222,6 +245,7 @@ pub fn decode<E>(
};
let mut operand_size = false;
let mut rep = false;
let mut repne = false;
let mut segment = None;
let mut byte = cursor.u8()?;
loop {
@@ -238,6 +262,11 @@ pub fn decode<E>(
byte = cursor.u8()?;
continue;
}
0xF2 => {
repne = 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() => {
@@ -260,20 +289,32 @@ pub fn decode<E>(
let (rex_w, rex_r, rex_x, rex_b) =
(rex & 8 != 0, (rex & 4) << 1, (rex & 2) << 2, (rex & 1) << 3);
let table = if byte == 0x0F {
byte = cursor.u8()?;
if rep { &TWO_BYTE_F3 } else { &TWO_BYTE }
} else {
&ONE_BYTE
};
let opcode = byte;
let one_byte = std::ptr::eq(table, &raw const ONE_BYTE);
// Only PAUSE (F3 90) has a meaning here for F3 on a one-byte opcode.
if rep && one_byte && opcode != 0x90 {
return Err(DecodeError::Unsupported(0xF3));
// F2 and F3 together have no defined meaning for any declared form.
if rep && repne {
return Err(DecodeError::Unsupported(0xF2));
}
let two_byte = byte == 0x0F;
let opcode = if two_byte { cursor.u8()? } else { byte };
let slot = usize::from(opcode);
let table = if !two_byte {
// Only PAUSE (F3 90) has a meaning here for F3 on a one-byte opcode.
if repne || (rep && opcode != 0x90) {
return Err(DecodeError::Unsupported(if rep { 0xF3 } else { 0xF2 }));
}
&ONE_BYTE
} else if rep {
&TWO_BYTE_F3
} else if repne {
&TWO_BYTE_F2
} else if operand_size && !matches!(TWO_BYTE_66[slot], Entry::Unsupported) {
// 0x66 selects the form instead of an operand size.
operand_size = false;
&TWO_BYTE_66
} else {
&TWO_BYTE
};
let entry = table[usize::from(opcode)];
let entry = table[slot];
let mut modrm = 0;
let form_index = match entry {
Entry::Unsupported => return Err(DecodeError::Unsupported(opcode)),
@@ -294,6 +335,7 @@ pub fn decode<E>(
OperandSize::None => 0,
OperandSize::Byte => 1,
OperandSize::Quad => 8,
OperandSize::Xmm => 16,
OperandSize::Wide | OperandSize::Variable if rex_w => 8,
OperandSize::Variable if operand_size => 2,
OperandSize::Wide | OperandSize::Variable => 4,
@@ -378,6 +420,7 @@ pub fn decode<E>(
Immediate::Signed32 => cursor.signed(4)?,
Immediate::Full => cursor.bytes(usize::from(size))?,
Immediate::Word => cursor.bytes(2)?,
Immediate::Byte => cursor.bytes(1)?,
};
let end = rip.wrapping_add(cursor.len as u64);
+7 -5
View File
@@ -13,6 +13,7 @@
use crate::cpu::{CpuState, ExitReason, RFlags, Register};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
use crate::x86_simd;
use crate::x86_table::Op;
const RAX: usize = Register::Rax as usize;
@@ -54,7 +55,7 @@ fn offset(cpu: &CpuState, operand: &MemOperand) -> u64 {
base.wrapping_add(index).wrapping_add_signed(operand.disp)
}
fn read_reg(cpu: &CpuState, reg: RegOperand, size: u8) -> u64 {
pub(crate) fn read_reg(cpu: &CpuState, reg: RegOperand, size: u8) -> u64 {
let value = cpu.gpr[usize::from(reg.index)];
if reg.high {
(value >> 8) & 0xFF
@@ -64,7 +65,7 @@ fn read_reg(cpu: &CpuState, reg: RegOperand, size: u8) -> u64 {
}
/// Write a register: 8- and 16-bit writes merge, 32-bit writes zero-extend.
fn write_reg(cpu: &mut CpuState, reg: RegOperand, size: u8, value: u64) {
pub(crate) fn write_reg(cpu: &mut CpuState, reg: RegOperand, size: u8, value: u64) {
let slot = &mut cpu.gpr[usize::from(reg.index)];
*slot = match (size, reg.high) {
(1, true) => (*slot & !0xFF00) | ((value & 0xFF) << 8),
@@ -73,7 +74,7 @@ fn write_reg(cpu: &mut CpuState, reg: RegOperand, size: u8, value: u64) {
};
}
fn read_mem(memory: &GuestMemory, address: u64, size: u8) -> Result<u64, ExitReason> {
pub(crate) fn read_mem(memory: &GuestMemory, address: u64, size: u8) -> Result<u64, ExitReason> {
match size {
1 => memory.read_u8(address).map(u64::from),
2 => memory.read_u16(address).map(u64::from),
@@ -83,7 +84,7 @@ fn read_mem(memory: &GuestMemory, address: u64, size: u8) -> Result<u64, ExitRea
.map_err(ExitReason::MemoryFault)
}
fn write_mem(
pub(crate) fn write_mem(
memory: &mut GuestMemory,
address: u64,
size: u8,
@@ -98,7 +99,7 @@ fn write_mem(
.map_err(ExitReason::MemoryFault)
}
fn rm_operand(insn: &Insn) -> Result<RmOperand, ExitReason> {
pub(crate) fn rm_operand(insn: &Insn) -> Result<RmOperand, ExitReason> {
// The decoder supplies a ModRM operand for every form that reaches here.
insn.rm.ok_or(ExitReason::IllegalInstruction(0))
}
@@ -554,6 +555,7 @@ pub fn execute(
cpu.rip = next;
return Ok(Some(ExitReason::Syscall(cpu.gpr[RAX])));
}
_ => x86_simd::execute(cpu, memory, insn)?,
}
cpu.rip = next;
Ok(None)
+388
View File
@@ -0,0 +1,388 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Semantic primitives for the SSE and SSE2 moves and packed integer forms.
//!
//! Lane 0 is the least significant. Every instruction is all-or-nothing and none
//! changes RFLAGS. Floating-point arithmetic is not implemented here: MXCSR is
//! state only, loaded and stored but not yet consulted.
use crate::cpu::{CpuState, ExitReason, Mxcsr};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, RegOperand, RmOperand};
use crate::x86_exec::{address, read_mem, read_reg, rm_operand, write_mem, write_reg};
use crate::x86_table::{FORMS, Op};
fn lane_mask(bits: u32) -> u128 {
(1 << bits) - 1
}
fn lane(value: u128, bits: u32, index: u32) -> u64 {
((value >> (bits * index)) & lane_mask(bits)) as u64
}
/// Signed value of a lane of `bits`.
fn signed(value: u64, bits: u32) -> i64 {
(value << (64 - bits)) as i64 >> (64 - bits)
}
/// Build a vector from a function of the lane index.
fn build(bits: u32, f: impl Fn(u32) -> u64) -> u128 {
(0..128 / bits).fold(0, |out, index| {
out | (u128::from(f(index)) & lane_mask(bits)) << (bits * index)
})
}
fn map(a: u128, b: u128, bits: u32, f: impl Fn(u64, u64) -> u64) -> u128 {
build(bits, |index| f(lane(a, bits, index), lane(b, bits, index)))
}
fn map_signed(a: u128, b: u128, bits: u32, f: impl Fn(i64, i64) -> i64) -> u128 {
map(a, b, bits, |x, y| {
f(signed(x, bits), signed(y, bits)) as u64
})
}
fn all_ones(condition: bool) -> u64 {
if condition { u64::MAX } else { 0 }
}
/// Clamp to the signed range of `bits`.
fn saturate(value: i64, bits: u32) -> i64 {
let limit = 1i64 << (bits - 1);
value.clamp(-limit, limit - 1)
}
/// Clamp to the unsigned range of `bits`.
fn saturate_unsigned(value: i64, bits: u32) -> i64 {
value.clamp(0, (1 << bits) - 1)
}
/// Narrow the lanes of `a` then `b`, each `bits` wide, to half width.
fn pack(a: u128, b: u128, bits: u32, narrow: impl Fn(i64, u32) -> i64) -> u128 {
let count = 128 / bits;
build(bits / 2, |index| {
let source = if index < count { a } else { b };
narrow(signed(lane(source, bits, index % count), bits), bits / 2) as u64
})
}
/// Interleave the low or high halves of `a` and `b`.
fn unpack(a: u128, b: u128, bits: u32, high: bool) -> u128 {
let start = if high { 64 / bits } else { 0 };
build(bits, |index| {
let source = if index % 2 == 0 { a } else { b };
lane(source, bits, start + index / 2)
})
}
/// Select lanes of `bits` by two-bit fields of `imm`, reading `a` for the low
/// half of the result and `b` for the high half.
fn shuffle_32(a: u128, b: u128, imm: u64) -> u128 {
build(32, |index| {
let source = if index < 2 { a } else { b };
lane(source, 32, (imm >> (2 * index) & 3) as u32)
})
}
/// Shuffle the four words starting at word `start`, keeping the other four.
fn shuffle_16(value: u128, imm: u64, start: u32) -> u128 {
build(16, |index| {
if (start..start + 4).contains(&index) {
lane(value, 16, start + (imm >> (2 * (index - start)) & 3) as u32)
} else {
lane(value, 16, index)
}
})
}
/// Logical or arithmetic shift of every lane; counts past the width give zero
/// or, for arithmetic shifts, copies of the sign.
fn shift(op: Op, value: u128, count: u64) -> u128 {
let (bits, kind) = match op {
Op::Psllw => (16, 0),
Op::Pslld => (32, 0),
Op::Psllq => (64, 0),
Op::Psrlw => (16, 1),
Op::Psrld => (32, 1),
Op::Psrlq => (64, 1),
Op::Psraw => (16, 2),
_ => (32, 2),
};
let over = count >= u64::from(bits);
map(value, 0, bits, |x, _| match kind {
0 if !over => x << count,
1 if !over => x >> count,
2 => (signed(x, bits) >> count.min(u64::from(bits) - 1)) as u64,
_ => 0,
})
}
fn shift_bytes(value: u128, count: u64, left: bool) -> u128 {
if count > 15 {
0
} else if left {
value << (8 * count)
} else {
value >> (8 * count)
}
}
/// Result of a two-source packed operation.
fn packed(op: Op, a: u128, b: u128) -> u128 {
match op {
Op::Pand => a & b,
Op::Pandn => !a & b,
Op::Por => a | b,
Op::Pxor => a ^ b,
Op::Paddb => map(a, b, 8, u64::wrapping_add),
Op::Paddw => map(a, b, 16, u64::wrapping_add),
Op::Paddd => map(a, b, 32, u64::wrapping_add),
Op::Paddq => map(a, b, 64, u64::wrapping_add),
Op::Psubb => map(a, b, 8, u64::wrapping_sub),
Op::Psubw => map(a, b, 16, u64::wrapping_sub),
Op::Psubd => map(a, b, 32, u64::wrapping_sub),
Op::Psubq => map(a, b, 64, u64::wrapping_sub),
Op::Paddsb => map_signed(a, b, 8, |x, y| saturate(x + y, 8)),
Op::Paddsw => map_signed(a, b, 16, |x, y| saturate(x + y, 16)),
Op::Psubsb => map_signed(a, b, 8, |x, y| saturate(x - y, 8)),
Op::Psubsw => map_signed(a, b, 16, |x, y| saturate(x - y, 16)),
Op::Paddusb => map(a, b, 8, |x, y| (x + y).min(0xFF)),
Op::Paddusw => map(a, b, 16, |x, y| (x + y).min(0xFFFF)),
Op::Psubusb => map(a, b, 8, u64::saturating_sub),
Op::Psubusw => map(a, b, 16, u64::saturating_sub),
Op::Pcmpeqb => map(a, b, 8, |x, y| all_ones(x == y)),
Op::Pcmpeqw => map(a, b, 16, |x, y| all_ones(x == y)),
Op::Pcmpeqd => map(a, b, 32, |x, y| all_ones(x == y)),
Op::Pcmpgtb => map_signed(a, b, 8, |x, y| all_ones(x > y) as i64),
Op::Pcmpgtw => map_signed(a, b, 16, |x, y| all_ones(x > y) as i64),
Op::Pcmpgtd => map_signed(a, b, 32, |x, y| all_ones(x > y) as i64),
Op::Pminub => map(a, b, 8, u64::min),
Op::Pmaxub => map(a, b, 8, u64::max),
Op::Pminsw => map_signed(a, b, 16, i64::min),
Op::Pmaxsw => map_signed(a, b, 16, i64::max),
Op::Pavgb => map(a, b, 8, |x, y| (x + y + 1) >> 1),
Op::Pavgw => map(a, b, 16, |x, y| (x + y + 1) >> 1),
Op::Pmullw => map(a, b, 16, u64::wrapping_mul),
Op::Pmulhw => map_signed(a, b, 16, |x, y| (x * y) >> 16),
Op::Pmulhuw => map(a, b, 16, |x, y| (x * y) >> 16),
Op::Pmuludq => map(a, b, 64, |x, y| (x & 0xFFFF_FFFF) * (y & 0xFFFF_FFFF)),
Op::Pmaddwd => build(32, |index| {
let product = |at| signed(lane(a, 16, at), 16) * signed(lane(b, 16, at), 16);
(product(2 * index) + product(2 * index + 1)) as u64
}),
Op::Psadbw => build(64, |half| {
(0..8)
.map(|at| lane(a, 8, 8 * half + at).abs_diff(lane(b, 8, 8 * half + at)))
.sum()
}),
Op::Packsswb => pack(a, b, 16, saturate),
Op::Packssdw => pack(a, b, 32, saturate),
Op::Packuswb => pack(a, b, 16, saturate_unsigned),
Op::Punpcklbw => unpack(a, b, 8, false),
Op::Punpcklwd => unpack(a, b, 16, false),
Op::Punpckldq => unpack(a, b, 32, false),
Op::Punpcklqdq => unpack(a, b, 64, false),
Op::Punpckhbw => unpack(a, b, 8, true),
Op::Punpckhwd => unpack(a, b, 16, true),
Op::Punpckhdq => unpack(a, b, 32, true),
Op::Punpckhqdq => unpack(a, b, 64, true),
// Vector counts are the low 64 bits of the source.
_ => shift(op, a, b as u64),
}
}
fn low_mask(size: u8) -> u128 {
if size == 16 {
u128::MAX
} else {
(1 << (8 * u32::from(size))) - 1
}
}
/// Address of the memory operand, checked for 16-byte alignment where required.
fn aligned_address(cpu: &CpuState, insn: &Insn) -> Result<Option<u64>, ExitReason> {
let Some(operand) = insn.memory() else {
return Ok(None);
};
let address = address(cpu, &operand);
let unaligned = FORMS[usize::from(insn.form)].unaligned;
if insn.rm_size == 16 && !unaligned && !address.is_multiple_of(16) {
return Err(ExitReason::GeneralProtection);
}
Ok(Some(address))
}
fn read_vector(memory: &GuestMemory, address: u64, size: u8) -> Result<u128, ExitReason> {
if size < 16 {
return read_mem(memory, address, size).map(u128::from);
}
let mut bytes = [0; 16];
memory
.read_bytes(address, &mut bytes)
.map_err(ExitReason::MemoryFault)?;
Ok(u128::from_le_bytes(bytes))
}
fn write_vector(
memory: &mut GuestMemory,
address: u64,
size: u8,
value: u128,
) -> Result<(), ExitReason> {
if size < 16 {
return write_mem(memory, address, size, value as u64);
}
memory
.write_bytes(address, &value.to_le_bytes())
.map_err(ExitReason::MemoryFault)
}
fn xmm(reg: RegOperand) -> usize {
usize::from(reg.index)
}
/// Full XMM register, or zero-extended memory, named by ModRM `rm`.
fn read_rm(cpu: &CpuState, memory: &GuestMemory, insn: &Insn) -> Result<u128, ExitReason> {
match (aligned_address(cpu, insn)?, rm_operand(insn)?) {
(Some(address), _) => read_vector(memory, address, insn.rm_size),
(None, RmOperand::Reg(reg)) => Ok(cpu.xmm[xmm(reg)]),
(None, RmOperand::Mem(_)) => Err(ExitReason::IllegalInstruction(0)),
}
}
/// Execute a vector instruction. RIP is advanced by the caller.
pub(crate) fn execute(
cpu: &mut CpuState,
memory: &mut GuestMemory,
insn: &Insn,
) -> Result<(), ExitReason> {
let reg = xmm(insn.reg);
let in_memory = insn.memory().is_some();
match (insn.op, insn.encoding) {
(Op::Ldmxcsr, _) => {
let value = read_rm(cpu, memory, insn)? as u32;
if value & !Mxcsr::WRITABLE != 0 {
return Err(ExitReason::GeneralProtection);
}
cpu.mxcsr = Mxcsr(value);
}
(Op::Stmxcsr, _) => {
if let Some(address) = aligned_address(cpu, insn)? {
write_mem(memory, address, 4, u64::from(cpu.mxcsr.0))?;
}
}
(Op::Movd, Encoding::XmmGpr) => {
let value = match rm_operand(insn)? {
RmOperand::Reg(source) => read_reg(cpu, source, insn.size),
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), insn.size)?,
};
cpu.xmm[reg] = u128::from(value);
}
(Op::Movd, _) => {
let value = cpu.xmm[reg] as u64;
match rm_operand(insn)? {
RmOperand::Reg(target) => write_reg(cpu, target, insn.size, value),
RmOperand::Mem(operand) => {
write_mem(memory, address(cpu, &operand), insn.size, value)?;
}
}
}
(Op::Pinsrw, _) => {
let value = match rm_operand(insn)? {
RmOperand::Reg(source) => read_reg(cpu, source, 2),
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), 2)?,
};
let shift = 16 * (insn.imm & 7);
cpu.xmm[reg] = cpu.xmm[reg] & !(0xFFFF << shift) | u128::from(value) << shift;
}
(Op::Pextrw, _) => {
let value = lane(read_rm(cpu, memory, insn)?, 16, (insn.imm & 7) as u32);
write_reg(cpu, insn.reg, insn.size, value);
}
(Op::Movmskps | Op::Movmskpd | Op::Pmovmskb, _) => {
let bits = match insn.op {
Op::Movmskps => 32,
Op::Movmskpd => 64,
_ => 8,
};
let value = read_rm(cpu, memory, insn)?;
let signs = (0..128 / bits).fold(0, |out, index| {
out | (lane(value, bits, index) >> (bits - 1)) << index
});
write_reg(cpu, insn.reg, insn.size, signs);
}
// MOVHLPS and MOVLHPS are the register forms of these opcodes.
(Op::Movlps, Encoding::XmmRm) => {
let source = read_rm(cpu, memory, insn)?;
let low = if in_memory { source } else { source >> 64 };
cpu.xmm[reg] = cpu.xmm[reg] & !low_mask(8) | low;
}
(Op::Movhps, Encoding::XmmRm) => {
let source = read_rm(cpu, memory, insn)?;
cpu.xmm[reg] = cpu.xmm[reg] & low_mask(8) | source << 64;
}
(Op::Movhps, _) => {
if let Some(address) = aligned_address(cpu, insn)? {
write_vector(memory, address, 8, cpu.xmm[reg] >> 64)?;
}
}
// Scalar loads from memory clear the rest of the register; between
// registers MOVSS and MOVSD merge and MOVQ clears.
(Op::Movss | Op::Movsd, Encoding::XmmRm) if !in_memory => {
let mask = low_mask(insn.rm_size);
let source = read_rm(cpu, memory, insn)?;
cpu.xmm[reg] = cpu.xmm[reg] & !mask | source & mask;
}
(
Op::Movaps | Op::Movups | Op::Movdqa | Op::Movdqu | Op::Movss | Op::Movsd | Op::Movq,
Encoding::XmmRm,
) => {
cpu.xmm[reg] = read_rm(cpu, memory, insn)? & low_mask(insn.rm_size);
}
(_, Encoding::RmXmm) => {
let mask = low_mask(insn.rm_size);
let value = cpu.xmm[reg] & mask;
match (aligned_address(cpu, insn)?, rm_operand(insn)?) {
(Some(address), _) => write_vector(memory, address, insn.rm_size, value)?,
(None, RmOperand::Reg(target)) => {
let target = &mut cpu.xmm[xmm(target)];
*target = match insn.op {
Op::Movq => value,
_ => *target & !mask | value,
};
}
(None, RmOperand::Mem(_)) => return Err(ExitReason::IllegalInstruction(0)),
}
}
(_, Encoding::RmImmXmm) => {
if let RmOperand::Reg(target) = rm_operand(insn)? {
let target = &mut cpu.xmm[xmm(target)];
*target = match insn.op {
Op::Psrldq => shift_bytes(*target, insn.imm, false),
Op::Pslldq => shift_bytes(*target, insn.imm, true),
op => shift(op, *target, insn.imm),
};
}
}
(_, Encoding::XmmRmImm) => {
let source = read_rm(cpu, memory, insn)?;
let old = cpu.xmm[reg];
let imm = insn.imm;
cpu.xmm[reg] = match insn.op {
Op::Pshufd => shuffle_32(source, source, imm),
Op::Pshuflw => shuffle_16(source, imm, 0),
Op::Pshufhw => shuffle_16(source, imm, 4),
Op::Shufps => shuffle_32(old, source, imm),
_ => build(64, |index| {
let from = if index == 0 { old } else { source };
lane(from, 64, (imm >> index & 1) as u32)
}),
};
}
(op, _) => {
let source = read_rm(cpu, memory, insn)?;
cpu.xmm[reg] = packed(op, cpu.xmm[reg], source);
}
}
Ok(())
}
File diff suppressed because it is too large. Load diff
+83
View File
@@ -77,3 +77,86 @@ fn flag_and_byte_operations_match_llvm() {
assert_eq!(assembler.instructions(), [*word], "{text}");
}
}
#[test]
fn vector_operations_match_llvm() {
let cases: &[(&str, Emit, u32)] = &[
(
"ldr q1, [x19, #160]",
|a| a.ldr_q_uoff(1, 19, 160),
0x3dc02a61,
),
(
"str q0, [x19, #400]",
|a| a.str_q_uoff(0, 19, 400),
0x3d806660,
),
("fmov d1, x0", |a| a.fmov_d_from_x(1, 0), 0x9e670001),
("mov v1.d[1], x1", |a| a.ins_d1_from_x(1, 1), 0x4e181c21),
(
"and v0.16b, v1.16b, v2.16b",
|a| a.neon3(0x4e20_1c00, 0, 1, 2),
0x4e221c20,
),
(
"sub v31.2d, v30.2d, v29.2d",
|a| a.neon3(0x6ee0_8400, 31, 30, 29),
0x6efd87df,
),
(
"shl v0.8h, v1.8h, #0",
|a| a.shl_vector(0, 1, 16, 0),
0x4f105420,
),
(
"shl v0.8h, v1.8h, #15",
|a| a.shl_vector(0, 1, 16, 15),
0x4f1f5420,
),
(
"shl v2.4s, v3.4s, #31",
|a| a.shl_vector(2, 3, 32, 31),
0x4f3f5462,
),
(
"shl v4.2d, v5.2d, #63",
|a| a.shl_vector(4, 5, 64, 63),
0x4f7f54a4,
),
(
"ushr v0.8h, v1.8h, #1",
|a| a.ushr_vector(0, 1, 16, 1),
0x6f1f0420,
),
(
"ushr v0.8h, v1.8h, #16",
|a| a.ushr_vector(0, 1, 16, 16),
0x6f100420,
),
(
"ushr v2.4s, v3.4s, #32",
|a| a.ushr_vector(2, 3, 32, 32),
0x6f200462,
),
(
"ushr v4.2d, v5.2d, #64",
|a| a.ushr_vector(4, 5, 64, 64),
0x6f4004a4,
),
(
"sshr v0.8h, v1.8h, #16",
|a| a.sshr_vector(0, 1, 16, 16),
0x4f100420,
),
(
"sshr v2.4s, v3.4s, #5",
|a| a.sshr_vector(2, 3, 32, 5),
0x4f3b0462,
),
];
for (text, emit, word) in cases {
let mut assembler = Arm64Assembler::new();
emit(&mut assembler);
assert_eq!(assembler.instructions(), [*word], "{text}");
}
}
+51 -10
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""Assemble the original x86-64 integer fixture with the LLVM assembler.
"""Assemble the original x86-64 fixtures with the LLVM assembler.
generate write crates/loader/tests/x86/integer.txt
--check reassemble in memory and fail if the committed fixture differs
generate write integer.txt and vector.txt next to this file
--check reassemble in memory and fail if a committed fixture differs
Each output line is `<hex bytes> | <Intel-syntax text>`. The assembler is
`clang -target x86_64-apple-macos` and the bytes are read with `objdump -d`,
@@ -15,7 +15,7 @@ import sys
import tempfile
from pathlib import Path
OUT = Path(__file__).resolve().parent / "integer.txt"
HERE = Path(__file__).resolve().parent
LOW = "a c d b sp bp si di".split()
CONDITIONS = "o no b ae e ne be a s ns p np l ge le g".split()
PTR = {8: "byte", 16: "word", 32: "dword", 64: "qword"}
@@ -92,6 +92,46 @@ def cases():
return list(dict.fromkeys(out))
PACKED = """punpcklbw punpcklwd punpckldq punpcklqdq punpckhbw punpckhwd punpckhdq punpckhqdq
packsswb packssdw packuswb pcmpgtb pcmpgtw pcmpgtd pcmpeqb pcmpeqw pcmpeqd paddb paddw paddd paddq
psubb psubw psubd psubq paddsb paddsw paddusb paddusw psubsb psubsw psubusb psubusw pmullw pmulhw
pmulhuw pmuludq pmaddwd psadbw pavgb pavgw pminub pmaxub pminsw pmaxsw pand pandn por pxor andps
andpd andnps andnpd orps orpd xorps xorpd unpcklps unpcklpd unpckhps unpckhpd psllw pslld psllq
psrlw psrld psrlq psraw psrad movaps movapd movups movupd movdqa movdqu""".split()
def vector_cases():
wide, quad, dword = (f"{w} ptr [rsi + 4*rdi + 16]" for w in ("xmmword", "qword", "dword"))
word = "word ptr [rsi + 4*rdi + 16]"
out = []
for op in PACKED:
out += [f"{op} xmm3, xmm9", f"{op} xmm10, {wide}", f"{op} xmm2, xmm2"]
for op in "movaps movapd movups movupd movdqa movdqu movntdq movntps movntpd".split():
out.append(f"{op} {wide}, xmm11")
for op, width in (("movss", dword), ("movsd", quad), ("movq", quad)):
out += [f"{op} xmm3, xmm9", f"{op} xmm10, {width}", f"{op} {width}, xmm11"]
for op in "movlps movlpd movhps movhpd".split():
out += [f"{op} xmm3, {quad}", f"{op} {quad}, xmm9"]
out += ["movhlps xmm3, xmm9", "movlhps xmm10, xmm1", "movhlps xmm2, xmm2", "movlhps xmm2, xmm2"]
out += ["movd xmm3, r9d", "movd xmm12, eax", "movq xmm3, r9", "movd r9d, xmm3", "movd ebx, xmm12",
"movq r9, xmm3", f"movd xmm3, {dword}", f"movd {dword}, xmm9"]
for op in "movmskps movmskpd pmovmskb".split():
out += [f"{op} ebx, xmm9", f"{op} r10d, xmm3"]
for op, bits in (("w", 16), ("d", 32), ("q", 64)):
for name in ("psll", "psrl", "psra"):
if name + op != "psraq":
out += [f"{name}{op} xmm{3 + 6 * (n % 2)}, {n}" for n in (0, 1, 7, bits - 1, bits, 255)]
for op in ("pslldq", "psrldq"):
out += [f"{op} xmm9, {n}" for n in (0, 1, 5, 15, 16, 255)]
for op in "pshufd pshufhw pshuflw shufps shufpd".split():
out += [f"{op} xmm3, xmm9, {n}" for n in (0, 27, 78, 177, 255)]
out += [f"{op} xmm10, {wide}, 114", f"{op} xmm2, xmm2, 57"]
for n in (0, 3, 7):
out += [f"pinsrw xmm9, ebx, {n}", f"pinsrw xmm3, {word}, {n}", f"pextrw r9d, xmm3, {n}"]
out += [f"stmxcsr {dword}"]
return list(dict.fromkeys(out))
def assemble(lines):
with tempfile.TemporaryDirectory() as directory:
source, obj = Path(directory, "a.s"), Path(directory, "a.o")
@@ -108,12 +148,13 @@ def assemble(lines):
def main(argv):
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
sys.exit("usage: assemble.py generate|--check")
text = assemble(cases())
if argv[1] == "generate":
OUT.write_text(text)
elif OUT.read_text() != text:
sys.exit("integer.txt differs from the assembler output")
print(f"{text.count(chr(10))} instructions")
for name, lines in (("integer.txt", cases()), ("vector.txt", vector_cases())):
text = assemble(lines)
if argv[1] == "generate":
(HERE / name).write_text(text)
elif (HERE / name).read_text() != text:
sys.exit(f"{name} differs from the assembler output")
print(f"{name}: {len(lines)} instructions")
if __name__ == "__main__":
+374
View File
@@ -0,0 +1,374 @@
66 41 0f 60 d9 | punpcklbw xmm3, xmm9
66 44 0f 60 54 be 10 | punpcklbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 60 d2 | punpcklbw xmm2, xmm2
66 41 0f 61 d9 | punpcklwd xmm3, xmm9
66 44 0f 61 54 be 10 | punpcklwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 61 d2 | punpcklwd xmm2, xmm2
66 41 0f 62 d9 | punpckldq xmm3, xmm9
66 44 0f 62 54 be 10 | punpckldq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 62 d2 | punpckldq xmm2, xmm2
66 41 0f 6c d9 | punpcklqdq xmm3, xmm9
66 44 0f 6c 54 be 10 | punpcklqdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6c d2 | punpcklqdq xmm2, xmm2
66 41 0f 68 d9 | punpckhbw xmm3, xmm9
66 44 0f 68 54 be 10 | punpckhbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 68 d2 | punpckhbw xmm2, xmm2
66 41 0f 69 d9 | punpckhwd xmm3, xmm9
66 44 0f 69 54 be 10 | punpckhwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 69 d2 | punpckhwd xmm2, xmm2
66 41 0f 6a d9 | punpckhdq xmm3, xmm9
66 44 0f 6a 54 be 10 | punpckhdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6a d2 | punpckhdq xmm2, xmm2
66 41 0f 6d d9 | punpckhqdq xmm3, xmm9
66 44 0f 6d 54 be 10 | punpckhqdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6d d2 | punpckhqdq xmm2, xmm2
66 41 0f 63 d9 | packsswb xmm3, xmm9
66 44 0f 63 54 be 10 | packsswb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 63 d2 | packsswb xmm2, xmm2
66 41 0f 6b d9 | packssdw xmm3, xmm9
66 44 0f 6b 54 be 10 | packssdw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6b d2 | packssdw xmm2, xmm2
66 41 0f 67 d9 | packuswb xmm3, xmm9
66 44 0f 67 54 be 10 | packuswb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 67 d2 | packuswb xmm2, xmm2
66 41 0f 64 d9 | pcmpgtb xmm3, xmm9
66 44 0f 64 54 be 10 | pcmpgtb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 64 d2 | pcmpgtb xmm2, xmm2
66 41 0f 65 d9 | pcmpgtw xmm3, xmm9
66 44 0f 65 54 be 10 | pcmpgtw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 65 d2 | pcmpgtw xmm2, xmm2
66 41 0f 66 d9 | pcmpgtd xmm3, xmm9
66 44 0f 66 54 be 10 | pcmpgtd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 66 d2 | pcmpgtd xmm2, xmm2
66 41 0f 74 d9 | pcmpeqb xmm3, xmm9
66 44 0f 74 54 be 10 | pcmpeqb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 74 d2 | pcmpeqb xmm2, xmm2
66 41 0f 75 d9 | pcmpeqw xmm3, xmm9
66 44 0f 75 54 be 10 | pcmpeqw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 75 d2 | pcmpeqw xmm2, xmm2
66 41 0f 76 d9 | pcmpeqd xmm3, xmm9
66 44 0f 76 54 be 10 | pcmpeqd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 76 d2 | pcmpeqd xmm2, xmm2
66 41 0f fc d9 | paddb xmm3, xmm9
66 44 0f fc 54 be 10 | paddb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fc d2 | paddb xmm2, xmm2
66 41 0f fd d9 | paddw xmm3, xmm9
66 44 0f fd 54 be 10 | paddw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fd d2 | paddw xmm2, xmm2
66 41 0f fe d9 | paddd xmm3, xmm9
66 44 0f fe 54 be 10 | paddd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fe d2 | paddd xmm2, xmm2
66 41 0f d4 d9 | paddq xmm3, xmm9
66 44 0f d4 54 be 10 | paddq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d4 d2 | paddq xmm2, xmm2
66 41 0f f8 d9 | psubb xmm3, xmm9
66 44 0f f8 54 be 10 | psubb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f8 d2 | psubb xmm2, xmm2
66 41 0f f9 d9 | psubw xmm3, xmm9
66 44 0f f9 54 be 10 | psubw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f9 d2 | psubw xmm2, xmm2
66 41 0f fa d9 | psubd xmm3, xmm9
66 44 0f fa 54 be 10 | psubd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fa d2 | psubd xmm2, xmm2
66 41 0f fb d9 | psubq xmm3, xmm9
66 44 0f fb 54 be 10 | psubq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fb d2 | psubq xmm2, xmm2
66 41 0f ec d9 | paddsb xmm3, xmm9
66 44 0f ec 54 be 10 | paddsb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ec d2 | paddsb xmm2, xmm2
66 41 0f ed d9 | paddsw xmm3, xmm9
66 44 0f ed 54 be 10 | paddsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ed d2 | paddsw xmm2, xmm2
66 41 0f dc d9 | paddusb xmm3, xmm9
66 44 0f dc 54 be 10 | paddusb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f dc d2 | paddusb xmm2, xmm2
66 41 0f dd d9 | paddusw xmm3, xmm9
66 44 0f dd 54 be 10 | paddusw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f dd d2 | paddusw xmm2, xmm2
66 41 0f e8 d9 | psubsb xmm3, xmm9
66 44 0f e8 54 be 10 | psubsb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e8 d2 | psubsb xmm2, xmm2
66 41 0f e9 d9 | psubsw xmm3, xmm9
66 44 0f e9 54 be 10 | psubsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e9 d2 | psubsw xmm2, xmm2
66 41 0f d8 d9 | psubusb xmm3, xmm9
66 44 0f d8 54 be 10 | psubusb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d8 d2 | psubusb xmm2, xmm2
66 41 0f d9 d9 | psubusw xmm3, xmm9
66 44 0f d9 54 be 10 | psubusw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d9 d2 | psubusw xmm2, xmm2
66 41 0f d5 d9 | pmullw xmm3, xmm9
66 44 0f d5 54 be 10 | pmullw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d5 d2 | pmullw xmm2, xmm2
66 41 0f e5 d9 | pmulhw xmm3, xmm9
66 44 0f e5 54 be 10 | pmulhw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e5 d2 | pmulhw xmm2, xmm2
66 41 0f e4 d9 | pmulhuw xmm3, xmm9
66 44 0f e4 54 be 10 | pmulhuw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e4 d2 | pmulhuw xmm2, xmm2
66 41 0f f4 d9 | pmuludq xmm3, xmm9
66 44 0f f4 54 be 10 | pmuludq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f4 d2 | pmuludq xmm2, xmm2
66 41 0f f5 d9 | pmaddwd xmm3, xmm9
66 44 0f f5 54 be 10 | pmaddwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f5 d2 | pmaddwd xmm2, xmm2
66 41 0f f6 d9 | psadbw xmm3, xmm9
66 44 0f f6 54 be 10 | psadbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f6 d2 | psadbw xmm2, xmm2
66 41 0f e0 d9 | pavgb xmm3, xmm9
66 44 0f e0 54 be 10 | pavgb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e0 d2 | pavgb xmm2, xmm2
66 41 0f e3 d9 | pavgw xmm3, xmm9
66 44 0f e3 54 be 10 | pavgw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e3 d2 | pavgw xmm2, xmm2
66 41 0f da d9 | pminub xmm3, xmm9
66 44 0f da 54 be 10 | pminub xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f da d2 | pminub xmm2, xmm2
66 41 0f de d9 | pmaxub xmm3, xmm9
66 44 0f de 54 be 10 | pmaxub xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f de d2 | pmaxub xmm2, xmm2
66 41 0f ea d9 | pminsw xmm3, xmm9
66 44 0f ea 54 be 10 | pminsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ea d2 | pminsw xmm2, xmm2
66 41 0f ee d9 | pmaxsw xmm3, xmm9
66 44 0f ee 54 be 10 | pmaxsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ee d2 | pmaxsw xmm2, xmm2
66 41 0f db d9 | pand xmm3, xmm9
66 44 0f db 54 be 10 | pand xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f db d2 | pand xmm2, xmm2
66 41 0f df d9 | pandn xmm3, xmm9
66 44 0f df 54 be 10 | pandn xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f df d2 | pandn xmm2, xmm2
66 41 0f eb d9 | por xmm3, xmm9
66 44 0f eb 54 be 10 | por xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f eb d2 | por xmm2, xmm2
66 41 0f ef d9 | pxor xmm3, xmm9
66 44 0f ef 54 be 10 | pxor xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ef d2 | pxor xmm2, xmm2
41 0f 54 d9 | andps xmm3, xmm9
44 0f 54 54 be 10 | andps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 54 d2 | andps xmm2, xmm2
66 41 0f 54 d9 | andpd xmm3, xmm9
66 44 0f 54 54 be 10 | andpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 54 d2 | andpd xmm2, xmm2
41 0f 55 d9 | andnps xmm3, xmm9
44 0f 55 54 be 10 | andnps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 55 d2 | andnps xmm2, xmm2
66 41 0f 55 d9 | andnpd xmm3, xmm9
66 44 0f 55 54 be 10 | andnpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 55 d2 | andnpd xmm2, xmm2
41 0f 56 d9 | orps xmm3, xmm9
44 0f 56 54 be 10 | orps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 56 d2 | orps xmm2, xmm2
66 41 0f 56 d9 | orpd xmm3, xmm9
66 44 0f 56 54 be 10 | orpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 56 d2 | orpd xmm2, xmm2
41 0f 57 d9 | xorps xmm3, xmm9
44 0f 57 54 be 10 | xorps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 57 d2 | xorps xmm2, xmm2
66 41 0f 57 d9 | xorpd xmm3, xmm9
66 44 0f 57 54 be 10 | xorpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 57 d2 | xorpd xmm2, xmm2
41 0f 14 d9 | unpcklps xmm3, xmm9
44 0f 14 54 be 10 | unpcklps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 14 d2 | unpcklps xmm2, xmm2
66 41 0f 14 d9 | unpcklpd xmm3, xmm9
66 44 0f 14 54 be 10 | unpcklpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 14 d2 | unpcklpd xmm2, xmm2
41 0f 15 d9 | unpckhps xmm3, xmm9
44 0f 15 54 be 10 | unpckhps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 15 d2 | unpckhps xmm2, xmm2
66 41 0f 15 d9 | unpckhpd xmm3, xmm9
66 44 0f 15 54 be 10 | unpckhpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 15 d2 | unpckhpd xmm2, xmm2
66 41 0f f1 d9 | psllw xmm3, xmm9
66 44 0f f1 54 be 10 | psllw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f1 d2 | psllw xmm2, xmm2
66 41 0f f2 d9 | pslld xmm3, xmm9
66 44 0f f2 54 be 10 | pslld xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f2 d2 | pslld xmm2, xmm2
66 41 0f f3 d9 | psllq xmm3, xmm9
66 44 0f f3 54 be 10 | psllq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f3 d2 | psllq xmm2, xmm2
66 41 0f d1 d9 | psrlw xmm3, xmm9
66 44 0f d1 54 be 10 | psrlw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d1 d2 | psrlw xmm2, xmm2
66 41 0f d2 d9 | psrld xmm3, xmm9
66 44 0f d2 54 be 10 | psrld xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d2 d2 | psrld xmm2, xmm2
66 41 0f d3 d9 | psrlq xmm3, xmm9
66 44 0f d3 54 be 10 | psrlq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d3 d2 | psrlq xmm2, xmm2
66 41 0f e1 d9 | psraw xmm3, xmm9
66 44 0f e1 54 be 10 | psraw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e1 d2 | psraw xmm2, xmm2
66 41 0f e2 d9 | psrad xmm3, xmm9
66 44 0f e2 54 be 10 | psrad xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e2 d2 | psrad xmm2, xmm2
41 0f 28 d9 | movaps xmm3, xmm9
44 0f 28 54 be 10 | movaps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 28 d2 | movaps xmm2, xmm2
66 41 0f 28 d9 | movapd xmm3, xmm9
66 44 0f 28 54 be 10 | movapd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 28 d2 | movapd xmm2, xmm2
41 0f 10 d9 | movups xmm3, xmm9
44 0f 10 54 be 10 | movups xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 10 d2 | movups xmm2, xmm2
66 41 0f 10 d9 | movupd xmm3, xmm9
66 44 0f 10 54 be 10 | movupd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 10 d2 | movupd xmm2, xmm2
66 41 0f 6f d9 | movdqa xmm3, xmm9
66 44 0f 6f 54 be 10 | movdqa xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6f d2 | movdqa xmm2, xmm2
f3 41 0f 6f d9 | movdqu xmm3, xmm9
f3 44 0f 6f 54 be 10 | movdqu xmm10, xmmword ptr [rsi + 4*rdi + 16]
f3 0f 6f d2 | movdqu xmm2, xmm2
44 0f 29 5c be 10 | movaps xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f 29 5c be 10 | movapd xmmword ptr [rsi + 4*rdi + 16], xmm11
44 0f 11 5c be 10 | movups xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f 11 5c be 10 | movupd xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f 7f 5c be 10 | movdqa xmmword ptr [rsi + 4*rdi + 16], xmm11
f3 44 0f 7f 5c be 10 | movdqu xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f e7 5c be 10 | movntdq xmmword ptr [rsi + 4*rdi + 16], xmm11
44 0f 2b 5c be 10 | movntps xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f 2b 5c be 10 | movntpd xmmword ptr [rsi + 4*rdi + 16], xmm11
f3 41 0f 10 d9 | movss xmm3, xmm9
f3 44 0f 10 54 be 10 | movss xmm10, dword ptr [rsi + 4*rdi + 16]
f3 44 0f 11 5c be 10 | movss dword ptr [rsi + 4*rdi + 16], xmm11
f2 41 0f 10 d9 | movsd xmm3, xmm9
f2 44 0f 10 54 be 10 | movsd xmm10, qword ptr [rsi + 4*rdi + 16]
f2 44 0f 11 5c be 10 | movsd qword ptr [rsi + 4*rdi + 16], xmm11
f3 41 0f 7e d9 | movq xmm3, xmm9
f3 44 0f 7e 54 be 10 | movq xmm10, qword ptr [rsi + 4*rdi + 16]
66 44 0f d6 5c be 10 | movq qword ptr [rsi + 4*rdi + 16], xmm11
0f 12 5c be 10 | movlps xmm3, qword ptr [rsi + 4*rdi + 16]
44 0f 13 4c be 10 | movlps qword ptr [rsi + 4*rdi + 16], xmm9
66 0f 12 5c be 10 | movlpd xmm3, qword ptr [rsi + 4*rdi + 16]
66 44 0f 13 4c be 10 | movlpd qword ptr [rsi + 4*rdi + 16], xmm9
0f 16 5c be 10 | movhps xmm3, qword ptr [rsi + 4*rdi + 16]
44 0f 17 4c be 10 | movhps qword ptr [rsi + 4*rdi + 16], xmm9
66 0f 16 5c be 10 | movhpd xmm3, qword ptr [rsi + 4*rdi + 16]
66 44 0f 17 4c be 10 | movhpd qword ptr [rsi + 4*rdi + 16], xmm9
41 0f 12 d9 | movhlps xmm3, xmm9
44 0f 16 d1 | movlhps xmm10, xmm1
0f 12 d2 | movhlps xmm2, xmm2
0f 16 d2 | movlhps xmm2, xmm2
66 41 0f 6e d9 | movd xmm3, r9d
66 44 0f 6e e0 | movd xmm12, eax
66 49 0f 6e d9 | movq xmm3, r9
66 41 0f 7e d9 | movd r9d, xmm3
66 44 0f 7e e3 | movd ebx, xmm12
66 49 0f 7e d9 | movq r9, xmm3
66 0f 6e 5c be 10 | movd xmm3, dword ptr [rsi + 4*rdi + 16]
66 44 0f 7e 4c be 10 | movd dword ptr [rsi + 4*rdi + 16], xmm9
41 0f 50 d9 | movmskps ebx, xmm9
44 0f 50 d3 | movmskps r10d, xmm3
66 41 0f 50 d9 | movmskpd ebx, xmm9
66 44 0f 50 d3 | movmskpd r10d, xmm3
66 41 0f d7 d9 | pmovmskb ebx, xmm9
66 44 0f d7 d3 | pmovmskb r10d, xmm3
66 0f 71 f3 00 | psllw xmm3, 0
66 41 0f 71 f1 01 | psllw xmm9, 1
66 41 0f 71 f1 07 | psllw xmm9, 7
66 41 0f 71 f1 0f | psllw xmm9, 15
66 0f 71 f3 10 | psllw xmm3, 16
66 41 0f 71 f1 ff | psllw xmm9, 255
66 0f 71 d3 00 | psrlw xmm3, 0
66 41 0f 71 d1 01 | psrlw xmm9, 1
66 41 0f 71 d1 07 | psrlw xmm9, 7
66 41 0f 71 d1 0f | psrlw xmm9, 15
66 0f 71 d3 10 | psrlw xmm3, 16
66 41 0f 71 d1 ff | psrlw xmm9, 255
66 0f 71 e3 00 | psraw xmm3, 0
66 41 0f 71 e1 01 | psraw xmm9, 1
66 41 0f 71 e1 07 | psraw xmm9, 7
66 41 0f 71 e1 0f | psraw xmm9, 15
66 0f 71 e3 10 | psraw xmm3, 16
66 41 0f 71 e1 ff | psraw xmm9, 255
66 0f 72 f3 00 | pslld xmm3, 0
66 41 0f 72 f1 01 | pslld xmm9, 1
66 41 0f 72 f1 07 | pslld xmm9, 7
66 41 0f 72 f1 1f | pslld xmm9, 31
66 0f 72 f3 20 | pslld xmm3, 32
66 41 0f 72 f1 ff | pslld xmm9, 255
66 0f 72 d3 00 | psrld xmm3, 0
66 41 0f 72 d1 01 | psrld xmm9, 1
66 41 0f 72 d1 07 | psrld xmm9, 7
66 41 0f 72 d1 1f | psrld xmm9, 31
66 0f 72 d3 20 | psrld xmm3, 32
66 41 0f 72 d1 ff | psrld xmm9, 255
66 0f 72 e3 00 | psrad xmm3, 0
66 41 0f 72 e1 01 | psrad xmm9, 1
66 41 0f 72 e1 07 | psrad xmm9, 7
66 41 0f 72 e1 1f | psrad xmm9, 31
66 0f 72 e3 20 | psrad xmm3, 32
66 41 0f 72 e1 ff | psrad xmm9, 255
66 0f 73 f3 00 | psllq xmm3, 0
66 41 0f 73 f1 01 | psllq xmm9, 1
66 41 0f 73 f1 07 | psllq xmm9, 7
66 41 0f 73 f1 3f | psllq xmm9, 63
66 0f 73 f3 40 | psllq xmm3, 64
66 41 0f 73 f1 ff | psllq xmm9, 255
66 0f 73 d3 00 | psrlq xmm3, 0
66 41 0f 73 d1 01 | psrlq xmm9, 1
66 41 0f 73 d1 07 | psrlq xmm9, 7
66 41 0f 73 d1 3f | psrlq xmm9, 63
66 0f 73 d3 40 | psrlq xmm3, 64
66 41 0f 73 d1 ff | psrlq xmm9, 255
66 41 0f 73 f9 00 | pslldq xmm9, 0
66 41 0f 73 f9 01 | pslldq xmm9, 1
66 41 0f 73 f9 05 | pslldq xmm9, 5
66 41 0f 73 f9 0f | pslldq xmm9, 15
66 41 0f 73 f9 10 | pslldq xmm9, 16
66 41 0f 73 f9 ff | pslldq xmm9, 255
66 41 0f 73 d9 00 | psrldq xmm9, 0
66 41 0f 73 d9 01 | psrldq xmm9, 1
66 41 0f 73 d9 05 | psrldq xmm9, 5
66 41 0f 73 d9 0f | psrldq xmm9, 15
66 41 0f 73 d9 10 | psrldq xmm9, 16
66 41 0f 73 d9 ff | psrldq xmm9, 255
66 41 0f 70 d9 00 | pshufd xmm3, xmm9, 0
66 41 0f 70 d9 1b | pshufd xmm3, xmm9, 27
66 41 0f 70 d9 4e | pshufd xmm3, xmm9, 78
66 41 0f 70 d9 b1 | pshufd xmm3, xmm9, 177
66 41 0f 70 d9 ff | pshufd xmm3, xmm9, 255
66 44 0f 70 54 be 10 72 | pshufd xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
66 0f 70 d2 39 | pshufd xmm2, xmm2, 57
f3 41 0f 70 d9 00 | pshufhw xmm3, xmm9, 0
f3 41 0f 70 d9 1b | pshufhw xmm3, xmm9, 27
f3 41 0f 70 d9 4e | pshufhw xmm3, xmm9, 78
f3 41 0f 70 d9 b1 | pshufhw xmm3, xmm9, 177
f3 41 0f 70 d9 ff | pshufhw xmm3, xmm9, 255
f3 44 0f 70 54 be 10 72 | pshufhw xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
f3 0f 70 d2 39 | pshufhw xmm2, xmm2, 57
f2 41 0f 70 d9 00 | pshuflw xmm3, xmm9, 0
f2 41 0f 70 d9 1b | pshuflw xmm3, xmm9, 27
f2 41 0f 70 d9 4e | pshuflw xmm3, xmm9, 78
f2 41 0f 70 d9 b1 | pshuflw xmm3, xmm9, 177
f2 41 0f 70 d9 ff | pshuflw xmm3, xmm9, 255
f2 44 0f 70 54 be 10 72 | pshuflw xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
f2 0f 70 d2 39 | pshuflw xmm2, xmm2, 57
41 0f c6 d9 00 | shufps xmm3, xmm9, 0
41 0f c6 d9 1b | shufps xmm3, xmm9, 27
41 0f c6 d9 4e | shufps xmm3, xmm9, 78
41 0f c6 d9 b1 | shufps xmm3, xmm9, 177
41 0f c6 d9 ff | shufps xmm3, xmm9, 255
44 0f c6 54 be 10 72 | shufps xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
0f c6 d2 39 | shufps xmm2, xmm2, 57
66 41 0f c6 d9 00 | shufpd xmm3, xmm9, 0
66 41 0f c6 d9 1b | shufpd xmm3, xmm9, 27
66 41 0f c6 d9 4e | shufpd xmm3, xmm9, 78
66 41 0f c6 d9 b1 | shufpd xmm3, xmm9, 177
66 41 0f c6 d9 ff | shufpd xmm3, xmm9, 255
66 44 0f c6 54 be 10 72 | shufpd xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
66 0f c6 d2 39 | shufpd xmm2, xmm2, 57
66 44 0f c4 cb 00 | pinsrw xmm9, ebx, 0
66 0f c4 5c be 10 00 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 0
66 44 0f c5 cb 00 | pextrw r9d, xmm3, 0
66 44 0f c4 cb 03 | pinsrw xmm9, ebx, 3
66 0f c4 5c be 10 03 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 3
66 44 0f c5 cb 03 | pextrw r9d, xmm3, 3
66 44 0f c4 cb 07 | pinsrw xmm9, ebx, 7
66 0f c4 5c be 10 07 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 7
66 44 0f c5 cb 07 | pextrw r9d, xmm3, 7
0f ae 5c be 10 | stmxcsr dword ptr [rsi + 4*rdi + 16]
+18 -4
View File
@@ -921,15 +921,29 @@ fn every_fixture_instruction_matches_the_reference_in_both_engines() {
#[test]
fn every_declared_form_is_executed_by_a_fixture() {
let mut seen = BTreeSet::new();
for case in cases() {
let vector = include_str!("x86/vector.txt");
for line in FIXTURE.lines().chain(vector.lines()) {
let (hex, _) = line.split_once(" | ").unwrap();
let code: Vec<u8> = hex
.split(' ')
.map(|byte| u8::from_str_radix(byte, 16).unwrap())
.collect();
let insn = decode(ENTRY, |address| {
case.code.get((address - ENTRY) as usize).copied().ok_or(())
code.get((address - ENTRY) as usize).copied().ok_or(())
})
.unwrap();
.unwrap_or_else(|error| panic!("{line}: {error:?}"));
seen.insert(usize::from(insn.form));
}
// Control flow and exits are covered by the tests below.
let separate = [Op::Jcc, Op::Jmp, Op::Call, Op::Ret, Op::Hlt, Op::Syscall];
let separate = [
Op::Ldmxcsr,
Op::Jcc,
Op::Jmp,
Op::Call,
Op::Ret,
Op::Hlt,
Op::Syscall,
];
let mut missing: BTreeMap<&str, Vec<String>> = BTreeMap::new();
for (index, form) in FORMS.iter().enumerate() {
if !separate.contains(&form.op) && !seen.contains(&index) {
+798
View File
@@ -0,0 +1,798 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent tests of the SSE and SSE2 moves and packed integer forms.
//!
//! `tests/x86/vector.txt` pairs LLVM encodings with Intel-syntax text. The
//! reference below reads only the text and works on byte arrays with exact
//! integer arithmetic, following the operation sections of the Intel SDM Vol. 2.
//! It shares nothing with the registry, decoder, production semantics or NEON
//! lowering.
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Mxcsr, RFlags};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
const ENTRY: u64 = 0x1000;
const DATA: u64 = 0x2000;
/// Address of `[rsi + 4*rdi + 16]` with RSI = DATA and RDI = 4.
const OPERAND: u64 = DATA + 32;
type Bytes = [u8; 16];
struct Case {
code: Vec<u8>,
text: &'static str,
}
fn parse(fixture: &'static str) -> Vec<Case> {
fixture
.lines()
.map(|line| {
let (hex, text) = line.split_once(" | ").unwrap();
let code = hex
.split(' ')
.map(|b| u8::from_str_radix(b, 16).unwrap())
.collect();
Case { code, text }
})
.collect()
}
fn cases() -> Vec<Case> {
parse(include_str!("x86/vector.txt"))
}
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
/// Bytes biased towards lane boundaries and, at times, small shift counts.
fn vector(&mut self) -> Bytes {
const EDGES: [u8; 8] = [0, 1, 0x7F, 0x80, 0x81, 0xFE, 0xFF, 0x10];
let mode = self.next() % 4;
let mut out = [0; 16];
for byte in &mut out {
*byte = match mode {
0 => self.next() as u8,
_ => EDGES[(self.next() % 8) as usize],
};
}
if mode == 3 {
out[..8].copy_from_slice(&(self.next() % 70).to_le_bytes());
}
out
}
fn machine(&mut self) -> Machine {
let mut gpr = [0; 16];
for register in &mut gpr {
*register = self.next();
}
(gpr[6], gpr[7]) = (DATA, 4);
let mut xmm = [[0; 16]; 16];
for register in &mut xmm {
*register = self.vector();
}
Machine {
gpr,
xmm,
operand: self.vector(),
mxcsr: (self.next() & 0xFFFF) as u32,
}
}
}
#[derive(Clone)]
struct Machine {
gpr: [u64; 16],
xmm: [Bytes; 16],
operand: Bytes,
mxcsr: u32,
}
// --- reference -------------------------------------------------------------
/// Unsigned lanes of `width` bytes, lane 0 first.
fn split(bytes: &[u8], width: usize) -> Vec<i128> {
bytes
.chunks(width)
.map(|chunk| {
chunk
.iter()
.rev()
.fold(0, |value, byte| value * 256 + i128::from(*byte))
})
.collect()
}
fn join(lanes: &[i128], width: usize) -> Bytes {
let mut out = Vec::new();
for lane in lanes {
let mut rest = lane.rem_euclid(1i128 << (8 * width));
for _ in 0..width {
out.push((rest % 256) as u8);
rest /= 256;
}
}
out.try_into().unwrap()
}
fn negative_form(value: i128, width: usize) -> i128 {
let modulus = 1i128 << (8 * width);
if value >= modulus / 2 {
value - modulus
} else {
value
}
}
fn zip(a: &Bytes, b: &Bytes, width: usize, f: impl Fn(i128, i128) -> i128) -> Bytes {
let pairs: Vec<i128> = split(a, width)
.into_iter()
.zip(split(b, width))
.map(|(x, y)| f(x, y))
.collect();
join(&pairs, width)
}
fn zip_signed(a: &Bytes, b: &Bytes, width: usize, f: impl Fn(i128, i128) -> i128) -> Bytes {
zip(a, b, width, |x, y| {
f(negative_form(x, width), negative_form(y, width))
})
}
/// Lane width in bytes named by a mnemonic suffix.
fn suffix(name: &str) -> usize {
match name.as_bytes()[name.len() - 1] {
b'b' => 1,
b'w' => 2,
b'd' => 4,
_ => 8,
}
}
fn clamp(value: i128, low: i128, high: i128) -> i128 {
if value < low {
low
} else if value > high {
high
} else {
value
}
}
fn shifted(name: &str, value: &Bytes, count: i128) -> Bytes {
let width = suffix(name);
let bits = 8 * width as i128;
let lanes: Vec<i128> = split(value, width)
.into_iter()
.map(|lane| {
let mut lane = if name.starts_with("psra") {
negative_form(lane, width)
} else {
lane
};
for _ in 0..clamp(count, 0, bits) {
lane = if name.starts_with("psll") {
(lane * 2).rem_euclid(1 << bits)
} else {
lane.div_euclid(2) // floors, so negative lanes keep their sign
};
}
lane
})
.collect();
join(&lanes, width)
}
fn packed(name: &str, a: &Bytes, b: &Bytes) -> Bytes {
let canonical = match name {
"andps" | "andpd" => "pand",
"andnps" | "andnpd" => "pandn",
"orps" | "orpd" => "por",
"xorps" | "xorpd" => "pxor",
"unpcklps" => "punpckldq",
"unpcklpd" => "punpcklqdq",
"unpckhps" => "punpckhdq",
"unpckhpd" => "punpckhqdq",
other => other,
};
let name = canonical;
let width = suffix(name);
let top = 1i128 << (8 * width);
let truth = |value: bool| if value { -1 } else { 0 };
match name {
"pand" => zip(a, b, 1, |x, y| x & y),
"pandn" => zip(a, b, 1, |x, y| (255 - x) & y),
"por" => zip(a, b, 1, |x, y| x | y),
"pxor" => zip(a, b, 1, |x, y| x ^ y),
"paddb" | "paddw" | "paddd" | "paddq" => zip(a, b, width, |x, y| x + y),
"psubb" | "psubw" | "psubd" | "psubq" => zip(a, b, width, |x, y| x - y),
"paddsb" | "paddsw" => zip_signed(a, b, width, |x, y| clamp(x + y, -top / 2, top / 2 - 1)),
"psubsb" | "psubsw" => zip_signed(a, b, width, |x, y| clamp(x - y, -top / 2, top / 2 - 1)),
"paddusb" | "paddusw" => zip(a, b, width, |x, y| clamp(x + y, 0, top - 1)),
"psubusb" | "psubusw" => zip(a, b, width, |x, y| clamp(x - y, 0, top - 1)),
"pcmpeqb" | "pcmpeqw" | "pcmpeqd" => zip(a, b, width, |x, y| truth(x == y)),
"pcmpgtb" | "pcmpgtw" | "pcmpgtd" => zip_signed(a, b, width, |x, y| truth(x > y)),
"pminub" => zip(a, b, 1, |x, y| if x < y { x } else { y }),
"pmaxub" => zip(a, b, 1, |x, y| if x > y { x } else { y }),
"pminsw" => zip_signed(a, b, 2, |x, y| if x < y { x } else { y }),
"pmaxsw" => zip_signed(a, b, 2, |x, y| if x > y { x } else { y }),
"pavgb" | "pavgw" => zip(a, b, width, |x, y| (x + y + 1) / 2),
"pmullw" => zip(a, b, 2, |x, y| x * y),
"pmulhw" => zip_signed(a, b, 2, |x, y| (x * y).div_euclid(65536)),
"pmulhuw" => zip(a, b, 2, |x, y| x * y / 65536),
"pmuludq" => zip(a, b, 8, |x, y| (x % (1 << 32)) * (y % (1 << 32))),
"pmaddwd" => {
let (x, y) = (split(a, 2), split(b, 2));
let product = |i: usize| negative_form(x[i], 2) * negative_form(y[i], 2);
join(&[0, 2, 4, 6].map(|i| product(i) + product(i + 1)), 4)
}
"psadbw" => {
let difference = |i: usize| (i128::from(a[i]) - i128::from(b[i])).abs();
join(
&[(0..8).map(difference).sum(), (8..16).map(difference).sum()],
8,
)
}
"packsswb" | "packssdw" | "packuswb" => {
let from = if name == "packssdw" { 4 } else { 2 };
let half = 1i128 << (4 * from);
let (low, high) = if name == "packuswb" {
(0, half - 1)
} else {
(-half / 2, half / 2 - 1)
};
let lanes: Vec<i128> = split(a, from)
.into_iter()
.chain(split(b, from))
.map(|lane| clamp(negative_form(lane, from), low, high))
.collect();
join(&lanes, from / 2)
}
_ if name.starts_with("punpck") => {
let width = match &name[7..] {
"bw" => 1,
"wd" => 2,
"dq" => 4,
_ => 8,
};
let start = if name.as_bytes()[6] == b'h' { 8 } else { 0 };
let mut out = Vec::new();
for at in (start..start + 8).step_by(width) {
out.extend_from_slice(&a[at..at + width]);
out.extend_from_slice(&b[at..at + width]);
}
out.try_into().unwrap()
}
_ if name.starts_with("psll") || name.starts_with("psrl") || name.starts_with("psra") => {
shifted(name, a, split(&b[..8], 8)[0])
}
// Full-width loads.
"movaps" | "movapd" | "movups" | "movupd" | "movdqa" | "movdqu" => *b,
other => panic!("no reference for {other}"),
}
}
fn register(text: &str) -> Option<usize> {
text.strip_prefix("xmm")
.and_then(|index| index.parse().ok())
}
/// Index and width in bytes of a general register used by the fixture.
fn general(text: &str) -> Option<(usize, usize)> {
Some(match text {
"eax" => (0, 4),
"ebx" => (3, 4),
"r9d" => (9, 4),
"r10d" => (10, 4),
"r9" => (9, 8),
_ => return None,
})
}
fn reference(m: &mut Machine, text: &str) {
let (name, rest) = text.split_once(' ').unwrap();
let parts: Vec<&str> = rest.split(", ").collect();
let width = |text: &str| match text.split(' ').next().unwrap() {
"xmmword" => 16,
"qword" => 8,
"dword" => 4,
"word" => 2,
other => panic!("width {other}"),
};
if name == "stmxcsr" {
m.operand[..4].copy_from_slice(&m.mxcsr.to_le_bytes());
return;
}
let destination = parts[0];
if destination.contains(" ptr ") {
// Stores write exactly their operand width.
let source = m.xmm[register(parts[1]).unwrap()];
let start = if name.starts_with("movh") { 8 } else { 0 };
let bytes = width(destination);
m.operand[..bytes].copy_from_slice(&source[start..start + bytes]);
return;
}
let source_text = parts.get(1).copied().unwrap_or("");
let memory = source_text.contains(" ptr ");
if let Some((index, bytes)) = general(destination) {
let source = m.xmm[register(source_text).unwrap()];
let lanes = |width: usize| -> u64 {
split(&source, width)
.iter()
.enumerate()
.filter(|(_, lane)| **lane >= 1i128 << (8 * width - 1))
.map(|(at, _)| 1u64 << at)
.sum()
};
m.gpr[index] = match name {
"movmskps" => lanes(4),
"movmskpd" => lanes(8),
"pmovmskb" => lanes(1),
"pextrw" => split(&source, 2)[parts[2].parse::<usize>().unwrap()] as u64,
_ => split(&source, bytes)[0] as u64,
};
return;
}
let target = register(destination).unwrap();
let old = m.xmm[target];
if let Some((index, bytes)) = general(source_text) {
let value = m.gpr[index].to_le_bytes();
if name == "pinsrw" {
let at = 2 * parts[2].parse::<usize>().unwrap();
m.xmm[target][at..at + 2].copy_from_slice(&value[..2]);
} else {
let mut out = [0; 16];
out[..bytes].copy_from_slice(&value[..bytes]);
m.xmm[target] = out;
}
return;
}
if let Ok(count) = source_text.parse::<i128>() {
m.xmm[target] = match name {
"pslldq" | "psrldq" => {
let mut out = [0; 16];
for (at, byte) in out.iter_mut().enumerate() {
let from = at as i128 + if name == "pslldq" { -count } else { count };
if (0..16).contains(&from) {
*byte = old[from as usize];
}
}
out
}
_ => shifted(name, &old, count),
};
return;
}
let source = if memory {
m.operand
} else {
m.xmm[register(source_text).unwrap()]
};
let imm = parts.get(2).map(|text| text.parse::<usize>().unwrap());
let mut out = old;
match name {
"movss" | "movsd" | "movq" => {
let bytes = match name {
"movss" => 4,
_ => 8,
};
if memory || name == "movq" {
out = [0; 16];
}
out[..bytes].copy_from_slice(&source[..bytes]);
}
"movlps" | "movlpd" => out[..8].copy_from_slice(&source[..8]),
"movhps" | "movhpd" => out[8..].copy_from_slice(&source[..8]),
"movhlps" => out[..8].copy_from_slice(&source[8..]),
"movlhps" => out[8..].copy_from_slice(&source[..8]),
"movd" => {
out = [0; 16];
out[..4].copy_from_slice(&source[..4]);
}
"pinsrw" => {
let at = 2 * imm.unwrap();
out[at..at + 2].copy_from_slice(&source[..2]);
}
"pshufd" | "shufps" => {
for lane in 0..4 {
let from = imm.unwrap() / 4usize.pow(lane) % 4;
let lane = lane as usize;
let input = if name == "shufps" && lane < 2 {
old
} else {
source
};
out[4 * lane..4 * lane + 4].copy_from_slice(&input[4 * from..4 * from + 4]);
}
}
"pshuflw" | "pshufhw" => {
out = source;
let base = if name == "pshufhw" { 8 } else { 0 };
for lane in 0..4 {
let from = base + 2 * (imm.unwrap() / 4usize.pow(lane) % 4);
let to = base + 2 * lane as usize;
out[to..to + 2].copy_from_slice(&source[from..from + 2]);
}
}
"shufpd" => {
let low = 8 * (imm.unwrap() % 2);
let high = 8 * (imm.unwrap() / 2 % 2);
out[..8].copy_from_slice(&old[low..low + 8]);
out[8..].copy_from_slice(&source[high..high + 8]);
}
_ => out = packed(name, &old, &source),
}
m.xmm[target] = out;
}
// --- harness ---------------------------------------------------------------
fn load(machine: &Machine, code: &[u8], permissions: MemoryPermissions) -> (CpuState, GuestMemory) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
let mut data = vec![0xEE; 0x100];
data[32..48].copy_from_slice(&machine.operand);
memory
.map_region_with_data(DATA, 0x100, permissions, &data)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr = machine.gpr;
cpu.xmm = machine.xmm.map(u128::from_le_bytes);
cpu.mxcsr = Mxcsr(machine.mxcsr);
cpu.flags = RFlags {
cf: true,
zf: false,
sf: true,
of: false,
pf: true,
af: false,
};
(cpu, memory)
}
fn run(native: bool, cpu: &CpuState, memory: &mut GuestMemory, budget: usize) -> ExecutionResult {
if native {
DbtEngine::new(256 * 1024)
.unwrap()
.run(&mut cpu.clone(), memory, budget)
} else {
Interpreter::new(cpu.clone(), memory, budget).run()
}
}
fn data(memory: &GuestMemory) -> Vec<u8> {
let mut out = vec![0; 0x100];
memory.read_bytes(DATA, &mut out).unwrap();
out
}
#[test]
fn every_vector_fixture_matches_the_reference_in_both_engines() {
let mut random = Random(0xA076_1D64_78BD_642F);
let mut native_forms = 0;
for case in cases() {
let text = case.text;
let insn = decode(ENTRY, |address| {
case.code.get((address - ENTRY) as usize).copied().ok_or(())
})
.unwrap_or_else(|error| panic!("{text}: {error:?}"));
let native = is_native(&insn);
native_forms += usize::from(native);
let mut engine = DbtEngine::new(64 * 1024).unwrap();
for _ in 0..64 {
let machine = random.machine();
let mut expected = machine.clone();
reference(&mut expected, text);
let (mut wanted, _) = load(&expected, &case.code, MemoryPermissions::READ_WRITE);
wanted.rip = ENTRY + case.code.len() as u64;
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
let interpreted = Interpreter::new(cpu.clone(), &mut memory, 1).run();
let (mut dbt_cpu, mut dbt_memory) =
load(&machine, &case.code, MemoryPermissions::READ_WRITE);
let translated = engine.run(&mut dbt_cpu, &mut dbt_memory, 1);
for (result, memory) in [(interpreted, memory), (translated, dbt_memory)] {
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{text}");
assert_eq!(result.final_state, wanted, "{text} from {cpu:x?}");
let mut bytes = vec![0xEE; 0x100];
bytes[32..48].copy_from_slice(&expected.operand);
assert_eq!(data(&memory), bytes, "{text}");
}
}
assert_eq!(engine.metrics.interpreter_fallbacks == 0, native, "{text}");
}
assert!(native_forms > 150, "{native_forms}");
}
#[test]
fn aligned_operands_fault_and_unaligned_operands_do_not() {
let mut random = Random(0x51);
let mut checked = [0, 0];
for case in cases()
.into_iter()
.filter(|case| case.text.contains("xmmword ptr"))
{
let name = case.text.split(' ').next().unwrap();
let unaligned = ["movups", "movupd", "movdqu"].contains(&name);
checked[usize::from(unaligned)] += 1;
for offset in [1, 4, 8, 15] {
let mut machine = random.machine();
machine.gpr[6] = DATA + offset;
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
let before = data(&memory);
let result = run(native, &cpu, &mut memory, 1);
if unaligned {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{}",
case.text
);
if case.text.starts_with(&format!("{name} xmm10")) {
let mut bytes = [0; 16];
bytes.copy_from_slice(&before[32 + offset as usize..48 + offset as usize]);
assert_eq!(result.final_state.xmm[10], u128::from_le_bytes(bytes));
}
} else {
assert_eq!(
result.exit_reason,
ExitReason::GeneralProtection,
"{}",
case.text
);
assert_eq!(result.final_state, cpu, "{}", case.text);
assert_eq!(data(&memory), before, "{}", case.text);
}
}
}
}
assert!(checked[0] > 60 && checked[1] == 6, "{checked:?}");
}
#[test]
fn faulting_vector_accesses_change_nothing() {
for case in cases()
.into_iter()
.filter(|case| case.text.contains(" ptr "))
{
let store = case.text.split(", ").next().unwrap().contains(" ptr ");
let mut machine = Random(0x77).machine();
let mut runs = vec![(0x9000, MemoryPermissions::READ_WRITE)];
if store {
runs.push((DATA, MemoryPermissions::READ_ONLY));
}
for (base, permissions) in runs {
machine.gpr[6] = base;
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &case.code, permissions);
let before = data(&memory);
let result = run(native, &cpu, &mut memory, 1);
assert!(
matches!(result.exit_reason, ExitReason::MemoryFault(_)),
"{}",
case.text
);
assert_eq!(result.final_state, cpu, "{}", case.text);
assert_eq!(data(&memory), before, "{}", case.text);
}
}
}
}
#[test]
fn only_the_operand_width_is_accessed_at_the_end_of_a_region() {
for (code, width) in [
(&[0xF3u8, 0x0F, 0x10, 0x03][..], 4), // movss xmm0, [rbx]
(&[0xF2, 0x0F, 0x10, 0x03], 8), // movsd xmm0, [rbx]
(&[0xF3, 0x0F, 0x7E, 0x03], 8), // movq xmm0, [rbx]
(&[0x66, 0x0F, 0xC4, 0x03, 0x01], 2), // pinsrw xmm0, [rbx], 1
(&[0x0F, 0x10, 0x03], 16), // movups xmm0, [rbx]
(&[0x0F, 0x11, 0x03], 16), // movups [rbx], xmm0
] {
let end = DATA + 0x100;
for (address, ok) in [(end - width, true), (end - width + 1, false)] {
let mut machine = Random(0x99).machine();
machine.gpr[3] = address;
for native in [false, true] {
let (cpu, mut memory) = load(&machine, code, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(
result.exit_reason == ExitReason::StepLimitExceeded,
ok,
"{code:02X?}"
);
}
}
}
}
#[test]
fn register_store_encodings_write_the_rm_operand() {
// The store opcodes with a register operand, which assemblers rarely emit;
// `objdump` (LLVM) disassembles each as the text given here.
let cases: &[(&str, &[u8])] = &[
("movaps xmm3, xmm9", &[0x44, 0x0F, 0x29, 0xCB]),
("movups xmm3, xmm9", &[0x44, 0x0F, 0x11, 0xCB]),
("movdqa xmm3, xmm9", &[0x66, 0x44, 0x0F, 0x7F, 0xCB]),
("movdqu xmm3, xmm9", &[0xF3, 0x44, 0x0F, 0x7F, 0xCB]),
("movss xmm3, xmm9", &[0xF3, 0x44, 0x0F, 0x11, 0xCB]),
("movsd xmm3, xmm9", &[0xF2, 0x44, 0x0F, 0x11, 0xCB]),
("movq xmm3, xmm9", &[0x66, 0x44, 0x0F, 0xD6, 0xCB]),
];
let mut random = Random(0x1234);
for (text, code) in cases {
for _ in 0..32 {
let machine = random.machine();
let mut expected = machine.clone();
reference(&mut expected, text);
for native in [false, true] {
let (cpu, mut memory) = load(&machine, code, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(
result.final_state.xmm,
expected.xmm.map(u128::from_le_bytes),
"{text}"
);
}
}
}
}
#[test]
fn mxcsr_resets_loads_stores_and_rejects_reserved_bits() {
assert_eq!(CpuState::new(0, 0).mxcsr, Mxcsr(0x1F80));
assert_eq!(CpuState::default().mxcsr, Mxcsr(0x1F80));
for (value, accepted) in [
(0x1F80u32, true),
(0, true),
(0xFFFF, true),
(0x1_0000, false),
(0x8000_1F80, false),
] {
// ldmxcsr dword ptr [rbx]; stmxcsr dword ptr [rbx+4]
let code = [0x0F, 0xAE, 0x13, 0x0F, 0xAE, 0x5B, 0x04];
let mut machine = Random(0x55).machine();
machine.gpr[3] = OPERAND;
machine.operand[..4].copy_from_slice(&value.to_le_bytes());
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &code, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 2);
if accepted {
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(result.final_state.mxcsr, Mxcsr(value));
assert_eq!(memory.read_u32(OPERAND + 4).unwrap(), value);
} else {
assert_eq!(result.exit_reason, ExitReason::GeneralProtection);
assert_eq!(result.final_state, cpu);
}
}
}
}
#[test]
fn unsupported_vector_encodings_are_rejected() {
let rejected: &[&[u8]] = &[
&[0x0F, 0xFC, 0xC1], // paddb mm0, mm1 (MMX)
&[0x0F, 0x58, 0xC1], // addps xmm0, xmm1
&[0xF2, 0x0F, 0x58, 0xC1], // addsd xmm0, xmm1
&[0x66, 0x0F, 0x38, 0x00, 0xC1], // pshufb xmm0, xmm1
&[0xC5, 0xF9, 0xFC, 0xC1], // vpaddb (VEX)
&[0xF2, 0xF3, 0x0F, 0x10, 0xC1], // both mandatory prefixes
&[0x66, 0xF3, 0x0F, 0x10, 0xC1], // 66 with a scalar move
&[0x66, 0x0F, 0x12, 0xC1], // movlpd with a register source
&[0x0F, 0x13, 0xC1], // movlps register store
&[0x66, 0x0F, 0xE7, 0xC1], // movntdq with a register
&[0x66, 0x0F, 0x71, 0x11, 0x01], // psrlw with a memory operand
&[0x66, 0x0F, 0x71, 0xC1, 0x01], // 71 /0
&[0x0F, 0xAE, 0xD1], // ldmxcsr with a register
&[0x66, 0x0F, 0xAE, 0x13], // 66 with ldmxcsr
];
for code in rejected {
let padded = [code, &[0x90; 8][..]].concat();
let machine = Random(0x31).machine();
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &padded, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 1);
assert!(
matches!(result.exit_reason, ExitReason::IllegalInstruction(_)),
"{code:02X?}: {:?}",
result.exit_reason
);
assert_eq!(result.final_state, cpu, "{code:02X?}");
}
}
}
#[test]
fn mixed_vector_and_integer_sequences_agree() {
let vectors = cases();
let integers: Vec<Case> = parse(include_str!("x86/integer.txt"))
.into_iter()
.filter(|case| {
!["push", "pop", "leave", "div", "idiv"]
.iter()
.any(|name| case.text.starts_with(name))
&& case.text != "mov sil, dil"
})
.collect();
let mut random = Random(0xBEEF);
for round in 0..3000 {
let mut code = Vec::new();
let mut text = Vec::new();
for _ in 0..2 + random.next() % 30 {
let pool = if random.next().is_multiple_of(4) {
&integers
} else {
&vectors
};
let case = &pool[(random.next() % pool.len() as u64) as usize];
code.extend_from_slice(&case.code);
text.push(case.text);
}
code.push(0xF4);
let mut machine = random.machine();
if random.next().is_multiple_of(8) {
machine.gpr[6] += 1 + random.next() % 15; // misaligned operand
}
let budget = 1 + (random.next() % 40) as usize;
let (cpu, mut first) = load(&machine, &code, MemoryPermissions::READ_WRITE);
let interpreted = run(false, &cpu, &mut first, budget);
let (_, mut second) = load(&machine, &code, MemoryPermissions::READ_WRITE);
let translated = run(true, &cpu, &mut second, budget);
assert_eq!(
translated.exit_reason, interpreted.exit_reason,
"{round}: {text:#?}"
);
assert_eq!(
translated.instructions_executed, interpreted.instructions_executed,
"{round}: {text:#?}"
);
assert_eq!(
translated.final_state, interpreted.final_state,
"{round}: {text:#?}"
);
assert_eq!(data(&first), data(&second), "{round}: {text:#?}");
}
}
#[test]
fn vector_shift_counts_use_all_64_low_bits() {
// The count is the low quadword of the source; its high quadword is ignored.
for case in cases() {
let name = case.text.split(' ').next().unwrap();
let is_shift = ["psll", "psrl", "psra"]
.iter()
.any(|prefix| name.starts_with(prefix));
if !is_shift || !case.text.ends_with("xmm3, xmm9") {
continue;
}
for (low, high) in [
(1u64 << 32 | 1, 0u64),
(1 << 63, 0),
(u64::MAX, 0),
(3, u64::MAX),
] {
let mut machine = Random(0x41).machine();
machine.xmm[9][..8].copy_from_slice(&low.to_le_bytes());
machine.xmm[9][8..].copy_from_slice(&high.to_le_bytes());
let mut expected = machine.clone();
reference(&mut expected, case.text);
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 1);
let wanted = expected.xmm.map(u128::from_le_bytes);
assert_eq!(result.final_state.xmm, wanted, "{} by {low:#x}", case.text);
}
}
}
}
File diff suppressed because it is too large. Load diff
+22 -2
View File
@@ -21,6 +21,7 @@ Evidence below is local to the named host unless stated. Nothing here is indepen
| --- | --- | --- | --- |
| 1 | cpu: correct the sign- and zero-extension family | MOVZX/MOVSX/MOVSXD, MOV-immediate regressions, SXTW, 32-bit access width, RIP-relative and LEA addressing, self-contained prefix test | `tests/movsxd.rs`: 9 tests over 93 LLVM-assembled register forms and 32 MOV immediates, each run by the interpreter and as native translated code; 16 of 16 targeted mutations caught |
| 2 | cpu: share one generated decoder and store guest flags | Registry, generator, shared decoder and semantics, integer expansion, architectural DBT flags, truthful probe support | `tests/x86_integer.rs`, `tests/arm64_encodings.rs`, `tests/x86_generator`; 37 targeted mutations: 36 caught (4 only after new tests), and one equivalent, whose redundant check was removed |
| 3 | cpu: add SSE2 state, moves and packed integer forms | XMM and MXCSR state, mandatory prefixes, SSE/SSE2 moves and packed integer operations, NEON lowering | `tests/x86_vector.rs` (9 tests, 374 LLVM-assembled instructions, 64 states each), `tests/arm64_encodings.rs`; 35 targeted mutations: 34 caught (1 only after a new test) and one equivalent |
Encodings: `clang -target x86_64-apple-macos -c` and `clang -target arm64-apple-macos -c`, read back with `objdump -d`.
@@ -42,9 +43,28 @@ Coverage: 56 operations, 184 declared forms, 279 opcode slots. 985 LLVM-assemble
`dbt_bench` on an Apple M5 Pro, 101 samples, three runs each of `5ab561b` and milestone 2, middle run: interpreter 12.69 to 11.12 MIPS, cold DBT 10.43 to 8.86 MIPS, warm DBT 468.83 to 424.86 MIPS, native code 242,608 to 290,184 bytes. The slowdown comes with the new work of storing six flags and the shared decode; the earlier figures belong to code that computed wrong flags. Not optimized yet. These are synthetic and say nothing about games.
## Verification of milestone 3 (local, real exit codes)
Main `19bea60` (#278 and QA tooling) was merged first as `70f1793`; it does not touch `crates/loader`. `CHANGELOG.md` and `docs/README.md` conflicted and both sides were kept.
| Gate | Result |
| --- | --- |
| Formatting; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 429 passed, 0 failed, 22 ignored |
| `generate_x86.py --check`, `assemble.py --check`, generator tests (10) | exit 0 |
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests; claims, dependencies and native audits; release build | exit 0 |
| `scripts/test-gpu.sh`, `demo.sh`, `build-app.sh`, `--smoke-frame`, `--inspect` | exit 0; GPU 74 passed, 0 failed, 1 ignored |
| `scripts/assemble-fixture.sh --check` and ignored LLVM AMDGPU tests | not verified: need `llvm-mc` |
| Fuzz and mutation campaigns | not run |
The registry now has 139 operations, 306 forms and 401 opcode slots. `dbt_bench`, integer only, middle of three runs: interpreter 11.18, cold DBT 8.62 and warm DBT 430.19 MIPS, with the same 290,184 native bytes as milestone 2. No SIMD throughput benchmark exists yet.
## Known limitations
- Only the integer forms in `x86/instructions.toml` exist. XMM and MXCSR state, string instructions, RCL, RCR, SHLD, SHRD, LOCK, fences and atomics are unsupported.
- Only the forms in `x86/instructions.toml` exist. Floating-point arithmetic, compares and conversions, SSE3 and later, MMX, VEX, string instructions, RCL, RCR, SHLD, SHRD, LOCK, fences and atomics are unsupported.
- MXCSR is stored but nothing consults it yet.
- Packs, shuffles, high multiplies, PSADBW, sign-mask extraction, word insertion and extraction, byte shifts and shifts by a register count run through the shared semantics in the DBT.
- XMM6-XMM15 preservation across Win64 service calls has no test yet.
- 8- and 16-bit ALU operations, shifts, MUL, DIV and bit operations run through the shared semantics in the DBT, not as ARM64.
- The reference and the implementation share an author.
- New CPU checks are not in CI; `.github` was left unchanged.
@@ -56,4 +76,4 @@ Coverage: 56 operations, 184 declared forms, 279 opcode slots. 985 LLVM-assemble
## Next task
XMM and MXCSR architectural state with SSE2 moves and bitwise operations (#124, #125), then native lowering of 8- and 16-bit ALU and shifts, then runtime resolution and typed imports. Nothing in those areas is started.
Scalar and packed floating point (#127, #128): define x86 NaN selection, the default NaN, MXCSR rounding, DAZ, FTZ and sticky exception flags before lowering anything to NEON, because ARM differs in the default NaN, NaN propagation and underflow detection. Then runtime resolution and typed imports. Nothing in those areas is started.
+8 -4
View File
@@ -7,7 +7,7 @@ The static PE probe, the interpreter and the native ARM64 dynamic binary transla
| Registry | `crates/loader/x86/instructions.toml` | Opcode map, opcode, ModRM digit, operand encoding, size, immediate, flag effects and public reference. Data only. |
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, unknown vocabulary and flags both written and undefined. |
| Tables | `crates/loader/src/x86_table.rs` | Generated static tables. No metadata is parsed at run time. |
| Semantics | `crates/loader/src/x86_exec.rs` | Reviewed Rust primitives. Every instruction is all-or-nothing. |
| Semantics | `crates/loader/src/x86_exec.rs`, `x86_simd.rs` | Rust primitives for integer and vector forms. Every instruction is all-or-nothing. |
| Lowering | `crates/loader/src/dbt.rs` | ARM64 for the forms `is_native` accepts. Every other form calls the shared semantics and is counted in `DbtMetrics::interpreter_fallbacks`. |
## Adding a form
@@ -15,19 +15,23 @@ The static PE probe, the interpreter and the native ARM64 dynamic binary transla
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference.
2. Run `python3 crates/loader/generate_x86.py generate`.
3. Implement the operation in `x86_exec.rs`. Leave flags the manuals call undefined unchanged.
4. Add assembly text to `crates/loader/tests/x86/assemble.py`, run it with `generate`, and extend the reference in `tests/x86_integer.rs`. A declared form without a fixture fails `every_declared_form_is_executed_by_a_fixture`.
4. Add assembly text to `crates/loader/tests/x86/assemble.py`, run it with `generate`, and extend the reference in `tests/x86_integer.rs` or `tests/x86_vector.rs`. A declared form without a fixture fails `every_declared_form_is_executed_by_a_fixture`.
5. Lower it natively only if the ARM64 result and flags match. The same tests require native forms never to call the helper, and helper forms always to.
A declared form is decodable, not implemented. Count a form as supported only when the tests above cover it.
## Independence
The reference in `tests/x86_integer.rs` reads only LLVM assembly text. It does not use the encodings, registry, decoder or production semantics, and works bit by bit. It was written by the same contributor as the implementation, so independent review is still required.
The references in `tests/x86_integer.rs` and `tests/x86_vector.rs` read only LLVM assembly text. They do not use the encodings, registry, decoder or production semantics, and work bit by bit or on byte arrays. They were written by the same contributor as the implementation, so independent review is still required.
## Guest flags
The DBT stores CF, ZF, SF, OF, PF and AF in `CpuState::flags`. It skips the store only when a later instruction in the block overwrites all six before anything can read them, fault or leave the block.
## Vector state
XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `CpuState::mxcsr`. A mandatory 0x66, F3 or F2 prefix selects a form; the generator rejects an opcode where 0x66 could be both a mandatory prefix and an operand size. A 16-byte memory operand must be aligned unless its form says otherwise, and a violation exits with `GeneralProtection` before any memory access. Non-temporal stores are ordinary stores.
## Rejected on purpose
LOCK, REPNE, REP on anything but PAUSE, POPCNT, TZCNT and LZCNT, address-size overrides, FS combined with GS, 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, XMM state, atomics and fences. The DBT also refuses raw SYSCALL.
LOCK, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, FS combined with GS, 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, floating-point arithmetic and conversions, SSE3 and later, VEX, atomics and fences. The DBT also refuses raw SYSCALL.
+11
View File
@@ -56,6 +56,17 @@ class GenerateX86(unittest.TestCase):
self.rejects(self.form('op = "nop"\nopcode = 0xD7\ndigit = 1\nenc = "none"\nsize = "n"'), "digit needs")
self.rejects(self.form('op = "nop"\nopcode = 0xD4\ncount = 8\nenc = "none"\nsize = "n"'), "aligned")
def test_mandatory_prefix_cannot_shadow_an_operand_size(self):
# 66 0F AF is a 16-bit IMUL, and 66 0F 6E is a MOVD; neither may be both.
self.rejects(self.form('op = "paddb"\nmap = "0f"\nprefix = "66"\nopcode = 0xAF\nenc = "xmm_rm"\nsize = "x"\nsrc = "x"'), "both an operand size")
self.rejects(self.form('op = "imul2"\nmap = "0f"\nopcode = 0x6E\nenc = "reg_rm"\nsize = "v"'), "both an operand size")
def test_vector_operand_rules(self):
self.rejects(self.form('op = "paddb"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "x"'), "source size")
self.rejects(self.form('op = "paddb"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "v"\nsrc = "x"'), "XMM size")
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_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")