Compare commits

..
Author SHA1 Message Date
Ranveer Soni 2b858ab7c6 Merge branch 'main' into runtime/last-error-per-thread 2026-11-24 20:52:39 +05:30
Ranveer Soni 076f3e52aa Merge pull request #313 from elforeign/task/215-gpu-skip
scripts: restore the VOP1 oracle's GPU gate skip (#215)
2026-11-24 20:51:33 +05:30
Ranveer Soni e17e3bfc63 Merge pull request #314 from elforeign/task/215-sopk-oracle
isa, decoder, shader, ref: the sixteen SOPK integer forms through the semantic registry (#215)
2026-11-24 20:50:46 +05:30
Ranveer Soni 1915e2374c Merge pull request #297 from Swastickc/task/196-bit-scan-bit-test
loader: lower BSF, BSR and register BT in the ARM64 DBT (#196)
2026-11-24 20:49:54 +05:30
LanaCodes-Boop d5514aa9d8 Merge main into runtime/last-error-per-thread
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:10:25 -03:00
LanaCodes-Boop 7623fde0e7 loader: retire a guest thread's last error and test the per-TEB contract (#202)
main keeps the last error per TEB since #310. This adds the missing
retirement step, so a reused TEB address starts at zero, and two
conformance tests: a successful call keeps a nonzero error, and one
thread's failure does not reach another.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:10:20 -03:00
LanaCodes-Boop 3a14bd98ab Merge main into runtime/last-error-per-thread
main gained per-TEB last-error handling in #310. The conflicts in
CHANGELOG.md, services.rs and runtime_services.rs are resolved to main's
version, which drops this branch's separate thread-context mechanism.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:08:04 -03:00
elforeign d31b8ef20c scripts: restore the VOP1 oracle's GPU gate skip (#215)
The merge of #309 kept only the wide-compare skip, so scripts/test-gpu.sh
runs vop1_integer_forms_match_the_guide_on_native_metal, which fails until
the translator implements the VOP1 integer forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:07:18 -06:00
LanaCodes-Boop 6e64737021 loader: keep a guest last error per modeled thread context (#202)
ServicesState held one process-wide last-error value, so every modeled
guest thread would have read and overwritten the same slot. The running
context now owns the live slot and the others are parked by identifier,
bounded at 1,024. No guest thread is scheduled: the embedder switches
contexts between service calls.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 11:41:05 -03:00
Swastick Chowdhury 547b10250d loader: lower BSF, BSR and register BT in the ARM64 DBT (#196)
BSF, BSR and BT were decoded and executed by the interpreter, but every
occurrence of them in a translated block fell back to the shared semantics,
because `is_native` did not list them. The static probe therefore counted
them among the instructions the ARM64 DBT does not support.

Lower them to ARM64:

- BSF writes the index of the lowest set bit of the source and BSR the index
  of the highest set bit. The lowest set bit is the highest set bit of the
  reversed value, so BSF is `RBIT` followed by `CLZ`, and BSR is 63 minus the
  leading zero count.
- A zero source sets the zero flag and leaves the destination undefined, so
  the destination keeps its value. The interpreter and the independent
  reference apply the same rule, and the reference marks the destination as
  undefined so it is not compared.
- BT sets the carry flag from the tested bit, with the bit index masked to
  the operand width. The bit string is not modified.

Only the `0F A3` form of BT is lowered. The `0F BA` group form takes an
immediate index and may write memory, so it stays on the shared semantics and
is not advertised as natively supported.

The new encodings of RBIT, CLZ and LSLV were cross-checked against LLVM 23.1.6
`llvm-mc -show-encoding`.

The BSF, BSR and BT fixtures in `tests/x86/integer.txt` already cover the
16-bit, 32-bit and 64-bit forms with register and memory sources, and the
fixture test asserts that a native form never reaches the shared-semantics
helper, so those fixtures now exercise the new native path against the
independent reference. A new test pins the zero source, the highest bit, the
operand widths, the flag results and the masked bit index.

Closes #196

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 19:17:53 +05:30
6 changed files with 279 additions and 6 deletions

No files matched your search

+20
View File
@@ -306,6 +306,26 @@ impl Arm64Assembler {
);
}
/// RBIT Xd, Xn: reverse the bit order of the source.
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
}
/// CLZ Xd, Xn: count the leading zero bits of the source.
pub fn clz_64(&mut self, xd: u8, xn: u8) {
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
}
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) {
self.emit(
0x9ac2_2000
| ((u32::from(xm) & 0x1f) << 16)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(xd) & 0x1f),
);
}
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
self.emit(
+85
View File
@@ -330,10 +330,18 @@ pub fn is_translatable(insn: &Insn) -> bool {
/// [`DbtMetrics::interpreter_fallbacks`].
pub fn is_native(insn: &Insn) -> bool {
let wide = matches!(insn.size, 4 | 8);
// The bit scans work on any register or memory source, and the bit test
// needs the index in a register.
let scanned = matches!(insn.size, 2 | 4 | 8);
match insn.op {
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
Op::Cmov => wide,
Op::Bsf | Op::Bsr => scanned,
// Only the `0F A3` form has the bit index in a register. The `0F BA`
// group form takes an immediate index and may write memory, so it
// stays on the shared semantics.
Op::Bt => scanned && insn.encoding == Encoding::RmReg,
Op::Pop => insn.encoding == Encoding::OpReg,
Op::Mov
| Op::Movzx
@@ -500,6 +508,18 @@ impl Emitter<'_> {
}
}
/// Zero-extend the low `size` bytes of `xd` to the full 64-bit register.
///
/// An operation narrower than the register reads only the low bytes of its
/// source, so the bits above them must not take part in a bit scan.
fn zero_extend(&mut self, xd: u8, size: u8) {
match size {
8 => {}
4 => self.asm.mov_reg_32(xd, xd),
_ => self.asm.uxth_32(xd, xd),
}
}
/// Effective address into X1, clobbering X9.
fn effective_address(&mut self, operand: &MemOperand, with_segment: bool) {
let asm = &mut *self.asm;
@@ -1032,6 +1052,71 @@ impl Emitter<'_> {
self.load_condition(insn.condition);
self.store_rm(insn, X12, completed);
}
Op::Bsf | Op::Bsr => {
// BSF and BSR write the index of the lowest or the highest set
// bit of the source into the destination and set the zero flag
// when the source is zero (Intel SDM Volume 2B, "BSF" and
// "BSR"). A zero source leaves the destination undefined, so
// the destination keeps its value, which is the same rule the
// interpreter and the reference apply.
self.load_rm(X9, insn, completed);
self.zero_extend(X9, insn.size);
match insn.op {
// The lowest set bit is the highest set bit of the
// reversed value, so its index is the leading zero count
// of the reversed value.
Op::Bsf => {
self.asm.rbit_64(X10, X9);
self.asm.clz_64(X10, X10);
}
// The highest set bit sits at 63 minus the leading zero
// count.
_ => {
self.asm.clz_64(X10, X9);
self.asm.movz_64(X13, 63, 0);
self.asm.sub_reg_64(X10, X13, X10);
}
}
self.load_reg(X11, insn.reg);
self.asm.tst_reg_64(X9, X9);
// CSEL takes the first operand when the condition holds, so
// the index is the value that replaces the destination.
self.asm.csel_64(X11, X10, X11, Condition::Ne);
match insn.size {
// A 16-bit destination keeps the bits above it, so the
// register is merged rather than replaced.
2 => self.store_reg(insn.reg, insn.size, X11),
// A 32-bit or 64-bit destination is written in full. The
// index has no bits above the operand width, so this
// matches the interpreter's 32-bit write, and a zero
// source keeps the whole register unchanged.
_ => self.asm.str_uoff_64(X11, X19, reg_offset(insn.reg.index)),
}
if flags {
// The zero flag is set when the source is zero. The other
// flags are undefined and keep their value.
self.asm.cset_32(X12, Condition::Eq);
self.asm.strb_uoff(X12, X19, ZF);
}
}
Op::Bt => {
// BT sets the carry flag from the tested bit and leaves the
// other flags undefined (Intel SDM Volume 2B, "BT"). The bit
// index comes from the register operand and is masked to the
// operand width.
self.load_rm(X9, insn, completed);
self.zero_extend(X9, insn.size);
self.load_reg(X10, insn.reg);
self.asm.load_imm_64(X13, u64::from(8 * insn.size - 1));
self.asm.and_reg_64(X10, X10, X13);
self.asm.load_imm_64(X11, 1);
self.asm.lslv_64(X11, X11, X10);
self.asm.tst_reg_64(X9, X11);
if flags {
self.asm.cset_32(X12, Condition::Ne);
self.asm.strb_uoff(X12, X19, CF);
}
}
Op::Cmov => {
self.load_rm(X10, insn, completed);
self.load_reg(X9, insn.reg);
+15
View File
@@ -251,6 +251,21 @@ impl ServicesState {
.unwrap_or(0)
}
/// Forget the last-error value of a guest thread that has ended, so a
/// later thread given the same TEB address starts at zero. Returns
/// whether a nonzero value was dropped.
///
/// Each service call names its own TEB and the values sit behind one
/// lock, so calls for different threads may run concurrently. Retire a
/// TEB only once no service call for that thread is still running.
pub fn retire_thread_last_error(&self, teb: u64) -> bool {
self.last_errors
.lock()
.expect("guest last-error state")
.remove(&teb)
.is_some()
}
fn set_last_error(&self, teb: u64, error: u32) {
let mut errors = self.last_errors.lock().expect("guest last-error state");
if error == 0 {
+54 -4
View File
@@ -120,17 +120,24 @@ fn build(imports: &[(&str, Symbol)]) -> Image {
}
fn standard(clock: u64) -> (ImportRegistry, Arc<MockClock>) {
let clock = Arc::new(MockClock::new(clock));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone())));
let (registry, clock, _) = standard_with_state(clock);
(registry, clock)
}
fn standard_with_state(clock: u64) -> (ImportRegistry, Arc<MockClock>, Arc<ServicesState>) {
let clock = Arc::new(MockClock::new(clock));
let state = Arc::new(ServicesState::new(clock.clone()));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, state.clone());
(registry, clock, state)
}
/// A guest whose image imports every generated service from its own library.
struct Guest {
engine: DbtEngine,
memory: GuestMemory,
clock: Arc<MockClock>,
state: Arc<ServicesState>,
teb: u64,
/// Upper halves and XMM lanes of unrelated arguments hold this pattern.
xmm: [u128; 4],
@@ -151,7 +158,7 @@ impl Guest {
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let (mut registry, clock) = standard(0x01DA_0000_1234_5678);
let (mut registry, clock, state) = standard_with_state(0x01DA_0000_1234_5678);
let bound = registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap();
@@ -162,6 +169,7 @@ impl Guest {
engine,
memory,
clock,
state,
teb: 0,
xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4],
}
@@ -554,6 +562,48 @@ fn last_error_isolated_across_guest_thread_switches() {
assert_eq!(guest.last_error(), 6);
}
/// The last-error code is documented as kept per thread, and most functions
/// set it only when they fail (errhandlingapi.h GetLastError).
#[test]
fn a_successful_call_keeps_another_threads_error_and_its_own() {
let mut guest = Guest::new();
guest.teb = 0x10000;
assert_eq!(guest.call("VirtualAlloc", &[0, 0, 0x3000, 4]), 0);
assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER
guest.teb = 0x20000;
guest.call("SetLastError", &[0xFFFF_FFFF]);
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
assert_eq!(guest.call("GetCurrentThreadId", &[]), 0x4104);
assert_eq!(
guest.last_error(),
0xFFFF_FFFF,
"success keeps a nonzero error"
);
guest.teb = 0x10000;
assert_eq!(guest.last_error(), 87);
}
#[test]
fn a_retired_thread_starts_clean_when_its_teb_address_is_reused() {
let mut guest = Guest::new();
guest.teb = 0x10000;
guest.call("SetLastError", &[998]);
guest.teb = 0x20000;
guest.call("CloseHandle", &[0x1234]);
assert!(guest.state.retire_thread_last_error(0x10000));
assert!(!guest.state.retire_thread_last_error(0x10000));
assert!(
!guest.state.retire_thread_last_error(0x30000),
"a thread that never failed holds no value"
);
assert_eq!(guest.last_error(), 6, "the other thread is untouched");
guest.teb = 0x10000;
assert_eq!(guest.last_error(), 0);
guest.call("SetLastError", &[5]);
assert_eq!(guest.last_error(), 5);
}
#[test]
fn last_error_is_set_by_failures_and_by_the_guest() {
let mut guest = Guest::new();
+101
View File
@@ -1298,6 +1298,107 @@ fn division_accepts_exactly_the_representable_quotients() {
}
}
/// The bit scans and the bit test keep the destination and the flags where
/// the architecture puts them.
///
/// The expectations come from the Intel SDM Volume 2B, "BSF", "BSR" and "BT":
/// BSF writes the index of the lowest set bit of the source and BSR the index
/// of the highest set bit, and both set the zero flag when the source is
/// zero, in which case the destination is undefined and keeps its value. BT
/// sets the carry flag from the tested bit, leaves the other flags alone and
/// masks the bit index to the operand width.
///
/// The encodings are `bsf rbx, r9` (49 0F BC D9), `bsr rbx, r9` (49 0F BD
/// D9), `bt rbx, r9` (4C 0F A3 CB), `bsf ebx, r9d` (41 0F BC D9),
/// `bsr ebx, r9d` (41 0F BD D9), `bt ebx, r9d` (44 0F A3 CB), `bsf bx, r9w`
/// (66 41 0F BC D9) and `bt bx, r9w` (66 44 0F A3 CB), as produced by LLVM
/// 23.1.6 `llvm-mc -show-encoding`.
#[test]
fn bit_scans_and_bit_tests_follow_the_architecture() {
const BSF64: &[u8] = &[0x49, 0x0F, 0xBC, 0xD9]; // bsf rbx, r9
const BSR64: &[u8] = &[0x49, 0x0F, 0xBD, 0xD9]; // bsr rbx, r9
const BT64: &[u8] = &[0x4C, 0x0F, 0xA3, 0xCB]; // bt rbx, r9
const BSF32: &[u8] = &[0x41, 0x0F, 0xBC, 0xD9]; // bsf ebx, r9d
const BSR32: &[u8] = &[0x41, 0x0F, 0xBD, 0xD9]; // bsr ebx, r9d
const BT32: &[u8] = &[0x44, 0x0F, 0xA3, 0xCB]; // bt ebx, r9d
const BSF16: &[u8] = &[0x66, 0x41, 0x0F, 0xBC, 0xD9]; // bsf bx, r9w
const BT16: &[u8] = &[0x66, 0x44, 0x0F, 0xA3, 0xCB]; // bt bx, r9w
/// A machine with R9 and RBX set and every other register zero.
fn machine(source: u64, destination: u64) -> Machine {
let mut gpr = [0; 16];
gpr[3] = destination;
gpr[9] = source;
Machine {
gpr,
flags: Flags::default(),
operand: 0,
pushed: 0,
top: STACK_TOP,
}
}
// The lowest set bit of the source is the index BSF writes.
let (state, _, _) = run_both(&machine(0x0000_0000_0000_0028, 0xFFFF), BSF64, 1);
assert_eq!(state.gpr[3], 3);
assert!(!state.flags.zf);
// The highest set bit of the source is the index BSR writes.
let (state, _, _) = run_both(&machine(0x8000_0000_0000_0028, 0xFFFF), BSR64, 1);
assert_eq!(state.gpr[3], 63);
assert!(!state.flags.zf);
// A zero source sets the zero flag and leaves the destination alone.
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSF64, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
assert!(state.flags.zf);
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSR64, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
assert!(state.flags.zf);
// A 32-bit destination holds a 32-bit index and clears the half above it.
let (state, _, _) = run_both(&machine(0x0000_0028, 0xFFFF_FFFF_FFFF_FFFF), BSF32, 1);
assert_eq!(state.gpr[3], 3);
let (state, _, _) = run_both(&machine(0x8000_0000, 0xFFFF_FFFF_FFFF_FFFF), BSR32, 1);
assert_eq!(state.gpr[3], 31);
// A 16-bit destination keeps the bits above it.
let (state, _, _) = run_both(&machine(0x0100, 0xFFFF_FFFF_FFFF_FFFF), BSF16, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_0008);
// BT reports the tested bit in the carry flag and leaves the bit string
// alone.
let (state, _, _) = run_both(&machine(1, 0b1010), BT64, 1);
assert!(state.flags.cf);
assert_eq!(state.gpr[3], 0b1010);
let (state, _, _) = run_both(&machine(0, 0b1010), BT64, 1);
assert!(!state.flags.cf);
assert_eq!(state.gpr[3], 0b1010);
// The bit index is masked to the operand width, so 64 selects bit 0 of a
// 64-bit bit string and 32 selects bit 0 of a 32-bit one.
let (state, _, _) = run_both(&machine(64, 0b1), BT64, 1);
assert!(state.flags.cf);
let (state, _, _) = run_both(&machine(32, 0b1), BT32, 1);
assert!(state.flags.cf);
let (state, _, _) = run_both(&machine(16, 0b1), BT16, 1);
assert!(state.flags.cf);
// The bit scans and the register form of the bit test are lowered to
// ARM64 instead of falling back to the shared semantics.
for code in [BSF64, BSR64, BT64, BSF32, BSR32, BT32, BSF16, BT16] {
let insn = decode(ENTRY, |address| {
code.get((address - ENTRY) as usize).copied().ok_or(())
})
.expect("decode");
assert!(is_native(&insn), "{code:02X?} is not native");
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let (mut cpu, mut memory) = load(&machine(0x28, 0), code);
engine.run(&mut cpu, &mut memory, 1);
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{code:02X?}");
}
}
#[test]
fn pop_rsp_and_push_rsp_use_the_architectural_stack_pointer() {
let machine = Random(17).machine();
+4 -2
View File
@@ -53,6 +53,8 @@ timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test audio_
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run
# Oracles whose translator side has not landed are skipped by name until it does.
# Oracles whose translator side has not landed are skipped by name until it does
# (#215: the PR that translates the forms removes its skip).
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1 \
--skip vopc_wide_match_the_guide_on_native_metal
--skip vopc_wide_match_the_guide_on_native_metal \
--skip vop1_integer_forms_match_the_guide_on_native_metal