Compare commits

...
Author SHA1 Message Date
atharvranjan d1bcd0249d Integrate PR #268 and clarify Win64 shadow-space expectations
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:44:49 -06:00
atharvranjan 097bb0b5b8 Merge commit '19f63a0' into integration/pr-284
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:43:15 -06:00
atharvranjan 2d77b35e56 Merge remote-tracking branch 'origin/main' into integration/pr-284
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 21:43:15 -06:00
atharvranjan 19f63a0985 Merge remote-tracking branch 'origin/main' into integration/pr-270
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:42:09 -06:00
atharvranjan 45322af82e Merge pull request #288 from MacosPorters/foc
Define BetterXen development phases and record migration repairs
2026-11-24 21:41:11 -06:00
atharvranjan aa9a961ef4 Remove README contributor avatar section
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:37:38 -06:00
atharvranjan 10347dc21b Document BetterXen development phases and migration check repairs
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:34:55 -06:00
atharvranjan 4d530392d1 Merge pull request #285 from MacosPorters/repo/add-codeowners
Add CODEOWNERS requiring maintainer review
2026-11-24 21:30:10 -06:00
atharvranjan f02eb2678e Add CODEOWNERS requiring maintainer review
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:21:45 -06:00
atharvranjan 19a905c30e Document migration archive refs as tags
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:01:27 -06:00
devil8blade f0c61c7a91 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>
2026-11-24 21:01:31 -05:00
Arthur Lacoste af1b84ad75 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 <arthurlacoste@users.noreply.github.com>
2026-11-24 22:14:29 +01:00
Arthur Lacoste cf438e25aa Merge remote-tracking branch 'origin/main' into runtime/win64-service-abi-201
# Conflicts:
#	CHANGELOG.md
2026-11-24 22:13:14 +01:00
plokhi d35c278284 Clarify ARM64 encoding audit coverage
Signed-off-by: plokhi <37208555+Plokhi@users.noreply.github.com>
2026-11-24 21:33:37 +01:00
plokhi fbec436b89 Fix ARM64 variable shift register encoding
Signed-off-by: plokhi <37208555+Plokhi@users.noreply.github.com>
2026-11-24 21:19:38 +01:00
Arthur Lacoste 7246ab5ea6 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 <arthurlacoste@users.noreply.github.com>
2026-11-24 20:57:41 +01:00
9 changed files with 933 additions and 26 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Every change needs a review from the maintainers team.
* @MacosPorters/maintainers
+9
View File
@@ -10,6 +10,11 @@ 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.
- 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.
- 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.
@@ -33,11 +38,14 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
@@ -235,6 +243,7 @@ remains unsupported.
- Fixed `DuplicateHandle` and `GetThreadId` naming the main thread from other guest threads, `OwningThread` in critical sections always holding the main thread's ID, the callback-depth limit being shared by all guest threads, and pending one-time initializations being unbounded.
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
+2 -6
View File
@@ -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.
@@ -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).
+49 -7
View File
@@ -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)
@@ -831,6 +835,44 @@ mod tests {
assert_eq!(branch.instructions()[0], 0x14000005);
}
#[test]
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
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 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),
|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();
+440 -11
View File
@@ -233,6 +233,22 @@ fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>,
/// 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<u8> {
(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<u8> {
(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::<f64>() / n as f64;
let sample_variance = samples
.iter()
.map(|sample| (sample - mean).powi(2))
.sum::<f64>()
/ (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]
);
}
}
}
+187
View File
@@ -7,6 +7,7 @@
//! convention documentation, not from the registry or the handlers.
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
@@ -696,6 +697,76 @@ fn floating_arguments_and_results_use_xmm_registers() {
assert_eq!(float("fabsf", garbage | 0xBF80_0000) as u32, 0x3F80_0000); // -1
}
#[test]
fn guest_call_through_dbt_preserves_win64_abi_state() {
use Register::{R8, R9, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4])>));
let seen = observed.clone();
let mut registry = ImportRegistry::new();
registry.register("t.dll", "F", move |_args, cpu, mem| {
let rsp = cpu.get(Rsp);
let shadow = [
mem.read_u64(rsp + 8).unwrap(),
mem.read_u64(rsp + 16).unwrap(),
mem.read_u64(rsp + 24).unwrap(),
mem.read_u64(rsp + 32).unwrap(),
];
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow));
cpu.set(Rcx, 0x11);
cpu.set(Rdx, 0x22);
cpu.set(R8, 0x33);
cpu.set(R9, 0x44);
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
*lane = u128::from(0x55_u64 + reg as u64);
}
Ok(0x99AA_BBCC_DDEE_F001)
});
let image = build(&[("t.dll", Symbol::Name("F"))]);
let pe = ParsedPe::parse(&image.bytes).unwrap();
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap();
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
// Before CALL RSP is 16-byte aligned; CALL pushes return address so the
// callee sees RSP % 16 == 8. Shadow space is [entry_rsp+8, entry_rsp+40).
let initial_rsp = STACK_TOP;
assert_eq!(initial_rsp % 16, 0);
let entry_rsp_expected = initial_rsp - 8;
for slot in 0..4u64 {
memory
.write_u64(entry_rsp_expected + 8 + slot * 8, 0x7000 + slot)
.unwrap();
}
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA), initial_rsp);
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
cpu.set(register, 0x6100 + index as u64);
}
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
*lane = u128::from(0x6200_u64 + (offset + 6) as u64);
}
let result = engine.run(&mut cpu, &mut memory, 1000);
assert_eq!(result.exit_reason, ExitReason::Halt);
let (entry_rsp, _, shadow) = observed.lock().unwrap().expect("service ran");
assert_eq!(entry_rsp, entry_rsp_expected);
assert_eq!(entry_rsp % 16, 8);
assert_eq!(shadow, [0x7000, 0x7001, 0x7002, 0x7003]);
assert_eq!(cpu.get(Rax), 0x99AA_BBCC_DDEE_F001);
assert_eq!(cpu.get(Rsp), initial_rsp);
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
assert_eq!(cpu.get(register), 0x6100 + index as u64, "{register:?}");
}
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
let index = offset + 6;
assert_eq!(*lane, u128::from(0x6200_u64 + index as u64), "xmm{index}");
}
}
#[test]
fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() {
let mut memory = GuestMemory::new();
@@ -957,6 +1028,122 @@ fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() {
}
}
#[test]
fn service_may_write_its_caller_allocated_shadow_space() {
// Microsoft x64 calling convention: the caller reserves four home slots,
// but the callee may use them. Their contents are not nonvolatile state.
let (registry, mut memory, trampoline) = bound_service(|_, cpu, memory| {
for slot in 0..4u64 {
memory
.write_u64(cpu.get(Register::Rsp) + 8 + slot * 8, 0xA000 + slot)
.unwrap();
}
Ok(7)
});
let entry_rsp = STACK_TOP - 8;
memory.write_u64(entry_rsp, 0x1234).unwrap();
let mut cpu = CpuState::new(trampoline, entry_rsp);
assert_eq!(registry.dispatch(trampoline, &mut cpu, &mut memory), Ok(()));
assert_eq!(cpu.rip, 0x1234);
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
assert_eq!(cpu.get(Register::Rax), 7);
for slot in 0..4u64 {
assert_eq!(memory.read_u64(entry_rsp + 8 + slot * 8), Ok(0xA000 + slot));
}
}
#[test]
fn service_calls_preserve_win64_abi_state() {
// Microsoft x64 calling convention: at entry RSP % 16 == 8 (return address
// pushed by CALL). Callee preserves RBX,RBP,RDI,RSI,R12-R15 and XMM6-XMM15.
// Caller allocates 32-byte shadow/home space at [RSP+8, RSP+40), which
// the callee may use. This handler leaves it unchanged; the separate
// shadow-space test checks a handler that writes it. RAX carries the
// return value; RCX,RDX,R8,R9,R10,R11,XMM0-XMM5 are volatile.
use Register::{R8, R9, R10, R11, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4], u64)>));
let seen = observed.clone();
let (registry, mut memory, trampoline) = bound_service(move |args, cpu, mem| {
let rsp = cpu.get(Rsp);
let shadow = [
mem.read_u64(rsp + 8).unwrap(),
mem.read_u64(rsp + 16).unwrap(),
mem.read_u64(rsp + 24).unwrap(),
mem.read_u64(rsp + 32).unwrap(),
];
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow, args.rcx));
// Clobber volatile registers; dispatcher must still return correctly and
// nonvolatile state must be preserved after return.
cpu.set(Rcx, 0xA1);
cpu.set(Rdx, 0xA2);
cpu.set(R8, 0xA3);
cpu.set(R9, 0xA4);
cpu.set(R10, 0xA5);
cpu.set(R11, 0xA6);
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
*lane = u128::from(0xB0_u64 + reg as u64);
}
Ok(0x1122_3344_5566_7788)
});
// Win64: before CALL RSP is 16-byte aligned; CALL pushes return address,
// so callee entry sees RSP % 16 == 8.
let call_rsp = STACK_TOP - 8;
assert_eq!(call_rsp % 16, 8);
memory.write_u64(call_rsp, 0x1234).unwrap();
for slot in 0..4u64 {
memory
.write_u64(call_rsp + 8 + slot * 8, 0xC000 + slot)
.unwrap();
}
let mut cpu = CpuState::new(trampoline, call_rsp);
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
cpu.set(register, 0x5AA5_0000_0001_0000 + index as u64);
}
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
*lane = u128::from(0xD000_0000_0000_0000_u64 + (offset + 6) as u64);
}
cpu.set(Rcx, 0x1357_9BDF_2468_ACE0);
let result = registry.dispatch(trampoline, &mut cpu, &mut memory);
assert_eq!(result, Ok(()));
let (entry_rsp, entry_rip, shadow, entry_rcx) = observed.lock().unwrap().expect("service ran");
assert_eq!(entry_rip, trampoline);
assert_eq!(
entry_rsp, call_rsp,
"service sees caller RSP at return address"
);
assert_eq!(entry_rsp % 16, 8, "Win64 entry RSP must be 8 mod 16");
assert_eq!(entry_rcx, 0x1357_9BDF_2468_ACE0);
// Shadow/home space is caller-owned and must be addressable by the service.
assert_eq!(shadow, [0xC000, 0xC001, 0xC002, 0xC003]);
for slot in 0..4u64 {
assert_eq!(
memory.read_u64(call_rsp + 8 + slot * 8).unwrap(),
0xC000 + slot,
"this handler leaves its home slots untouched"
);
}
// Post-return ABI state.
assert_eq!(cpu.get(Rax), 0x1122_3344_5566_7788);
assert_eq!(cpu.get(Rsp), call_rsp + 8);
assert_eq!(cpu.rip, 0x1234);
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
assert_eq!(
cpu.get(register),
0x5AA5_0000_0001_0000 + index as u64,
"nonvolatile {register:?} must be preserved"
);
}
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
let index = offset + 6;
assert_eq!(
*lane,
u128::from(0xD000_0000_0000_0000_u64 + index as u64),
"nonvolatile xmm{index} must be preserved"
);
}
}
#[test]
fn a_call_that_cannot_return_runs_no_service() {
let calls = Arc::new(AtomicUsize::new(0));
+4
View File
@@ -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.
+238
View File
@@ -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.
+2 -2
View File
@@ -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/<original-number>/head` and `archive/pull/<original-number>/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/<original-number>/head` branches. The other 163 refs are preserved as tags named `archive/pull/<original-number>/head` or `archive/pull/<original-number>/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.