diff --git a/CHANGELOG.md b/CHANGELOG.md index 3350631..9417f51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -244,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. diff --git a/crates/loader/src/graphics.rs b/crates/loader/src/graphics.rs index 5f4ea58..afeaa95 100644 --- a/crates/loader/src/graphics.rs +++ b/crates/loader/src/graphics.rs @@ -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() { diff --git a/crates/loader/tests/repeated_frames.rs b/crates/loader/tests/repeated_frames.rs new file mode 100644 index 0000000..a78dd14 --- /dev/null +++ b/crates/loader/tests/repeated_frames.rs @@ -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 = 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 { + (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, 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(); + } +}