mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 14:10:43 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3bbc955bc |
No files matched your search
@@ -196,6 +196,7 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed the intermittent failure of the frame-loop memory-footprint test (#290). Each frame-loop session opened its own Metal command queue. The first command buffer on a queue makes the GPU driver allocate a working set for it (about 45 MiB on an Apple M5 with Metal validation), and the driver frees it asynchronously 10–50 ms after the queue is released, so the process footprint read right after a session ended depended on how far that release had got. Measured immediately after each of 50 destroys, it ranged from 45 to 96 MiB; the unchanged test failed 5 times in 30 runs, with up to 26 MiB of apparent growth. There was no leak: one second after each destroy the footprint was back at the same floor every time. Frame-loop sessions now share one process-wide Metal device and command queue, so the working set is allocated once and kept: the same readings stay within 93–98 MiB across 50 sessions, and the unchanged test passed 30 runs in a row (largest growth 0.31 MiB). The cost is that the process keeps that GPU memory (about 50 MiB with validation, 58 MiB total footprint without) after its first frame loop. A new 50-session test (normal completion, pause and resume, destroy while running) checks the readings stay within 16 MiB; it fails without the fix.
|
||||
- Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile.
|
||||
- Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame.
|
||||
- Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect.
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! the guest leaves its loop and halts.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
@@ -171,8 +171,8 @@ impl FrameLoop {
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.map_err(|e| format!("shader translation: {e}"))?;
|
||||
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
|
||||
// The session's GPU resources live on the guest thread, where the import runs.
|
||||
let gpu = shared_gpu()?;
|
||||
// The import runs on the guest thread, so the session's shader lives there too.
|
||||
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
@@ -268,7 +268,26 @@ impl FrameLoop {
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static GPU: RefCell<Option<(NativeCompute, String)>> = const { RefCell::new(None) };
|
||||
static GPU: RefCell<Option<(&'static NativeCompute, String)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// One Metal device and command queue shared by every frame-loop session (#290).
|
||||
///
|
||||
/// The first command buffer submitted on a queue makes the GPU driver allocate a
|
||||
/// working set for it (about 45 MiB on an Apple M5 with Metal validation), and the
|
||||
/// driver frees that memory asynchronously, 10–50 ms after the queue is released.
|
||||
/// A queue per session therefore allocated and freed it once per session, and the
|
||||
/// process footprint depended on how far that release had progressed. One queue
|
||||
/// for the process allocates the working set once and keeps it: bounded caching,
|
||||
/// not per-session churn. `NativeCompute` is `Send + Sync`, and rendering takes
|
||||
/// `&self`, so concurrent sessions can share it. A device that cannot be opened
|
||||
/// is reported to every session that asks.
|
||||
fn shared_gpu() -> Result<&'static NativeCompute, String> {
|
||||
static SHARED: OnceLock<Result<NativeCompute, String>> = OnceLock::new();
|
||||
SHARED
|
||||
.get_or_init(|| NativeCompute::new().map_err(|e| format!("Metal device: {e}")))
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
}
|
||||
|
||||
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
|
||||
|
||||
+139
-21
@@ -82,25 +82,6 @@ fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Statu
|
||||
}
|
||||
}
|
||||
|
||||
/// Footprint once it has stopped changing. After a session is destroyed, Metal gives
|
||||
/// back its memory asynchronously: measured on an Apple M5, a reading taken right after
|
||||
/// destroy was up to about 45 MiB above the floor it returned to within one second,
|
||||
/// every time. A single immediate reading therefore mixes in memory that is already on
|
||||
/// its way out. Read every 50 ms until two consecutive readings agree within 1 MiB
|
||||
/// (at most 5 s). A genuine leak still settles high, so it is still caught.
|
||||
fn settled_footprint() -> u64 {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut previous = footprint();
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let current = footprint();
|
||||
if current.abs_diff(previous) < 1 << 20 || Instant::now() >= deadline {
|
||||
return current;
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
|
||||
fn footprint() -> u64 {
|
||||
unsafe extern "C" {
|
||||
@@ -264,11 +245,11 @@ fn repeated_sessions_do_not_grow_the_memory_footprint() {
|
||||
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
|
||||
run();
|
||||
run();
|
||||
let baseline = settled_footprint();
|
||||
let baseline = footprint();
|
||||
for _ in 0..5 {
|
||||
run();
|
||||
}
|
||||
let after = settled_footprint();
|
||||
let after = footprint();
|
||||
let growth = after.saturating_sub(baseline);
|
||||
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
|
||||
assert!(
|
||||
@@ -276,3 +257,140 @@ fn repeated_sessions_do_not_grow_the_memory_footprint() {
|
||||
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression test for #290: the footprint read right after each destroy must stay
|
||||
/// flat across many sessions. Each session used to open its own Metal command queue,
|
||||
/// and the GPU driver frees a queue's working set (about 45 MiB on an Apple M5 with
|
||||
/// validation) asynchronously after release, so these readings swung by about 50 MiB
|
||||
/// from session to session. Sessions now share one queue. The mix of sessions covers
|
||||
/// normal completion, pause and resume, and destruction while running.
|
||||
#[test]
|
||||
fn fifty_sessions_keep_a_flat_footprint_after_each_destroy() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let one = |kind: usize| {
|
||||
let session = session();
|
||||
match kind {
|
||||
0 => {
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
|
||||
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
|
||||
}
|
||||
1 => {
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
|
||||
wait_until(session, "10 frames", |s| s.completed >= 10);
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
|
||||
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "a frame", |s| s.completed >= 1);
|
||||
}
|
||||
}
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
footprint()
|
||||
};
|
||||
one(0); // the first session allocates the shared queue's working set
|
||||
let readings: Vec<u64> = (0..50).map(|i| one(i % 3)).collect();
|
||||
let mib: Vec<u64> = readings.iter().map(|r| r >> 20).collect();
|
||||
println!("footprint after each destroy (MiB): {mib:?}");
|
||||
let median = |values: &[u64]| {
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_unstable();
|
||||
sorted[sorted.len() / 2]
|
||||
};
|
||||
// Sustained growth: the typical reading at the end against the start.
|
||||
let (start, end) = (median(&readings[..10]), median(&readings[40..]));
|
||||
assert!(
|
||||
end.saturating_sub(start) < 16 << 20,
|
||||
"footprint grew from {start} to {end} bytes (median of first and last ten sessions)"
|
||||
);
|
||||
// Per-session churn, the cause fixed in #290: with a queue per session, about half
|
||||
// of all readings sat some 45 MiB away from the median. With the shared queue,
|
||||
// a reading is still occasionally caught while the driver frees a batch of
|
||||
// per-frame render resources: graphics-tagged memory only, 16 to 44 MiB, gone
|
||||
// within about 100 ms, measured in 13 of 6,000 sessions (0.22%). Allowing two such
|
||||
// readings in 50 keeps a false failure near 1 in 5,000 runs while per-session
|
||||
// churn would exceed it every time.
|
||||
let centre = median(&readings);
|
||||
let outliers: Vec<u64> = readings
|
||||
.iter()
|
||||
.filter(|&&r| r.abs_diff(centre) >= 16 << 20)
|
||||
.map(|r| r >> 20)
|
||||
.collect();
|
||||
assert!(
|
||||
outliers.len() <= 2,
|
||||
"{} of 50 readings were 16 MiB or more from the median {} MiB: {outliers:?}",
|
||||
outliers.len(),
|
||||
centre >> 20
|
||||
);
|
||||
}
|
||||
|
||||
/// Two sessions render at the same time through the shared Metal queue (#290). Each
|
||||
/// must keep its own frame sequence and pixels, pausing one must not stop the other,
|
||||
/// and destroying one mid-run must not disturb the other.
|
||||
#[test]
|
||||
fn concurrent_sessions_share_the_queue_but_stay_isolated() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let (a, b) = (session(), session());
|
||||
assert_eq!(xenora_session_start_frame_loop(a, 400), XENORA_OK);
|
||||
assert_eq!(xenora_session_start_frame_loop(b, 250), XENORA_OK);
|
||||
wait_until(a, "session A started", |s| s.completed >= 5);
|
||||
wait_until(b, "session B started", |s| s.completed >= 5);
|
||||
|
||||
// Pausing A holds only A.
|
||||
assert_eq!(xenora_session_pause_frame_loop(a), XENORA_OK);
|
||||
let a_held = wait_until(a, "session A paused", |s| s.state == XENORA_LOOP_PAUSED);
|
||||
let b_before = status(b).completed;
|
||||
let b_moving = wait_until(b, "session B progress while A is paused", |s| {
|
||||
s.completed >= b_before + 20 || s.state != XENORA_LOOP_RUNNING
|
||||
});
|
||||
assert!(
|
||||
b_moving.completed > b_before,
|
||||
"B kept rendering while A was paused"
|
||||
);
|
||||
let a_still = status(a);
|
||||
assert_eq!(a_still.state, XENORA_LOOP_PAUSED);
|
||||
// At most the frame A was rendering when paused can still complete.
|
||||
assert!(a_still.completed <= a_held.completed + 1);
|
||||
assert_eq!(a_still.rgba.to_vec(), expected(a_still.frame_id));
|
||||
assert_eq!(xenora_session_resume_frame_loop(a), XENORA_OK);
|
||||
|
||||
// Both finish with their own counts and their own final frames.
|
||||
let a_done = wait_until(a, "session A finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
let b_done = wait_until(b, "session B finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(
|
||||
(a_done.state, a_done.completed, a_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 400, 399)
|
||||
);
|
||||
assert_eq!(
|
||||
(b_done.state, b_done.completed, b_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 250, 249)
|
||||
);
|
||||
assert_eq!(a_done.rgba.to_vec(), expected(399));
|
||||
assert_eq!(b_done.rgba.to_vec(), expected(249));
|
||||
assert_eq!(xenora_session_destroy(a), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(b), XENORA_OK);
|
||||
|
||||
// Destroying one running session leaves the other running to completion.
|
||||
let (c, d) = (session(), session());
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(c, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(xenora_session_start_frame_loop(d, 300), XENORA_OK);
|
||||
wait_until(c, "session C started", |s| s.completed >= 5);
|
||||
wait_until(d, "session D started", |s| s.completed >= 5);
|
||||
assert_eq!(xenora_session_destroy(c), XENORA_OK);
|
||||
let d_done = wait_until(d, "session D finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(
|
||||
(d_done.state, d_done.completed, d_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 300, 299)
|
||||
);
|
||||
assert_eq!(d_done.rgba.to_vec(), expected(299));
|
||||
assert_eq!(xenora_session_destroy(d), XENORA_OK);
|
||||
}
|
||||
@@ -306,26 +306,6 @@ 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(
|
||||
|
||||
@@ -330,18 +330,10 @@ 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
|
||||
@@ -508,18 +500,6 @@ 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;
|
||||
@@ -1052,71 +1032,6 @@ 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);
|
||||
|
||||
@@ -1298,107 +1298,6 @@ 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();
|
||||
|
||||
Reference in new issue
Block a user