Compare commits

...
Author SHA1 Message Date
Swastick Chowdhury e3bbc955bc ffi: share one Metal device and queue across frame-loop sessions (#290)
Each frame-loop session opened its own Metal command queue. The GPU
driver allocates a per-queue working set on the first command buffer
(about 45 MiB on an Apple M5 with validation) and frees it
asynchronously 10-50 ms after the queue is released, so the footprint
read right after a session ended swung by about 50 MiB and the
repeated-sessions footprint test failed intermittently (5 of 30 runs).
There was no leak. Sessions now share one process-wide NativeCompute,
which is Send + Sync, so the working set is allocated once and kept.

Remove the settled_footprint wait added in #292: the original test
measures the immediate footprint again. Add a 50-session regression
test (completion, pause and resume, destroy while running) and a
concurrent two-session test for shared-queue correctness and session
isolation.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 19:07:18 +05:30
Ranveer Soni c7351c846d Merge pull request #291 from Swastickc/task/289-segment-tests
loader: restore and complete FS/GS segment-override tests (#289)
2026-11-24 18:13:09 +05:30
Ranveer Soni 78d52c0eeb Merge pull request #292 from Swastickc/task/290-footprint-settle
test(ffi): read a settled memory footprint in the frame-loop test (#290)
2026-11-24 18:12:55 +05:30
Ranveer Soni 4ebbd4767f Merge pull request #288 from jelly013/cpu-runtime-continuation
CPU and runtime: shared x86-64 decoder, SSE2, exact floating point and typed imports
2026-11-24 18:12:23 +05:30
Swastick Chowdhury 5a6a3b3e4f test(ffi): read a settled memory footprint in the frame-loop test (#290)
After a session is destroyed, Metal returns its memory asynchronously;
an immediate reading can sit up to about 45 MiB above the floor it
returns to within a second. Read the footprint until two consecutive
readings agree within 1 MiB (at most 5 s) for both the baseline and the
final sample. The 16 MiB threshold and Metal validation are unchanged,
and an injected per-session leak still fails the test.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 18:08:35 +05:30
Swastick Chowdhury 8cae9772b6 loader: restore and complete FS/GS segment-override tests (#289)
Restore the six #280 regression tests that the merge resolving #280's
conflict with #283 removed. Add FS and GS RIP-relative loads and stores
with positive and negative displacements, a differential run comparing
the native DBT and interpreter registers and memory bytes, and
RIP-relative faults reporting the segment-adjusted address. Make the
existing differential test compare both paths' memory.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 18:08:32 +05:30
4 changed files with 580 additions and 4 deletions

No files matched your search

+1
View File
@@ -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.
+23 -4
View File
@@ -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.
+137
View File
@@ -257,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);
}
+419
View File
@@ -1763,4 +1763,423 @@ mod tests {
]
);
}
// FS/GS segment override regression tests from #280 (#72), restored after a
// merge-conflict resolution dropped them.
/// A segment-relative store and load through the FS base.
///
/// The encodings are `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00)
/// and `mov rdx, [fs:0x8]` (64 48 8B 14 25 08 00 00 00), as produced by
/// LLVM 23.1.6 `llvm-mc -show-encoding`. The SIB byte 0x25 selects "no
/// index" and "no base", so the address is the FS base plus the
/// displacement 8.
///
/// Per Intel SDM Volume 3A section 3.4.4 the linear address is
/// `(FS or GS).base + index + displacement`, so the store must land at
/// `FS_BASE + 8`.
#[test]
fn fs_segment_override_adds_the_fs_base_to_the_address() {
let code = [
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
0x64, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [fs:0x8]
0xF4, // hlt
];
let (mut engine, mut cpu, mut memory) = fixture(&code);
const FS_BASE: u64 = 0x7000;
const GS_BASE: u64 = 0x8000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
// The store landed at the FS base plus the displacement, not at the
// bare displacement and not at the GS base. The bare displacement
// address 8 is not mapped at all, so reaching it would have faulted.
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), STORED_VALUE);
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), 0);
// The load read back the same location.
assert_eq!(result.final_state.get(Register::Rdx), STORED_VALUE);
}
/// A RIP-relative segment-relative store adds the segment base too.
///
/// The encoding is `mov [fs:(%rip)], rbx` (64 48 89 1D 00 00 00 00), as
/// produced by LLVM 23.1.6 `llvm-mc -show-encoding`. The displacement is
/// zero, so the address is the address of the next instruction plus the
/// FS base.
///
/// The segment base is added to the effective address for every addressing
/// form, so this must land at `FS_BASE + ENTRY + 8` and not at the bare
/// RIP-relative address.
#[test]
fn rip_relative_segment_override_adds_the_segment_base() {
let code = [
0x64, 0x48, 0x89, 0x1D, 0x00, 0x00, 0x00, 0x00, // mov [fs:(%rip)], rbx
0xF4, // hlt
];
let (mut engine, mut cpu, mut memory) = fixture(&code);
const FS_BASE: u64 = 0x7000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
cpu.fs_base = FS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
// The segment-adjusted address is FS_BASE + ENTRY + 8, so the region
// has to reach that far.
memory
.map_region(FS_BASE, 0x2000, MemoryPermissions::READ_WRITE)
.unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
// The instruction is 8 bytes long, so the next instruction is at
// ENTRY + 8 and the displacement of zero makes that the offset.
assert_eq!(memory.read_u64(FS_BASE + ENTRY + 8).unwrap(), STORED_VALUE);
}
/// The two execution paths must agree on segment-relative addressing.
///
/// The native DBT translator and the software interpreter are separate
/// implementations of the same guest semantics, so a program that uses a
/// segment override must produce the same result and the same memory
/// writes under both.
///
/// The encodings are `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00),
/// `mov [gs:0x10], rbx` (65 48 89 1C 25 10 00 00 00),
/// `mov rdx, [fs:0x8]` (64 48 8B 14 25 08 00 00 00) and
/// `mov rsi, [gs:0x10]` (65 48 8B 34 25 10 00 00 00), as produced by
/// LLVM 23.1.6 `llvm-mc -show-encoding`.
#[test]
fn interpreter_and_native_dbt_agree_on_segment_relative_addressing() {
const CODE: [u8; 37] = [
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
0x65, 0x48, 0x89, 0x1C, 0x25, 0x10, 0x00, 0x00, 0x00, // mov [gs:0x10], rbx
0x64, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [fs:0x8]
0x65, 0x48, 0x8B, 0x34, 0x25, 0x10, 0x00, 0x00, 0x00, // mov rsi, [gs:0x10]
0xF4, // hlt
];
const FS_BASE: u64 = 0x7000;
const GS_BASE: u64 = 0x8000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
// The native DBT path.
let (mut engine, mut cpu, mut memory) = fixture(&CODE);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let native = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(native.exit_reason, ExitReason::Halt);
let native_memory = memory;
// The software interpreter path over the same program.
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, CODE.len(), MemoryPermissions::READ_EXECUTE, &CODE)
.unwrap();
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
let mut interp = crate::cpu::Interpreter::new(cpu, &mut memory, 16);
let interpreted = interp.run();
assert_eq!(interpreted.exit_reason, native.exit_reason);
assert_eq!(interpreted.final_state, native.final_state);
assert_eq!(
memory.read_u64(FS_BASE + 8).unwrap(),
native.final_state.get(Register::Rbx)
);
assert_eq!(
memory.read_u64(GS_BASE + 0x10).unwrap(),
native.final_state.get(Register::Rbx)
);
// The bytes each path left in guest memory must be identical, not only the
// two words checked above.
for base in [FS_BASE, GS_BASE] {
assert_eq!(
region_bytes(&native_memory, base, 0x100),
region_bytes(&memory, base, 0x100),
"segment region at {base:#x}"
);
}
}
fn region_bytes(memory: &GuestMemory, base: u64, len: usize) -> Vec<u8> {
let mut bytes = vec![0; len];
memory.read_bytes(base, &mut bytes).unwrap();
bytes
}
/// FS and GS RIP-relative loads and stores with positive and negative
/// displacements. The effective address is the segment base plus the address of
/// the next instruction plus the signed disp32 (AMD64 APM vol. 1, RIP-relative
/// addressing; FS/GS overrides still apply in 64-bit mode). Each expected address
/// below is worked out by hand from that rule.
const RIP_CODE: [u8; 33] = [
// 0x1000: mov fs:[rip - 0x100], rbx -> FS + 0x1008 - 0x100 = FS + 0x0F08
0x64, 0x48, 0x89, 0x1D, 0x00, 0xFF, 0xFF, 0xFF,
// 0x1008: mov gs:[rip + 0x40], rbx -> GS + 0x1010 + 0x40 = GS + 0x1050
0x65, 0x48, 0x89, 0x1D, 0x40, 0x00, 0x00, 0x00,
// 0x1010: mov rdx, fs:[rip - 0x28] -> FS + 0x1018 - 0x28 = FS + 0x0FF0
0x64, 0x48, 0x8B, 0x15, 0xD8, 0xFF, 0xFF, 0xFF,
// 0x1018: mov rsi, gs:[rip + 0x20] -> GS + 0x1020 + 0x20 = GS + 0x1040
0x65, 0x48, 0x8B, 0x35, 0x20, 0x00, 0x00, 0x00, // 0x1020: hlt
0xF4,
];
const RIP_FS: u64 = 0x10_0000;
const RIP_GS: u64 = 0x20_0000;
const RIP_STORED: u64 = 0x0102_0304_0506_0708;
const RIP_FS_SEED: u64 = 0xA1A2_A3A4_A5A6_A7A8;
const RIP_GS_SEED: u64 = 0xB1B2_B3B4_B5B6_B7B8;
fn rip_setup(cpu: &mut CpuState, memory: &mut GuestMemory) {
cpu.fs_base = RIP_FS;
cpu.gs_base = RIP_GS;
cpu.set(Register::Rbx, RIP_STORED);
for base in [RIP_FS, RIP_GS] {
memory
.map_region(base, 0x2000, MemoryPermissions::READ_WRITE)
.unwrap();
}
memory.write_u64(RIP_FS + 0x0FF0, RIP_FS_SEED).unwrap();
memory.write_u64(RIP_GS + 0x1040, RIP_GS_SEED).unwrap();
}
fn check_rip_results(state: &CpuState, memory: &GuestMemory, path: &str) {
assert_eq!(
memory.read_u64(RIP_FS + 0x0F08).unwrap(),
RIP_STORED,
"{path}: FS store, negative disp"
);
assert_eq!(
memory.read_u64(RIP_GS + 0x1050).unwrap(),
RIP_STORED,
"{path}: GS store, positive disp"
);
assert_eq!(
state.get(Register::Rdx),
RIP_FS_SEED,
"{path}: FS load, negative disp"
);
assert_eq!(
state.get(Register::Rsi),
RIP_GS_SEED,
"{path}: GS load, positive disp"
);
}
#[test]
fn fs_and_gs_rip_relative_loads_and_stores_use_the_segment_base() {
let (mut engine, mut cpu, mut memory) = fixture(&RIP_CODE);
rip_setup(&mut cpu, &mut memory);
let native = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(native.exit_reason, ExitReason::Halt);
check_rip_results(&native.final_state, &memory, "native DBT");
}
#[test]
fn interpreter_and_native_dbt_agree_on_rip_relative_segment_accesses() {
let (mut engine, mut cpu, mut native_memory) = fixture(&RIP_CODE);
rip_setup(&mut cpu, &mut native_memory);
let native = engine.run(&mut cpu, &mut native_memory, 16);
let (_, mut cpu, mut memory) = fixture(&RIP_CODE);
rip_setup(&mut cpu, &mut memory);
let interpreted = crate::cpu::Interpreter::new(cpu, &mut memory, 16).run();
assert_eq!(interpreted.exit_reason, native.exit_reason);
assert_eq!(interpreted.final_state, native.final_state);
check_rip_results(&interpreted.final_state, &memory, "interpreter");
for base in [RIP_FS, RIP_GS] {
assert_eq!(
region_bytes(&native_memory, base, 0x2000),
region_bytes(&memory, base, 0x2000),
"segment region at {base:#x}"
);
}
}
#[test]
fn rip_relative_segment_faults_report_the_segment_adjusted_address() {
// One instruction per case, with nothing mapped at either segment base.
let cases: [(&[u8], u64); 4] = [
// mov fs:[rip - 0x10], rbx -> FS + 0x1008 - 0x10
(
&[0x64, 0x48, 0x89, 0x1D, 0xF0, 0xFF, 0xFF, 0xFF, 0xF4],
RIP_FS + 0x0FF8,
),
// mov gs:[rip + 0x30], rbx -> GS + 0x1008 + 0x30
(
&[0x65, 0x48, 0x89, 0x1D, 0x30, 0x00, 0x00, 0x00, 0xF4],
RIP_GS + 0x1038,
),
// mov rdx, fs:[rip - 0x800] -> FS + 0x1008 - 0x800
(
&[0x64, 0x48, 0x8B, 0x15, 0x00, 0xF8, 0xFF, 0xFF, 0xF4],
RIP_FS + 0x0808,
),
// mov rsi, gs:[rip + 0x8] -> GS + 0x1008 + 0x8
(
&[0x65, 0x48, 0x8B, 0x35, 0x08, 0x00, 0x00, 0x00, 0xF4],
RIP_GS + 0x1010,
),
];
for (code, fault) in cases {
let expected = ExitReason::MemoryFault(MemoryError::UnmappedAddress(fault));
let (mut engine, mut cpu, mut memory) = fixture(code);
cpu.fs_base = RIP_FS;
cpu.gs_base = RIP_GS;
let native = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(
native.exit_reason, expected,
"native DBT, fault at {fault:#x}"
);
let (_, mut cpu, mut memory) = fixture(code);
cpu.fs_base = RIP_FS;
cpu.gs_base = RIP_GS;
let interpreted = crate::cpu::Interpreter::new(cpu, &mut memory, 16).run();
assert_eq!(
interpreted.exit_reason, expected,
"interpreter, fault at {fault:#x}"
);
}
}
/// Both execution paths must agree when an instruction carries an FS and
/// a GS override together.
///
/// The Intel SDM states that "the effect of redundant prefixes (more than
/// one prefix from a group) is undefined", and FS and GS are in the same
/// prefix group. The architecture therefore does not define which base
/// applies, so this test pins the local rule instead: both paths prefer
/// GS, and they must agree with each other.
///
/// The encoding is `mov [fs:0x8], rbx` preceded by a GS override
/// (65 64 48 89 1C 25 08 00 00 00).
#[test]
fn redundant_fs_and_gs_overrides_are_handled_the_same_by_both_paths() {
const CODE: [u8; 11] = [
0x65, 0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
0xF4, // hlt
];
const FS_BASE: u64 = 0x7000;
const GS_BASE: u64 = 0x8000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
let (mut engine, mut cpu, mut memory) = fixture(&CODE);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let native = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(native.exit_reason, ExitReason::Halt);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, CODE.len(), MemoryPermissions::READ_EXECUTE, &CODE)
.unwrap();
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
let mut interp = crate::cpu::Interpreter::new(cpu, &mut memory, 16);
let interpreted = interp.run();
assert_eq!(interpreted.exit_reason, native.exit_reason);
assert_eq!(interpreted.final_state, native.final_state);
// The local rule prefers GS, so the store landed at the GS base.
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), STORED_VALUE);
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), 0);
}
/// The GS segment override adds the GS base, and distinct FS and GS bases
/// must not be confused with each other.
///
/// The encodings are `mov [gs:0x8], rbx` (65 48 89 1C 25 08 00 00 00)
/// and `mov rdx, [gs:0x8]` (65 48 8B 14 25 08 00 00 00), as produced by
/// LLVM 23.1.6 `llvm-mc -show-encoding`.
#[test]
fn gs_segment_override_adds_the_gs_base_to_the_address() {
let code = [
0x65, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [gs:0x8], rbx
0x65, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [gs:0x8]
0xF4, // hlt
];
let (mut engine, mut cpu, mut memory) = fixture(&code);
const FS_BASE: u64 = 0x7000;
const GS_BASE: u64 = 0x8000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), STORED_VALUE);
// The FS base must be untouched.
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), 0);
assert_eq!(result.final_state.get(Register::Rdx), STORED_VALUE);
}
/// A segment-relative access to an unmapped address must fault, and the
/// fault must report the segment-adjusted address.
///
/// The encoding is `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00).
/// The FS base points outside every mapped region, so the store faults at
/// `FS_BASE + 8`.
#[test]
fn segment_relative_access_to_an_unmapped_address_faults() {
let code = [
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
0xF4, // hlt
];
let (mut engine, mut cpu, mut memory) = fixture(&code);
const FS_BASE: u64 = 0x7000;
cpu.fs_base = FS_BASE;
cpu.set(Register::Rbx, 0x1122_3344_5566_7788);
// No region is mapped at FS_BASE, so the segment-adjusted address
// FS_BASE + 8 is unmapped.
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(
result.exit_reason,
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
);
}
}