mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 11:40:43 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4652eb08cb | ||
|
|
d1bcd0249d | ||
|
|
af1b84ad75 | ||
|
|
cf438e25aa | ||
|
|
7246ab5ea6 | ||
|
|
729e1b4cb1 |
No files matched your search
@@ -38,12 +38,14 @@ remains unsupported.
|
||||
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
|
||||
|
||||
### Added
|
||||
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
|
||||
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
|
||||
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
|
||||
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
|
||||
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
@@ -242,6 +244,7 @@ remains unsupported.
|
||||
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
|
||||
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
|
||||
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
|
||||
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
|
||||
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
|
||||
|
||||
@@ -120,10 +120,11 @@ pub enum GraphicsError {
|
||||
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
|
||||
InvalidIndexFormat(u32),
|
||||
/// An indexed draw reads past its index buffer or fetches a vertex,
|
||||
/// after applying the base vertex, outside its vertex buffer.
|
||||
/// after applying the base vertex, outside its vertex buffer, or a flat
|
||||
/// draw reads its vertices outside the vertex buffer.
|
||||
IndexOutOfRange,
|
||||
/// A descriptor heap, view, sampler, root signature or binding outside
|
||||
/// the supported texture-binding subset. Nothing is drawn.
|
||||
/// A descriptor heap, view, sampler, root signature, binding or draw
|
||||
/// outside the supported subset. Nothing is drawn.
|
||||
Unsupported(&'static str),
|
||||
}
|
||||
|
||||
@@ -151,8 +152,8 @@ impl std::fmt::Display for GraphicsError {
|
||||
Self::InvalidIndexFormat(format) => {
|
||||
write!(f, "unsupported index buffer format {format}")
|
||||
}
|
||||
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
|
||||
Self::Unsupported(what) => write!(f, "unsupported texture binding: {what}"),
|
||||
Self::IndexOutOfRange => write!(f, "draw outside its index or vertex buffer"),
|
||||
Self::Unsupported(what) => write!(f, "unsupported graphics operation: {what}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1673,9 +1674,22 @@ impl GraphicsContext {
|
||||
rendered_output = Some(pixels);
|
||||
continue;
|
||||
}
|
||||
if *vertex_count_per_instance < 3 {
|
||||
// Zero instances, or fewer vertices than one triangle,
|
||||
// draw nothing. The flat path draws only the first
|
||||
// triangle of the view, once; anything else is rejected
|
||||
// rather than drawn as a different triangle.
|
||||
if *vertex_count_per_instance < 3 || *instance_count == 0 {
|
||||
continue;
|
||||
}
|
||||
if *vertex_count_per_instance != 3
|
||||
|| *instance_count != 1
|
||||
|| *start_vertex_location != 0
|
||||
|| *start_instance_location != 0
|
||||
{
|
||||
return Err(GraphicsError::Unsupported(
|
||||
"flat draw other than one instance of the view's first three vertices",
|
||||
));
|
||||
}
|
||||
draw_count += 1;
|
||||
let v_res_handle =
|
||||
vertex_resource.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
@@ -1684,15 +1698,10 @@ impl GraphicsContext {
|
||||
.get(&v_res_handle)
|
||||
.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
|
||||
// Read vertices from guest memory backing or resource data
|
||||
let mut raw_vtx = [0u8; 48]; // 3 * 4 * float32
|
||||
if let Some(guest_addr) = v_res.guest_backing_addr {
|
||||
memory.read_bytes(guest_addr + vertex_offset as u64, &mut raw_vtx)?;
|
||||
} else if v_res.data.len() >= vertex_offset + 48 {
|
||||
raw_vtx.copy_from_slice(&v_res.data[vertex_offset..vertex_offset + 48]);
|
||||
} else {
|
||||
return Err(GraphicsError::InvalidDescriptor);
|
||||
}
|
||||
// Three float4 positions, inside the resource whether it
|
||||
// is backed by guest memory or by its own bytes.
|
||||
let mut raw_vtx = [0u8; 48];
|
||||
Self::read_resource(v_res, memory, vertex_offset, &mut raw_vtx)?;
|
||||
|
||||
let mut vertices = [[0.0f32; 4]; 3];
|
||||
for (i, row) in vertices.iter_mut().enumerate() {
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Repeated-frame regression for the guest graphics context (issue #148).
|
||||
//!
|
||||
//! One device, queue, allocator and command list are driven through the
|
||||
//! per-frame loop a D3D12 guest uses: reset, record, close, execute. Each
|
||||
//! frame changes the guest-backed vertex data, the clear colour or the draw
|
||||
//! parameters. Expected pixels are written out by hand below for triangles
|
||||
//! chosen so their coverage of a 4×3 viewport is obvious; they are not
|
||||
//! computed by the rasterizer under test. These tests use the software
|
||||
//! reference backend only; no native Metal result is claimed here.
|
||||
|
||||
use xenora_loader::graphics::{
|
||||
CommandListType, GraphicsBackendId, GraphicsContext, GraphicsError, GraphicsHandle,
|
||||
ResourceDesc, ResourceDimension, ResourceStates,
|
||||
};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
const WIDTH: usize = 4;
|
||||
const HEIGHT: usize = 3;
|
||||
const VERTICES: u64 = 0x0010_0000;
|
||||
/// Two triangles of three float4 positions each.
|
||||
const VERTEX_BYTES: usize = 96;
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
/// Covers every pixel centre of the viewport.
|
||||
const FULL: [[f32; 4]; 3] = [
|
||||
[-1.0, -1.0, 0.0, 1.0],
|
||||
[3.0, -1.0, 0.0, 1.0],
|
||||
[-1.0, 3.0, 0.0, 1.0],
|
||||
];
|
||||
/// Its right edge is x = 0 in clip space, so it covers the two left columns
|
||||
/// (centres at x = -0.75 and -0.25) and none of the two right ones.
|
||||
const LEFT_HALF: [[f32; 4]; 3] = [
|
||||
[0.0, 10.0, 0.0, 1.0],
|
||||
[0.0, -10.0, 0.0, 1.0],
|
||||
[-30.0, 0.0, 0.0, 1.0],
|
||||
];
|
||||
/// Lies wholly outside the viewport.
|
||||
const OFFSCREEN: [[f32; 4]; 3] = [
|
||||
[2.0, 2.0, 0.0, 1.0],
|
||||
[3.0, 2.0, 0.0, 1.0],
|
||||
[2.0, 3.0, 0.0, 1.0],
|
||||
];
|
||||
|
||||
struct Rig {
|
||||
ctx: GraphicsContext,
|
||||
memory: GuestMemory,
|
||||
queue: GraphicsHandle,
|
||||
alloc: GraphicsHandle,
|
||||
list: GraphicsHandle,
|
||||
vertices: GraphicsHandle,
|
||||
target: GraphicsHandle,
|
||||
}
|
||||
|
||||
fn rig() -> Rig {
|
||||
let mut ctx = GraphicsContext::new();
|
||||
let device = ctx.create_device().unwrap();
|
||||
let queue = ctx
|
||||
.create_command_queue(device, CommandListType::Direct)
|
||||
.unwrap();
|
||||
let alloc = ctx
|
||||
.create_command_allocator(device, CommandListType::Direct)
|
||||
.unwrap();
|
||||
let list = ctx
|
||||
.create_command_list(device, alloc, CommandListType::Direct)
|
||||
.unwrap();
|
||||
// A new list starts open; close it so every frame begins with a reset.
|
||||
ctx.close_command_list(list).unwrap();
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(VERTICES, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let buffer = ResourceDesc {
|
||||
dimension: ResourceDimension::Buffer,
|
||||
width: VERTEX_BYTES as u64,
|
||||
height: 1,
|
||||
depth_or_array_size: 1,
|
||||
mip_levels: 1,
|
||||
format_rgba8: false,
|
||||
};
|
||||
let vertices = ctx
|
||||
.create_committed_resource(
|
||||
device,
|
||||
buffer,
|
||||
ResourceStates::VERTEX_AND_CONSTANT_BUFFER,
|
||||
Some(VERTICES),
|
||||
)
|
||||
.unwrap();
|
||||
let texture = ResourceDesc {
|
||||
dimension: ResourceDimension::Texture2D,
|
||||
width: WIDTH as u64,
|
||||
height: HEIGHT as u32,
|
||||
depth_or_array_size: 1,
|
||||
mip_levels: 1,
|
||||
format_rgba8: true,
|
||||
};
|
||||
let target = ctx
|
||||
.create_committed_resource(device, texture, ResourceStates::PRESENT, None)
|
||||
.unwrap();
|
||||
Rig {
|
||||
ctx,
|
||||
memory,
|
||||
queue,
|
||||
alloc,
|
||||
list,
|
||||
vertices,
|
||||
target,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_triangle(memory: &mut GuestMemory, slot: u64, triangle: [[f32; 4]; 3]) {
|
||||
let bytes: Vec<u8> = triangle
|
||||
.iter()
|
||||
.flatten()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect();
|
||||
memory.write_bytes(VERTICES + slot * 48, &bytes).unwrap();
|
||||
}
|
||||
|
||||
/// Pixels with `columns` red from the left and the rest in `clear`.
|
||||
fn expected(columns: usize, clear: [u8; 4]) -> Vec<u8> {
|
||||
(0..WIDTH * HEIGHT)
|
||||
.flat_map(|pixel| if pixel % WIDTH < columns { RED } else { clear })
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct Draw {
|
||||
clear: [u8; 4],
|
||||
offset: usize,
|
||||
vertex_count: u32,
|
||||
instance_count: u32,
|
||||
start_vertex: u32,
|
||||
start_instance: u32,
|
||||
}
|
||||
|
||||
impl Draw {
|
||||
fn one(clear: [u8; 4]) -> Self {
|
||||
Self {
|
||||
clear,
|
||||
offset: 0,
|
||||
vertex_count: 3,
|
||||
instance_count: 1,
|
||||
start_vertex: 0,
|
||||
start_instance: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record one frame: target to RENDER_TARGET, draw, back to PRESENT.
|
||||
fn record(rig: &mut Rig, draw: &Draw) -> Result<(), GraphicsError> {
|
||||
let ctx = &mut rig.ctx;
|
||||
ctx.reset_command_list(rig.list, rig.alloc)?;
|
||||
ctx.cmd_resource_barrier(
|
||||
rig.list,
|
||||
rig.target,
|
||||
ResourceStates::PRESENT,
|
||||
ResourceStates::RENDER_TARGET,
|
||||
)?;
|
||||
ctx.cmd_set_viewport(rig.list, WIDTH, HEIGHT)?;
|
||||
ctx.cmd_set_render_targets(rig.list, Some(rig.target), draw.clear)?;
|
||||
ctx.cmd_set_vertex_buffer(rig.list, rig.vertices, draw.offset, 48)?;
|
||||
ctx.cmd_draw_instanced(
|
||||
rig.list,
|
||||
draw.vertex_count,
|
||||
draw.instance_count,
|
||||
draw.start_vertex,
|
||||
draw.start_instance,
|
||||
)?;
|
||||
ctx.cmd_resource_barrier(
|
||||
rig.list,
|
||||
rig.target,
|
||||
ResourceStates::RENDER_TARGET,
|
||||
ResourceStates::PRESENT,
|
||||
)?;
|
||||
ctx.close_command_list(rig.list)
|
||||
}
|
||||
|
||||
fn frame(rig: &mut Rig, draw: &Draw) -> Result<(Vec<u8>, usize), GraphicsError> {
|
||||
record(rig, draw)?;
|
||||
let outcome = rig
|
||||
.ctx
|
||||
.execute_command_list(rig.queue, rig.list, &rig.memory)?;
|
||||
assert_eq!(outcome.backend, GraphicsBackendId::SoftwareReference);
|
||||
assert_eq!((outcome.width, outcome.height), (WIDTH, HEIGHT));
|
||||
Ok((outcome.pixels, outcome.draw_count))
|
||||
}
|
||||
|
||||
fn frame_index(rig: &Rig) -> u64 {
|
||||
rig.ctx.last_presentation.lock().unwrap().frame_index
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_frame_reflects_its_own_guest_vertices_and_clear_colour() {
|
||||
let mut rig = rig();
|
||||
let frames = [
|
||||
(LEFT_HALF, [0, 0, 64, 255], 2),
|
||||
(FULL, [10, 20, 30, 255], WIDTH),
|
||||
(OFFSCREEN, [1, 2, 3, 4], 0),
|
||||
(LEFT_HALF, [9, 9, 9, 255], 2),
|
||||
];
|
||||
for (index, (triangle, clear, columns)) in frames.into_iter().enumerate() {
|
||||
write_triangle(&mut rig.memory, 0, triangle);
|
||||
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
|
||||
let want = expected(columns, clear);
|
||||
assert_eq!(pixels, want, "frame {index}");
|
||||
assert_eq!(draws, 1, "frame {index}");
|
||||
assert_eq!(frame_index(&rig), index as u64 + 1);
|
||||
// The presentation holds this frame's pixels, not an earlier one's.
|
||||
let presented = rig.ctx.last_presentation.lock().unwrap().pixels.clone();
|
||||
assert_eq!(presented, want, "presented frame {index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_instance_or_zero_vertex_frame_draws_nothing() {
|
||||
let mut rig = rig();
|
||||
write_triangle(&mut rig.memory, 0, FULL);
|
||||
let clear = [5, 6, 7, 255];
|
||||
for (vertices, instances) in [(3, 0), (0, 1), (2, 1)] {
|
||||
let draw = Draw {
|
||||
vertex_count: vertices,
|
||||
instance_count: instances,
|
||||
..Draw::one(clear)
|
||||
};
|
||||
let (pixels, draws) = frame(&mut rig, &draw).unwrap();
|
||||
assert_eq!(pixels, expected(0, clear), "{vertices} x {instances}");
|
||||
assert_eq!(draws, 0, "{vertices} x {instances}");
|
||||
}
|
||||
// The next ordinary frame still draws.
|
||||
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
|
||||
assert_eq!((pixels, draws), (expected(WIDTH, clear), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_draw_parameters_fail_and_the_next_frame_recovers() {
|
||||
let mut rig = rig();
|
||||
write_triangle(&mut rig.memory, 0, LEFT_HALF);
|
||||
write_triangle(&mut rig.memory, 1, FULL);
|
||||
let clear = [0, 0, 0, 255];
|
||||
frame(&mut rig, &Draw::one(clear)).unwrap();
|
||||
let rejected = [
|
||||
Draw {
|
||||
start_vertex: 3,
|
||||
..Draw::one(clear)
|
||||
},
|
||||
Draw {
|
||||
instance_count: 2,
|
||||
..Draw::one(clear)
|
||||
},
|
||||
Draw {
|
||||
start_instance: 1,
|
||||
..Draw::one(clear)
|
||||
},
|
||||
Draw {
|
||||
vertex_count: 6,
|
||||
..Draw::one(clear)
|
||||
},
|
||||
];
|
||||
for draw in &rejected {
|
||||
// Only the draw is rejected. The barrier before it already ran, so
|
||||
// the target is left in RENDER_TARGET, as a guest would see it.
|
||||
let before = frame_index(&rig);
|
||||
let result = frame(&mut rig, draw);
|
||||
assert!(
|
||||
matches!(result, Err(GraphicsError::Unsupported(_))),
|
||||
"{result:?}"
|
||||
);
|
||||
assert_eq!(frame_index(&rig), before, "a failed frame is not presented");
|
||||
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
|
||||
rig.ctx
|
||||
.cmd_resource_barrier(
|
||||
rig.list,
|
||||
rig.target,
|
||||
ResourceStates::RENDER_TARGET,
|
||||
ResourceStates::PRESENT,
|
||||
)
|
||||
.unwrap();
|
||||
rig.ctx.close_command_list(rig.list).unwrap();
|
||||
rig.ctx
|
||||
.execute_command_list(rig.queue, rig.list, &rig.memory)
|
||||
.unwrap();
|
||||
}
|
||||
// The second triangle is still reachable through the view offset.
|
||||
let draw = Draw {
|
||||
offset: 48,
|
||||
..Draw::one(clear)
|
||||
};
|
||||
let (pixels, _) = frame(&mut rig, &draw).unwrap();
|
||||
assert_eq!(pixels, expected(WIDTH, clear));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_view_outside_its_buffer_fails_without_reading_past_it() {
|
||||
let mut rig = rig();
|
||||
write_triangle(&mut rig.memory, 0, FULL);
|
||||
write_triangle(&mut rig.memory, 1, FULL);
|
||||
// Mapped guest memory continues past the buffer; the view must not.
|
||||
write_triangle(&mut rig.memory, 2, FULL);
|
||||
let clear = [0, 0, 0, 255];
|
||||
for offset in [VERTEX_BYTES - 47, VERTEX_BYTES, usize::MAX - 100] {
|
||||
let draw = Draw {
|
||||
offset,
|
||||
..Draw::one(clear)
|
||||
};
|
||||
assert_eq!(
|
||||
frame(&mut rig, &draw),
|
||||
Err(GraphicsError::IndexOutOfRange),
|
||||
"offset {offset}"
|
||||
);
|
||||
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
|
||||
rig.ctx
|
||||
.cmd_resource_barrier(
|
||||
rig.list,
|
||||
rig.target,
|
||||
ResourceStates::RENDER_TARGET,
|
||||
ResourceStates::PRESENT,
|
||||
)
|
||||
.unwrap();
|
||||
rig.ctx.close_command_list(rig.list).unwrap();
|
||||
rig.ctx
|
||||
.execute_command_list(rig.queue, rig.list, &rig.memory)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
//! convention documentation, not from the registry or the handlers.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
@@ -696,6 +697,76 @@ fn floating_arguments_and_results_use_xmm_registers() {
|
||||
assert_eq!(float("fabsf", garbage | 0xBF80_0000) as u32, 0x3F80_0000); // -1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guest_call_through_dbt_preserves_win64_abi_state() {
|
||||
use Register::{R8, R9, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
|
||||
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4])>));
|
||||
let seen = observed.clone();
|
||||
let mut registry = ImportRegistry::new();
|
||||
registry.register("t.dll", "F", move |_args, cpu, mem| {
|
||||
let rsp = cpu.get(Rsp);
|
||||
let shadow = [
|
||||
mem.read_u64(rsp + 8).unwrap(),
|
||||
mem.read_u64(rsp + 16).unwrap(),
|
||||
mem.read_u64(rsp + 24).unwrap(),
|
||||
mem.read_u64(rsp + 32).unwrap(),
|
||||
];
|
||||
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow));
|
||||
cpu.set(Rcx, 0x11);
|
||||
cpu.set(Rdx, 0x22);
|
||||
cpu.set(R8, 0x33);
|
||||
cpu.set(R9, 0x44);
|
||||
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
|
||||
*lane = u128::from(0x55_u64 + reg as u64);
|
||||
}
|
||||
Ok(0x99AA_BBCC_DDEE_F001)
|
||||
});
|
||||
let image = build(&[("t.dll", Symbol::Name("F"))]);
|
||||
let pe = ParsedPe::parse(&image.bytes).unwrap();
|
||||
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
registry
|
||||
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
|
||||
.unwrap();
|
||||
let mut engine = DbtEngine::new(256 * 1024).unwrap();
|
||||
engine.set_import_registry(registry);
|
||||
// Before CALL RSP is 16-byte aligned; CALL pushes return address so the
|
||||
// callee sees RSP % 16 == 8. Shadow space is [entry_rsp+8, entry_rsp+40).
|
||||
let initial_rsp = STACK_TOP;
|
||||
assert_eq!(initial_rsp % 16, 0);
|
||||
let entry_rsp_expected = initial_rsp - 8;
|
||||
for slot in 0..4u64 {
|
||||
memory
|
||||
.write_u64(entry_rsp_expected + 8 + slot * 8, 0x7000 + slot)
|
||||
.unwrap();
|
||||
}
|
||||
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA), initial_rsp);
|
||||
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
|
||||
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
|
||||
cpu.set(register, 0x6100 + index as u64);
|
||||
}
|
||||
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
|
||||
*lane = u128::from(0x6200_u64 + (offset + 6) as u64);
|
||||
}
|
||||
let result = engine.run(&mut cpu, &mut memory, 1000);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
let (entry_rsp, _, shadow) = observed.lock().unwrap().expect("service ran");
|
||||
assert_eq!(entry_rsp, entry_rsp_expected);
|
||||
assert_eq!(entry_rsp % 16, 8);
|
||||
assert_eq!(shadow, [0x7000, 0x7001, 0x7002, 0x7003]);
|
||||
assert_eq!(cpu.get(Rax), 0x99AA_BBCC_DDEE_F001);
|
||||
assert_eq!(cpu.get(Rsp), initial_rsp);
|
||||
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
|
||||
assert_eq!(cpu.get(register), 0x6100 + index as u64, "{register:?}");
|
||||
}
|
||||
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
|
||||
let index = offset + 6;
|
||||
assert_eq!(*lane, u128::from(0x6200_u64 + index as u64), "xmm{index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() {
|
||||
let mut memory = GuestMemory::new();
|
||||
@@ -957,6 +1028,122 @@ fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_may_write_its_caller_allocated_shadow_space() {
|
||||
// Microsoft x64 calling convention: the caller reserves four home slots,
|
||||
// but the callee may use them. Their contents are not nonvolatile state.
|
||||
let (registry, mut memory, trampoline) = bound_service(|_, cpu, memory| {
|
||||
for slot in 0..4u64 {
|
||||
memory
|
||||
.write_u64(cpu.get(Register::Rsp) + 8 + slot * 8, 0xA000 + slot)
|
||||
.unwrap();
|
||||
}
|
||||
Ok(7)
|
||||
});
|
||||
let entry_rsp = STACK_TOP - 8;
|
||||
memory.write_u64(entry_rsp, 0x1234).unwrap();
|
||||
let mut cpu = CpuState::new(trampoline, entry_rsp);
|
||||
assert_eq!(registry.dispatch(trampoline, &mut cpu, &mut memory), Ok(()));
|
||||
assert_eq!(cpu.rip, 0x1234);
|
||||
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
|
||||
assert_eq!(cpu.get(Register::Rax), 7);
|
||||
for slot in 0..4u64 {
|
||||
assert_eq!(memory.read_u64(entry_rsp + 8 + slot * 8), Ok(0xA000 + slot));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_calls_preserve_win64_abi_state() {
|
||||
// Microsoft x64 calling convention: at entry RSP % 16 == 8 (return address
|
||||
// pushed by CALL). Callee preserves RBX,RBP,RDI,RSI,R12-R15 and XMM6-XMM15.
|
||||
// Caller allocates 32-byte shadow/home space at [RSP+8, RSP+40), which
|
||||
// the callee may use. This handler leaves it unchanged; the separate
|
||||
// shadow-space test checks a handler that writes it. RAX carries the
|
||||
// return value; RCX,RDX,R8,R9,R10,R11,XMM0-XMM5 are volatile.
|
||||
use Register::{R8, R9, R10, R11, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
|
||||
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4], u64)>));
|
||||
let seen = observed.clone();
|
||||
let (registry, mut memory, trampoline) = bound_service(move |args, cpu, mem| {
|
||||
let rsp = cpu.get(Rsp);
|
||||
let shadow = [
|
||||
mem.read_u64(rsp + 8).unwrap(),
|
||||
mem.read_u64(rsp + 16).unwrap(),
|
||||
mem.read_u64(rsp + 24).unwrap(),
|
||||
mem.read_u64(rsp + 32).unwrap(),
|
||||
];
|
||||
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow, args.rcx));
|
||||
// Clobber volatile registers; dispatcher must still return correctly and
|
||||
// nonvolatile state must be preserved after return.
|
||||
cpu.set(Rcx, 0xA1);
|
||||
cpu.set(Rdx, 0xA2);
|
||||
cpu.set(R8, 0xA3);
|
||||
cpu.set(R9, 0xA4);
|
||||
cpu.set(R10, 0xA5);
|
||||
cpu.set(R11, 0xA6);
|
||||
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
|
||||
*lane = u128::from(0xB0_u64 + reg as u64);
|
||||
}
|
||||
Ok(0x1122_3344_5566_7788)
|
||||
});
|
||||
// Win64: before CALL RSP is 16-byte aligned; CALL pushes return address,
|
||||
// so callee entry sees RSP % 16 == 8.
|
||||
let call_rsp = STACK_TOP - 8;
|
||||
assert_eq!(call_rsp % 16, 8);
|
||||
memory.write_u64(call_rsp, 0x1234).unwrap();
|
||||
for slot in 0..4u64 {
|
||||
memory
|
||||
.write_u64(call_rsp + 8 + slot * 8, 0xC000 + slot)
|
||||
.unwrap();
|
||||
}
|
||||
let mut cpu = CpuState::new(trampoline, call_rsp);
|
||||
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
|
||||
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
|
||||
cpu.set(register, 0x5AA5_0000_0001_0000 + index as u64);
|
||||
}
|
||||
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
|
||||
*lane = u128::from(0xD000_0000_0000_0000_u64 + (offset + 6) as u64);
|
||||
}
|
||||
cpu.set(Rcx, 0x1357_9BDF_2468_ACE0);
|
||||
let result = registry.dispatch(trampoline, &mut cpu, &mut memory);
|
||||
assert_eq!(result, Ok(()));
|
||||
let (entry_rsp, entry_rip, shadow, entry_rcx) = observed.lock().unwrap().expect("service ran");
|
||||
assert_eq!(entry_rip, trampoline);
|
||||
assert_eq!(
|
||||
entry_rsp, call_rsp,
|
||||
"service sees caller RSP at return address"
|
||||
);
|
||||
assert_eq!(entry_rsp % 16, 8, "Win64 entry RSP must be 8 mod 16");
|
||||
assert_eq!(entry_rcx, 0x1357_9BDF_2468_ACE0);
|
||||
// Shadow/home space is caller-owned and must be addressable by the service.
|
||||
assert_eq!(shadow, [0xC000, 0xC001, 0xC002, 0xC003]);
|
||||
for slot in 0..4u64 {
|
||||
assert_eq!(
|
||||
memory.read_u64(call_rsp + 8 + slot * 8).unwrap(),
|
||||
0xC000 + slot,
|
||||
"this handler leaves its home slots untouched"
|
||||
);
|
||||
}
|
||||
// Post-return ABI state.
|
||||
assert_eq!(cpu.get(Rax), 0x1122_3344_5566_7788);
|
||||
assert_eq!(cpu.get(Rsp), call_rsp + 8);
|
||||
assert_eq!(cpu.rip, 0x1234);
|
||||
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
|
||||
assert_eq!(
|
||||
cpu.get(register),
|
||||
0x5AA5_0000_0001_0000 + index as u64,
|
||||
"nonvolatile {register:?} must be preserved"
|
||||
);
|
||||
}
|
||||
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
|
||||
let index = offset + 6;
|
||||
assert_eq!(
|
||||
*lane,
|
||||
u128::from(0xD000_0000_0000_0000_u64 + index as u64),
|
||||
"nonvolatile xmm{index} must be preserved"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_that_cannot_return_runs_no_service() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
Reference in new issue
Block a user