From 729e1b4cb1a937b5b3a8a5d5502155a71a4b08ea Mon Sep 17 00:00:00 2001 From: Swastickc <28708247+Swastickc@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:34:19 +0530 Subject: [PATCH 01/12] loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148) Flat DrawInstanced ignored InstanceCount, StartInstanceLocation and StartVertexLocation, so a zero-instance draw still drew and a changed start vertex drew the first triangle. Zero instances or fewer than three vertices now draw nothing; other unsupported parameters fail with GraphicsError::Unsupported. Vertex reads use the range-checked read_resource, so a view past its buffer or an overflowing guest address fails with IndexOutOfRange. Add tests/repeated_frames.rs: repeated reset, record, close and execute frames with hand-derived pixels on the software reference backend. Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/loader/src/graphics.rs | 39 +-- crates/loader/tests/repeated_frames.rs | 325 +++++++++++++++++++++++++ 3 files changed, 350 insertions(+), 15 deletions(-) create mode 100644 crates/loader/tests/repeated_frames.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index e686c9c..e9293aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -187,6 +187,7 @@ remains unsupported. native DBT. ### Fixed +- 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 import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201). - Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers. 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(); + } +} From 7246ab5ea60f5b722177dc9b731db04a20b6a905 Mon Sep 17 00:00:00 2001 From: Arthur Lacoste Date: Tue, 24 Nov 2026 20:57:41 +0100 Subject: [PATCH 02/12] loader: add Win64 service ABI preservation tests (#201) Add dispatch and DBT-backed runtime service tests that verify Win64 callee entry alignment, caller-owned shadow space, return state, and preservation of nonvolatile GPRs/XMM registers across registered service calls. AI-Assisted: Codex (GPT-5) helped draft the tests; I reviewed the diff and ran fmt/clippy(loader)/loader tests locally. Signed-off-by: Arthur Lacoste --- CHANGELOG.md | 1 + crates/loader/tests/runtime_services.rs | 163 ++++++++++++++++++++++++ 2 files changed, 164 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e686c9c..d853bd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added +- 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. - Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215. - Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted. - Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215. diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 5d5d2fa..1dd24de 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -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,79 @@ 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 in 0..6 { + cpu.xmm[reg] = 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 index in 6..16 { + cpu.xmm[index] = u128::from(0x6200_u64 + index 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 index in 6..16 { + assert_eq!( + cpu.xmm[index], + 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 +1031,95 @@ fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() { } } +#[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 owns 32-byte shadow/home space at [RSP+8, RSP+40). 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 in 0..6 { + cpu.xmm[reg] = 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 index in 6..16 { + cpu.xmm[index] = u128::from(0xD000_0000_0000_0000_u64 + index 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, + "service call must not mutate caller shadow space" + ); + } + // 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 index in 6..16 { + assert_eq!( + cpu.xmm[index], + 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)); From fbec436b89735642eea2cbad3a60140f0e02e805 Mon Sep 17 00:00:00 2001 From: plokhi <37208555+Plokhi@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:19:38 +0100 Subject: [PATCH 03/12] Fix ARM64 variable shift register encoding Signed-off-by: plokhi <37208555+Plokhi@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/loader/src/arm64.rs | 56 +++++++++++++++++++++++++++++++++----- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bdc634..c13f154 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -202,6 +202,7 @@ remains unsupported. ### Fixed - 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 the ARM64 `LSLV` emitter setting bit 1 of the shift-count register field (#131). The `RBIT`, `CLZ` and `LSLV` emitters now reject out-of-range register numbers, with encoding tests checked against LLVM's assembler. - 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 the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review. - Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review. diff --git a/crates/loader/src/arm64.rs b/crates/loader/src/arm64.rs index 6557f06..4c47a44 100644 --- a/crates/loader/src/arm64.rs +++ b/crates/loader/src/arm64.rs @@ -307,23 +307,27 @@ impl Arm64Assembler { } /// RBIT Xd, Xn: reverse the bit order of the source. + /// Panics if a register number exceeds 31. pub fn rbit_64(&mut self, xd: u8, xn: u8) { - self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f)); + assert!(xd <= XZR && xn <= XZR, "RBIT register must be in 0..=31"); + self.emit(0xdac0_0000 | (u32::from(xn) << 5) | u32::from(xd)); } /// CLZ Xd, Xn: count the leading zero bits of the source. + /// Panics if a register number exceeds 31. pub fn clz_64(&mut self, xd: u8, xn: u8) { - self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f)); + assert!(xd <= XZR && xn <= XZR, "CLZ register must be in 0..=31"); + self.emit(0xdac0_1000 | (u32::from(xn) << 5) | u32::from(xd)); } /// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm. + /// Panics if a register number exceeds 31. 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), + assert!( + xd <= XZR && xn <= XZR && xm <= XZR, + "LSLV register must be in 0..=31" ); + self.emit(0x9ac0_2000 | (u32::from(xm) << 16) | (u32::from(xn) << 5) | u32::from(xd)); } /// LDR Qt, [Xn, #offset] (offset a multiple of 16) @@ -791,6 +795,44 @@ mod tests { assert_eq!(branch.instructions()[0], 0x14000005); } + #[test] + fn bit_scan_and_bit_test_encodings_match_llvm() { + // A64 words from Apple Clang's integrated assembler and llvm-objdump. + let mut asm = Arm64Assembler::new(); + asm.rbit_64(X10, X9); // rbit x10, x9 + asm.rbit_64(X0, XZR); // rbit x0, xzr + asm.clz_64(X10, X10); // clz x10, x10 + asm.clz_64(XZR, X30); // clz xzr, x30 + asm.lslv_64(X11, X11, X10); // lslv x11, x11, x10 + asm.lslv_64(X0, X1, X0); // lslv x0, x1, x0 + asm.lslv_64(XZR, X30, XZR); // lslv xzr, x30, xzr + assert_eq!( + asm.instructions(), + [ + 0xdac0012a, 0xdac003e0, 0xdac0114a, 0xdac013df, 0x9aca216b, 0x9ac02020, 0x9adf23df, + ] + ); + } + + #[test] + fn bit_scan_and_bit_test_reject_out_of_range_registers() { + let invalid_operands: [fn(&mut Arm64Assembler); 7] = [ + |asm| asm.rbit_64(32, X0), + |asm| asm.rbit_64(X0, 32), + |asm| asm.clz_64(32, X0), + |asm| asm.clz_64(X0, 32), + |asm| asm.lslv_64(32, X0, X0), + |asm| asm.lslv_64(X0, 32, X0), + |asm| asm.lslv_64(X0, X0, 32), + ]; + for (index, emit) in invalid_operands.into_iter().enumerate() { + let mut asm = Arm64Assembler::new(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| emit(&mut asm))); + assert!(result.is_err(), "invalid operand case {index} was accepted"); + assert!(asm.instructions().is_empty()); + } + } + #[test] fn unsigned_offset_stores_scale_by_access_size() { let mut asm = Arm64Assembler::new(); From d35c278284037abb36315b865c5dca4f63c1a179 Mon Sep 17 00:00:00 2001 From: plokhi <37208555+Plokhi@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:33:37 +0100 Subject: [PATCH 04/12] Clarify ARM64 encoding audit coverage Signed-off-by: plokhi <37208555+Plokhi@users.noreply.github.com> --- CHANGELOG.md | 2 +- crates/loader/src/arm64.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c13f154..17b4503 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -202,7 +202,7 @@ remains unsupported. ### Fixed - 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 the ARM64 `LSLV` emitter setting bit 1 of the shift-count register field (#131). The `RBIT`, `CLZ` and `LSLV` emitters now reject out-of-range register numbers, with encoding tests checked against LLVM's assembler. +- 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. - 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 the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review. - Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review. diff --git a/crates/loader/src/arm64.rs b/crates/loader/src/arm64.rs index 4c47a44..5c8dc65 100644 --- a/crates/loader/src/arm64.rs +++ b/crates/loader/src/arm64.rs @@ -796,7 +796,7 @@ mod tests { } #[test] - fn bit_scan_and_bit_test_encodings_match_llvm() { + fn rbit_clz_lslv_encodings_match_llvm() { // A64 words from Apple Clang's integrated assembler and llvm-objdump. let mut asm = Arm64Assembler::new(); asm.rbit_64(X10, X9); // rbit x10, x9 @@ -815,7 +815,7 @@ mod tests { } #[test] - fn bit_scan_and_bit_test_reject_out_of_range_registers() { + fn rbit_clz_lslv_reject_out_of_range_registers() { let invalid_operands: [fn(&mut Arm64Assembler); 7] = [ |asm| asm.rbit_64(32, X0), |asm| asm.rbit_64(X0, 32), From af1b84ad75f23bca616b030ea30523c37e892928 Mon Sep 17 00:00:00 2001 From: Arthur Lacoste Date: Tue, 24 Nov 2026 22:14:29 +0100 Subject: [PATCH 05/12] loader: fix needless_range_loop in Win64 ABI tests (#201) Address review feedback from zachdoxsee on PR #369: replace index-only XMM range loops with iterator-based loops so strict clippy passes on Rust 1.100. Signed-off-by: Arthur Lacoste --- crates/loader/tests/runtime_services.rs | 30 ++++++++++++------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 1dd24de..466d2ca 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -716,8 +716,8 @@ fn guest_call_through_dbt_preserves_win64_abi_state() { cpu.set(Rdx, 0x22); cpu.set(R8, 0x33); cpu.set(R9, 0x44); - for reg in 0..6 { - cpu.xmm[reg] = u128::from(0x55_u64 + reg as u64); + for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() { + *lane = u128::from(0x55_u64 + reg as u64); } Ok(0x99AA_BBCC_DDEE_F001) }); @@ -747,8 +747,8 @@ fn guest_call_through_dbt_preserves_win64_abi_state() { for (index, register) in nonvolatile_gpr.into_iter().enumerate() { cpu.set(register, 0x6100 + index as u64); } - for index in 6..16 { - cpu.xmm[index] = u128::from(0x6200_u64 + 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); @@ -761,12 +761,9 @@ fn guest_call_through_dbt_preserves_win64_abi_state() { for (index, register) in nonvolatile_gpr.into_iter().enumerate() { assert_eq!(cpu.get(register), 0x6100 + index as u64, "{register:?}"); } - for index in 6..16 { - assert_eq!( - cpu.xmm[index], - u128::from(0x6200_u64 + index as u64), - "xmm{index}" - ); + 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}"); } } @@ -1057,8 +1054,8 @@ fn service_calls_preserve_win64_abi_state() { cpu.set(R9, 0xA4); cpu.set(R10, 0xA5); cpu.set(R11, 0xA6); - for reg in 0..6 { - cpu.xmm[reg] = u128::from(0xB0_u64 + reg as u64); + for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() { + *lane = u128::from(0xB0_u64 + reg as u64); } Ok(0x1122_3344_5566_7788) }); @@ -1077,8 +1074,8 @@ fn service_calls_preserve_win64_abi_state() { for (index, register) in nonvolatile_gpr.into_iter().enumerate() { cpu.set(register, 0x5AA5_0000_0001_0000 + index as u64); } - for index in 6..16 { - cpu.xmm[index] = u128::from(0xD000_0000_0000_0000_u64 + 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); @@ -1111,9 +1108,10 @@ fn service_calls_preserve_win64_abi_state() { "nonvolatile {register:?} must be preserved" ); } - for index in 6..16 { + for (offset, lane) in cpu.xmm[6..16].iter().enumerate() { + let index = offset + 6; assert_eq!( - cpu.xmm[index], + *lane, u128::from(0xD000_0000_0000_0000_u64 + index as u64), "nonvolatile xmm{index} must be preserved" ); From 0caca186344e84493077f8ec49ab863b58750f63 Mon Sep 17 00:00:00 2001 From: devil8blade <360741796+devil8blade@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:49:19 -0500 Subject: [PATCH 06/12] shader: opt-in IR common-subexpression elimination (#142) Reuse the first equivalent pure vector unary or binary when CompileOptions::eliminate_common_subexpressions is set. The flag defaults off, so existing output stays byte-identical. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or mask-dependent ops are not reused. Constant folding still runs first. Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/shader/src/lib.rs | 174 ++++++++- crates/shader/tests/compiler.rs | 661 ++++++++++++++++++++++++++++++++ 3 files changed, 833 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a99346d..cbc4390 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ remains unsupported. ### Added - 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. - `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=` 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. diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 5b67f2c..4f16981 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -2,6 +2,7 @@ //! Verified compilation for Xenora's synthetic compute and graphics ABIs. +use std::collections::HashMap; use std::fmt::{self, Write}; mod graphics; @@ -34,8 +35,8 @@ pub struct CompiledShader { /// Optional translation passes applied after verification. /// /// Default options preserve the historical IR shape: constants from scalar -/// evaluation and immediates remain, but pure vector expressions between -/// constants are not rewritten. +/// evaluation and immediates remain, pure vector expressions between +/// constants are not rewritten, and duplicate pure expressions are not reused. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct CompileOptions { /// Replace pure vector unary/binary ops whose operands are already @@ -43,6 +44,12 @@ pub struct CompileOptions { /// the existing exact positive-normal rules accept the result. Loads, /// stores, lane masks, merges and branches are never folded. pub fold_constants: bool, + /// Reuse the first result of an equivalent pure vector unary or binary + /// expression. Equivalence is the same operation and the same operand + /// values in the same order; constant operands compare by bit pattern. + /// Loads, stores, constants, lane masks, merges, branches and other + /// mask-dependent or side-effecting ops are never reused. + pub eliminate_common_subexpressions: bool, } #[derive(Debug)] @@ -155,6 +162,9 @@ enum Op { fallthrough: Value, taken: Value, }, + /// The value is the earlier pure result `source`. The definition index stays + /// so later operands do not need renumbering. + Reuse(Value), } impl Op { @@ -186,6 +196,7 @@ impl Op { fallthrough, taken, } => vec![mask, fallthrough, taken], + Self::Reuse(source) => vec![source], } } @@ -262,6 +273,7 @@ impl Op { _ => unreachable!("not a VCC arithmetic operation"), } } + Self::Reuse(source) => name(source), Self::Store(_) | Self::ScalarBranch { .. } | Self::CarryMask { .. } @@ -303,7 +315,7 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { } } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] enum Binary { FloatAdd, FloatMul, @@ -506,6 +518,11 @@ pub fn compile_with( if options.fold_constants { fold_constant_ops(&mut operations); } + // Fold first so a constant expression is `const.u32` before reuse. CSE does + // not fold, and it does not turn those constants back into arithmetic. + if options.eliminate_common_subexpressions { + eliminate_common_subexpressions(&mut operations); + } let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect(); let mut ir = String::new(); @@ -685,6 +702,10 @@ pub fn compile_with( format!("store.u32 output[index], {value}"), format!("output[index] = {value};"), ), + Op::Reuse(source) => ( + format!("{dest} = reuse.u32 {source}"), + format!("uint {dest} = {source};"), + ), }; // Writing to a String is infallible. let _ = writeln!(ir, "{offset:04x}: {step}"); @@ -1489,6 +1510,153 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result = HashMap::new(); + let mut seen: Vec<(PureExpr, usize)> = Vec::new(); + + for index in 0..operations.len() { + let current = operations[index].1; + if let Op::Constant(bits) = current { + const_bits.entry(bits).or_insert(index); + continue; + } + let canonical = match current { + Op::Unary(operator, source) => Op::Unary( + operator, + equivalent_value(&expr_alias, &const_bits, operations, source), + ), + Op::Binary(operator, left, right) => Op::Binary( + operator, + equivalent_value(&expr_alias, &const_bits, operations, left), + equivalent_value(&expr_alias, &const_bits, operations, right), + ), + other => other, + }; + let rewritten = map_uses(current, |value| reused_value(&expr_alias, value)); + if let Some(key) = pure_expr(canonical) { + if let Some(&(_, first)) = seen.iter().find(|(seen_key, _)| *seen_key == key) { + expr_alias[index] = Some(first); + operations[index].1 = Op::Reuse(Value(first)); + continue; + } + seen.push((key, index)); + } + operations[index].1 = rewritten; + } +} + +fn reused_value(expr_alias: &[Option], value: Value) -> Value { + match expr_alias.get(value.0).and_then(|slot| *slot) { + Some(index) => Value(index), + None => value, + } +} + +/// SSA value to use when matching a pure expression. Follows a reuse edge, then +/// the earliest constant with the same bits. +fn equivalent_value( + expr_alias: &[Option], + const_bits: &HashMap, + operations: &[(usize, Op)], + value: Value, +) -> Value { + let root = reused_value(expr_alias, value); + match operations.get(root.0).map(|(_, operation)| *operation) { + Some(Op::Constant(bits)) => const_bits.get(&bits).copied().map(Value).unwrap_or(root), + _ => root, + } +} + +fn map_uses(operation: Op, map: impl Fn(Value) -> Value) -> Op { + match operation { + Op::Load | Op::Constant(_) | Op::ScalarBranch { .. } => operation, + Op::Binary(operator, left, right) => Op::Binary(operator, map(left), map(right)), + Op::Unary(operator, source) => Op::Unary(operator, map(source)), + Op::MergeLanes { + mask, + active, + inactive, + } => Op::MergeLanes { + mask, + active: map(active), + inactive: map(inactive), + }, + Op::Store(value) => Op::Store(map(value)), + Op::VccArithmetic { + primitive, + left, + right, + mask, + flag, + } => Op::VccArithmetic { + primitive, + left: map(left), + right: map(right), + mask: map(mask), + flag, + }, + Op::CarryMask { flag, exec } => Op::CarryMask { + flag: map(flag), + exec, + }, + Op::LaneMask { + op, + name, + sdst, + src0, + src1, + high, + exec, + } => Op::LaneMask { + op, + name, + sdst, + src0: map(src0), + src1: map(src1), + high: high.map(|(left, right)| (map(left), map(right))), + exec, + }, + Op::RuntimeBranch { mask, target } => Op::RuntimeBranch { + mask: map(mask), + target, + }, + Op::JoinVccz { + mask, + fallthrough, + taken, + } => Op::JoinVccz { + mask: map(mask), + fallthrough: map(fallthrough), + taken: map(taken), + }, + Op::Reuse(source) => Op::Reuse(map(source)), + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum PureExpr { + Unary(VectorUnary, usize), + Binary(Binary, usize, usize), +} + +fn pure_expr(operation: Op) -> Option { + match operation { + Op::Unary(operator, source) => Some(PureExpr::Unary(operator, source.0)), + Op::Binary(operator, left, right) => Some(PureExpr::Binary(operator, left.0, right.0)), + _ => None, + } +} + /// Replace pure constant expressions with `Op::Constant` in place. /// /// Operands stay addressable by their original `Value` indices so later uses diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index 3243728..e69e2a9 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -649,6 +649,7 @@ fn compile_fold_off(code: &[u8]) -> xenora_shader::CompiledShader { code, CompileOptions { fold_constants: false, + ..CompileOptions::default() }, ) .unwrap() @@ -660,6 +661,7 @@ fn compile_fold_on(code: &[u8]) -> xenora_shader::CompiledShader { code, CompileOptions { fold_constants: true, + ..CompileOptions::default() }, ) .unwrap() @@ -843,6 +845,7 @@ fn rejects_inexact_float_add_of_constants_at_verify() { &code, CompileOptions { fold_constants: false, + ..CompileOptions::default() }, ); let on = compile_with( @@ -850,6 +853,7 @@ fn rejects_inexact_float_add_of_constants_at_verify() { &code, CompileOptions { fold_constants: true, + ..CompileOptions::default() }, ); assert!( @@ -862,3 +866,660 @@ fn rejects_inexact_float_add_of_constants_at_verify() { ); // Folder unchanged: no stay-unfolded path exists for this pair. } + +// --- Opt-in common-subexpression elimination (#142) --------------------------- +// Expected IR is derived from the lifter's value order and the reuse rule +// (same unary/binary op, same operand values in order), not from the pass +// output. Constant bits cited below are computed by hand. + +fn compile_options(code: &[u8], fold: bool, cse: bool) -> xenora_shader::CompiledShader { + compile_with( + Architecture::Gfx1030, + code, + CompileOptions { + fold_constants: fold, + eliminate_common_subexpressions: cse, + }, + ) + .unwrap() +} + +fn vopc(op: u32, src0_vgpr: u32, src1_vgpr: u32) -> u32 { + // VOPC: encoding bits 0x7c00_0000, OP in bits 17-24, VSRC1 in bits 9-16, + // SRC0 in bits 0-8 (VGPR selector 256 + register). + 0x7c00_0000 | (op << 17) | (src1_vgpr << 9) | (0x100 + src0_vgpr) +} + +/// load; mov v2, 0xff00ff00; and v3 and v4 with v1, v2; xor each and with v2. +/// The two ands are the same pure op. The two xors become the same pure op +/// only after the second and is reused, so the second xor must reuse the first. +fn duplicate_and_xor_fixture() -> Vec { + words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + 0xff00_ff00, + vop2(27, 3, 1, 2), // v_and_b32 v3, v1, v2 + vop2(27, 4, 1, 2), // v_and_b32 v4, v1, v2 + vop2(29, 5, 3, 2), // v_xor_b32 v5, v3, v2 + vop2(29, 6, 4, 2), // v_xor_b32 v6, v4, v2 + 0xe070_2000, + 0x8001_0600, // buffer_store_dword v6 + 0xbbfd_0000, + 0xbf81_0000, + ]) +} + +const DUPLICATE_AND_OFF: &str = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0xff00ff00 +0014: t2 = and.b32 t0, t1 +0018: t3 = and.b32 t0, t1 +001c: t4 = xor.b32 t2, t1 +0020: t5 = xor.b32 t3, t1 +0024: store.u32 output[index], t5 +"; + +const DUPLICATE_AND_ON: &str = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0xff00ff00 +0014: t2 = and.b32 t0, t1 +0018: t3 = reuse.u32 t2 +001c: t4 = xor.b32 t2, t1 +0020: t5 = reuse.u32 t4 +0024: store.u32 output[index], t4 +"; + +const DUPLICATE_AND_MSL_OFF: &str = "\ +#include +using namespace metal; +kernel void xenora_compute( + device const uint* input [[buffer(0)]], + device uint* output [[buffer(1)]], + uint index [[thread_position_in_grid]]) { + uint t0 = input[index]; + uint t1 = 0xff00ff00u; + uint t2 = t0 & t1; + uint t3 = t0 & t1; + uint t4 = t2 ^ t1; + uint t5 = t3 ^ t1; + output[index] = t5; +} +"; + +const DUPLICATE_AND_MSL_ON: &str = "\ +#include +using namespace metal; +kernel void xenora_compute( + device const uint* input [[buffer(0)]], + device uint* output [[buffer(1)]], + uint index [[thread_position_in_grid]]) { + uint t0 = input[index]; + uint t1 = 0xff00ff00u; + uint t2 = t0 & t1; + uint t3 = t2; + uint t4 = t2 ^ t1; + uint t5 = t4; + output[index] = t4; +} +"; + +#[test] +fn default_compile_matches_cse_off() { + assert_eq!( + CompileOptions::default(), + CompileOptions { + fold_constants: false, + eliminate_common_subexpressions: false, + } + ); + let code = duplicate_and_xor_fixture(); + let baseline = compile(Architecture::Gfx1030, &code).unwrap(); + let explicit = compile_options(&code, false, false); + assert_eq!(baseline.ir, explicit.ir); + assert_eq!(baseline.msl, explicit.msl); + assert_eq!(baseline.ir, DUPLICATE_AND_OFF); + assert_eq!(baseline.msl, DUPLICATE_AND_MSL_OFF); + // add.bin has no duplicate pure expression. CSE on must not touch it. + let add = compile(Architecture::Gfx1030, FIXTURE).unwrap(); + let add_cse = compile_options(FIXTURE, false, true); + assert_eq!(add.ir, include_str!("../../../fixtures/golden/add.ir")); + assert_eq!(add_cse.ir, add.ir); + assert_eq!(add_cse.msl, add.msl); +} + +#[test] +fn reuses_duplicate_and_and_the_xor_of_that_and() { + // Off: two and.b32 and two xor.b32. On: one of each, plus reuse.u32. + // The xor is not evaluated: xor of a value with a different operand stays + // xor.b32. (xor with itself is not what this fixture computes.) + let code = duplicate_and_xor_fixture(); + let off = compile_options(&code, false, false); + let on = compile_options(&code, false, true); + assert_eq!(off.ir, DUPLICATE_AND_OFF); + assert_eq!(off.msl, DUPLICATE_AND_MSL_OFF); + assert_eq!(on.ir, DUPLICATE_AND_ON); + assert_eq!(on.msl, DUPLICATE_AND_MSL_ON); + assert_eq!(off.ir.matches("and.b32").count(), 2); + assert_eq!(on.ir.matches("and.b32").count(), 1); + assert_eq!(off.ir.matches("xor.b32").count(), 2); + assert_eq!(on.ir.matches("xor.b32").count(), 1); + assert_eq!(on.ir.matches("store.u32").count(), 1); +} + +#[test] +fn reuses_duplicate_not() { + // v_not_b32 twice on the loaded word. ~x computed once. + let code = words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + vop1(55, 2, 1), // v_not_b32 v2, v1 (VOP1 opcode 55) + vop1(55, 3, 1), // v_not_b32 v3, v1 + 0xe070_2000, + 0x8001_0300, + 0xbbfd_0000, + 0xbf81_0000, + ]); + let off = "\ +0000: t0 = load.u32 input[index] +000c: t1 = not.b32 t0 +0010: t2 = not.b32 t0 +0014: store.u32 output[index], t2 +"; + let on = "\ +0000: t0 = load.u32 input[index] +000c: t1 = not.b32 t0 +0010: t2 = reuse.u32 t1 +0014: store.u32 output[index], t1 +"; + assert_eq!(compile_options(&code, false, false).ir, off); + assert_eq!(compile_options(&code, false, true).ir, on); + let msl = compile_options(&code, false, true).msl; + assert!(msl.contains("uint t1 = ~t0;")); + assert!(msl.contains("uint t2 = t1;")); + assert_eq!(msl.matches("~t0").count(), 1); +} + +#[test] +fn does_not_reuse_swapped_subtract() { + // sub is not commutative: if the load is 0, v1 - 1 = 0xffffffff and + // 1 - v1 = 1. The third sub repeats the first and is reused. + let code = words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + 1, + vop2(38, 3, 1, 2), // v_sub_nc_u32 v3, v1, v2 + vop2(38, 4, 2, 1), // v_sub_nc_u32 v4, v2, v1 + vop2(38, 5, 1, 2), // v_sub_nc_u32 v5, v1, v2 + 0xe070_2000, + 0x8001_0500, + 0xbbfd_0000, + 0xbf81_0000, + ]); + let off = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0x00000001 +0014: t2 = sub.u32 t0, t1 +0018: t3 = sub.u32 t1, t0 +001c: t4 = sub.u32 t0, t1 +0020: store.u32 output[index], t4 +"; + let on = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0x00000001 +0014: t2 = sub.u32 t0, t1 +0018: t3 = sub.u32 t1, t0 +001c: t4 = reuse.u32 t2 +0020: store.u32 output[index], t2 +"; + assert_eq!(compile_options(&code, false, false).ir, off); + assert_eq!(compile_options(&code, false, true).ir, on); + assert_eq!( + compile_options(&code, false, true) + .ir + .matches("sub.u32") + .count(), + 2 + ); +} + +#[test] +fn does_not_reuse_a_different_opcode() { + // and vs or of the same bits differ. 0xff00ff00 & 0x0f0f0f0f = 0x0f000f00; + // 0xff00ff00 | 0x0f0f0f0f = 0xff0fff0f. + let code = words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + 0xff00_ff00, + vop2(27, 3, 1, 2), // v_and_b32 + vop2(28, 4, 1, 2), // v_or_b32 + 0xe070_2000, + 0x8001_0300, + 0xbbfd_0000, + 0xbf81_0000, + ]); + let ir = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0xff00ff00 +0014: t2 = and.b32 t0, t1 +0018: t3 = or.b32 t0, t1 +001c: store.u32 output[index], t2 +"; + let off = compile_options(&code, false, false); + let on = compile_options(&code, false, true); + assert_eq!(off.ir, ir); + assert_eq!(on.ir, ir); + assert!(!on.ir.contains("reuse.u32")); +} + +#[test] +fn does_not_merge_loads_or_duplicate_constant_definitions() { + // Two loads of input[index] stay two loads. Two movs of the same immediate + // stay two const.u32 definitions. The ands use different constant temps + // with equal bits, so the pure and is reused and the consts remain. + let code = words(&[ + 0xe030_2000, + 0x8000_0100, // buffer_load_dword v1 + 0xbf8c_3f70, + 0xe030_2000, + 0x8000_0200, // buffer_load_dword v2 + 0xbf8c_3f70, + mov_lit(3), + 0x1234_5678, + mov_lit(4), + 0x1234_5678, + vop2(27, 5, 1, 3), // v_and_b32 v5, v1, v3 + vop2(27, 6, 1, 4), // v_and_b32 v6, v1, v4 + 0xe070_2000, + 0x8001_0600, + 0xbbfd_0000, + 0xbf81_0000, + ]); + let off = "\ +0000: t0 = load.u32 input[index] +000c: t1 = load.u32 input[index] +0018: t2 = const.u32 0x12345678 +0020: t3 = const.u32 0x12345678 +0028: t4 = and.b32 t0, t2 +002c: t5 = and.b32 t0, t3 +0030: store.u32 output[index], t5 +"; + // Constant temps compare by bits, so the second and reuses the first. + // The load temps differ, and neither load is removed. + let on = "\ +0000: t0 = load.u32 input[index] +000c: t1 = load.u32 input[index] +0018: t2 = const.u32 0x12345678 +0020: t3 = const.u32 0x12345678 +0028: t4 = and.b32 t0, t2 +002c: t5 = reuse.u32 t4 +0030: store.u32 output[index], t4 +"; + assert_eq!(compile_options(&code, false, false).ir, off); + assert_eq!(compile_options(&code, false, true).ir, on); + assert_eq!( + compile_options(&code, false, true) + .ir + .matches("load.u32") + .count(), + 2 + ); + assert_eq!( + compile_options(&code, false, true) + .ir + .matches("const.u32 0x12345678") + .count(), + 2 + ); +} + +#[test] +fn does_not_merge_lane_masks() { + // Two identical v_cmp_eq_u32_e32 (VOPC opcode 194) write the wave mask. + // The results are lane-mask values and are not reused. + let code = words(&[ + mov_lit(1), + 1, + mov_lit(2), + 2, + vopc(194, 1, 2), + vopc(194, 1, 2), + mov_lit(3), + 0, + 0xe070_2000, + 0x8001_0300, + 0xbbfd_0000, + 0xbf81_0000, + ]); + let ir = "\ +0000: t0 = const.u32 0x00000001 +0008: t1 = const.u32 0x00000002 +0010: t2 = wave.mask v_cmp_eq_u32_e32 t0, t1 exec=0xffffffff +0014: t3 = wave.mask v_cmp_eq_u32_e32 t0, t1 exec=0xffffffff +0018: t4 = const.u32 0x00000000 +0020: store.u32 output[index], t4 +"; + let off = compile_options(&code, false, false); + let on = compile_options(&code, false, true); + assert_eq!(off.ir, ir); + assert_eq!(on.ir, ir); + assert_eq!(on.ir.matches("wave.mask").count(), 2); + assert!(!on.ir.contains("reuse.u32")); +} + +#[test] +fn does_not_merge_lane_merges_under_partial_exec() { + // EXEC = 1 merges each and with that destination's previous value. + // The and itself is pure and is reused. The two merges see different + // inactive values (the two zero temps) and both remain. + let code = words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + 0xff00_ff00, + mov_lit(3), + 0, // v3 initialized before the partial write + mov_lit(4), + 0, // v4 initialized before the partial write + 0xbefe_0381, // s_mov_b32 exec_lo, 1 + vop2(27, 3, 1, 2), // v_and_b32 v3, v1, v2 + vop2(27, 4, 1, 2), // v_and_b32 v4, v1, v2 + 0xbefe_03c1, // s_mov_b32 exec_lo, -1 + 0xe070_2000, + 0x8001_0300, // buffer_store_dword v3 + 0xbbfd_0000, + 0xbf81_0000, + ]); + let off = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0xff00ff00 +0014: t2 = const.u32 0x00000000 +001c: t3 = const.u32 0x00000000 +0028: t4 = and.b32 t0, t1 +0028: t5 = merge.lanes mask=0x00000001, t4, t2 +002c: t6 = and.b32 t0, t1 +002c: t7 = merge.lanes mask=0x00000001, t6, t3 +0034: store.u32 output[index], t5 +"; + let on = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0xff00ff00 +0014: t2 = const.u32 0x00000000 +001c: t3 = const.u32 0x00000000 +0028: t4 = and.b32 t0, t1 +0028: t5 = merge.lanes mask=0x00000001, t4, t2 +002c: t6 = reuse.u32 t4 +002c: t7 = merge.lanes mask=0x00000001, t4, t3 +0034: store.u32 output[index], t5 +"; + assert_eq!(compile_options(&code, false, false).ir, off); + assert_eq!(compile_options(&code, false, true).ir, on); + assert_eq!( + compile_options(&code, false, true) + .ir + .matches("merge.lanes") + .count(), + 2 + ); +} + +#[test] +fn does_not_merge_vcc_select() { + // v_cndmask_b32 reads VCC. Two identical selects stay two vcc.Select ops. + let code = words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + 0x1111_1111, + 0xbeea_0381, // s_mov_b32 vcc_lo, 1 + vop2(1, 3, 1, 2), // v_cndmask_b32 v3, v1, v2 + vop2(1, 4, 1, 2), // v_cndmask_b32 v4, v1, v2 + 0xe070_2000, + 0x8001_0300, + 0xbbfd_0000, + 0xbf81_0000, + ]); + let ir = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0x11111111 +0018: t2 = const.u32 0x00000001 +0018: t3 = vcc.Select t0, t1, t2 +001c: t4 = const.u32 0x00000001 +001c: t5 = vcc.Select t0, t1, t4 +0020: store.u32 output[index], t3 +"; + let off = compile_options(&code, false, false); + let on = compile_options(&code, false, true); + assert_eq!(off.ir, ir); + assert_eq!(on.ir, ir); + assert_eq!(on.ir.matches("vcc.Select").count(), 2); + assert!(!on.ir.contains("reuse.u32")); +} + +#[test] +fn cse_leaves_branch_and_float_fixtures_unchanged() { + // No duplicate pure expression, so the pass is a no-op, including on the + // uniform branches and the load-derived float ops. + for (code, ir) in [ + ( + BRANCH, + include_str!("../../../fixtures/golden/bitwise-branch.ir"), + ), + ( + FLOAT, + include_str!("../../../fixtures/golden/float-exact.ir"), + ), + ] { + let plain = compile(Architecture::Gfx1030, code).unwrap(); + let on = compile_options(code, false, true); + assert_eq!(plain.ir, ir); + assert_eq!(on.ir, plain.ir); + assert_eq!(on.msl, plain.msl); + } +} + +#[test] +fn cse_leaves_every_golden_fixture_unchanged() { + // None of these fixtures repeats a pure op. Several use equal-bit + // constants in different ops whose operands must not be renamed. + macro_rules! golden { + ($name:literal) => {{ + let code = include_bytes!(concat!("../../../fixtures/rdna2/", $name, ".bin")); + let shader = compile_options(code, false, true); + assert_eq!( + shader.ir, + include_str!(concat!("../../../fixtures/golden/", $name, ".ir")), + "ir changed for {}", + $name + ); + assert_eq!( + shader.msl, + include_str!(concat!("../../../fixtures/golden/", $name, ".metal")), + "msl changed for {}", + $name + ); + }}; + } + golden!("add"); + golden!("bitwise-branch"); + golden!("float-exact"); + golden!("scalar-alu"); + golden!("scalar-arith"); + golden!("scalar-compare"); + golden!("scalar-immediate"); + golden!("scalar-logic"); + golden!("scalar-unary"); + golden!("vector-compare"); + golden!("vector-compare-ft"); + golden!("vector-integer"); + golden!("vector-unary"); +} + +/// 1 + 2 = 3, and the same add twice, then and the load with each sum. +fn fold_and_cse_fixture() -> Vec { + words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + 1, + mov_lit(3), + 2, + vop2(37, 4, 2, 3), // v_add_nc_u32 v4, v2, v3 + vop2(37, 5, 2, 3), // v_add_nc_u32 v5, v2, v3 + vop2(27, 6, 1, 4), // v_and_b32 v6, v1, v4 + vop2(27, 7, 1, 5), // v_and_b32 v7, v1, v5 + 0xe070_2000, + 0x8001_0700, + 0xbbfd_0000, + 0xbf81_0000, + ]) +} + +#[test] +fn cse_interacts_with_constant_folding() { + // Hand-computed: 1 + 2 = 3 (0x00000003). Folding rewrites the adds and + // does not reuse the ands. CSE reuses both the add and the and, and does + // not invent the constant 3. Both passes: the adds are constants first, + // the two const 3 temps stay, and the ands reuse because those temps have + // the same bits. + let code = fold_and_cse_fixture(); + let off = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0x00000001 +0014: t2 = const.u32 0x00000002 +001c: t3 = add.u32 t1, t2 +0020: t4 = add.u32 t1, t2 +0024: t5 = and.b32 t0, t3 +0028: t6 = and.b32 t0, t4 +002c: store.u32 output[index], t6 +"; + let cse_only = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0x00000001 +0014: t2 = const.u32 0x00000002 +001c: t3 = add.u32 t1, t2 +0020: t4 = reuse.u32 t3 +0024: t5 = and.b32 t0, t3 +0028: t6 = reuse.u32 t5 +002c: store.u32 output[index], t5 +"; + let fold_only = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0x00000001 +0014: t2 = const.u32 0x00000002 +001c: t3 = const.u32 0x00000003 +0020: t4 = const.u32 0x00000003 +0024: t5 = and.b32 t0, t3 +0028: t6 = and.b32 t0, t4 +002c: store.u32 output[index], t6 +"; + let both = "\ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0x00000001 +0014: t2 = const.u32 0x00000002 +001c: t3 = const.u32 0x00000003 +0020: t4 = const.u32 0x00000003 +0024: t5 = and.b32 t0, t3 +0028: t6 = reuse.u32 t5 +002c: store.u32 output[index], t5 +"; + assert_eq!(compile_options(&code, false, false).ir, off); + assert_eq!(compile_options(&code, false, true).ir, cse_only); + assert_eq!(compile_options(&code, true, false).ir, fold_only); + assert_eq!(compile_options(&code, true, true).ir, both); + assert!(!cse_only.contains("0x00000003")); + assert_eq!(fold_only.matches("const.u32 0x00000003").count(), 2); + assert_eq!(both.matches("and.b32").count(), 1); + assert!(!both.contains("add.u32")); +} + +#[test] +fn cse_does_not_fold_exact_float_add() { + // 1.0 + 2.0 = 3.0 exactly. Bits 0x3f800000 + 0x40000000 = 0x40400000. + // CSE reuses the add and leaves the operation. Folding replaces both + // adds with that constant. Enabling both matches folding alone: the adds + // are gone before reuse, and the two result constants are not merged. + let code = words(&[ + mov_lit(2), + 0x3f80_0000, + mov_lit(3), + 0x4000_0000, + vop2(3, 4, 2, 3), // v_add_f32 v4, v2, v3 + vop2(3, 5, 2, 3), // v_add_f32 v5, v2, v3 + 0xe070_2000, + 0x8001_0500, + 0xbbfd_0000, + 0xbf81_0000, + ]); + let cse_ir = "\ +0000: t0 = const.u32 0x3f800000 +0008: t1 = const.u32 0x40000000 +0010: t2 = add.f32 t0, t1 +0014: t3 = reuse.u32 t2 +0018: store.u32 output[index], t2 +"; + let fold_ir = "\ +0000: t0 = const.u32 0x3f800000 +0008: t1 = const.u32 0x40000000 +0010: t2 = const.u32 0x40400000 +0014: t3 = const.u32 0x40400000 +0018: store.u32 output[index], t3 +"; + let cse_msl = "\ +#include +using namespace metal; +kernel void xenora_compute( + device const uint* input [[buffer(0)]], + device uint* output [[buffer(1)]], + uint index [[thread_position_in_grid]]) { + #pragma clang fp contract(off) + #pragma clang fp reassociate(off) + uint t0 = 0x3f800000u; + uint t1 = 0x40000000u; + uint t2 = as_type(as_type(t0) + as_type(t1)); + uint t3 = t2; + output[index] = t2; +} +"; + let folded = compile_options(&code, true, false); + let both = compile_options(&code, true, true); + assert_eq!(compile_options(&code, false, true).ir, cse_ir); + assert_eq!(compile_options(&code, false, true).msl, cse_msl); + assert_eq!(folded.ir, fold_ir); + assert_eq!(both.ir, folded.ir); + assert_eq!(both.msl, folded.msl); + assert!(!cse_ir.contains("0x40400000")); + assert_eq!(fold_ir.matches("const.u32 0x40400000").count(), 2); +} + +#[test] +fn cse_does_not_bypass_inexact_float_verification() { + // Same pair the folder refuses: 1.0 + 2^-24 is not an f32 value. Verify + // rejects it before either optional pass. + let code = binary_const_fixture(3, 0x3f80_0000, 0x3380_0000, false); + for fold in [false, true] { + for cse in [false, true] { + let result = compile_with( + Architecture::Gfx1030, + &code, + CompileOptions { + fold_constants: fold, + eliminate_common_subexpressions: cse, + }, + ); + assert!( + matches!(result, Err(CompileError::Verify { .. })), + "fold={fold} cse={cse} must reject at verify: {result:?}" + ); + } + } +} From f0c61c7a91bddcfbfbe65a8376394536591024ab Mon Sep 17 00:00:00 2001 From: devil8blade <360741796+devil8blade@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:01:31 -0500 Subject: [PATCH 07/12] loader: copy mid-size TLS templates into the zeroed block (#111) Templates from 64 KiB up to 1 MiB were staged in a second buffer and copied again into the thread block. Proving those bytes readable, then copying them into the block that is already zeroed, avoids that buffer and still maps nothing when the template cannot be read. Smaller templates and templates of 1 MiB or more keep the single staged read, which measured as fast or faster. Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/loader/src/tls.rs | 451 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 441 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a99346d..f5daf2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation. - Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle). - The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only. - Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104). diff --git a/crates/loader/src/tls.rs b/crates/loader/src/tls.rs index 684ec05..6538e46 100644 --- a/crates/loader/src/tls.rs +++ b/crates/loader/src/tls.rs @@ -233,6 +233,22 @@ fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result, /// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array. const TLS_ARRAY_SIZE: usize = 0x1000; +/// Bytes read per step when a template is checked and then copied into its +/// block. +const TEMPLATE_COPY_CHUNK: usize = 4096; + +/// Smallest template copied into the zeroed block instead of a staging buffer. +/// +/// Release timings of original synthetic templates on an Apple M2 Pro put the +/// point where a second buffer dominates at 64 KiB. Below that, one read into +/// a staging buffer is as fast or faster. +const DIRECT_TEMPLATE_MIN: usize = 64 * 1024; + +/// Templates at least this big keep the single staged read. On the same +/// machine, proving the bytes readable and then copying them was no faster +/// than the staging buffer once the template reached 1 MiB. +const DIRECT_TEMPLATE_LIMIT: usize = 1024 * 1024; + /// Set up TLS runtime state in guest memory: /// 1. Assign TLS index 0 at `index_address`. /// 2. Map the thread's TLS pointer array at `thread_tls_base`. @@ -244,6 +260,12 @@ const TLS_ARRAY_SIZE: usize = 0x1000; /// TLS pointer. Compiled code loads that pointer, indexes it by the module's /// TLS index to find the data block, and then adds a variable's offset, so the /// array and the data are separate regions. +/// +/// The block is the template followed by `SizeOfZeroFill` zero bytes. A +/// template of at least 64 KiB and below 1 MiB is proved readable and then +/// copied into a zeroed block. Every other size is read once into a staging +/// buffer that initializes the block. Either way, a template that cannot be +/// read leaves the pointer array unmapped. pub fn setup_tls( tls: &TlsDirectory, loaded_base: u64, @@ -278,11 +300,19 @@ pub fn setup_tls( let total_size = template_size + (tls.size_of_zero_fill as usize); if total_size > 0 { - // Read template bytes from image - let mut template_data = vec![0u8; template_size]; - if template_size > 0 { - memory.read_bytes(actual_start, &mut template_data)?; - } + let direct = (DIRECT_TEMPLATE_MIN..DIRECT_TEMPLATE_LIMIT).contains(&template_size); + // The read happens before anything is mapped, so a missing or + // unreadable template does not leave a pointer array behind. + let staged = if direct { + prove_template_readable(memory, actual_start, template_size)?; + None + } else { + let mut staged = vec![0u8; template_size]; + if template_size > 0 { + memory.read_bytes(actual_start, &mut staged)?; + } + Some(staged) + }; // Allocate the pointer array and the per-thread TLS block. let block_base = thread_tls_base @@ -295,12 +325,17 @@ pub fn setup_tls( TLS_ARRAY_SIZE, MemoryPermissions::READ_WRITE, )?; - memory.map_region_with_data( - block_base, - map_size, - MemoryPermissions::READ_WRITE, - &template_data, - )?; + if let Some(staged) = staged.as_deref() { + memory.map_region_with_data( + block_base, + map_size, + MemoryPermissions::READ_WRITE, + staged, + )?; + } else { + memory.map_region(block_base, map_size, MemoryPermissions::READ_WRITE)?; + copy_template(memory, actual_start, block_base, template_size)?; + } // Slot 0 belongs to the index assigned above. memory.write_u64(thread_tls_base, block_base)?; } @@ -308,6 +343,44 @@ pub fn setup_tls( Ok(()) } +/// Read every template byte, discarding the contents. +/// +/// Failure here means the template is not available. Callers map the block +/// only after this returns. +fn prove_template_readable(memory: &GuestMemory, addr: u64, len: usize) -> Result<(), TlsError> { + let mut chunk = [0u8; TEMPLATE_COPY_CHUNK]; + let mut offset = 0usize; + while offset < len { + let n = (len - offset).min(TEMPLATE_COPY_CHUNK); + let at = addr + .checked_add(offset as u64) + .ok_or(MemoryError::Overflow)?; + memory.read_bytes(at, &mut chunk[..n])?; + offset += n; + } + Ok(()) +} + +/// Copy `len` bytes from `src` to `dst`. `dst` is already zeroed, which is the +/// template's `SizeOfZeroFill` and the rounded tail of the block. +fn copy_template(memory: &mut GuestMemory, src: u64, dst: u64, len: usize) -> Result<(), TlsError> { + let mut chunk = [0u8; TEMPLATE_COPY_CHUNK]; + let mut offset = 0usize; + while offset < len { + let n = (len - offset).min(TEMPLATE_COPY_CHUNK); + let from = src + .checked_add(offset as u64) + .ok_or(MemoryError::Overflow)?; + let to = dst + .checked_add(offset as u64) + .ok_or(MemoryError::Overflow)?; + memory.read_bytes(from, &mut chunk[..n])?; + memory.write_bytes(to, &chunk[..n])?; + offset += n; + } + Ok(()) +} + /// Execute all registered TLS callbacks in sequence. /// Signature: void (NTAPI *PIMAGE_TLS_CALLBACK)(PVOID DllHandle, DWORD Reason, PVOID Reserved); /// - RCX = DllHandle (loaded_base) @@ -392,6 +465,8 @@ mod tests { use super::*; use crate::pe::PeSection; + use std::hint::black_box; + use std::time::Instant; const IMAGE_BASE: u64 = 0x1_4000_0000; const SECTION_RVA: u32 = 0x1000; @@ -680,4 +755,358 @@ mod tests { assert_eq!(none, Ok(0)); } } + + /// Bytes that do not repeat every 256 or every 4096 bytes, so a chunk + /// copied from the wrong offset cannot match. + fn synthetic_template(len: usize) -> Vec { + (0..len) + .map(|index| { + let mixed = index ^ (index >> 8) ^ (index >> 16); + mixed.wrapping_mul(131).wrapping_add(17) as u8 + }) + .collect() + } + + /// Image template at `template_at`, with `sentinel` 0xA5 bytes after it, and + /// a writable index that does not start at zero. + fn template_memory( + template_at: u64, + template: &[u8], + sentinel: usize, + index_at: u64, + ) -> GuestMemory { + let mut image = template.to_vec(); + image.extend(std::iter::repeat_n(0xA5, sentinel)); + let map = (image.len() + 0xFFF) & !0xFFF; + image.resize(map, 0); + let mut memory = GuestMemory::new(); + memory + .map_region_with_data(template_at, map, MemoryPermissions::READ_ONLY, &image) + .unwrap(); + memory + .map_region_with_data(index_at, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8]) + .unwrap(); + memory + } + + fn directory_at( + template_at: u64, + template_len: u64, + index_at: u64, + zero_fill: u32, + ) -> TlsDirectory { + TlsDirectory { + raw_data_start_va: template_at, + raw_data_end_va: template_at + template_len, + index_address: index_at, + size_of_zero_fill: zero_fill, + ..TlsDirectory::default() + } + } + + fn assert_block( + memory: &GuestMemory, + thread: u64, + index: u64, + template: &[u8], + zero_fill: usize, + ) { + assert_eq!(memory.read_u32(index).unwrap(), 0); + let block = memory.read_u64(thread).unwrap(); + assert_eq!(block, thread + 0x1000, "the data block is the next page"); + // The block is mapped up to the next page boundary and no further. + let mapped = (template.len() + zero_fill + 0xFFF) & !0xFFF; + let mut got = vec![0xEEu8; mapped]; + memory.read_bytes(block, &mut got).unwrap(); + assert_eq!(&got[..template.len()], template); + assert!(got[template.len()..].iter().all(|byte| *byte == 0)); + let end = block + mapped as u64; + assert_eq!(memory.read_u8(end), Err(MemoryError::UnmappedAddress(end))); + } + + const TEMPLATE_AT: u64 = 0x2_0020_0000; + const INDEX_AT: u64 = 0x2_0000_1000; + const THREAD_AT: u64 = 0x5_0000_0000; + + #[test] + fn a_small_template_is_copied_and_zero_fill_does_not_take_the_following_bytes() { + let template = synthetic_template(48); + let mut memory = template_memory(TEMPLATE_AT, &template, 16, INDEX_AT); + setup_tls( + &directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 16), + IMAGE_BASE, + IMAGE_BASE, + &mut memory, + THREAD_AT, + ) + .unwrap(); + assert_block(&memory, THREAD_AT, INDEX_AT, &template, 16); + let mut tail = [0u8; 16]; + memory + .read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail) + .unwrap(); + assert_eq!(tail, [0xA5; 16]); + let block = memory.read_u64(THREAD_AT).unwrap(); + memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap(); + let mut image = [0u8; 8]; + memory.read_bytes(TEMPLATE_AT + 8, &mut image).unwrap(); + assert_eq!(image, template[8..16]); + } + + #[test] + fn the_staged_and_direct_copy_boundaries_keep_every_template_byte() { + for len in [ + DIRECT_TEMPLATE_MIN - 1, + DIRECT_TEMPLATE_MIN, + DIRECT_TEMPLATE_MIN + TEMPLATE_COPY_CHUNK + 100, + DIRECT_TEMPLATE_LIMIT - 1, + DIRECT_TEMPLATE_LIMIT, + ] { + let template = synthetic_template(len); + let mut memory = template_memory(TEMPLATE_AT, &template, 24, INDEX_AT); + setup_tls( + &directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 24), + IMAGE_BASE, + IMAGE_BASE, + &mut memory, + THREAD_AT, + ) + .unwrap(); + assert_block(&memory, THREAD_AT, INDEX_AT, &template, 24); + let mut tail = [0u8; 24]; + memory + .read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail) + .unwrap(); + assert_eq!(tail, [0xA5; 24], "len {len}"); + } + } + + #[test] + fn a_rebased_direct_copy_reads_the_loaded_image() { + let template = synthetic_template(DIRECT_TEMPLATE_MIN); + let preferred = 0x1_4000_0000u64; + let loaded = preferred + 0x80_0000; + let template_at = preferred + 0x20_0000; + let index_at = preferred + 0x1000; + let mut memory = + template_memory(template_at + 0x80_0000, &template, 0, index_at + 0x80_0000); + setup_tls( + &directory_at(template_at, template.len() as u64, index_at, 8), + loaded, + preferred, + &mut memory, + THREAD_AT, + ) + .unwrap(); + assert_block(&memory, THREAD_AT, index_at + 0x80_0000, &template, 8); + } + + #[test] + fn an_unreadable_template_maps_no_pointer_array() { + for len in [32usize, DIRECT_TEMPLATE_MIN, DIRECT_TEMPLATE_MIN + 50] { + let mut missing = GuestMemory::new(); + missing + .map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8]) + .unwrap(); + let missing_result = setup_tls( + &directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0), + IMAGE_BASE, + IMAGE_BASE, + &mut missing, + THREAD_AT, + ); + assert_eq!( + missing_result, + Err(TlsError::Memory(MemoryError::UnmappedAddress(TEMPLATE_AT))), + "{len}" + ); + assert_eq!(missing.read_u32(INDEX_AT).unwrap(), 0); + assert!(matches!( + missing.read_u64(THREAD_AT), + Err(MemoryError::UnmappedAddress(_)) + )); + + let mut denied = GuestMemory::new(); + denied + .map_region(TEMPLATE_AT, len.max(0x1000), MemoryPermissions::NO_ACCESS) + .unwrap(); + denied + .map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8]) + .unwrap(); + let denied_result = setup_tls( + &directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0), + IMAGE_BASE, + IMAGE_BASE, + &mut denied, + THREAD_AT, + ); + assert_eq!( + denied_result, + Err(TlsError::Memory(MemoryError::PermissionViolation { + address: TEMPLATE_AT, + required: "read", + })), + "{len}" + ); + assert_eq!(denied.read_u32(INDEX_AT).unwrap(), 0); + assert!(matches!( + denied.read_u64(THREAD_AT), + Err(MemoryError::UnmappedAddress(_)) + )); + } + } + + #[test] + fn a_direct_copy_template_that_runs_out_of_its_mapping_maps_nothing() { + let len = DIRECT_TEMPLATE_MIN + 100; + let mut memory = GuestMemory::new(); + // Only the first chunk is mapped. The rest of the template is not. + memory + .map_region_with_data( + TEMPLATE_AT, + TEMPLATE_COPY_CHUNK, + MemoryPermissions::READ_ONLY, + &synthetic_template(TEMPLATE_COPY_CHUNK), + ) + .unwrap(); + memory + .map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8]) + .unwrap(); + let result = setup_tls( + &directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0), + IMAGE_BASE, + IMAGE_BASE, + &mut memory, + THREAD_AT, + ); + // The same first unreadable byte the single staged read reports. + assert_eq!( + result, + Err(TlsError::Memory(MemoryError::UnmappedAddress( + TEMPLATE_AT + TEMPLATE_COPY_CHUNK as u64 + ))) + ); + assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0); + assert!(matches!( + memory.read_u64(THREAD_AT), + Err(MemoryError::UnmappedAddress(_)) + )); + } + + #[test] + fn an_empty_template_and_zero_fill_only_assigns_the_index() { + let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT); + setup_tls( + &directory_at(TEMPLATE_AT, 0, INDEX_AT, 0), + IMAGE_BASE, + IMAGE_BASE, + &mut memory, + THREAD_AT, + ) + .unwrap(); + assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0); + assert!(matches!( + memory.read_u64(THREAD_AT), + Err(MemoryError::UnmappedAddress(_)) + )); + } + + #[test] + fn a_zero_fill_only_block_is_zero_and_separate_from_the_array() { + let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT); + setup_tls( + &directory_at(TEMPLATE_AT, 0, INDEX_AT, 24), + IMAGE_BASE, + IMAGE_BASE, + &mut memory, + THREAD_AT, + ) + .unwrap(); + assert_block(&memory, THREAD_AT, INDEX_AT, &[], 24); + } + + /// Byte pattern from the before/after timing runs. It is not the pattern + /// the correctness tests use to catch a chunk copied from the wrong offset. + fn timed_template(len: usize) -> Vec { + (0..len) + .map(|index| (index.wrapping_mul(131).wrapping_add(17)) as u8) + .collect() + } + + fn timed_guest(template_len: usize, zero_fill: u32) -> (GuestMemory, TlsDirectory) { + let template = timed_template(template_len); + let mut memory = GuestMemory::new(); + if template_len > 0 { + let map = (template_len + 0xFFF) & !0xFFF; + memory + .map_region_with_data(TEMPLATE_AT, map, MemoryPermissions::READ_ONLY, &template) + .unwrap(); + } + memory + .map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8]) + .unwrap(); + ( + memory, + directory_at(TEMPLATE_AT, template_len as u64, INDEX_AT, zero_fill), + ) + } + + #[test] + #[ignore = "manual TLS template timing run; release build on an otherwise idle host"] + fn tls_template_initialization_profile() { + // Sizes, zero fill and batch counts from the interleaved before/after runs. + let cases = [ + (64usize, 0u32, 80usize), + (4096, 0, 40), + (65535, 0, 20), + (65536, 128, 16), + (262144, 0, 6), + (786432, 0, 4), + (1048576, 0, 4), + (0, 1048576, 4), + ]; + for (template_len, zero_fill, batch) in cases { + let (mut memory, directory) = timed_guest(template_len, zero_fill); + setup_tls(&directory, IMAGE_BASE, IMAGE_BASE, &mut memory, THREAD_AT).unwrap(); + if template_len > 0 { + let template = timed_template(template_len); + let block = memory.read_u64(THREAD_AT).unwrap(); + let mut byte = [0u8; 1]; + memory.read_bytes(block, &mut byte).unwrap(); + assert_eq!(byte[0], template[0]); + memory + .read_bytes(block + template_len as u64 - 1, &mut byte) + .unwrap(); + assert_eq!(byte[0], template[template_len - 1]); + } + + let mut samples = Vec::new(); + for run in 0..33 { + let mut guests: Vec<_> = (0..batch) + .map(|_| timed_guest(template_len, zero_fill)) + .collect(); + let start = Instant::now(); + for (memory, directory) in &mut guests { + setup_tls(directory, IMAGE_BASE, IMAGE_BASE, memory, THREAD_AT).unwrap(); + black_box(memory); + } + if run >= 2 { + let per_ns = start.elapsed().as_secs_f64() * 1e9 / batch as f64; + samples.push(per_ns); + } + } + samples.sort_by(f64::total_cmp); + let n = samples.len(); + let mean = samples.iter().sum::() / n as f64; + let sample_variance = samples + .iter() + .map(|sample| (sample - mean).powi(2)) + .sum::() + / (n - 1) as f64; + println!( + "template={template_len} zero_fill={zero_fill} batch={batch} n={n} median_ns={:.1} sample_variance_ns2={sample_variance:.1}", + samples[n / 2] + ); + } + } } From bfe0bbfaf72996aec3512270c9d45301fde21dae Mon Sep 17 00:00:00 2001 From: Arths17 Date: Tue, 24 Nov 2026 20:51:08 -0600 Subject: [PATCH 08/12] Rename project and native applications to BetterXen Update active repository links and coordination settings while retaining upstream history, notices, legacy library names and guest interfaces. Document the independent-copy migration and its limits. Signed-off-by: Arths17 --- .github/agent-queue.json | 11 ++++--- .github/workflows/ci.yml | 4 +-- AGENTS.md | 10 +++---- CHANGELOG.md | 1 + CODE_OF_CONDUCT.md | 4 +-- CONTRIBUTING.md | 8 ++--- Cargo.lock | 2 +- README.md | 40 +++++++++++++------------ SECURITY.md | 4 +-- SUPPORT.md | 6 ++-- app/Package.swift | 4 +-- app/Sources/Xenora/main.swift | 6 ++-- crates/cli/Cargo.toml | 2 +- crates/cli/src/main.rs | 35 +++++++++++----------- crates/cli/src/runner.rs | 2 +- crates/cli/src/shaders.rs | 6 ++-- crates/cli/tests/default_report.rs | 4 +-- crates/cli/tests/imports_sync.rs | 10 +++---- docs/README.md | 6 ++-- docs/assets/xenora-progress.svg | 2 +- docs/cpu/instruction-registry.md | 2 +- docs/interfaces.md | 10 +++---- docs/legal.md | 6 ++-- docs/migration.md | 21 +++++++++++++ docs/progress.md | 2 +- scripts/audit/status.py | 2 +- scripts/build-app.sh | 14 ++++----- scripts/demo.sh | 4 +-- scripts/qa/repo_health.py | 2 +- tests/agent_queue/test_workflows_cli.py | 2 +- tests/compat_fixtures/README.md | 2 +- 31 files changed, 130 insertions(+), 104 deletions(-) create mode 100644 docs/migration.md diff --git a/.github/agent-queue.json b/.github/agent-queue.json index 100a227..00a7d60 100644 --- a/.github/agent-queue.json +++ b/.github/agent-queue.json @@ -1,9 +1,8 @@ { "lease_hours": 168, - "upstream": "ranveersoni98/Xenora", - "maintainers": ["ranveersoni98"], - "contributors": { - "ranveersoni98": ["cpu", "shared", "qa"], - "elforeign": ["gpu", "shared", "qa"] - } + "upstream": "MacosPorters/betterxen", + "maintainers": [ + "Arths17" + ], + "contributors": {} } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b3421c8..0e35ed7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,8 +72,8 @@ jobs: LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh - name: Inspect native CLI run: | - cargo build --locked -p xenora - binary=target/aarch64-apple-darwin/debug/xenora + cargo build --locked -p betterxen + binary=target/aarch64-apple-darwin/debug/betterxen file "$binary" test "$(lipo -archs "$binary")" = arm64 otool -L "$binary" diff --git a/AGENTS.md b/AGENTS.md index 7e5bb33..37e60ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,4 +1,4 @@ -# Xenora engineering rules +# BetterXen engineering rules ### Native Apple Silicon @@ -7,7 +7,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep - SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime. - All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L. - Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation. -- The guest architecture being decoded may be x86-64, but Xenora itself runs natively on ARM64. +- The guest architecture being decoded may be x86-64, but BetterXen itself runs natively on ARM64. - Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities. - Use aarch64-apple-darwin as the Rust target. @@ -20,7 +20,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep - Never replace GPU tests with mocks and then claim GPU support. - Unknown information is classified as unknown and becomes a documented research task. - Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one. -- Never claim "verified on Xbox hardware". Xenora has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so. +- Never claim "verified on Xbox hardware". BetterXen has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so. - Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score. ### Independence of verification @@ -32,9 +32,9 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep - Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions. - Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions. -- Include a plain statement in docs/legal.md: Xenora does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201. +- Include a plain statement in docs/legal.md: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201. - Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved. -- Keep Xenora's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects. +- Keep BetterXen's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects. - Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply. - Never place restricted material in the repository or its Git history. - Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness. diff --git a/CHANGELOG.md b/CHANGELOG.md index cbc4390..e8bf02e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained. - Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle). - The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only. - Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104). diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 3a1a9fb..a350fd1 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,6 +1,6 @@ # Code of Conduct -Xenora welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect. +BetterXen welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect. ## Expected behavior @@ -19,4 +19,4 @@ If possible, use an available private contact channel for a repository maintaine Maintainers may remove content, limit participation or block accounts when necessary to protect the community. Responses should be proportionate to the behavior and protect the privacy of affected people. Do not retaliate against anyone reporting a concern in good faith. -This policy applies to repository issues, pull requests, discussions and other spaces officially managed by Xenora. +This policy applies to repository issues, pull requests, discussions and other spaces officially managed by BetterXen. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3bf5724..687f4f6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ -# Contributing to Xenora +# Contributing to BetterXen -Xenora is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims. +BetterXen is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims. ## Getting started @@ -28,11 +28,11 @@ For a performance change, provide reproducible before-and-after results using eq ## Research and clean-room policy -Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under Xenora's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs. +Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs. Distinguish desktop RDNA behavior from Xbox-specific behavior. Cite primary sources with exact applicable architectures and record uncertainties using the project's evidence classification when available. Tests on Apple GPUs do not establish verification on Xbox hardware. -Xenora implements its own Rust guest runtime, decoder, typed IR, shader +BetterXen implements its own Rust guest runtime, decoder, typed IR, shader compiler and native Metal backend from public technical specifications and independently derived tests. Contributions must not copy, port or adapt code, decoder tables, internal metadata or implementation diff --git a/Cargo.lock b/Cargo.lock index 613d3f9..105d2ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -150,7 +150,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] -name = "xenora" +name = "betterxen" version = "0.1.0" dependencies = [ "xenora-decoder", diff --git a/README.md b/README.md index 5f5d38b..fc5b94f 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,25 @@ -# Xenora +# BetterXen + +BetterXen is an independent continuation copied from [XenoraOSS/Xenora](https://github.com/XenoraOSS/Xenora). The original Git history, licenses and contributor attribution are retained. See the [migration notes](docs/migration.md) for imported issue and pull-request history. **Experimental Xbox Series X|S emulation research for Apple Silicon Macs.** -Xenora is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend. +BetterXen is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend. **No Wine. No CrossOver. No Rosetta. No Vulkan runtime.** -Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations). +BetterXen is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations). > [!CAUTION] -> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft or any other publisher or platform holder. +> **BetterXen strictly opposes piracy.** BetterXen is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. BetterXen is not affiliated with Microsoft or any other publisher or platform holder. -[![Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml) +[![Native Rust checks](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml) --- ## What works today? -Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon. +BetterXen has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon. The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results. @@ -57,7 +59,7 @@ All existing verification refers to independently authored synthetic programs an ## Native graphics translation -Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language. +BetterXen's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language. The translation process is: @@ -164,7 +166,7 @@ The resource system remains experimental. Native GPU work already in flight duri ## Texture support -Xenora includes original texture upload, readback and block-compression paths. +BetterXen includes original texture upload, readback and block-compression paths. Implemented and tested functionality includes: @@ -183,7 +185,7 @@ Xbox-specific texture layouts and additional compression formats require further ## Architecture -Xenora is organized around three connected subsystems: guest execution, shader translation and native GPU execution. +BetterXen is organized around three connected subsystems: guest execution, shader translation and native GPU execution. ```mermaid flowchart TD @@ -230,7 +232,7 @@ flowchart TD end ``` -Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64. +BetterXen's host execution environment is native ARM64. The guest architecture being interpreted is x86-64. The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references. @@ -242,7 +244,7 @@ See [Interface Contracts](docs/interfaces.md) for the documented execution and r ## Current limitations -Xenora is an engineering research project, not a working commercial-game emulator. +BetterXen is an engineering research project, not a working commercial-game emulator. The following remain unsupported or incomplete: @@ -257,13 +259,13 @@ The following remain unsupported or incomplete: | Performance | Production-scale workloads, CPU/GPU profiling and optimized execution | | Game compatibility | No demonstrated execution of commercial Xbox titles | -Xenora's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility. +BetterXen's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility. Progress is measured by reproducible tests rather than estimated game compatibility percentages. --- -## Building Xenora +## Building BetterXen ### Requirements @@ -278,15 +280,15 @@ The recorded Apple M5 environment uses Rust 1.100.0 and Xcode 27.2. ### Clone ```sh -git clone https://github.com/ranveersoni98/Xenora.git -cd Xenora +git clone https://github.com/MacosPorters/betterxen.git +cd betterxen ``` ### Build ```sh scripts/bootstrap.sh -cargo build --locked -p xenora +cargo build --locked -p betterxen ``` ### Run core tests @@ -361,14 +363,14 @@ See the [roadmap table](#development-milestones) for proposed milestones, and th ### Contributors -[![Contributors](https://contrib.rocks/image?repo=ranveersoni98/Xenora)](https://github.com/ranveersoni98/Xenora/graphs/contributors) +[![Contributors](https://contrib.rocks/image?repo=MacosPorters/betterxen)](https://github.com/MacosPorters/betterxen/graphs/contributors) ## License -Xenora is licensed under the [GNU General Public License v3 or later](LICENSE). +BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries. -Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple. +BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple. --- diff --git a/SECURITY.md b/SECURITY.md index 8603d7a..6588c3c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,13 +2,13 @@ ## Scope -Xenora is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment. +BetterXen is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment. The project does not promise a fixed security support window at this stage. Report issues against a specific revision, preferably reproduced on current `main` where safe. ## Reporting vulnerabilities -Use [GitHub private vulnerability reporting](https://github.com/ranveersoni98/Xenora/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data. +Use [GitHub private vulnerability reporting](https://github.com/MacosPorters/betterxen/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data. Include the affected commit, environment, affected component, expected and actual behavior, impact and a minimal, authorized reproduction. Use synthetic inputs wherever possible. Do not attach protected content, leaked SDK material or proprietary shaders. diff --git a/SUPPORT.md b/SUPPORT.md index 51d4ecb..22db65d 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -1,9 +1,9 @@ # Getting help -Start with the [README](README.md) and the relevant documentation in the repository, if available. Xenora is an experimental research project, not a commercial game compatibility service. +Start with the [README](README.md) and the relevant documentation in the repository, if available. BetterXen is an experimental research project, not a commercial game compatibility service. -- Use [GitHub Issues](https://github.com/ranveersoni98/Xenora/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports. -- Use [GitHub Discussions](https://github.com/ranveersoni98/Xenora/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question. +- Use [GitHub Issues](https://github.com/MacosPorters/betterxen/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports. +- Use [GitHub Discussions](https://github.com/MacosPorters/betterxen/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question. - Follow [SECURITY.md](SECURITY.md) for security-sensitive reports. Include the exact revision, host architecture, macOS version, relevant tool versions, steps to reproduce and sanitized output. Do not share personal paths, private account information, protected game assets, credentials or confidential material. If the reported feature is not yet implemented, identify it as a request rather than a regression. diff --git a/app/Package.swift b/app/Package.swift index 1f2e076..c1d4a19 100644 --- a/app/Package.swift +++ b/app/Package.swift @@ -4,10 +4,10 @@ import PackageDescription let package = Package( - name: "Xenora", + name: "BetterXen", platforms: [.macOS(.v14)], targets: [ .systemLibrary(name: "CXenora", path: "Sources/CXenora"), - .executableTarget(name: "Xenora", dependencies: ["CXenora"]), + .executableTarget(name: "BetterXen", dependencies: ["CXenora"], path: "Sources/Xenora"), ] ) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index a3fb18f..9ab6667 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -834,13 +834,13 @@ struct ContentView: View { } } -struct XenoraApp: App { +struct BetterXenApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate let model = FrameModel() let loop = FrameLoopModel() var body: some Scene { - WindowGroup("Xenora") { ContentView(model: model, loop: loop) } + WindowGroup("BetterXen") { ContentView(model: model, loop: loop) } } } @@ -1015,4 +1015,4 @@ if CommandLine.arguments.contains("--smoke") { print(probe.summary) exit(probe.connected ? 0 : 1) } -XenoraApp.main() +BetterXenApp.main() diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 20c4160..005dc73 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "xenora" +name = "betterxen" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 55ba78d..5262052 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -13,7 +13,7 @@ fn main() -> ExitCode { match std::env::args().nth(1).as_deref() { Some("info") => { println!( - "Xenora {} ({})", + "BetterXen {} ({})", env!("CARGO_PKG_VERSION"), std::env::consts::ARCH ); @@ -21,7 +21,7 @@ fn main() -> ExitCode { } Some("inspect") => { let Some(file_path) = std::env::args().nth(2) else { - eprintln!("usage: xenora inspect "); + eprintln!("usage: betterxen inspect "); return ExitCode::from(2); }; match xenora_loader::triage_file(&file_path) { @@ -90,7 +90,7 @@ fn main() -> ExitCode { let Some(pe) = pe_path else { eprintln!( - "usage: xenora probe --pe [--mode ] [--report ]" + "usage: betterxen probe --pe [--mode ] [--report ]" ); return ExitCode::from(2); }; @@ -111,7 +111,7 @@ fn main() -> ExitCode { let config = xenora_loader::ProbeConfig::default(); match xenora_loader::run_probe_and_export(&bytes, &report_dir, &config) { Ok(report) => { - println!("Xenora static PE probe complete."); + println!("BetterXen static PE probe complete."); println!("Artifacts exported to: {report_dir}"); println!("Sections: {}", report.parsed.sections.len()); println!("Relocations: {}", report.relocations.total_entries); @@ -137,19 +137,19 @@ fn main() -> ExitCode { } } _ => { - eprintln!("usage: xenora "); + eprintln!("usage: betterxen "); ExitCode::from(2) } } } -/// `xenora imports sync [--report ] [--check]` -/// `xenora imports generate --pe [--out ]` -/// `xenora imports metadata sync [--out ]` -/// `xenora imports verify` +/// `betterxen imports sync [--report ] [--check]` +/// `betterxen imports generate --pe [--out ]` +/// `betterxen imports metadata sync [--out ]` +/// `betterxen imports verify` fn imports_command(args: Vec) -> ExitCode { if args.is_empty() { - eprintln!("usage: xenora imports [options]"); + eprintln!("usage: betterxen imports [options]"); return ExitCode::from(2); } @@ -160,7 +160,7 @@ fn imports_command(args: Vec) -> ExitCode { "verify" => run_imports_verify_cli(&args[1..]), other => { eprintln!("unknown imports subcommand: {other}"); - eprintln!("usage: xenora imports [options]"); + eprintln!("usage: betterxen imports [options]"); ExitCode::from(2) } } @@ -331,7 +331,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode { } } else { eprintln!( - "usage: xenora imports generate <--pe | --csv > [--out ]" + "usage: betterxen imports generate <--pe | --csv > [--out ]" ); return ExitCode::from(2); }; @@ -437,9 +437,10 @@ fn run_imports_sync( let imports_csv_path = std::path::Path::new(report_dir).join("imports.csv"); if !imports_csv_path.exists() { - return Err( - format!("imports.csv not found in '{report_dir}'. Run `xenora probe` first.").into(), - ); + return Err(format!( + "imports.csv not found in '{report_dir}'. Run `betterxen probe` first." + ) + .into()); } // Build the standard registry to get current implementation state. @@ -525,11 +526,11 @@ fn run_imports_sync( // Build the refreshed import_backlog.md. let mut md = String::new(); - let _ = writeln!(md, "# Xenora import compatibility backlog"); + let _ = writeln!(md, "# BetterXen import compatibility backlog"); let _ = writeln!(md); let _ = writeln!( md, - "Generated by `xenora imports sync`. Do not edit manually." + "Generated by `betterxen imports sync`. Do not edit manually." ); let _ = writeln!( md, diff --git a/crates/cli/src/runner.rs b/crates/cli/src/runner.rs index d0a9156..45b2a4a 100644 --- a/crates/cli/src/runner.rs +++ b/crates/cli/src/runner.rs @@ -27,7 +27,7 @@ const TICKET: u64 = 17; const DRAW_RESULT: u64 = 0x42; const EXTENT: [usize; 2] = [4, 3]; const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255]; -const USAGE: &str = "usage: xenora run --pe --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]"; +const USAGE: &str = "usage: betterxen run --pe --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]"; struct Options { path: PathBuf, diff --git a/crates/cli/src/shaders.rs b/crates/cli/src/shaders.rs index ae86e3e..c4f2766 100644 --- a/crates/cli/src/shaders.rs +++ b/crates/cli/src/shaders.rs @@ -1,11 +1,11 @@ -//! `xenora shaders`: instruction inventory and stream inspection. +//! `betterxen shaders`: instruction inventory and stream inspection. use std::process::ExitCode; use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at}; use xenora_isa::meta::{self, EncodingFamily, FORMS, identify}; -const USAGE: &str = "usage: xenora shaders >"; +const USAGE: &str = "usage: betterxen shaders >"; pub fn command(args: &[String]) -> ExitCode { match args.first().map(String::as_str) { @@ -109,7 +109,7 @@ fn inspect(path: &str) -> ExitCode { ExitCode::SUCCESS } -/// The printed rows of `xenora shaders inspect`, the number of rows that do +/// The printed rows of `betterxen shaders inspect`, the number of rows that do /// not decode into executable instructions and the identification failure /// that ended the stream early, if any. struct Listing { diff --git a/crates/cli/tests/default_report.rs b/crates/cli/tests/default_report.rs index 3164f14..64997a6 100644 --- a/crates/cli/tests/default_report.rs +++ b/crates/cli/tests/default_report.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later -//! Default report folder of `xenora probe` and `xenora imports sync`. +//! Default report folder of `betterxen probe` and `betterxen imports sync`. use std::process::Command; @@ -13,7 +13,7 @@ fn probe_and_sync_use_the_same_default_folder() { let folder = std::env::temp_dir().join(format!("xenora-default-{}", std::process::id())); std::fs::create_dir(&folder).unwrap(); for arguments in [&["probe", "--pe", fixture][..], &["imports", "sync"]] { - let status = Command::new(env!("CARGO_BIN_EXE_xenora")) + let status = Command::new(env!("CARGO_BIN_EXE_betterxen")) .args(arguments) .current_dir(&folder) .status() diff --git a/crates/cli/tests/imports_sync.rs b/crates/cli/tests/imports_sync.rs index 1fb45b0..9ae7a1b 100644 --- a/crates/cli/tests/imports_sync.rs +++ b/crates/cli/tests/imports_sync.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later -//! `xenora imports sync` over a probe report that lists delay-loaded imports. +//! `betterxen imports sync` over a probe report that lists delay-loaded imports. use std::process::Command; @@ -13,8 +13,8 @@ fn backlog_leaves_out_delay_loaded_imports() { "/../../fixtures/pe/delay-imports.exe" ); let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id())); - let xenora = |arguments: &[&str]| { - let status = Command::new(env!("CARGO_BIN_EXE_xenora")) + let betterxen = |arguments: &[&str]| { + let status = Command::new(env!("CARGO_BIN_EXE_betterxen")) .args(arguments) .arg("--report") .arg(&report) @@ -22,8 +22,8 @@ fn backlog_leaves_out_delay_loaded_imports() { .unwrap(); assert!(status.success(), "{arguments:?}"); }; - xenora(&["probe", "--pe", fixture]); - xenora(&["imports", "sync"]); + betterxen(&["probe", "--pe", fixture]); + betterxen(&["imports", "sync"]); let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap(); let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap(); std::fs::remove_dir_all(report).unwrap(); diff --git a/docs/README.md b/docs/README.md index 89a2ada..3b27d18 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,4 +1,4 @@ -# Xenora documentation +# BetterXen documentation ## Getting started @@ -63,7 +63,9 @@ either path. The [changelog](../CHANGELOG.md) records notable changes. - [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings. - [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements. - [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents. -- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Progress ledger for the Xenora native CPU and runtime compatibility campaign: starting/current commits, completed batches, new forms, verification evidence and the next implementation target. +- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Progress ledger for the BetterXen native CPU and runtime compatibility campaign: starting/current commits, completed batches, new forms, verification evidence and the next implementation target. - [Infrastructure QA ownership](coordination/infrastructure-qa-ownership.md) — Non-overlapping paths for infrastructure and QA tooling. - [Agent queue smoke evidence](coordination/agent-queue-smoke.md) — Live Actions results from the disposable smoke repository. - [Infrastructure QA tooling](testing/infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks. + +- [Migration to BetterXen](migration.md): source attribution, imported history and compatibility names. diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index 81b88cd..bcb5dda 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,5 +1,5 @@ -Xenora · recorded progress +BetterXen · recorded progress Decoded gfx1030 forms: 185 of 185. Accepted Metal forms · Apple M5: 18 of 185. Accepted guest milestones · X1–X4: 4 of 4 diff --git a/docs/cpu/instruction-registry.md b/docs/cpu/instruction-registry.md index f55af79..13b6c46 100644 --- a/docs/cpu/instruction-registry.md +++ b/docs/cpu/instruction-registry.md @@ -95,7 +95,7 @@ CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences: - SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too. -- The table is therefore truthful about Xenora, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not. +- The table is therefore truthful about BetterXen, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not. - A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first. `xenora_loader::cpu::cpuid` is the one copy of the table. A runtime service that reports processor features should read it rather than keep its own list. diff --git a/docs/interfaces.md b/docs/interfaces.md index 342db01..44af6ee 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -104,7 +104,7 @@ section table and data directories; it cannot write or execute them. When startup loads an image away from its preferred base, it writes the load base into the mapped optional header's `ImageBase` field after the relocations have been applied, so an entry aimed at that field cannot leave any other value -there. This is Xenora's policy: the PE specification defines `ImageBase` as the +there. This is BetterXen's policy: the PE specification defines `ImageBase` as the preferred base, and the behaviour has not been compared with Windows. The load is refused with `PeError::InvalidHeaderSize` when `SizeOfHeaders` is @@ -117,9 +117,9 @@ pages count toward the 256 MiB mapping budget of one image, which is checked before anything is mapped. `ParsedPe::parse` does not make these checks, so static inspection of a file is unchanged. -`xenora probe --mode static` inventories ordinary and delay-loaded PE imports +`betterxen probe --mode static` inventories ordinary and delay-loaded PE imports without guest execution. Without `--report` it writes to `diagnostics/probe`, -where `xenora imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys +where `betterxen imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys with their import address table relative virtual addresses. The full inventory, `imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table` column and records whether each key is registered, its implementation @@ -138,7 +138,7 @@ ordinal, and slot in the delay import address table, after the ordinary rows. Binding does not resolve them: the PE format leaves that to a delay-load helper inside the image. The totals above and `missing_imports.csv` therefore cover ordinary imports only, and the JSON report counts delayed slots and DLLs in -`delayed_imports` and `delayed_imported_dlls_count`. `xenora imports sync` +`delayed_imports` and `delayed_imported_dlls_count`. `betterxen imports sync` leaves delayed rows out of its backlog for the same reason. The probe reads only descriptors that lie wholly inside the directory's @@ -475,7 +475,7 @@ four row-major Block Compression 1 (BC1) blocks, including slots beyond the logical edge. The reader validates the full byte length, rejects padding coordinates and can decode each logical block to sixteen RGBA8 texels. The decoder uses bit replication to expand 5:6:5 endpoints and rounds integer -palette interpolation down. This layout is specific to Xenora fixtures. The block encoding follows the +palette interpolation down. This layout is specific to BetterXen fixtures. The block encoding follows the [Direct3D BC1 description](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression). `TiledBc1::linearize` strips the tile padding from one selected subresource diff --git a/docs/legal.md b/docs/legal.md index 79b8c41..4dd350b 100644 --- a/docs/legal.md +++ b/docs/legal.md @@ -1,14 +1,14 @@ # Clean-room scope -Xenora does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. +BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. ## User-provided game files -Users obtain and supply their own files. Xenora evaluates file structure, +Users obtain and supply their own files. BetterXen evaluates file structure, supported features, compatibility and safe execution. Game import does not check ownership, request receipts or account verification, investigate acquisition, or block a technically supported file solely because its -origin is unknown. Xenora does not distribute or host commercial game +origin is unknown. BetterXen does not distribute or host commercial game files or provide acquisition services. ## Project contributions and testing diff --git a/docs/migration.md b/docs/migration.md new file mode 100644 index 0000000..ed8eb43 --- /dev/null +++ b/docs/migration.md @@ -0,0 +1,21 @@ +# Migration to BetterXen + +BetterXen is an independent copy of [XenoraOSS/Xenora](https://github.com/XenoraOSS/Xenora), hosted at [MacosPorters/betterxen](https://github.com/MacosPorters/betterxen). This is a copy, not a GitHub ownership transfer. The source repository remains unchanged. + +## Preserved history + +Original commits and authorship are retained. Available pull-request head and merge refs are preserved as `archive/pull//head` and `archive/pull//merge` branches. Not every historical PR ref is still exposed by the source; the metadata archive also includes patches obtained through GitHub's API. + +Issues are recreated with original-source links, author attribution and archived comment text. Original timestamps and authors cannot be assigned to recreated GitHub records. Destination issue and pull-request numbers differ. Historical `#number` references in upstream records refer to the original repository; consult the source link and number maps in the migration archive. + +Open PRs are recreated against copied branches. Closed and merged PRs are retained as historical archive records, including descriptions, comments, reviews, changed-file metadata, commits and patches; they are not represented as newly merged work. Recreated PRs do not inherit approvals or check results. + +The migration archive is attached to the repository's migration release. It includes JSON metadata, a readable issue/PR index, patches and original-to-destination number maps. It records the public state observed during migration, not an atomic snapshot. Linked external attachments and unavailable private data are not embedded unless explicitly listed in its manifest. + +Stars, watchers, source organization membership, private settings, secrets, deploy keys, inaccessible project data, and Actions run history are not copied. The source wiki could not be cloned (GitHub reported that it was not found). No source releases were present during inventory. The one public discussion is archived and recreated with attribution. The destination was private at the initial inventory and later reported public visibility. The migration commands did not request a visibility change. + +## Names and compatibility + +The primary executable and Cargo package are `betterxen`. Existing `xenora-*` library package names, C interface symbols, the synthetic CPUID vendor string, environment-variable names and synthetic guest import names are retained for compatibility. Copyright notices, licenses, historical review evidence and upstream attribution retain their original names. Prior hardware and verification claims describe upstream evidence and do not certify this renamed copy. + +The destination coordination configuration names `Arths17` as its maintainer. Source-specific contributor routing is cleared; destination maintainers can configure it for their own team. diff --git a/docs/progress.md b/docs/progress.md index 254d918..e8e4459 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,6 +1,6 @@ # Engineering progress -Xenora is an experimental research project. Verified work is restricted to +BetterXen is an experimental research project. Verified work is restricted to independently authored synthetic programs and shaders; commercial game execution and authentic Xbox startup are unsupported. Progress is measured by reproducible tests, not by estimated game compatibility percentages. diff --git a/scripts/audit/status.py b/scripts/audit/status.py index e5cd3a1..776d91d 100644 --- a/scripts/audit/status.py +++ b/scripts/audit/status.py @@ -68,7 +68,7 @@ def render_progress(status): ] svg = [ '', - 'Xenora · recorded progress', + 'BetterXen · recorded progress', '' + escape(". ".join(f"{label}: {count} of {total}" for label, count, total in rows)) + '', '', '', diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 3b778f0..19fe502 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -1,6 +1,6 @@ #!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later -# Build Xenora.app (native ARM64) into build/Xenora.app and run its smoke check. +# Build BetterXen.app (native ARM64) into build/BetterXen.app and run its smoke check. # Requires: macOS on Apple Silicon, Rust 1.100 (aarch64-apple-darwin), Swift 6 toolchain. set -eu cd "$(dirname "$0")/.." @@ -19,18 +19,18 @@ MACOSX_DEPLOYMENT_TARGET=14.0 cargo build --locked --release -p xenora-ffi --tar swift build --package-path app -c release --arch arm64 \ -Xlinker -L -Xlinker "$root/target/$target/release" -bundle="$root/build/Xenora.app" +bundle="$root/build/BetterXen.app" rm -rf "$bundle" mkdir -p "$bundle/Contents/MacOS" -cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/Xenora" "$bundle/Contents/MacOS/Xenora" +cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/BetterXen" "$bundle/Contents/MacOS/BetterXen" cat > "$bundle/Contents/Info.plist" < - CFBundleExecutableXenora - CFBundleIdentifierlocal.xenora.Xenora - CFBundleNameXenora + CFBundleExecutableBetterXen + CFBundleIdentifierorg.macosporters.betterxen + CFBundleNameBetterXen CFBundlePackageTypeAPPL CFBundleShortVersionString0.1.0 LSMinimumSystemVersion14.0 @@ -52,7 +52,7 @@ PLIST # this build executes no guest code, so it needs no JIT entitlement. codesign --force --sign - "$bundle" -binary="$bundle/Contents/MacOS/Xenora" +binary="$bundle/Contents/MacOS/BetterXen" [ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")" "$binary" --smoke echo "build-app: built $bundle" diff --git a/scripts/demo.sh b/scripts/demo.sh index f0b0653..998d08d 100755 --- a/scripts/demo.sh +++ b/scripts/demo.sh @@ -9,5 +9,5 @@ export MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1 export MTL_SHADER_VALIDATION_ABORT_ON_FAULT=1 export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4} -cargo build --locked -p xenora -exec timeout 30s cargo run --locked -p xenora -- demo +cargo build --locked -p betterxen +exec timeout 30s cargo run --locked -p betterxen -- demo diff --git a/scripts/qa/repo_health.py b/scripts/qa/repo_health.py index 91ca0dd..4f31b71 100644 --- a/scripts/qa/repo_health.py +++ b/scripts/qa/repo_health.py @@ -33,7 +33,7 @@ def check_large_generated_paths(tracked_paths: Iterable[str], *, suspicious_pref return HealthFinding("generated-paths", ok, detail) -def check_upstream_configured(remotes: Iterable[str], *, expected: str = "ranveersoni98/Xenora") -> HealthFinding: +def check_upstream_configured(remotes: Iterable[str], *, expected: str = "MacosPorters/betterxen") -> HealthFinding: names = set(remotes) # Accept either a remote named upstream or origin pointing at expected. ok = "upstream" in names or "origin" in names diff --git a/tests/agent_queue/test_workflows_cli.py b/tests/agent_queue/test_workflows_cli.py index cc0df68..ffd8396 100644 --- a/tests/agent_queue/test_workflows_cli.py +++ b/tests/agent_queue/test_workflows_cli.py @@ -132,7 +132,7 @@ class Cli(unittest.TestCase): def test_shipped_config_parses(self): r = self.run_cli("config-get", "upstream") self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(r.stdout.strip(), "ranveersoni98/Xenora") + self.assertEqual(r.stdout.strip(), "MacosPorters/betterxen") def test_summary_accepts_now_after_subcommand(self): # Actions passes --now after `summary`; parent-only --now used to reject that. diff --git a/tests/compat_fixtures/README.md b/tests/compat_fixtures/README.md index 423dceb..33ce38f 100644 --- a/tests/compat_fixtures/README.md +++ b/tests/compat_fixtures/README.md @@ -106,7 +106,7 @@ the tool's own run paths. The script writes the versions it used to test process under the Cargo target directory, so two runs that share a target directory do not overwrite each other's files; `cargo clean` removes them. -Provenance. The source, the name lists and the script were written for Xenora +Provenance. The source, the name lists and the script were written for BetterXen and are GPL-3.0-or-later. Nothing from a Windows SDK, a C runtime or another project is compiled or linked. The compiler and linker are LLVM projects under the Apache License 2.0 with LLVM exceptions; they are tools, not inputs. From 19a905c30ea85166c05084da4fba67e356920912 Mon Sep 17 00:00:00 2001 From: Arths17 Date: Tue, 24 Nov 2026 21:01:27 -0600 Subject: [PATCH 09/12] Document migration archive refs as tags Signed-off-by: Arths17 --- CHANGELOG.md | 1 + docs/migration.md | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e8bf02e..449dede 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts. - Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained. - Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle). - The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only. diff --git a/docs/migration.md b/docs/migration.md index ed8eb43..a5e070a 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -4,13 +4,13 @@ BetterXen is an independent copy of [XenoraOSS/Xenora](https://github.com/Xenora ## Preserved history -Original commits and authorship are retained. Available pull-request head and merge refs are preserved as `archive/pull//head` and `archive/pull//merge` branches. Not every historical PR ref is still exposed by the source; the metadata archive also includes patches obtained through GitHub's API. +Original commits and authorship are retained. All 161 original pull-request heads and 24 available merge refs were copied. The 22 open PRs keep their `archive/pull//head` branches. The other 163 refs are preserved as tags named `archive/pull//head` or `archive/pull//merge`; their branch aliases were removed to avoid recent-push banners for historical work. Every tag was checked against its original commit before its branch alias was removed. The metadata archive also includes patches obtained through GitHub's API. Issues are recreated with original-source links, author attribution and archived comment text. Original timestamps and authors cannot be assigned to recreated GitHub records. Destination issue and pull-request numbers differ. Historical `#number` references in upstream records refer to the original repository; consult the source link and number maps in the migration archive. Open PRs are recreated against copied branches. Closed and merged PRs are retained as historical archive records, including descriptions, comments, reviews, changed-file metadata, commits and patches; they are not represented as newly merged work. Recreated PRs do not inherit approvals or check results. -The migration archive is attached to the repository's migration release. It includes JSON metadata, a readable issue/PR index, patches and original-to-destination number maps. It records the public state observed during migration, not an atomic snapshot. Linked external attachments and unavailable private data are not embedded unless explicitly listed in its manifest. +The migration archive was uploaded with the `migration-archive-2026-11-24` release, but that release was no longer listed by GitHub during the branch cleanup. A verified local copy remains at `artifacts/repo-migration/xenora-to-betterxen-archive.zip`; `artifacts/` is ignored by Git. Git history also remains on GitHub through the active PR branches and archive tags. It includes JSON metadata, a readable issue/PR index, patches and original-to-destination number maps. It records the public state observed during migration, not an atomic snapshot. Linked external attachments and unavailable private data are not embedded unless explicitly listed in its manifest. Stars, watchers, source organization membership, private settings, secrets, deploy keys, inaccessible project data, and Actions run history are not copied. The source wiki could not be cloned (GitHub reported that it was not found). No source releases were present during inventory. The one public discussion is archived and recreated with attribution. The destination was private at the initial inventory and later reported public visibility. The migration commands did not request a visibility change. From f02eb2678e76e91876be5706ce91dca25dcc3017 Mon Sep 17 00:00:00 2001 From: Arths17 Date: Tue, 24 Nov 2026 21:21:45 -0600 Subject: [PATCH 10/12] Add CODEOWNERS requiring maintainer review Signed-off-by: Arths17 --- .github/CODEOWNERS | 2 ++ CHANGELOG.md | 1 + 2 files changed, 3 insertions(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..b49b5b7 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Every change needs a review from the maintainers team. +* @MacosPorters/maintainers diff --git a/CHANGELOG.md b/CHANGELOG.md index 449dede..7a7e128 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges. - Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts. - Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained. - Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle). From 10347dc21b35b19f980063c524a43254eea104f6 Mon Sep 17 00:00:00 2001 From: Arths17 Date: Tue, 24 Nov 2026 21:30:48 -0600 Subject: [PATCH 11/12] Document BetterXen development phases and migration check repairs Signed-off-by: Arths17 --- CHANGELOG.md | 2 + README.md | 4 +- docs/README.md | 4 + docs/development-phases.md | 238 +++++++++++++++++++++++++++++++++++++ 4 files changed, 246 insertions(+), 2 deletions(-) create mode 100644 docs/development-phases.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a7e128..86945f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ remains unsupported. ### Changed - Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges. +- Repaired destination issue links in 20 migrated PR descriptions while retaining the imported text, attribution and contributor certifications. Template and review requirements remain in place. - Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts. - Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained. - Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle). @@ -35,6 +36,7 @@ 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 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. diff --git a/README.md b/README.md index fc5b94f..4593387 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # BetterXen -BetterXen is an independent continuation copied from [XenoraOSS/Xenora](https://github.com/XenoraOSS/Xenora). The original Git history, licenses and contributor attribution are retained. See the [migration notes](docs/migration.md) for imported issue and pull-request history. +BetterXen is a community-maintained continuation. Original Git history, licenses and contributor attribution are retained. See the [project history and migration notes](docs/migration.md) for source attribution and imported issue and pull-request records. **Experimental Xbox Series X|S emulation research for Apple Silicon Macs.** @@ -53,7 +53,7 @@ The latest verified milestones include **translated gfx1030 vertex and pixel sha | X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal | | X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal | -**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run. +**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Follow the [BetterXen development phases](docs/development-phases.md) for the current work order and existing issue/PR dependencies. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run. All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified. diff --git a/docs/README.md b/docs/README.md index 3b27d18..36f4ea6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,6 +8,10 @@ then read the [interface contracts](interfaces.md). Reproduce an [independent validation suite](../tests/validation/README.md) before changing either path. The [changelog](../CHANGELOG.md) records notable changes. +Use the [BetterXen development phases](development-phases.md) for current work +order, existing issue/PR dependencies and measurable completion criteria. +Historical phase checkpoints retain their original evidence scope. + ## Architecture and technical design - [Interface contracts](interfaces.md) — Translated shader stages, guest services, native command submission, and synthetic textures. diff --git a/docs/development-phases.md b/docs/development-phases.md new file mode 100644 index 0000000..c5de163 --- /dev/null +++ b/docs/development-phases.md @@ -0,0 +1,238 @@ +# BetterXen development phases + +This is BetterXen's working development plan. Each phase ends with a reproducible +application or engineering result. The plan is based on the current repository, +not on completing an inherited prompt or reaching a compatibility percentage. +No phase authorizes a release, publication, or commercial-game compatibility claim. + +## Starting point + +The source review used `19a905c30ea85166c05084da4fba67e356920912` on destination +`main`, with the local documentation work starting after the separate CODEOWNERS +commit `f02eb2678e76e91876be5706ce91dca25dcc3017`. The latter changes governance, +not runtime behavior. Open issues and PRs were inspected on November 24, 2026 +(America/Chicago). Recheck their current heads and claims before taking work. + +This task performed source inspection and read-only inventories. It did not +rerun the Rust, native GPU, application, fuzz, mutation, or performance suites. +Historical results below remain evidence for their recorded candidates only. + +| Area | Present in the inspected source | Boundary for this plan | +| --- | --- | --- | +| Guest CPU | Generated x86-64 decoder, interpreter, ARM64 dynamic binary translator (DBT), integer and vector tests; inventory reports 491 declared forms and 206 operations | Declarations and lowering classifications do not establish independent acceptance or broad application compatibility. | +| Runtime | PE loading, import resolution, service handlers, process-exit tests and the compiled-C A1 fixture | The typed registry inventories only 20 services: 7 marked implemented and 13 partial. Many handwritten handlers are outside that inventory; 20 is not the total runtime service count. | +| Threads | Deterministic scheduler, guest thread contexts and guarded stacks, thread services and compiled-C thread tests | Guest threads execute serially on one host thread. Blocking synchronization, sleep behavior and thread lifecycle callbacks still have documented gaps. | +| Graphics | gfx1030 shader decoder/compiler/reference, native Metal execution paths, texture and draw tests | Synthetic desktop instruction fixtures do not establish Xbox behavior. Acceptance is tracked separately from local readback. | +| Native app | Swift app, Rust C interface, controller input and audio/virtual-filesystem fixtures | Existing fixtures do not establish one integrated threaded C++ 3D application. | +| Quality tools | CPU/runtime inventories, shader coverage reconciliation, task queue, PR checks and acceptance records | Some inventories and ledgers contain stale limitation text. A successful tool invocation does not prove every catalog entry is current. | + +Sources: [CPU registry](cpu/instruction-registry.md), +[runtime registry](runtime/registry.md), [guest threads](runtime/threads.md), +[interfaces](interfaces.md), [shader coverage](shaders/semantic-coverage.md), +[Gate A](testing/gate-a.md), and [QA tooling](testing/infrastructure/README.md). +The read-only shader reconciliation reported zero mismatches during this task; +that result is inventory consistency, not new GPU verification. + +## How previous phase names fit + +Keep historical evidence and attribution intact. These records remain useful, +but their phase numbers are not the sequence for new BetterXen work. + +| Existing record or name | Meaning | How to use it now | +| --- | --- | --- | +| [Phase 01 checkpoints and assurance](testing/phase01-assurance.md), [risk register](risk-register.md), [review log](testing/review-log.md) and [mutation record](testing/mutation.md) | Earlier bounded shader research and candidate-specific gates | Consult the original gate definitions and unresolved findings; do not relabel them as current acceptance. | +| [Phase 02 GPU/guest baseline](testing/phase-02-baseline.md) and [CPU feasibility](research/phase02-cpu-feasibility.md), [ecosystem](research/phase02-ecosystem.md), [collaboration](research/phase02-collaboration.md) research | Early graphics expansion and CPU feasibility work | Reuse documented public sources and evidence limits, checking them against current source. | +| [CPU/runtime campaign ledger](coordination/cpu-campaign-ledger.md) | Implementation batches and local evidence | Its older limitations are not a current feature inventory: scheduler, atomic and string work has since landed. | +| [Infrastructure Phase II/III tooling](testing/infrastructure/README.md) and [compatibility ledger](testing/infrastructure/phase3-compat-ledger.md) | A separate QA campaign | Tool code now includes compatibility-gap analysis and verification profiles beyond the ledger's early checkpoint. Coordinate with existing issue #219 rather than starting another QA framework. | +| [Gate A](testing/gate-a.md) | Compiled C execution, split into A1 and hosted-C A2 | A1 has a main-branch test. A2 is under review in PR #283; the document's “not started” description predates that PR. Neither is independently accepted by this plan. | +| Native app numbered gates in `crates/ffi` and `app` | Bounded session, graphics, audio and filesystem fixtures | Inspect their tests before proposing integration. Gate numbers are separate from shader acceptance gates. | +| README X1–X25 milestones | Broad capability map | Retain as a capability reference; use the phases below for the next work order. | +| Supplied Discord III, III-B, IV, V and VI excerpts | Broad runtime, graphics, application and performance objectives | Only excerpts were supplied. Their omitted requirements and completion status are unknown; they are not execution instructions. | + +Bare issue numbers in historical documents may refer to the source repository. +All issue and PR links in the work sections below refer to **MacosPorters/betterxen**. +Use [migration records](migration.md) to resolve historical references. + +## Phase 1 — Establish a trustworthy working baseline + +**Outcome:** contributors can tell what exists on main, what is pending review, +and which checks actually ran on the candidate they are using. + +1. Reconcile the current source with the CPU campaign ledger, Gate A document, + runtime inventory scope, and QA compatibility ledger. In particular, the QA + CPU inventory's intentional-rejection catalog still lists strings and + atomics/fences despite source and tests for supported subsets. Correct the + catalog through its existing owner; do not remove explicit unsupported forms. +2. Preserve all imported attribution. Repair destination links in migrated PRs + without recreating sign-offs or treating archived reviews as current approval. +3. Reproduce the applicable existing CPU, generator and repository checks for a + pinned candidate. Run GPU and app checks separately on an eligible native host. + Record errors, unavailable tools and skipped tests separately. +4. Review conflicting PR branches with their authors. Changing descriptions + cannot resolve source conflicts or provide missing ARM64 build checks. +5. Finish BetterXen's active branding where needed. Preserve copyright notices, + licenses and accurate historical records. Package names, C symbols, guest ABI + names and environment variables require a compatibility migration, not a + blanket search-and-replace. Do not rewrite authorship to imply new ownership. + +Existing work: [migration checks #286](https://github.com/MacosPorters/betterxen/issues/286), +[QA scope #219](https://github.com/MacosPorters/betterxen/issues/219), +[app CI #248](https://github.com/MacosPorters/betterxen/issues/248). + +**Exit criteria:** a candidate SHA, a current capability/blocker inventory, +links to retained logs for each executed gate, explicit pending reviews, and +usable PR descriptions. Independent acceptance remains a separate decision. +No release is required. + +## Phase 2 — Finish a reproducible hosted C application + +**Outcome:** an original hosted C program starts, uses the runtime, reports +results and exits through the guest path with checked cleanup. + +Review and integrate existing work rather than creating a competing runtime: + +| Prerequisite | Existing destination work | +| --- | --- | +| CRT startup calls | [issue #237](https://github.com/MacosPorters/betterxen/issues/237), [PR #273](https://github.com/MacosPorters/betterxen/pull/273) | +| Arguments and environment | [issue #242](https://github.com/MacosPorters/betterxen/issues/242), [PR #277](https://github.com/MacosPorters/betterxen/pull/277) | +| Normal termination and exit handlers | [issue #243](https://github.com/MacosPorters/betterxen/issues/243), [PR #280](https://github.com/MacosPorters/betterxen/pull/280) | +| Formatted standard output | [issue #245](https://github.com/MacosPorters/betterxen/issues/245), [PR #281](https://github.com/MacosPorters/betterxen/pull/281) | +| File streams | [issue #246](https://github.com/MacosPorters/betterxen/issues/246), [PR #282](https://github.com/MacosPorters/betterxen/pull/282) | +| Integrated hosted-C fixture | [issue #262](https://github.com/MacosPorters/betterxen/issues/262), [PR #283](https://github.com/MacosPorters/betterxen/pull/283) | + +Check dependency order and stacked branches against their actual heads. Audit +the compiler and linked CRT's per-file licensing and native ARM64 build tools. +An x86-64 guest fixture is permitted; its compiler must run natively on ARM64. + +**Exit criteria:** reproducible original fixture build; checked stdout/stderr, +arguments, file contents, exit status, callback order and cleanup; unresolved +imports and exhausted budgets fail explicitly. Existing A1 behavior still passes. +Independent reviewers derive expected results from public specifications and the +fixture contract. No general C++ or Xbox startup claim follows from this result. + +## Phase 3 — Make threaded application behavior coherent + +**Outcome:** an original worker-based application can block and resume without +stalling unrelated guest work or leaking per-thread state. + +Extend the existing scheduler under [issue #228](https://github.com/MacosPorters/betterxen/issues/228). +Prioritize a small fixture that exposes a documented gap: guest sleep currently +delays all guest threads, and critical-section/SRW/condition-variable waits are +not fully connected to scheduling. Claim one gap and its paths before editing. + +Then add the thread lifecycle behavior required by that workload, including +static thread-local storage (TLS), library attach/detach and fiber-local storage +(FLS) cleanup where supported. Keep unsupported callbacks explicit until their +semantics and safety are implemented. Preserve Win64 nonvolatile register checks +and coordinate with [issue #193 / PR #268](https://github.com/MacosPorters/betterxen/pull/268). + +**Exit criteria:** deterministic results at several scheduling quanta; another +worker progresses while one waits; timeouts, cancellation, abandoned objects, +thread-local errors, stack bounds and cleanup have negative controls. Repeat +runs reclaim thread resources. Serial guest scheduling remains the execution +model unless a separately reviewed memory-ordering design replaces it. + +## Phase 4 — Connect resource updates to translated rendering + +**Outcome:** one original guest workload updates a texture and geometry, submits +translated rendering, waits for completion and produces an independently checked +frame through the existing native Metal backend. + +Start with a bounded scene and its concrete missing features. Do not make all +RDNA2 instructions, mesh shaders or ray tracing prerequisites for a first scene. +Reuse the semantic registry and distinguish declared, decoded, lowered, +reference-tested, locally GPU-tested and independently accepted forms. + +Coordinate [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205), +[mip footprints #241 / PR #278](https://github.com/MacosPorters/betterxen/pull/278), +[graphics fences #224](https://github.com/MacosPorters/betterxen/issues/224), +[shared resource lifetime #148](https://github.com/MacosPorters/betterxen/issues/148), +and [texture-update workload #147](https://github.com/MacosPorters/betterxen/issues/147). +Wave divergence, cross-lane operations and additional formats get separate +fixture contracts and claims when this workload needs them. + +**Exit criteria:** actual Metal execution and frame readback against an +independently derived expectation; update/submission/retirement order is checked; +invalid descriptors, stale handles and unsupported shader forms fail explicitly. +Record host capability detection, hardware, validation settings and evidence +class. Test counts and tolerances retain their existing definitions. Results +remain synthetic desktop-gfx1030 evidence, never Xbox hardware verification. + +## Phase 5 — Run one integrated interactive application reliably + +**Outcome:** a small, original application joins guest execution, rendering, +input, bounded audio, filesystem access and lifecycle behavior in one session. + +Start from [multi-module startup #256](https://github.com/MacosPorters/betterxen/issues/256) +and the existing app/FFI fixtures. First prove a compiled workload can reach a +checked frame. Add C++ language/runtime features only when an independently +authored failing fixture demonstrates the need. Audit any linked runtime first. +Do not treat the Swift audio/input demonstrations as guest integration evidence. + +Coordinate [audio #227](https://github.com/MacosPorters/betterxen/issues/227), +[session errors #250](https://github.com/MacosPorters/betterxen/issues/250), +[report schema #254](https://github.com/MacosPorters/betterxen/issues/254), +[worker diagnostics #255](https://github.com/MacosPorters/betterxen/issues/255), +and [application quick start #247](https://github.com/MacosPorters/betterxen/issues/247). +Execution-admission changes remain owned by [issue #212](https://github.com/MacosPorters/betterxen/issues/212). + +**Exit criteria:** scripted input and deterministic checkpoints; start, pause, +resume, stop and restart behavior; checked audio sample data before device +playback; bounded memory and handle use; sandbox escape attempts rejected; +useful failure reports and a repeatable soak protocol. Specify soak duration, +resource limits and acceptance conditions before measuring. A fixture worker +passing does not certify arbitrary files safe or commercial titles playable. + +## Phase 6 — Improve measured bottlenecks + +**Outcome:** faster or lower-resource execution of workloads whose correctness +is already checked, with measurements that another contributor can reproduce. + +Performance analysis can begin earlier; changes must preserve the relevant +phase's correctness. Select bottlenecks from actual measurements rather than +assuming every shared-semantics call, allocation or cache miss needs replacement. +Potential work includes CPU helper lowering, bounded translation-cache policy, +Metal startup, texture transfers and frame-loop overhead. + +Reuse [startup measurements #171 / PR #266](https://github.com/MacosPorters/betterxen/pull/266), +[TLS optimization #107 / PR #284](https://github.com/MacosPorters/betterxen/pull/284), +[DBT comparison #110 / PR #272](https://github.com/MacosPorters/betterxen/pull/272), +and [conditional cache prewarming #258](https://github.com/MacosPorters/betterxen/issues/258). + +**Exit criteria:** correctness gates pass on the changed candidate; baseline and +candidate use equivalent inputs, toolchains, settings and hardware; idle-machine +samples include variance and separate cold/warm startup. Report regressions as +well as gains. Run validation-off benchmarks separately from validation-on GPU +correctness. Capability differences across Apple Silicon generations remain +unknown until measured; runtime detection controls optional paths. + +## Taking the next task + +Begin with Phase 1's evidence reconciliation and review Phase 2's existing PRs. +The phase-plan issue does not claim their implementation files. Read every +comment on a target issue and inspect linked PRs; never take a live claim. +Issue #219's QA paths and subsystem owners remain independent of this plan. + +Each implementation task needs a bounded outcome, permitted files, dependencies, +public semantic sources, a failing fixture or other meaningful acceptance check, +and the required independent reviewers. Use original code and expectations; +never copy another emulator to satisfy a phase. Do not require a fixed number +of agents: use available resources only within the repository's LOW-reasoning +and independent-review rules. + +Useful existing commands for the candidate record: + +```sh +PYTHONPATH=scripts python3 -m qa cpu-inventory --compact +PYTHONPATH=scripts python3 -m qa runtime-inventory --compact +PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact +python3 scripts/audit/status.py --check +scripts/audit/claims.sh +scripts/audit/dependencies.sh +``` + +For implementation, run the applicable checkout commands in `AGENTS.md` and the +subsystem acceptance protocol. Keep logs under ignored `artifacts/`. Use at most +four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or mutation +campaign at a time. New verification must name the exact candidate; skipped +tests never count as GPU evidence. Passing a phase does not authorize a release. From aa9a961ef48da96669ac6d77b975acb2e8c4370e Mon Sep 17 00:00:00 2001 From: Arths17 Date: Tue, 24 Nov 2026 21:37:38 -0600 Subject: [PATCH 12/12] Remove README contributor avatar section Signed-off-by: Arths17 --- CHANGELOG.md | 1 + README.md | 4 ---- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86945f4..f8ff9fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- Removed the contributor avatar section from the README. - Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges. - Repaired destination issue links in 20 migrated PR descriptions while retaining the imported text, attribution and contributor certifications. Template and review requirements remain in place. - Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts. diff --git a/README.md b/README.md index 4593387..62a11c8 100644 --- a/README.md +++ b/README.md @@ -361,10 +361,6 @@ See the [roadmap table](#development-milestones) for proposed milestones, and th --- -### Contributors - -[![Contributors](https://contrib.rocks/image?repo=MacosPorters/betterxen)](https://github.com/MacosPorters/betterxen/graphs/contributors) - ## License BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE).