Compare commits

..
Author SHA1 Message Date
atharvranjan e50268d872 Add isolated Remill AOT evaluation and adapter design
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 02:54:32 -06:00
16 changed files with 2175 additions and 676 deletions

No files matched your search

+2 -1
View File
@@ -10,7 +10,6 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- Replaced the active phase plan and README X1–X25 roadmap with one native macOS workload sequence and added a pinned PortWatch ecosystem review linked to eight contributor follow-ups. The plan distinguishes existing synthetic execution from future Xbox compatibility; no new runtime behavior, execution result or independent acceptance is claimed.
- 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.
@@ -43,6 +42,8 @@ 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
- Documented proposed Remill numerical and per-instruction execution adapters, including explicit ABI/state ownership, exception commits, exact budget exits and regression requirements. This is a design only; the recorded numerical and budget failures remain open.
- Added an isolated Remill native ARM64 experiment with original x86-64 fixtures, a bridge to checked guest memory, and comparisons against the existing interpreter and DBT. The local Apple M4 run passed 32 case/path checks; a wrong-answer control fails explicitly. The extended evaluation retains eight failing floating-point cases and a missing guest-budget exit, alongside narrow vector/control results and exploratory toy-workload timings. Production CPU behavior is unchanged; adoption and independent acceptance remain open.
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
+30 -19
View File
@@ -23,26 +23,37 @@ BetterXen has progressed from executing individual x86-64 instructions to runnin
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.
### Development phases
### Development milestones
The active plan follows demonstrable native macOS workloads. Every phase has
completion checks, dependencies and contributor issues in the
[full development plan](docs/development-phases.md).
| Milestone | Implementation | Status |
| --- | --- | --- |
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
| 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 |
| Phase | Result to demonstrate |
| --- | --- |
| 1 — Compiled guest boot | Reproduce and independently accept the existing original C execution path on native ARM64. |
| 2 — Modular guest runtime | Run an original executable with companion libraries, workers, checked waits and lifecycle cleanup. |
| 3 — Guest-controlled Metal scene | Reach translated textured rendering through compiled guest calls, with checked resource lifetime and pixels. |
| 4 — Interactive application | Combine guest execution, rendering, input, audio, saves and session controls in one original application. |
| 5 — Compatibility corpus | Expand CPU/runtime/shader behavior using varied original workloads and independently derived regressions. |
| 6 — Sustained native execution | Verify bounded long runs and measured performance on the Apple Silicon hosts actually tested. |
| 7 — Xbox compatibility experiments | Resolve public console contracts and demonstrate each separately admitted execution stage before claiming support. |
These phases replace the previous roadmap. They are targets, not completed
acceptance claims or a game-release timeline. Console-contract research and
bounded subsystem work can proceed in parallel. Historical fixture identifiers
such as X9 remain labels for their original test/evidence records.
**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.
@@ -342,7 +353,7 @@ Compiling a shader is not equivalent to proving its GPU output is correct.
### Where the work is heading
See the [development phases](docs/development-phases.md) for the current work order, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
---
+3 -3
View File
@@ -11,8 +11,6 @@ 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.
The active plan replaces the former roadmap with workload-based phases, from
compiled guest boot to separately admitted Xbox compatibility experiments.
## Architecture and technical design
@@ -38,6 +36,9 @@ compiled guest boot to separately admitted Xbox compatibility experiments.
## Guest CPU and runtime experiments
- [Remill adapter design](../experiments/remill/adapter-design.md) — Proposed numerical and instruction-budget contracts, state/result ownership and planned regression gates; not implemented.
- [Isolated Remill evaluation](../experiments/remill/README.md) — Native ARM64 prototype, checked-memory comparison, floating-point/budget blockers, exploratory measurements and adoption requirements; local evidence only.
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
- [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form.
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
@@ -60,7 +61,6 @@ compiled guest boot to separately admitted Xbox compatibility experiments.
## Research and engineering decisions
- [PortWatch projects and the native macOS plan](research/portwatch-native-macos.md) — Complete pinned tracker screen, native ARM64 gaps, contributor issues and revised phase dependencies; external claims remain unverified.
- [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior.
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
+187 -296
View File
@@ -1,347 +1,238 @@
# BetterXen development phases
BetterXen's objective is to execute supported Xbox Series software through an
original native ARM64 runtime and direct Metal on macOS. Commercial game
execution, including GTA VI, is currently unsupported. The demonstrated results
are bounded, independently authored programs and shaders.
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.
This is the sole active phase sequence. It replaces the previous phase plan and
the README's X1–X25 roadmap. Historical fixture names and acceptance records
retain their meaning as evidence for their original candidates; they are not a
second development schedule.
## Starting point
## Starting position
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.
The reviewed main revision is
[`b2654e93a42e74e29570183da1f31bb8cdc6f721`](https://github.com/MacosPorters/betterxen/tree/b2654e93a42e74e29570183da1f31bb8cdc6f721),
checked on November 24, 2026 (America/Chicago). Research began from a working
tree at `f02eb2678e76e91876be5706ce91dca25dcc3017` and inspected newer main in a
separate snapshot. This documentation change is based on the reviewed main
revision; it changes no runtime implementation.
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.
On inspected main, the source contains an x86-64 interpreter, an ARM64 dynamic
binary translator (DBT), PE32+ loading, a partial runtime, a deterministic guest
scheduler, translated graphics, texture/sampler bindings and a native Swift app.
The hosted C fixtures A1 and A2 are implemented and reported locally passing;
both still await independent acceptance. These pieces have not established a
complete commercial game or one integrated threaded 3D application.
The [public-project review](research/portwatch-native-macos.md) explains the
external comparisons and current-source limits. Windows projects often execute
x86-64 instructions directly and use Windows/D3D12 services. The inspected Mac
guest-execution projects use Rosetta; native asset renderers demonstrate a
different workload. Their progress is a research lead, not BetterXen evidence.
No competitor emulator implementation may be copied or adapted.
No phase is declared complete by this planning task. It ran documentation and
inventory checks, not new CPU/GPU execution, fuzzing, mutation or benchmarks.
## Delivery sequence
| Phase | Demonstrable result | Principal dependency |
| Area | Present in the inspected source | Boundary for this plan |
| --- | --- | --- |
| 1 | A reproducible compiled guest boots and exits on native ARM64 | Existing A1/A2 and native tool evidence |
| 2 | One modular guest program runs workers and cleans up correctly | Module startup, scheduling and lifecycle contracts |
| 3 | Guest code controls a translated textured Metal scene | Validated guest graphics calls, bindings and completion |
| 4 | An original interactive application combines execution, graphics, input, audio and saves | The supported paths from phases 2 and 3 |
| 5 | A varied original workload corpus exposes and closes specific compatibility gaps | A repeatable integrated application and diagnostics |
| 6 | Sustained execution is measured and verified across native Apple Silicon hosts | Checked workloads, resource bounds and actual host reports |
| 7 | A separately admitted Xbox compatibility experiment has documented contracts and reproducible results | Public console evidence and all behavior required by that input |
| 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. |
Each result has its own admission profile. A simple scene need not wait for all
AVX2 instructions, mesh shaders or ray tracing. A workload needing an unsupported
feature stops explicitly. Research, diagnostics, CPU expansion and performance
measurement can proceed alongside these phases on independently claimed paths.
A phase's number does not grant exclusive ownership of a subsystem.
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.
## Phase 1 — Boot a reproducible compiled guest
## How previous phase names fit
**Deliverable:** a contributor can build an original guest from source, start it
through BetterXen's supported test entry point and reproduce its output and exit
without an Intel host executable or Windows compatibility runtime.
Keep historical evidence and attribution intact. These records remain useful,
but their phase numbers are not the sequence for new BetterXen work.
Use the existing [Gate A fixtures](testing/gate-a.md). On inspected main,
[PR #283](https://github.com/MacosPorters/betterxen/pull/283) already supplies the
hosted C program. Reproduce and review that implementation; do not create a
competing CRT startup or mark it unimplemented because this checkout is older.
| 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. |
The candidate record identifies the exact source revision, local modifications,
native compiler/linker, linked support-code licenses, execution path and limits.
Check host executables/dependencies with `file`, `lipo -archs` and `otool -L`.
Guest x86-64 bytes are permitted data; native host tools must support ARM64.
Use `aarch64-apple-darwin` for BetterXen.
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.
**Completion checks:**
## Phase 1 — Establish a trustworthy working baseline
- A1/A2 reproduce the specified stdout/stderr, files, callback order, exit status
and cleanup on the named candidate. Missing compilers fail visibly.
- Existing wrong-input, unresolved-import and instruction-budget controls still
fail for their specified reasons. A trapped stub is not implemented behavior.
- The admission profile states which CPU forms, imports and startup features it
supports. The test entry point is distinguished from CLI/app execution.
- Independent reviewers accept the semantic expectations and the scope of the
native evidence. A local pass alone does not close this phase.
**Outcome:** contributors can tell what exists on main, what is pending review,
and which checks actually ran on the candidate they are using.
**Contributor work:** [CPU coverage #154](https://github.com/MacosPorters/betterxen/issues/154),
[native reports #303](https://github.com/MacosPorters/betterxen/issues/303), and
[existing compatibility report #254](https://github.com/MacosPorters/betterxen/issues/254).
Use existing audit/test tooling and coordinate schema changes with its owners.
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.
## Phase 2 — Run a modular program with guest workers
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).
**Deliverable:** an original executable and companion libraries initialize,
start workers, exchange results, block/resume and exit with checked teardown.
**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.
Begin with [the EXE/two-DLL startup contract #301](https://github.com/MacosPorters/betterxen/issues/301)
and [worker lifecycle design #305](https://github.com/MacosPorters/betterxen/issues/305).
The fixture records dependency initialization, per-module static thread-local
storage (TLS), worker-visible values and supported detach/destructor calls.
Expected order must be derived before implementing the loader or callbacks.
Built-in service-module lookup is not general guest DLL loading.
## Phase 2 — Finish a reproducible hosted C application
Extend the existing serial scheduler under
[#228](https://github.com/MacosPorters/betterxen/issues/228). Its documented
`Sleep` behavior can stall every worker; [#304](https://github.com/MacosPorters/betterxen/issues/304)
owns the narrow yielding fix after parent/runtime ownership coordination.
Handle critical sections, condition variables and other waits as separately
specified gaps, not incidental additions to that fix.
**Outcome:** an original hosted C program starts, uses the runtime, reports
results and exits through the guest path with checked cleanup.
Broader CPU behavior is driven by the admitted fixture. Start
[AVX/YMM design #299](https://github.com/MacosPorters/betterxen/issues/299) and
[unwind design #300](https://github.com/MacosPorters/betterxen/issues/300) in
parallel, but do not require their entire future scope for a simpler program.
A workload using those features must wait for real support. CPU feature bits
must not advertise unsupported behavior. Stack walking, structured exception
handling (SEH) and C++ exceptions are separate capabilities.
Review and integrate existing work rather than creating a competing runtime:
**Completion checks:**
| 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) |
- The source-built module graph has independently derived results and
initialization/teardown records, with explicit forwarder/cycle/search policy.
- One worker progresses while another waits. Results hold across specified
scheduling quanta; the injected clock and timeout units remain consistent.
- Static TLS, dynamic TLS, fiber-local storage (FLS), errors, errno and CPU state
retain their specified per-thread isolation. Dropping a value does not count
as executing its registered guest callback.
- Missing exports, failed attach, invalid callback targets, stack faults,
timeouts, deadlock and exhausted budgets have precise, bounded outcomes.
- Repeated runs reclaim owned modules, handles, stacks and callback state.
Unsupported delayed imports or lifecycle paths are rejected explicitly.
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.
**Contributor work:** reuse [package census #211](https://github.com/MacosPorters/betterxen/issues/211)
and the existing scheduler. Runtime PRs #263/#290 overlap; their authors and
maintainers must resolve ownership before shared production edits. Parallel
host-thread execution remains outside the serial scheduler's ordering claim.
**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 — Render a scene controlled by guest code
## Phase 3 — Make threaded application behavior coherent
**Deliverable:** a compiled original guest creates resources, uploads a texture
and geometry, submits translated rendering, waits for completion and checks the
resulting frame through its guest-visible interface.
**Outcome:** an original worker-based application can block and resume without
stalling unrelated guest work or leaking per-thread state.
Use [startup-to-frame integration #256](https://github.com/MacosPorters/betterxen/issues/256)
as the integration task. A Rust test calling a host graphics method does not
alone prove the compiled guest can call it. Specify the supported service/call
boundary and check its Win64 argument/return and nonvolatile-state behavior.
Guest addresses must resolve to checked ranges and opaque handles, never host
pointers.
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.
Existing translated `image_sample_lz`, guest descriptor-table bindings, texture
upload paths, blend/index/depth tests and packed compressed-texture footprints
are starting components. [Binding/entry design #302](https://github.com/MacosPorters/betterxen/issues/302)
specifies expansion beyond the bounded texture/sampler contract. Use an original
scene with distinguishable textures and resource updates so wrong bindings or
stale data change checked pixels.
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).
**Completion checks:**
**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.
- Actual native Metal execution produces frame readback matching expectations
derived independently of the decoder, compiler and production renderer.
- Changing one guest texture, transform or binding changes the expected frame;
a skipped draw or substituted shader cannot pass as correct rendering.
- Update, submit, completion, readback and retirement order are checked.
Resources remain valid for in-flight work and stale handles are rejected.
- Bad descriptors, overflowing ranges, unsupported shader forms and invalid
resource states fail before unsupported work reaches Metal.
- The report records device capability queries, validation settings, candidate,
commands and hardware. Synthetic gfx1030 success is not Xbox GPU verification.
## Phase 4 — Connect resource updates to translated rendering
**Contributor work:** [resource-update workload #147](https://github.com/MacosPorters/betterxen/issues/147),
[shared lifetime #148](https://github.com/MacosPorters/betterxen/issues/148),
[fences #224](https://github.com/MacosPorters/betterxen/issues/224), and
[format inventory #260](https://github.com/MacosPorters/betterxen/issues/260).
Respect the active format claim; do not duplicate its inventory.
**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.
## Phase 4 — Run an original interactive application
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.
**Deliverable:** one small original game-like application runs through the guest
CPU/runtime and native app with translated graphics, scripted input, bounded
audio and a save/load cycle in a persistent session.
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.
Compose the admitted paths from phases 2 and 3. Define the application source,
input replay, frame checkpoints, sample-data checks and save format before
implementation. Start with the CPU/shader subset already justified by the scene.
Add C++ or additional runtime functionality only when an original failing
fixture demonstrates the requirement and linked runtime terms are reviewed.
**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.
Wire the application through the existing Swift/Rust interface and worker
lifecycle. Existing native audio, controller and filesystem demonstrations are
components, not proof that guest code reaches each service. This phase must
exercise those guest connections in one session.
## Phase 5 — Run one integrated interactive application reliably
**Completion checks:**
**Outcome:** a small, original application joins guest execution, rendering,
input, bounded audio, filesystem access and lifecycle behavior in one session.
- A deterministic replay reaches independently specified state/frame checkpoints.
- Input reaches guest logic; expected audio samples are checked before device
playback; save/load preserves specified state and reports I/O failures.
- Start, pause, resume, stop, restart and worker failure have defined outcomes.
Commands do not report success after a worker has failed.
- Resource/handle counts and cleanup remain bounded across repeated sessions;
invalid guest paths and resource requests fail according to the interface.
- The native app/CLI provide a reproducible quick start and useful stage-specific
failure reports. This fixture still establishes no commercial compatibility.
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.
**Contributor work:** [audio #227](https://github.com/MacosPorters/betterxen/issues/227),
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),
[app CI #248](https://github.com/MacosPorters/betterxen/issues/248), and
[quick start #247](https://github.com/MacosPorters/betterxen/issues/247).
Execution-admission policy remains with
[#212](https://github.com/MacosPorters/betterxen/issues/212).
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).
## Phase 5 — Expand compatibility through a varied workload corpus
**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.
**Deliverable:** a versioned set of original source-built workloads exercises
meaningfully different CPU, runtime and graphics behavior through the integrated
path, with precise accepted/rejected profiles and reproducible regressions.
## Phase 6 — Improve measured bottlenecks
Choose additions from actual failures. Examples include another compiler or
runtime profile, vector-heavy arithmetic, runtime-dependent shader branches,
bounded loops, multiple resource views and streaming texture updates. Each
addition must demonstrate a gap not already owned by an existing task.
**Outcome:** faster or lower-resource execution of workloads whose correctness
is already checked, with measurements that another contributor can reproduce.
Use [CPU design #299](https://github.com/MacosPorters/betterxen/issues/299),
[unwind design #300](https://github.com/MacosPorters/betterxen/issues/300),
[runtime uniform branches #179](https://github.com/MacosPorters/betterxen/issues/179),
[bounded shader loops #180](https://github.com/MacosPorters/betterxen/issues/180),
and [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205).
Wave divergence, cross-lane operations, local data share (LDS), barriers, mesh
stages and ray tracing require their own public contracts, fixtures and native
capability checks when a selected workload needs them.
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.
**Completion checks:**
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).
- Each workload identifies its source/build recipe, required forms/services,
original expected outputs, limits and exact independently accepted candidate.
- Coverage separates declared, decoded, lowered, CPU-tested, locally GPU-tested
and independently accepted behavior. Compilation counts are not compatibility.
- Unsupported behavior retains explicit diagnostic controls; expected values do
not come from the same implementation being tested.
- Targeted mutation/fuzz/regression checks demonstrate sensitivity to the changed
behavior without altering tolerances, gate definitions or mutation counting.
- Earlier integrated workloads still pass. Failures become bounded tasks with
proposed files and dependencies, not a generic rewrite of a subsystem.
**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.
**Contributor work:** [original corpus #150](https://github.com/MacosPorters/betterxen/issues/150),
[shader acceptance #225](https://github.com/MacosPorters/betterxen/issues/225),
CPU coverage #154 and the existing QA owner #219. Reuse their tools and acceptance
rules; do not create another competing status or test framework.
## Taking the next task
## Phase 6 — Sustain execution across Apple Silicon
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.
**Deliverable:** admitted workloads run for a specified duration under bounded
memory/resource use, and performance/correctness reports are reproducible on
the actual native hosts contributors test.
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.
Specify soak duration, replay, resource limits and failure conditions before the
run. Measure guest execution, translation, service calls, transfers, Metal
startup, submission and readback to identify the actual bottleneck. Record
cold/warm behavior, variance and regressions as well as improvements.
Useful existing commands for the candidate record:
Use the existing native audit, GPU tests and benchmarks. Reuse merged startup
measurements and DBT comparison tooling; evaluate prewarming/persistence only
under [#258](https://github.com/MacosPorters/betterxen/issues/258) when measurements
justify it. Guest code-cache lifetime and same-block executable writes remain
explicit CPU correctness risks under #95 and #291.
```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
```
**Completion checks:**
- The agreed soak/restart protocol passes on the pinned candidate with recorded
resource accounting and no hidden fallback or silent loss of work.
- Baseline/candidate measurements use equivalent inputs, toolchains, settings
and hardware. Validation-on correctness and validation-off performance are
separate runs; benchmarks use an idle host as required by the protocol.
- [Native reports #303](https://github.com/MacosPorters/betterxen/issues/303)
distinguish host binary architecture, documented capabilities, actual execution,
failure, unavailable tools and skipped tests. Skips are never GPU passes.
- Runtime capability detection selects optional paths. M1–M5/future-device cells
stay unknown until actual reports exist; one machine cannot verify them all.
- Contributor preview preparation follows app/native gates. Signing, notarization,
redistribution review and publication require their own evidence and explicit
release authorization; this phase does not authorize uploads.
**Contributor work:** [soak #149](https://github.com/MacosPorters/betterxen/issues/149),
[memory pressure #204](https://github.com/MacosPorters/betterxen/issues/204),
[dependency evidence #158](https://github.com/MacosPorters/betterxen/issues/158),
and [preview preparation #259](https://github.com/MacosPorters/betterxen/issues/259).
## Phase 7 — Attempt documented Xbox compatibility
**Deliverable:** a separately reviewed compatibility experiment with admissible
inputs demonstrates exactly the supported startup/execution/rendering stages,
or records a specific unresolved contract that prevents the attempt.
Begin [public console-contract research #306](https://github.com/MacosPorters/betterxen/issues/306)
now, alongside the earlier engineering phases. Maintain evidence for launch and
CPU entry state, executable admission, service ABI, shader entry/bindings,
resource and command layouts, synchronization and memory aliases. Public PE,
AMD desktop ISA and D3D12 documents establish their documented contracts; they
do not automatically establish Xbox behavior. Unknown console details remain
unknown rather than becoming guessed implementations.
An actual execution attempt depends on demonstrated technical support for its
input, project-permitted authorized/unprotected material, explicit admission
and independent review. Do not obtain or use leaked executables, restricted
SDKs, confidential headers, proprietary shader collections, firmware or keys;
do not implement protection bypasses. A torrent filename or container does not
establish a supported executable, launch environment or compatibility result.
User files stay outside the repository. File validation concerns technical
compatibility and safety; it must not demand receipts, accounts or ownership
provenance uploads.
**Completion checks:**
- Required contracts have precise public sources and repository evidence classes,
or are visible blockers. Restricted/unavailable evidence is not bypassed.
- The admitted input profile, candidate, runtime capabilities and expected
outcomes are reviewed before execution and precisely bounded.
- Actual results separately identify inspection, loading, entry, menu/frame,
world simulation, interaction and sustained play. Reaching one does not
certify the next; crashes and missing behavior remain in the report.
- R1 audits evidence/provenance and R2 independently derives semantic expectations.
BetterXen has no Xbox hardware access and must never claim such verification.
- No game title is called supported or playable without a demonstrated repeatable
result. No date, compatibility percentage or release follows from this plan.
This phase can remain blocked while earlier original workloads continue to
improve. There is currently no demonstrated GTA VI execution in BetterXen.
## How contributors start
The [research tracker #298](https://github.com/MacosPorters/betterxen/issues/298)
links the eight new bounded tasks #299–#306 and the existing work they depend on.
The phase plan claims no implementation files. Research/design tasks can begin
on their documented paths; production changes must coordinate subsystem owners
and active claims. Read all comments, including imported archived claims, and
inspect linked open PRs before claiming one issue in a plain reply.
Every task needs an outcome, proposed files, dependencies, public semantic
sources, meaningful positive/negative checks and independent reviewers. Update
the changelog for meaningful changes. Record candidate-specific results and raw
logs under ignored `artifacts/`; distinguish implementation, local verification
and independent acceptance. Preserve historical evidence and attribution.
Run the applicable commands from `AGENTS.md`. Across simultaneous work use at
most four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or
mutation campaign. Never count unrun or skipped checks as passes. No commit,
push, merge or release is authorized by a phase or an issue claim.
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.
-357
View File
@@ -1,357 +0,0 @@
# PortWatch review and a native macOS execution plan
Reviewed November 24, 2026 (America/Chicago). This is a public-documentation and
source-boundary review, not a competitor execution campaign or independent
acceptance. **BetterXen does not support commercial Xbox game execution.**
## Recommendation
Continue BetterXen as an original ARM64 runtime with its own x86-64 CPU
translation and direct Metal backend. The Windows projects expose useful
engineering questions, test structures and failure categories. Their code is
not a drop-in native port. Do not fork a Windows emulator into this repository,
replace the CPU with Rosetta, or add a Vulkan/Windows compatibility runtime.
The next useful result is an original compiled application that starts through
a checked module/runtime path and reaches a translated, checked Metal frame.
Broader vector instructions, thread lifecycle, binding metadata and console
contracts must advance through explicit fixture-backed increments. Completing
synthetic applications alone cannot prove Xbox compatibility.
## What was inspected
The tracker snapshot is [PortWatch 2cedf62a](https://github.com/4lwayz/portwatch-vi/blob/2cedf62a16b63697f096763ecb99b4c10d4dbccc/data/tracker.json),
whose update timestamp is `2026-11-25T04:22:56.289Z` (November 24 locally).
Its 35 efforts, 22 tools and 30 candidates were screened. One candidate repeats
XCL. Three efforts have no public repository; seven repository endpoints were
unavailable across the combined list. Available repositories were pinned to
their observed default-branch commit; their metadata, README and public tree
were used to classify target, host assumptions, lineage and evidence scope.
The per-project tables below include every entry in these three lists: 85
unique repository endpoints were checked, 78 available and seven unavailable.
This is not a line-by-line audit of every source file, proof of all contributor
provenance, or a claim to understand unavailable/private code. No upstream
project, setup script, Windows executable, game, shader corpus, asset collection,
restricted SDK or decryption tool was run. Archive and protection-related entries
were screened at metadata/README level only; no mirrored implementation or
restricted payload was recovered. The tracker's flagged/ignored discovery/spam
queues are not endorsed engineering candidates and were not imported.
Selected public architecture/status documentation was read more deeply for
VIctory, VIctory-macOS, TuxBox, NativeX, SeriesX and XValkyrie; XSXEmu's README
provides detailed admission, TLS and graphics boundaries. Those documents
explain their own designs; they do not verify their claimed test/hardware results.
The supplied `/so` website URL was unavailable to the web reader; the public,
pinned repository data was accessible and matched the initial screened JSON.
BetterXen's working tree started at `f02eb2678e76e91876be5706ce91dca25dcc3017`
with existing local documentation edits. Read-only `git fetch` found newer main
[`b2654e93`](https://github.com/MacosPorters/betterxen/tree/b2654e93a42e74e29570183da1f31bb8cdc6f721).
A separate ignored source snapshot was inspected without switching, resetting
or merging the working tree. This distinction changes the hosted-C status.
The documentation PR is based on the reviewed newer main revision and changes
no runtime implementation.
## Why the PC results do not transfer directly
| Layer | Common PC approach described upstream | Native ARM64 BetterXen requirement |
| --- | --- | --- |
| CPU | Guest x86-64 runs on a matching x86-64 CPU; several projects require AVX2 | Decode/execute or translate each supported form, preserve precise state/faults, and advertise only satisfied guest features. |
| Loader/runtime | Windows APIs or Wine/Proton supply much of PE startup, TLS, exceptions, threads, files and CRT behavior | Original checked guest memory, module lifecycle, service implementations, callback bridges and guest exception design. |
| Graphics API | Console-facing objects dispatch onto desktop D3D12, sometimes through Vulkan | Explicit validated guest handles/commands and native Metal objects, lifetime, resource state and completion. |
| Shaders | RDNA machine code becomes HLSL/DXIL or SPIR-V | Independently verified RDNA-to-IR-to-MSL behavior, entry state and resource bindings. SPIR-V may be an intermediate, not a Vulkan runtime requirement. |
| Assets | Title supplies its own loaders or tools convert game-specific data | No need to become an archive viewer to prove guest execution; codecs/layouts require public contracts and demonstrated workload needs. |
| Evidence | README milestones, streams, screenshots, compilation counts or self-reported FPS | Pinned original fixtures, independent expectations, actual native execution/readback and candidate-specific receipts. |
PortWatch is a discovery/editorial service. Its percentages are not compatibility
measurements. The observed entries label their verification self-reported;
phrases such as “confirmed” inside editorial summaries do not become BetterXen
acceptance. Several forks share VIctory/XCL/Leonida lineage: ten forks are not
ten independent confirmations. Compilation, shader validation, first pixels,
scene completeness, interactive progress and stable play are distinct outcomes.
## macOS efforts and what “native” means here
[VIctory-macOS edba53dd](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/README.md)
uses Rosetta, CrossOver Wine and D3DMetal for the guest route. Native builds of
its portable crates are a different result. Its reported passing tests neither
establish a fully ARM64 runtime nor demonstrate playable game execution here.
Its [port notes](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/docs/macos.md)
provide leads for cache identity, upload visibility, floating-point edge cases,
capability/behavior mismatches and masked-store page faults. Reproduce relevant
questions with original Metal/CPU fixtures; do not copy its workarounds or assume
a D3DMetal defect exists in BetterXen's direct Metal path.
[XSXEmu 2d937f83](https://github.com/daeken/XSXEmu/blob/2d937f8360fbcdac368a0e363c24df322fa24db2/README.md)
is another macOS effort, so “nobody is working on Mac” would be inaccurate.
Its guest path uses an x86-64 Mach-O process and Rosetta, while owned shader
translation fixtures use Metal. It explicitly separates static audit from
execution admission and says no game frame has been produced. Its useful
lesson is that entry/binding information and DLL/TLS lifecycle are separate
contracts; its Rosetta guest route does not satisfy BetterXen's ARM64 rule.
[6stars 480d9a4d](https://github.com/meetox80/6stars/blob/480d9a4d00ed11560f7b4d989643723a0f5c451c/README.md)
and the separately listed 6stars engine candidate describe Swift/Metal world-data
rendering. An independent renderer may produce a convincing scene while never
executing the original game program. That is valuable work with a different
scope. No verified reusable component or file-level license clearance was
established by this review.
[nativ64 3b826108](https://github.com/Ybucaille/nativ64/blob/3b82610882bc55cb27f0ec563c126a226855a8ea/README.md)
targets Linux x86-64. Its central observation is relevant: host Windows APIs
that a Windows project forwards still need implementation on a different OS.
Its Linux syscalls/futexes and x64 ABI are not native Darwin ARM64 services.
BetterXen should prioritize from its own import/fixture failures, not copy that
project's title-specific API totals or implementation.
## BetterXen's actual starting point
| Area | Observed on current main b2654e93 | Consequence |
| --- | --- | --- |
| CPU inventory | 498 declared forms, 213 operations; tool classifies 93 operations native and 120 shared-semantics | These are inventory/lowering categories, not 498 independently accepted instructions or a compatibility percentage. VEX remains rejected. |
| Typed runtime registry | 47 services: 7 implemented, 37 partial, 3 stubs; tool reports 0 verified entries | This is the typed subset, not the total handwritten runtime. Named exports alone do not prove behavior. |
| Hosted C | A1 and A2 are present; PR #283 merged as d26af53c. Gate A records local passes awaiting independent review | Do not open another “implement hosted C” issue. Reproduce/accept the candidate and expand from a failing original workload. |
| Modules | startup.rs accepts one image; modules.rs exposes built-in service modules | Built-in LoadLibrary/GetProcAddress is not general EXE plus guest-DLL startup and teardown. |
| Threads | Deterministic serial guest scheduler with worker stacks/TEBs, waits and handles | Sleep can stall all workers; static worker TLS and thread/FLS callbacks remain documented gaps. Serial scheduling does not prove parallel x86 memory ordering. |
| Graphics | Translated image_sample_lz pixel stage, native texture tests and guest descriptor-table bindings already exist | The inspected README's former X10 description understated this bounded path; the replacement roadmap removes that stale planning row. Broader bindings, control flow and sampling still need contracts. |
| Shader inventory | Table records 1,465 identified forms, 189 decoded, 185 IR/MSL, 18 accepted Metal forms; reconciliation finds zero mismatches | Different domains and acceptance stages must stay separate. The compute inventory does not fully describe graphics-only sampling. #225 owns pending acceptance. |
| Texture/resource work | Packed BC footprints and bounded private texture staging merged; original resource/draw tests exist | Reuse them. Do not duplicate #260's active format inventory or assume guest/console integration from host upload success. |
| Native app | Existing Swift/FFI fixtures; app/CI and usability PRs remain separate | UI/audio/input fixtures are not one integrated compiled guest application. #256 is the existing integration task. |
| Console contract | Public AMD desktop ISA/PE/D3D12 documentation and explicit synthetic ABIs | Authentic launch, descriptors/commands and console-specific behavior remain unknown or unverified. No Xbox hardware access exists. |
Evidence for these boundaries: current-main
[CPU registry](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/cpu/instruction-registry.md),
[Gate A](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/testing/gate-a.md),
[startup](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/loader/src/startup.rs),
[module services](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/loader/src/services/modules.rs),
[threads](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/runtime/threads.md),
[graphics compiler](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/shader/src/graphics.rs),
and [semantic coverage](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/shaders/semantic-coverage.md).
These are source/inventory observations. Historical hardware results retain
their existing class A scope; none was rerun or independently certified here.
## What to take forward
Take **questions and test designs**, then implement independently from primary
sources. No emulator source was copied, ported, translated, vendored or adapted.
Repository-level license labels below are metadata only. They do not establish
per-file grants, GPL-3.0-or-later compatibility or rights to fixtures/data.
1. Build a small, falsifiable workload before expanding an entire subsystem.
TuxBox/NativeX-style separation of loader, ABI, GPU and presentation tests is
useful; their own expected outputs cannot become BetterXen's oracle.
2. Treat unresolved host services as a concrete inventory. Reuse #211's package
census, #254's report schema and #255's startup diagnostics. Keep unsupported
calls explicit; never return success merely to get farther.
3. Model CPU state and faults before optimizing translation. AVX/YMM, masked
memory accesses, unwinding and lifecycle cannot be supplied by ARM64 host
calling conventions or a renamed Windows DLL.
4. Make shader entry state, resources and pipeline identity explicit. A shader
can compile and still read the wrong descriptor or run under the wrong mask.
A replaced/skipped shader or an empty draw cannot pass a correctness gate.
5. Validate resource ownership and completion before pursuing zero-copy. Apple
unified memory does not remove guest/host address translation, storage modes,
alignment, cache visibility or in-flight lifetime requirements.
6. Expand wave behavior, loops, mesh and ray tracing only as separate reviewed
contracts. A first simple scene does not require all of them; future console
workloads may. Do not infer optional Metal features from a product name.
7. Measure startup/steady-state and correctness separately, with actual host
receipts. Cache keys must cover full relevant identity; prewarming is an
experiment under #258, not a prerequisite or promised performance win.
Primary semantic authorities are the [Intel SDM](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html),
[public PE format](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format),
[Microsoft x64 exception handling](https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64),
[AMD ISA publications](https://gpuopen.com/amd-gpu-architecture-programming-documentation/),
[public resource-binding specification](https://microsoft.github.io/DirectX-Specs/d3d/ResourceBinding.html),
and [Apple Metal feature tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf).
Class B applies only to what the relevant public specification documents;
applying desktop behavior to Xbox needs separate evidence (often C or U).
Feature tables are documentation, not our execution evidence across M1–M5.
## Contributor work and dependencies
The review is tracked in [#298](https://github.com/MacosPorters/betterxen/issues/298).
The new tasks below have bounded deliverables, proposed paths, public references,
negative controls and acceptance limits. They are unclaimed implementation work.
Design tasks can begin with public documentation; runtime changes must respect
parent claims and shared-file ownership. Read every issue comment and linked PR
before claiming. Do not claim several tasks in one comment.
| Priority/order | Work | Dependency and boundary |
| --- | --- | --- |
| First, research | [#299 AVX/AVX2 state and decode contract](https://github.com/MacosPorters/betterxen/issues/299) | Extends beyond existing #120–#124; keeps CPUID honest. No blanket AVX2 implementation claim. |
| First, research | [#300 bounded AMD64 unwind](https://github.com/MacosPorters/betterxen/issues/300) | Separates metadata/stack walking from SEH and C++ exceptions; existing trap stubs remain. |
| First, loader contract/fixtures | [#301 original EXE plus two-DLL startup](https://github.com/MacosPorters/betterxen/issues/301) | Reuses #211 census and supplies a prerequisite to #256. Production mapping changes are separately coordinated. |
| First, GPU contract | [#302 shader entry and resource bindings](https://github.com/MacosPorters/betterxen/issues/302) | Builds on existing #226 sampling/table work; coordinates #205, #179, #180 and #224. |
| First, QA design | [#303 native capability receipts](https://github.com/MacosPorters/betterxen/issues/303) | Reuses #254 schema, #248 app CI and #158 dependency evidence. No automatic fleet posting. |
| Next, scheduler implementation | [#304 Sleep yields ready workers](https://github.com/MacosPorters/betterxen/issues/304) | Narrow #228 child; coordinate parent and runtime PRs before code edits. |
| First, lifecycle design | [#305 worker static TLS and callbacks](https://github.com/MacosPorters/betterxen/issues/305) | Depends on module/scheduler contracts for production; no competing scheduler. |
| Parallel, public research | [#306 console launch/graphics evidence ledger](https://github.com/MacosPorters/betterxen/issues/306) | Links existing public research; unknown console details remain blockers rather than guesses. |
Reuse existing tasks rather than adding duplicates: #179 runtime uniform
branches, #180 bounded loops, #205 semantic expansion, #225 independent shader
acceptance, #224 fences, #147 resource-update workload, #148 shared lifetime,
#256 startup-to-frame integration, #260 format inventory, #247 quick start,
#250 session errors, #254 compatibility reports and #255 worker diagnostics.
PRs #293–#297 already cover app CI, CPU coverage, selection ordering, Open and
texture inventory respectively. Runtime PRs #263/#290 overlap substantially;
their author/maintainer must resolve them before new runtime edits. These
references are destination-repository numbers, not imported source numbers.
The replacement [development phases](../development-phases.md) define the sole
active work order, from compiled guest boot through modular workers, a
guest-controlled Metal scene, an interactive application, a compatibility
corpus, sustained native execution and conditional Xbox experiments.
Hosted C is implemented on inspected main, awaiting independent acceptance;
it is no longer an untouched prerequisite. Original integration, then measured
optimization, then only evidence-admissible compatibility experiments is the
path. There is no supported date or estimate for running a commercial game.
## Complete project screen
Each pin links to the exact README reviewed. “Unavailable” means that the
observed public GitHub endpoint returned 404; it does not prove why or justify
looking for restricted mirrors. “Unresolved” licenses and NOASSERTION are not
reuse permission. Descriptions below classify documentation, not executed code.
### Tracker efforts (35)
| Entry | Pinned public documentation | Classification and BetterXen decision |
| --- | --- | --- |
| ZETTROX (`Zettrox/ztrx`) | [`90b529f8`](https://github.com/Zettrox/ztrx/blob/90b529f878a470fec9bf07b7be316bc769a12232/README.md); license metadata: `GPL-3.0` | VIctory/victory-fork lineage; Windows x64 + D3D12. Hardware tuning and reported gameplay are not independent native-Mac evidence. |
| Uilian (`uiliannn/VItoriaBr`) | [`c2485475`](https://github.com/uiliannn/VItoriaBr/blob/c24854750132af24c10e954765047525e0249bd3/README.md); license metadata: `GPL-3.0` | VIctory-family Windows/DXIL fork; README and tracker differ on readiness. Keep results self-reported; no ARM64 execution path. |
| suri | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
| omonkey | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
| CGBJ | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
| hyphennn (`fxceless/victory-fork`) | [`310c6eb6`](https://github.com/fxceless/victory-fork/blob/310c6eb6c16822ab95076aad61fce19bba86bb98/README.md); license metadata: `GPL-3.0` | VIctory rendering fork, Windows x64/D3D12; useful failure categories include bindings and mesh work. No implementation reuse. |
| VIctory (`Marvisak/VIctory`) | [`940d32f6`](https://github.com/Marvisak/VIctory/blob/940d32f69b22265690a0b5a15d6ded572ba33baf/README.md); license metadata: `GPL-3.0` | Windows x64 direct guest execution, HLE and D3D12/DXIL. Public architecture documents host pass-through and title-specific work. |
| xbox-emulator (`omonkeyz/xbox-emulator`) | [`f89e4106`](https://github.com/omonkeyz/xbox-emulator/blob/f89e4106fe8a1728515afa34ceb5097132cadcda/README.md); license metadata: `GPL-3.0` | TomBox continuation; Windows-process runtime and RDNA shader work. README title reports are unverified here; assets/captures are excluded. |
| XCL (`xcl-dev/xcl`) | [`f5c5bdf0`](https://github.com/xcl-dev/xcl/blob/f5c5bdf0e91035f8f1404f46f4f2f7aedc259e7f/README.md); license metadata: `GPL-2.0` | Windows x64 direct execution plus D3D12/DXIL; host services and pipeline behavior matter. GPL-2.0-only README; no reuse clearance. |
| ScarlettX (`Freminet/ScarlettX`) | [`01c642cf`](https://github.com/Freminet/ScarlettX/blob/01c642cf62a6d9978f535e2c438c488ebcb4cd39/README.md); license metadata: `unresolved` | Windows x64 HLE/D3D12; separates console precompiled-shader gaps from desktop paths. Console-binary-derived findings need independent public evidence. |
| TuxBox (`brcly/TuxBox`) | [`97b8ad31`](https://github.com/brcly/TuxBox/blob/97b8ad3192def18d491fe72ea3a55e204bc77a5d/README.md); license metadata: `Apache-2.0` | x86-64 Windows and Linux/Proton; owned guest fixtures and provider-specific failures are useful testing patterns, not an ARM64 solution. |
| americas-recomp (`realdody/americas-recomp`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| Leonida (`ItsNotRexed/Leonida`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| OpenScarlett (`californiaAlmonds/OpenScarlett`) | [`022a8b25`](https://github.com/californiaAlmonds/OpenScarlett/blob/022a8b25148cc08412df8ac7e752b9efed4cd819/README.md); license metadata: `MIT` | Windows x64, D3D12/Vulkan; broad completeness claims are upstream reports. Public-spec-backed original fixtures are the only proposed transfer. |
| scarlett-layer (`jadeowaowa/scarlett-layer`) | [`0e436b3e`](https://github.com/jadeowaowa/scarlett-layer/blob/0e436b3e1c654765b193c1cb705918fbf101b10b/README.md); license metadata: `Apache-2.0` | Windows import interception/shims, D3D12 and synthetic test tiers; useful distinction between desktop samples and console compatibility. |
| Xbox2Windows (`R0Y00/Xbox2Windows`) | [`ab9a020c`](https://github.com/R0Y00/Xbox2Windows/blob/ab9a020c0783f9ce1dd10876cbeb119707b9ada9/README.md); license metadata: `MIT` | x64-to-C++ AOT/loader and DXIL research; distinguishes modified diagnostic startup from original executable compatibility. Host ABI still differs. |
| AnyXboxX (`LooperSalty/AnyXboxX`) | [`b92a71b9`](https://github.com/LooperSalty/AnyXboxX/blob/b92a71b9308e76f8ec9059c01d6e18f21611dc20/README.md); license metadata: `GPL-3.0` | Unicorn research and native Windows routes; current README also uses VIctory lineage. Do not treat its older interpreter label as ARM64 readiness. |
| XValkyrie (`sammwyy/xvalkyrie`) | [`c4c04970`](https://github.com/sammwyy/xvalkyrie/blob/c4c04970930d029a25622743e3ff4ef873ac17a6/README.md); license metadata: `GPL-3.0` | Windows x64 console API and shader translation; useful subsystem boundaries. Console/title-specific ABI claims remain unverified. |
| GTAVI-Recomp (`JamesCicada/GTAVI-Recomp`) | [`71766d8b`](https://github.com/JamesCicada/GTAVI-Recomp/blob/71766d8b5c669bc44639ad85bfd84edd8337c75a/README.md); license metadata: `GPL-2.0` | PS5/AnyPS5 route, not an Xbox launch contract; do not adapt emulator source or transfer PS5 APIs to Series. |
| AnyXboxSeries (`edupode/anyxboxseries`) | [`9ca2d053`](https://github.com/edupode/anyxboxseries/blob/9ca2d05329fe878db6abea6060889f9a95566719/README.md); license metadata: `NOASSERTION` | Windows D3D12 loader/inspection and an original sample; sample presentation does not establish Xbox guest execution. |
| SCARAB (`p-portela/SCARAB`) | [`8140e0be`](https://github.com/p-portela/SCARAB/blob/8140e0be4908499a5c4381eb4532410f05e39369/README.md); license metadata: `GPL-3.0` | Windows/D3D12 bridge, Linux through vkd3d-proton; memory/presentation incompleteness is explicit. Not native ARM64. |
| AnyBox (`Dark3581/AnyBox`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| PercyScarlett (`rpatty-dev/PercyScarlett`) | [`64719f96`](https://github.com/rpatty-dev/PercyScarlett/blob/64719f96d32f74d9d68cec69243b515ba675741f/README.md); license metadata: `GPL-2.0` | Windows x64/D3D12; README distinguishes existing DXIL titles from RDNA lifting and reports instability. GPL-2.0-only; no reuse. |
| GrandTheftXbox (`zohaiblazuli/GrandTheftXbox`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| Scarlett Windows Compat (`ProhorovIlja/NativeX-Runtime`) | [`b3087ce0`](https://github.com/ProhorovIlja/NativeX-Runtime/blob/b3087ce0ab191227dc9e7af37cab97a0b097bb98/README.md); license metadata: `MIT` | Portable inspection and separate Windows/Linux ABI/graphics probes. Useful test decomposition; not a complete application runtime. |
| DedSec (`Hylanderry/DedSec`) | [`c44b38ca`](https://github.com/Hylanderry/DedSec/blob/c44b38ca0207900cd27c687bb9213a6c8474bc69/README.md); license metadata: `MIT` | Windows x64/direct execution and D3D12; performance/feature claims need reproducible evidence. No Mac execution established. |
| Xbgtasix (`ljm-233/Xbgtasix`) | [`1a767872`](https://github.com/ljm-233/Xbgtasix/blob/1a7678729cd436f9adaa9772b76d97af3d292321/README.md); license metadata: `GPL-3.0` | Windows compatibility DLLs rely on the Windows loader for imports, relocation and TLS. This omitted host work is required on Darwin. |
| SeriesX Emulator (`anrq0/SeriesX-Emulator`) | [`4f07d76f`](https://github.com/anrq0/SeriesX-Emulator/blob/4f07d76f9f641ce85ce4238081c06d1cef1b7521/README.md); license metadata: `MIT` | Interpreter, original test applications and desktop launcher; README explicitly excludes commercial compatibility. Reported vectors are not our oracle. |
| GTA6-COMPAT-LAYER (ScarlettCompat) (`SSTGxf/ScarlettCompat`) | [`b92f060b`](https://github.com/SSTGxf/ScarlettCompat/blob/b92f060b1754580338dc30f57bb50777af38749d/README.md); license metadata: `MIT` | Windows native loader and console shims. Diagnostic bootstrap is a useful stage model; passing imports is not an implemented API. |
| XlaunchVI (`JPTuba9/xlaunch-vi`) | [`40feebd7`](https://github.com/JPTuba9/xlaunch-vi/blob/40feebd73a59c13ac5d65c3e61d21906111294e7/README.md); license metadata: `unresolved` | Windows x64, D3D12/Vulkan and frontend. README explicitly denies game compatibility; UI work is separate from guest execution. |
| OpenScarlett (Community Edition) (`OpenCommunityEdition/OpenScarlett`) | [`d1285fdd`](https://github.com/OpenCommunityEdition/OpenScarlett/blob/d1285fddbe399927581a772f536239b33a1e2cf4/README.md); license metadata: `AGPL-3.0` | Windows/Linux API layer; README build requires GDKX. Do not follow restricted tooling dependencies or import its sources. |
| Five Star Recomp (`ThatRecompDev/five-star-recomp`) | [`fb3b3a2d`](https://github.com/ThatRecompDev/five-star-recomp/blob/fb3b3a2def5af6eef6004c954c11f2cd22574168/README.md); license metadata: `GPL-3.0` | Windows platform, shader and asset tools; title startup claims do not establish a complete scene or native Mac execution. |
| G6Recomp (`Kajcsi/G6Recomp`) | [`82ccaa5d`](https://github.com/Kajcsi/G6Recomp/blob/82ccaa5d4b3fdc1edb9cdd95c8dbab4ee7cde352/README.md); license metadata: `GPL-3.0` | Windows AVX2/direct-execution loader with fixture tests; static-recompilation name does not remove reliance on x64/Windows ABI. |
| GTA6-BootTest (`OnlyMoisties/GTA6-BootTest`) | [`32683d8f`](https://github.com/OnlyMoisties/GTA6-BootTest/blob/32683d8fe2841bddeb0b437109e97bc32cf55724/README.md); license metadata: `unresolved` | Windows debugger/shim/GPU startup harness. Reported first UI frame is not full scene correctness; no root license identified by metadata. |
| Palmetto (`luizwidmer/palmetto`) | [`6416a273`](https://github.com/luizwidmer/palmetto/blob/6416a273336599341dfd31e64cc3da3fd1b855ed/README.md); license metadata: `GPL-3.0` | Windows runtime and RDNA-to-SPIR-V/Vulkan path; behavior-stage reporting is useful, runtime/backend is incompatible with our target. |
### Tracker tools (22)
| Entry | Pinned public documentation | Classification and BetterXen decision |
| --- | --- | --- |
| `lynxnathan/rage-tools-vi` | [`547ee9ba`](https://github.com/lynxnathan/rage-tools-vi/blob/547ee9ba2dde236644a597cef65a18f7bd5549be/README.md); license metadata: `MIT` | Asset/catalog tooling; README mentions executable-derived information. No derived corpus imported; not a CPU/runtime shortcut. |
| `fishingpvalues/gta6-pc-port-hub` | [`3a7d8d18`](https://github.com/fishingpvalues/gta6-pc-port-hub/blob/3a7d8d18f6fdc2071f8609f35153fb07ac25d1b5/README.md); license metadata: `CC0-1.0` | Archived coordination hub. Its missing-executable snapshot is historical, not evidence of current file availability or native compatibility. |
| `holdmysocks/SixNG` | [`8897a1f6`](https://github.com/holdmysocks/SixNG/blob/8897a1f60c6700553987954f567d9146f898d882/README.md); license metadata: `GPL-3.0` | Asset exporter with explicit texture fallback limitations; fallback pixels must never become BetterXen correctness evidence. Defer format work to #260. |
| `rpatty-dev/PercyStar` | [`ca4cd4c0`](https://github.com/rpatty-dev/PercyStar/blob/ca4cd4c09bb3a4e29cc2d33e69385725c5fb2220/README.md); license metadata: `NOASSERTION` | Asset/shader/media tools with custom attribution terms. macOS tooling does not establish guest execution or GPL-compatible reuse. |
| `breadbbbb/rpf9-explorer` | [`cab9bb6e`](https://github.com/breadbbbb/rpf9-explorer/blob/cab9bb6ebe6d46fec6ac90ee5004bdd8cfd9e31a/README.md); license metadata: `unresolved` | Cross-platform asset viewer/exporter; root grant unresolved in metadata. Exclude code/assets; sample viewing is not guest execution. |
| `Ahmet-Dedeler/bcpack-rs` | [`b1c3099a`](https://github.com/Ahmet-Dedeler/bcpack-rs/blob/b1c3099a3402de8b76c9263a828791bd8bc0c930/README.md); license metadata: `NOASSERTION` | Texture codec research with reported synthetic tests; useful codec boundary, but exact tables/provenance/file licenses are unreviewed. Defer to #260. |
| `nullbrik/RageForge` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| `woreksami/ttpf-studio` | [`a2fe110d`](https://github.com/woreksami/ttpf-studio/blob/a2fe110d8e7aeb8ed3be37c365c75078a408c089/README.md); license metadata: `MIT` | Texture/archive/video tooling. No original executable execution; no proprietary payload or replacement asset imported. |
| `walkthestars/GTA6-Asset-Info` | [`bad5bc21`](https://github.com/walkthestars/GTA6-Asset-Info/blob/bad5bc2180ade416eafdb50aa21e21eeec5adbda/README.md); license metadata: `GPL-3.0` | Asset-format notes for SixNG. Discovery only; derived samples/tables remain outside this review. |
| `Ahmet-Dedeler/awesome-gta6-reverse-engineering` | [`34a6e945`](https://github.com/Ahmet-Dedeler/awesome-gta6-reverse-engineering/blob/34a6e945b9698975ccd4e0c2e039034914dcc278/README.md); license metadata: `NOASSERTION` | Discovery index. Linked tools, code and asset claims have separate provenance and terms; no linked payloads were obtained. |
| `HolyRoses/gta6-explorer` | [`8e383a49`](https://github.com/HolyRoses/gta6-explorer/blob/8e383a49d07da5068fa30ebf208025e307018fcc/README.md); license metadata: `MIT` | Read-only package/asset inspection; not a guest runtime. No package bytes or format-derived corpus imported. |
| `meetox80/6stars` | [`480d9a4d`](https://github.com/meetox80/6stars/blob/480d9a4d00ed11560f7b4d989643723a0f5c451c/README.md); license metadata: `unresolved` | Swift/Metal world-data renderer. Native graphics demonstration is a different objective from executing original Xbox CPU/shader code. |
| `Ahmet-Dedeler/rage9-re` | [`30c6d215`](https://github.com/Ahmet-Dedeler/rage9-re/blob/30c6d2150ad9d3021802f509ff3ee232d466f499/README.md); license metadata: `NOASSERTION` | Animation/script asset-format tools, not executable compatibility. No asset samples or derived format tables imported. |
| `Albotterin/AWC_from_RPF9_Extractor` | [`decfde54`](https://github.com/Albotterin/AWC_from_RPF9_Extractor/blob/decfde54243d9a982550b08c7db21c34a20a1775/README.md); license metadata: `MIT` | Audio extraction tooling with upstream dependency/license scopes. Does not implement guest audio APIs; no extracted audio or code reuse. |
| `SentinelInteractive/0x52504639` | [`f1a383a7`](https://github.com/SentinelInteractive/0x52504639/blob/f1a383a72e90706b88d82f0ed1a674a0d7fcba58/README.md); license metadata: `MIT` | Format notes/catalogs, no execution evidence. Do not promote derived counts into console support. |
| `JoshRob297/rpf9-research` | [`144d3451`](https://github.com/JoshRob297/rpf9-research/blob/144d345191bd37de3f6bd5e85df3e8ae8815552e/README.md); license metadata: `GPL-3.0` | Container research/catalogs; protected-index/key questions are outside BetterXen scope. No derived indexes imported. |
| `Librett0/vice-lens` | [`8b8c8a84`](https://github.com/Librett0/vice-lens/blob/8b8c8a847ef926d8d6298ecfade142db19cfce5d/README.md); license metadata: `MIT` | Asset viewer/world renderer and media tooling; viewing a scene is not original-game execution. No asset/capture reuse. |
| `batatinhafcbatatinha-pixel/xseriesrecomp` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| `sub-north/xbox-hle-lab` | [`8863028b`](https://github.com/sub-north/xbox-hle-lab/blob/8863028b486dedf660303fcd3c756b05bbbebf91/README.md); license metadata: `MIT` | Separate original probes, docs and XCL patches with different license scopes. Useful falsifiable-reproduction discipline; no patch reuse. |
| `kry-vex-gta/XBOX-Inspector` | [`0a3d067f`](https://github.com/kry-vex-gta/XBOX-Inspector/blob/0a3d067f7167a30b5e2517a4e781ec1ada3006d7/README.md); license metadata: `MIT` | Static inspection/recompilation prechecks. Metadata analysis is not guest execution; existing #211/#254 own comparable BetterXen work. |
| `nineforge0/forge9` | [`f40381ca`](https://github.com/nineforge0/forge9/blob/f40381cac62ade007a62e728eaa988fd9677bec4/README.md); license metadata: `MIT` | README advertises decryption and executable-derived key/table workflow. Excluded from implementation/input research; no such code or inputs accessed. |
| `TheoBIET/OpenVI` | [`fd415911`](https://github.com/TheoBIET/OpenVI/blob/fd4159118e750084451b9bad364169660daaa5e2/README.md); license metadata: `GPL-3.0` | Cross-platform asset explorer. macOS UI availability is not native emulation; no content or auto-update workflow executed. |
### Tracker candidates (30, including repeated XCL)
| Entry | Pinned public documentation | Classification and BetterXen decision |
| --- | --- | --- |
| `edsuuu/VI-BR-PORT` | [`7a30f506`](https://github.com/edsuuu/VI-BR-PORT/blob/7a30f5063dafeda1ceab84d251c22dc581d4dfc6/README.md); license metadata: `GPL-3.0` | VIctory-family Windows/NVIDIA memory tuning; wave32 assumptions must not be transferred to Apple GPU capability claims. |
| `xcl-dev/xcl` | [`f5c5bdf0`](https://github.com/xcl-dev/xcl/blob/f5c5bdf0e91035f8f1404f46f4f2f7aedc259e7f/README.md); license metadata: `GPL-2.0` | Windows x64 direct execution plus D3D12/DXIL; host services and pipeline behavior matter. GPL-2.0-only README; no reuse clearance. |
| `ZigZagBoi1/ScarlettPort` | [`48ba23a9`](https://github.com/ZigZagBoi1/ScarlettPort/blob/48ba23a91a83121f8d0625a633e88fa463d5a0ca/README.md); license metadata: `NOASSERTION` | Windows x64/D3D12 compatibility route; no native Darwin CPU/runtime established. |
| `Steinkoloss/port-of-the-americas` | [`0f3be36a`](https://github.com/Steinkoloss/port-of-the-americas/blob/0f3be36aaefe69c25f06e05222b88453f3557acd/README.md); license metadata: `unresolved` | Linux x64/Proton/vkd3d-proton shims; README names Leonida shader conversion. No implementation reuse. |
| `Leucodermique/VIce` | [`8c7b24fd`](https://github.com/Leucodermique/VIce/blob/8c7b24fda90eb08fe64044726b7c880065a86ee0/README.md); license metadata: `GPL-3.0` | VIctory-based Windows distribution/frontend; consolidation does not independently validate combined changes. |
| `flipflapov/DSTN` | [`7066ae66`](https://github.com/flipflapov/DSTN/blob/7066ae669c7b0e20d0b05675826169cdc7442883/README.md); license metadata: `GPL-3.0` | Leonida fork; tool portability on macOS does not establish native guest execution. No implementation reuse. |
| `daeken/XSXEmu` | [`2d937f83`](https://github.com/daeken/XSXEmu/blob/2d937f8360fbcdac368a0e363c24df322fa24db2/README.md); license metadata: `MIT` | macOS Rust host with Rosetta guest execution and separate native Metal shader fixtures; not a fully ARM64 guest CPU path. No game frame claimed. |
| `SixLauncher/VILauncher` | [`bf2f6ca9`](https://github.com/SixLauncher/VILauncher/blob/bf2f6ca9a6445aee6ebdff2b1cef87266f9cf1f4/README.md); license metadata: `GPL-3.0` | Linux launcher selecting VIctory/XCL under Wine/Proton. Not a new guest execution or Metal implementation. |
| `4Sakens/Project-Kalaga` | [`56b41fb4`](https://github.com/4Sakens/Project-Kalaga/blob/56b41fb4a68b89e5e356c1445699ba4ac6b8cc83/README.md); license metadata: `unresolved` | Windows consolidation of existing efforts; aggregated subsystems and local paths are not independent compatibility evidence. |
| `idvwork/rebox` | [`a833078e`](https://github.com/idvwork/rebox/blob/a833078e3366a70a74edef0cbfe01b80a81dd55c/README.md); license metadata: `GPL-2.0` | WineGDK/vkd3d-proton and AnyPS5 shader lineage; incompatible runtime and no emulator adaptation permitted. |
| `Yhozen/series-web` | [`d7512b29`](https://github.com/Yhozen/series-web/blob/d7512b299fe2836e08783665308cd8c4bb924345/README.md); license metadata: `GPL-2.0` | PISCO AOT x86-to-WebAssembly/runtime research; original browser workloads differ from native ARM64/Metal and Xbox compatibility. |
| `DesignWithTommy/Neonbridge` | [`954c00c5`](https://github.com/DesignWithTommy/Neonbridge/blob/954c00c506a8616e985e94e8ea6bcbfba7f80f48/README.md); license metadata: `GPL-3.0` | Windows VIctory-family launcher/runtime; frontend and startup improvements are not CPU translation for ARM64. |
| `moonrelax/basalt` | [`8af09135`](https://github.com/moonrelax/basalt/blob/8af091350e0d5cdf89f3736a756235a72b67bea9/README.md); license metadata: `MIT` | Original interpreter/cooperative scheduler research; GPU objects are fake and no rendering is claimed. Do not reuse stubs as acceptance. |
| `ka1qux/victory-ka1qux` | [`77b8a9eb`](https://github.com/ka1qux/victory-ka1qux/blob/77b8a9eb0d29521f34ffe6061530cc873090e844/README.md); license metadata: `GPL-3.0` | VIctory-family AMD Windows rendering fork. Vendor-specific counters and claimed fixes need independent original tests. |
| `ethan00013/keylime` | [`361c7e94`](https://github.com/ethan00013/keylime/blob/361c7e94ab9d29d88cb1e5bfaadc8c3fb909bebc/README.md); license metadata: `GPL-3.0` | Windows x64 runtime with Vulkan/SPIR-V; no native Mac route. Backend and console-specific claims need independent contracts. |
| `Joaco9020/mangrove` | [`d16326c6`](https://github.com/Joaco9020/mangrove/blob/d16326c652b6f82e7b59b390f63e37cab816acd3/README.md); license metadata: `GPL-3.0` | VIctory-family Windows fork tuned for lower-VRAM NVIDIA GPUs. Settings are not portable Metal correctness work. |
| `chvabalo-interactive/sludgemu` | [`29cf795e`](https://github.com/chvabalo-interactive/sludgemu/blob/29cf795e23bb4917b9a8acd6be95d38a0f3b99b1/README.md); license metadata: `unresolved` | Windows direct guest execution and D3D12/DXIL, early startup with logging stubs. Stubs are not behavior support. |
| `larpingvibecoder/sonoma` | [`835f386a`](https://github.com/larpingvibecoder/sonoma/blob/835f386a144eca0b903b8bec63c0a003d7e07071/README.md); license metadata: `Apache-2.0` | Windows Rust runtime/direct DXIL, early proof of concept; name does not indicate macOS support. |
| `7jycwjmbfn-eng/scenegate-vi` | [`d5908947`](https://github.com/7jycwjmbfn-eng/scenegate-vi/blob/d590894710631a3c6adc6cca526c44d3c0c2bd41/README.md); license metadata: `MIT` | Windows/Vulkan startup and scene work based on Leonida; retain only documented failure categories, not code or title-derived inputs. |
| `TaynanGT/victory-windows-anterior-20261125` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
| `TaynanGT/victory-windows` | [`cdcff8fe`](https://github.com/TaynanGT/victory-windows/blob/cdcff8fe96182bade41343a10b985c028e9e8968/README.md); license metadata: `GPL-3.0` | VIctory-family Windows work on a non-main default branch; pin the actual branch, not its name. |
| `Archivist-Atlas/gta-vi-astral` | [`ff21332e`](https://github.com/Archivist-Atlas/gta-vi-astral/blob/ff21332e5ea2ea1c254a97c0b3036d36ff8e79ce/README.md); license metadata: `unresolved` | Go Windows runtime research citing VIctory/Leonida designs; no independent ARM64/Metal execution established. |
| `airpiglabs/crouton` | [`faad29e6`](https://github.com/airpiglabs/crouton/blob/faad29e6af4c45804cfa8a42901341a52d9c824c/README.md); license metadata: `GPL-2.0` | XCL/Bathyal lineage, Windows then Wine/Proton; GPL-2.0-only and incompatible host/runtime route. |
| `natedemoss/vice-pc` | [`2f98c053`](https://github.com/natedemoss/vice-pc/blob/2f98c05325237bc8ed8faf0e7b95bc0e6d22b9bb/README.md); license metadata: `MIT` | Windows loader proof of concept; README says nothing boots. No ARM64 or Metal evidence. |
| `JoseArranzSanchez/GTA6_PCPORT_INFO` | [`585b42a1`](https://github.com/JoseArranzSanchez/GTA6_PCPORT_INFO/blob/585b42a184bf1cdf1a5f8e76e0d2e7f8a9102857/README.md); license metadata: `NOASSERTION` | Secondary feasibility report, not implementation or primary legal authority. No legal conclusions adopted from it. |
| `DBWilliamEngineering/IraRationis` | [`67106e80`](https://github.com/DBWilliamEngineering/IraRationis/blob/67106e80ef34407f545b82bbd9b2c244f304ca3c/README.md); license metadata: `GPL-3.0` | C#/.NET AOT adaptation of ztrx; Windows x64 target remains. Review mixed license scopes if ever considering unrelated tooling. |
| `Guernica4u/GTA6-PC-Port-Archive` | [`7b69fa54`](https://github.com/Guernica4u/GTA6-PC-Port-Archive/blob/7b69fa5430ae19fd013b0ba19ffbd7badf3b93e8/README.md); license metadata: `unresolved` | Archive of other projects. Metadata/README screen only; do not use it to recover unavailable or prohibited implementation/material. |
| `idvwork/6stars-gta-vi-engine` | [`26a52ba2`](https://github.com/idvwork/6stars-gta-vi-engine/blob/26a52ba2ce5504c2c94a77c15838573538da5b70/README.md); license metadata: `unresolved` | Swift/Metal asset-world renderer, same stated approach as 6stars. Rendering data is distinct from executing the original guest; license/provenance unresolved. |
| `Ybucaille/nativ64` | [`3b826108`](https://github.com/Ybucaille/nativ64/blob/3b82610882bc55cb27f0ec563c126a226855a8ea/README.md); license metadata: `Apache-2.0` | Linux x86-64 Windows-API replacement library, not CPU translation. Its host-API inventory explains native-port work hidden by Windows pass-through. |
| `sleep10dev/XPORT` | [`2baf2a0f`](https://github.com/sleep10dev/XPORT/blob/2baf2a0f7c2af9f031158e082dfc4a6bb5b8266c/README.md); license metadata: `GPL-3.0` | Windows Rust loader/HLE/partial RDNA/D3D12 research, no demonstrated game compatibility. |
### Explicitly supplied Mac project and tracker
| Project | Pin | Decision |
| --- | --- | --- |
| `pragyaangaur/VIctory-macOS` | [`edba53dd`](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/README.md); license metadata: `GPL-3.0` | Wine/CrossOver + Rosetta + D3DMetal guest route. Native platform unit tests are distinct from Windows-under-Wine GPU tests. |
| `4lwayz/portwatch-vi` | [`2cedf62a`](https://github.com/4lwayz/portwatch-vi/blob/2cedf62a16b63697f096763ecb99b4c10d4dbccc/README.md); license metadata: `unresolved` | Editorial discovery site and JSON data, not an emulator. Scores and live-stream summaries are not independent acceptance. |
## Verification performed and remaining limits
Read-only inventories ran for both the working-tree baseline and the extracted
current-main snapshot. Working-tree CPU/runtime counts were 491 forms/206
operations and 20 typed services; current main reports 498/213 and 47. Shader
reconciliation reported zero mismatches for both. These checks inspect catalogs;
they are not CPU instruction execution, GPU tests or independent acceptance.
Documentation checks also ran successfully on the working-tree candidate:
`python3 scripts/audit/status.py --check`, `scripts/audit/claims.sh` (22 claims),
`scripts/audit/dependencies.sh` (five graphics crates), Markdown local-file link
checks and `git diff --check`. These audit results do not verify runtime changes
present only on the separately inspected newer main snapshot.
Research metadata and ignored raw documentation are retained locally under
`artifacts/research-portwatch/`. GitHub API reads and issue/PR state checks
establish accessibility and observed state. Python HTTPS initially failed
certificate verification; authenticated `gh api` reads succeeded without
turning off certificate checks. No dependency was installed to work around it.
No Rust build, CPU execution suite, native GPU test, demo, fuzz, mutation or
benchmark ran for this documentation task. New acceptance must use the exact
candidate, actual native tool architecture and actual eligible hardware.
Independent reviewers have not certified this report's proposed implementations.
The research stage installed or executed no upstream project or game content.
Documentation publication and the GitHub research/follow-up issues were requested
by the user; their delivery status is recorded in the linked PR/tracker. No
runtime merge, release or compatibility acceptance is implied.
+140
View File
@@ -0,0 +1,140 @@
# Remill native ARM64 experiment
Issue [#324](https://github.com/MacosPorters/betterxen/issues/324). This is an
isolated evaluation, with no production CPU or workspace dependency changes.
It uses original fixture bytes and harness code. Remill and its dependencies
remain external under ignored `artifacts/`; their notices are retained there.
## Decision and local result
**Keep the existing translator. The extended Remill adapter fails tested
floating-point and instruction-budget requirements.** See the
[extended evaluation](evaluation-2.md) for the failing cases, vector/control
results and exploratory measurements.
Remill built natively and the small lifted integer workload executed correctly
on this host. This establishes a usable experiment, not a production backend.
Broader instruction semantics, representative performance and runtime
integration remain unestablished.
Commercial Xbox execution remains unsupported.
The experiment also passed Rust formatting, strict Clippy for the standalone
bridge and its targets, C++ compilation with `-Wall -Wextra -Werror`, Python
syntax checks, local documentation-link checks and `git diff --check`. Full
workspace/GPU suites, fuzzing, mutation campaigns and the production benchmark
suite were not run. The extended report records separate toy-workload timings.
The initial November 25, 2026 prototype on Apple M4/macOS 27.0 (26A428) completed:
| Check | Local result |
| --- | --- |
| Dependencies and Remill | Native ARM64 builds succeeded with LLVM 17.0.6; upstream build warnings remain in the logs. Upstream tests were disabled; the result below comes from the original experiment harness. |
| Original AMD64 fixtures | Five traces lifted to LLVM IR, then compiled to ARM64 Mach-O objects with LLVM. Guest x86 bytes were never executed as host code. |
| Arithmetic | Six ADD/store/return cases passed through Remill, BetterXen's interpreter and its ARM64 dynamic binary translator (DBT). All three matched hand-derived RAX, carry/parity/auxiliary-carry/zero/sign/overflow flags, stored data and stack movement. |
| Checked memory | Four cases passed through all three paths: unmapped read, unmapped write, read-only write and an eight-byte write crossing the end of a mapping. Each stopped at guest RIP `0x1000`, preserved the checked registers and flags, and left both data words and the read-only sentinel unchanged. |
| Unsupported control | Remill's UD2 and indirect jump traces stopped explicitly in the harness. This does not implement guest exception delivery or indirect dispatch. |
| Wrong-answer control | Changing the first expected sum makes the harness fail with exit 1, as required. |
| Aggregate | 32 case/path checks passed: `(6 arithmetic + 4 memory) × 3 engines + 2 Remill control rejections`. |
| Native audit | `file`, `lipo -archs` and `otool -L` receipts cover the native tools, linked non-system dylibs, dependency archives, generated objects and final executable. macOS shared-cache libraries are identified separately. |
Host execution evidence above is **class A: direct local observation on this
Apple M4**. It is not Xbox hardware evidence, independent R1/R2 acceptance,
an M1–M5 compatibility result or a performance result. No GPU tests were run;
this is a CPU experiment. The author of this harness does not certify it.
The default Rust 1.94.1 build was refused by BetterXen's Rust 1.100 requirement;
an exploratory `--ignore-rust-version` attempt also failed on `atomic_try_update`.
The successful run uses the separately installed native Rust 1.100.0, without
changing BetterXen's requirement or implementation. Both failures remain logged.
## What the prototype does
`evaluate.py` checks the pinned Remill source, audits native inputs, optionally
builds dependencies/Remill, lifts five explicit byte strings and lowers the
resulting IR to ARM64. Only entry symbol names and x86 code-generation attributes
are adjusted; instruction bodies are retained. The original IR and adjusted IR
are both kept for inspection. LLVM receives the native host target explicitly.
`prototype.cpp` supplies the checked 64-bit memory intrinsics, a validated return
sentinel and explicit rejection hooks. Its flag annotation functions return the
predicate already computed by the lifted semantics. Unimplemented intrinsic
symbols cause a link failure. No generic no-op fallback is supplied.
`bridge/` is a separate, non-publishable Rust crate. It calls the real
`xenora_loader::memory::GuestMemory` methods and runs the same bytes through
BetterXen's existing interpreter and DBT. It is not a second memory mock. Its C
ABI accepts trusted harness pointers only, and is not a public guest interface.
The C++ error escape happens after a Rust memory call has returned; it does not
unwind through a Rust frame. This single-threaded harness cannot be used as a
general runtime error adapter.
The arithmetic program is `add rax, rcx; mov [rbx], rax; ret`. The six input pairs
cover an ordinary sum, unsigned wraparound, positive signed overflow, two
negative operands overflowing to zero, an auxiliary carry and zero. Expected
values are literal, hand-derived constants in the harness, independent of the
three execution paths. The Intel instruction reference is the semantic source:
[Intel Software Developer's Manuals](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html),
Volume 2, ADD/MOV/RET/UD2. These expectations still require independent review.
## Reproduce
Use native ARM64 macOS, Rust 1.100.0, CMake, Ninja, Git, Python 3 and native
Homebrew LLVM 17. Keep all source/build products beneath an ignored artifact
directory. The dependency builds can download a substantial Ghidra source tree.
The driver bounds each build to 1,800 seconds and limits parallel builds to two
jobs. It does not install system packages or change shell configuration.
From this worktree's root:
```sh
TASK_ROOT="$PWD/artifacts/remill-evaluation"
mkdir -p "$TASK_ROOT"
git clone https://github.com/lifting-bits/remill.git "$TASK_ROOT/upstream"
git -C "$TASK_ROOT/upstream" checkout --detach 66c488c9911fd9b368e4d0c9647d74239f8bba8b
python3 experiments/remill/evaluate.py --root "$TASK_ROOT" --build
```
For an already built artifact directory, omit `--build`. The `--llvm` argument
can select another installation of LLVM 17. Commands, exit statuses, native
architecture/linkage checks, source hashes and the actual harness output go to
`receipt.json` and individual logs in that directory. A failed stage leaves a
failed receipt and raises an error; absent prerequisites never count as a pass.
Raw receipts and generated files remain in the ignored artifact directory
selected with `--root`. The full build-driver receipt is `receipt-build.json`;
`receipt.json` records the initial prototype and `receipt-extended.json` records
the failing extended evaluation. This review branch includes source, reproduction
instructions and scoped findings; it does not include upstream build trees,
executables, raw gate logs or machine-specific paths. Recorded results are local
evidence, not independent acceptance.
## Adapter design
[Proposed correctness adapters](adapter-design.md) specify exact numerical-helper
commit rules, per-instruction dispatch, a versioned result layout and regression
gates. This is a design deliverable; the adapters are not implemented and the
existing extended gate still fails.
## Requirements before adoption
1. **State and faults:** define conversions for all CPU state, precise memory
fault metadata, partial/restartable instructions, exceptions and budget exits.
This harness checks only a small integer state slice and four memory faults.
2. **Execution:** supply bounded block dispatch, indirect calls/returns, service
interception, cache invalidation, code lifetime and scheduler transitions.
Ahead-of-time compilation of these five traces establishes none of those.
3. **Instruction coverage:** independently test the actual SSE/AVX forms needed
by admitted workloads. Validate rounding, MXCSR, NaNs and x87 behavior against
BetterXen's documented contract; advertised lifting coverage is insufficient.
4. **Memory ordering:** derive atomic/barrier semantics and fault atomicity for
ARM64 explicitly. No atomics, concurrency or host TSO assumptions were tested.
5. **Measurements:** compare matched workloads, cold compilation, warm execution,
memory use and code size with the current DBT. The harness recreates engines
for correctness cases; its elapsed time is not a meaningful speed comparison.
6. **Review and licensing:** obtain independent R1/R2 review and a complete
file/dependency attribution audit for the precise integration. See
[the preliminary license record](licenses.md). No release artifact is cleared.
Primary upstream design references:
[Remill README](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/README.md),
[architecture and memory intrinsics](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/docs/DESIGN.md),
[runtime intrinsic declarations](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/include/remill/Arch/Runtime/Intrinsics.h).
+297
View File
@@ -0,0 +1,297 @@
# Proposed Remill correctness adapters
**Design only. No adapter described here is implemented or independently
accepted.** The [extended evaluation](evaluation-2.md) still has eight numerical
mismatches and a missing guest-budget exit. Keep the current production CPU
path. This design is the next bounded experiment under issue #324; it does not
authorize changes to production admission, CPUID or the AVX work in #299.
The candidate remains BetterXen `b2654e93a42e74e29570183da1f31bb8cdc6f721`
and Remill `66c488c9911fd9b368e4d0c9647d74239f8bba8b`. All initial implementation
files belong under `experiments/remill/`; generated code and logs stay under
ignored `artifacts/`. Upstream code remains external with its notices intact.
## Architecture decision
Build a consumer of Remill's **single-instruction** lifting interface. Return
from each admitted instruction to a dispatcher that owns budgets, faults and
canonical guest state. Initially reuse BetterXen's exact integer-based numerical
implementation for legacy register-to-register `ADDSS`. Handle the small admitted
control-transfer subset explicitly in the adapter, and report that work in its
own counters. Do not pass arbitrary floating-point instructions to an unguarded
LLVM floating-point operation.
The existing `remill-lift-17` command optimizes whole traces before exporting
them. Its output is useful evidence but has already lost dependable instruction
boundaries. Do not recover a budget contract by counting optimized IR operations,
searching textual IR labels, charging only backward branches, or relying on the
external timeout. Each guest instruction can produce many IR operations, and
optimization can merge or remove them.
The pinned upstream interfaces actually inspected are:
- `Arch::DecodeInstruction` in `include/remill/Arch/Arch.h`.
- `InstructionLifterIntf::LiftIntoBlock` and `LiftStatus` in
`include/remill/BC/InstructionLifter.h`.
- `Instruction::bytes`, `pc`, `next_pc`, `branch_taken_pc`,
`branch_not_taken_pc` and `category` in `include/remill/Arch/Instruction.h`.
Upstream warns that decoding a larger byte stream can fuse idioms. Supply exactly
one independently bounded instruction and reject a disagreement in length,
operands or category. The actual consumer and its LLVM wrapper still need to be
written and tested; these interfaces do not supply the proposed dispatcher.
```mermaid
flowchart TD
A[Dispatcher: remaining budget] -->|zero| B[StepLimitExceeded: no fetch]
A -->|positive| C[Checked fetch and single-instruction admission]
C --> D[Execute into temporary state]
D --> E{Outcome}
E -->|ordinary fault| F[Discard temporary changes; preserve fault details]
E -->|unmasked SIMD exception| G[Commit permitted MXCSR flags only]
E -->|completed instruction| H[Commit state and permitted memory write]
H --> I[Increment retired count; decrement remaining budget]
I -->|continue| A
I -->|guest stop| J[Return guest stop and completed count]
```
## First admission profile
The first adapter is for trusted original fixtures, not a general executable
loader. Every admitted form is listed explicitly; other forms return an
unsupported result with their guest PC and bytes.
| Forms | Proposed execution route | Initial boundary |
| --- | --- | --- |
| 64-bit register ADD, INC and DEC | Remill single-instruction thunk | Explicit fixture registers; defined arithmetic flags only |
| Legacy `ADDSS xmm0, xmm1` | Exact numerical helper | Register sources only; preserve the upper 96 destination bits and all source bits |
| JNE with a direct relative target | Adapter reads committed ZF and chooses the checked decoded target | Count as an adapter control step; no native jump directly to another guest thunk |
| HLT | Adapter guest stop | Completes one instruction and advances RIP, matching the existing synthetic CPU policy |
| 64-bit MOV through RBX and RET | Checked adapter memory/transfer operations in a later increment | One eight-byte span; authenticated fixture return sentinel; no general services or arbitrary host calls |
Using the numerical helper or explicit control adapter is visible routing,
not additional Remill-native instruction coverage. Preserve separate attempted
and retired counters for Remill thunks, numerical helpers and adapter controls.
There is no generic interpreter fallback and no implicit no-op.
VEX/EVEX, packed floating point, x87 operations, atomics, REP/string operations,
guest services and concurrent guest execution remain outside this profile. The
earlier vector probes remain separate research fixtures; their passing results
do not admit them into this adapter or establish production AVX state support.
## Numerical helper and state commit
The existing public Rust numerical surface is `softfloat::arithmetic`, using
`Arithmetic::Add`, `F32`, `Control::from_mxcsr` and `Outcome { bits, flags }`.
The private `x86_float::Raised::commit` cannot be called from the experiment.
The adapter must implement and independently test its exception-commit contract;
making private production handlers public is outside this work's scope.
The **proposed** helper ABI accepts two raw binary32 bit patterns and a guest
MXCSR value, and returns result bits, newly raised exception bits, the resulting
MXCSR and a normal/exception status through trusted host-owned storage. These are
new adapter fields, not existing Remill APIs. The proposed `AddssResultV1` has
four consecutive `uint32_t` fields: `result_bits`, `new_flags`, `mxcsr_after` and
`outcome`, with size 16 and alignment 4. `outcome` is 0 for completion or 4 for
SIMD exception; `result_bits` is consumed only on completion. A trusted wrapper
checks an explicit output-buffer size before writing, and distinguishes an ABI
error from a guest exception. These names and layouts are design proposals, not
functions already supplied by Remill or BetterXen.
Do not expose a Rust enum or cast either CPU structure across the C boundary.
No host float argument, floating-point return, `fesetround`, host FPCR change or
host exception flag is involved.
For each admitted ADDSS:
1. Snapshot the destination, source and guest MXCSR. The current guest instruction
PC remains authoritative until the instruction completes.
2. Ask the exact helper to compute the low lane and newly raised flags. The
high 96 destination bits, every source bit and integer flags are unchanged.
3. Decode exception masks from MXCSR bits 7–12. Newly raised pre-computation
exceptions are considered before post-computation exceptions. An old sticky
flag by itself must not cause a new trap.
4. If an unmasked pre-computation exception exists, commit the applicable new
pre-computation flags to MXCSR and return `SimdException`. Otherwise OR the
newly raised flags into MXCSR, and return `SimdException` if one is unmasked.
Preserve existing sticky flags and all MXCSR control bits.
5. On an exception, leave the entire destination, source, integer flags, memory
and RIP unchanged. MXCSR's permitted exception flags are the sole change.
The faulting instruction does not increment the completed-instruction count.
6. Otherwise merge the computed low lane, advance RIP and retire one instruction.
This describes the intended compatibility contract for the first scalar form.
Packed-lane exception priority needs its own specification before packed forms
are admitted. Nonzero reserved bits in an externally seeded initial MXCSR are
an admission error, not a fabricated ADDSS exception. LDMXCSR is not admitted by
this initial helper profile.
Intercept the identified ADDSS **before** general semantic lifting/optimization.
Emit its helper call and checked status branches as an instruction operation.
Do not globally replace every LLVM `fadd`, infer x86 semantics from optimized
floating-point IR, or let a helper exception continue into a destination write.
Do not mark the helper pure or speculate it across an instruction boundary.
Expected outputs must remain independent. Reusing `softfloat` means agreement
between this route and the current CPU engines is a consistency check, not a
second numerical oracle. Keep the nine literal ADDSS cases and independently
derived fraction/manual cases as the acceptance expectations. Never generate
those expectations by calling this helper or reading its actual output.
## Budget, state and memory protocol
The **proposed** per-step result distinguishes completion, completion with guest
stop, unsupported form, ordinary fault and SIMD exception. It carries the current
PC, successor PC when applicable, and typed fault information. The proposed
`StepResultV1` layout is:
| Offset | Field | C type | Meaning |
| ---: | --- | --- | --- |
| 0 | abi_version | uint32_t | Exactly 1 |
| 4 | outcome | uint32_t | 0 complete, 1 completed guest stop, 2 ordinary fault, 3 unsupported, 4 SIMD exception, 5 host failure |
| 8 | instruction_pc | uint64_t | Guest PC admitted for this step |
| 16 | successor_pc | uint64_t | Valid only for outcomes 0 and 1 |
| 24 | detail | uint32_t | Outcome-specific tag; guest stop 1 is HLT; fault 1 is unmapped, 2 protection, 3 general protection |
| 28 | access | uint32_t | 0 none, 1 read, 2 write, 3 execute |
| 32 | fault_address | uint64_t | Valid only for a memory/fetch fault carrying an address; never a fabricated CR2 value for a general-protection fault |
| 40 | access_width | uint32_t | Requested byte width for the reported memory operation; otherwise zero |
| 44 | mxcsr_after | uint32_t | Guest MXCSR following the permitted commit rule |
Size is 48 bytes, alignment 8. Future implementation must assert every offset
and size independently in Rust and C++. All fields are initialized on every
return, but callers must branch on `outcome` and `detail` before consuming
conditional fields. A trusted entry takes an opaque adapter-context handle,
requested ABI version, output pointer and explicit output size; it rejects a wrong size/version without
writing beyond that buffer. Contexts are created and destroyed by their owner,
are not reentrant, and are never guest addresses. Temporary Remill state remains
C++-owned, canonical CPU/memory state remains Rust-owned, and conversions use
explicit fields. No whole-state structure is passed by value across the ABI.
Host failure is an experiment failure, not a guest trap or success. Unmapped,
permission, execute-fetch and canonical-address/general-protection failures stay
distinct; unsupported decode/lifting details retain the actual bytes in the host
diagnostic record. An execute-fetch fault uses `access = 3` and retains its
unmapped/protection detail. Unsupported details are 1 for an unadmitted form,
2 for decode disagreement and 3 for an unadmitted transfer. Host-failure details
are 1 for ABI mismatch, 2 for lifting/verification failure, 3 for state conversion
failure and 4 for an internal memory error. Unrecognized tags fail as host errors.
This is an experiment ABI proposal, not a stable production interface.
Budget behavior follows the existing interpreter's public `ExecutionResult`:
- Check remaining budget before fetch, decoding, compilation or operand access.
A zero budget returns `StepLimitExceeded`, count zero and unchanged state even
when the current PC is unmapped.
- Fetch only bytes required for the current instruction through execute-checked
guest memory. Do not read a speculative fifteen-byte span or decode the next
instruction just because it shares a trace. An earlier data fault must win
over an unsupported or inaccessible following instruction.
- Reserve a step without retiring it. Execute into temporary state; retire only
after its permitted effects commit. Decode failures, operand faults, unsupported
forms and unmasked SIMD exceptions do not retire an instruction. A completed
HLT does. Do not underflow remaining budget or wrap the retired counter.
- Every taken or untaken branch returns to dispatch. There is no direct thunk
recursion or native backedge bypassing the budget check. Returning to the same
PC still requires another budget admission.
- At exhaustion, RIP names the next instruction that would execute. A later call
with a fresh budget resumes from that exact state and never replays a completed
store or instruction. This is the exact-budget API, not the current scheduler's
separately documented block-boundary slicing behavior.
Canonical CPU state remains owned by the dispatcher. A temporary Remill state
requires explicit conversion of each admitted register, arithmetic flag, RIP,
XMM and MXCSR field; never `memcpy` a Rust `CpuState` into a Remill `State`.
Validate the pinned Remill structure sizes and offsets at build time. Modelled
state outside the initial profile must be initialized and preserved under an
explicit admission rule, not silently discarded. Live YMM/AVX state integration
waits for the contract in #299.
Memory faults need more than the current experiment's boolean read/write result.
Carry operation kind, guest address, width and the actual memory/protection fault
back to the dispatcher. GuestMemory's mapping checks do not replace architectural
canonical-address and alignment checks. Ordinary faults must preserve all guest
state, including flags; earlier completed instructions remain committed.
For the first eight-byte store form, validate the whole span and retain one
pending write until instruction commit. No other form with multiple writes is
admitted. End validation and commit on the same single-threaded memory owner;
do not allow a callback to remap the span between them. The initial RET subset
reads through checked memory and admits only the authenticated fixture return
sentinel. Other transfers are explicitly unsupported by this profile. Do not
infer a general x86 RET policy from that restriction: a future admitted guest
return retires before an instruction-fetch fault at its successor, whose execute
check belongs to the next dispatcher turn.
Do not unwind a C++ exception or longjmp across a Rust frame or assume LLVM
`nounwind` code can carry a foreign exception. The current harness escape is not
the new protocol. Checked operations return explicit status, and generated IR
branches to the fault exit **before** any consumer uses an invalid result. There
is no zero/dummy read value followed by continued guest execution. A lifting or
verification failure stops compilation; it is not a guest success.
Initially compile fixed fixture instructions ahead of time; no general cache is
admitted. Keep guest code read/execute-only and reject self-modification in this
profile. Any later reusable cache must respect executable-generation and address-
space identity checks, checked fetch on revalidation, and in-flight code lifetime.
That integration requires the production CPU owner's review.
## Regression and review gates
These are **planned tests**, not results of this design task.
| Gate | Required observation |
| --- | --- |
| Existing numerical failures | All nine ADDSS cases retain their original bit/MXCSR/exit expectations; all destination/source preservation checks remain |
| Sticky flag handling | An exact operation with pre-existing PE set completes without a new precision trap; unrelated MXCSR bits remain unchanged |
| Fault atomicity | Invalid memory or an unmasked SIMD exception preserves destination and current RIP; only explicitly permitted MXCSR flags may change |
| No speculative execution | A faulting MOV followed by UD2 or an inaccessible instruction reports the MOV fault first |
| Zero budget | No instruction fetch or state/memory change, including an unmapped initial PC |
| Exact boundary | `inc rax; inc rax; hlt`, initially RAX 5 at `0x1000`: budgets 0/1/2/3 yield RAX 5/6/7/7, RIP `1000/1003/1006/1007`, counts 0/1/2/3; only budget 3 yields Halt |
| Resume | Running that program with budgets 1, then 1, then 1 matches one budget-3 run, including flags, memory and terminal status |
| Fault after progress | An instruction fault after two completions reports count two and leaves earlier effects intact; retry never double-retires them |
| Loops | Counts 1/3/7 still match; count zero and larger finite counts return exact guest-budget exits without supervisor termination |
| Decode agreement | Current-instruction length/category disagreement and a fused idiom are refused explicitly; no change to production decoder coverage |
| Compiler preservation | Optimized and unoptimized adapter runs obey the same counts, side-effect order and fault PCs; IR/control-flow inspection finds no edge bypassing dispatch |
| Wrong-answer controls | Incorrect result, missing MXCSR update, missing budget check and premature store each cause their intended failure |
Run native ARM64 correctness and provenance checks on the named candidate before
comparing performance. Keep the old unadapted route as a separately labelled
baseline with its failures; do not overwrite its receipts or redefine its gates.
Retain the supervisor timeout as a containment check, reported separately from
guest budget behavior. R1 reviews provenance, claims and native execution; R2
independently derives semantic expectations and reviews fault/count behavior.
The implementer cannot promote its own work to independent acceptance.
## Implementation order and exit decision
1. Specify the versioned status/state ABI and implement exact single-instruction
dispatch for INC/DEC/JNE/HLT. Close zero-budget, boundary, resume and runaway
regressions without numerical or memory operations.
2. Add the original ADDSS bit-pattern helper and transactional register/MXCSR
commit. Close the unchanged nine-case numerical gate and sticky-flag controls.
3. Add the checked MOV/RET subset, typed memory faults and one-write commit.
Close fault precedence, mapping-boundary and preservation tests.
4. Review the admitted profile independently. Only then measure matched release
workloads on an idle native host with equivalent budget/fault guarantees,
separating helper, dispatch, compilation, memory and code-size costs.
Stay isolated if any required semantic or budget gate fails, or if the combined
adapter adds complexity without a demonstrated workload benefit. Production
adoption is a separate decision after reviewed correctness, attributable
dependencies and representative measurements. This design adds no new hardware,
execution, benchmark or compatibility claim.
## Sources
- [Extended local findings](evaluation-2.md), including the retained failure receipts.
- [Current CPU contract](../../docs/cpu/instruction-registry.md),
[CPU state/counting](../../crates/loader/src/cpu.rs),
[exact numerical implementation](../../crates/loader/src/softfloat.rs), and
[current numerical commit behavior](../../crates/loader/src/x86_float.rs).
- [Pinned Remill instruction lifter](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/include/remill/BC/InstructionLifter.h),
[decoder interface and idiom warning](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/include/remill/Arch/Arch.h),
[instruction metadata](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/include/remill/Arch/Instruction.h), and
[CLI optimization order](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/bin/lift/Lift.cpp).
- [Intel SDM Volume 1](https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf),
sections 10.2.3 and 11.5; Volume 2 instruction entries for each admitted form.
Architectural expectations and project budget policy are separate contracts.
+106
View File
@@ -0,0 +1,106 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "betterxen-remill-experiment"
version = "0.0.0"
dependencies = [
"xenora-loader",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "xenora-loader"
version = "0.1.0"
dependencies = [
"libc",
"sha2",
"xenora-texture",
]
[[package]]
name = "xenora-texture"
version = "0.1.0"
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "betterxen-remill-experiment"
version = "0.0.0"
edition = "2024"
license = "GPL-3.0-or-later"
publish = false
[workspace]
[lib]
crate-type = ["staticlib"]
[dependencies]
xenora-loader = { path = "../../../crates/loader" }
[profile.release]
lto = "fat"
codegen-units = 1
+331
View File
@@ -0,0 +1,331 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Trusted experiment-only C ABI; never accepts an untrusted host pointer.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
#[repr(C)]
pub struct ResultState {
rax: u64,
rsp: u64,
rip: u64,
flags: u64,
data: u64,
data_hi: u64,
read_only: u64,
exit: u64,
}
#[unsafe(no_mangle)]
pub extern "C" fn bx_memory_new() -> *mut GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region(0x2000, 16, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region_with_data(
0x3000,
16,
MemoryPermissions::READ_WRITE,
&0x4000u64.to_le_bytes(),
)
.unwrap();
memory
.map_region_with_data(0x6000, 16, MemoryPermissions::READ_ONLY, &[0xa5; 16])
.unwrap();
Box::into_raw(Box::new(memory))
}
/// # Safety
/// `memory` must be a live pointer returned by bx_memory_new, freed once.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_memory_free(memory: *mut GuestMemory) {
unsafe {
drop(Box::from_raw(memory));
}
}
/// # Safety
/// Pointers must reference a live memory object and an eight-byte output cell.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_read(memory: *const GuestMemory, address: u64, value: *mut u64) -> u8 {
match unsafe { &*memory }.read_u64(address) {
Ok(result) => {
unsafe {
*value = result;
}
1
}
Err(_) => 0,
}
}
/// # Safety
/// `memory` must exclusively reference a live bx_memory_new allocation.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_write(memory: *mut GuestMemory, address: u64, value: u64) -> u8 {
u8::from(unsafe { &mut *memory }.write_u64(address, value).is_ok())
}
/// # Safety
/// The byte span and output pointer must be valid for this call. Engine is 0 or 1.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_run(
engine: u32,
code: *const u8,
len: usize,
a: u64,
b: u64,
address: u64,
output: *mut ResultState,
) -> u8 {
let code = unsafe { std::slice::from_raw_parts(code, len) };
let raw = bx_memory_new();
let memory = unsafe { &mut *raw };
memory
.map_region_with_data(0x1000, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region_with_data(0x4000, 1, MemoryPermissions::READ_EXECUTE, &[0xf4])
.unwrap();
let mut cpu = CpuState::new(0x1000, 0x3000);
cpu.set(Register::Rax, a);
cpu.set(Register::Rcx, b);
cpu.set(Register::Rbx, address);
let result = match engine {
0 => Interpreter::new(cpu, memory, 32).run(),
1 => match DbtEngine::new(1024 * 1024) {
Ok(mut dbt) => dbt.run(&mut cpu, memory, 32),
Err(_) => {
unsafe {
bx_memory_free(raw);
}
return 0;
}
},
_ => {
unsafe {
bx_memory_free(raw);
}
return 0;
}
};
let state = result.final_state;
let flags = state.flags;
let exit = match result.exit_reason {
ExitReason::Halt => 0,
ExitReason::MemoryFault(_) => 1,
ExitReason::StepLimitExceeded => 4,
_ => 2,
};
unsafe {
*output = ResultState {
rax: state.get(Register::Rax),
rsp: state.get(Register::Rsp),
rip: state.rip,
flags: u64::from(flags.cf)
| u64::from(flags.pf) << 2
| u64::from(flags.af) << 4
| u64::from(flags.zf) << 6
| u64::from(flags.sf) << 7
| u64::from(flags.of) << 11,
data: memory.read_u64(0x2000).unwrap(),
data_hi: memory.read_u64(0x2008).unwrap(),
read_only: memory.read_u64(0x6000).unwrap(),
exit,
};
bx_memory_free(raw);
}
1
}
#[repr(C)]
pub struct SimdResult {
xmm0: [u64; 2],
xmm1: [u64; 2],
mxcsr: u64,
exit: u64,
}
/// # Safety
/// All pointers refer to trusted harness storage with the indicated lengths.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_simd_run(
engine: u32,
code: *const u8,
len: usize,
inputs: *const u64,
mxcsr: u32,
output: *mut SimdResult,
) -> u8 {
let code = unsafe { std::slice::from_raw_parts(code, len) };
let inputs = unsafe { std::slice::from_raw_parts(inputs, 4) };
let raw = bx_memory_new();
let memory = unsafe { &mut *raw };
memory
.map_region_with_data(0x1000, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region_with_data(0x4000, 1, MemoryPermissions::READ_EXECUTE, &[0xf4])
.unwrap();
let mut cpu = CpuState::new(0x1000, 0x3000);
cpu.xmm[0] = u128::from(inputs[0]) | u128::from(inputs[1]) << 64;
cpu.xmm[1] = u128::from(inputs[2]) | u128::from(inputs[3]) << 64;
cpu.mxcsr.0 = mxcsr;
let result = match engine {
0 => Interpreter::new(cpu, memory, 32).run(),
1 => match DbtEngine::new(1024 * 1024) {
Ok(mut dbt) => dbt.run(&mut cpu, memory, 32),
Err(_) => {
unsafe {
bx_memory_free(raw);
}
return 0;
}
},
_ => {
unsafe {
bx_memory_free(raw);
}
return 0;
}
};
let state = result.final_state;
unsafe {
*output = SimdResult {
xmm0: [state.xmm[0] as u64, (state.xmm[0] >> 64) as u64],
xmm1: [state.xmm[1] as u64, (state.xmm[1] >> 64) as u64],
mxcsr: u64::from(state.mxcsr.0),
exit: match result.exit_reason {
ExitReason::Halt => 0,
ExitReason::MemoryFault(_) => 1,
ExitReason::SimdException => 3,
ExitReason::IllegalInstruction(_) => 5,
_ => 2,
},
};
bx_memory_free(raw);
}
1
}
pub struct Bench {
memory: GuestMemory,
dbt: Option<DbtEngine>,
engine: u32,
}
#[repr(C)]
#[derive(Default)]
pub struct BenchResult {
ns: u64,
compiled: u64,
cache_hits: u64,
fallbacks: u64,
native_bytes: u64,
}
/// # Safety
/// The code span is valid trusted straight-line fixture code, ending with RET.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_bench_new(engine: u32, code: *const u8, len: usize) -> *mut Bench {
if engine > 2 {
return std::ptr::null_mut();
}
let mut memory = unsafe { *Box::from_raw(bx_memory_new()) };
let code = unsafe { std::slice::from_raw_parts(code, len) };
memory
.map_region_with_data(0x1000, len, MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region_with_data(0x4000, 1, MemoryPermissions::READ_EXECUTE, &[0xf4])
.unwrap();
let dbt = if engine == 1 {
match DbtEngine::new(1024 * 1024) {
Ok(dbt) => Some(dbt),
Err(_) => return std::ptr::null_mut(),
}
} else {
None
};
Box::into_raw(Box::new(Bench {
memory,
dbt,
engine,
}))
}
/// # Safety
/// Bench is a live exclusive allocation returned by bx_bench_new; output is valid.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_bench_run(
bench: *mut Bench,
repetitions: u32,
output: *mut BenchResult,
) -> u8 {
let bench = unsafe { &mut *bench };
if repetitions == 0 || repetitions > 10_000 {
return 0;
}
let mut stats = BenchResult::default();
let before = bench
.dbt
.as_ref()
.map(|dbt| dbt.metrics)
.unwrap_or_default();
let start = std::time::Instant::now();
for _ in 0..repetitions {
bench.memory.write_u64(0x2000, 0).unwrap();
let mut cpu = CpuState::new(0x1000, 0x3000);
cpu.set(Register::Rax, 1);
cpu.set(Register::Rcx, 1);
cpu.set(Register::Rbx, 0x2000);
let result = if let Some(dbt) = &mut bench.dbt {
dbt.run(&mut cpu, &mut bench.memory, 1024)
} else if bench.engine == 0 {
Interpreter::new(cpu, &mut bench.memory, 1024).run()
} else {
let Ok(mut dbt) = DbtEngine::new(1024 * 1024) else {
return 0;
};
let result = dbt.run(&mut cpu, &mut bench.memory, 1024);
stats.compiled += dbt.metrics.blocks_compiled as u64;
stats.cache_hits += dbt.metrics.cache_hits as u64;
stats.fallbacks += dbt.metrics.interpreter_fallbacks as u64;
stats.native_bytes += dbt.metrics.native_bytes_emitted as u64;
result
};
let state = result.final_state;
if result.exit_reason != ExitReason::Halt
|| state.get(Register::Rax) != 257
|| state.get(Register::Rsp) != 0x3008
|| state.flags != Default::default()
|| bench.memory.read_u64(0x2000).unwrap() != 257
|| bench.memory.read_u64(0x2008).unwrap() != 0
|| bench.memory.read_u64(0x6000).unwrap() != 0xa5a5_a5a5_a5a5_a5a5
{
return 0;
}
}
stats.ns = start.elapsed().as_nanos() as u64;
if let Some(dbt) = &bench.dbt {
stats.compiled = (dbt.metrics.blocks_compiled - before.blocks_compiled) as u64;
stats.cache_hits = (dbt.metrics.cache_hits - before.cache_hits) as u64;
stats.fallbacks = (dbt.metrics.interpreter_fallbacks - before.interpreter_fallbacks) as u64;
stats.native_bytes =
(dbt.metrics.native_bytes_emitted - before.native_bytes_emitted) as u64;
}
unsafe {
*output = stats;
}
1
}
/// # Safety
/// Bench is a live allocation returned by bx_bench_new and is freed exactly once.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_bench_free(bench: *mut Bench) {
unsafe {
drop(Box::from_raw(bench));
}
}
+295
View File
@@ -0,0 +1,295 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Build/run the trusted, isolated Remill experiment; write receipts under artifacts/."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import platform
import re
import shutil
import signal
import statistics
import subprocess
import time
PIN = "66c488c9911fd9b368e4d0c9647d74239f8bba8b"
HERE = Path(__file__).resolve().parent
FIXTURES = {
"add": "4801c8488903c3", # add rax,rcx; mov [rbx],rax; ret
"load": "488b03c3", # mov rax,[rbx]; ret
"store": "488903c3", # mov [rbx],rax; ret
"ud2": "0f0b", # deliberately invalid guest instruction
"jump": "ffe0", # indirect jmp rax; unsupported by our dispatcher
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True,
help="artifact directory containing upstream/ at the pinned revision")
parser.add_argument("--llvm", type=Path, default=Path("/opt/homebrew/opt/llvm@17"))
parser.add_argument("--extended", action="store_true", help="run SIMD/control probes and matched integer measurements")
parser.add_argument("--build", action="store_true", help="configure/build dependencies and Remill first")
args = parser.parse_args()
root, llvm = args.root.resolve(), args.llvm.absolute()
if platform.system() != "Darwin" or platform.machine() != "arm64":
parser.error("this experiment requires native arm64 macOS")
# Never place generated source or receipts in a tracked directory.
root.mkdir(parents=True, exist_ok=True)
check = subprocess.run(["git", "check-ignore", str(root / "receipt.json")],
cwd=root, capture_output=True)
if check.returncode:
parser.error("--root must be inside an ignored artifacts/ directory")
host_version = platform.mac_ver()[0]
receipt = {"remill_revision": PIN, "platform": platform.platform(),
"commands": [], "native": [], "outcome": "incomplete"}
env = dict(os.environ, CMAKE_BUILD_PARALLEL_LEVEL="2", CARGO_BUILD_JOBS="2",
CARGO_TARGET_DIR=str(root / "bridge-target"))
def run(name, argv, timeout=180, cwd=root, expected_exit=0):
if args.extended:
name = "extended-" + name
argv = list(map(str, argv))
start = time.monotonic()
record = {"name": name, "argv": argv, "cwd": str(cwd)}
receipt["commands"].append(record)
try:
proc = subprocess.Popen(argv, cwd=cwd, env=env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, start_new_session=True)
try:
output, _ = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
# Bound the entire build process group, including nested Ninja jobs.
os.killpg(proc.pid, signal.SIGTERM)
try:
output, _ = proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(proc.pid, signal.SIGKILL)
output, _ = proc.communicate()
(root / (name + ".log")).write_bytes(output)
record.update(exit="timeout", seconds=time.monotonic() - start)
raise RuntimeError(f"{name} exceeded {timeout} seconds")
(root / (name + ".log")).write_bytes(output)
record.update(exit=proc.returncode, seconds=time.monotonic() - start)
record["expected_exit"] = expected_exit
if proc.returncode != expected_exit:
raise RuntimeError(f"{name} failed ({proc.returncode}); see {root / (name + '.log')}")
return output.decode(errors="replace")
except OSError:
record.update(exit="could not execute", seconds=time.monotonic() - start)
raise
audited = set()
def audit(path):
path = Path(path).resolve()
if path in audited:
return
audited.add(path)
name = "native-" + hashlib.sha256(str(path).encode()).hexdigest()[:12]
description = run(name + "-file", ["/usr/bin/file", path])
archs = run(name + "-archs", ["/usr/bin/lipo", "-archs", path]).strip()
if not any(a.startswith("arm64") for a in archs.split()):
raise RuntimeError(f"refusing non-ARM64 native input: {path}")
item = {"path": str(path), "archs": archs, "file": description.strip()}
receipt["native"].append(item)
# Archives have no dynamic load commands. Check their ARM64 slice above.
if path.suffix == ".a":
return
links = run(name + "-links", ["/usr/bin/otool", "-L", path])
commands = run(name + "-load", ["/usr/bin/otool", "-l", path])
rpaths = re.findall(r"cmd LC_RPATH\s+cmdsize \d+\s+path (.*?) \(offset", commands)
def expand(value):
return value.replace("@loader_path", str(path.parent)).replace("@executable_path", str(path.parent))
dependencies = []
for line in links.splitlines()[1:]:
if " (compatibility version" not in line:
continue
lib = line.strip().split(" (compatibility")[0]
if lib.startswith(("/usr/lib/", "/System/Library/")):
dependencies.append({"install_name": lib, "system_shared_cache": True})
continue
candidates = [Path(expand(lib))]
if lib.startswith("@rpath/"):
candidates = [Path(expand(r)) / lib[7:] for r in rpaths]
candidates += [llvm / "lib" / lib[7:]]
resolved = next((p for p in candidates if p.exists()), None)
if resolved is None:
raise RuntimeError(f"unresolved native dependency: {path}: {lib}")
dependencies.append({"install_name": lib, "resolved": str(resolved.resolve())})
audit(resolved)
item["dependencies"] = dependencies
try:
upstream = root / "upstream"
revision = run("upstream-revision", ["git", "rev-parse", "HEAD"], cwd=upstream).strip()
if revision != PIN or run("upstream-status", ["git", "status", "--porcelain"], cwd=upstream).strip():
raise RuntimeError("upstream must be clean and match PIN")
receipt["project_revision"] = run("project-revision", ["git", "rev-parse", "HEAD"], cwd=HERE).strip()
receipt["fixture_bytes"] = FIXTURES
receipt["source_sha256"] = {str(p.relative_to(HERE)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in [Path(__file__), HERE / "prototype.cpp", HERE / "bridge/src/lib.rs", HERE / "bridge/Cargo.lock"]}
for tool in ["cmake", "ninja", "git", "make", "rustup"]:
audit(shutil.which(tool))
for tool in ["clang", "clang++", "llvm-ar", "llvm-link", "llc", "opt", "llvm-mc", "llvm-nm", "llvm-objcopy", "llvm-objdump"]:
audit(llvm / "bin" / tool)
# Check real toolchain executables, not only the rustup proxy.
for tool in ["cargo", "rustc"]:
path = run("which-" + tool, ["rustup", "which", "--toolchain", "1.100.0", tool]).strip()
audit(path)
audit(shutil.which("python3"))
if args.build:
common = [f"-DCMAKE_C_COMPILER={llvm}/bin/clang",
f"-DCMAKE_CXX_COMPILER={llvm}/bin/clang++", "-DCMAKE_OSX_ARCHITECTURES=arm64"]
run("deps-configure", ["cmake", "-G", "Ninja", "-S", upstream / "dependencies", "-B", root / "deps-build",
"-DUSE_EXTERNAL_LLVM=ON", "-DENABLE_SLEIGH=ON", f"-DCMAKE_PREFIX_PATH={llvm}",
f"-DCMAKE_INSTALL_PREFIX={root}/deps-install", *common])
run("deps-build", ["cmake", "--build", root / "deps-build", "--parallel", "2"], timeout=1800)
run("remill-configure", ["cmake", "-G", "Ninja", "-S", upstream, "-B", root / "remill-build",
f"-DCMAKE_PREFIX_PATH={root}/deps-install;{llvm}",
f"-DCMAKE_INSTALL_PREFIX={root}/remill-install", "-DCMAKE_BUILD_TYPE=Release",
"-DREMILL_FETCH_SLEIGH=OFF", "-DREMILL_ENABLE_TESTING=OFF", *common])
run("remill-build", ["cmake", "--build", root / "remill-build", "--parallel", "2"], timeout=1800)
dependency_sources = {
"gflags": ("gflags-prefix/src/gflags", "52e94563eba1968783864942fedf6e87e3c611f4"),
"glog": ("glog-prefix/src/glog", "7b134a5c82c0c0b5698bb6bf7a835b230c5638e4"),
"googletest": ("googletest-prefix/src/googletest", "52eb8108c5bdec04579160ae17225d66034bd723"),
"xed": ("xed-prefix/src/xed", "dc6bdbe036515c7ef55d3b2d50bafc5232bfe534"),
"mbuild": ("xed-prefix/src/mbuild", "7c4497f41f576b43a80bb0f8d8452bbcfd58b6e2"),
"sleigh": ("sleigh-prefix/src/sleigh", "7c6b7424467d0382a1303c278633e99b0d094d5b"),
}
receipt["dependency_revisions"] = {}
for name, (relative, expected) in dependency_sources.items():
path = root / "deps-build" / relative
actual = run("revision-" + name, ["git", "rev-parse", "HEAD"], cwd=path).strip()
if actual != expected:
raise RuntimeError(f"dependency revision mismatch: {name}: {actual}")
receipt["dependency_revisions"][name] = actual
ghidra = root / "deps-build/sleigh-prefix/src/sleigh-build/_deps/ghidrasource-src"
base = "80ccdadeba79cd42fb0b85796b55952e0f79f323"
run("ghidra-base", ["git", "merge-base", "--is-ancestor", base, "HEAD"], cwd=ghidra)
receipt["dependency_revisions"]["ghidra_base"] = base
receipt["ghidra_patch_commits"] = run("ghidra-patches", ["git", "log", "--format=%H %s", base + "..HEAD"], cwd=ghidra)
receipt["upstream_patch_sha256"] = {str(p.relative_to(upstream)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in (upstream / "dependencies/sleigh_patches").glob("*.patch")}
cache = (root / "deps-build/CMakeCache.txt").read_text()
python_path = re.search(r"^_Python3_EXECUTABLE:INTERNAL=(.+)$", cache, re.MULTILINE)
if python_path:
audit(python_path.group(1))
run("remill-install", ["cmake", "--install", root / "remill-build"])
lifter = root / "remill-install/bin/remill-lift-17"
audit(lifter)
for binary in (root / "deps-install/bin").iterdir():
if binary.is_file() and binary.open("rb").read(4) in (b"\xcf\xfa\xed\xfe", b"\xca\xfe\xba\xbe"):
audit(binary)
for archive in (root / "deps-install/lib").glob("*.a"):
audit(archive)
release = ["--release"] if args.extended else []
run("bridge-build", ["cargo", "+1.100.0", "build", *release, "--locked", "--manifest-path", HERE / "bridge/Cargo.toml",
"--target", "aarch64-apple-darwin"], timeout=300, cwd=HERE)
profile = "release" if args.extended else "debug"
bridge = root / f"bridge-target/aarch64-apple-darwin/{profile}/libbetterxen_remill_experiment.a"
audit(bridge)
fixtures = dict(FIXTURES)
if args.extended:
fixtures.update(addss="f30f58c1c3", paddd="660ffec1c3", vpaddd="c5fdfec1c3", vpxor="c5f9efc0c3",
loop="48ffc048ffc975f8488903c3", register256="4801c8" * 256 + "488903c3",
memory256="4801c8488903" * 256 + "c3")
run("fixture-assemble", [llvm / "bin/llvm-mc", "-triple=x86_64-unknown-linux-gnu", "-filetype=obj",
HERE / "fixtures.s", "-o", root / "extended-fixtures.o"])
run("fixture-extract", [llvm / "bin/llvm-objcopy", "--only-section=.text", "-O", "binary",
root / "extended-fixtures.o", root / "extended-fixtures.bin"])
symbols = run("fixture-symbols", [llvm / "bin/llvm-nm", "--numeric-sort", "--defined-only", root / "extended-fixtures.o"])
offsets = [(int(line.split()[0], 16), line.split()[-1]) for line in symbols.splitlines()]
raw = (root / "extended-fixtures.bin").read_bytes()
aliases = {"bench_register": "register256", "bench_memory": "memory256"}
for index, (offset, symbol) in enumerate(offsets):
name = aliases.get(symbol, symbol.removesuffix("_probe"))
end = offsets[index+1][0] if index+1 < len(offsets) else len(raw)
if raw[offset:end].hex() != fixtures[name]:
raise RuntimeError(f"original fixture assembler mismatch: {name}")
receipt["source_sha256"].update({name: hashlib.sha256((HERE / name).read_bytes()).hexdigest()
for name in ["probes.cpp", "fixtures.s", "bridge/Cargo.toml"]})
receipt["fixture_bytes"] = fixtures
objects = []
for name, code in fixtures.items():
ir = root / (name + ".ll")
run("lift-" + name, [lifter, "--arch", "amd64_avx" if name in {"addss", "paddd", "vpaddd", "vpxor"} else "amd64", "--os", "linux", "--address", "4096",
"--bytes", code, "--ir_out", ir])
source = ir.read_text()
if "@sub_1000(" not in source:
raise RuntimeError("entry symbol missing from lifted output")
# Preserve the lifted body. Override only the entry name and host codegen attributes.
# Guest x86 target-features must not be handed to the ARM64 backend.
source = source.replace("@sub_1000(", "@lifted_" + name + "(")
source = re.sub(r' "target-(?:cpu|features|tune-cpu)"="[^"]*"', "", source)
native_ir = root / (name + "-arm64.ll")
native_ir.write_text(source)
obj = root / (name + ".o")
run("lower-" + name, [llvm / "bin/llc", f"-mtriple=arm64-apple-macosx{host_version}", "-filetype=obj", "-O2", native_ir, "-o", obj])
audit(obj)
if args.extended and name in {"register256", "memory256"}:
sections = run("sections-" + name, [llvm / "bin/llvm-objdump", "--section-headers", obj])
match = re.search(r"^\s*\d+ __text\s+([0-9a-fA-F]+)\s", sections, re.MULTILINE)
if not match:
raise RuntimeError("native text section missing")
receipt.setdefault("remill_text_bytes", {})[name] = int(match.group(1), 16)
objects.append(obj)
executable = root / ("prototype-extended" if args.extended else "prototype")
run("prototype-link", [llvm / "bin/clang++", "-std=c++17", "-O2", f"-mmacosx-version-min={host_version}", "-Wall", "-Wextra", "-Werror", "-arch", "arm64", "-DADDRESS_SIZE_BITS=64",
f"-DHAS_FEATURE_AVX={int(args.extended)}", "-DHAS_FEATURE_AVX512=0", "-I", upstream / "include",
HERE / ("probes.cpp" if args.extended else "prototype.cpp"), *objects, bridge, "-framework", "Security", "-framework", "CoreFoundation",
"-liconv", "-lresolv", "-o", executable])
audit(executable)
semantic_error = None
try:
output = run("prototype-run", [executable], timeout=30)
except RuntimeError as error:
if not args.extended:
raise
semantic_error = str(error)
output = (root / "extended-prototype-run.log").read_text()
if args.extended:
# Integer measurements have their own per-run correctness gate. A failed SIMD
# contract remains a failed gate even if these separate measurements succeed.
receipt["measurement_limits"] = "Exploratory active-desktop run; not an idle-machine benchmark. Includes reset/check/return glue."
measurements = run("benchmark", [executable, "--benchmark"], timeout=120)
receipt["measurements"] = [json.loads(line) for line in measurements.splitlines()]
receipt["measurement_summary"] = {}
for workload in ["register256", "memory256"]:
receipt["measurement_summary"][workload] = {}
for engine in range(4):
rows = [r for r in receipt["measurements"] if r["kind"] == "sample" and r["workload"] == workload and r["engine"] == engine]
if len(rows) != 9:
raise RuntimeError("incomplete timing sample set")
values = [r["ns"] / r["repetitions"] / 1000 for r in rows]
receipt["measurement_summary"][workload][engine] = {"median_us": statistics.median(values), "min_us": min(values), "max_us": max(values)}
try:
run("runaway-budget", [executable, "--runaway"], timeout=1)
receipt["runaway_budget"] = "returned; inspect exit/log"
except RuntimeError as error:
receipt["runaway_budget"] = str(error)
semantic_error = (semantic_error + "; " if semantic_error else "") + str(error)
receipt["semantic_observations"] = [json.loads(line) for line in output.splitlines() if line.startswith("{")]
run("wrong-answer-control", [executable, "--wrong-answer"], timeout=30, expected_exit=1)
receipt["outcome"] = "local prototype passed; independent acceptance pending"
receipt["output"] = output.strip()
receipt["executable_sha256"] = hashlib.sha256(executable.read_bytes()).hexdigest()
print(output, end="")
if semantic_error:
raise RuntimeError(semantic_error)
except Exception as error:
receipt["outcome"] = "failed"
receipt["error"] = str(error)
raise
finally:
(root / ("receipt-extended.json" if args.extended else "receipt.json")).write_text(json.dumps(receipt, indent=2) + "\n")
if __name__ == "__main__":
main()
+154
View File
@@ -0,0 +1,154 @@
# Extended Remill evaluation
**Decision: retain BetterXen's current CPU path. The tested Remill adapter fails
floating-point and instruction-budget requirements needed before adoption.**
This is a local research result from November 25, 2026, not independent acceptance
or a verdict on every possible Remill integration. The original native prototype
remains usable; its 32 checks also passed inside this extended run.
## Candidate and evidence
- BetterXen worktree: `b2654e93a42e74e29570183da1f31bb8cdc6f721`, with local files
restricted to the experiment, documentation index and changelog.
- Remill: `66c488c9911fd9b368e4d0c9647d74239f8bba8b`, unchanged upstream source.
- Apple M4, native ARM64, macOS 27.0 (26A428), LLVM/Clang 17.0.6 and Rust 1.100.0.
- Native tool/object/archive/linkage receipts cover 59 inputs. Guest x86-64
ELF objects are assembler data and were never executed as host binaries.
- Evidence class A applies to the observed execution on this particular host.
Expected CPU behavior is spec-derived, not compared with physical x86 or Xbox.
Independent reviewers have not accepted these results.
`fixtures.s` contains seven additional original programs. LLVM assembles them,
and the driver compares the extracted bytes against the separately declared
fixture bytes before lifting. Remill's SSE/AVX probes use `amd64_avx`; the bridge
keeps the same explicitly sized state layout. The production CPU registry,
CPUID and AVX contracts are unchanged. The related design scope remains #299.
The extended executable exits **1**, and the driver records **failed**. It does
not turn mismatches into successful tests. There are **48 additional semantic
observations, with eight mismatches**, all in the Remill floating-point route.
Explicit VEX rejection checks on the existing engines are rejection evidence,
not AVX support. The runaway-budget failure is recorded separately.
## Floating-point findings
Nine `ADDSS xmm0, xmm1` cases check binary32 result bits, preservation of the
other vector lanes and source register, guest MXCSR, and the execution exit.
Both existing BetterXen engines match all nine expectations; Remill matches the
exact `1 + 2` case and fails the other eight through this adapter.
Expected values were specified as literal constants before the lifted code ran.
The midpoint cases use `1 + 2^-24` or `-1 + -2^-24`. Positive round-up must choose
`3f800001`; negative round-down must choose `bf800001`. Inexact results set the
precision flag, and enabling denormals-are-zeros changes a subnormal input to
zero. MXCSR was initialized in Remill's `state.x87.fxsave64` model for each case.
The host rounding mode was checked as round-to-nearest.
| Case | Expected low 32 bits / MXCSR | Remill low 32 bits / MXCSR | Comparison |
| --- | --- | --- | --- |
| exact | `40400000` / `1f80` | `40400000` / `1f80` | match |
| tie-nearest | `3f800000` / `1fa0` | `3f800000` / `1f80` | mismatch |
| tie-down | `3f800000` / `3fa0` | `3f800000` / `3f80` | mismatch |
| tie-up | `3f800001` / `5fa0` | `3f800000` / `5f80` | mismatch |
| tie-zero | `3f800000` / `7fa0` | `3f800000` / `7f80` | mismatch |
| negative-down | `bf800001` / `3fa0` | `bf800000` / `3f80` | mismatch |
| denormal | `00000001` / `1f82` | `00000001` / `1f80` | mismatch |
| denormal-daz | `00000000` / `1fc0` | `00000001` / `1fc0` | mismatch |
| precision-unmasked | `3f800000` / `0fa0` | `3f800000` / `0f80` | mismatch |
The unmasked-precision case must also stop with the guest SIMD exception, leaving
the destination unchanged. BetterXen reports that exit; the Remill trace returns
normally. The sticky-flag failures matter even when result bits happen to agree.
The primary reference is [Intel SDM Volume 1, December 2024](https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf),
sections 10.2.3.1–10.2.3.4 and 11.5.2.6, plus Volume 2's ADDSS entry. The generated
`addss.ll` contains a plain LLVM `fadd` and no guest MXCSR update. That supports
the inference that this route needs additional guest floating-point modeling;
merely lowering the current lifted IR to ARM64 is insufficient. This experiment
did not test other floating-point instructions, NaNs, flush-to-zero or x87.
## Vector and execution findings
- `PADDD xmm0, xmm1` matches four independently calculated wrapping integer lanes
in all three paths, preserves the source, and leaves MXCSR unchanged.
- Remill's legacy PADD preserves the tested YMM upper half; `VPADDD ymm0, ymm0,
ymm1` matches eight lanes; VEX.128 `VPXOR xmm0, xmm0, xmm0` zeroes the tested full
YMM destination. These are three narrow Remill state checks, not AVX2 coverage.
- The existing interpreter and DBT explicitly reject both VEX fixtures without
changing the checked XMM state. No production AVX support was added.
- A backward `INC/DEC/JNE` loop terminates with the hand-derived result and flags
for counts 1, 3 and 7 in all three paths.
- For the same loop starting at count zero, both existing engines return their
32-instruction budget exit. The Remill route does not yield a guest budget
exit; the supervisor terminates its process group after one second. A process
timeout does not satisfy the guest instruction-budget contract.
## Exploratory measurements
**The desktop was active. These are diagnostic toy-workload measurements, not
an idle-machine benchmark campaign, acceptance gate G10 or a general speedup.**
The earlier exploratory receipt is retained rather than selecting a favorable
run. No production optimization was made.
Both workloads start RAX and RCX at one, execute 256 additions, store the final
value and return. `register256` stores once; `memory256` stores after every add.
The same guest bytes are used by every path. All timed repetitions check RAX
257, the stored value, six arithmetic flags, stack movement and memory sentinels.
Each path performs one untimed correctness/warmup run, then nine batches of
200 repetitions, rotating engine order between batches. Warm DBT samples assert
zero new translations and positive cache hits.
Values below are microseconds per guest invocation: median, with minimum and
maximum batch averages in parentheses. They describe the final recorded run.
| Workload | Interpreter | Warm DBT | Cold DBT | Remill AOT |
| --- | ---: | ---: | ---: | ---: |
| register256 | 4.531 (3.907–11.857) | 0.552 (0.481–0.977) | 19.482 (17.350–44.555) | 0.959 (0.824–1.774) |
| memory256 | 8.310 (8.057–14.108) | 2.716 (2.639–4.356) | 47.383 (45.075–51.644) | 1.862 (1.796–3.760) |
Cold DBT creates an engine and translates each invocation. Remill is compiled
before these samples; its lift/lower process durations are separate receipt
entries, so the cold-DBT column must not be compared as equal preparation work.
The bridge uses release mode, fat LTO and one codegen unit, matching the project's
release profile; Remill objects use LLVM `llc -O2`, and the harness uses C++ `-O2`.
The interpreter and DBT also execute a terminal sentinel HLT after RET; the Remill
harness validates the return sentinel directly.
These timings include resetting CPU state, checked-memory access and validation.
State sizes, return plumbing and per-instruction budget checks differ, and Remill
still calls predicate-annotation helpers. They are not isolated instruction
throughput or equally featured production runtimes. Background activity and
these adapter costs limit any performance conclusion. Warm DBT is faster on
this register trace; Remill is faster on this store-heavy trace in the recorded
run. There is no demonstrated overall performance winner.
Remill object text is 48,288 bytes for `register256`
and 58,488 for `memory256`; warmed DBT reports
6,396 and 38,852 emitted native bytes respectively. These are code-size counters
for different glue/dispatch strategies, not full process memory or cache-use
measurements. Full-workload memory consumption remains unmeasured.
## Reproduce and next decision
```sh
python3 experiments/remill/evaluate.py --root /path/to/ignored/artifacts/remill-evaluation --extended
```
This command currently returns nonzero because the semantic and budget gates
fail. It still records the separately correctness-gated integer measurements.
`receipt-extended.json` contains command exit statuses, source hashes, assembled
bytes, observations, raw timing samples, summaries and the executable hash.
`extended-prototype-run.log`, `extended-benchmark.log` and
`extended-runaway-budget.log` retain the actual outcomes. The first extended
receipt and the intermediate exit-mapping diagnostic receipt are also retained.
The latter exposed a harness status-mapping omission; a distinct illegal-opcode
status fixed the reporting without altering either existing CPU engine or the
rejection expectations.
Before considering production use, implement and independently review a guest
floating-point contract and instruction-budget/dispatch adapter. Preserve the
known failing inputs as regressions. Then expand the workload corpus and run
matched, idle-host performance/memory measurements with equivalent guarantees.
No engine replacement, guest API change, game execution, GPU verification or
independent sign-off follows from these results. This review branch publishes
the isolated experiment sources and reports; raw artifacts remain local.
+34
View File
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Original guest instructions. Assembled for inspection only; never a host executable.
.intel_syntax noprefix
.text
addss_probe:
addss xmm0, xmm1
ret
paddd_probe:
paddd xmm0, xmm1
ret
vpaddd_probe:
vpaddd ymm0, ymm0, ymm1
ret
vpxor_probe:
vpxor xmm0, xmm0, xmm0
ret
loop_probe:
inc rax
dec rcx
jne loop_probe
mov [rbx], rax
ret
bench_register:
.rept 256
add rax, rcx
.endr
mov [rbx], rax
ret
bench_memory:
.rept 256
add rax, rcx
mov [rbx], rax
.endr
ret
+40
View File
@@ -0,0 +1,40 @@
# Remill experiment provenance and preliminary license review
This records a local research build, not redistribution clearance. Original
BetterXen fixture/harness code is GPL-3.0-or-later. No upstream emulator source
was copied or adapted into the experiment. Remill code is compiled externally;
the harness includes its external state headers and links generated semantics.
Keep all upstream notices and source with any future redistributed derivative.
| Component | Exact source revision | Reviewed license/notice |
| --- | --- | --- |
| lifting-bits/remill | `66c488c9911fd9b368e4d0c9647d74239f8bba8b` | Apache-2.0, root `LICENSE`; file notices in `include/remill/Arch/X86/Runtime/State.h`, the included runtime headers, `lib/Arch/X86/Semantics/BINARY.cpp`, `DATAXFER.cpp`, `CALL_RET.cpp`, `MISC.cpp`, `MMX.cpp`, `LOGICAL.cpp`, and `CMakeLists.txt`. Trail of Bits copyright notices remain intact. |
| gflags/gflags | `52e94563eba1968783864942fedf6e87e3c611f4` | BSD-3-Clause, `COPYING.txt`. |
| google/glog (v0.7.1) | `7b134a5c82c0c0b5698bb6bf7a835b230c5638e4` | BSD-3-Clause, `COPYING`. |
| google/googletest (v1.17.0) | `52eb8108c5bdec04579160ae17225d66034bd723` | BSD-3-Clause, `LICENSE`; built as part of upstream's dependency superbuild. |
| intelxed/xed (v2025.06.08) | `dc6bdbe036515c7ef55d3b2d50bafc5232bfe534` | Apache-2.0, `LICENSE`. |
| intelxed/mbuild (v2024.11.04) | `7c4497f41f576b43a80bb0f8d8452bbcfd58b6e2` | Apache-2.0, `LICENSE`; build tool. |
| lifting-bits/sleigh | `7c6b7424467d0382a1303c278633e99b0d094d5b` | Apache-2.0, `LICENSE`. |
| NationalSecurityAgency/ghidra | `80ccdadeba79cd42fb0b85796b55952e0f79f323` before upstream Sleigh patches | `LICENSE` and `NOTICE`; sampled decompiler source headers carry Apache-2.0. Generated `xml.cc` also contains the FSF GPL-3.0-or-later Bison skeleton notice and its larger-work exception. Do not describe every Ghidra file as solely Apache-2.0. |
| LLVM/Clang | Homebrew LLVM 17.0.6 | Apache-2.0 WITH LLVM-exception; native external build/lifting tools. |
The Remill checkout is unchanged. Sleigh's superbuild applies its published
Ghidra patches and Remill's `dependencies/sleigh_patches/*.patch`; no experiment
patch was added to these upstream trees. The locally patched Ghidra checkout
initially ended at `9660b9036d4247eed1e572486db3ad1f839b763d`; the full driver
rebuild ended at `6a53bbfaa98fe272d12d7ba38b2e7ef96355e30f`. Patch-generated commit IDs
can depend on the build environment; the source base and patch content are the
reproducibility inputs. Git identities in the BetterXen checkout were not changed.
Apache-2.0 and BSD-3-Clause are compatible in principle with GPL-3.0-or-later;
the Bison notice must also be retained where applicable. This preliminary review
does not clear all transitive source files, generated language specifications,
system SDK terms or future binary packaging. Before adoption/distribution,
audit the actual linked files, preserve required license/copyright/NOTICE text,
record every modification and satisfy GPL corresponding-source requirements.
The bridge's locked Cargo dependencies are separate from the production lockfile;
their redistribution notices also require review for any shipped artifact.
No foreign source is vendored by this task. Machine-specific dependency revisions
are recorded in `artifacts/remill-evaluation/dependency-revisions.json`; original
licenses, notices, patches and source stay in the ignored upstream build trees.
+319
View File
@@ -0,0 +1,319 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#define REMILL_EXTENDED_PROBES
#include "prototype.cpp"
#include <array>
#include <cfenv>
#include <chrono>
#include <vector>
struct SimdResult {
uint64_t xmm0[2], xmm1[2], mxcsr, exit;
};
struct BenchResult {
uint64_t ns, compiled, cache_hits, fallbacks, native_bytes;
};
struct Bench;
extern "C" {
uint8_t bx_simd_run(uint32_t, const uint8_t *, size_t, const uint64_t *,
uint32_t, SimdResult *);
Bench *bx_bench_new(uint32_t, const uint8_t *, size_t);
uint8_t bx_bench_run(Bench *, uint32_t, BenchResult *);
void bx_bench_free(Bench *);
Memory *lifted_addss(State &, uint64_t, Memory *);
Memory *lifted_paddd(State &, uint64_t, Memory *);
Memory *lifted_vpaddd(State &, uint64_t, Memory *);
Memory *lifted_vpxor(State &, uint64_t, Memory *);
Memory *lifted_loop(State &, uint64_t, Memory *);
Memory *lifted_register256(State &, uint64_t, Memory *);
Memory *lifted_memory256(State &, uint64_t, Memory *);
// This intrinsic is a predicate annotation, just like the flag annotations.
bool __remill_compare_neq(bool value) { return value; }
}
static unsigned observations, mismatches;
static void observe(const char *name, unsigned engine, bool match,
uint64_t bits, uint64_t expected, uint64_t mxcsr,
uint64_t expected_mxcsr, uint64_t exit) {
++observations;
if (!match)
++mismatches;
std::printf(
"{\"kind\":\"semantic\",\"name\":\"%s\",\"engine\":%u,\"match\":%s,"
"\"bits\":%llu,\"expected\":%llu,\"mxcsr\":%llu,\"expected_mxcsr\":%llu,"
"\"exit\":%llu}\n",
name, engine, match ? "true" : "false", (unsigned long long)bits,
(unsigned long long)expected, (unsigned long long)mxcsr,
(unsigned long long)expected_mxcsr, (unsigned long long)exit);
}
static SimdResult remill_simd(Trace trace, const uint64_t *inputs,
uint32_t mxcsr) {
std::memset(&state, 0, sizeof(state));
std::memcpy(&state.vec[0], inputs, 16);
std::memcpy(&state.vec[1], inputs + 2, 16);
state.x87.fxsave.mxcsr.flat = mxcsr;
state.gpr.rsp.qword = 0x3000;
Memory *memory = bx_memory_new();
returned = false;
int status = setjmp(escape);
if (!status) {
trace(state, 0x1000, memory);
if (!returned)
stop(3);
}
SimdResult result{};
std::memcpy(result.xmm0, &state.vec[0], 16);
std::memcpy(result.xmm1, &state.vec[1], 16);
result.mxcsr = state.x87.fxsave.mxcsr.flat;
result.exit = status;
bx_memory_free(memory);
return result;
}
static void floating_point() {
// Literal IEEE binary32 answers, derived before executing the lifted code.
// 1 + 2^-24 is halfway between adjacent floats; PE is bit 5 of MXCSR.
struct Case {
const char *name;
uint32_t a, b, mxcsr, bits, after;
unsigned exit;
};
const Case cases[] = {
{"exact", 0x3f800000, 0x40000000, 0x1f80, 0x40400000, 0x1f80, 0},
{"tie-nearest", 0x3f800000, 0x33800000, 0x1f80, 0x3f800000, 0x1fa0, 0},
{"tie-down", 0x3f800000, 0x33800000, 0x3f80, 0x3f800000, 0x3fa0, 0},
{"tie-up", 0x3f800000, 0x33800000, 0x5f80, 0x3f800001, 0x5fa0, 0},
{"tie-zero", 0x3f800000, 0x33800000, 0x7f80, 0x3f800000, 0x7fa0, 0},
{"negative-down", 0xbf800000, 0xb3800000, 0x3f80, 0xbf800001, 0x3fa0, 0},
{"denormal", 0x00000001, 0x00000000, 0x1f80, 0x00000001, 0x1f82, 0},
{"denormal-daz", 0x00000001, 0x00000000, 0x1fc0, 0x00000000, 0x1fc0, 0},
{"precision-unmasked", 0x3f800000, 0x33800000, 0x0f80, 0x3f800000, 0x0fa0,
3},
};
const uint8_t code[] = {0xf3, 0x0f, 0x58, 0xc1, 0xc3};
for (const auto &c : cases) {
const uint64_t inputs[] = {
0x1122334400000000ULL | c.a, 0x5566778899aabbccULL,
0xaabbccdd00000000ULL | c.b, 0x0123456789abcdefULL};
for (unsigned engine = 0; engine < 3; ++engine) {
SimdResult actual{};
if (engine == 2)
actual = remill_simd(lifted_addss, inputs, c.mxcsr);
else
require(
bx_simd_run(engine, code, sizeof(code), inputs, c.mxcsr, &actual),
"SIMD baseline available");
const uint64_t expected = 0x1122334400000000ULL | c.bits;
bool match = actual.xmm0[0] == expected && actual.xmm0[1] == inputs[1] &&
actual.xmm1[0] == inputs[2] && actual.xmm1[1] == inputs[3] &&
actual.mxcsr == c.after && actual.exit == c.exit;
observe(c.name, engine, match, actual.xmm0[0], expected, actual.mxcsr,
c.after, actual.exit);
}
}
}
static void vectors() {
const uint32_t left[8] = {0xffffffff, 0x7fffffff, 10, 0x80000000, 3, 5, 7, 9};
const uint32_t right[8] = {1, 1, 20, 0x80000000, 4, 6, 8, 10};
const uint32_t expected[8] = {0, 0x80000000, 30, 0, 7, 11, 15, 19};
uint64_t inputs[4];
std::memcpy(inputs, left, 16);
std::memcpy(inputs + 2, right, 16);
const uint8_t code[] = {0x66, 0x0f, 0xfe, 0xc1, 0xc3};
for (unsigned engine = 0; engine < 3; ++engine) {
SimdResult actual{};
if (engine == 2)
actual = remill_simd(lifted_paddd, inputs, 0x1f80);
else
require(bx_simd_run(engine, code, sizeof(code), inputs, 0x1f80, &actual),
"PADD baseline available");
observe("paddd128", engine,
std::memcmp(actual.xmm0, expected, 16) == 0 &&
std::memcmp(actual.xmm1, inputs + 2, 16) == 0 &&
actual.mxcsr == 0x1f80 && actual.exit == 0,
actual.xmm0[0], uint64_t(expected[0]) | uint64_t(expected[1]) << 32,
actual.mxcsr, 0x1f80, actual.exit);
}
const uint8_t vex[2][5] = {{0xc5, 0xfd, 0xfe, 0xc1, 0xc3},
{0xc5, 0xf9, 0xef, 0xc0, 0xc3}};
for (unsigned form = 0; form < 2; ++form)
for (unsigned engine = 0; engine < 2; ++engine) {
SimdResult actual{};
require(bx_simd_run(engine, vex[form], 5, inputs, 0x1f80, &actual),
"VEX rejection baseline available");
observe("baseline-vex-rejection", engine,
actual.exit == 5 && actual.mxcsr == 0x1f80 &&
std::memcmp(actual.xmm0, inputs, 16) == 0 &&
std::memcmp(actual.xmm1, inputs + 2, 16) == 0,
actual.xmm0[0], inputs[0], actual.mxcsr, 0x1f80, actual.exit);
}
const Trace traces[] = {lifted_paddd, lifted_vpaddd, lifted_vpxor};
const char *names[] = {"legacy-upper-preserved", "vpaddd256",
"vpxor128-upper-zero"};
for (unsigned i = 0; i < 3; ++i) {
std::memset(&state, 0, sizeof(state));
std::memcpy(&state.vec[0], left, 32);
std::memcpy(&state.vec[1], right, 32);
state.gpr.rsp.qword = 0x3000;
Memory *memory = bx_memory_new();
returned = false;
int status = setjmp(escape);
if (!status) {
traces[i](state, 0x1000, memory);
if (!returned)
stop(3);
}
uint32_t result[8];
std::memcpy(result, &state.vec[0], 32);
const uint32_t zero[8] = {};
bool match = status == 0 && std::memcmp(&state.vec[1], right, 32) == 0;
if (i == 0)
match = match && std::memcmp(result, expected, 16) == 0 &&
std::memcmp(result + 4, left + 4, 16) == 0;
else
match = match && std::memcmp(result, i == 1 ? expected : zero, 32) == 0;
observe(names[i], 2, match, result[0], i == 2 ? 0 : expected[0], 0, 0,
status);
bx_memory_free(memory);
}
}
static void control_flow() {
const uint8_t code[] = {0x48, 0xff, 0xc0, 0x48, 0xff, 0xc9,
0x75, 0xf8, 0x48, 0x89, 0x03, 0xc3};
for (unsigned count : {1, 3, 7}) {
const auto actual = run(lifted_loop, 5, count, 0x2000);
observe("finite-loop", 2,
actual.exit == 0 && actual.rax == 5 + count &&
actual.data == 5 + count && actual.flags == 0x44,
actual.rax, 5 + count, 0, 0, actual.exit);
for (unsigned engine = 0; engine < 2; ++engine) {
ResultState baseline{};
require(bx_run(engine, code, sizeof(code), 5, count, 0x2000, &baseline),
"loop baseline available");
observe("finite-loop", engine,
baseline.exit == 0 && baseline.rax == 5 + count &&
baseline.data == 5 + count && baseline.flags == 0x44,
baseline.rax, 5 + count, 0, 0, baseline.exit);
}
}
for (unsigned engine = 0; engine < 2; ++engine) {
ResultState actual{};
require(bx_run(engine, code, sizeof(code), 5, 0, 0x2000, &actual),
"budget baseline available");
observe("baseline-step-budget", engine, actual.exit == 4, actual.rax, 0, 0,
0, actual.exit);
}
}
static uint64_t remill_batch(Trace trace, Memory *memory,
unsigned repetitions) {
const auto start = std::chrono::steady_clock::now();
for (unsigned i = 0; i < repetitions; ++i) {
std::memset(&state, 0, sizeof(state));
state.gpr.rax.qword = 1;
state.gpr.rcx.qword = 1;
state.gpr.rbx.qword = 0x2000;
state.gpr.rsp.qword = 0x3000;
require(bx_write(memory, 0x2000, 0), "benchmark reset");
returned = false;
int status = setjmp(escape);
if (!status)
trace(state, 0x1000, memory);
uint64_t data = 0, hi = 0, ro = 0;
require(!status && returned && state.gpr.rax.qword == 257 &&
state.gpr.rsp.qword == 0x3008 && state.aflag.cf == 0 &&
state.aflag.pf == 0 && state.aflag.af == 0 &&
state.aflag.zf == 0 && state.aflag.sf == 0 &&
state.aflag.of == 0 && bx_read(memory, 0x2000, &data) &&
data == 257 && bx_read(memory, 0x2008, &hi) && hi == 0 &&
bx_read(memory, 0x6000, &ro) && ro == 0xa5a5a5a5a5a5a5a5ULL,
"benchmark Remill correctness");
}
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - start)
.count();
}
static void benchmark() {
constexpr unsigned repetitions = 200, samples = 9;
const Trace traces[] = {lifted_register256, lifted_memory256};
const char *names[] = {"register256", "memory256"};
for (unsigned work = 0; work < 2; ++work) {
std::vector<uint8_t> code;
for (unsigned i = 0; i < 256; ++i) {
code.insert(code.end(), {0x48, 0x01, 0xc8});
if (work)
code.insert(code.end(), {0x48, 0x89, 0x03});
}
if (!work) {
code.insert(code.end(), {0x48, 0x89, 0x03});
}
code.push_back(0xc3);
Bench *benches[3];
for (unsigned engine = 0; engine < 3; ++engine) {
benches[engine] = bx_bench_new(engine, code.data(), code.size());
require(benches[engine], "benchmark context");
BenchResult warm{};
require(bx_bench_run(benches[engine], 1, &warm),
"benchmark warmup correctness");
std::printf("{\"kind\":\"warmup\",\"workload\":\"%s\",\"engine\":%u,"
"\"native_bytes\":%llu,\"compiled\":%llu}\n",
names[work], engine, (unsigned long long)warm.native_bytes,
(unsigned long long)warm.compiled);
}
Memory *memory = bx_memory_new();
remill_batch(traces[work], memory, 1);
for (unsigned sample = 0; sample < samples; ++sample)
for (unsigned turn = 0; turn < 4; ++turn) {
const unsigned engine = (sample + turn) % 4;
BenchResult result{};
if (engine == 3)
result.ns = remill_batch(traces[work], memory, repetitions);
else {
require(bx_bench_run(benches[engine], repetitions, &result),
"benchmark baseline correctness");
if (engine == 1)
require(result.compiled == 0 && result.cache_hits > 0,
"warm DBT must reuse its cache");
}
std::printf("{\"kind\":\"sample\",\"workload\":\"%s\",\"engine\":%u,"
"\"sample\":%u,\"repetitions\":%u,"
"\"ns\":%llu,\"compiled\":%llu,\"cache_hits\":%llu,"
"\"fallbacks\":%llu}\n",
names[work], engine, sample, repetitions,
(unsigned long long)result.ns,
(unsigned long long)result.compiled,
(unsigned long long)result.cache_hits,
(unsigned long long)result.fallbacks);
}
bx_memory_free(memory);
for (auto *bench : benches)
bx_bench_free(bench);
}
}
int main(int argc, char **argv) {
if (argc == 2 && std::strcmp(argv[1], "--benchmark") == 0) {
benchmark();
return 0;
}
if (argc == 2 && std::strcmp(argv[1], "--runaway") == 0) {
run(lifted_loop, 5, 0, 0x2000);
return 9;
}
if (argc == 2 && std::strcmp(argv[1], "--wrong-answer") == 0)
return integer_checks(argc, argv);
if (argc != 1)
return 64;
integer_checks(argc, argv);
require(std::fegetround() == FE_TONEAREST,
"probe requires host round-to-nearest");
floating_point();
vectors();
control_flow();
std::printf("{\"kind\":\"summary\",\"observations\":%u,\"mismatches\":%u}\n",
observations, mismatches);
return mismatches ? 1 : 0;
}
+219
View File
@@ -0,0 +1,219 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original trusted harness. Remill headers remain external, under Apache-2.0.
#include "remill/Arch/X86/Runtime/State.h"
#include <csetjmp>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
struct ResultState {
uint64_t rax, rsp, rip, flags, data, data_hi, read_only, exit;
};
extern "C" {
Memory *bx_memory_new();
void bx_memory_free(Memory *);
uint8_t bx_read(const Memory *, uint64_t, uint64_t *);
uint8_t bx_write(Memory *, uint64_t, uint64_t);
uint8_t bx_run(uint32_t, const uint8_t *, size_t, uint64_t, uint64_t, uint64_t,
ResultState *);
Memory *lifted_add(State &, uint64_t, Memory *);
Memory *lifted_load(State &, uint64_t, Memory *);
Memory *lifted_store(State &, uint64_t, Memory *);
Memory *lifted_ud2(State &, uint64_t, Memory *);
Memory *lifted_jump(State &, uint64_t, Memory *);
}
static std::jmp_buf escape;
static bool returned;
[[noreturn]] static void stop(int reason) { std::longjmp(escape, reason); }
extern "C" uint64_t __remill_read_memory_64(Memory *m, uint64_t address) {
uint64_t result;
if (!bx_read(m, address, &result))
stop(1);
return result;
}
extern "C" Memory *__remill_write_memory_64(Memory *m, uint64_t address,
uint64_t value) {
if (!bx_write(m, address, value))
stop(1);
return m;
}
extern "C" Memory *__remill_function_return(State &, uint64_t address,
Memory *m) {
if (address != 0x4000)
stop(3);
returned = true;
return m;
}
// All other transfers fail explicitly; this harness has no guest dispatcher.
extern "C" Memory *__remill_jump(State &, uint64_t, Memory *) { stop(2); }
extern "C" Memory *__remill_error(State &, uint64_t, Memory *) { stop(2); }
extern "C" Memory *__remill_missing_block(State &, uint64_t, Memory *) {
stop(2);
}
extern "C" Memory *__remill_function_call(State &, uint64_t, Memory *) {
stop(2);
}
extern "C" Memory *__remill_async_hyper_call(State &, uint64_t, Memory *) {
stop(2);
}
extern "C" Memory *__remill_sync_hyper_call(State &, Memory *, uint32_t) {
stop(2);
}
// These intrinsics annotate an already-computed predicate; they do not compute
// flags.
extern "C" bool __remill_flag_computation_zero(bool value, ...) {
return value;
}
extern "C" bool __remill_flag_computation_sign(bool value, ...) {
return value;
}
extern "C" bool __remill_flag_computation_overflow(bool value, ...) {
return value;
}
extern "C" bool __remill_flag_computation_carry(bool value, ...) {
return value;
}
using Trace = Memory *(*)(State &, uint64_t, Memory *);
static State state;
static ResultState run(Trace trace, uint64_t a, uint64_t b, uint64_t address) {
std::memset(&state, 0, sizeof(state));
state.gpr.rax.qword = a;
state.gpr.rcx.qword = b;
state.gpr.rbx.qword = address;
state.gpr.rsp.qword = 0x3000;
Memory *memory = bx_memory_new();
returned = false;
int status = setjmp(escape);
if (!status) {
trace(state, 0x1000, memory);
if (!returned)
stop(3);
}
uint64_t data = 0, data_hi = 0, read_only = 0;
if (!bx_read(memory, 0x2000, &data) || !bx_read(memory, 0x2008, &data_hi) ||
!bx_read(memory, 0x6000, &read_only))
std::abort();
const auto &f = state.aflag;
ResultState result{state.gpr.rax.qword,
state.gpr.rsp.qword,
state.gpr.rip.qword,
uint64_t(f.cf) | uint64_t(f.pf) << 2 |
uint64_t(f.af) << 4 | uint64_t(f.zf) << 6 |
uint64_t(f.sf) << 7 | uint64_t(f.of) << 11,
data,
data_hi,
read_only,
uint64_t(status)};
bx_memory_free(memory);
return result;
}
static void require(bool condition, const char *message) {
if (!condition) {
std::fprintf(stderr, "FAIL: %s\n", message);
std::exit(1);
}
}
static const uint8_t add_code[] = {0x48, 0x01, 0xc8, 0x48, 0x89, 0x03, 0xc3};
static const uint8_t load_code[] = {0x48, 0x8b, 0x03, 0xc3};
static const uint8_t store_code[] = {0x48, 0x89, 0x03, 0xc3};
static int integer_checks(int argc, char **argv) {
// Hand-derived ADD results: CF/PF/AF/ZF/SF/OF occupy x86 RFLAGS positions.
struct Case {
uint64_t a, b, value, flags;
};
Case cases[] = {
{1, 2, 3, 0x4},
{~0ULL, 1, 0, 0x55},
{0x7fffffffffffffffULL, 1, 0x8000000000000000ULL, 0x894},
{0x8000000000000000ULL, 0x8000000000000000ULL, 0, 0x845},
{15, 1, 16, 0x10},
{0, 0, 0, 0x44},
};
if (argc == 2 && std::strcmp(argv[1], "--wrong-answer") == 0)
cases[0].value ^= 1;
else if (argc != 1)
return 64;
unsigned checks = 0;
for (const auto &c : cases) {
auto actual = run(lifted_add, c.a, c.b, 0x2000);
require(actual.exit == 0 && actual.rax == c.value &&
actual.data == c.value && actual.flags == c.flags &&
actual.rsp == 0x3008 && actual.data_hi == 0 &&
actual.read_only == 0xa5a5a5a5a5a5a5a5ULL,
"Remill ADD known answer");
for (unsigned engine = 0; engine < 2; ++engine) {
ResultState baseline{};
require(bx_run(engine, add_code, sizeof(add_code), c.a, c.b, 0x2000,
&baseline),
"baseline available");
require(baseline.exit == 0 && baseline.rax == c.value &&
baseline.data == c.value && baseline.flags == c.flags &&
baseline.rsp == 0x3008 && baseline.data_hi == 0 &&
baseline.read_only == 0xa5a5a5a5a5a5a5a5ULL,
"BetterXen ADD known answer");
++checks;
}
++checks;
}
// Checked GuestMemory rejects unmapped reads/writes, read-only writes and
// split writes.
struct Fault {
Trace trace;
const uint8_t *code;
size_t size;
uint64_t address;
};
const Fault faults[] = {
{lifted_load, load_code, sizeof(load_code), 0x5000},
{lifted_store, store_code, sizeof(store_code), 0x5000},
{lifted_store, store_code, sizeof(store_code), 0x6000},
{lifted_store, store_code, sizeof(store_code), 0x200c},
};
for (const auto &c : faults) {
const auto actual = run(c.trace, 42, 0, c.address);
require(actual.exit == 1 && actual.rip == 0x1000 && actual.rax == 42 &&
actual.rsp == 0x3000 && actual.flags == 0 && actual.data == 0 &&
actual.data_hi == 0 &&
actual.read_only == 0xa5a5a5a5a5a5a5a5ULL,
"Remill checked memory rejection");
for (unsigned engine = 0; engine < 2; ++engine) {
ResultState baseline{};
require(bx_run(engine, c.code, c.size, 42, 0, c.address, &baseline),
"fault baseline available");
require(baseline.exit == 1 && baseline.rip == 0x1000 &&
baseline.rax == 42 && baseline.rsp == 0x3000 &&
baseline.flags == 0 && baseline.data == 0 &&
baseline.data_hi == 0 &&
baseline.read_only == 0xa5a5a5a5a5a5a5a5ULL,
"BetterXen checked memory rejection");
std::printf("fault address=0x%llx engine=%u baseline_rip=0x%llx "
"remill_rip=0x%llx\n",
(unsigned long long)c.address, engine,
(unsigned long long)baseline.rip,
(unsigned long long)actual.rip);
++checks;
}
++checks;
}
require(run(lifted_ud2, 0, 0, 0x2000).exit == 2, "UD2 must stop");
++checks;
require(run(lifted_jump, 0x5000, 0, 0x2000).exit == 2,
"indirect jump must stop");
++checks;
std::printf(
"PASS %u checks: 6 arithmetic cases and 4 memory rejections across "
"Remill, interpreter and DBT; 2 Remill control rejections\n",
checks);
return 0;
}
#ifndef REMILL_EXTENDED_PROBES
int main(int argc, char **argv) { return integer_checks(argc, argv); }
#endif