Compare commits

...
Author SHA1 Message Date
atharvranjan 9923e59114 Merge pull request #296 from maridogolpeador/app/252-open-command
app: add Command-O and show file-picker errors (#252)
2026-11-25 12:08:20 -06:00
atharvranjan feba95fe39 Merge origin/main into app/252-open-command
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 11:52:31 -06:00
atharvranjan a275de6e2e Merge pull request #295 from maridogolpeador/app/251-inspection-request-order
app: keep inspection results tied to the latest selection (#251)
2026-11-25 11:51:15 -06:00
atharvranjan 25986845da Merge origin/main into app/251-inspection-request-order
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 11:46:03 -06:00
atharvranjan df9652740b Merge pull request #309 from soggyramennoodle/task/255-startup-diagnostics
Report trusted fixture startup progress
2026-11-25 11:42:21 -06:00
atharvranjan 1ca491d8d0 Merge pull request #297 from maridogolpeador/docs/260-texture-format-inventory
docs: inventory texture formats and layouts by stage (#260)
2026-11-25 11:42:08 -06:00
atharvranjan 964a8296f2 Merge pull request #294 from atesahmet0/task/154-cpu-coverage-map
Add the verified CPU/loader coverage map
2026-11-25 11:41:54 -06:00
atharvranjan d8a8c96408 Merge pull request #338 from Thxlx/perf/89-arm64-constant-load
perf: shorten ARM64 loads for zero-extended constants
2026-11-25 11:40:55 -06:00
atharvranjan 50321b3f14 Merge pull request #337 from Thxlx/docs/299-avx-contract 2026-11-25 10:56:04 -06:00
Thilo Schaeffer 1fe07f45ee test: clarify ARM64 assembler offset units
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:45:05 +01:00
Thilo Schaeffer d486d21813 docs: clarify AVX exception policy and Intel references
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:45:04 +01:00
Thilo Schaeffer 4c92c88b29 perf: shorten ARM64 loads for zero-extended constants
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:31:03 +01:00
Thilo Schaeffer 478e9218ac docs: specify the guest AVX and AVX2 contract
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:21:18 +01:00
Adeeb Rahman 8d2662dcd7 Preserve startup report delivery and worker errors
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 09:56:31 -05:00
Adeeb Rahman fe1bf568c8 Merge BetterXen main
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 09:51:45 -05:00
maridogolpeador 873652d685 app: run inspection reads on a Dispatch queue, not a concurrency worker (#251)
Review follow-up. The reader blocks on file I/O, and in the
--smoke-inspection-order check on its gate semaphore. Inside
Task.detached that blocked a Swift concurrency worker; with a
single-worker cooperative pool the released newer read could not start
while the older one waited, and the check timed out. The read now runs
on DispatchQueue.global(qos: .userInitiated) and is bridged back with
withCheckedContinuation. The request-number guard is unchanged.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:38:12 -03:00
ates 84f561b12b Fix the documented known-answer count command
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 16:14:50 +03:00
maridogolpeador 2b113a2e5e docs: separate host API coverage from guest reachability and link sources (#260)
Review follow-up. The Guest column credited the descriptor-table SRVs,
which tests call directly from Rust and the interface contract says
are not yet wired to guest imports. The table now has a Host graphics
API column for them and keeps Guest for paths an original PE fixture
reaches through imported services: today only RGBA8, through the
synthetic xenora.dll texture services of the Gate 5 fixture. Every
repository path is now a relative link, and each format row links the
exact Khronos DFS 1.3 section and Microsoft or Apple page it relies on.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:44 -03:00
maridogolpeador 9a26e1ee36 docs: inventory texture formats and layouts by stage (#260)
Add docs/research/texture-formats.md, built from BetterXen main. For
RGBA8, BC1-BC7 and Depth32Float it separates container recognition,
CPU decoding, layout conversion, native Metal upload and readback,
translated sampling and guest reachability, linking the implementing
files and tests for each cell, including the packed BC footprints from

It cross-references #208 and #209 rather than opening duplicate tasks,
records console layouts, console descriptors and asset or audio
containers as unknowns, and ranks three proposed follow-ups with an
original-fixture recipe, an independent source of expected values and
an owner each. Deferred formats with no demonstrated need are listed.

docs/README.md indexes the page. Research only; no code changed.

Ported from XenoraOSS/Xenora#427 and re-checked against BetterXen main.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:43 -03:00
maridogolpeador c84b80b24f app: route Command-O to the focused window's importer (#252)
Review follow-up. The command set a shared Boolean, so with every
window closed there was no importer to present it, and with several
windows each one bound the same flag. Each ContentView now owns its
importer state and publishes an open action with focusedSceneValue;
OpenExecutableCommand reads it with @FocusedValue, calls it for the
focused window and is disabled when no window provides it. The
inspector button uses the same per-window action. InspectionModel no
longer holds the importer flag; requestImport only clears the previous
selection error.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador ae804f0530 app: gate the inspection-order smoke check instead of sleeping (#251)
Review follow-up. The check used fixed 300/700 ms pauses, so on a
loaded host a late stale read could arrive after an assertion, or the
newer read could finish before the busy-state check. The injected
reader now blocks until the check releases that file, and the check
waits on InspectionModel.finishedReads, which counts every finished
read whether it was published or discarded. A five-second deadline
bounds the wait without deciding the order.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador 64e7b16983 app: add Command-O and show file-picker errors (#252)
The inspector had an Open Executable… button but no app-level Open
command, and the file importer's completion ignored failures, so a
picker error was never shown.

- File > Open Executable… with Command-O, after New Window. It calls
  the same requestImport() as the button, so it opens the same
  read-only importer and the chosen file reaches inspect(), the path
  shared with drag and drop and Finder Open With.
- importFinished(_:) handles the importer result: success inspects,
  a user cancellation (CocoaError.userCancelled) shows nothing, and any
  other failure is shown in red with the error's description. The
  message clears on the next request or selection.
- --smoke-import-result checks cancellation, a shown failure and its
  clearing without opening files; scripts/build-app.sh runs it after
  --smoke. It fails with the previous importer handling and without the
  cancellation check.

Opening a file still never starts guest execution, the DBT or the JIT.

Ported from XenoraOSS/Xenora#424.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador 1ea898b4bf app: keep inspection results tied to the latest selection (#251)
InspectionModel.inspect started a detached read per call and published
status, report and busy whenever any of them finished. A slow first
inspection that completed after a fast second one replaced the newer
report and status, and could clear busy while the newer read was still
running.

- Each inspect call takes a request number; a completion is applied
  only while it is still the latest, so stale success and stale failure
  are discarded. Picker, drag and drop and Finder Open With all go
  through inspect and share this.
- A new selection clears the previous report, and a failed inspection
  of the latest file is shown in red above its report.
- The read is unchanged: size checked before reading, balanced
  security-scoped access, nothing executed. The reader is injectable
  only for the smoke check.
- --smoke-inspection-order drives the model with an injected slow and
  fast reader: slow then fast with either outcome, and busy held for the
  newer request while an older read finishes. scripts/build-app.sh runs
  it after --smoke. All four checks fail without the change.

Ported from XenoraOSS/Xenora#423.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
ates 7946968cc4 Address coverage review and merge current main
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 16:03:49 +03:00
atharvranjan 67b8cff9df Merge pull request #326 from MacosPorters/claude/pr-294-review-nftzfu
Rewrite the README around the development phases and launch target
2026-11-25 05:59:17 -06:00
atharvranjan 51c23a2f38 Merge pull request #293 from maridogolpeador/ci/248-app-build
ci: build and smoke-test BetterXen.app on native ARM64 runners (#248)
2026-11-25 05:58:01 -06:00
Claude 7d97e67448 Rewrite the README around the development phases and launch target
Reorganize the README around the six development phases and the first
launchable application tracker, add colour-coded Mermaid diagrams and
registry-derived charts, a repository overview and a contributing
section, and correct the texture-sampling and recompiler wording.

Signed-off-by: Claude <noreply@anthropic.com>
2026-11-25 11:53:09 +00:00
atharvranjan d9261db887 Merge pull request #325 from MacosPorters/repo/add-codeowners
Add CODEOWNERS and replace
2026-11-25 04:39:37 -06:00
atharvranjan 5c0c82b3f9 Add a fast repository hygiene check
Add hygiene.yml and scripts/audit/docs_hygiene.py: fail on merge-conflict
markers, broken relative Markdown links and invalid workflow YAML, and
warn (advisory) when source changes lack a changelog entry.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:24:36 -06:00
atharvranjan b71db3c25a Remove the pull request template
Delete .github/PULL_REQUEST_TEMPLATE.md and update CONTRIBUTING.md and
the changelog to match.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:23:03 -06:00
atharvranjan 566f803111 Remove the PR template check
Delete the pr-template workflow, its checker script and tests, and the
CI step that ran those tests. Update CONTRIBUTING.md and the changelog.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:18:06 -06:00
atharvranjan 857c16fcf7 Merge origin/main into repo/add-codeowners
Resolve conflicts in favor of main's development phases and roadmap
text. Keep the game-title wording and PE-Vulkan project renames, the
PortWatch research notes and their docs index link.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:16:38 -06:00
atharvranjan 4f5c6913f5 Replace game-title and upstream-project names in our own docs
Use generic 'commercial title' wording for our own references to a
specific game, rename the ignored diagnostics folders to
title-candidate-* and title-check, and refer to the upstream PE/Vulkan
project as 'PE-Vulkan project' in prose. Third-party URLs and repository
paths are unchanged to keep provenance accurate. Also adds the native
macOS development phases and PortWatch research notes already in the
working tree.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:12:59 -06:00
Adeeb Rahman e4ddb05a1a Run startup draw check on native Metal hardware
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 00:27:42 -05:00
Adeeb Rahman d33a7c6941 Report trusted fixture startup progress
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 00:23:04 -05:00
maridogolpeador 4e838207fe ci: check the printed dependency listing and reject empty or failed listings (#248)
Review follow-up. build-app.sh now runs otool -L once in a checked
assignment, prints that output and parses the same text, so a failing
or empty listing fails the gate instead of skipping the loop. Every
Swift executable links libSystem, so an empty list is an error.
Bundle-relative entries (@rpath, @executable_path, @loader_path) get
their own message. The changelog entry now separates the designed CI
behaviour from what has been verified locally.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 02:09:22 -03:00
ates b40bbae1da Refresh the coverage map at merged main b2654e9
The branch now contains main b2654e9, which includes the merged DBT
cache-identity pull and the migration-benchmark checks, so the map pins
its single gate run to that revision: the former self-modifying-code
defect test executes and passes in both DBT engines (cpu_known_answers
50 passed, 0 ignored) and the workspace gate reports 116 result lines
with 1015 passed, 0 failed and 34 ignored. The ignore taxonomy in the
map names all three kinds from their own messages: Metal-gated,
LLVM-gated (gfx1030 AMDGPU target) and manual timing runs.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 08:07:53 +03:00
maridogolpeador b04b41f26a ci: build and smoke-test BetterXen.app on native ARM64 runners (#248)
The CI workflow built and inspected the CLI but never ran
scripts/build-app.sh, so a Swift compile, link or smoke failure in app/
passed CI.

- ci.yml: a second job, "Native app build and smoke", on the same
  macos-26 image, pinned Rust toolchain and CARGO_BUILD_JOBS as the Rust
  job. It verifies an arm64 host without Rosetta, prints the Xcode and
  Swift versions and runs scripts/build-app.sh. The Rust job is
  unchanged.
- build-app.sh: after the lipo check, print file and otool -L for the
  executable and fail if it links anything outside /System/Library/ and
  /usr/lib/.

No Metal fixture runs in the new job; --smoke probes the C interface
and the trusted fixture's headers only. The same change was proposed
upstream as XenoraOSS/Xenora#426.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 01:59:03 -03:00
ates 3dd3ef06e2 Merge main into CPU coverage map
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 07:58:15 +03:00
atharvranjan b2654e93a4 Merge pull request #292 from MacosPorters/fix/migration-benchmark-checks
Run benchmark report tests in CI and record migration integration
2026-11-24 22:52:27 -06:00
ates fee956293d Add the verified CPU/loader coverage map
Document what the CPU and loader tests verify, per operation family, in
docs/testing/cpu-coverage.md: the declared-form inventory (213 operations,
403 forms, 498 opcode slots from the validated registry), the per-operation
engine split (93 native-lowered, 120 shared-semantic, with the conditional
width and encoding gates), a per-artifact evidence table with exact pass
counts from one full workspace gate run on Apple M5, the reconciliation of
the eight operations covered by model tests instead of the assembly-fixture
corpus, and a recorded note that three advisory qa cpu-inventory
unsupported-catalog rows are stale against the implemented and tested forms.
Also updates the docs/README.md description line and adds the CHANGELOG
entry under [Unreleased].

Closes #154.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 07:52:19 +03:00
atharvranjan 146d2dd467 Correct Win64 call-entry alignment wording
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:46:05 -06:00
atharvranjan a0d9b85dbf Run benchmark report tests in workspace CI and record migration review
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:42:19 -06:00
atharvranjan 5366b93986 Merge pull request #269 from MacosPorters/archive/pull/371/head
Validate DBT caches with executable generations and source revalidation
2026-11-24 22:31:00 -06:00
atharvranjan 50c392111d Merge pull request #266 from MacosPorters/archive/pull/352/head
bench: measure Metal startup in fresh processes and repeated runs (#178)
2026-11-24 22:26:04 -06:00
atharvranjan f43a07ce31 Synchronize cache generation fix with the integrated hosted C runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:25:18 -06:00
atharvranjan 10fd1cd4be Merge pull request #265 from MacosPorters/archive/pull/346/head
metal: budgeted staged RGBA8 texture upload into Private storage (#144)
2026-11-24 22:24:24 -06:00
atharvranjan 95aa10c60f Merge pull request #278 from MacosPorters/archive/pull/394/head
Pack block-compressed texture mip chains by subresource
2026-11-24 22:24:17 -06:00
atharvranjan 873b4fd4a9 Integrate PR #266 and distinguish imported benchmark evidence
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:19:01 -06:00
atharvranjan 120878de2d Integrate PR #265 bounded native Metal texture staging
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:16:37 -06:00
atharvranjan d26af53cef Merge pull request #283 from MacosPorters/archive/pull/420/head
loader: add the Gate A2 hosted C program and its test (#419)
2026-11-24 22:15:23 -06:00
atharvranjan b6ebaaad5e Merge pull request #282 from MacosPorters/archive/pull/418/head
loader: add files for a hosted C program: fopen, fclose, fgets and perror (#402)
2026-11-24 22:11:50 -06:00
atharvranjan aba82cdb77 Integrate PR #278 packed texture footprints
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:11:44 -06:00
atharvranjan 44ac976291 Retain cache-hit assertions with generation-triggered source revalidation
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:10:24 -06:00
atharvranjan d71efe0495 Integrate Gate A2 and verify native compiler architecture before execution
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:09:39 -06:00
atharvranjan 0bd8e19aac Merge pull request #281 from MacosPorters/archive/pull/401/head
loader: add standard output and printf formatting for a hosted C program (#400)
2026-11-24 22:08:23 -06:00
atharvranjan a1744a2754 Integrate PR #282 file streams with the combined runtime registry
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:05:58 -06:00
atharvranjan e93509ef5b Merge pull request #280 from MacosPorters/archive/pull/399/head
loader: add exit, _exit and abort for a hosted C program (#395)
2026-11-24 22:04:34 -06:00
atharvranjan 8344e299c9 Merge pull request #277 from MacosPorters/archive/pull/393/head
loader: add program arguments for a hosted C program (#392)
2026-11-24 22:04:27 -06:00
atharvranjan 433dc43695 Merge pull request #273 from MacosPorters/archive/pull/385/head
loader: add nine C runtime startup services a hosted C program imports (#382)
2026-11-24 22:04:19 -06:00
atharvranjan c18f9ffa7f Integrate PR #281 with existing startup and argument services
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:04:16 -06:00
atharvranjan a0f2d833aa Merge pull request #276 from MacosPorters/archive/pull/390/head
loader: add VirtualProtect, VirtualQuery and __C_specific_handler as stubs (#388)
2026-11-24 22:04:10 -06:00
atharvranjan 61afca42c9 Merge pull request #279 from MacosPorters/archive/pull/397/head
loader: run LOOP, LOOPE, LOOPNE and JRCXZ (#396)
2026-11-24 22:04:02 -06:00
atharvranjan be19e4e28f Merge pull request #275 from MacosPorters/archive/pull/389/head
loader: run LAHF and SAHF and report them in CPUID (#387)
2026-11-24 22:03:56 -06:00
atharvranjan 33ccf7fd55 Merge pull request #271 from MacosPorters/archive/pull/381/head
loader: add FNINIT and the x87 control, status and tag words (#378)
2026-11-24 22:03:49 -06:00
atharvranjan bb62353cfe Merge pull request #274 from MacosPorters/archive/pull/386/head
loader: raise #GP for instructions longer than 15 bytes (#384)
2026-11-24 22:03:42 -06:00
atharvranjan 1f2e7d3bb6 Merge pull request #272 from MacosPorters/archive/pull/383/head
bench: compare two dbt_bench JSON results (#114)
2026-11-24 22:03:34 -06:00
atharvranjan b5b646a58d Warm differential-test caches within the same guest address space
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:02:34 -06:00
atharvranjan acb3839351 Integrate PR #280 process termination and exit callbacks
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:00:19 -06:00
atharvranjan 4314071ac7 Validate DBT cache identity with executable generations instead of byte scans
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:59:14 -06:00
atharvranjan 4e15e5f43b Synchronize PR #275 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:16 -06:00
atharvranjan cf4010ba94 Synchronize PR #271 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:14 -06:00
atharvranjan b9e6a9d365 Synchronize PR #274 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:12 -06:00
atharvranjan a1a1020ebd Synchronize PR #272 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:10 -06:00
atharvranjan e755ee94ed Merge pull request #264 from MacosPorters/archive/pull/340/head
benchmarks: measure gfx1030 metadata identification
2026-11-24 21:57:34 -06:00
atharvranjan e289318132 Merge pull request #267 from MacosPorters/archive/pull/359/head
loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
2026-11-24 21:49:39 -06:00
atharvranjan f685b54e32 Merge pull request #268 from MacosPorters/archive/pull/369/head
loader: add Win64 service ABI preservation tests (#201)
2026-11-24 21:48:28 -06:00
atharvranjan 0690a3ecb4 Merge pull request #284 from MacosPorters/archive/pull/422/head
loader: copy mid-size TLS templates into the zeroed block (#111)
2026-11-24 21:48:22 -06:00
atharvranjan 7286989296 Merge pull request #270 from MacosPorters/archive/pull/374/head
Fix ARM64 variable shift register encoding
2026-11-24 21:47:03 -06:00
zachdoxsee 81a32e3ec6 Merge task/402-crt-files into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:33:07 +01:00
zachdoxsee 8edf3abf53 Merge task/395-crt-exit into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:33:07 +01:00
zachdoxsee 0c397c5957 Merge upstream/main into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:32:58 +01:00
zachdoxsee 417b19c859 Merge task/382-crt-startup into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:32:58 +01:00
Ranveer Soni 4cc703d566 Merge branch 'main' into fix/84-dbt-stale-code-cache 2026-11-25 07:02:16 +05:30
zachdoxsee 5ae43a3cb8 Merge task/400-standard-output (with upstream main) into task/402-crt-files
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:27:10 +01:00
zachdoxsee ab73969135 Merge upstream main into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:27:10 +01:00
zachdoxsee 8ee0304237 Merge upstream main into task/400-standard-output
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:27:04 +01:00
zachdoxsee 0a17f0cb73 loader: add the Gate A2 hosted C program and its test (#419)
An original C program, tests/compat_fixtures/gate_a2.c, is built from
source with the mingw-w64 C runtime (UCRT) and run through the loader, the
standard services and the ARM64 DBT. The runtime's own startup code runs
before main; the program uses argc and argv, the heap, qsort, printf, a file
written with fprintf and read back with fgets, atexit, and a return from
main. Expected output is recomputed in Rust, not read back from a run.
Control variants end in a failed check, in exit(42) and in abort().

The test fails, and does not skip, when the compiler is missing, so the CI
workflow installs mingw-w64. Nothing from mingw-w64 is stored in the
repository.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:25:26 +01:00
zachdoxsee db80c0b3e3 Merge task/402-crt-files into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:20 +01:00
zachdoxsee db46390fa9 Merge task/395-crt-exit into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:20 +01:00
zachdoxsee a9abc36eef Merge task/392-program-arguments into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:20 +01:00
zachdoxsee 972bc0a35c Merge task/388-must-exist-stubs into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:20 +01:00
zachdoxsee c0e90338d1 Merge task/382-crt-startup into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:19 +01:00
zachdoxsee e32c85ff12 Merge task/378-fninit into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:51 +01:00
zachdoxsee d409c26458 Merge task/329-gate-a1 into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:51 +01:00
zachdoxsee 1fafc2e43f Merge task/400-standard-output into task/402-crt-files
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 0aeb2b69a9 Merge task/329-gate-a1 into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 1342878c49 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee d6c9f846f0 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 34e99b3745 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 43f8287c92 Merge task/400-standard-output (with upstream main) into task/402-crt-files
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:52 +01:00
zachdoxsee a91c7fa39d Merge task/329-gate-a1 (with upstream main) into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:52 +01:00
zachdoxsee 874c7c7a63 Merge upstream main into task/400-standard-output
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 0236ec6ba9 loader: a failed fopen leaves the drive untouched (#402)
fopen created a missing file before it allocated the FILE object, so a
failed allocation left an empty file behind. The FILE object is now
allocated first and released again if the drive cannot take the file.
A test fills the heap and checks that neither a new file appears nor an
existing one loses its contents.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:00:04 +01:00
zachdoxsee 48d22f533b Merge task/329-gate-a1 (with upstream main) into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:57:12 +01:00
zachdoxsee 52e7e3808d Merge task/400-standard-output (with upstream main) into task/402-crt-files
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:57:12 +01:00
zachdoxsee 464393e02a Merge upstream main into task/400-standard-output
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:59 +01:00
zachdoxsee 1c8d7a40de loader: add files for a hosted C program: fopen, fclose, fgets and perror (#402)
A program built with the mingw-w64 runtime imports fopen, fclose, fgets
and perror, and writes to the stream fopen returns with fprintf, fwrite
and fputs. The four did not resolve, and the output functions accepted
only stdout and stderr.

Adds the four services and file streams for the output functions. The
files are the ones on the in-memory C: drive behind CreateFileW, so a
file written through a C stream is the file ReadFile reads. Text mode,
the default, translates line ends as the fopen documentation describes.

Built on the standard streams from #400. Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:49:52 +01:00
zachdoxsee afe8d16d9e loader: add standard output and printf formatting for a hosted C program (#400)
A program built with the mingw-w64 runtime prints through
__stdio_common_vfprintf on the stream __acrt_iob_func(1) returns, and
through fwrite, fputs, fflush and setvbuf. None resolved, and there was
nowhere for standard output to go that a host or a test could read.

Adds a formatting engine for the narrow printf family (d, i, u, o, x, X,
c, s, p and %% with their flags, width, precision and size prefixes), the
three standard streams, those six services, and capture of stdout and
stderr through ServicesState. Floating-point and wide conversions, a
locale, files and input are not modelled and stop the guest.

The engine is compared with the host C library's snprintf on 2,600
generated cases whose result ISO C defines.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:25:20 +01:00
zachdoxsee d326e929a9 loader: add exit, _exit and abort for a hosted C program (#395)
A C program ends through the C runtime's exit, not ExitProcess, and a
program built with the mingw-w64 runtime imports exit, _exit and abort.
None resolved, so the loader refused the program before its entry point.

exit calls the functions registered with atexit and _crt_atexit, most
recently registered first, then ends the guest with ProcessExit(status).
_exit ends it with its status and abort with exit code 3; neither calls a
registered function. All three use the cleanup behind ExitProcess.

Built on the process exit from #329. Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 00:47:33 +01:00
katherinebytes a6b0e89cac Pack block-compressed texture mip chains by subresource
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 22:40:57 +00:00
atharvranjan e856f080d1 dbt: retranslate cached blocks when guest code changes (#84)
Each cached block keeps the guest bytes it was translated from and is compared with the current executable bytes on every lookup.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 14:17:40 -06:00
Swastickc b09d96fd62 bench: measure Metal startup in fresh processes and repeated runs (#178)
Add `xenora-bench startup`. It checks one manifest fixture against the
independent reference, then times it phase by phase in two regimes: a
series of fresh child processes that each create the Metal device and
queue, translate and run the fixture once, and one process that
repeats the run. Phases are launch to main, device and queue,
translation, library, pipeline, submission, GPU and readback, reported
as median, p90, p99 and maximum, with raw fresh samples in launch
order.

Every sample must produce the expected output. A wrong output, a
failed or hung child (killed after 60 s) or a damaged sample line
stops the run before any result is written. Children inherit the
environment so the recorded MTL_* validation state applies to both
regimes.

Document the method and one recorded release run on an Apple M4 in
docs/testing/benchmarks.md, and add a changelog entry. Measurement
only.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:59:59 +05:30
Swastickc 6814d78230 metal: budgeted staged RGBA8 texture upload into Private storage (#144)
Add an opt-in staged upload beside the existing direct upload.
plan_staged_upload splits a full RGBA8 upload into submissions of
whole-row bands that never exceed a StagingBudget. It rejects missing,
duplicate or out-of-range mip levels, wrong mip sizes, short row
pitches or byte buffers, and budgets smaller than one row before any
Metal object exists.

MetalRgba8Texture::upload_staged fills a Private-storage texture
through one reused Shared staging buffer with blit copies, and reuses
the buffer only after the previous command buffer completed with
status Completed. read_back copies any mip back as tight RGBA8 bytes
through a blit. A Private texture refuses upload_mip with an error.

Enable objc2-metal's MTLBlitCommandEncoder feature for the blit
encoder; Cargo.lock is unchanged.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:32:49 +05:30
70 changed files with 12347 additions and 448 deletions

No files matched your search

-40
View File
@@ -1,40 +0,0 @@
## Summary
<!-- What changes, and why? -->
Closes #<!-- the issue you claimed -->
## Implementation and evidence
<!-- Describe affected subsystems, architecture assumptions, specification sections and upstream provenance where applicable. -->
## Verification
<!-- List actual commands and outcomes. Include hardware, validation-layer state and pass/fail/skip counts for GPU tests. Mark unrun checks explicitly. -->
| Check | Result / evidence |
| --- | --- |
| Formatting and lint | |
| Unit / integration tests | |
| GPU / differential tests | |
| Fuzzing / mutation / benchmarks, if relevant | |
## Compatibility and limitations
<!-- Note unsupported behavior, regressions, interface changes, performance effects and remaining uncertainty. -->
## Checklist
- [ ] I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
- [ ] I did not report skipped or unrun tests as passing.
- [ ] I updated applicable documentation, claims and status records.
- [ ] Third-party code and fixtures have verified licenses and provenance, or none were added.
- [ ] No restricted materials, credentials or private data are included.
- [ ] My commits are signed off under the DCO.
## AI assistance
<!-- Describe material assistance and the checks you personally performed, or state none. -->
+43 -2
View File
@@ -35,6 +35,19 @@ jobs:
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustc -vV
- name: Install the Gate A2 C toolchain
# crates/loader/tests/gate_a2.rs builds a hosted C program from source
# with mingw-w64 and fails, never skips, when the compiler is missing.
env:
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
run: |
brew install mingw-w64
compiler="$(brew --prefix mingw-w64)/bin/x86_64-w64-mingw32-gcc"
file -bL "$compiler" | grep arm64
lipo -archs "$compiler" | grep arm64
otool -L "$compiler"
"$compiler" --version | head -1
- name: Check generated status and PE fixtures
run: |
python3 crates/isa/generate_rdna2_meta.py --check
@@ -50,8 +63,6 @@ jobs:
run: |
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test native audit JSON decoding
run: python3 -m unittest discover -s tests/audit
- name: Test semantic registry generator and coverage report
@@ -77,3 +88,33 @@ jobs:
file "$binary"
test "$(lipo -archs "$binary")" = arm64
otool -L "$binary"
native-app:
name: Native app build and smoke
runs-on: macos-26
timeout-minutes: 20
env:
CARGO_BUILD_JOBS: 3
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Verify runner architecture
run: |
uname -m
test "$(uname -m)" = arm64
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install native Rust
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal
rustc -vV
- name: Show Swift and Xcode
run: |
xcodebuild -version
swift --version
# Builds the locked C ABI library and the Swift app together, checks the
# executable is arm64-only and links only system libraries, and runs
# `--smoke`. This is an app build and smoke result, not GPU verification.
- name: Build BetterXen.app and run its smoke check
run: scripts/build-app.sh
+43
View File
@@ -0,0 +1,43 @@
name: Repository hygiene
# Fast checks on tracked files that need no Rust toolchain and no network:
# merge-conflict markers, broken relative Markdown links and invalid workflow
# YAML (scripts/audit/docs_hygiene.py). A second, advisory step warns when
# source or script changes arrive without a CHANGELOG.md update; it never fails.
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: hygiene-${{ github.ref }}
cancel-in-progress: true
jobs:
hygiene:
name: Repository hygiene
runs-on: ubuntu-24.04-arm
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
fetch-depth: 0
- name: Install PyYAML
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
- name: Check documentation and workflow files
run: python3 scripts/audit/docs_hygiene.py --require-yaml
- name: Remind about the changelog (advisory)
if: github.event_name == 'pull_request'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
changed="$(git diff --name-only "$BASE_SHA"...HEAD || true)"
if printf '%s\n' "$changed" | grep -Eq '^(crates|scripts|shaders|fixtures)/' \
&& ! printf '%s\n' "$changed" | grep -qx 'CHANGELOG.md'; then
echo "::warning title=Changelog::Source or script files changed without a CHANGELOG.md update."
fi
-38
View File
@@ -1,38 +0,0 @@
name: PR template
# Fails when a pull request description does not follow
# .github/PULL_REQUEST_TEMPLATE.md: every section present and filled in, a
# linked issue ("Closes #N" or "No linked issue: <reason>"), and the
# claimed-first and DCO checkboxes ticked. Runs again whenever the description
# is edited; comments never start it. Runs on the base branch: pull request
# code is never checked out or executed, and the description is read as data.
#
# To make it blocking, mark the "PR template / description" check as required
# in the branch protection rule for main.
on:
pull_request_target:
types: [opened, edited, reopened, synchronize]
permissions: {}
jobs:
description:
runs-on: ubuntu-24.04-arm
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check the description against the template
run: |
set -u
status=0
python3 scripts/pr_template_check.py --event "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/result.txt" || status=$?
cat "$RUNNER_TEMP/result.txt"
{ echo '## PR template'; cat "$RUNNER_TEMP/result.txt"; } >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -ne 0 ]; then
echo "::error title=PR description does not follow the template::$(tail -n +2 "$RUNNER_TEMP/result.txt" | head -n -1 | tr '\n' ' ')"
fi
exit "$status"
+2 -2
View File
@@ -36,8 +36,8 @@
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
/diagnostics/title-candidate-*/
/diagnostics/title-check/
# Native application build output
/app/.build/
+1 -1
View File
@@ -34,7 +34,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
- Include a plain statement in docs/legal.md: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
- Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved.
- Keep BetterXen's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
- Keep BetterXen's emulator implementation original. Never copy, port, translate or adapt emulator source from PE-Vulkan project, KyTx, AnyPS5 or similar projects.
- Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply.
- Never place restricted material in the repository or its Git history.
- Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness.
+48 -1
View File
@@ -9,7 +9,18 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Added
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling, the host-side D3D12-shaped API (called from Rust, not wired to guest imports) and guest reachability through imported services, and links each cell's implementing files and tests and each format's exact public specification sections, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed.
- Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally.
- Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub.
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
### Removed
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Replaced our own references to a specific commercial game title (README non-affiliation line, research and integration notes, ignored diagnostics folder names) with generic "commercial title" wording. The ignored folder names are now `diagnostics/title-candidate-*` and `diagnostics/title-check`. Third-party repository names, URLs and code-span paths in research notes are unchanged so their provenance stays accurate. Our own prose references to the upstream project formerly named in the research notes now read "PE-Vulkan project". Added the PortWatch native-macOS research notes. No behavior change.
- 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.
@@ -20,6 +31,7 @@ remains unsupported.
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
- The ARM64 assembler uses one 32-bit `MOVN` for zero-extended constants such as `0xFFFF1234` that previously took two wide moves (#89). On an Apple M1 Pro, a synthetic workload with 4,096 affected loads emitted 163,920 native bytes, down from 180,304 (9.1%). The native tests verify the encoding and the full 64-bit register result.
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
@@ -33,12 +45,38 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
- Added a `Native app build and smoke` CI job (#248). On the same native `macos-26` runner image and pinned Rust toolchain as the Rust checks, it runs `scripts/build-app.sh`, which builds the locked C ABI library and the Swift app together, bundles and ad-hoc signs `BetterXen.app`, and runs its `--smoke` check, so a Swift compile, link or smoke failure is designed to fail CI (implemented and verified locally; not yet shown on a CI run). `scripts/build-app.sh` also prints `file` and a single `otool -L` listing for the executable, fails if that listing fails or is empty, and fails if the executable links any library outside `/System/Library/` and `/usr/lib/`, naming bundle-relative (`@rpath`, `@executable_path`, `@loader_path`) entries separately (checked locally against stubbed failing, empty, bundle-relative and non-system listings). The job is an app build and smoke result; it runs no Metal fixture and is not GPU verification.
- Added a CPU and loader coverage map (#154) with decoder inventory, native and shared execution paths, and test counts from a pinned Apple M5 run.
- 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,
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
only; nothing was optimized.
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
`upload` and its callers are unchanged. Not yet independently accepted.
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
@@ -48,10 +86,11 @@ remains unsupported.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
- Added checked, per-mip copy footprints for synthetic block-compressed texture arrays. Contributors can pack tight block rows or repack entire chains with independent row and placement alignment, and pass selected BC1–BC5 levels to the existing Metal readers (#391).
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
@@ -129,14 +168,20 @@ remains unsupported.
- Added nested guest directories and checked file deletion on the synthetic drive.
- Added the second Gate A milestone, A2 (#419): an original hosted C program, `tests/compat_fixtures/gate_a2.c`, built from source by the new test `crates/loader/tests/gate_a2.rs` with the mingw-w64 C runtime (UCRT) and run through the loader, the standard services and the ARM64 DBT. The runtime's own startup code runs before `main`. The program takes `argc` and `argv`, sorts heap data with `qsort`, prints with `printf`, writes a report with `fprintf` and reads it back with `fgets`, registers a function with `atexit` and returns from `main`. At `-O0`, `-O1`, `-O2` and `-Os` it ends with exit status 0, and its captured output and its report match, byte for byte, text recomputed in Rust. Seven more tests cover other arguments, four wrong command lines, a step budget that is too small, and control variants that end in a failed check, in `exit(42)` and in `abort()`. The test needs mingw-w64 on the host and fails, not skips, without it, so the CI workflow now installs it. Nothing from mingw-w64 is stored in the repository. Local runs used mingw-w64 14.0.0 with GCC 16.2.0. This is one program and one C runtime, compared by hand with a native build of the same source and not with Windows or x86 hardware; `docs/testing/gate-a.md` lists what it does not show. Awaiting independent review.
- Added file seeking and end-of-file resizing on the synthetic guest drive.
- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries.
- Added files for a hosted C program (#402, part of Gate A2): `fopen`, `fclose`, `fgets` and `perror`, and file streams for the output services from #400, so `fprintf`, `fwrite` and `fputs` write to a file `fopen` returned. The files are the ones on the in-memory `C:` drive behind `CreateFileW`, so a file written through a C stream is the file `ReadFile` reads, and the reverse. `fopen` takes `r`, `w` or `a` with `+`, `b` and `t` as Microsoft's page describes them; text mode, the default, stores a line feed as carriage return and line feed, reads the pair back as a line feed and ends input at `CTRL+Z`. Failures return their documented results; the `errno` values beyond `EINVAL` for a null or empty argument are Xenora's choice. Nothing is buffered, there is no seeking, a C stream takes no part in Win32 sharing, and the other mode characters are refused. All four services are `partial`. Eight tests in `runtime_services.rs`, four in the new `crt_files.rs` that cross-check with `ReadFile` and `WriteFile`, and a unit test of the mode strings cover it. Not compared with Windows; awaiting independent review.
- Added unnamed guest semaphores with checked release and immediate mixed-object waits.
- Added non-alertable extended event waits through both Win64 wait APIs.
- Added the C runtime's `exit`, `_exit` and `abort` (#395, part of Gate A2), on top of the process exit from #329. A C program ends through `exit`, not `ExitProcess`, and a program built with the mingw-w64 runtime imports all three; the loader refused it before its entry point because they did not resolve. `exit` calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, and then ends the guest with `ExitReason::ProcessExit(status)`; `_exit` ends it with its status and `abort` with exit code 3, and neither calls a registered function. All three go through the same cleanup as `ExitProcess` and never end the host. A function registered while `exit` runs is called next, as ISO C requires; `exit` called again from a registered function, which ISO C leaves undefined, runs the remaining functions once and ends with the later status. All three are partial: no stream is flushed because there are none, `abort` prints no message and calls no `SIGABRT` handler, and thread-local destructors are not run. Nine tests in `crt_exit.rs` call them from guest code. `docs/testing/gate-a.md` now describes A2 as in progress and not passing. Not compared with Windows; awaiting independent review.
- Added immediate wait-any and wait-all for guest event handles.
- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings.
@@ -145,6 +190,8 @@ remains unsupported.
- Added bounded guest CRT long-integer parsing for byte and wide strings.
- Added standard output for a hosted C program (#400, part of Gate A2): a `printf` formatting engine, the standard streams, and capture of what the guest writes to `stdout` and `stderr`. The services are `__acrt_iob_func`, `__stdio_common_vfprintf` (what `printf` and `fprintf` call in a program built with the mingw-w64 runtime), `fwrite`, `fputs`, `fflush` and `setvbuf`; a host reads the output through `ServicesState::standard_output` and `standard_error`. The engine handles the flags, width, precision and size prefixes of `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%` as Microsoft's format specification page and ISO C describe, reading arguments from the guest's `va_list`. The standard streams are text-mode streams, so a line feed is captured as carriage return and line feed. Floating-point and wide conversions, a locale object, other streams and files are not modelled and stop the guest with the runtime-limit fault instead of printing something wrong; `%n` and unknown conversions return -1 with `EINVAL`. All six services are `partial`. The engine's output matches the host C library's `snprintf` on 2,600 generated cases whose result ISO C defines (`crates/loader/tests/printf/reference.py`), with hand-written cases for the Windows-specific rules, and seven tests in `runtime_services.rs` call the services from guest code. Not compared with Windows; awaiting independent review.
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+1 -1
View File
@@ -44,7 +44,7 @@ Before incorporating third-party code, verify per-file license compatibility wit
## Pull requests
- Branch from the current main branch, keep commits focused, and link relevant issues.
- Fill in every section of the pull request template, keep `Closes #<number>` (or write `No linked issue: <reason>`), and tick the claimed-first and DCO checkboxes. The *PR template* check fails until the description does, and runs again each time you edit it.
- Describe what changes and why, link the issue you claimed with `Closes #<number>`, state which checks you actually ran, and disclose material AI assistance. Separate unverified work from supported behavior.
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
- Never include secrets, personal paths, credentials or private data in patches or logs.
+156 -19
View File
@@ -1,29 +1,95 @@
<div align="center">
# BetterXen
BetterXen is a community-maintained continuation. Original Git history, licenses and contributor attribution are retained. See the [project history and migration notes](docs/migration.md) for source attribution and imported issue and pull-request records.
**Experimental Xbox Series X|S emulation research, built natively for Apple Silicon.**
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
BetterXen is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
[![Native Rust checks](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
![Platform: Apple Silicon](https://img.shields.io/badge/platform-Apple%20Silicon%20(ARM64)-1f6feb?logo=apple&logoColor=white)
![Graphics: Metal](https://img.shields.io/badge/graphics-native%20Metal-8957e5)
![Language: Rust](https://img.shields.io/badge/language-Rust%201.100-dea584?logo=rust&logoColor=white)
![Status: experimental](https://img.shields.io/badge/status-experimental-d29922)
![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-2ea043)
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
BetterXen is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
</div>
BetterXen is a community-maintained, open-source project written primarily in Rust. It builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend. The host runs as ARM64 code; the x86-64 code being emulated is guest data.
> [!IMPORTANT]
> **BetterXen is experimental.** Verified work is restricted to independently authored synthetic programs and shaders. Authentic Xbox executable loading, system-service compatibility and commercial game execution are **not supported**. Progress is measured by reproducible tests, not by estimated game compatibility percentages. See the [current limitations](#current-limitations).
> [!CAUTION]
> **BetterXen strictly opposes piracy.** BetterXen is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. BetterXen is not affiliated with Microsoft or any other publisher or platform holder.
[![Native Rust checks](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
---
## How it fits together
One guest program travels through three native subsystems. Every stage is checked against an independently derived expectation.
```mermaid
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
flowchart LR
A["Original PE32+<br/>test program"]:::guest --> B["Loader<br/>relocations, TLS, imports"]:::guest
B --> C["x86-64 interpreter<br/>+ ARM64 translator"]:::cpu
C --> D["Typed runtime<br/>services"]:::cpu
D --> E["Guest graphics<br/>commands"]:::gpu
S["Original gfx1030<br/>shader bytes"]:::shader --> T["RDNA 2 decoder<br/>+ validated IR"]:::shader --> U["Metal Shading<br/>Language"]:::shader
E --> M["Native Metal<br/>pipelines"]:::gpu
U --> M
M --> G["Apple Silicon GPU<br/>+ readback"]:::gpu
G --> V{"Matches the<br/>independent<br/>CPU reference?"}:::check
S -.-> R["Independent<br/>CPU reference"]:::check -.-> V
classDef guest fill:#ddf4ff,stroke:#0969da,color:#0a3069
classDef cpu fill:#dafbe1,stroke:#1a7f37,color:#0f5323
classDef shader fill:#fbefff,stroke:#8250df,color:#512a97
classDef gpu fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef check fill:#ffebe9,stroke:#cf222e,color:#82071e
```
Legend: 🟦 guest loading · 🟩 guest CPU and services · 🟪 shader translation · 🟨 native Metal · 🟥 independent verification.
---
## What works today?
## Milestones
BetterXen has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
BetterXen's work order is the six [development phases](docs/development-phases.md), which lead to one concrete target: the **first launchable application** (tracker [#311](https://github.com/MacosPorters/betterxen/issues/311)). That target is an original C program, built with native ARM64 tools, that runs through the ARM64 translator, controls its own translated shader pipeline, and shows its Metal frame in the native app window. It is **not** a commercial or authentic Xbox title, and no date or percentage is attached to it.
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.
```mermaid
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
flowchart LR
P1["<b>Phase 1</b><br/>Trustworthy baseline"]:::wip --> P2["<b>Phase 2</b><br/>Hosted C application"]:::wip
P2 --> P3["<b>Phase 3</b><br/>Coherent threading"]:::wip
P3 --> P4["<b>Phase 4</b><br/>Resource updates<br/>to translated rendering"]:::wip
P4 --> P5["<b>Phase 5</b><br/>One integrated<br/>interactive application"]:::plan
P5 --> P6["<b>Phase 6</b><br/>Measured performance"]:::plan
P2 --> L(["<b>First launchable app</b><br/>issue 311"]):::goal
P4 --> L
classDef wip fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef plan fill:#eaeef2,stroke:#8c959f,color:#24292f
classDef goal fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:3px
```
### Development milestones
<sub>🟨 work under way · ⬜ not started · 🟩 the next original-workload target. Nothing here is independently accepted.</sub>
| Phase | Goal | State | What exists now |
| --- | --- | --- | --- |
| **1 · Baseline** | Contributors can tell what exists on `main`, what is pending review, and which checks ran | 🟡 In progress | CODEOWNERS review, a fast repository hygiene check, claim-before-work rules, generated status tables and claim audits |
| **2 · Hosted C application** | An original hosted C program starts, uses the runtime, reports results and exits with checked cleanup | 🟡 In progress | CRT startup, arguments, exit handlers, formatted output, file streams and the hosted-C fixture (A2) are integrated; a stdio follow-up is still open and the result is not independently accepted |
| **3 · Threaded behavior** | A worker-based application can block and resume without stalling other guest work | 🟡 In progress | Deterministic scheduler, guest thread contexts, guarded stacks and thread services. Guest `Sleep` still delays all guest threads (#304); worker TLS and callback lifecycle is a design draft (#312) |
| **4 · Resource updates to rendering** | A guest updates a texture and geometry, submits translated rendering and gets a checked frame | 🟡 In progress | Persistent resources, descriptor-table texture binding, translated vertex and pixel stages, blend, depth and indexed draws. Guest-selected pipelines and the typed graphics bridge are open (#314–#316) |
| **5 · Integrated interactive app** | Guest execution, rendering, input, audio, filesystem and lifecycle in one session | ⚪ Planned | Swift app with frame loop, input, audio and sandboxed filesystem fixtures exists, but those demonstrations are not guest-integration evidence |
| **6 · Measured performance** | Faster execution of workloads whose correctness is already checked | ⚪ Planned | Startup, DBT and TLS measurements recorded; bottlenecks are chosen from measurements, not assumed |
The launch milestone's proposed acceptance is **60 bounded frames containing two independently distinguishable guest-controlled states, then a clean close and one restart**. Sixty is a fixture criterion, not a measured frame rate. The work is tracked as issues [#313](https://github.com/MacosPorters/betterxen/issues/313)–[#323](https://github.com/MacosPorters/betterxen/issues/323).
<details>
<summary><b>Capability reference: the original X1–X25 map</b></summary>
The X1–X25 names are an older, broad capability map. Keep them as a reference; use the phases above for the next work order. X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence.
| Milestone | Implementation | Status |
| --- | --- | --- |
@@ -36,7 +102,7 @@ The latest verified milestones include **translated gfx1030 vertex and pixel sha
| 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 |
| X10 — Texture sampling | One translated `image_sample_lz` pixel stage with point/clamp sampling of RGBA8 and BC1 2D textures bound through descriptor tables, locally verified on Apple M5 Pro; upload, readback and decode of BC compressed formats (see [Texture support](#texture-support)). Other image instructions and formats are not implemented | Implemented subset |
| 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 |
@@ -53,10 +119,60 @@ The latest verified milestones include **translated gfx1030 vertex and pixel sha
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. 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.
</details>
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
---
## Repository at a glance
Counts below come from the generated registries and were read from the repository, not measured on new runs. They describe synthetic fixtures only.
| Area | Where | What exists today |
| --- | --- | --- |
| Guest CPU | `crates/loader` | A generated x86-64 decoder and interpreter, plus a native ARM64 dynamic binary translator (DBT) for a bounded subset. The instruction registry declares 213 operations, 403 forms and 498 opcode slots; 93 operations have at least one form lowered to ARM64 and the rest run through shared interpreter semantics. See the [instruction registry](docs/cpu/instruction-registry.md). |
| Executable loading | `crates/loader` | PE32+ loading, relocations, thread-local storage, import binding and a static inspection report. |
| Runtime services | `crates/loader`, `crates/import-gen` | A typed service registry: 47 declared services (7 implemented, 37 partial, 3 stubs), all exercised through guest dispatch, none independently accepted. See the [registry](docs/runtime/registry.md) and [generated coverage](docs/runtime/services.md). Guest threads run on a deterministic scheduler on one host thread. |
| Shader ISA | `crates/isa`, `crates/decoder`, `crates/shader`, `crates/ref` | The RDNA 2 (gfx1030) instruction snapshot lists 1,465 forms; 189 are decoder-supported, 185 are lowered to Metal Shading Language, and 18 are Metal-verified on fixtures. See the [semantic coverage](docs/shaders/semantic-coverage.md). An independent CPU reference checks GPU output. |
| Metal backend | `crates/metal` | Native compute, blend, indexed-draw, depth and sampled-texture passes, with Metal API and shader validation. |
| Textures | `crates/texture` | Upload, readback, BC1 to BC7 decoding and sampler code. |
| Application | `app`, `crates/ffi` | A Swift macOS app over a versioned C interface: frame loop, interactive input, persistent resources, audio and a sandboxed virtual filesystem, all against synthetic guests. |
| Test and tooling | `tests`, `fuzz`, `benchmarks`, `scripts` | Original guest programs, independent validation, fuzz targets (CPU decode, PE parse, instruction streams, fixtures, reference, runtime services), mutation testing, correctness-gated benchmarks, and audit scripts for claims, status tables and dependency direction. |
The `betterxen` command-line tool provides `info`, `demo`, `inspect <pe>`, `probe --pe <path> --mode static`, `run`, `imports` and `shaders`. Run `cargo run -p betterxen` with no arguments to see its usage.
### Where the numbers stand
Counts come from the repository's generated registries at this revision. They describe synthetic fixtures only and are not compatibility percentages.
```mermaid
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d0d7de','pieTitleTextSize':'16px','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
pie showData title Guest CPU — 213 declared x86-64 operations
"Lowered to ARM64 (at least one native form)" : 93
"Shared interpreter semantics only" : 120
```
```mermaid
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d4a72c','pie3':'#cf222e','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
pie showData title Runtime services — 47 declared, none independently accepted
"Implemented" : 7
"Partial" : 37
"Stub" : 3
```
```mermaid
%%{init: {'theme':'base','themeVariables':{'xyChart':{'plotColorPalette':'#8250df'}}}}%%
xychart-beta
title "gfx1030 instruction forms by stage (1,465 identified)"
x-axis ["Decoder-supported", "Lowered to MSL", "Metal-verified"]
y-axis "Forms" 0 --> 200
bar [189, 185, 18]
```
---
## Native graphics translation
BetterXen's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
@@ -177,9 +293,9 @@ Implemented and tested functionality includes:
- Edge-block and transparency tests.
- Invalid descriptor and bounds rejection.
**Translated texture-sampling instructions are not yet implemented.**
**Translated texture sampling covers one instruction and one sampler mode.** A guest draw with the translated `image_sample_lz` pixel stage and a point/clamp sampler matched the software reference and hand-derived images on a local Apple M5 Pro run (one-level RGBA8 and an 8×8 BC1 texture). Other image instructions, filtering modes and formats are not implemented, and this is local verification, not independent acceptance.
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
The texture upload and readback paths use authored Metal kernels. They should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
Xbox-specific texture layouts and additional compression formats require further research and validation.
@@ -230,13 +346,22 @@ flowchart TD
L --> M
K --> M
end
classDef guestNode fill:#dafbe1,stroke:#1a7f37,color:#0f5323
classDef shaderNode fill:#fbefff,stroke:#8250df,color:#512a97
classDef metalNode fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef checkNode fill:#ffebe9,stroke:#cf222e,color:#82071e
class A,B,C,D guestNode
class E,F,G,H shaderNode
class I,J,K metalNode
class L,M checkNode
```
BetterXen's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
The native ARM64 dynamic recompiler covers a bounded subset of x86-64 instructions; the rest run through the shared interpreter semantics (see the [CPU coverage map](docs/testing/cpu-coverage.md) once it lands). The project does not provide a complete Xbox operating-system implementation.
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
@@ -254,8 +379,8 @@ The following remain unsupported or incomplete:
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
| Graphics | Translated texture sampling and broader resource binding |
| Textures | Authentic Xbox memory layouts and translated sampling |
| Graphics | Broader translated texture sampling (one instruction and sampler mode exist) and broader resource binding |
| Textures | Authentic Xbox memory layouts and broader translated sampling |
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
| Game compatibility | No demonstrated execution of commercial Xbox titles |
@@ -351,9 +476,21 @@ Testing distinguishes between:
Compiling a shader is not equivalent to proving its GPU output is correct.
### Contributing
Contributions are welcome, and several people and coding agents work in this repository at once. To avoid duplicated work:
1. Read every comment on an issue and check for open pull requests that link it.
2. Claim the issue with a plain reply (for example "I'm taking this. Plan: ...") before you edit anything. The earliest live claim wins, and a claim is stale only after about seven days without a pull request.
3. Stay inside the files the issue lists, and put `Closes #<n>` in the pull request description.
4. Sign off every commit (DCO) and use only public documentation and original code. Anyone who has seen leaked or confidential Xbox material must not contribute.
5. Update `CHANGELOG.md` for meaningful changes. Changes to `main` need maintainer review through [CODEOWNERS](.github/CODEOWNERS).
See [CONTRIBUTING.md](CONTRIBUTING.md), [docs/legal.md](docs/legal.md) and the [documentation index](docs/README.md) for the full rules.
### Where the work is heading
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).
See the [milestones](#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).
---
@@ -367,6 +504,6 @@ BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE
See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries.
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, any game publisher or Apple.
---
+213 -6
View File
@@ -638,13 +638,65 @@ final class InspectionModel: ObservableObject {
@Published var report = ""
@Published var status: Int32 = Int32(XENORA_OK)
@Published var busy = false
@Published var importing = false
/// Why the last file selection could not be used, shown until the next selection.
@Published var selectionError: String?
/// Called when a window is about to show the read-only file importer, from its
/// button or File > Open Executable…. Each window presents its own importer.
func requestImport() {
selectionError = nil
}
/// Handles the importer's completion. A cancelled picker is not a failure.
func importFinished(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
inspect(url)
case .failure(let error):
if let cocoa = error as? CocoaError, cocoa.code == .userCancelled {
return
}
selectionError = "The selected file could not be opened: \(error.localizedDescription)"
}
}
/// Reads and reports one file off the main thread. Replaceable only for the
/// `--smoke-inspection-order` check.
private let reader: @Sendable (URL) -> (Int32, String)
/// Number of the latest `inspect` call. Only that call may publish a result.
private var latestRequest: UInt64 = 0
/// Reads that have finished, whether their result was published or discarded.
/// `--smoke-inspection-order` waits on it instead of on a fixed delay.
private(set) var finishedReads: UInt64 = 0
init(reader: @escaping @Sendable (URL) -> (Int32, String) = InspectionModel.run) {
self.reader = reader
}
var failed: Bool { !busy && fileName != nil && status != Int32(XENORA_OK) }
func inspect(_ url: URL) {
latestRequest &+= 1
let request = latestRequest
selectionError = nil
fileName = url.lastPathComponent
report = ""
status = Int32(XENORA_OK)
busy = true
let reader = reader
Task {
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
// The read blocks on file I/O (and, in `--smoke-inspection-order`, on
// its gate), so it runs on a Dispatch queue instead of occupying a
// Swift concurrency worker that other tasks may need.
let (newStatus, newReport) = await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
continuation.resume(returning: reader(url))
}
}
finishedReads &+= 1
// A newer selection owns the published state, including `busy`;
// an older read that finishes late is discarded.
guard request == latestRequest else { return }
status = newStatus
report = newReport
busy = false
@@ -685,17 +737,51 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
}
/// Opens the file importer of the focused window. Absent when no window can
/// present it, which disables File > Open Executable….
struct OpenExecutableKey: FocusedValueKey {
typealias Value = () -> Void
}
extension FocusedValues {
var openExecutable: OpenExecutableKey.Value? {
get { self[OpenExecutableKey.self] }
set { self[OpenExecutableKey.self] = newValue }
}
}
/// File > Open Executable… (Command-O), routed to the focused window's importer.
struct OpenExecutableCommand: Commands {
@FocusedValue(\.openExecutable) private var openExecutable
var body: some Commands {
CommandGroup(after: .newItem) {
Button("Open Executable…") { openExecutable?() }
.keyboardShortcut("o")
.disabled(openExecutable == nil)
}
}
}
struct InspectorView: View {
@ObservedObject var model: InspectionModel
let openImporter: () -> Void
var body: some View {
Section("Executable inspection (read-only)") {
HStack {
Button("Open Executable…") { model.importing = true }
Button("Open Executable…") { openImporter() }
Text("or drop a file on this window").foregroundStyle(.secondary)
}
if let error = model.selectionError {
Text(error).foregroundStyle(.red)
}
if let name = model.fileName {
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
if model.failed {
Text("Inspection of \(name) failed (status \(model.status)).")
.foregroundStyle(.red)
}
ScrollView {
Text(model.report)
.font(.system(.caption, design: .monospaced))
@@ -716,12 +802,19 @@ struct ContentView: View {
@ObservedObject var model: FrameModel
@ObservedObject var loop: FrameLoopModel
@ObservedObject var inspection = InspectionModel.shared
/// This window's importer. Kept per window so only the window that asked shows it.
@State private var importing = false
private var frame: GuestFrame? { model.frame }
private var running: Bool { model.running }
private func openImporter() {
inspection.requestImport()
importing = true
}
var body: some View {
Form {
InspectorView(model: inspection)
InspectorView(model: inspection, openImporter: openImporter)
Section("Guest display") {
if let image = frame?.image {
Image(decorative: image, scale: 1)
@@ -822,8 +915,8 @@ struct ContentView: View {
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
if case .success(let url) = result { inspection.inspect(url) }
.fileImporter(isPresented: $importing, allowedContentTypes: [.item]) { result in
inspection.importFinished(result)
}
.dropDestination(for: URL.self) { urls, _ in
guard let url = urls.first, url.isFileURL else { return false }
@@ -831,6 +924,7 @@ struct ContentView: View {
return true
}
.frame(minWidth: 520, minHeight: 680)
.focusedSceneValue(\.openExecutable, openImporter)
}
}
@@ -841,6 +935,7 @@ struct BetterXenApp: App {
var body: some Scene {
WindowGroup("BetterXen") { ContentView(model: model, loop: loop) }
.commands { OpenExecutableCommand() }
}
}
@@ -1009,6 +1104,118 @@ if CommandLine.arguments.contains("--smoke-frame") {
exit(frame.status == XENORA_OK ? 0 : 1)
}
// `--smoke-inspection-order` checks that only the latest selection publishes an
// inspection result. Files are never read: an injected reader blocks until the check
// releases that file, so the check, not timing, decides which read finishes first.
// It needs no GPU.
if CommandLine.arguments.contains("--smoke-inspection-order") {
final class ReadGates: @unchecked Sendable {
private let lock = NSLock()
private var gates: [String: DispatchSemaphore] = [:]
func gate(_ name: String) -> DispatchSemaphore {
lock.lock()
defer { lock.unlock() }
if let gate = gates[name] { return gate }
let gate = DispatchSemaphore(value: 0)
gates[name] = gate
return gate
}
func release(_ name: String) { gate(name).signal() }
}
let gates = ReadGates()
// "<scenario>-<a|b>-<ok|fail>"; a gate that is never released times out
// instead of hanging, and the check then fails on its own deadline.
let reader: @Sendable (URL) -> (Int32, String) = { url in
let name = url.lastPathComponent
_ = gates.gate(name).wait(timeout: .now() + 10)
let status = name.hasSuffix("-ok") ? Int32(XENORA_OK) : Int32(XENORA_INVALID_ARGUMENT)
return (status, "report \(name)")
}
func file(_ name: String) -> URL { URL(fileURLWithPath: "/nonexistent/\(name)") }
Task { @MainActor in
var failures: [String] = []
// Waits for the model to finish `count` reads. The deadline only bounds the
// check; the order of completions is set by releasing gates.
@MainActor func settle(_ model: InspectionModel, _ count: UInt64, _ label: String) async -> Bool {
let deadline = Date().addingTimeInterval(5)
while model.finishedReads < count {
if Date() > deadline {
failures.append("\(label): read \(count) did not finish")
return false
}
try? await Task.sleep(nanoseconds: 2_000_000)
}
return true
}
@MainActor func expect(_ model: InspectionModel, _ name: String, busy: Bool, report: String, ok: Bool, _ label: String) {
let actual = "file=\(model.fileName ?? "-") busy=\(model.busy) status=\(model.status) report=\(model.report)"
if model.fileName != name || model.busy != busy || model.report != report
|| (model.status == Int32(XENORA_OK)) != ok {
failures.append("\(label): \(actual)")
}
}
// The newer read finishes first; the older one finishes afterwards and must
// change nothing, whatever its outcome.
for (scenario, first, second, ok) in [("s1", "a-ok", "b-ok", true), ("s2", "a-fail", "b-ok", true),
("s3", "a-ok", "b-fail", false)] {
let (older, newer) = ("\(scenario)-\(first)", "\(scenario)-\(second)")
let model = InspectionModel(reader: reader)
model.inspect(file(older))
model.inspect(file(newer))
gates.release(newer)
if await settle(model, 1, "\(older) then \(newer)") {
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "\(newer) finished")
}
gates.release(older)
if await settle(model, 2, "\(older) then \(newer)") {
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "stale \(older) finished")
}
}
// The older read finishes first and must not clear the newer request's busy state.
let model = InspectionModel(reader: reader)
model.inspect(file("s4-a-ok"))
model.inspect(file("s4-b-fail"))
gates.release("s4-a-ok")
if await settle(model, 1, "s4") {
expect(model, "s4-b-fail", busy: true, report: "", ok: true, "stale s4-a-ok finished first")
}
gates.release("s4-b-fail")
if await settle(model, 2, "s4") {
expect(model, "s4-b-fail", busy: false, report: "report s4-b-fail", ok: false, "s4-b-fail finished")
}
for failure in failures { print("smoke-inspection-order: FAILED \(failure)") }
print("smoke-inspection-order: \(failures.isEmpty ? "ok" : "\(failures.count) failed")")
exit(failures.isEmpty ? 0 : 1)
}
dispatchMain()
}
// `--smoke-import-result` checks how a file-importer result reaches the inspector:
// a cancelled picker shows nothing, a failure is shown, and a new selection clears it.
// No file is opened or read.
if CommandLine.arguments.contains("--smoke-import-result") {
let ok = MainActor.assumeIsolated { () -> Bool in
var failures: [String] = []
let model = InspectionModel()
model.importFinished(.failure(CocoaError(.userCancelled)))
if model.selectionError != nil || model.fileName != nil { failures.append("cancel shows a message") }
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
if model.selectionError == nil || model.fileName != nil { failures.append("failure is not shown") }
model.requestImport()
if model.selectionError != nil { failures.append("reopening keeps the old message") }
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
model.inspect(URL(fileURLWithPath: "/nonexistent/import-result-check"))
if model.selectionError != nil || model.fileName != "import-result-check" {
failures.append("a new selection keeps the old message")
}
for failure in failures { print("smoke-import-result: FAILED \(failure)") }
return failures.isEmpty
}
print("smoke-import-result: \(ok ? "ok" : "failed")")
exit(ok ? 0 : 1)
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
+17 -2
View File
@@ -162,10 +162,21 @@ struct BatchResult {
pipelined: Stats,
}
mod startup;
mod startup_report;
fn main() -> Result<(), Box<dyn Error>> {
// Taken before anything else so a fresh startup child can report the time
// from its parent's spawn to `main`.
let entered = SystemTime::now();
let mut args = std::env::args().skip(1).peekable();
match args.peek().map(String::as_str) {
Some("startup") => return startup::run(args.skip(1)),
Some("startup-child") => return startup::child(entered, args.skip(1)),
_ => {}
}
let mut output = PathBuf::from("benchmarks/results");
let mut reps = DEFAULT_REPS;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--output" => {
@@ -179,7 +190,11 @@ fn main() -> Result<(), Box<dyn Error>> {
.map_err(|_| "--reps must be a positive integer")?;
}
"--help" | "-h" => {
println!("usage: xenora-bench [--output DIR] [--reps N]");
println!(
"usage: xenora-bench [--output DIR] [--reps N]\n \
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
[--reps N] [--output DIR]"
);
return Ok(());
}
other => return Err(format!("unknown argument {other}").into()),
+405
View File
@@ -0,0 +1,405 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
//!
//! `xenora-bench startup` checks one manifest fixture against the independent
//! reference, then measures it two ways:
//!
//! - **Fresh process.** It launches its own executable `--processes` times. Each
//! child creates the Metal device and queue, translates the fixture, runs it
//! once with `run_words_profiled`, checks the output and prints one sample line.
//! - **Repeated.** In this process it creates one device, then translates and runs
//! the same fixture `--reps` times. The first run is reported on its own.
//!
//! Every sample must produce the expected words. One wrong output, failed child or
//! unparsable sample line stops the run before anything is written. The
//! numbers describe this host only; two distributions do not explain each other.
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, ENTRY_POINT, compile};
use crate::startup_report::Report;
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
const DEFAULT_PROCESSES: usize = 30;
const DEFAULT_REPS: usize = 100;
/// A fresh process that has not exited by then is killed and fails the run.
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
pub(crate) const PHASES: [&str; 8] = [
"spawn_to_main",
"device",
"translate",
"library",
"pipeline",
"submit",
"gpu",
"readback",
];
/// One run's phase timings, indexed like [`PHASES`].
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
impl Sample {
fn line(&self) -> String {
let fields: Vec<String> = PHASES
.iter()
.zip(self.0)
.map(|(name, value)| format!("{name}={value:e}"))
.collect();
format!("startup-sample {}", fields.join(" "))
}
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
pub(crate) fn parse(line: &str) -> Result<Self, String> {
let rest = line
.strip_prefix("startup-sample ")
.ok_or("missing startup-sample prefix")?;
let fields: Vec<&str> = rest.split(' ').collect();
if fields.len() != PHASES.len() {
return Err(format!(
"expected {} fields, got {}",
PHASES.len(),
fields.len()
));
}
let mut sample = Self::default();
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
let value = field
.strip_prefix(name)
.and_then(|v| v.strip_prefix('='))
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
if !value.is_finite() || value < 0.0 {
return Err(format!("{name} must be finite and non-negative"));
}
sample.0[i] = value;
}
Ok(sample)
}
}
/// Median, tail and extremes of one phase.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Summary {
pub(crate) n: usize,
pub(crate) min: f64,
pub(crate) median: f64,
pub(crate) p90: f64,
pub(crate) p99: f64,
pub(crate) max: f64,
}
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
if values.is_empty() {
return None;
}
let mut sorted = values.to_vec();
sorted.sort_by(f64::total_cmp);
Some(Summary {
n: sorted.len(),
min: sorted[0],
median: percentile(&sorted, 0.5),
p90: percentile(&sorted, 0.9),
p99: percentile(&sorted, 0.99),
max: sorted[sorted.len() - 1],
})
}
struct Options {
fixture: Option<String>,
words: Option<usize>,
processes: usize,
reps: usize,
output: PathBuf,
}
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
let n: usize = value
.ok_or_else(|| format!("{flag} needs a count"))?
.parse()
.map_err(|_| format!("{flag} must be a positive integer"))?;
if n == 0 {
return Err(format!("{flag} must be at least 1"));
}
Ok(n)
}
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
let mut options = Options {
fixture: None,
words: None,
processes: DEFAULT_PROCESSES,
reps: DEFAULT_REPS,
output: PathBuf::from("artifacts/startup"),
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
"--words" => options.words = Some(count(args.next(), "--words")?),
"--processes" => options.processes = count(args.next(), "--processes")?,
"--reps" => options.reps = count(args.next(), "--reps")?,
"--output" => {
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
}
other => return Err(format!("unknown startup argument {other}")),
}
}
Ok(options)
}
/// The fixture to time and its word count, after the reference agrees with it.
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
let fixture = match &options.fixture {
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
None => fixtures.into_iter().next(),
}
.ok_or("fixture not found in benchmarks/manifest.toml")?;
let code = fs::read(&fixture.path)?;
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
if reference != fixture.expected {
return Err("reference disagrees with hand-derived expected values".into());
}
let words = options
.words
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
Ok((fixture, words))
}
/// Translates and runs the fixture once on `metal`, checking the output.
fn run_once(
metal: &NativeCompute,
fixture: &Fixture,
words: usize,
sample: &mut Sample,
) -> Result<(), Box<dyn Error>> {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let start = Instant::now();
let code = fs::read(&fixture.path)?;
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
sample.0[2] = start.elapsed().as_secs_f64();
let profile = metal
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
.map_err(|e| e.to_string())?;
if profile.output != expected {
return Err(format!("{} output disagrees with known answers", fixture.name).into());
}
sample.0[3] = profile.library_seconds;
sample.0[4] = profile.pipeline_seconds;
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
sample.0[6] = profile.gpu_seconds;
sample.0[7] = profile.readback_seconds;
Ok(())
}
fn unix_nanos(time: SystemTime) -> u128 {
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
}
/// Entry point of one fresh child process, called first thing in `main`.
///
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
/// time just before it spawned this process.
pub(crate) fn child(
entered: SystemTime,
mut args: impl Iterator<Item = String>,
) -> Result<(), Box<dyn Error>> {
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let mut sample = Sample::default();
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
sample.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut sample)?;
println!("{}", sample.line());
Ok(())
}
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
vec![
"--fixture".into(),
fixture.name.clone(),
"--words".into(),
words.to_string(),
]
}
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
///
/// The child inherits this process's environment on purpose, so its `MTL_*`
/// validation settings are the ones the run's metadata records.
fn spawn_child(
exe: &std::path::Path,
fixture: &Fixture,
words: usize,
) -> Result<(f64, String), Box<dyn Error>> {
let started = Instant::now();
let spawned = unix_nanos(SystemTime::now());
let mut child = Command::new(exe)
.arg("startup-child")
.arg(spawned.to_string())
.args(forwarded(fixture, words))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
// Drain both pipes while waiting, so a child that writes more than a pipe
// buffer (validation logs, for example) cannot block and look like a hang.
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
std::thread::spawn(move || {
let mut text = String::new();
if let Some(mut pipe) = pipe {
let _ = pipe.read_to_string(&mut text);
}
text
})
};
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if started.elapsed() > CHILD_TIMEOUT {
child.kill()?;
child.wait()?;
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
}
std::thread::sleep(Duration::from_millis(1));
};
let seconds = started.elapsed().as_secs_f64();
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
if !status.success() {
return Err(format!("{status}: {}", stderr.trim()).into());
}
Ok((seconds, stdout))
}
/// Runs both regimes and writes `startup.json` and `report.md`.
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let exe = std::env::current_exe()?;
let mut fresh = Vec::with_capacity(options.processes);
let mut wall = Vec::with_capacity(options.processes);
for i in 0..options.processes {
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
wall.push(seconds);
let line = stdout
.lines()
.find(|l| l.starts_with("startup-sample "))
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
}
let mut first = Sample::default();
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
first.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut first)?;
let mut repeated = Vec::with_capacity(options.reps);
for _ in 0..options.reps {
let mut sample = Sample::default();
run_once(&metal, &fixture, words, &mut sample)?;
repeated.push(sample);
}
let metadata = Metadata::collect(&metal.device_name(), options.reps);
let dir = options
.output
.join(slug(&metadata.device))
.join(&metadata.run_id);
fs::create_dir_all(&dir)?;
fs::write(dir.join("metadata.json"), metadata.to_json())?;
let report = Report {
fixture: &fixture.name,
words,
fresh: &fresh,
wall: &wall,
first: &first,
repeated: &repeated,
};
fs::write(dir.join("startup.json"), report.json())?;
let markdown = report.markdown(&metadata);
fs::write(dir.join("report.md"), &markdown)?;
println!("{markdown}");
println!("Startup results written to {}", dir.display());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample_lines_round_trip() {
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
}
#[test]
fn sample_lines_reject_damaged_input() {
let line = Sample([1.0; PHASES.len()]).line();
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
// Phases out of order are refused even when every name is present.
let swapped = line
.replacen("device=", "TMP=", 1)
.replacen("translate=", "device=", 1)
.replacen("TMP=", "translate=", 1);
assert!(Sample::parse(&swapped).is_err());
}
#[test]
fn summary_uses_interpolated_percentiles() {
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
// 0.99 * 99 = 98.01 between 99 and 100.
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
let s = summarize(&values).unwrap();
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
assert!((s.median - 50.5).abs() < 1e-9);
assert!((s.p90 - 90.1).abs() < 1e-9);
assert!((s.p99 - 99.01).abs() < 1e-9);
assert_eq!(summarize(&[]), None);
let one = summarize(&[3.0]).unwrap();
assert_eq!(
(one.median, one.p90, one.p99, one.max),
(3.0, 3.0, 3.0, 3.0)
);
}
#[test]
fn options_reject_bad_counts_and_flags() {
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
let defaults = parse(&[]).unwrap();
assert_eq!(
(defaults.processes, defaults.reps),
(DEFAULT_PROCESSES, DEFAULT_REPS)
);
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
assert!(parse(&["--processes", "0"]).is_err());
assert!(parse(&["--reps", "-1"]).is_err());
assert!(parse(&["--words"]).is_err());
assert!(parse(&["--fast"]).is_err());
}
}
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! JSON and markdown output of `xenora-bench startup` (#178).
use std::fmt::Write as _;
use crate::startup::{PHASES, Sample, Summary, summarize};
use crate::{Metadata, json_str};
pub(crate) struct Report<'a> {
pub(crate) fixture: &'a str,
pub(crate) words: usize,
pub(crate) fresh: &'a [Sample],
pub(crate) wall: &'a [f64],
pub(crate) first: &'a Sample,
pub(crate) repeated: &'a [Sample],
}
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
samples.iter().map(|s| s.0[phase]).collect()
}
fn summary_json(summary: Option<Summary>) -> String {
summary.map_or_else(
|| "null".to_string(),
|s| {
format!(
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
s.n, s.min, s.median, s.p90, s.p99, s.max
)
},
)
}
impl Report<'_> {
pub(crate) fn json(&self) -> String {
let mut out = format!(
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
json_str(self.fixture),
self.words,
summary_json(summarize(self.wall))
);
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
let _ = writeln!(out, " \"{regime}\": {{");
for (i, phase) in PHASES.iter().enumerate() {
let comma = if i + 1 < PHASES.len() { "," } else { "" };
let summary = if regime == "repeated" && i < 2 {
None
} else {
summarize(&column(samples, i))
};
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
}
out.push_str(" },\n");
}
let first: Vec<String> = PHASES
.iter()
.zip(self.first.0)
.skip(1)
.map(|(p, v)| format!("\"{p}\": {v:e}"))
.collect();
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
// Raw fresh-process samples in launch order, so a cold first process
// (for example an empty Metal shader cache) stays visible.
let rows: Vec<String> = self
.fresh
.iter()
.zip(self.wall)
.map(|(sample, wall)| {
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
format!("[{}, {wall:e}]", phases.join(", "))
})
.collect();
let _ = writeln!(
out,
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
PHASES
.iter()
.map(|p| json_str(p))
.collect::<Vec<_>>()
.join(", "),
rows.join(",\n ")
);
out
}
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
let ms = |v: f64| format!("{:.3}", v * 1e3);
let mut out = format!(
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
self.fixture,
self.words,
metadata.device,
metadata.profile,
metadata.commit,
metadata.api_validation,
metadata.shader_validation,
metadata.power,
metadata.thermal,
self.fresh.len(),
self.repeated.len(),
);
for (i, phase) in PHASES.iter().enumerate() {
let fresh = summarize(&column(self.fresh, i));
let repeated = (i >= 2)
.then(|| summarize(&column(self.repeated, i)))
.flatten();
let cells = |s: Option<Summary>| {
s.map_or_else(
|| "– | – | – | –".to_string(),
|s| {
format!(
"{} | {} | {} | {}",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
)
},
)
};
let first = if i == 0 {
"–".to_string()
} else {
ms(self.first.0[i])
};
let _ = writeln!(
out,
"| `{phase}` | {} | {first} | {} |",
cells(fresh),
cells(repeated)
);
}
if let Some(s) = summarize(self.wall) {
let _ = writeln!(
out,
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
);
}
out
}
}
+120 -17
View File
@@ -2,10 +2,10 @@
use std::error::Error;
use std::ffi::OsString;
use std::fs::{self, File};
use std::fs::{self, File, OpenOptions};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use std::process::{Child, Command, ExitCode, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -16,6 +16,10 @@ use xenora_loader::{
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
#[path = "startup_report.rs"]
mod startup_report;
use startup_report::{Events, JOURNAL_ERROR_EXIT, Journal, Termination, WATCHDOG_EXIT};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe");
const WALL_LIMIT: Duration = Duration::from_secs(15);
@@ -27,7 +31,7 @@ const TICKET: u64 = 17;
const DRAW_RESULT: u64 = 0x42;
const EXTENT: [usize; 2] = [4, 3];
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]";
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>] [--startup-report <path>]";
struct Options {
path: PathBuf,
@@ -35,6 +39,8 @@ struct Options {
worker: bool,
trace: bool,
hud: bool,
report: Option<PathBuf>,
journal: Option<PathBuf>,
}
impl Options {
@@ -42,6 +48,8 @@ impl Options {
let mut args = args.into_iter();
let mut path = None;
let mut max_steps = None;
let mut report = None;
let mut journal = None;
let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false);
while let Some(arg) = args.next() {
match arg.to_str() {
@@ -56,6 +64,16 @@ impl Options {
.ok_or("--max-steps must be in 1..=10000")?,
);
}
Some("--startup-report") if report.is_none() => {
report = Some(PathBuf::from(
args.next().ok_or("missing --startup-report path")?,
));
}
Some("--startup-journal") if journal.is_none() => {
journal = Some(PathBuf::from(
args.next().ok_or("missing worker journal path")?,
));
}
Some("--experimental") if !experimental => experimental = true,
Some("--trace") if !trace => trace = true,
Some("--metal-hud") if !hud => hud = true,
@@ -66,12 +84,17 @@ impl Options {
if !experimental {
return Err("run requires --experimental".into());
}
if (worker && report.is_some()) || (!worker && journal.is_some()) {
return Err("invalid startup report option for this process".into());
}
Ok(Self {
path: path.ok_or("missing --pe path")?,
max_steps: max_steps.unwrap_or(DEFAULT_STEPS),
worker,
trace,
hud,
report,
journal,
})
}
}
@@ -85,7 +108,7 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
}
};
let result = if options.worker {
run_worker(&options).map(|()| ExitCode::SUCCESS)
worker_command(&options)
} else {
launch_worker(&options)
};
@@ -99,8 +122,26 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
}
fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
let journal = options
.report
.as_ref()
.map(|_| Journal::create())
.transpose()?;
let executable = std::env::current_exe()?;
let destination = options
.report
.as_ref()
.map(|path| {
OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| format!("could not create startup report: {error}"))
})
.transpose()?;
let started = Instant::now();
let mut child = Command::new(std::env::current_exe()?)
let mut command = Command::new(executable);
command
.args([
"run",
"--experimental",
@@ -112,29 +153,73 @@ fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
.arg(options.max_steps.to_string())
.arg("--pe")
.arg(&options.path)
.stdin(Stdio::null())
.spawn()?;
.stdin(Stdio::null());
if let Some(journal) = &journal {
command.arg("--startup-journal").arg(journal.path());
}
let termination = command
.spawn()
.and_then(|child| supervise(child, started, WALL_LIMIT));
if let (Some(journal), Some(destination)) = (&journal, destination)
&& let Err(error) = journal.finish(destination, &termination)
{
eprintln!("could not write startup report: {error}");
if matches!(&termination, Ok(Termination::Exited(status)) if status.success()) {
return Ok(ExitCode::FAILURE);
}
}
match termination? {
Termination::Exited(status) => match status.code() {
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
None => Err(format!("worker terminated: {status}").into()),
},
Termination::Deadline => {
Err("experimental worker exceeded its 15 second wall deadline".into())
}
}
}
fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Result<Termination> {
loop {
match child.try_wait() {
Ok(Some(status)) => {
return match status.code() {
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
None => Err(format!("worker terminated: {status}").into()),
};
}
Ok(None) if started.elapsed() < WALL_LIMIT => {
Ok(Some(status)) => return Ok(Termination::Exited(status)),
Ok(None) if started.elapsed() < limit => {
std::thread::sleep(Duration::from_millis(10));
}
status => {
let _ = child.kill();
child.wait()?;
status?;
return Err("experimental worker exceeded its 15 second wall deadline".into());
return Ok(Termination::Deadline);
}
}
}
}
fn worker_command(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
let mut events = match options.journal.as_deref().map(Events::open).transpose() {
Ok(events) => events,
Err(error) => {
eprintln!("could not open startup journal: {error}");
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
}
};
let result = run_worker(options, events.as_mut());
if let Some(events) = events.as_mut() {
if let Err(error) = &result {
events.failure(error.as_ref());
}
if let Some(error) = events.write_error() {
if let Err(error) = result {
eprintln!("run failed: {error}");
}
eprintln!("could not write startup journal: {error}");
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
}
}
result.map(|()| ExitCode::SUCCESS)
}
fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
let valid_metadata =
|metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64;
@@ -158,14 +243,14 @@ fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
.ok_or_else(|| rejection.into())
}
fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
fn run_worker(options: &Options, mut events: Option<&mut Events>) -> Result<(), Box<dyn Error>> {
std::thread::Builder::new()
.name("xenora-deadline".into())
.spawn(|| {
std::thread::sleep(WALL_LIMIT);
// The supervisor also enforces this deadline. The worker retains
// its own deadline if it is invoked directly.
std::process::exit(124);
std::process::exit(i32::from(WATCHDOG_EXIT));
})?;
let fixture = verify_fixture(&options.path)?;
let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE {
@@ -232,6 +317,16 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
imports,
options.max_steps,
|event| {
if let Some(events) = events.as_deref_mut() {
events.stage(match &event {
StartupEvent::Parsed { .. } => "parsed",
StartupEvent::Mapped { .. } => "mapped",
StartupEvent::Relocated { .. } => "relocated",
StartupEvent::ImportsBound { .. } => "imports_bound",
StartupEvent::TlsCompleted { .. } => "tls_completed",
StartupEvent::Entering { .. } => "entry",
});
}
if options.trace {
trace_startup(event);
}
@@ -244,6 +339,11 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
.take();
let exit = startup.execution.exit_reason;
let rax = startup.execution.final_state.get(Register::Rax);
if exit == ExitReason::Halt
&& let Some(events) = events.as_deref_mut()
{
events.stage("exit");
}
if options.trace {
println!(
"trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}",
@@ -264,6 +364,9 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
return Err("trusted fixture startup or result differs from the expected values".into());
}
let frame = result.ok_or("guest halted without a draw")??;
if let Some(events) = events {
events.stage("framebuffer");
}
if options.trace {
println!(
"trace stage=framebuffer extent={}x{} verified_pixels={}",
+399
View File
@@ -0,0 +1,399 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::fmt::Write as _;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use std::process::ExitStatus;
use std::sync::atomic::{AtomicUsize, Ordering};
pub(super) const WATCHDOG_EXIT: u8 = 124;
pub(super) const JOURNAL_ERROR_EXIT: u8 = 125;
const VERSION: &str = "1";
const RECORD_SEPARATOR: char = '\t';
const MAX_BYTES: usize = 8192;
const MAX_ERROR_BYTES: usize = 2048;
const STAGES: [&str; 8] = [
"parsed",
"mapped",
"relocated",
"imports_bound",
"tls_completed",
"entry",
"exit",
"framebuffer",
];
pub(super) struct Journal(PathBuf);
impl Journal {
pub(super) fn create() -> io::Result<Self> {
static NEXT: AtomicUsize = AtomicUsize::new(0);
loop {
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let directory =
std::env::temp_dir().join(format!("betterxen-startup-{}-{id}", std::process::id()));
match fs::DirBuilder::new().mode(0o700).create(&directory) {
Ok(()) => return Ok(Self(directory)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
pub(super) fn path(&self) -> PathBuf {
self.0.join("events")
}
fn read(&self) -> Report {
let mut bytes = Vec::new();
match File::open(self.path())
.and_then(|file| file.take((MAX_BYTES + 1) as u64).read_to_end(&mut bytes))
{
Ok(_) => Report::parse(&bytes),
Err(error) if error.kind() == io::ErrorKind::NotFound => Report::default(),
Err(_) => Report {
integrity: "unreadable",
..Report::default()
},
}
}
pub(super) fn finish(
&self,
mut destination: File,
termination: &io::Result<Termination>,
) -> io::Result<()> {
destination.write_all(self.read().json(termination).as_bytes())
}
}
impl Drop for Journal {
fn drop(&mut self) {
let _ = fs::remove_file(self.path());
let _ = fs::remove_dir(&self.0);
}
}
pub(super) struct Events(File, Option<io::Error>);
impl Events {
pub(super) fn open(path: &Path) -> io::Result<Self> {
OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map(|file| Self(file, None))
}
pub(super) fn stage(&mut self, stage: &str) {
self.record(format_args!("{VERSION}\t{stage}"));
}
pub(super) fn failure(&mut self, error: &dyn std::error::Error) {
let message = error.to_string();
let end = message.floor_char_boundary(MAX_ERROR_BYTES);
let mut encoded = String::with_capacity(end * 2);
for byte in message[..end].bytes() {
write!(encoded, "{byte:02x}").unwrap();
}
self.record(format_args!(
"{VERSION}\tfailure\t{}\t{encoded}",
u8::from(end < message.len())
));
}
fn record(&mut self, arguments: std::fmt::Arguments<'_>) {
if self.1.is_none() {
self.1 = writeln!(self.0, "{arguments}").err();
}
}
pub(super) fn write_error(&self) -> Option<&io::Error> {
self.1.as_ref()
}
}
pub(super) enum Termination {
Exited(ExitStatus),
Deadline,
}
struct Report {
completed: usize,
error: Option<String>,
error_truncated: bool,
integrity: &'static str,
}
impl Default for Report {
fn default() -> Self {
Self {
completed: 0,
error: None,
error_truncated: false,
integrity: "complete",
}
}
}
impl Report {
fn parse(bytes: &[u8]) -> Self {
let mut report = Self::default();
let bounded = &bytes[..bytes.len().min(MAX_BYTES)];
for line in bounded.split_inclusive(|&byte| byte == b'\n') {
let Some(line) = line.strip_suffix(b"\n") else {
report.integrity = "truncated";
break;
};
if !std::str::from_utf8(line).is_ok_and(|line| report.record(line)) {
report.integrity = "malformed";
break;
}
}
if bytes.len() > MAX_BYTES {
report.integrity = "oversized";
}
report
}
fn record(&mut self, line: &str) -> bool {
let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else {
return false;
};
if self.error.is_some() {
return false;
}
if STAGES.get(self.completed) == Some(&record) {
self.completed += 1;
return true;
}
let Some((truncated, encoded)) = record
.strip_prefix("failure\t")
.and_then(|s| s.split_once('\t'))
else {
return false;
};
if !matches!(truncated, "0" | "1")
|| encoded.len() > MAX_ERROR_BYTES * 2
|| !encoded.len().is_multiple_of(2)
|| !encoded.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return false;
}
let (pairs, _) = encoded.as_bytes().as_chunks::<2>();
let Some(message) = pairs
.iter()
.map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
.collect::<Option<Vec<_>>>()
.and_then(|bytes| String::from_utf8(bytes).ok())
else {
return false;
};
self.error = Some(message);
self.error_truncated = truncated == "1";
true
}
fn json(&self, termination: &io::Result<Termination>) -> String {
let unwritable = matches!(termination, Ok(Termination::Exited(status))
if status.code() == Some(i32::from(JOURNAL_ERROR_EXIT)));
let integrity = if unwritable {
"unwritable"
} else {
self.integrity
};
let (outcome, status, detail) = match termination {
Ok(Termination::Deadline) => (
"timeout",
None,
Some("worker exceeded the wall deadline".into()),
),
Err(error) => ("unknown", None, Some(error.to_string())),
Ok(Termination::Exited(status)) if status.code() == Some(i32::from(WATCHDOG_EXIT)) => (
"timeout",
Some(status),
Some("worker watchdog expired".into()),
),
Ok(Termination::Exited(status)) if unwritable => (
"unknown",
Some(status),
Some("worker could not write its startup journal".into()),
),
Ok(Termination::Exited(status))
if status.success()
&& self.error.is_none()
&& self.completed == STAGES.len()
&& self.integrity == "complete" =>
{
("verified", Some(status), None)
}
Ok(Termination::Exited(status))
if status.code().is_some() && !status.success() && self.error.is_some() =>
{
("stage_failure", Some(status), None)
}
Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => {
("early_exit", Some(status), Some(status.to_string()))
}
Ok(Termination::Exited(status)) => ("unknown", Some(status), Some(status.to_string())),
};
let stages = &STAGES[..self.completed];
let records = stages
.iter()
.map(|stage| format!(r#"{{"schema_version":{VERSION},"stage":"{stage}"}}"#))
.collect::<Vec<_>>()
.join(",");
let last = json_string(stages.last().copied());
let error = json_string(self.error.as_deref());
let detail = json_string(detail.as_deref());
let code = status
.and_then(|status| status.code())
.map_or("null".into(), |code| code.to_string());
format!(
"{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n",
integrity, self.error_truncated
)
}
}
fn json_string(value: Option<&str>) -> String {
let Some(value) = value else {
return String::from("null");
};
let mut escaped = String::from("\"");
for ch in value.chars() {
match ch {
'"' => escaped.push_str("\\\""),
'\\' => escaped.push_str("\\\\"),
'\0'..='\u{1f}' => write!(escaped, "\\u{:04x}", u32::from(ch)).unwrap(),
_ => escaped.push(ch),
}
}
escaped.push('"');
escaped
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
use std::time::{Duration, Instant};
#[test]
fn journal_write_error_surfaces_in_report() {
use std::os::unix::process::ExitStatusExt;
let journal = Journal::create().unwrap();
fs::write(journal.path(), b"1\tparsed\n").unwrap();
let mut events = Events(File::open(journal.path()).unwrap(), None);
events.stage("mapped");
assert!(events.write_error().is_some());
let status = ExitStatus::from_raw(i32::from(JOURNAL_ERROR_EXIT) << 8);
let result = journal.read().json(&Ok(Termination::Exited(status)));
assert!(
result.contains(r#""record_integrity":"unwritable""#),
"{result}"
);
assert!(
result.contains(r#""last_completed_stage":"parsed""#),
"{result}"
);
}
#[test]
fn terminal_failure_keeps_signal_detail_after_all_stages() {
use std::os::unix::process::ExitStatusExt;
let journal = Journal::create().unwrap();
let mut events = Events::open(&journal.path()).unwrap();
for stage in STAGES {
events.stage(stage);
}
events.failure(&io::Error::other("late error"));
let report = journal.read();
assert_eq!(report.integrity, "complete");
let result = report.json(&Ok(Termination::Exited(ExitStatus::from_raw(15))));
assert!(result.contains(r#""outcome":"unknown""#), "{result}");
assert!(result.contains(r#""error":"late error""#), "{result}");
assert!(result.contains("signal: 15"), "{result}");
}
#[test]
fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() {
for (script, limit, outcome, code) in [
("exit 9", Duration::from_secs(2), "early_exit", "9"),
("exit 124", Duration::from_secs(2), "timeout", "124"),
("kill -TERM $$", Duration::from_secs(2), "unknown", "null"),
(
"exec sleep 5",
Duration::from_millis(250),
"timeout",
"null",
),
] {
let journal = Journal::create().unwrap();
let started = Instant::now();
let child = Command::new("/bin/sh")
.args([
"-c",
&format!("printf '1\\tparsed\\n' > \"$1\"; {script}"),
"worker",
])
.arg(journal.path())
.spawn()
.unwrap();
let termination = super::super::supervise(child, started, limit);
let report = journal.read().json(&termination);
assert!(
report.contains(&format!(r#""outcome":"{outcome}""#)),
"{report}"
);
assert!(
report.contains(&format!(r#""worker_exit_code":{code}"#)),
"{report}"
);
assert!(
report.contains(r#""last_completed_stage":"parsed""#),
"{report}"
);
}
}
#[test]
fn invalid_records_keep_only_the_valid_prefix() {
let mut oversized = b"1\tparsed\n1\tmapped".to_vec();
oversized.resize(MAX_BYTES + 1, b'x');
for (bytes, integrity) in [
(&b"1\tparsed\n1\tmapped"[..], "truncated"),
(&b"1\tparsed\n1\tentry\n1\tmapped\n"[..], "malformed"),
(&b"1\tparsed\n1\tfailure\t0\tqq\n"[..], "malformed"),
(oversized.as_slice(), "oversized"),
] {
let journal = Journal::create().unwrap();
fs::write(journal.path(), bytes).unwrap();
let report = journal.read();
assert_eq!(report.completed, 1);
assert_eq!(report.integrity, integrity);
assert!(report.error.is_none());
}
}
#[test]
fn failure_preserves_original_context_with_bounded_utf8() {
let journal = Journal::create().unwrap();
let mut events = Events::open(&journal.path()).unwrap();
events.stage("parsed");
let message = format!("line\nwith \"quote\" and \\{}", "é".repeat(MAX_ERROR_BYTES));
events.failure(&io::Error::other(&message[..]));
let report = journal.read();
assert_eq!(
report.error.as_deref(),
Some(&message[..message.floor_char_boundary(MAX_ERROR_BYTES)])
);
assert!(report.error_truncated);
let json = report.json(&Ok(Termination::Deadline));
assert!(
json.contains(r#"line\u000awith \"quote\" and \\"#),
"{json}"
);
}
}
+109
View File
@@ -0,0 +1,109 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::process::Command;
const STARTUP_STAGES: &[&str] = &[
"parsed",
"mapped",
"relocated",
"imports_bound",
"tls_completed",
"entry",
];
#[test]
fn trusted_fixture_preserves_step_failure() {
let report = run_fixture("1", false);
assert!(report.contains(r#""outcome":"stage_failure""#), "{report}");
assert!(
report.contains(r#""last_completed_stage":"entry""#),
"{report}"
);
assert!(report.contains("step budget exhausted"), "{report}");
assert_stages(&report, STARTUP_STAGES);
assert!(!report.contains(r#""stage":"exit""#), "{report}");
}
#[test]
#[ignore = "requires a native Metal device with Apple family 7 capabilities"]
fn trusted_fixture_reports_verified_progress() {
let report = run_fixture("100", true);
assert!(report.contains(r#""outcome":"verified""#), "{report}");
assert!(
report.contains(r#""last_completed_stage":"framebuffer""#),
"{report}"
);
let stages = [STARTUP_STAGES, &["exit", "framebuffer"]].concat();
assert_stages(&report, &stages);
}
fn run_fixture(steps: &str, success: bool) -> String {
let path = std::env::temp_dir().join(format!(
"betterxen-report-test-{}-{steps}.json",
std::process::id()
));
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let output = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args([
"run",
"--experimental",
"--pe",
fixture,
"--max-steps",
steps,
"--startup-report",
])
.arg(&path)
.output()
.unwrap();
let report = std::fs::read_to_string(&path);
if report.is_ok() {
std::fs::remove_file(&path).unwrap();
}
assert_eq!(output.status.success(), success, "{output:?}, {report:?}");
report.unwrap()
}
fn assert_stages(report: &str, stages: &[&str]) {
assert!(report.contains(r#""schema_version":1"#), "{report}");
let mut remaining = report;
for stage in stages {
remaining = remaining
.split_once(&format!(r#""stage":"{stage}""#))
.unwrap()
.1;
}
}
#[test]
fn existing_report_path_prevents_worker_launch() {
let path = std::env::temp_dir().join(format!(
"betterxen-report-existing-{}.json",
std::process::id()
));
std::fs::write(&path, "previous report").unwrap();
let result = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args([
"run",
"--experimental",
"--pe",
"missing-fixture",
"--startup-report",
])
.arg(&path)
.output()
.unwrap();
let contents = std::fs::read_to_string(&path).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(contents, "previous report");
assert!(!result.status.success());
let stderr = String::from_utf8(result.stderr).unwrap();
assert!(
stderr.contains("could not create startup report"),
"{stderr}"
);
assert!(!stderr.contains("No such file or directory"), "{stderr}");
}
+4 -2
View File
@@ -14,8 +14,9 @@
//! refused, with exit status 1, unless both runs used the same host, workload,
//! build settings and sample counts.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! Report, comparison and percentile tests run in ordinary workspace tests
//! through `tests/dbt_benchmark_report.rs`. The benchmark target itself disables
//! Cargo's test harness. To run its tests directly, build with
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
//! and run the executable named by the benchmark's compiler-artifact message.
@@ -982,6 +983,7 @@ mod tests {
blocks_compiled: 626,
cache_hits: 0,
cache_misses: 626,
blocks_invalidated: 0,
native_bytes_emitted: 245_168,
dbt_dispatches: 626,
instructions_executed: 10_002,
+87
View File
@@ -116,6 +116,93 @@ service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
ref sysinfoapi.h GetSystemTimeAsFileTime
test system_time_comes_from_the_injected_clock
# Standard streams and formatted output for a hosted C program. Output to
# stdout and stderr is captured, and a stream from fopen is a file. A pointer
# that is no stream, reading stdin, and floating-point and wide conversions
# stop the guest with the runtime-limit fault.
service ucrtbase.dll __acrt_iob_func(index: u32) -> ptr
handler standard_stream
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails stops the guest for an index above 2 or when the streams cannot be allocated
ref corecrt_wstdio.h __acrt_iob_func
test standard_streams_are_three_stable_file_objects
service ucrtbase.dll __stdio_common_vfprintf(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32
handler vfprintf
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled
ref corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax
test formatted_output_reaches_the_captured_standard_streams
service ucrtbase.dll fwrite(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64
handler fwrite
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails 0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
ref stdio.h fwrite
test fwrite_and_fputs_write_to_the_captured_standard_streams
service ucrtbase.dll fputs(text: ptr, stream: ptr) -> i32
handler fputs
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
ref stdio.h fputs
test fwrite_and_fputs_write_to_the_captured_standard_streams
service ucrtbase.dll fflush(stream: ptr) -> i32
handler fflush
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails stops the guest for a pointer that is no stream
ref stdio.h fflush
test fflush_and_setvbuf_return_their_documented_results
service ucrtbase.dll setvbuf(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32
handler setvbuf
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream
ref stdio.h setvbuf
test fflush_and_setvbuf_return_their_documented_results
# Files for a hosted C program, on the in-memory drive the handle services use.
service ucrtbase.dll fopen(name: ptr, mode: ptr) -> ptr
handler fopen
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM
ref stdio.h fopen
test a_file_written_through_a_stream_reads_back_line_by_line
service ucrtbase.dll fclose(stream: ptr) -> i32
handler fclose
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream
ref stdio.h fclose
test a_file_written_through_a_stream_reads_back_line_by_line
service ucrtbase.dll fgets(buffer: ptr, count: i32, stream: ptr) -> ptr
handler fgets
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream
ref stdio.h fgets
test fgets_reads_lines_within_its_count
service ucrtbase.dll perror(message: ptr) -> void
handler perror
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails never
ref stdio.h perror
test perror_writes_the_message_and_the_error_text_to_stderr
service kernel32.dll GetLastError() -> u32
handler get_last_error
status partial
+33 -10
View File
@@ -633,15 +633,22 @@ impl Arm64Assembler {
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
}
/// Load a full 64-bit constant into register Xd with the fewest MOVZ or
/// MOVN plus MOVK instructions: one for each halfword that differs from
/// the background the first instruction leaves, and always at least one.
/// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used
/// when more halfwords are 0xFFFF than zero.
/// Load a full 64-bit constant into Xd with the fewest wide moves.
/// A 32-bit MOVN leaves one low halfword set to 0xFFFF and zero-extends
/// the result into Xd. For other values, select a 64-bit MOVZ or MOVN
/// background and use MOVK for the remaining halfwords.
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
let zeros = halves.iter().filter(|&&h| h == 0).count();
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
// With only the top two halfwords zero, a 32-bit MOVN saves one
// instruction when either of the lower halfwords is all ones.
if zeros == 2 && ones != 0 && val >> 32 == 0 {
let index = usize::from(halves[1] != u16::MAX);
let imm16 = u32::from(!halves[index]);
self.emit(0x1280_0000 | ((index as u32) << 21) | (imm16 << 5) | u32::from(xd & 0x1f));
return;
}
let background = if ones > zeros { 0xffff } else { 0 };
// The first halfword that differs from the background, or halfword 0
// when none does (val is 0 or all ones).
@@ -883,12 +890,14 @@ mod tests {
}
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
const IMMEDIATE_EDGES: [u64; 16] = [
const IMMEDIATE_EDGES: [u64; 18] = [
0,
1,
0xffff,
0x1_0000,
0x8000_0000,
0xffff_1234,
0x1234_ffff,
0xffff_ffff,
0x1_0000_0000,
0x1234_0000_0000_0000,
@@ -904,10 +913,13 @@ mod tests {
#[test]
fn immediate_sequences_match_llvm_encodings() {
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
// A64 words from llvm-mc and Apple Clang's integrated assembler.
let cases: &[(u64, &[u32])] = &[
(0, &[0xd2800000]), // movz x0, #0
(u64::MAX, &[0x92800000]), // movn x0, #0
(0xffff_1234, &[0x129db960]), // movn w0, #0xedcb
(0x1234_ffff, &[0x12bdb960]), // movn w0, #0xedcb, lsl #16
(0xffff_ffff, &[0x12800000]), // movn w0, #0
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
@@ -930,9 +942,16 @@ mod tests {
);
}
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
/// A 32-bit MOVN can write a zero-extended value if its low word's
/// complement fits in a single halfword. Otherwise count the halfwords
/// that differ from either 64-bit initializer's background.
fn shortest_wide_move(value: u64) -> usize {
if let Ok(low) = u32::try_from(value) {
let complement = !low;
if complement <= u32::from(u16::MAX) || complement.trailing_zeros() >= 16 {
return 1;
}
}
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
let not_zero = halves.clone().filter(|&h| h != 0).count();
let not_ones = halves.filter(|&h| h != 0xffff).count();
@@ -964,9 +983,13 @@ mod tests {
for value in values {
for register in [X0, X9] {
let mut asm = Arm64Assembler::new();
// Seed the destination so a W-register load must clear the high bits.
asm.movn_64(register, 0, 0);
// Assembler offsets count 32-bit instruction words.
let start = asm.current_offset();
asm.load_imm_64(register, value);
assert_eq!(
asm.instructions().len(),
asm.current_offset() - start,
shortest_wide_move(value),
"{value:#x}"
);
+278 -17
View File
@@ -15,7 +15,7 @@ use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment, decode};
use crate::x86_exec;
use crate::x86_table::{FORMS, Op};
use std::collections::HashMap;
use std::{collections::HashMap, sync::Arc};
const MAX_BLOCK_INSTRUCTIONS: usize = 16;
@@ -29,6 +29,9 @@ pub struct DbtMetrics {
pub blocks_compiled: usize,
pub cache_hits: usize,
pub cache_misses: usize,
/// Cached blocks discarded because their guest bytes or executable mappings
/// changed. Each also counts as a cache miss.
pub blocks_invalidated: usize,
pub native_bytes_emitted: usize,
pub dbt_dispatches: usize,
pub instructions_executed: usize,
@@ -37,11 +40,42 @@ pub struct DbtMetrics {
pub service_calls: usize,
}
/// A translated block and its executable-memory generation.
///
/// Guest stores into executable memory (Intel SDM Vol. 3A 11.6), executable
/// mapping changes and another address space invalidate the retained token.
/// An unchanged token takes a constant-time check. After a generation or address
/// space change, bytes and execute permissions are revalidated once before an
/// identical translation may be reused in that generation.
/// Validation occurs at dispatch boundaries: a store into the currently running
/// block's later instructions still needs a separate dispatch-boundary design.
struct CachedBlock {
code: *const u8,
generation: Arc<()>,
start: u64,
source: Box<[u8]>,
}
impl CachedBlock {
fn is_current(&mut self, memory: &GuestMemory) -> bool {
if memory.code_is_current(&self.generation) {
return true;
}
if !self.source.iter().enumerate().all(|(offset, &byte)| {
matches!(memory.fetch_instruction_byte(self.start.wrapping_add(offset as u64)), Ok(current) if current == byte)
}) {
return false;
}
self.generation = memory.code_generation();
true
}
}
/// Dynamic Binary Translator and native execution runtime.
pub struct DbtEngine {
jit: JitMemory,
block_cache: HashMap<u64, *const u8>,
limited_block_cache: HashMap<(u64, usize), *const u8>,
block_cache: HashMap<u64, CachedBlock>,
limited_block_cache: HashMap<(u64, usize), CachedBlock>,
assembler: Arm64Assembler,
/// Decoded instructions that emitted helper calls point into.
decoded_blocks: Vec<Box<[Insn]>>,
@@ -245,26 +279,34 @@ impl DbtEngine {
block_limit: usize,
) -> Result<*const u8, ExitReason> {
if block_limit == MAX_BLOCK_INSTRUCTIONS {
if let Some(&fn_ptr) = self.block_cache.get(&rip) {
self.metrics.cache_hits += 1;
return Ok(fn_ptr);
if let Some(cached) = self.block_cache.get_mut(&rip) {
if cached.is_current(memory) {
self.metrics.cache_hits += 1;
return Ok(cached.code);
}
self.metrics.blocks_invalidated += 1;
}
self.metrics.cache_misses += 1;
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
self.block_cache.insert(rip, compiled_ptr);
return Ok(compiled_ptr);
let compiled = self.compile_block(rip, memory, block_limit)?;
let code = compiled.code;
self.block_cache.insert(rip, compiled);
return Ok(code);
}
// Keep budget-limited blocks separate so they cannot shorten a later run.
let key = (rip, block_limit);
if let Some(&fn_ptr) = self.limited_block_cache.get(&key) {
self.metrics.cache_hits += 1;
return Ok(fn_ptr);
if let Some(cached) = self.limited_block_cache.get_mut(&key) {
if cached.is_current(memory) {
self.metrics.cache_hits += 1;
return Ok(cached.code);
}
self.metrics.blocks_invalidated += 1;
}
self.metrics.cache_misses += 1;
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
self.limited_block_cache.insert(key, compiled_ptr);
Ok(compiled_ptr)
let compiled = self.compile_block(rip, memory, block_limit)?;
let code = compiled.code;
self.limited_block_cache.insert(key, compiled);
Ok(code)
}
fn compile_block(
@@ -272,7 +314,7 @@ impl DbtEngine {
start_rip: u64,
memory: &GuestMemory,
block_limit: usize,
) -> Result<*const u8, ExitReason> {
) -> Result<CachedBlock, ExitReason> {
// Decode the whole block first: lowering needs to know whether a later
// instruction observes the flags an earlier one produces.
let mut decoded = Vec::with_capacity(block_limit);
@@ -351,8 +393,17 @@ impl DbtEngine {
.map_err(|_| ExitReason::JitCacheExhausted)?;
self.metrics.blocks_compiled += 1;
self.metrics.native_bytes_emitted += asm.instructions().len() * 4;
let source = (0..rip.wrapping_sub(start_rip))
.map(|offset| memory.fetch_instruction_byte(start_rip.wrapping_add(offset)))
.collect::<Result<Box<[u8]>, _>>()
.map_err(ExitReason::MemoryFault)?;
self.decoded_blocks.push(insns);
Ok(emitted)
Ok(CachedBlock {
code: emitted,
generation: memory.code_generation(),
start: start_rip,
source,
})
}
}
@@ -1569,6 +1620,216 @@ mod tests {
)
}
/// `mov eax, imm32; hlt`, with the immediate at `ENTRY + 1`.
fn mov_eax(imm: u8) -> [u8; 6] {
[0xB8, imm, 0x00, 0x00, 0x00, 0xF4]
}
fn writable_fixture(code: &[u8]) -> (DbtEngine, GuestMemory) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
ENTRY,
code.len(),
MemoryPermissions::READ_WRITE_EXECUTE,
code,
)
.unwrap();
(DbtEngine::new(64 * 1024).unwrap(), memory)
}
fn rax_after_run(engine: &mut DbtEngine, memory: &mut GuestMemory, limit: usize) -> u64 {
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, memory, limit);
assert_eq!(result.exit_reason, ExitReason::Halt);
cpu.get(Register::Rax)
}
#[test]
fn unchanged_code_stays_cached() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(engine.metrics.blocks_compiled, 1);
assert_eq!(engine.metrics.cache_hits, 1);
assert_eq!(engine.metrics.blocks_invalidated, 0);
}
#[test]
fn data_writes_and_allocations_do_not_invalidate_executable_code() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
memory
.map_region(ENTRY + 0x1000, 8, MemoryPermissions::READ_WRITE)
.unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
for value in 0..64 {
memory.write_u64(ENTRY + 0x1000, value).unwrap();
let allocation = memory
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE)
.unwrap();
assert!(memory.release_virtual_allocation(allocation));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
}
assert_eq!(engine.metrics.blocks_compiled, 1);
assert_eq!(engine.metrics.cache_hits, 64);
assert_eq!(engine.metrics.blocks_invalidated, 0);
}
#[test]
fn cloned_address_spaces_diverge_when_executable_code_changes() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
let mut cloned = memory.clone();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
memory.write_u8(ENTRY + 1, 7).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 7);
// A deep clone shares the proven identical executable snapshot. The
// write in the original space must still force retranslation there.
assert_eq!(engine.metrics.blocks_compiled, 2);
assert_eq!(engine.metrics.cache_hits, 2);
}
#[test]
fn executable_bypass_writes_invalidate_cached_translations() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
ENTRY,
8,
MemoryPermissions::READ_EXECUTE,
&[0xB8, 1, 0, 0, 0, 0xF4, 0, 0],
)
.unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert!(memory.write_u32(ENTRY + 1, 9).is_err());
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(engine.metrics.blocks_invalidated, 0);
memory
.write_u64_bypass(ENTRY, u64::from_le_bytes([0xB8, 2, 0, 0, 0, 0xF4, 0, 0]))
.unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
memory.write_u32_bypass(ENTRY + 1, 3).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 3);
assert_eq!(engine.metrics.blocks_invalidated, 2);
}
#[test]
fn executable_writes_crossing_regions_invalidate_cached_translations() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, 2, MemoryPermissions::READ_WRITE_EXECUTE, &[0xB8, 1])
.unwrap();
memory
.map_region_with_data(
ENTRY + 2,
4,
MemoryPermissions::READ_WRITE_EXECUTE,
&[0, 0, 0, 0xF4],
)
.unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
memory.write_u32(ENTRY + 1, 9).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 9);
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn remapped_non_executable_memory_cannot_reuse_a_translation() {
let mut memory = GuestMemory::new();
let base = memory
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE_EXECUTE)
.unwrap();
memory.write_bytes(base, &mov_eax(1)).unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let mut cpu = CpuState::new(base, 0);
assert_eq!(
engine.run(&mut cpu, &mut memory, 16).exit_reason,
ExitReason::Halt
);
assert!(memory.release_virtual_allocation(base));
assert_eq!(
memory.map_virtual_allocation(base, 4096, MemoryPermissions::READ_WRITE),
Ok(base)
);
memory.write_bytes(base, &mov_eax(1)).unwrap();
let mut cpu = CpuState::new(base, 0);
assert!(matches!(
engine.run(&mut cpu, &mut memory, 16).exit_reason,
ExitReason::MemoryFault(_)
));
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn repeated_code_rewrites_report_bounded_jit_cache_exhaustion() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
for value in 0..16_384u32 {
memory.write_u32(ENTRY + 1, value).unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 16);
if result.exit_reason == ExitReason::JitCacheExhausted {
return;
}
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(cpu.get(Register::Rax), u64::from(value));
}
panic!("rewritten blocks unexpectedly avoided the bounded JIT capacity");
}
#[test]
fn rewritten_code_is_translated_again() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
memory.write_bytes(ENTRY + 1, &[2]).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
assert_eq!(engine.metrics.blocks_compiled, 2);
assert_eq!(engine.metrics.blocks_invalidated, 1);
// The new translation is cached in turn.
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
assert_eq!(engine.metrics.blocks_compiled, 2);
}
#[test]
fn rewriting_the_last_byte_of_a_block_is_detected() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
// HLT becomes NOP, so the block now runs off the end of the mapping.
memory.write_bytes(ENTRY + 5, &[0x90]).unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 16);
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn budget_limited_block_is_checked_against_current_bytes() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
for expected in [1, 3] {
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(cpu.get(Register::Rax), expected);
memory.write_bytes(ENTRY + 1, &[3]).unwrap();
}
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn another_address_space_does_not_reuse_a_block() {
let (mut engine, mut first) = writable_fixture(&mov_eax(1));
let (_, mut second) = writable_fixture(&mov_eax(7));
assert_eq!(rax_after_run(&mut engine, &mut first, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut second, 16), 7);
let mut unmapped = GuestMemory::new();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut unmapped, 16);
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
}
#[test]
fn cached_block_obeys_remaining_budget() {
let code = [
+57 -3
View File
@@ -5,7 +5,7 @@
//! Provides isolated, page-aligned guest virtual memory with permission checking
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
use std::{fmt, ops::Range};
use std::{fmt, ops::Range, sync::Arc};
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
@@ -119,8 +119,13 @@ impl MappedRegion {
}
/// Guest virtual memory address space.
#[derive(Default, Clone)]
#[derive(Default)]
pub struct GuestMemory {
// A retained token identifies a validated executable snapshot. Independent
// address spaces get distinct tokens. A deep clone may share its identical
// snapshot; an executable mutation detaches only the changed address space.
// Cached translations retain tokens, preventing allocator-address reuse.
executable_generation: Arc<()>,
regions: Vec<MappedRegion>,
private_heaps: std::collections::BTreeSet<u64>,
private_heap_serial: u64,
@@ -130,7 +135,32 @@ pub struct GuestMemory {
std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>,
}
impl Clone for GuestMemory {
fn clone(&self) -> Self {
Self {
executable_generation: Arc::clone(&self.executable_generation),
regions: self.regions.clone(),
private_heaps: self.private_heaps.clone(),
private_heap_serial: self.private_heap_serial,
crt_errno: self.crt_errno.clone(),
callback_frames: self.callback_frames.clone(),
}
}
}
impl GuestMemory {
pub(crate) fn code_generation(&self) -> Arc<()> {
Arc::clone(&self.executable_generation)
}
pub(crate) fn code_is_current(&self, generation: &Arc<()>) -> bool {
Arc::ptr_eq(&self.executable_generation, generation)
}
fn invalidate_executable_code(&mut self) {
self.executable_generation = Arc::new(());
}
/// Create a new empty guest address space.
pub fn new() -> Self {
Self::default()
@@ -197,6 +227,9 @@ impl GuestMemory {
allocation,
});
self.regions.sort_by_key(|r| r.base);
if permissions.execute && size != 0 {
self.invalidate_executable_code();
}
Ok(())
}
@@ -256,8 +289,14 @@ impl GuestMemory {
if !self.private_heaps.remove(&heap) {
return false;
}
let executable = self.regions.iter().any(|region| {
region.allocation == AllocationKind::Heap(heap) && region.permissions.execute
});
self.regions
.retain(|region| region.allocation != AllocationKind::Heap(heap));
if executable {
self.invalidate_executable_code();
}
true
}
@@ -377,10 +416,14 @@ impl GuestMemory {
if size < previous {
region.data.shrink_to_fit();
}
let executable = region.permissions.execute;
if destination != base {
region.base = destination;
self.regions.sort_by_key(|region| region.base);
}
if executable && (size != previous || destination != base) {
self.invalidate_executable_code();
}
Ok(destination)
}
@@ -420,7 +463,10 @@ impl GuestMemory {
else {
return false;
};
self.regions.remove(index);
let removed = self.regions.remove(index);
if removed.permissions.execute && !removed.data.is_empty() {
self.invalidate_executable_code();
}
true
}
@@ -510,11 +556,16 @@ impl GuestMemory {
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
let mut executable = false;
for (index, offset, take) in self.resolve(address, src.len(), required)? {
executable |= take != 0 && self.regions[index].permissions.execute;
self.regions[index].data[offset..offset + take]
.copy_from_slice(&src[done..done + take]);
done += take;
}
if executable {
self.invalidate_executable_code();
}
Ok(())
}
@@ -524,6 +575,9 @@ impl GuestMemory {
&& self.regions[index].permissions.write
{
self.regions[index].data[range].copy_from_slice(src);
if !src.is_empty() && self.regions[index].permissions.execute {
self.invalidate_executable_code();
}
return Ok(());
}
self.write_checked(address, src, Some("write"))
+205 -1
View File
@@ -8,7 +8,7 @@ use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};
use crate::services::{ServicesState, handlers};
use std::sync::Arc;
pub static SERVICES: [ServiceMetadata; 37] = [
pub static SERVICES: [ServiceMetadata; 47] = [
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetProcessPriorityBoost",
@@ -141,6 +141,116 @@ pub static SERVICES: [ServiceMetadata; 37] = [
reference: "sysinfoapi.h GetSystemTimeAsFileTime",
tests: &["system_time_comes_from_the_injected_clock"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__acrt_iob_func",
parameters: &[Parameter { name: "index", kind: "u32" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "stops the guest for an index above 2 or when the streams cannot be allocated",
reference: "corecrt_wstdio.h __acrt_iob_func",
tests: &["standard_streams_are_three_stable_file_objects"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__stdio_common_vfprintf",
parameters: &[Parameter { name: "options", kind: "u64" }, Parameter { name: "stream", kind: "ptr" }, Parameter { name: "format", kind: "ptr" }, Parameter { name: "locale", kind: "ptr" }, Parameter { name: "arguments", kind: "ptr" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "-1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled",
reference: "corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax",
tests: &["formatted_output_reaches_the_captured_standard_streams"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fwrite",
parameters: &[Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "count", kind: "u64" }, Parameter { name: "stream", kind: "ptr" }],
result: "u64",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream",
reference: "stdio.h fwrite",
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fputs",
parameters: &[Parameter { name: "text", kind: "ptr" }, Parameter { name: "stream", kind: "ptr" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream",
reference: "stdio.h fputs",
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fflush",
parameters: &[Parameter { name: "stream", kind: "ptr" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "stops the guest for a pointer that is no stream",
reference: "stdio.h fflush",
tests: &["fflush_and_setvbuf_return_their_documented_results"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "setvbuf",
parameters: &[Parameter { name: "stream", kind: "ptr" }, Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "mode", kind: "i32" }, Parameter { name: "size", kind: "u64" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "-1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream",
reference: "stdio.h setvbuf",
tests: &["fflush_and_setvbuf_return_their_documented_results"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fopen",
parameters: &[Parameter { name: "name", kind: "ptr" }, Parameter { name: "mode", kind: "ptr" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM",
reference: "stdio.h fopen",
tests: &["a_file_written_through_a_stream_reads_back_line_by_line"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fclose",
parameters: &[Parameter { name: "stream", kind: "ptr" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream",
reference: "stdio.h fclose",
tests: &["a_file_written_through_a_stream_reads_back_line_by_line"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fgets",
parameters: &[Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "count", kind: "i32" }, Parameter { name: "stream", kind: "ptr" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream",
reference: "stdio.h fgets",
tests: &["fgets_reads_lines_within_its_count"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "perror",
parameters: &[Parameter { name: "message", kind: "ptr" }],
result: "void",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "never",
reference: "stdio.h perror",
tests: &["perror_writes_the_message_and_the_error_text_to_stderr"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetLastError",
@@ -518,6 +628,100 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
Ok(0)
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__acrt_iob_func", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u32(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::standard_stream(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__stdio_common_vfprintf", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let a2 = call.u64(2)?;
let a3 = call.u64(3)?;
let a4 = call.u64(4)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::vfprintf(&mut context, a0, a1, a2, a3, a4)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fwrite", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let a2 = call.u64(2)?;
let a3 = call.u64(3)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::fwrite(&mut context, a0, a1, a2, a3)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fputs", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::fputs(&mut context, a0, a1)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fflush", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::fflush(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "setvbuf", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let a2 = call.i32(2)?;
let a3 = call.u64(3)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::setvbuf(&mut context, a0, a1, a2, a3)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fopen", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::fopen(&mut context, a0, a1)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fclose", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::fclose(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fgets", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.i32(1)?;
let a2 = call.u64(2)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::fgets(&mut context, a0, a1, a2)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "perror", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let () = handlers::perror(&mut context, a0)?;
Ok(0)
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
+149
View File
@@ -12,7 +12,10 @@
mod crt;
mod crt_arguments;
mod crt_callbacks;
mod crt_files;
mod crt_format;
mod crt_startup;
mod crt_streams;
mod events;
mod files;
mod gdk_queue;
@@ -28,6 +31,7 @@ mod winsock;
use crate::runtime::HResult;
pub use crt_arguments::{MAX_PROGRAM_ARGUMENT_BYTES, ProgramArgumentsError};
pub use crt_streams::MAX_CAPTURED_OUTPUT;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
@@ -205,6 +209,7 @@ pub struct ServicesState {
last_errors: Mutex<BTreeMap<u64, u32>>,
crt_arguments: Mutex<crt_arguments::CrtArguments>,
synch: Mutex<synch::Synch>,
crt_streams: Mutex<crt_streams::StandardStreams>,
pub(crate) threads: Mutex<threads::ThreadTable>,
pub(crate) hooks: Arc<threads::SchedulerHooks>,
/// Functions registered with `atexit`, run in reverse order by `_cexit`.
@@ -235,6 +240,7 @@ impl ServicesState {
last_errors: Mutex::default(),
crt_arguments: Mutex::default(),
synch: Mutex::default(),
crt_streams: Mutex::default(),
threads: Mutex::default(),
hooks: Arc::default(),
atexit: Mutex::default(),
@@ -348,6 +354,23 @@ impl ServicesState {
status
}
/// Everything the guest has written to `stdout`, as the bytes a text-mode
/// stream hands the operating system: each line feed the program wrote is
/// a carriage return and a line feed here.
pub fn standard_output(&self) -> Vec<u8> {
self.crt_streams().output().to_vec()
}
/// Everything the guest has written to `stderr`, in the same form as
/// [`Self::standard_output`].
pub fn standard_error(&self) -> Vec<u8> {
self.crt_streams().error().to_vec()
}
fn crt_streams(&self) -> std::sync::MutexGuard<'_, crt_streams::StandardStreams> {
self.crt_streams.lock().expect("standard streams")
}
/// Read the last-error value for a guest thread's TEB.
pub fn last_error(&self, teb: u64) -> u32 {
self.last_errors
@@ -915,6 +938,132 @@ pub(crate) mod handlers {
.map_err(ExitReason::MemoryFault)
}
// Streams, files and formatted output (#400, #402). `crt_streams.rs` and
// `crt_files.rs` hold the rules; a failure that has an errno value sets it
// here. The stream state is always locked before the object state.
fn or_errno<T>(
context: &mut ServiceContext<'_>,
outcome: crt_streams::Outcome<T>,
) -> Outcome<T> {
match outcome? {
Ok(value) => Ok(value),
Err(crt_streams::Failed(value, errno)) => {
crt::set_errno(context.memory, context.teb, errno)?;
Ok(value)
}
}
}
pub fn standard_stream(context: &mut ServiceContext<'_>, index: u32) -> Outcome<u64> {
context.state.crt_streams().file(context.memory, index)
}
pub fn vfprintf(
context: &mut ServiceContext<'_>,
options: u64,
stream: u64,
format: u64,
locale: u64,
arguments: u64,
) -> Outcome<i32> {
let outcome = {
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.print(
context.memory,
&mut drive,
options,
stream,
format,
locale,
arguments,
)
};
or_errno(context, outcome)
}
pub fn fwrite(
context: &mut ServiceContext<'_>,
buffer: u64,
size: u64,
count: u64,
stream: u64,
) -> Outcome<u64> {
let outcome = {
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.write_items(context.memory, &mut drive, buffer, size, count, stream)
};
or_errno(context, outcome)
}
pub fn fputs(context: &mut ServiceContext<'_>, text: u64, stream: u64) -> Outcome<i32> {
let outcome = {
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.put_string(context.memory, &mut drive, text, stream)
};
or_errno(context, outcome)
}
pub fn fflush(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
context.state.crt_streams().flush(stream)
}
pub fn setvbuf(
context: &mut ServiceContext<'_>,
stream: u64,
_buffer: u64,
mode: i32,
size: u64,
) -> Outcome<i32> {
let outcome = context.state.crt_streams().set_buffer(stream, mode, size);
or_errno(context, outcome)
}
pub fn fopen(context: &mut ServiceContext<'_>, name: u64, mode: u64) -> Outcome<u64> {
let outcome = {
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.open(context.memory, &mut drive, name, mode)
};
or_errno(context, outcome)
}
pub fn fclose(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
let outcome = context.state.crt_streams().close(context.memory, stream);
or_errno(context, outcome)
}
pub fn fgets(
context: &mut ServiceContext<'_>,
buffer: u64,
count: i32,
stream: u64,
) -> Outcome<u64> {
let outcome = {
let mut streams = context.state.crt_streams();
let drive = context.state.objects.lock().expect("guest object state");
streams.get_line(context.memory, &drive, buffer, count, stream)
};
or_errno(context, outcome)
}
pub fn perror(context: &mut ServiceContext<'_>, message: u64) -> Outcome<()> {
let address = context
.memory
.crt_errno_address(context.teb)
.map_err(ExitReason::MemoryFault)?;
let errno = context
.memory
.read_u32(address)
.map_err(ExitReason::MemoryFault)?;
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.report(context.memory, &mut drive, message, errno)
}
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
Ok(context.state.last_error(context.teb))
}
@@ -400,6 +400,57 @@ impl CallbackTask for ExitFunctions {
}
}
/// `exit`: calls the functions registered with `atexit` and `_crt_atexit`,
/// most recently registered first, and then ends the guest process.
///
/// It takes one function at a time from the shared list. A function that is
/// registered while `exit` runs is therefore called next, before the older
/// ones that have not run yet, as ISO C requires (7.22.4.2, 7.22.4.4). A
/// registered function that calls `exit` again, which ISO C leaves undefined,
/// starts a second task on the same list: the remaining functions run once
/// each and the process ends with the later status.
struct Exit {
state: Arc<ServicesState>,
status: u32,
}
impl Exit {
fn next(&mut self) -> Result<CallbackStep, ExitReason> {
let function = self
.state
.atexit
.lock()
.expect("guest atexit functions")
.pop();
match function {
Some(entry) => Ok(CallbackStep::Call {
entry,
args: [0; 4],
}),
None => Err(ExitReason::ProcessExit(
self.state.exit_process(self.status),
)),
}
}
fn start(mut self) -> Result<CallbackStart, ExitReason> {
match self.next()? {
CallbackStep::Call { entry, args } => Ok(CallbackStart::Call {
task: Box::new(self),
entry,
args,
}),
CallbackStep::Return(value) => Ok(CallbackStart::Return(value)),
}
}
}
impl CallbackTask for Exit {
fn resume(&mut self, _: u64, _: u64, _: &mut GuestMemory) -> Result<CallbackStep, ExitReason> {
self.next()
}
}
fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
registry.register(UCRT, "_initialize_onexit_table", |args, _, mem| {
let table = args.rcx;
@@ -473,6 +524,24 @@ fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState
Ok(ExitFunctions { pending }.start())
});
// exit does not return. It is partial: no stream is flushed, because
// there are none, and thread-local destructors are not run.
let s = Arc::clone(state);
registry.register_callback_task(
UCRT,
"exit",
ServiceStatus::Partial,
move |args, _, _, _| {
// The status is an int, the low half of the first argument.
Exit {
state: Arc::clone(&s),
status: args.rcx as u32,
}
.start()
},
);
registry.alias(CRT_RUNTIME_API, UCRT, "exit");
for symbol in [
"_initialize_onexit_table",
"_register_onexit_function",
+347
View File
@@ -0,0 +1,347 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The C runtime's file streams: what `fopen` opens.
//!
//! A stream reads and writes a file on the in-memory `C:` drive that the
//! handle services in `files.rs` also use, as the C runtime sits on Win32
//! files on Windows. The rules are from the Microsoft Learn pages "fopen,
//! _wfopen", "fclose, _fcloseall", "fgets, fgetws" and "perror, _wperror".
//!
//! Modes: `r`, `w` or `a`, then any of `+`, `b` and `t`. In text mode, which
//! is the default as `_fmode` starts as `_O_TEXT`, "LF characters are
//! translated to CR-LF combinations on output", "CR-LF combinations are
//! translated into single line feeds on input", and "CTRL+Z is interpreted as
//! an end-of-file character on input".
//!
//! Nothing is buffered: a write reaches the drive at once. There is no
//! seeking, so the only positions are the start, the end, and wherever the
//! last read or write left off.
use super::ObjectState;
use super::files::DriveEntry;
use crate::memory::{GuestMemory, PROCESS_HEAP};
use std::collections::BTreeMap;
/// errno.h values.
pub(super) const ENOENT: u32 = 2;
pub(super) const EBADF: u32 = 9;
pub(super) const ENOMEM: u32 = 12;
pub(super) const EACCES: u32 = 13;
pub(super) const EINVAL: u32 = 22;
pub(super) const EMFILE: u32 = 24;
pub(super) const ENOSPC: u32 = 28;
/// The most streams `fopen` keeps open at once.
pub(super) const MAX_OPEN_STREAMS: usize = 64;
/// `CTRL+Z`, which ends the input of a text-mode stream.
const CTRL_Z: u8 = 0x1A;
/// The text `perror` prints for an `errno` value. The page gives the text for
/// a missing file in its example; the others are the usual C library wording
/// and are Xenora's choice.
pub(super) fn error_text(errno: u32) -> &'static str {
match errno {
0 => "No error",
ENOENT => "No such file or directory",
EBADF => "Bad file descriptor",
ENOMEM => "Not enough space",
EACCES => "Permission denied",
EINVAL => "Invalid argument",
EMFILE => "Too many open files",
ENOSPC => "No space left on device",
_ => "Unknown error",
}
}
struct Mode {
readable: bool,
writable: bool,
/// Every write goes to the end of the file.
append: bool,
/// The file must already exist.
existing: bool,
/// The file's contents are destroyed on opening.
truncate: bool,
text: bool,
}
/// `r`, `w` or `a` first, then `+`, `b` and `t` in any order, each at most
/// once and not both `b` and `t`. Anything else is not a mode this runtime
/// opens, including the other characters the page lists.
fn parse_mode(mode: &[u8]) -> Option<Mode> {
let (&kind, rest) = mode.split_first()?;
let (mut update, mut binary, mut text) = (false, false, false);
for &byte in rest {
let seen = match byte {
b'+' => &mut update,
b'b' => &mut binary,
b't' => &mut text,
_ => return None,
};
if std::mem::replace(seen, true) {
return None;
}
}
if binary && text {
return None;
}
let (readable, writable, append, existing, truncate) = match kind {
b'r' => (true, update, false, true, false),
b'w' => (update, true, false, false, true),
b'a' => (update, true, true, false, false),
_ => return None,
};
Some(Mode {
readable,
writable,
append,
existing,
truncate,
text: !binary,
})
}
struct FileStream {
path: String,
/// Where the next read, or the next write of a stream that does not
/// append, takes place.
position: u64,
readable: bool,
writable: bool,
append: bool,
text: bool,
}
#[derive(Default)]
pub(super) struct FileStreams {
/// Open streams by the guest address of their `FILE` object.
open: BTreeMap<u64, FileStream>,
}
impl FileStreams {
pub(super) fn contains(&self, file: u64) -> bool {
self.open.contains_key(&file)
}
/// `fopen`. Returns the guest address of a new `FILE` object, or the
/// `errno` value of the failure.
pub(super) fn open(
&mut self,
memory: &mut GuestMemory,
drive: &mut ObjectState,
name: &[u8],
mode: &[u8],
) -> Result<u64, u32> {
// An empty name or mode is an invalid parameter: neither is a mode
// nor a name the drive accepts. Xenora's choice: so is any other mode
// it does not open and any other name the drive rejects.
let mode = parse_mode(mode).ok_or(EINVAL)?;
let path = ObjectState::drive_path(name).ok_or(EINVAL)?;
if self.open.len() >= MAX_OPEN_STREAMS {
return Err(EMFILE);
}
let create = match drive.drive_entry(&path) {
DriveEntry::Directory => return Err(EACCES),
DriveEntry::File => false,
DriveEntry::Missing { .. } if mode.existing => return Err(ENOENT),
DriveEntry::Missing { parent: false } => return Err(ENOENT),
DriveEntry::Missing { parent: true } => true,
};
// The FILE object is allocated before the drive is touched, so a
// failed fopen neither creates a file nor destroys the contents of
// one.
let file = memory
.map_heap_allocation(PROCESS_HEAP, 8)
.map_err(|_| ENOMEM)?;
if create && !drive.drive_create(&path) {
memory.release_heap_allocation(PROCESS_HEAP, file);
return Err(ENOSPC);
}
if mode.truncate {
drive.drive_truncate(&path);
}
self.open.insert(
file,
FileStream {
path,
position: 0,
readable: mode.readable,
writable: mode.writable,
append: mode.append,
text: mode.text,
},
);
Ok(file)
}
/// `fclose`. False when `file` is not an open stream.
pub(super) fn close(&mut self, memory: &mut GuestMemory, file: u64) -> bool {
if self.open.remove(&file).is_none() {
return false;
}
memory.release_heap_allocation(PROCESS_HEAP, file);
true
}
/// Write to an open stream, in its mode. Returns the `errno` value of a
/// failure, with nothing written.
pub(super) fn write(
&mut self,
drive: &mut ObjectState,
file: u64,
bytes: &[u8],
) -> Result<(), u32> {
let stream = self.open.get_mut(&file).ok_or(EBADF)?;
if !stream.writable {
return Err(EBADF);
}
let stored: Vec<u8> = if stream.text {
let mut stored = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' {
stored.push(b'\r');
}
stored.push(byte);
}
stored
} else {
bytes.to_vec()
};
// "All write operations occur at the end of the file."
if stream.append {
stream.position = drive.drive_file(&stream.path).ok_or(EBADF)?.len() as u64;
}
match drive.drive_write(&stream.path, stream.position, &stored) {
Some(true) => {
stream.position += stored.len() as u64;
Ok(())
}
Some(false) => Err(ENOSPC),
// The file was deleted or moved while the stream was open.
None => Err(EBADF),
}
}
/// `fgets`: up to `limit` characters, ending after a newline. `None` is
/// end of file with nothing read.
pub(super) fn read_line(
&mut self,
drive: &ObjectState,
file: u64,
limit: usize,
) -> Result<Option<Vec<u8>>, u32> {
let stream = self.open.get_mut(&file).ok_or(EBADF)?;
if !stream.readable {
return Err(EBADF);
}
let data = drive.drive_file(&stream.path).ok_or(EBADF)?;
let mut at = usize::try_from(stream.position).map_or(data.len(), |at| at.min(data.len()));
let ended = at == data.len() || (stream.text && data[at] == CTRL_Z);
if limit == 0 {
// No room to read a character: an empty line unless the stream
// has ended.
return Ok((!ended).then(Vec::new));
}
let mut line = Vec::new();
while line.len() < limit && at < data.len() {
let mut byte = data[at];
if stream.text {
if byte == CTRL_Z {
break;
}
if byte == b'\r' && data.get(at + 1) == Some(&b'\n') {
at += 1;
byte = b'\n';
}
}
at += 1;
line.push(byte);
if byte == b'\n' {
break;
}
}
stream.position = at as u64;
Ok((!line.is_empty()).then_some(line))
}
}
#[cfg(test)]
mod tests {
use super::parse_mode;
/// The six access types of the `fopen` page, each alone and with `t` or
/// `b`, and what the page says of each.
#[test]
fn modes_follow_the_fopen_page() {
// (mode, readable, writable, append, must exist, truncates)
for (mode, readable, writable, append, existing, truncate) in [
("r", true, false, false, true, false),
("w", false, true, false, false, true),
("a", false, true, true, false, false),
("r+", true, true, false, true, false),
("w+", true, true, false, false, true),
("a+", true, true, true, false, false),
] {
for (suffix, text) in [("", true), ("t", true), ("b", false)] {
let mut spellings = vec![format!("{mode}{suffix}")];
if mode.len() == 2 && !suffix.is_empty() {
// "rb+" is the same mode as "r+b".
spellings.push(format!("{}{suffix}+", &mode[..1]));
}
for spelling in spellings {
let parsed = parse_mode(spelling.as_bytes())
.unwrap_or_else(|| panic!("{spelling} is a mode"));
assert_eq!(
(
parsed.readable,
parsed.writable,
parsed.append,
parsed.existing,
parsed.truncate,
parsed.text
),
(readable, writable, append, existing, truncate, text),
"{spelling}"
);
}
}
}
// "If t or b is prefixed to the argument, the function fails." The
// other mode characters the page lists are not opened here, and
// neither is anything that is not a mode.
for mode in [
"",
"t",
"b",
"tr",
"br",
"+r",
"x",
"rw",
"wr",
"ra",
"rbt",
"rtb",
"r++",
"rbb",
"wtt",
"wx",
"w+x",
"rc",
"rn",
"rN",
"rS",
"rR",
"wT",
"wD",
"r,ccs=UTF-8",
"R",
"W",
"r ",
" r",
"rb+t",
] {
assert!(parse_mode(mode.as_bytes()).is_none(), "{mode:?}");
}
}
}
+743
View File
@@ -0,0 +1,743 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Formatting for the narrow `printf` family.
//!
//! The rules are from Microsoft's "Format specification syntax: printf and
//! wprintf functions" and, where that page is silent, from ISO C 7.21.6.1. A
//! conversion specification is `%[flags][width][.precision][size]type`.
//!
//! Supported: the flags `-`, `+`, space, `#` and `0`; a width and a precision
//! given as digits or as `*`; the size prefixes `hh`, `h`, `l`, `ll`, `j`,
//! `z`, `t`, `I`, `I32` and `I64`; and the types `d`, `i`, `u`, `o`, `x`, `X`,
//! `c`, `s`, `p` and `%%`.
//!
//! Refused as invalid, as Windows does by default: `%n`, and a character that
//! has no meaning as a type. Refused as not modelled, so that nothing is
//! printed wrongly: the floating-point types, and wide characters and strings.
//!
//! Where the documentation leaves a choice, the choice made here is marked
//! "Xenora's choice" at the code that makes it.
use crate::memory::MemoryError;
/// The most one call may produce, and the largest width or precision.
pub(super) const MAX_OUTPUT: usize = 1 << 20;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum FormatError {
/// The format is not valid: `%n`, an unknown type, a size prefix that
/// does not apply to its type, or a string that ends inside a
/// specification.
Invalid,
/// The format is valid and asks for something that is not modelled.
Unsupported,
/// The output, a width or a precision exceeds [`MAX_OUTPUT`].
TooLong,
/// Reading an argument or a string failed.
Fault(MemoryError),
}
/// Where the arguments and strings of one call come from.
pub(super) trait Source {
/// The next 8-byte argument slot.
fn argument(&mut self) -> Result<u64, MemoryError>;
/// The bytes of the string at `address` up to its terminator, or the first
/// `limit` of them. Never called with a null address.
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError>;
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Size {
None,
Char,
Short,
/// `l`: a `long`, which is 32 bits on Windows, or a wide character or
/// string.
Long,
/// `ll`, `j`, `z`, `t`, `I` and `I64`: 64 bits on a 64-bit system.
Quad,
/// `I32`.
Int32,
/// `w`: a wide character or string.
Wide,
/// `L`: a `long double`.
LongDouble,
}
#[derive(Default)]
struct Flags {
left: bool,
plus: bool,
space: bool,
alternate: bool,
zero: bool,
}
struct Spec {
flags: Flags,
width: usize,
precision: Option<usize>,
size: Size,
}
struct Parser<'a> {
format: &'a [u8],
at: usize,
}
impl Parser<'_> {
fn peek(&self) -> Option<u8> {
self.format.get(self.at).copied()
}
fn take(&mut self, byte: u8) -> bool {
let found = self.peek() == Some(byte);
self.at += usize::from(found);
found
}
/// Decimal digits, possibly none.
fn number(&mut self) -> Result<usize, FormatError> {
let mut value = 0usize;
while let Some(digit @ b'0'..=b'9') = self.peek() {
value = value * 10 + usize::from(digit - b'0');
if value > MAX_OUTPUT {
return Err(FormatError::TooLong);
}
self.at += 1;
}
Ok(value)
}
fn size(&mut self) -> Size {
if self.take(b'h') {
return if self.take(b'h') {
Size::Char
} else {
Size::Short
};
}
if self.take(b'l') {
return if self.take(b'l') {
Size::Quad
} else {
Size::Long
};
}
if self.take(b'I') {
let rest = &self.format[self.at..];
if rest.starts_with(b"64") {
self.at += 2;
return Size::Quad;
}
if rest.starts_with(b"32") {
self.at += 2;
return Size::Int32;
}
// `I` alone is ptrdiff_t or size_t.
return Size::Quad;
}
match self.peek() {
Some(b'j' | b'z' | b't') => {
self.at += 1;
Size::Quad
}
Some(b'w') => {
self.at += 1;
Size::Wide
}
Some(b'L') => {
self.at += 1;
Size::LongDouble
}
_ => Size::None,
}
}
}
/// An `int` argument is the low half of its slot.
fn int(slot: u64) -> i32 {
slot as u32 as i32
}
fn bounded(value: usize) -> Result<usize, FormatError> {
if value > MAX_OUTPUT {
Err(FormatError::TooLong)
} else {
Ok(value)
}
}
/// Pad `body` to the field width. `zeros` puts the padding after the first
/// `lead` bytes (a sign or prefix) as zeros instead of before them as blanks.
fn pad(out: &mut Vec<u8>, spec: &Spec, lead: usize, body: &[u8], zeros: bool) {
let fill = spec.width.saturating_sub(body.len());
if spec.flags.left {
out.extend_from_slice(body);
out.resize(out.len() + fill, b' ');
} else if zeros {
out.extend_from_slice(&body[..lead]);
out.resize(out.len() + fill, b'0');
out.extend_from_slice(&body[lead..]);
} else {
out.resize(out.len() + fill, b' ');
out.extend_from_slice(body);
}
}
fn digits(mut value: u64, base: u64, upper: bool) -> Vec<u8> {
let table: &[u8; 16] = if upper {
b"0123456789ABCDEF"
} else {
b"0123456789abcdef"
};
let mut reversed = Vec::new();
loop {
reversed.push(table[(value % base) as usize]);
value /= base;
if value == 0 {
break;
}
}
reversed.reverse();
reversed
}
fn integer(out: &mut Vec<u8>, spec: &Spec, kind: u8, slot: u64) -> Result<(), FormatError> {
let signed = matches!(kind, b'd' | b'i');
// Without a size prefix an integer argument is a 32-bit int, and so is a
// long. `hh` and `h` arguments arrive as an int and are converted back.
let (negative, magnitude) = if signed {
let value = match spec.size {
Size::None | Size::Long | Size::Int32 => i64::from(int(slot)),
Size::Char => i64::from(slot as u8 as i8),
Size::Short => i64::from(slot as u16 as i16),
Size::Quad => slot as i64,
Size::Wide | Size::LongDouble => return Err(FormatError::Invalid),
};
(value < 0, value.unsigned_abs())
} else {
let value = match spec.size {
Size::None | Size::Long | Size::Int32 => u64::from(slot as u32),
Size::Char => u64::from(slot as u8),
Size::Short => u64::from(slot as u16),
Size::Quad => slot,
Size::Wide | Size::LongDouble => return Err(FormatError::Invalid),
};
(false, value)
};
let (base, upper) = match kind {
b'o' => (8, false),
b'x' => (16, false),
b'X' => (16, true),
_ => (10, false),
};
// The precision is the minimum number of digits, 1 by default. A zero
// value with a precision of zero has no digits.
let precision = spec.precision.unwrap_or(1);
let mut number = if magnitude == 0 && precision == 0 {
Vec::new()
} else {
digits(magnitude, base, upper)
};
if number.len() < precision {
let mut padded = vec![b'0'; precision - number.len()];
padded.append(&mut number);
number = padded;
}
let mut body = Vec::new();
if signed {
// The blank is ignored when both it and + appear.
if negative {
body.push(b'-');
} else if spec.flags.plus {
body.push(b'+');
} else if spec.flags.space {
body.push(b' ');
}
}
if spec.flags.alternate {
match kind {
// ISO C: the precision grows, only if it must, so that the first
// digit is a zero. A zero value with a precision of zero is "0".
b'o' if number.first() != Some(&b'0') => body.push(b'0'),
b'x' if magnitude != 0 => body.extend_from_slice(b"0x"),
b'X' if magnitude != 0 => body.extend_from_slice(b"0X"),
_ => {}
}
}
let lead = body.len();
body.append(&mut number);
bounded(body.len().max(spec.width))?;
// 0 is ignored with - and when an integer has a precision.
let zeros = spec.flags.zero && spec.precision.is_none();
pad(out, spec, lead, &body, zeros);
Ok(())
}
/// Format `format` with the arguments and strings `source` supplies. Returns
/// the bytes to write; their number is the function result of the `printf`
/// family.
pub(super) fn format(format: &[u8], source: &mut dyn Source) -> Result<Vec<u8>, FormatError> {
let mut out = Vec::new();
let mut parser = Parser { format, at: 0 };
while let Some(byte) = parser.peek() {
parser.at += 1;
if byte != b'%' {
out.push(byte);
bounded(out.len())?;
continue;
}
if parser.take(b'%') {
out.push(b'%');
continue;
}
let mut flags = Flags::default();
loop {
match parser.peek() {
Some(b'-') => flags.left = true,
Some(b'+') => flags.plus = true,
Some(b' ') => flags.space = true,
Some(b'#') => flags.alternate = true,
Some(b'0') => flags.zero = true,
_ => break,
}
parser.at += 1;
}
let width = if parser.take(b'*') {
// ISO C: a negative width is the - flag and a positive width.
let value = int(source.argument().map_err(FormatError::Fault)?);
flags.left |= value < 0;
bounded(value.unsigned_abs() as usize)?
} else {
parser.number()?
};
let precision = if !parser.take(b'.') {
None
} else if parser.take(b'*') {
// ISO C: a negative precision is taken as if it were omitted.
let value = int(source.argument().map_err(FormatError::Fault)?);
match usize::try_from(value) {
Ok(value) => Some(bounded(value)?),
Err(_) => None,
}
} else {
Some(parser.number()?)
};
let size = parser.size();
let spec = Spec {
flags,
width,
precision,
size,
};
let kind = parser.peek().ok_or(FormatError::Invalid)?;
parser.at += 1;
match kind {
b'd' | b'i' | b'u' | b'o' | b'x' | b'X' => {
let slot = source.argument().map_err(FormatError::Fault)?;
integer(&mut out, &spec, kind, slot)?;
}
b'c' => {
match spec.size {
Size::None | Size::Short => {}
Size::Long | Size::Wide => return Err(FormatError::Unsupported),
_ => return Err(FormatError::Invalid),
}
// The precision has no effect on a character.
let slot = source.argument().map_err(FormatError::Fault)?;
// Xenora's choice: 0 pads any type, as the page's description
// of the flag is not limited to numbers.
pad(&mut out, &spec, 0, &[slot as u8], spec.flags.zero);
}
b's' => {
match spec.size {
Size::None | Size::Short => {}
Size::Long | Size::Wide => return Err(FormatError::Unsupported),
_ => return Err(FormatError::Invalid),
}
let address = source.argument().map_err(FormatError::Fault)?;
let limit = spec.precision.unwrap_or(MAX_OUTPUT + 1);
let text = if address == 0 {
// Xenora's choice: the precision also limits "(null)".
let null = b"(null)";
null[..null.len().min(limit)].to_vec()
} else {
source.string(address, limit).map_err(FormatError::Fault)?
};
bounded(text.len().max(spec.width))?;
pad(&mut out, &spec, 0, &text, spec.flags.zero);
}
b'p' => {
if spec.size != Size::None {
return Err(FormatError::Invalid);
}
let slot = source.argument().map_err(FormatError::Fault)?;
// "An address in hexadecimal digits" is all the page says.
// Xenora's choice: sixteen upper-case digits, and no other
// flag or precision has an effect.
let text = format!("{slot:016X}");
pad(&mut out, &spec, 0, text.as_bytes(), false);
}
// Wide characters and strings, floating point and the counted
// string structures are valid and not modelled.
b'C' | b'S' | b'Z' | b'e' | b'E' | b'f' | b'F' | b'g' | b'G' | b'a' | b'A' => {
return Err(FormatError::Unsupported);
}
// %n is disabled by default, and any other character has no
// meaning as a type.
_ => return Err(FormatError::Invalid),
}
bounded(out.len())?;
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::{FormatError, MAX_OUTPUT, Source, format};
use crate::memory::MemoryError;
/// A string argument is the address `STRINGS + 0x100 * index`.
const STRINGS: u64 = 0x1000_0000;
struct Call {
slots: Vec<u64>,
strings: Vec<Vec<u8>>,
next: usize,
}
impl Source for Call {
fn argument(&mut self) -> Result<u64, MemoryError> {
let slot = self.slots.get(self.next).copied();
self.next += 1;
slot.ok_or(MemoryError::UnmappedAddress(self.next as u64))
}
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError> {
let index = ((address - STRINGS) / 0x100) as usize;
let text = self
.strings
.get(index)
.ok_or(MemoryError::UnmappedAddress(address))?;
Ok(text[..text.len().min(limit)].to_vec())
}
}
fn run(text: &str, slots: &[u64], strings: &[&str]) -> Result<String, FormatError> {
let mut call = Call {
slots: slots.to_vec(),
strings: strings
.iter()
.map(|text| text.as_bytes().to_vec())
.collect(),
next: 0,
};
let bytes = format(text.as_bytes(), &mut call)?;
assert_eq!(call.next, slots.len(), "{text}: arguments consumed");
Ok(String::from_utf8(bytes).unwrap())
}
fn ok(text: &str, slots: &[u64], strings: &[&str]) -> String {
run(text, slots, strings).unwrap_or_else(|error| panic!("{text}: {error:?}"))
}
/// The host C library's `snprintf`, on cases whose behaviour ISO C
/// defines and Windows shares. `tests/printf/reference.py` wrote the file
/// and says how each line is laid out.
#[test]
fn output_matches_the_host_c_library_on_defined_cases() {
let vectors = include_str!("../../tests/printf/vectors.txt");
let unhex = |text: &str| -> Vec<u8> {
(0..text.len() / 2)
.map(|at| u8::from_str_radix(&text[2 * at..2 * at + 2], 16).unwrap())
.collect()
};
let mut cases = 0;
for line in vectors.lines().filter(|line| !line.starts_with('#')) {
let fields: Vec<&str> = line.split('\t').collect();
let [template, arguments, expected] = fields[..] else {
panic!("three fields: {line}");
};
let template = unhex(template);
let (mut slots, mut strings) = (Vec::new(), Vec::new());
for argument in arguments.split(',').filter(|text| !text.is_empty()) {
let (kind, value) = argument.split_once(':').unwrap();
match kind {
"i" => slots.push(u64::from_str_radix(value, 16).unwrap()),
"s" => {
slots.push(STRINGS + 0x100 * strings.len() as u64);
strings.push(unhex(value));
}
"n" => slots.push(0),
_ => panic!("argument kind {kind}"),
}
}
let mut call = Call {
slots,
strings,
next: 0,
};
let shown = String::from_utf8_lossy(&template).into_owned();
let got = format(&template, &mut call)
.unwrap_or_else(|error| panic!("{shown} {arguments}: {error:?}"));
assert_eq!(
String::from_utf8_lossy(&got),
String::from_utf8_lossy(&unhex(expected)),
"{shown} with {arguments}"
);
assert_eq!(call.next, call.slots.len(), "{shown}: arguments consumed");
cases += 1;
}
assert!(cases > 2000, "{cases} cases");
}
/// Rules the host C library does not share or that the reference leaves
/// out, each from the format specification page.
#[test]
fn windows_sizes_follow_the_format_specification_page() {
// "The formatter consumes integer arguments ... as 32-bit int types";
// a long is a 32-bit type on Windows. The upper half of the slot is
// not part of either.
let slot = 0xFFFF_FFFF_8000_0001;
assert_eq!(ok("%d", &[slot], &[]), "-2147483647");
assert_eq!(ok("%ld", &[slot], &[]), "-2147483647");
assert_eq!(ok("%lu", &[slot], &[]), "2147483649");
assert_eq!(ok("%lx", &[0x1_2345_6789], &[]), "23456789");
assert_eq!(ok("%I32d", &[slot], &[]), "-2147483647");
assert_eq!(ok("%I32u", &[slot], &[]), "2147483649");
// ll, I64, j, t, z and I alone are 64-bit.
for size in ["ll", "I64", "j", "t", "z", "I"] {
assert_eq!(
ok(&format!("%{size}d"), &[slot], &[]),
"-2147483647",
"{size}"
);
assert_eq!(
ok(&format!("%{size}u"), &[u64::MAX], &[]),
"18446744073709551615",
"{size}"
);
assert_eq!(
ok(&format!("%{size}x"), &[0x1_2345_6789], &[]),
"123456789",
"{size}"
);
}
assert_eq!(ok("%I64d", &[1 << 63], &[]), "-9223372036854775808");
// I followed by other digits is the size I and then literal text?
// No: digits after the size are not a type, so the format is invalid.
assert_eq!(run("%I16d", &[1], &[]), Err(FormatError::Invalid));
}
#[test]
fn strings_characters_and_pointers() {
// "If the argument that corresponds to %s ... is a null pointer,
// "(null)" is displayed."
assert_eq!(ok("[%s]", &[0], &[]), "[(null)]");
assert_eq!(ok("[%10s]", &[0], &[]), "[ (null)]");
assert_eq!(ok("[%-8s]", &[0], &[]), "[(null) ]");
// Xenora's choice: the precision limits it too.
assert_eq!(ok("[%.3s]", &[0], &[]), "[(nu]");
// h is a single-byte character or string, as no prefix is.
assert_eq!(
ok("%hc%hs", &[u64::from(b'x'), super::tests::STRINGS], &["yz"]),
"xyz"
);
// The precision has no effect on a character.
assert_eq!(ok("[%.0c]", &[0x141], &[]), "[A]");
// Xenora's choice for %p: sixteen upper-case hexadecimal digits.
assert_eq!(ok("%p", &[0x1_4000_1abc], &[]), "0000000140001ABC");
assert_eq!(ok("%p", &[0], &[]), "0000000000000000");
assert_eq!(ok("[%20p]", &[0xABC], &[]), "[ 0000000000000ABC]");
assert_eq!(ok("[%-20p]", &[0xABC], &[]), "[0000000000000ABC ]");
// Xenora's choice: 0 pads a character and a string as it pads a number.
assert_eq!(ok("[%03c]", &[u64::from(b'a')], &[]), "[00a]");
assert_eq!(ok("[%05s]", &[STRINGS], &["ab"]), "[000ab]");
assert_eq!(ok("[%-05s]", &[STRINGS], &["ab"]), "[ab ]");
// "+: Use a sign (+ or -) to prefix the output value if it's of a
// signed type", and the blank likewise: neither affects an unsigned
// conversion.
for (text, wanted) in [
("%+u", "7"),
("% u", "7"),
("%+x", "7"),
("% X", "7"),
("%+o", "7"),
("%+ 5u", " 7"),
("%+d", "+7"),
("% d", " 7"),
] {
assert_eq!(ok(text, &[7], &[]), wanted, "{text}");
}
// ISO C for %#.0o with a zero value, which the page does not cover.
assert_eq!(ok("[%#.0o]", &[0], &[]), "[0]");
assert_eq!(ok("[%.0o]", &[0], &[]), "[]");
// Text between and around specifications is copied, and %% is a
// percent sign.
assert_eq!(
ok("100%% of %s%c", &[STRINGS, u64::from(b'!')], &["it"]),
"100% of it!"
);
assert_eq!(ok("", &[], &[]), "");
assert_eq!(ok("plain", &[], &[]), "plain");
}
#[test]
fn invalid_formats_are_refused() {
// "The n specifier is disabled by default", and "if a percent sign is
// followed by a character that has no meaning as a format field, the
// invalid parameter handler is invoked."
for text in [
"%n",
"%hn",
"count %d%n",
"%y",
"%",
"%5",
"%-",
"%.",
"%.3",
"%l",
"%ll",
"%h",
"%I64",
"%5%",
"% %",
"%!",
"%\u{1}",
] {
let slots = [1, 2, 3];
let mut call = Call {
slots: slots.to_vec(),
strings: Vec::new(),
next: 0,
};
assert_eq!(
format(text.as_bytes(), &mut call),
Err(FormatError::Invalid),
"{text:?}"
);
}
// A size prefix that does not apply to its type.
for text in [
"%wd", "%Ld", "%wu", "%Lx", "%llc", "%hhc", "%jc", "%lls", "%zs", "%I64s", "%lp",
"%hp", "%llp", "%I32c",
] {
assert_eq!(run(text, &[1], &["s"]), Err(FormatError::Invalid), "{text}");
}
}
#[test]
fn valid_conversions_that_are_not_modelled_are_refused() {
for kind in ["e", "E", "f", "F", "g", "G", "a", "A"] {
for prefix in ["", ".3", "l", "L", "10.2", "#"] {
let text = format!("%{prefix}{kind}");
let mut call = Call {
slots: vec![0x3FF0_0000_0000_0000],
strings: Vec::new(),
next: 0,
};
assert_eq!(
format(text.as_bytes(), &mut call),
Err(FormatError::Unsupported),
"{text}"
);
}
}
// Wide characters and strings: C and S, and c and s with l or w.
for text in ["%C", "%S", "%lc", "%ls", "%wc", "%ws", "%Z", "%hC", "%hS"] {
let mut call = Call {
slots: vec![STRINGS],
strings: vec![b"w".to_vec()],
next: 0,
};
assert_eq!(
format(text.as_bytes(), &mut call),
Err(FormatError::Unsupported),
"{text}"
);
}
// Nothing is produced before a later refusal either: the caller gets
// an error, not a prefix.
assert_eq!(
run("ok %d then %f", &[1, 2], &[]),
Err(FormatError::Unsupported)
);
}
#[test]
fn bounds_and_faults() {
let most = MAX_OUTPUT;
// A width or precision up to the bound is honoured; one more is not.
assert_eq!(ok(&format!("%{most}d"), &[7], &[]).len(), most);
assert_eq!(
run(&format!("%{}d", most + 1), &[7], &[]),
Err(FormatError::TooLong)
);
assert_eq!(ok(&format!("%.{most}d"), &[7], &[]).len(), most);
assert_eq!(
run(&format!("%.{}d", most + 1), &[7], &[]),
Err(FormatError::TooLong)
);
assert_eq!(
run("%99999999999999999999d", &[7], &[]),
Err(FormatError::TooLong)
);
// The same through *, and the total over several conversions.
assert_eq!(ok("%*d", &[most as u64, 7], &[]).len(), most);
assert_eq!(
run("%*d", &[most as u64 + 1, 7], &[]),
Err(FormatError::TooLong)
);
assert_eq!(
run("%.*d", &[most as u64 + 1, 7], &[]),
Err(FormatError::TooLong)
);
let half = most / 2 + 1;
assert_eq!(
run(&format!("%{half}d%{half}d"), &[1, 2], &[]),
Err(FormatError::TooLong)
);
// The most negative width is a left-justified width past the bound.
assert_eq!(
run("%*d", &[0x8000_0000, 7], &[]),
Err(FormatError::TooLong)
);
// A string is read only up to its precision.
assert_eq!(ok("%.2s", &[STRINGS], &["abcdef"]), "ab");
// A missing argument or an unreadable string is a fault, wherever in
// the specification it is needed.
for text in [
"%d",
"%*d",
"%.*d",
"%5.*d",
"%s",
"%c",
"%p",
"%d %d %d %d",
] {
assert!(
matches!(run(text, &[], &[]), Err(FormatError::Fault(_))),
"{text}"
);
}
let mut call = Call {
slots: vec![STRINGS + 0x900],
strings: Vec::new(),
next: 0,
};
assert_eq!(
format(b"%s", &mut call),
Err(FormatError::Fault(MemoryError::UnmappedAddress(
STRINGS + 0x900
)))
);
}
}
+412
View File
@@ -0,0 +1,412 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The streams of a hosted C program, and where their output goes.
//!
//! `__acrt_iob_func` hands out the `FILE` objects for `stdin`, `stdout` and
//! `stderr`. What the guest writes to `stdout` and to `stderr` is kept in two
//! host-side buffers that a host or a test reads through `ServicesState`.
//!
//! The standard streams "always open in text mode by default", and in text
//! mode "each line feed is replaced with a carriage return-line feed pair"
//! that "has no effect on the return value" (Microsoft Learn, "Text and
//! binary mode file I/O" and "fwrite"). The buffers hold the bytes after that
//! replacement, which is what the operating system would be handed.
//!
//! A stream that `fopen` returned is a file on the in-memory drive; its rules
//! are in `crt_files.rs`.
//!
//! Output is never held back: there is no buffering to flush or to configure.
//! A pointer that is no stream, reading `stdin` and closing a standard stream
//! are not modelled and stop the guest with the runtime-limit fault.
use super::ObjectState;
use super::crt_files::{self, EBADF, EINVAL, FileStreams};
use super::crt_format::{self, FormatError, Source};
use crate::cpu::ExitReason;
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
/// The exit for a request the runtime does not model.
const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
/// `typedef struct _iobuf { void* _Placeholder; } FILE;` (corecrt_wstdio.h).
const FILE_BYTES: u64 = 8;
/// The most a format string or one `fwrite` or `fputs` may hold.
const MAX_TRANSFER: u64 = 1 << 20;
/// The longest file name or mode string `fopen` reads, in bytes.
const MAX_NAME: u64 = 260;
/// The most each captured stream keeps. Writing past it stops the guest.
pub const MAX_CAPTURED_OUTPUT: usize = 16 << 20;
/// Option bits of `__stdio_common_vfprintf` (corecrt_stdio_config.h) that do
/// not change anything this engine formats: the wide-specifier bit concerns
/// the wide functions, and the exponent and rounding bits concern floating
/// point. Any other bit stops the guest.
const IGNORED_OPTIONS: u64 = 0x04 | 0x10 | 0x20;
/// `_IOFBF`, `_IOLBF` and `_IONBF` (stdio.h).
const IOFBF: i32 = 0x0000;
const IOLBF: i32 = 0x0040;
const IONBF: i32 = 0x0004;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Stream {
Input,
Output,
Error,
/// A stream `fopen` returned, by the address of its `FILE` object.
File(u64),
}
#[derive(Default)]
pub(super) struct StandardStreams {
/// Guest address of the three `FILE` objects, `stdin` first.
files: Option<u64>,
output: Vec<u8>,
error: Vec<u8>,
/// The streams `fopen` has open.
opened: FileStreams,
}
/// What a service returns when it fails with a result and an `errno` value:
/// the handler sets `errno` to the second field and returns the first.
pub(super) struct Failed<T>(pub T, pub u32);
pub(super) type Outcome<T> = Result<Result<T, Failed<T>>, ExitReason>;
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
/// The bytes of the C string at `address`, without its terminator.
fn c_string(memory: &GuestMemory, address: u64, limit: u64) -> Result<Vec<u8>, MemoryError> {
let mut bytes = Vec::new();
for offset in 0..limit {
let at = address.checked_add(offset).ok_or(MemoryError::Overflow)?;
match memory.read_u8(at)? {
0 => break,
byte => bytes.push(byte),
}
}
Ok(bytes)
}
/// Arguments from the guest's `va_list`: one 8-byte slot each, in order.
struct VaList<'a> {
memory: &'a GuestMemory,
next: u64,
}
impl Source for VaList<'_> {
fn argument(&mut self) -> Result<u64, MemoryError> {
let slot = self.memory.read_u64(self.next)?;
self.next = self.next.checked_add(8).ok_or(MemoryError::Overflow)?;
Ok(slot)
}
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError> {
c_string(self.memory, address, limit as u64)
}
}
impl StandardStreams {
pub(super) fn output(&self) -> &[u8] {
&self.output
}
pub(super) fn error(&self) -> &[u8] {
&self.error
}
/// `__acrt_iob_func`: the `FILE` object of `stdin` (0), `stdout` (1) or
/// `stderr` (2). The three are allocated together from the process heap
/// on first use.
pub(super) fn file(&mut self, memory: &mut GuestMemory, index: u32) -> Result<u64, ExitReason> {
if index > 2 {
return Err(RUNTIME_LIMIT);
}
let base = match self.files {
Some(base) => base,
None => {
let base = memory
.map_heap_allocation(PROCESS_HEAP, (3 * FILE_BYTES) as usize)
.map_err(fault)?;
self.files = Some(base);
base
}
};
Ok(base + FILE_BYTES * u64::from(index))
}
/// Which stream a non-null `FILE*` is: a standard stream, or one `fopen`
/// returned. Any other pointer is no stream.
fn stream(&self, file: u64) -> Result<Stream, ExitReason> {
match self.files.map(|base| file.wrapping_sub(base)) {
Some(0) => Ok(Stream::Input),
Some(8) => Ok(Stream::Output),
Some(16) => Ok(Stream::Error),
_ if self.opened.contains(file) => Ok(Stream::File(file)),
_ => Err(RUNTIME_LIMIT),
}
}
/// A stream that may be written. Writing `stdin` is not modelled.
fn writable(&self, file: u64) -> Result<Stream, ExitReason> {
match self.stream(file)? {
Stream::Input => Err(RUNTIME_LIMIT),
stream => Ok(stream),
}
}
/// Write to a stream. A standard stream is captured in text mode: each
/// line feed becomes a carriage return and a line feed. A file stream can
/// fail, with the `errno` value in the inner result and nothing written.
fn write(
&mut self,
drive: &mut ObjectState,
stream: Stream,
bytes: &[u8],
) -> Result<Result<(), u32>, ExitReason> {
let captured = match stream {
Stream::Output => &mut self.output,
Stream::Error => &mut self.error,
Stream::Input => return Err(RUNTIME_LIMIT),
Stream::File(file) => return Ok(self.opened.write(drive, file, bytes)),
};
let feeds = bytes.iter().filter(|byte| **byte == b'\n').count();
if bytes.len() + feeds > MAX_CAPTURED_OUTPUT - captured.len() {
return Err(RUNTIME_LIMIT);
}
for &byte in bytes {
if byte == b'\n' {
captured.push(b'\r');
}
captured.push(byte);
}
Ok(Ok(()))
}
/// `__stdio_common_vfprintf`. Returns the number of characters written,
/// before the text-mode replacement.
#[allow(clippy::too_many_arguments)]
pub(super) fn print(
&mut self,
memory: &GuestMemory,
drive: &mut ObjectState,
options: u64,
file: u64,
format: u64,
locale: u64,
arguments: u64,
) -> Outcome<i32> {
// A null stream or format: the function returns -1 and sets errno.
if file == 0 || format == 0 {
return Ok(Err(Failed(-1, EINVAL)));
}
if options & !IGNORED_OPTIONS != 0 || locale != 0 {
return Err(RUNTIME_LIMIT);
}
let stream = self.writable(file)?;
let template = c_string(memory, format, MAX_TRANSFER + 1).map_err(fault)?;
if template.len() as u64 > MAX_TRANSFER {
return Err(RUNTIME_LIMIT);
}
let mut source = VaList {
memory,
next: arguments,
};
let text = match crt_format::format(&template, &mut source) {
Ok(text) => text,
// Windows calls the invalid parameter handler for an invalid
// format. Xenora's choice for when execution continues: nothing
// is written and the result is that of a null format.
Err(FormatError::Invalid) => return Ok(Err(Failed(-1, EINVAL))),
Err(FormatError::Unsupported | FormatError::TooLong) => return Err(RUNTIME_LIMIT),
Err(FormatError::Fault(error)) => return Err(fault(error)),
};
// "A negative value if an output error occurs."
Ok(match self.write(drive, stream, &text)? {
Ok(()) => Ok(text.len() as i32),
Err(errno) => Err(Failed(-1, errno)),
})
}
/// `fwrite`. Returns the number of whole items written.
pub(super) fn write_items(
&mut self,
memory: &GuestMemory,
drive: &mut ObjectState,
buffer: u64,
size: u64,
count: u64,
file: u64,
) -> Outcome<u64> {
if buffer == 0 || file == 0 {
return Ok(Err(Failed(0, EINVAL)));
}
let stream = self.writable(file)?;
let Some(length) = size
.checked_mul(count)
.filter(|bytes| *bytes <= MAX_TRANSFER)
else {
return Err(RUNTIME_LIMIT);
};
if length == 0 {
return Ok(Ok(0));
}
let mut bytes = vec![0; length as usize];
memory.read_bytes(buffer, &mut bytes).map_err(fault)?;
// Fewer items than `count` means an error. A failed write here
// writes none of them.
Ok(match self.write(drive, stream, &bytes)? {
Ok(()) => Ok(count),
Err(errno) => Err(Failed(0, errno)),
})
}
/// `fputs`. Writes the string without its terminator and returns a
/// nonnegative value, here 0; `EOF` is -1.
pub(super) fn put_string(
&mut self,
memory: &GuestMemory,
drive: &mut ObjectState,
text: u64,
file: u64,
) -> Outcome<i32> {
if text == 0 || file == 0 {
return Ok(Err(Failed(-1, EINVAL)));
}
let stream = self.writable(file)?;
let bytes = c_string(memory, text, MAX_TRANSFER + 1).map_err(fault)?;
if bytes.len() as u64 > MAX_TRANSFER {
return Err(RUNTIME_LIMIT);
}
Ok(match self.write(drive, stream, &bytes)? {
Ok(()) => Ok(0),
Err(errno) => Err(Failed(-1, errno)),
})
}
/// `fflush`. A null stream means every open stream. Nothing is ever held
/// back, so there is nothing to do.
pub(super) fn flush(&self, file: u64) -> Result<i32, ExitReason> {
if file != 0 {
self.stream(file)?;
}
Ok(0)
}
/// `setvbuf`. The mode and size are checked as documented and then have
/// no effect.
pub(super) fn set_buffer(&self, file: u64, mode: i32, size: u64) -> Outcome<i32> {
if file == 0 {
return Ok(Err(Failed(-1, EINVAL)));
}
self.stream(file)?;
let valid = match mode {
// "No buffer is used, regardless of buffer or size."
IONBF => true,
// "Allowable range: 2 <= size <= INT_MAX".
IOFBF | IOLBF => (2..=i32::MAX as u64).contains(&size),
_ => false,
};
Ok(if valid {
Ok(0)
} else {
Err(Failed(-1, EINVAL))
})
}
/// `fopen`. Returns the new `FILE*`, or null with the `errno` value.
pub(super) fn open(
&mut self,
memory: &mut GuestMemory,
drive: &mut ObjectState,
name: u64,
mode: u64,
) -> Outcome<u64> {
// A null name or mode is an invalid parameter, as an empty one is.
if name == 0 || mode == 0 {
return Ok(Err(Failed(0, EINVAL)));
}
let name = c_string(memory, name, MAX_NAME + 1).map_err(fault)?;
let mode = c_string(memory, mode, MAX_NAME + 1).map_err(fault)?;
if name.len() as u64 > MAX_NAME || mode.len() as u64 > MAX_NAME {
return Ok(Err(Failed(0, EINVAL)));
}
Ok(self
.opened
.open(memory, drive, &name, &mode)
.map_err(|errno| Failed(0, errno)))
}
/// `fclose`. Returns 0, or `EOF` with `EINVAL` for a null stream. Closing
/// a standard stream is not modelled.
pub(super) fn close(&mut self, memory: &mut GuestMemory, file: u64) -> Outcome<i32> {
if file == 0 {
return Ok(Err(Failed(-1, EINVAL)));
}
match self.stream(file)? {
Stream::File(file) => {
self.opened.close(memory, file);
Ok(Ok(0))
}
_ => Err(RUNTIME_LIMIT),
}
}
/// `fgets`. Returns `buffer`, or null at end of file or on an error.
pub(super) fn get_line(
&mut self,
memory: &mut GuestMemory,
drive: &ObjectState,
buffer: u64,
count: i32,
file: u64,
) -> Outcome<u64> {
if buffer == 0 || file == 0 || count <= 0 {
return Ok(Err(Failed(0, EINVAL)));
}
let file = match self.stream(file)? {
Stream::File(file) => file,
// Reading the standard input is not modelled.
Stream::Input => return Err(RUNTIME_LIMIT),
// The output streams cannot be read.
Stream::Output | Stream::Error => return Ok(Err(Failed(0, EBADF))),
};
// Up to count - 1 characters, and then the terminator.
let limit = ((count - 1) as u64).min(MAX_TRANSFER) as usize;
let mut line = match self.opened.read_line(drive, file, limit) {
Ok(Some(line)) => line,
// End of file with nothing read: null, and the buffer is left
// alone.
Ok(None) => return Ok(Ok(0)),
Err(errno) => return Ok(Err(Failed(0, errno))),
};
line.push(0);
memory.write_bytes(buffer, &line).map_err(fault)?;
Ok(Ok(buffer))
}
/// `perror`: the message, a colon and a space when there is a message,
/// then the text for `errno` and a newline, to `stderr`.
pub(super) fn report(
&mut self,
memory: &GuestMemory,
drive: &mut ObjectState,
message: u64,
errno: u32,
) -> Result<(), ExitReason> {
let mut text = Vec::new();
if message != 0 {
text = c_string(memory, message, MAX_TRANSFER + 1).map_err(fault)?;
if text.len() as u64 > MAX_TRANSFER {
return Err(RUNTIME_LIMIT);
}
}
if !text.is_empty() {
text.extend_from_slice(b": ");
}
text.extend_from_slice(crt_files::error_text(errno).as_bytes());
text.push(b'\n');
self.write(drive, Stream::Error, &text).map(|_| ())
}
}
+86
View File
@@ -625,3 +625,89 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
}
}
/// What a path names on the drive, for the C runtime's file streams.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum DriveEntry {
File,
Directory,
/// Nothing has this name. `parent` says whether its directory exists.
Missing {
parent: bool,
},
}
/// The drive as the C runtime's file streams (`crt_files.rs`) use it. They read
/// and write the same files as the handle services above. A stream is not a
/// handle: it takes no part in sharing, and a file it has open can be deleted
/// or moved, after which its operations fail.
impl super::ObjectState {
/// A narrow file name as the drive stores it: ASCII, either slash, any
/// case, with or without `C:\`. `None` for a name the drive rejects.
pub(super) fn drive_path(name: &[u8]) -> Option<String> {
if !name.is_ascii() {
return None;
}
let path = String::from_utf8_lossy(name)
.replace('/', "\\")
.to_ascii_lowercase();
let path = path.strip_prefix("c:\\").unwrap_or(&path).to_owned();
path.split('\\').all(valid_component).then_some(path)
}
pub(super) fn drive_entry(&self, path: &str) -> DriveEntry {
if self.files.contains_key(path) {
DriveEntry::File
} else if self.directories.contains(path) {
DriveEntry::Directory
} else {
let parent = parent(path);
DriveEntry::Missing {
parent: parent.is_empty() || self.directories.contains(parent),
}
}
}
/// Create an empty file. False when the drive already holds as many files
/// as it can.
pub(super) fn drive_create(&mut self, path: &str) -> bool {
if self.files.len() >= MAX_FILES {
return false;
}
self.files.insert(path.to_owned(), Vec::new());
true
}
pub(super) fn drive_file(&self, path: &str) -> Option<&[u8]> {
self.files.get(path).map(Vec::as_slice)
}
/// Empty a file. False when it does not exist.
pub(super) fn drive_truncate(&mut self, path: &str) -> bool {
self.files.get_mut(path).map(Vec::clear).is_some()
}
/// Write `bytes` at `position`, growing the file as needed. `None` when
/// the file does not exist; `Some(false)`, with nothing written, when the
/// write would pass the drive's size bound.
pub(super) fn drive_write(&mut self, path: &str, position: u64, bytes: &[u8]) -> Option<bool> {
let used: usize = self.files.values().map(Vec::len).sum();
let data = self.files.get_mut(path)?;
let Some(end) = position
.checked_add(bytes.len() as u64)
.filter(|end| *end <= MAX_BYTES as u64)
else {
return Some(false);
};
let (start, end) = (position as usize, end as usize);
let growth = end.saturating_sub(data.len());
if growth > MAX_BYTES - used {
return Some(false);
}
if growth != 0 {
data.resize(end, 0);
}
data[start..end].copy_from_slice(bytes);
Some(true)
}
}
+26
View File
@@ -8,6 +8,10 @@ use crate::imports::{ImportRegistry, ServiceStatus};
use std::sync::Arc;
const PROCESS_THREADS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
const UCRT: &str = "ucrtbase.dll";
const CRT_RUNTIME_API: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
/// The exit code `abort` ends the process with (Microsoft Learn, "abort").
const ABORT_STATUS: u32 = 3;
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
// ExitProcess does not return (processthreadsapi.h). It stops the guest
@@ -20,4 +24,26 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
});
registry.alias(PROCESS_THREADS_API, KERNEL32, "ExitProcess");
registry.set_status(KERNEL32, "ExitProcess", ServiceStatus::Partial);
// _exit ends the process without calling the functions registered with
// atexit (Microsoft Learn, "exit, _Exit, _exit"). `exit`, which does call
// them, is beside `_cexit` in crt_callbacks.rs.
let s = Arc::clone(state);
registry.register(UCRT, "_exit", move |args, _, _| {
// The status is an int, the low half of the first argument.
Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32)))
});
// abort ends the process with exit code 3 and calls no registered
// function. It is partial: it prints no message, and it does not call a
// SIGABRT handler, which the documentation says it does when one is set.
let s = Arc::clone(state);
registry.register(UCRT, "abort", move |_, _, _| {
Err(ExitReason::ProcessExit(s.exit_process(ABORT_STATUS)))
});
for symbol in ["_exit", "abort"] {
registry.alias(CRT_RUNTIME_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
+2 -3
View File
@@ -5723,10 +5723,9 @@ fn interpreter_executes_modified_code_after_a_jump() {
assert_eq!(self_modified_result(Engine::Interpreter), wanted);
}
/// Known defect: the DBT keeps running the block it translated before the store.
/// The DBT must not keep running the block it translated before the store (#84).
#[test]
#[ignore = "known defect (#155): the DBT keeps translated blocks after the guest rewrites their code"]
fn defect_dbt_executes_modified_code_after_a_jump() {
fn dbt_executes_modified_code_after_a_jump() {
for engine in [Engine::Dbt, Engine::DbtStepped] {
let wanted = (1, 2, ExitReason::Halt);
assert_eq!(self_modified_result(engine), wanted, "{engine:?}");
+332
View File
@@ -0,0 +1,332 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The C runtime's `exit`, `_exit` and `abort` (issue #395), called from
//! translated guest code through a bound import table.
//!
//! Expected behaviour is from the Microsoft Learn pages "exit, _Exit, _exit"
//! (`exit` calls the functions registered by `atexit` "in last-in-first-out
//! (LIFO) order"; `_exit` terminates "without ... processing atexit or _onexit
//! functions") and "abort" ("calls _exit to terminate the process with exit
//! code 3"), and from ISO C 7.22.4.2 and 7.22.4.4 for a function registered
//! while `exit` runs. Calling `exit` again from a registered function is
//! undefined in ISO C; the test for it states Xenora's rule. The order each
//! test expects is the order in which it registered its functions. The guest
//! code is original.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
use xenora_loader::import_table::ImportName;
use xenora_loader::imports::{ImportRegistry, ServiceStatus};
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
const KERNEL32: &str = "kernel32.dll";
const UCRT: &str = "ucrtbase.dll";
const RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
const EXIT: usize = 0;
const ATEXIT: usize = 3;
const IMPORTS: &[(&str, &str)] = &[
(UCRT, "exit"),
(UCRT, "_exit"),
(UCRT, "abort"),
(UCRT, "atexit"),
(RUNTIME, "_crt_atexit"),
(RUNTIME, "_cexit"),
(KERNEL32, "CreateEventW"),
(KERNEL32, "SetLastError"),
];
/// The same imports as a program built with mingw-w64 names the three: by the
/// runtime API set.
const BY_API_SET: &[(&str, &str)] = &[
(RUNTIME, "exit"),
(RUNTIME, "_exit"),
(RUNTIME, "abort"),
(UCRT, "atexit"),
(RUNTIME, "_crt_atexit"),
(RUNTIME, "_cexit"),
(KERNEL32, "CreateEventW"),
(KERNEL32, "SetLastError"),
];
/// A decimal log of the registered functions that ran, oldest digit first.
const LOG: u64 = SCRATCH;
/// Set to one by code placed after a call that must not return.
const RETURNED: u64 = SCRATCH + 0x100;
/// Guest address of the stub `call [slot]; hlt` for import `index`.
fn stub(index: usize) -> u64 {
BASE + u64::from(CODE_RVA) + 16 * index as u64
}
/// Guest address of the import address table slot of import `index`, read
/// from the displacement of its stub.
fn slot(guest: &Guest, index: usize) -> u64 {
let displacement = guest.u32_at(stub(index) + 2) as i32;
(stub(index) + 6).wrapping_add_signed(i64::from(displacement))
}
// Routine indices. Routines are 32 bytes apart.
const APPEND_1: usize = 0;
const APPEND_2: usize = 1;
const APPEND_3: usize = 2;
const APPEND_4: usize = 3;
const APPEND_5: usize = 4;
const REGISTER_4_THEN_APPEND_5: usize = 5;
const EXIT_AGAIN: usize = 6;
/// The status the `EXIT_AGAIN` routine exits with.
const SECOND_STATUS: u32 = 77;
/// `log = log * 10 + digit; return 0`
fn append(digit: u8) -> Vec<u8> {
let mut code = vec![0x48, 0xB8]; // mov rax, LOG
code.extend(LOG.to_le_bytes());
code.extend([
0x48, 0x8B, 0x08, // mov rcx, [rax]
0x48, 0x6B, 0xC9, 0x0A, // imul rcx, rcx, 10
0x48, 0x83, 0xC1, digit, // add rcx, digit
0x48, 0x89, 0x08, // mov [rax], rcx
0x31, 0xC0, // xor eax, eax
0xC3, // ret
]);
code
}
fn rel32(from_end: u64, to: u64) -> [u8; 4] {
(to.wrapping_sub(from_end) as u32).to_le_bytes()
}
/// A registered function that registers `APPEND_4` with `atexit`, through the
/// import address table as compiled code would, and then appends 5.
fn register_4_then_append_5(atexit_slot: u64) -> Vec<u8> {
let at = routine(REGISTER_4_THEN_APPEND_5);
let mut code = vec![0x48, 0x83, 0xEC, 0x28]; // sub rsp, 0x28
code.extend([0x48, 0x8D, 0x0D]); // lea rcx, [rip + APPEND_4]
code.extend(rel32(at + 11, routine(APPEND_4)));
code.extend([0xFF, 0x15]); // call [rip + atexit slot]
code.extend(rel32(at + 17, atexit_slot));
code.extend([0x48, 0x83, 0xC4, 0x28]); // add rsp, 0x28
code.push(0xE9); // jmp APPEND_5
code.extend(rel32(at + 26, routine(APPEND_5)));
code
}
/// A registered function that calls `exit(SECOND_STATUS)`. The code after the
/// call would record that `exit` returned.
fn exit_again() -> Vec<u8> {
let at = routine(EXIT_AGAIN);
let mut code = vec![0x48, 0x83, 0xEC, 0x28]; // sub rsp, 0x28
code.push(0xB9); // mov ecx, SECOND_STATUS
code.extend(SECOND_STATUS.to_le_bytes());
code.push(0xE8); // call <exit stub>
code.extend(rel32(at + 14, stub(EXIT)));
code.extend([0x48, 0xB8]); // mov rax, RETURNED
code.extend(RETURNED.to_le_bytes());
code.extend([
0xC6, 0x00, 0x01, // mov byte ptr [rax], 1
0x48, 0x83, 0xC4, 0x28, // add rsp, 0x28
0xC3, // ret
]);
code
}
fn guest_with(imports: &'static [(&'static str, &'static str)]) -> Guest {
// The slot of `atexit` depends only on the import list, so a guest built
// without routines tells where it is.
let atexit_slot = slot(&Guest::new(imports, &[]), ATEXIT);
let routines = [
append(1),
append(2),
append(3),
append(4),
append(5),
register_4_then_append_5(atexit_slot),
exit_again(),
];
let guest = Guest::new(imports, &routines);
assert_eq!(slot(&guest, ATEXIT), atexit_slot);
guest
}
fn guest() -> Guest {
guest_with(IMPORTS)
}
fn register(guest: &mut Guest, symbol: &str, index: usize) {
assert_eq!(guest.call(symbol, &[routine(index)]) as u32, 0, "{symbol}");
}
#[test]
fn exit_runs_registered_functions_most_recent_first_then_ends_the_process() {
for imports in [IMPORTS, BY_API_SET] {
let mut guest = guest_with(imports);
// atexit and _crt_atexit feed one list.
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "_crt_atexit", APPEND_2);
register(&mut guest, "atexit", APPEND_3);
assert_eq!(guest.u64_at(LOG), 0);
assert_eq!(guest.state.exit_status(), None);
// The status is an int: the upper half of RCX is not part of it.
let (_, exit) = guest.run("exit", &[0xAAAA_BBBB_1234_5678]);
assert_eq!(exit, ExitReason::ProcessExit(0x1234_5678));
assert_eq!(guest.u64_at(LOG), 321, "last registered runs first");
assert_eq!(guest.state.exit_status(), Some(0x1234_5678));
}
}
#[test]
fn exit_with_nothing_registered_ends_the_process_with_its_status() {
for (argument, status) in [
(0, 0),
(1, 1),
(300, 300),
(0xFFFF_FFFF, 0xFFFF_FFFF),
(0x1_0000_0000, 0),
] {
let mut guest = guest();
// The stub is `call [exit]; hlt`: a service that returned would reach
// the HLT and report Halt.
let (_, exit) = guest.run("exit", &[argument]);
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
assert_eq!(guest.u64_at(LOG), 0);
assert_eq!(guest.state.exit_status(), Some(status));
}
}
/// ISO C 7.22.4.4: registered functions are called in reverse order of
/// registration, "except that a function is called after any previously
/// registered functions that had already been called at the time it was
/// registered". A function registered by the second function to run is
/// therefore the third to run, ahead of the one registered first.
#[test]
fn a_function_registered_while_exit_runs_is_called_next() {
let mut guest = guest();
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "atexit", REGISTER_4_THEN_APPEND_5);
register(&mut guest, "atexit", APPEND_3);
let (_, exit) = guest.run("exit", &[6]);
assert_eq!(exit, ExitReason::ProcessExit(6));
// 3 ran first; then the function that registered 4 and logged 5; then 4,
// registered during exit; then 1, the oldest.
assert_eq!(guest.u64_at(LOG), 3541);
}
/// Calling `exit` from a registered function is undefined in ISO C. Xenora's
/// rule: the functions that have not run yet run once each, and the process
/// ends with the status of the later call. Nothing runs twice and the inner
/// call does not return.
#[test]
fn exit_called_again_from_a_registered_function_finishes_with_the_later_status() {
let mut guest = guest();
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "atexit", EXIT_AGAIN);
register(&mut guest, "atexit", APPEND_3);
let (_, exit) = guest.run("exit", &[5]);
assert_eq!(exit, ExitReason::ProcessExit(SECOND_STATUS));
// 3, then the function that called exit again, then 1 from inside that
// second call. A status of 5 would mean the function never ran.
assert_eq!(guest.u64_at(LOG), 31);
assert_eq!(guest.memory.read_u8(RETURNED).unwrap(), 0);
assert_eq!(guest.state.exit_status(), Some(SECOND_STATUS));
}
#[test]
fn underscore_exit_and_abort_run_no_registered_function() {
for imports in [IMPORTS, BY_API_SET] {
// _exit ends the process with its status, an int.
for (argument, status) in [(9, 9), (0xAAAA_BBBB_0000_0102, 0x102), (0, 0)] {
let mut guest = guest_with(imports);
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "_crt_atexit", APPEND_2);
let (_, exit) = guest.run("_exit", &[argument]);
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
assert_eq!(guest.u64_at(LOG), 0);
assert_eq!(guest.state.exit_status(), Some(status));
}
// abort takes no argument and ends the process with exit code 3,
// whatever the argument registers hold.
for junk in [0, 0x1234] {
let mut guest = guest_with(imports);
register(&mut guest, "atexit", APPEND_1);
let (_, exit) = guest.run("abort", &[junk, junk, junk, junk]);
assert_eq!(exit, ExitReason::ProcessExit(3));
assert_eq!(guest.u64_at(LOG), 0);
assert_eq!(guest.state.exit_status(), Some(3));
}
}
}
#[test]
fn each_way_out_closes_the_guest_handles() {
for symbol in ["exit", "_exit", "abort"] {
let mut guest = guest();
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
assert_ne!(guest.call("CreateEventW", &[0, 0, 1, 0]), 0);
assert_eq!(guest.state.open_handle_count(), 2);
let (_, exit) = guest.run(symbol, &[4]);
assert!(matches!(exit, ExitReason::ProcessExit(_)), "{symbol}");
assert_eq!(guest.state.open_handle_count(), 0, "{symbol}");
}
// With registered functions: they run while the handles are still open,
// and the handles are closed once the last one has returned.
let mut guest = guest();
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
register(&mut guest, "atexit", APPEND_1);
assert_eq!(guest.run("exit", &[0]).1, ExitReason::ProcessExit(0));
assert_eq!(guest.u64_at(LOG), 1);
assert_eq!(guest.state.open_handle_count(), 0);
}
#[test]
fn an_exited_guest_runs_nothing_further() {
for symbol in ["exit", "_exit", "abort"] {
let mut guest = guest();
let first = guest.run(symbol, &[8]).1;
assert!(matches!(first, ExitReason::ProcessExit(_)), "{symbol}");
// Neither another service nor a second exit takes effect.
for (later, argument) in [("SetLastError", 5), ("exit", 9), ("_exit", 9), ("abort", 0)] {
assert_eq!(guest.run(later, &[argument]).1, first, "{symbol}, {later}");
}
assert_eq!(guest.state.last_error(THREAD_A), 0, "{symbol}");
}
}
#[test]
fn functions_already_run_by_cexit_are_not_run_again_by_exit() {
let mut guest = guest();
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "atexit", APPEND_2);
// _cexit runs the registered functions and returns to the caller.
assert_eq!(guest.call("_cexit", &[]), 0);
assert_eq!(guest.u64_at(LOG), 21);
// One registered afterwards is the only one exit has left to run.
register(&mut guest, "atexit", APPEND_3);
assert_eq!(guest.run("exit", &[2]).1, ExitReason::ProcessExit(2));
assert_eq!(guest.u64_at(LOG), 213);
}
#[test]
fn the_three_resolve_under_the_library_and_the_runtime_api_set() {
let state = std::sync::Arc::new(ServicesState::new(std::sync::Arc::new(MockClock::new(0))));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, state);
let named = |name: &str| ImportName::Name(name.to_owned());
for symbol in ["exit", "_exit", "abort"] {
let service = registry
.resolve(UCRT, &named(symbol))
.unwrap_or_else(|| panic!("{symbol}"));
let aliased = registry.resolve(RUNTIME, &named(symbol)).unwrap();
assert!(std::ptr::eq(service, aliased), "{symbol}");
assert_eq!(service.status, ServiceStatus::Partial, "{symbol}");
// Not exported by kernel32, and not through an unrelated API set.
assert!(registry.resolve(KERNEL32, &named(symbol)).is_none());
assert!(
registry
.resolve("api-ms-win-crt-heap-l1-1-0.dll", &named(symbol))
.is_none()
);
}
// The spelling is exact: _Exit is another function and is not provided.
assert!(registry.resolve(UCRT, &named("_Exit")).is_none());
}
+263
View File
@@ -0,0 +1,263 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! C runtime file streams and the Win32 file services on one drive (issue
//! #402). On Windows the C runtime's streams sit on Win32 files, so a file
//! written through one is the file read through the other.
//!
//! In text mode a C stream writes each line feed as a carriage return and a
//! line feed and reads the pair back as a line feed (Microsoft Learn, "fopen,
//! _wfopen"). `ReadFile` and `WriteFile` transfer bytes as they are. Expected
//! bytes are what each test wrote, with that translation applied by hand.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
const KERNEL32: &str = "kernel32.dll";
const UCRT: &str = "ucrtbase.dll";
const IMPORTS: &[(&str, &str)] = &[
(KERNEL32, "CreateFileW"),
(KERNEL32, "ReadFile"),
(KERNEL32, "WriteFile"),
(KERNEL32, "CloseHandle"),
(KERNEL32, "CreateDirectoryW"),
(KERNEL32, "DeleteFileW"),
(UCRT, "fopen"),
(UCRT, "fclose"),
(UCRT, "fgets"),
(UCRT, "fputs"),
(UCRT, "_errno"),
(UCRT, "malloc"),
(UCRT, "free"),
];
const GENERIC_READ: u64 = 0x8000_0000;
const GENERIC_WRITE: u64 = 0x4000_0000;
const CREATE_ALWAYS: u64 = 2;
const OPEN_EXISTING: u64 = 3;
const INVALID_HANDLE: u64 = u64::MAX;
const ENOENT: u32 = 2;
const EBADF: u32 = 9;
const ENOMEM: u32 = 12;
const EACCES: u32 = 13;
// Scratch layout: a wide name, a narrow name, a mode, a transfer buffer and a
// count.
const WIDE: u64 = SCRATCH;
const NARROW: u64 = SCRATCH + 0x200;
const MODE: u64 = SCRATCH + 0x300;
const BUFFER: u64 = SCRATCH + 0x400;
const COUNT: u64 = SCRATCH + 0x800;
fn guest() -> Guest {
Guest::new(IMPORTS, &[])
}
fn narrow(guest: &mut Guest, at: u64, text: &str) -> u64 {
guest.memory.write_bytes(at, text.as_bytes()).unwrap();
guest.memory.write_u8(at + text.len() as u64, 0).unwrap();
at
}
fn wide(guest: &mut Guest, text: &str) -> u64 {
let units: Vec<u8> = text
.encode_utf16()
.chain([0])
.flat_map(u16::to_le_bytes)
.collect();
guest.memory.write_bytes(WIDE, &units).unwrap();
WIDE
}
fn errno(guest: &mut Guest) -> u32 {
let address = guest.call("_errno", &[]);
guest.u32_at(address)
}
fn fopen(guest: &mut Guest, name: &str, mode: &str) -> u64 {
let name = narrow(guest, NARROW, name);
let mode = narrow(guest, MODE, mode);
guest.call("fopen", &[name, mode])
}
/// `CreateFileW` with no sharing restriction on later opens.
fn create_file(guest: &mut Guest, name: &str, access: u64, disposition: u64) -> u64 {
let name = wide(guest, name);
guest.call("CreateFileW", &[name, access, 3, 0, disposition, 0, 0])
}
/// Everything `ReadFile` returns for a file, up to 256 bytes.
fn read_through_win32(guest: &mut Guest, name: &str) -> Vec<u8> {
let handle = create_file(guest, name, GENERIC_READ, OPEN_EXISTING);
assert_ne!(handle, INVALID_HANDLE, "{name}");
assert_eq!(guest.call("ReadFile", &[handle, BUFFER, 256, COUNT, 0]), 1);
let count = guest.u32_at(COUNT) as usize;
let mut bytes = vec![0; count];
guest.memory.read_bytes(BUFFER, &mut bytes).unwrap();
assert_eq!(guest.call("CloseHandle", &[handle]), 1);
bytes
}
fn write_through_win32(guest: &mut Guest, name: &str, bytes: &[u8]) {
let handle = create_file(guest, name, GENERIC_WRITE, CREATE_ALWAYS);
assert_ne!(handle, INVALID_HANDLE, "{name}");
guest.memory.write_bytes(BUFFER, bytes).unwrap();
let count = bytes.len() as u64;
assert_eq!(
guest.call("WriteFile", &[handle, BUFFER, count, COUNT, 0]),
1
);
assert_eq!(u64::from(guest.u32_at(COUNT)), count);
assert_eq!(guest.call("CloseHandle", &[handle]), 1);
}
fn put(guest: &mut Guest, stream: u64, text: &str) -> u32 {
let text = narrow(guest, BUFFER, text);
guest.call("fputs", &[text, stream]) as u32
}
/// One `fgets` of up to 127 characters.
fn get(guest: &mut Guest, stream: u64) -> Option<Vec<u8>> {
if guest.call("fgets", &[BUFFER, 128, stream]) == 0 {
return None;
}
let mut bytes = vec![0; 128];
guest.memory.read_bytes(BUFFER, &mut bytes).unwrap();
let end = bytes.iter().position(|byte| *byte == 0).unwrap();
bytes.truncate(end);
Some(bytes)
}
#[test]
fn a_file_written_through_a_c_stream_is_read_through_win32() {
let mut guest = guest();
// Text mode stores a carriage return before each line feed.
let stream = fopen(&mut guest, "from-c.txt", "w");
assert_ne!(stream, 0);
assert_eq!(put(&mut guest, stream, "line one\nline two\n"), 0);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
assert_eq!(
read_through_win32(&mut guest, "C:\\from-c.txt"),
b"line one\r\nline two\r\n"
);
// Binary mode stores what was written.
let stream = fopen(&mut guest, "from-c.bin", "wb");
assert_eq!(put(&mut guest, stream, "raw\nbytes"), 0);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
assert_eq!(read_through_win32(&mut guest, "from-c.bin"), b"raw\nbytes");
// Nothing is held back: the bytes are on the drive before fclose.
let stream = fopen(&mut guest, "unflushed.bin", "wb");
assert_eq!(put(&mut guest, stream, "now"), 0);
assert_eq!(read_through_win32(&mut guest, "unflushed.bin"), b"now");
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
}
#[test]
fn a_file_written_through_win32_is_read_through_a_c_stream() {
let mut guest = guest();
write_through_win32(&mut guest, "C:\\from-win32.txt", b"win32\r\ndata\nlast");
// Text mode reads the pair as one line feed and leaves a lone one alone.
let stream = fopen(&mut guest, "from-win32.txt", "r");
assert_ne!(stream, 0);
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"win32\n"[..]));
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"data\n"[..]));
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"last"[..]));
assert_eq!(get(&mut guest, stream), None);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
// Binary mode reads the bytes as they are.
let stream = fopen(&mut guest, "from-win32.txt", "rb");
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"win32\r\n"[..]));
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
// A file Win32 created is there for "r", and "w" destroys its contents
// for Win32 too.
let stream = fopen(&mut guest, "from-win32.txt", "w");
assert_ne!(stream, 0);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
assert!(read_through_win32(&mut guest, "from-win32.txt").is_empty());
}
#[test]
fn directories_are_not_files_and_hold_files() {
let mut guest = guest();
let name = wide(&mut guest, "C:\\folder");
assert_eq!(guest.call("CreateDirectoryW", &[name, 0]), 1);
// A directory cannot be opened as a stream, for reading or writing.
for mode in ["r", "w", "a", "r+"] {
assert_eq!(fopen(&mut guest, "folder", mode), 0, "{mode}");
assert_eq!(errno(&mut guest), EACCES, "{mode}");
}
// A file inside it can, by either slash.
let stream = fopen(&mut guest, "folder/inside.txt", "wb");
assert_ne!(stream, 0);
assert_eq!(put(&mut guest, stream, "in"), 0);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
assert_eq!(
read_through_win32(&mut guest, "c:\\FOLDER\\inside.txt"),
b"in"
);
// A directory that does not exist has no files.
assert_eq!(fopen(&mut guest, "nowhere\\inside.txt", "w"), 0);
assert_eq!(errno(&mut guest), ENOENT);
}
/// A C stream is not a Win32 handle: it does not stop the file being deleted.
/// Once the file is gone the stream's operations fail with `EBADF`, and
/// closing it still succeeds. This is Xenora's behaviour, not Windows's,
/// where the open stream would keep the file from being deleted.
#[test]
fn a_stream_whose_file_was_deleted_fails_cleanly() {
let mut guest = guest();
let stream = fopen(&mut guest, "gone.txt", "w+b");
assert_ne!(stream, 0);
assert_eq!(put(&mut guest, stream, "data\n"), 0);
let name = wide(&mut guest, "C:\\gone.txt");
assert_eq!(guest.call("DeleteFileW", &[name]), 1);
assert_eq!(put(&mut guest, stream, "more"), u32::MAX);
assert_eq!(errno(&mut guest), EBADF);
assert_eq!(get(&mut guest, stream), None);
assert_eq!(errno(&mut guest), EBADF);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
// The closed stream is no stream any more.
let exit = guest.fails("fclose", &[stream]);
assert_eq!(exit, RUNTIME_LIMIT);
assert!(matches!(exit, ExitReason::IllegalInstruction(0xFE)));
// And the name is free again.
assert_eq!(fopen(&mut guest, "gone.txt", "r"), 0);
assert_eq!(errno(&mut guest), ENOENT);
}
/// A `FILE` object comes from the process heap. When the heap has no room for
/// one, `fopen` fails with `ENOMEM` and has neither created the file nor
/// destroyed the contents of an existing one. The heap holds 4,096 blocks.
#[test]
fn an_fopen_that_cannot_allocate_leaves_the_drive_alone() {
let mut guest = guest();
write_through_win32(&mut guest, "kept.txt", b"keep me");
// Fill the heap one byte at a time until it refuses.
let mut blocks = Vec::new();
loop {
let block = guest.call("malloc", &[1]);
if block == 0 {
break;
}
blocks.push(block);
assert!(blocks.len() <= 4096, "the heap never filled");
}
for (name, mode) in [
("new.txt", "w"),
("new.txt", "a"),
("kept.txt", "w"),
("kept.txt", "r"),
] {
assert_eq!(fopen(&mut guest, name, mode), 0, "{name} {mode}");
assert_eq!(errno(&mut guest), ENOMEM, "{name} {mode}");
}
// With room for one block again: the new file was never created, and the
// existing one still has its contents.
guest.call("free", &[blocks.pop().unwrap()]);
assert_eq!(fopen(&mut guest, "new.txt", "r"), 0);
assert_eq!(errno(&mut guest), ENOENT);
assert_eq!(read_through_win32(&mut guest, "kept.txt"), b"keep me");
}
@@ -0,0 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Run the benchmark's report, comparison and percentile tests in normal CI.
//! Timing runs remain confined to the standalone benchmark entry point.
#[allow(dead_code)]
#[path = "../benches/dbt_bench.rs"]
mod benchmark;
+440
View File
@@ -0,0 +1,440 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate A2 (issue #419): a hosted C program, built from source by this test
//! with the mingw-w64 C runtime and run through the loader, the standard
//! services and the ARM64 DBT.
//!
//! "Hosted" means the C runtime's own startup code runs before `main`, and
//! the program uses the standard C library as an ordinary program does:
//! command-line arguments, heap memory, `qsort` with a callback, `printf`, a
//! file written with `fprintf` and read back with `fgets`, `atexit`, and a
//! return from `main`.
//!
//! `tests/compat_fixtures/build-gate-a2.sh` compiles
//! `tests/compat_fixtures/gate_a2.c` with `x86_64-w64-mingw32-gcc`, so the
//! test needs mingw-w64 on the host. It fails, and does not skip, when the
//! compiler is missing.
//!
//! Every expected value is recomputed here, in Rust, from the description of
//! the program: nothing is read back from a run and asserted. The host
//! arithmetic and the guest arithmetic share no code. The program also
//! checks its own results and exits with the number of the first check that
//! fails, and three control variants end in three other ways, so a runtime
//! that reported success for everything would fail this test.
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, OnceLock};
use xenora_loader::cpu::ExitReason;
use xenora_loader::imports::ImportRegistry;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
use xenora_loader::startup::{StartupLayout, StartupResult, run_synthetic_startup};
const REPORT: &str = "C:\\gate-a2-report.txt";
const COUNT: usize = 48;
const SEED: u32 = 2026;
const LABEL: &str = "xenora";
const ARGUMENTS: [&str; 3] = ["gate-a2.exe", "2026", LABEL];
const BUDGET: usize = 2_000_000;
/// Build every variant once and return the output directory.
fn built() -> &'static Path {
static OUT: OnceLock<PathBuf> = OnceLock::new();
OUT.get_or_init(|| {
// One directory per test process: two `cargo test` runs that share a
// target directory must not write and read the same files.
let out = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
.join(format!("gate-a2-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&out);
let script = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/compat_fixtures/build-gate-a2.sh"
);
let build = Command::new("sh")
.arg(script)
.arg(&out)
.output()
.expect("run tests/compat_fixtures/build-gate-a2.sh");
assert!(
build.status.success(),
"the Gate A2 program did not build; it needs mingw-w64 \
(x86_64-w64-mingw32-gcc):\n{}{}",
String::from_utf8_lossy(&build.stdout),
String::from_utf8_lossy(&build.stderr)
);
let toolchain = std::fs::read_to_string(out.join("toolchain.txt")).unwrap();
println!("Gate A2 built with:\n{toolchain}");
out
})
}
struct Outcome {
result: StartupResult,
state: Arc<ServicesState>,
}
impl Outcome {
fn output(&self) -> String {
String::from_utf8(self.state.standard_output()).expect("ASCII output")
}
fn errors(&self) -> String {
String::from_utf8(self.state.standard_error()).expect("ASCII output")
}
}
/// Run one built variant through the real startup path with the standard
/// services and the given command line, loaded away from its preferred base
/// so its relocations matter.
fn run_with(name: &str, arguments: Option<&[&str]>, budget: usize) -> Outcome {
let bytes = std::fs::read(built().join(format!("{name}.exe"))).unwrap();
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
if let Some(arguments) = arguments {
state.set_program_arguments(arguments).unwrap();
}
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::clone(&state));
let layout = StartupLayout {
image_base: 0x2_5000_0000,
stack_top: 0x2_0001_0000,
tls_base: 0x3_0000_0000,
};
let result = run_synthetic_startup(&bytes, layout, registry, budget)
.unwrap_or_else(|error| panic!("{name}: {error}"));
Outcome { result, state }
}
fn run(name: &str) -> Outcome {
run_with(name, Some(&ARGUMENTS), BUDGET)
}
// ---------------------------------------------------------------------------
// What the program computes, restated independently
// ---------------------------------------------------------------------------
/// The program's generator: a linear congruential step, then bits 8 to 23.
fn values(seed: u32) -> Vec<u32> {
let mut state = seed;
(0..COUNT)
.map(|_| {
state = state.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(state >> 8) & 0xFFFF
})
.collect()
}
/// 64-bit FNV-1a over each value's four bytes, low byte first.
fn checksum(values: &[u32]) -> u64 {
values
.iter()
.flat_map(|value| value.to_le_bytes())
.fold(14_695_981_039_346_656_037, |sum, byte| {
(sum ^ u64::from(byte)).wrapping_mul(1_099_511_628_211)
})
}
struct Expected {
/// Standard output of a complete run, with the line ends a text-mode
/// stream produces.
output: String,
/// The report file as it is stored on the drive.
report: String,
/// What the program prints before its first self-check on the data.
arguments: String,
sorted_line: String,
}
/// How many checks the program counts on a complete run: five on its
/// arguments, one for the allocation, 47 on the sort order, one on the total,
/// the first `fopen`, five on writing the report, fifteen on reading it back
/// and one for the missing file.
const CHECKS: u32 = 5 + 1 + 47 + 1 + 1 + 5 + 15 + 1;
fn expected() -> Expected {
let unsorted = values(SEED);
let mut sorted = unsorted.clone();
sorted.sort_unstable();
let total: u64 = unsorted.iter().map(|value| u64::from(*value)).sum();
let (min, max) = (sorted[0], sorted[COUNT - 1]);
// A text-mode stream stores each line feed as a carriage return and a
// line feed.
let arguments = format!(
"gate a2: 3 arguments\r\n argv[0] = \"gate-a2.exe\"\r\n argv[1] = \"{SEED}\"\r\n \
argv[2] = \"{LABEL}\"\r\n"
);
let sorted_line = format!("sorted {COUNT} values: min {min}, max {max}, total {total}\r\n");
let output = format!(
"{arguments}{sorted_line}checksum before {:016x}, after {:016x}\r\nreport \
gate-a2-report.txt read back and verified\r\natexit: {CHECKS} checks passed\r\n",
checksum(&unsorted),
checksum(&sorted)
);
let report = format!("label {LABEL}\r\ntotal {total}\r\nrange {min} {max}\r\nend\r\n");
Expected {
output,
report,
arguments,
sorted_line,
}
}
#[test]
fn the_restated_program_is_not_trivial() {
// The generator really produces varied data, the sort really changes it,
// and the two checksums really differ: the expected text is not built
// from degenerate values.
let unsorted = values(SEED);
let mut sorted = unsorted.clone();
sorted.sort_unstable();
assert_ne!(unsorted, sorted);
assert_ne!(checksum(&unsorted), checksum(&sorted));
let mut distinct = sorted.clone();
distinct.dedup();
assert!(distinct.len() > COUNT / 2);
assert_eq!(CHECKS, 76);
}
// ---------------------------------------------------------------------------
// The gate
// ---------------------------------------------------------------------------
#[test]
fn the_program_runs_to_its_exit_at_every_optimization_level() {
let wanted = expected();
for name in ["gate-a2-O0", "gate-a2-O1", "gate-a2-O2", "gate-a2-Os"] {
let outcome = run(name);
let result = &outcome.result;
let state = &outcome.state;
// It returned from main, and the C runtime turned that into exit(0).
assert_eq!(
result.execution.exit_reason,
ExitReason::ProcessExit(0),
"{name}: stdout {:?}, stderr {:?}",
outcome.output(),
outcome.errors()
);
assert_eq!(state.exit_status(), Some(0), "{name}");
// Standard output, byte for byte, including the line the function
// registered with atexit printed after main returned.
assert_eq!(outcome.output(), wanted.output, "{name}");
assert_eq!(outcome.errors(), "", "{name}");
// The report file is on the drive as the program wrote it, and the
// file it looked for was not created.
let report = state.file_contents(REPORT).expect("a report");
assert_eq!(String::from_utf8(report).unwrap(), wanted.report, "{name}");
assert_eq!(
state.file_contents("C:\\gate-a2-missing.txt"),
None,
"{name}"
);
assert_eq!(state.open_handle_count(), 0, "{name}");
// It was loaded, relocated and bound by the real startup path, and
// ran as translated ARM64 code. The C runtime's startup code is most
// of what runs.
assert!(
result.bound_imports >= 40,
"{name}: {}",
result.bound_imports
);
assert!(result.relocations.applied_dir64 > 0, "{name}");
let metrics = &result.dbt_metrics;
assert!(
metrics.blocks_compiled > 0 && metrics.native_bytes_emitted > 0,
"{name}"
);
assert!(metrics.instructions_executed > 5_000, "{name}");
assert!(metrics.service_calls > 60, "{name}");
println!(
"{name}: {} imports bound, {} guest instructions, {} of them through the shared \
semantics, {} service calls",
result.bound_imports,
metrics.instructions_executed,
metrics.interpreter_fallbacks,
metrics.service_calls
);
}
}
#[test]
fn other_arguments_give_other_results() {
// A different seed and label change the data, the checksums and the
// report, so the expected text above is not a constant the runtime could
// echo.
let outcome = run_with("gate-a2-O1", Some(&["a2", "7", "seven"]), BUDGET);
assert_eq!(
outcome.result.execution.exit_reason,
ExitReason::ProcessExit(0)
);
let unsorted = values(7);
let mut sorted = unsorted.clone();
sorted.sort_unstable();
let total: u64 = unsorted.iter().map(|value| u64::from(*value)).sum();
let output = outcome.output();
assert!(
output.starts_with(
"gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"7\"\r\n argv[2] = \
\"seven\"\r\n"
),
"{output:?}"
);
assert!(
output.contains(&format!(
"sorted {COUNT} values: min {}, max {}, total {total}\r\n",
sorted[0],
sorted[COUNT - 1]
)),
"{output:?}"
);
assert!(
output.contains(&format!(
"checksum before {:016x}, after {:016x}\r\n",
checksum(&unsorted),
checksum(&sorted)
)),
"{output:?}"
);
let report = outcome.state.file_contents(REPORT).unwrap();
assert_eq!(
String::from_utf8(report).unwrap(),
format!(
"label seven\r\ntotal {total}\r\nrange {} {}\r\nend\r\n",
sorted[0],
sorted[COUNT - 1]
)
);
}
#[test]
fn wrong_arguments_fail_the_check_that_looks_at_them() {
// (arguments, exit status, the lines printed before the failure)
let cases: [(Option<&[&str]>, u32, &str); 4] = [
// No host arguments: one empty argument, so the count is wrong.
(None, 11, "gate a2: 1 arguments\r\n argv[0] = \"\"\r\n"),
(
Some(&["a2", "5"]),
11,
"gate a2: 2 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5\"\r\n",
),
// A seed that is not a number.
(
Some(&["a2", "5x", "label"]),
13,
"gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5x\"\r\n argv[2] = \
\"label\"\r\n",
),
// An empty label.
(
Some(&["a2", "5", ""]),
14,
"gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5\"\r\n argv[2] = \
\"\"\r\n",
),
];
for (arguments, status, printed) in cases {
let outcome = run_with("gate-a2-O1", arguments, BUDGET);
let what = format!("{arguments:?}");
assert_eq!(
outcome.result.execution.exit_reason,
ExitReason::ProcessExit(status),
"{what}"
);
// The failed check says so on standard error, and the function
// registered with atexit still runs, because main returned. It
// reports the checks that passed before the failure: registering
// itself, and then one for each argument check before this one.
assert_eq!(
outcome.errors(),
format!("gate a2: check {status} failed\r\n"),
"{what}"
);
let passed = status - 10;
assert_eq!(
outcome.output(),
format!("{printed}atexit: {passed} checks passed\r\n"),
"{what}"
);
assert_eq!(outcome.state.file_contents(REPORT), None, "{what}");
}
}
#[test]
fn a_wrong_expectation_exits_with_the_number_of_the_failed_check() {
// The variant expects the sorted total to be one more than it is.
// Everything before that check passes, and nothing after it runs.
let wanted = expected();
let outcome = run("gate-a2-break");
assert_eq!(
outcome.result.execution.exit_reason,
ExitReason::ProcessExit(22)
);
assert_eq!(outcome.state.exit_status(), Some(22));
assert_eq!(outcome.errors(), "gate a2: check 22 failed\r\n");
// Five argument checks, the allocation and 47 comparisons passed.
assert_eq!(
outcome.output(),
format!("{}atexit: 53 checks passed\r\n", wanted.arguments)
);
assert_eq!(outcome.state.file_contents(REPORT), None);
}
#[test]
fn exit_half_way_runs_the_registered_function_and_nothing_after() {
// The variant calls exit(42) after the sort. The status is exit's, the
// function registered with atexit runs, and the report is never written.
let wanted = expected();
let outcome = run("gate-a2-exit");
assert_eq!(
outcome.result.execution.exit_reason,
ExitReason::ProcessExit(42)
);
assert_eq!(outcome.state.exit_status(), Some(42));
assert_eq!(outcome.errors(), "");
let output = outcome.output();
assert!(
output.starts_with(&format!("{}{}", wanted.arguments, wanted.sorted_line)),
"{output:?}"
);
// Through check 22: 5 + 1 + 47 + 1.
assert!(
output.ends_with("atexit: 54 checks passed\r\n"),
"{output:?}"
);
assert!(!output.contains("report "), "{output:?}");
assert_eq!(outcome.state.file_contents(REPORT), None);
}
#[test]
fn abort_half_way_runs_no_registered_function() {
// The variant calls abort() after the sort: exit code 3, and the function
// registered with atexit does not run.
let wanted = expected();
let outcome = run("gate-a2-abort");
assert_eq!(
outcome.result.execution.exit_reason,
ExitReason::ProcessExit(3)
);
assert_eq!(outcome.state.exit_status(), Some(3));
let output = outcome.output();
assert!(
output.starts_with(&format!("{}{}", wanted.arguments, wanted.sorted_line)),
"{output:?}"
);
assert!(!output.contains("atexit:"), "{output:?}");
assert_eq!(outcome.state.file_contents(REPORT), None);
}
#[test]
fn a_step_budget_that_is_too_small_is_not_an_exit() {
let outcome = run_with("gate-a2-O1", Some(&ARGUMENTS), 200);
assert_eq!(
outcome.result.execution.exit_reason,
ExitReason::StepLimitExceeded
);
assert_eq!(outcome.state.exit_status(), None);
assert_eq!(outcome.output(), "");
assert_eq!(outcome.state.file_contents(REPORT), None);
}
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Reference outputs for the printf formatting engine, from the host C library.
generate write vectors.txt beside this script
--check regenerate in memory; exit 1 if the committed file differs
The cases are generated here, compiled into a small C program with the host
`clang`, and formatted by the host C library's `snprintf`. That library is an
implementation of ISO C 7.21.6.1 that shares no code with Xenora, so the file
is an independent answer for every case whose result ISO C defines.
Left out on purpose, because the host and Windows differ or ISO C leaves the
result undefined; `crt_format.rs` tests these by hand from Microsoft's page:
- the `l` size (a long is 64 bits on the host and 32 on Windows), `I`, `I32`
and `I64`, which the host does not know
- `%p`, and a null pointer for `%s`
- `#` with `d`, `i`, `u`, `c` or `s`, `0` with `c` or `s`, and a precision
with `c`, which ISO C leaves undefined
- floating point, wide characters and `%n`, which the engine refuses
Each line of vectors.txt is three tab-separated fields:
format the format string, in hexadecimal
arguments comma-separated, in order; `i:<16 hex digits>` is an 8-byte
argument slot as the Win64 calling convention passes it (for an
int the upper half is junk that must be ignored); `s:<hex>` is a
string argument's bytes
output what snprintf wrote, in hexadecimal
Standard library only (Python 3.9+). Needs `clang` on PATH.
"""
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
VECTORS = HERE / "vectors.txt"
MASK64 = (1 << 64) - 1
class Random:
"""xorshift64*, so the cases do not depend on the Python version."""
def __init__(self, seed):
self.state = seed
def next(self):
s = self.state
s ^= s >> 12
s ^= (s << 25) & MASK64
s ^= s >> 27
self.state = s
return (s * 0x2545F4914F6CDD1D) & MASK64
def below(self, bound):
return self.next() % bound
def pick(self, items):
return items[self.below(len(items))]
EDGES = [0, 1, 2, 7, 8, 9, 10, 15, 16, 99, 100, 127, 128, 255, 256, 4095, 32767, 32768, 65535,
65536, 2**31 - 1, 2**31, 2**32 - 1, 2**32, 2**63 - 1, 2**63, 2**64 - 1]
# size prefix -> (bits, C type for a signed conversion, C type for an unsigned one)
SIZES = {
"": (32, "int", "unsigned"),
"hh": (8, "int", "unsigned"),
"h": (16, "int", "unsigned"),
"ll": (64, "long long", "unsigned long long"),
"j": (64, "intmax_t", "uintmax_t"),
"z": (64, "ssize_t", "size_t"),
"t": (64, "ptrdiff_t", "size_t"),
}
STRINGS = [b"", b"a", b"ab", b"hello", b"hello, world", b" padded ", b"100%", b"tab\there",
bytes([0xC3, 0xA9, 0x7E, 0x80, 0xFF]), b"x" * 40]
def value(random):
kind = random.below(4)
if kind == 0:
return random.pick(EDGES)
if kind == 1:
return (-random.pick(EDGES)) & MASK64
if kind == 2:
return random.below(1000)
return random.next()
def junk(random):
"""Upper half of a slot that holds a 32-bit argument."""
return random.pick([0, 0xFFFFFFFF, 0xDEADBEEF, random.next() >> 32]) << 32
def int_argument(random, number):
"""An `int` argument: its C text and its slot."""
low = number & 0xFFFFFFFF
signed = low - (1 << 32) if low >> 31 else low
return f"(int)({signed})", f"i:{junk(random) | low:016x}"
def spec(random, kinds):
"""One conversion specification: (text, [(C argument, slot text)])."""
kind = random.pick(kinds)
arguments = []
# + and blank ask for a sign on a signed conversion. On an unsigned one they
# are defined and have no effect, which is worth checking.
allowed = {"d": "-+ 0", "i": "-+ 0", "u": "-+ 0", "o": "-+ #0", "x": "-+ #0", "X": "-+ #0",
"c": "-", "s": "-"}[kind]
flags = "".join(flag for flag in allowed if random.below(3) == 0)
if flags and random.below(2):
flags = flags[::-1]
text = "%" + flags
choice = random.below(6)
if choice in (1, 2):
text += str(random.pick([1, 2, 3, 5, 8, 12, 20, 33]))
elif choice == 3:
text += "*"
width = random.pick([0, 1, 4, 9, 17, -1, -6, -15])
arguments.append(int_argument(random, width))
if kind != "c":
choice = random.below(7)
if choice == 1:
text += "."
elif choice in (2, 3):
text += "." + str(random.pick([0, 1, 2, 4, 7, 11, 25]))
elif choice == 4:
text += ".*"
precision = random.pick([0, 1, 3, 6, 14, -1, -5])
arguments.append(int_argument(random, precision))
if kind == "c":
byte = random.pick([0x41, 0x7A, 0x20, 0x25, 0x01, 0x7F, 0x80, 0xFF, 0x00, random.below(256)])
# The argument is an int; only its low byte is the character.
number = byte | (random.below(3) << 8)
arguments.append(int_argument(random, number))
elif kind == "s":
string = random.pick(STRINGS)
literal = "".join(f"\\{byte:03o}" for byte in string)
arguments.append((f'"{literal}"', "s:" + string.hex()))
else:
size = random.pick(list(SIZES))
text += size
bits, signed_type, unsigned_type = SIZES[size]
number = value(random)
if bits == 64:
if kind in "di":
signed = number - (1 << 64) if number >> 63 else number
# LLONG_MIN has no literal of its own.
literal = "(-9223372036854775807LL - 1)" if signed == -(1 << 63) else f"{signed}LL"
arguments.append((f"({signed_type})({literal})", f"i:{number:016x}"))
else:
arguments.append((f"({unsigned_type})({number}ULL)", f"i:{number:016x}"))
else:
# hh and h arguments are passed as an int that need not be in
# range: the library converts it before printing.
arguments.append(int_argument(random, number))
return text + kind, arguments
def cases():
random = Random(0x9E3779B97F4A7C15)
out = []
literals = ["", "a", " ", "x=", "[", "]", "%%", "100%% ", "\n", "end"]
for index in range(2600):
if index < 1500:
kinds = "diuoxX"
elif index < 1800:
kinds = "cs"
else:
kinds = "diuoxXcs"
count = 1 if index < 1800 else 1 + random.below(3)
text, arguments = random.pick(literals), []
for _ in range(count):
piece, more = spec(random, kinds)
text += piece + random.pick(literals)
arguments += more
out.append((text.encode(), arguments))
return out
def reference(all_cases):
lines = ["#include <stdio.h>", "#include <stdint.h>", "#include <stddef.h>",
"#include <sys/types.h>",
"static char b[8192];",
"static void emit(int n) {",
" if (n < 0 || n >= (int)sizeof b) { puts(\"!\"); return; }",
" for (int i = 0; i < n; i++) printf(\"%02x\", (unsigned char)b[i]);",
" putchar('\\n');",
"}",
"int main(void) {"]
for text, arguments in all_cases:
literal = "".join(f"\\{byte:03o}" for byte in text)
call = ", ".join([f'"{literal}"'] + [argument for argument, _ in arguments])
lines.append(f" emit(snprintf(b, sizeof b, {call}));")
lines += [" return 0;", "}"]
with tempfile.TemporaryDirectory() as directory:
source, binary = Path(directory, "reference.c"), Path(directory, "reference")
source.write_text("\n".join(lines) + "\n")
subprocess.run(["clang", "-w", "-O0", source, "-o", binary], check=True)
output = subprocess.run([binary], check=True, capture_output=True, text=True).stdout
results = output.splitlines()
if len(results) != len(all_cases) or "!" in results:
sys.exit("the reference program did not format every case")
return results
def main(argv):
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
sys.exit("usage: reference.py generate|--check")
all_cases = cases()
results = reference(all_cases)
header = ["# Generated by crates/loader/tests/printf/reference.py from the host C library's",
"# snprintf. Do not edit. Fields: format, arguments, output; see that script."]
rows = [f"{text.hex()}\t{','.join(slot for _, slot in arguments)}\t{result}"
for (text, arguments), result in zip(all_cases, results)]
content = "\n".join(header + rows) + "\n"
if argv[1] == "generate":
VECTORS.write_text(content)
elif not VECTORS.exists() or VECTORS.read_text() != content:
sys.exit("vectors.txt differs from the host C library's output; run reference.py generate")
print(f"vectors.txt: {len(rows)} cases")
if __name__ == "__main__":
main(sys.argv)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -33,6 +33,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
"std",
"MTLAllocation",
"MTLArgument",
"MTLBlitCommandEncoder",
"MTLBuffer",
"MTLCommandBuffer",
"MTLCommandEncoder",
+513 -41
View File
@@ -11,8 +11,9 @@ use std::ptr::NonNull;
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::ProtocolObject;
use objc2_metal::{
MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize, MTLStorageMode,
MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder,
MTLCommandQueue, MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize,
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{SamplerError, TextureMetadata};
@@ -100,6 +101,9 @@ impl Rgba8TextureDesc {
pub struct MetalRgba8Texture {
texture: Retained<ProtocolObject<dyn MTLTexture>>,
desc: Rgba8TextureDesc,
/// Shared storage, which `replaceRegion` may write. Private textures are
/// filled only through `upload_staged`.
cpu_writable: bool,
}
impl MetalRgba8Texture {
@@ -108,6 +112,19 @@ impl MetalRgba8Texture {
device: &ProtocolObject<dyn MTLDevice>,
desc: Rgba8TextureDesc,
) -> Result<Self, MetalError> {
Self::allocate_with_storage(device, desc, MTLStorageMode::Shared)
}
fn allocate_with_storage(
device: &ProtocolObject<dyn MTLDevice>,
desc: Rgba8TextureDesc,
storage: MTLStorageMode,
) -> Result<Self, MetalError> {
let options = if storage == MTLStorageMode::Private {
MTLResourceOptions::StorageModePrivate
} else {
MTLResourceOptions::StorageModeShared
};
autoreleasepool(|_| {
// SAFETY: Validated non-zero dimensions within MAX_TEXTURE_PIXELS and RGBA8Unorm format.
let descriptor = unsafe {
@@ -124,8 +141,8 @@ impl MetalRgba8Texture {
descriptor.setMipmapLevelCount(desc.mips as usize);
}
}
descriptor.setStorageMode(MTLStorageMode::Shared);
descriptor.setResourceOptions(MTLResourceOptions::StorageModeShared);
descriptor.setStorageMode(storage);
descriptor.setResourceOptions(options);
descriptor.setUsage(MTLTextureUsage::ShaderRead);
let texture = device
@@ -137,51 +154,25 @@ impl MetalRgba8Texture {
)
})?;
Ok(Self { texture, desc })
Ok(Self {
texture,
desc,
cpu_writable: storage == MTLStorageMode::Shared,
})
})
}
/// Upload a single validated mip level into this texture.
///
/// Only Shared-storage textures from `allocate` or `upload` accept CPU writes.
pub fn upload_mip(&self, mip: &Rgba8MipLevel<'_>) -> Result<(), MetalError> {
let (expected_w, expected_h) = self.desc.mip_extent(mip.level)?;
if mip.width != expected_w || mip.height != expected_h {
if !self.cpu_writable {
return Err(MetalError::new(
"mip dimensions",
format!(
"mip level {} expected {}x{}, got {}x{}",
mip.level, expected_w, expected_h, mip.width, mip.height
),
));
}
let tight_pitch = mip
.width
.checked_mul(RGBA8_TEXEL_BYTES)
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
if mip.row_pitch < tight_pitch {
return Err(MetalError::new(
"row pitch",
format!(
"row pitch {} smaller than tight pitch {}",
mip.row_pitch, tight_pitch
),
));
}
let min_bytes = mip
.row_pitch
.checked_mul(mip.height)
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
if mip.bytes.len() < min_bytes {
return Err(MetalError::new(
"mip buffer bounds",
format!(
"buffer length {} is less than required {}",
mip.bytes.len(),
min_bytes
),
"texture storage",
"a Private-storage texture is filled only by upload_staged",
));
}
validate_mip(&self.desc, mip)?;
autoreleasepool(|_| {
let region = MTLRegion {
@@ -227,6 +218,148 @@ impl MetalRgba8Texture {
Ok(texture)
}
/// Allocate a Private-storage RGBA8 texture and fill every mip level through
/// a reused Shared staging buffer that never exceeds `budget`.
///
/// The plan from [`plan_staged_upload`] is built, and every input checked,
/// before any Metal object is created. Each submission copies its rows into
/// the staging buffer, blits them into the texture and waits until the
/// command buffer has completed. Only a `Completed` status lets the buffer be
/// reused; any other status is returned as an error.
pub fn upload_staged(
device: &ProtocolObject<dyn MTLDevice>,
queue: &ProtocolObject<dyn MTLCommandQueue>,
desc: Rgba8TextureDesc,
mips: &[Rgba8MipLevel<'_>],
budget: StagingBudget,
) -> Result<(Self, StagedUploadReport), MetalError> {
let plan = plan_staged_upload(&desc, mips, budget)?;
let staging_len = plan.iter().map(|s| s.staging_bytes).max().unwrap_or(0);
let texture = Self::allocate_with_storage(device, desc, MTLStorageMode::Private)?;
let staging = device
.newBufferWithLength_options(staging_len, MTLResourceOptions::StorageModeShared)
.ok_or_else(|| MetalError::new("newBufferWithLength", "staging allocation failed"))?;
let mut copied = 0;
for submission in &plan {
for copy in &submission.copies {
let mip = mips
.iter()
.find(|mip| mip.level == copy.level)
.ok_or_else(|| MetalError::new("staged upload", "planned level missing"))?;
let tight = mip.width * RGBA8_TEXEL_BYTES;
for row in 0..copy.rows {
let src = &mip.bytes[(copy.first_row + row) * mip.row_pitch..][..tight];
let offset = copy.staging_offset + row * tight;
// SAFETY: The plan keeps offset + tight within staging_len, the
// buffer is Shared and CPU-visible, and the previous submission
// has completed, so the GPU no longer reads these bytes.
unsafe {
let dst = staging.contents().cast::<u8>().as_ptr().add(offset);
std::ptr::copy_nonoverlapping(src.as_ptr(), dst, tight);
}
}
copied += copy.rows * tight;
}
autoreleasepool(|_| texture.encode_staged(queue, &staging, submission))?;
}
let report = StagedUploadReport {
submissions: plan.len(),
peak_staging_bytes: staging_len,
bytes_copied: copied,
};
Ok((texture, report))
}
fn encode_staged(
&self,
queue: &ProtocolObject<dyn MTLCommandQueue>,
staging: &ProtocolObject<dyn MTLBuffer>,
submission: &StagedSubmission,
) -> Result<(), MetalError> {
let command = queue
.commandBuffer()
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
let blit = command
.blitCommandEncoder()
.ok_or_else(|| MetalError::new("blitCommandEncoder", "blit encoder creation failed"))?;
for copy in &submission.copies {
let (width, _) = self.desc.mip_extent(copy.level)?;
let pitch = width * RGBA8_TEXEL_BYTES;
// SAFETY: The plan validated the level, the row range within the mip and
// the staging range within the buffer. The command buffer retains both
// resources, and the caller waits for completion before reusing staging.
unsafe {
blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
staging,
copy.staging_offset,
pitch,
pitch * copy.rows,
MTLSize { width, height: copy.rows, depth: 1 },
&self.texture,
0,
copy.level as usize,
MTLOrigin { x: 0, y: copy.first_row, z: 0 },
);
}
}
blit.endEncoding();
command.commit();
command.waitUntilCompleted();
check_completed(&command)
}
/// Copy one mip level back into tightly packed RGBA8 bytes through a blit.
///
/// Works for Shared and Private textures and shares no code with the upload
/// paths, so tests can compare its output with independently built pixels.
pub fn read_back(
&self,
device: &ProtocolObject<dyn MTLDevice>,
queue: &ProtocolObject<dyn MTLCommandQueue>,
level: u32,
) -> Result<Vec<u8>, MetalError> {
let (width, height) = self.desc.mip_extent(level)?;
let pitch = width * RGBA8_TEXEL_BYTES;
let len = pitch * height;
autoreleasepool(|_| {
let buffer = device
.newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
.ok_or_else(|| {
MetalError::new("newBufferWithLength", "readback allocation failed")
})?;
let command = queue.commandBuffer().ok_or_else(|| {
MetalError::new("commandBuffer", "command buffer creation failed")
})?;
let blit = command.blitCommandEncoder().ok_or_else(|| {
MetalError::new("blitCommandEncoder", "blit encoder creation failed")
})?;
// SAFETY: The level is in range, the source region is the whole mip and
// the destination buffer holds exactly pitch * height bytes.
unsafe {
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage(
&self.texture,
0,
level as usize,
MTLOrigin { x: 0, y: 0, z: 0 },
MTLSize { width, height, depth: 1 },
&buffer,
0,
pitch,
len,
);
}
blit.endEncoding();
command.commit();
command.waitUntilCompleted();
check_completed(&command)?;
// SAFETY: The command buffer completed, so the Shared buffer holds len
// initialized bytes and the GPU no longer writes it.
let bytes =
unsafe { std::slice::from_raw_parts(buffer.contents().cast::<u8>().as_ptr(), len) };
Ok(bytes.to_vec())
})
}
/// Access the underlying native Metal texture protocol object.
#[inline]
pub fn raw(&self) -> &ProtocolObject<dyn MTLTexture> {
@@ -240,6 +373,198 @@ impl MetalRgba8Texture {
}
}
/// Upper bound on the staging bytes one staged upload holds at a time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagingBudget {
max_bytes: usize,
}
impl StagingBudget {
/// A budget of `max_bytes`, which must be a non-zero multiple of the RGBA8
/// texel size so every staged row starts on a texel boundary.
pub fn new(max_bytes: usize) -> Result<Self, MetalError> {
if max_bytes == 0 || !max_bytes.is_multiple_of(RGBA8_TEXEL_BYTES) {
return Err(MetalError::new(
"staging budget",
format!("budget {max_bytes} must be a non-zero multiple of {RGBA8_TEXEL_BYTES}"),
));
}
Ok(Self { max_bytes })
}
/// The largest staging allocation this budget allows.
#[must_use]
pub fn max_bytes(&self) -> usize {
self.max_bytes
}
}
/// One blit of whole rows of one mip level from the staging buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagedCopy {
pub level: u32,
pub first_row: usize,
pub rows: usize,
/// Byte offset of the first row in the staging buffer. Rows are packed tightly.
pub staging_offset: usize,
}
/// The copies that share one staging fill and one command buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StagedSubmission {
pub copies: Vec<StagedCopy>,
/// Staging bytes this submission uses, never more than the budget.
pub staging_bytes: usize,
}
/// What a staged upload did, measured from the executed plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagedUploadReport {
/// Command buffers committed and completed.
pub submissions: usize,
/// Size of the one staging buffer, the most staging memory held at once.
pub peak_staging_bytes: usize,
/// Texel bytes copied into the texture.
pub bytes_copied: usize,
}
/// Split a full RGBA8 upload into budget-sized submissions of whole rows.
///
/// Every level `0..desc.mips` must appear exactly once, because a Private
/// texture has no defined contents for a level nobody writes. Each mip is
/// checked like [`MetalRgba8Texture::upload_mip`] checks it. The budget must hold
/// at least one row of the widest level. Rows are packed in level order, and a
/// submission closes when the next row would exceed the budget.
pub fn plan_staged_upload(
desc: &Rgba8TextureDesc,
mips: &[Rgba8MipLevel<'_>],
budget: StagingBudget,
) -> Result<Vec<StagedSubmission>, MetalError> {
let mut by_level: Vec<Option<&Rgba8MipLevel<'_>>> = vec![None; desc.mips as usize];
for mip in mips {
validate_mip(desc, mip)?;
let slot = &mut by_level[mip.level as usize];
if slot.is_some() {
return Err(MetalError::new(
"staged upload",
format!("mip level {} appears more than once", mip.level),
));
}
*slot = Some(mip);
}
let mut plan = Vec::new();
let mut current = StagedSubmission {
copies: Vec::new(),
staging_bytes: 0,
};
for (level, mip) in by_level.iter().enumerate() {
let mip = mip.ok_or_else(|| {
MetalError::new("staged upload", format!("mip level {level} is missing"))
})?;
let pitch = mip.width * RGBA8_TEXEL_BYTES;
if pitch > budget.max_bytes {
return Err(MetalError::new(
"staging budget",
format!(
"budget {} is smaller than one {pitch}-byte row of mip level {level}",
budget.max_bytes
),
));
}
let mut row = 0;
while row < mip.height {
let fit = (budget.max_bytes - current.staging_bytes) / pitch;
if fit == 0 {
// Unreachable after the row check above, but an empty submission
// that cannot take one row must never loop.
if current.copies.is_empty() {
return Err(MetalError::new(
"staging budget",
"a row does not fit an empty staging buffer",
));
}
plan.push(std::mem::replace(
&mut current,
StagedSubmission {
copies: Vec::new(),
staging_bytes: 0,
},
));
continue;
}
let rows = fit.min(mip.height - row);
current.copies.push(StagedCopy {
level: mip.level,
first_row: row,
rows,
staging_offset: current.staging_bytes,
});
current.staging_bytes += rows * pitch;
row += rows;
}
}
if !current.copies.is_empty() {
plan.push(current);
}
Ok(plan)
}
fn check_completed(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
let status = command.status();
if status != MTLCommandBufferStatus::Completed {
let detail = command.error().map_or_else(
|| format!("unexpected command status {status:?}"),
|error| error.localizedDescription().to_string(),
);
return Err(MetalError::new("waitUntilCompleted", detail));
}
Ok(())
}
/// Check one mip level against the texture description and return its tight row pitch.
fn validate_mip(desc: &Rgba8TextureDesc, mip: &Rgba8MipLevel<'_>) -> Result<usize, MetalError> {
let (expected_w, expected_h) = desc.mip_extent(mip.level)?;
if mip.width != expected_w || mip.height != expected_h {
return Err(MetalError::new(
"mip dimensions",
format!(
"mip level {} expected {}x{}, got {}x{}",
mip.level, expected_w, expected_h, mip.width, mip.height
),
));
}
let tight_pitch = mip
.width
.checked_mul(RGBA8_TEXEL_BYTES)
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
if mip.row_pitch < tight_pitch {
return Err(MetalError::new(
"row pitch",
format!(
"row pitch {} smaller than tight pitch {}",
mip.row_pitch, tight_pitch
),
));
}
let min_bytes = mip
.row_pitch
.checked_mul(mip.height)
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
if mip.bytes.len() < min_bytes {
return Err(MetalError::new(
"mip buffer bounds",
format!(
"buffer length {} is less than required {}",
mip.bytes.len(),
min_bytes
),
));
}
Ok(tight_pitch)
}
/// Resource binding indices and lifetime conventions for sampling pipelines.
///
/// In the Xenora fixture ABI and translated shader conventions:
@@ -328,3 +653,150 @@ impl BoundSampledTexture {
self.sampler_slot
}
}
#[cfg(test)]
mod tests {
use super::*;
fn copy(level: u32, first_row: usize, rows: usize, staging_offset: usize) -> StagedCopy {
StagedCopy {
level,
first_row,
rows,
staging_offset,
}
}
fn levels<'a>(desc: &Rgba8TextureDesc, bytes: &'a [u8]) -> Vec<Rgba8MipLevel<'a>> {
(0..desc.mips)
.map(|level| {
let (w, h) = desc.mip_extent(level).unwrap();
Rgba8MipLevel::new_packed(level, w, h, &bytes[..w * h * RGBA8_TEXEL_BYTES])
})
.collect()
}
fn plan(desc: Rgba8TextureDesc, budget: usize) -> Vec<StagedSubmission> {
let bytes = vec![0; desc.width * desc.height * RGBA8_TEXEL_BYTES];
plan_staged_upload(
&desc,
&levels(&desc, &bytes),
StagingBudget::new(budget).unwrap(),
)
.unwrap()
}
fn error(desc: Rgba8TextureDesc, mips: &[Rgba8MipLevel<'_>], budget: usize) -> String {
plan_staged_upload(&desc, mips, StagingBudget::new(budget).unwrap())
.unwrap_err()
.to_string()
}
#[test]
fn budget_must_be_a_non_zero_texel_multiple() {
assert!(StagingBudget::new(0).is_err());
assert!(StagingBudget::new(6).is_err());
assert_eq!(StagingBudget::new(8).unwrap().max_bytes(), 8);
}
#[test]
fn rows_split_into_budget_sized_submissions() {
// 8 texels × 4 bytes = 32 bytes per row; a 64-byte budget holds two rows.
let desc = Rgba8TextureDesc::new(8, 4, 1).unwrap();
let plan = plan(desc, 64);
assert_eq!(plan.len(), 2);
assert_eq!(plan[0].copies, [copy(0, 0, 2, 0)]);
assert_eq!(plan[1].copies, [copy(0, 2, 2, 0)]);
assert!(plan.iter().all(|s| s.staging_bytes == 64));
}
#[test]
fn one_submission_packs_every_level_when_it_fits() {
// Levels 8×4, 4×2, 2×1: 128 + 32 + 8 = 168 bytes.
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
let plan = plan(desc, 168);
assert_eq!(plan.len(), 1);
assert_eq!(
plan[0].copies,
[copy(0, 0, 4, 0), copy(1, 0, 2, 128), copy(2, 0, 1, 160)]
);
assert_eq!(plan[0].staging_bytes, 168);
}
#[test]
fn a_submission_closes_when_the_next_row_does_not_fit() {
// A 40-byte budget holds one 32-byte row of level 0, then two 16-byte rows of
// level 1 and the single 8-byte row of level 2 together.
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
let plan = plan(desc, 40);
assert_eq!(plan.len(), 5);
for (row, submission) in plan[..4].iter().enumerate() {
assert_eq!(submission.copies, [copy(0, row, 1, 0)]);
assert_eq!(submission.staging_bytes, 32);
}
assert_eq!(plan[4].copies, [copy(1, 0, 2, 0), copy(2, 0, 1, 32)]);
assert_eq!(plan[4].staging_bytes, 40);
}
#[test]
fn every_row_is_planned_once_within_budget() {
for (w, h, mips) in [(1, 1, 1), (37, 19, 6), (64, 3, 7), (5, 128, 8)] {
let desc = Rgba8TextureDesc::new(w, h, mips).unwrap();
let widest = w * RGBA8_TEXEL_BYTES;
for budget in [
widest,
widest + 4,
3 * widest,
w * h * RGBA8_TEXEL_BYTES * 2,
] {
let mut next_row = vec![0; mips as usize];
for submission in plan(desc, budget) {
assert!(submission.staging_bytes <= budget);
let mut offset = 0;
for c in &submission.copies {
let (mw, _) = desc.mip_extent(c.level).unwrap();
assert_eq!(c.first_row, next_row[c.level as usize]);
assert_eq!(c.staging_offset, offset);
assert!(c.rows > 0);
offset += c.rows * mw * RGBA8_TEXEL_BYTES;
next_row[c.level as usize] += c.rows;
}
assert_eq!(offset, submission.staging_bytes);
}
for level in 0..mips {
assert_eq!(next_row[level as usize], desc.mip_extent(level).unwrap().1);
}
}
}
}
#[test]
fn rejects_partial_and_malformed_uploads_before_planning() {
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
let bytes = vec![0; 8 * 4 * RGBA8_TEXEL_BYTES];
let mips = levels(&desc, &bytes);
let missing = error(desc, &mips[..1], 1024);
assert!(missing.contains("mip level 1 is missing"), "{missing}");
let duplicate = error(desc, &[mips[0], mips[1], mips[1]], 1024);
assert!(duplicate.contains("more than once"), "{duplicate}");
let out_of_range = Rgba8MipLevel::new_packed(2, 2, 1, &bytes[..8]);
let range = error(desc, &[mips[0], mips[1], out_of_range], 1024);
assert!(range.contains("out of bounds"), "{range}");
let wrong_size = Rgba8MipLevel::new_packed(1, 4, 1, &bytes[..16]);
assert!(error(desc, &[mips[0], wrong_size], 1024).contains("expected 4x2"));
let mut short_pitch = mips[0];
short_pitch.row_pitch = 28;
assert!(error(desc, &[short_pitch, mips[1]], 1024).contains("row pitch"));
let short_bytes = Rgba8MipLevel::new_packed(0, 8, 4, &bytes[..127]);
assert!(error(desc, &[short_bytes, mips[1]], 1024).contains("buffer length"));
let small = error(desc, &mips, 28);
assert!(small.contains("smaller than one 32-byte row"), "{small}");
}
}
+161
View File
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_metal::texture_pipeline::{Rgba8TextureDesc, StagingBudget, plan_staged_upload};
use xenora_metal::{MetalRgba8Texture, Rgba8MipLevel};
use xenora_texture::{Bc1Upload, Bc1UploadDesc, TiledBc1};
use super::context;
@@ -133,3 +135,162 @@ fn samples_pitched_bc1_upload_across_mips_and_layers() {
);
println!("checked 33 RGBA8 texels from pitched BC1 subresources");
}
/// Texel bytes chosen so neighbouring texels, rows and levels all differ, built
/// without any Xenora code so the readback has an independent expectation.
fn pattern_texel(level: u32, x: usize, y: usize) -> [u8; 4] {
let level = level as usize;
[
(x * 7 + level * 50) as u8,
(y * 13 + level) as u8,
((x ^ y) * 3) as u8,
(255 - level * 9) as u8,
]
}
fn tight_pattern(level: u32, width: usize, height: usize) -> Vec<u8> {
(0..height)
.flat_map(|y| (0..width).flat_map(move |x| pattern_texel(level, x, y)))
.collect()
}
/// Each row padded by `pad` bytes of 0xEE, which must never reach the texture.
fn padded_pattern(level: u32, width: usize, height: usize, pad: usize) -> Vec<u8> {
let tight = tight_pattern(level, width, height);
tight
.chunks(width * 4)
.flat_map(|row| row.iter().copied().chain(std::iter::repeat_n(0xEE, pad)))
.collect()
}
fn padded_levels(desc: Rgba8TextureDesc, pad: usize) -> Vec<(usize, usize, Vec<u8>)> {
(0..desc.mips)
.map(|level| {
let (w, h) = desc.mip_extent(level).unwrap();
(w, h, padded_pattern(level, w, h, pad))
})
.collect()
}
fn mip_views(levels: &[(usize, usize, Vec<u8>)], pad: usize) -> Vec<Rgba8MipLevel<'_>> {
levels
.iter()
.enumerate()
.map(|(level, (w, h, bytes))| Rgba8MipLevel {
level: level as u32,
width: *w,
height: *h,
row_pitch: w * 4 + pad,
bytes,
})
.collect()
}
#[test]
fn staged_upload_matches_the_source_under_every_budget() {
let gpu = context();
// 37×19 has six levels, down to 1×1, and odd sizes at every level.
let desc = Rgba8TextureDesc::new(37, 19, 6).unwrap();
let pad = 12;
let levels = padded_levels(desc, pad);
let mips = mip_views(&levels, pad);
let total: usize = levels.iter().map(|(w, h, _)| w * h * 4).sum();
let widest_row = 37 * 4;
// One submission, several bands, a single row per band, and a budget that
// leaves a remainder at every level.
for budget in [total, 3 * widest_row, widest_row, widest_row + 4] {
let budget = StagingBudget::new(budget).unwrap();
let plan = plan_staged_upload(&desc, &mips, budget).unwrap();
let (texture, report) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget)
.unwrap();
assert_eq!(report.submissions, plan.len());
assert!(report.peak_staging_bytes <= budget.max_bytes());
assert_eq!(report.bytes_copied, total);
if budget.max_bytes() == total {
assert_eq!(report.submissions, 1);
} else {
assert!(report.submissions > 1);
}
for level in 0..desc.mips {
let (w, h) = desc.mip_extent(level).unwrap();
let actual = texture.read_back(gpu.device(), gpu.queue(), level).unwrap();
assert_eq!(
actual,
tight_pattern(level, w, h),
"budget {} level {level}",
budget.max_bytes()
);
}
}
}
#[test]
fn staged_and_direct_uploads_produce_the_same_texels() {
let gpu = context();
let desc = Rgba8TextureDesc::new(16, 9, 5).unwrap();
let levels = padded_levels(desc, 0);
let mips = mip_views(&levels, 0);
let direct = MetalRgba8Texture::upload(gpu.device(), desc, &mips).unwrap();
let budget = StagingBudget::new(16 * 4 * 2).unwrap();
let (staged, _) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
for level in 0..desc.mips {
let (w, h) = desc.mip_extent(level).unwrap();
let expected = tight_pattern(level, w, h);
assert_eq!(
direct.read_back(gpu.device(), gpu.queue(), level).unwrap(),
expected
);
assert_eq!(
staged.read_back(gpu.device(), gpu.queue(), level).unwrap(),
expected
);
}
}
#[test]
fn staged_upload_handles_a_single_texel() {
let gpu = context();
let desc = Rgba8TextureDesc::new(1, 1, 1).unwrap();
let texel = pattern_texel(0, 0, 0);
let mips = [Rgba8MipLevel::new_packed(0, 1, 1, &texel)];
let budget = StagingBudget::new(4).unwrap();
let (texture, report) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
assert_eq!((report.submissions, report.peak_staging_bytes), (1, 4));
assert_eq!(
texture.read_back(gpu.device(), gpu.queue(), 0).unwrap(),
texel
);
}
#[test]
fn staged_upload_rejects_bad_input_before_touching_the_gpu() {
let gpu = context();
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
let levels = padded_levels(desc, 0);
let mips = mip_views(&levels, 0);
let small = StagingBudget::new(28).unwrap();
let error = MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, small)
.unwrap_err();
assert!(!error.is_capability_unavailable());
assert!(
error.to_string().contains("smaller than one 32-byte row"),
"{error}"
);
let budget = StagingBudget::new(1024).unwrap();
let missing =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips[..1], budget)
.unwrap_err();
assert!(
missing.to_string().contains("mip level 1 is missing"),
"{missing}"
);
// A Private texture refuses CPU writes instead of failing inside Metal.
let (texture, _) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
let refused = texture.upload_mip(&mips[0]).unwrap_err();
assert!(refused.to_string().contains("Private-storage"), "{refused}");
}
+161
View File
@@ -0,0 +1,161 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#![cfg(all(feature = "gpu-tests", target_arch = "aarch64", target_os = "macos"))]
use xenora_metal::{MetalError, NativeCompute};
use xenora_texture::{
BcAlphaFormat, BcChannelFormat, BcCopyAlignment, BcFormat, BcTextureDesc, BcTextureLayout,
PackedBcUpload,
};
const EXTENTS: [(usize, usize); 4] = [(9, 5), (4, 2), (2, 1), (1, 1)];
const BLOCK_COUNTS: [usize; 4] = [6, 1, 1, 1];
// Zero selector bits pick the first endpoint. These RGB565 endpoints encode
// exact red, green, blue and white.
const COLORS: [[u8; 2]; 4] = [[0x00, 0xf8], [0xe0, 0x07], [0x1f, 0x00], [0xff, 0xff]];
const PIXELS: [[u8; 4]; 4] = [
[255, 0, 0, 255],
[0, 255, 0, 255],
[0, 0, 255, 255],
[255, 255, 255, 255],
];
fn append_block(bytes: &mut Vec<u8>, format: BcFormat, variant: usize) {
let color = COLORS[variant];
let color_block = [color[0], color[1], 0, 0, 0, 0, 0, 0];
let endpoint_block = |first| [first, 0, 0, 0, 0, 0, 0, 0];
match format {
BcFormat::Bc1 => bytes.extend(color_block),
BcFormat::BcAlpha(format) => {
bytes.extend(match format {
BcAlphaFormat::Bc2 => [0xff; 8],
BcAlphaFormat::Bc3 => endpoint_block(255),
});
bytes.extend(color_block);
}
BcFormat::BcChannel(format) => match format {
BcChannelFormat::Bc4Unorm => bytes.extend(endpoint_block(PIXELS[variant][0])),
BcChannelFormat::Bc5Unorm => {
bytes.extend(endpoint_block(PIXELS[variant][0]));
bytes.extend(endpoint_block(PIXELS[variant][1]));
}
BcChannelFormat::Bc4Snorm => bytes.extend(endpoint_block([129, 127, 0, 64][variant])),
BcChannelFormat::Bc5Snorm => {
bytes.extend(endpoint_block([129, 127, 0, 64][variant]));
bytes.extend(endpoint_block([127, 129, 64, 0][variant]));
}
},
_ => unreachable!("native readback fixture covers BC1–BC5"),
}
}
fn expected_words(format: BcFormat, layer: usize, mip: usize) -> Vec<u32> {
let (width, height) = EXTENTS[mip];
let mut result = Vec::new();
for y in 0..height {
for x in 0..width {
// The base image has a 3×2 physical block grid. Small levels
// have a single block even when either texel extent is below 4.
let variant = ((y / 4) * 3 + x / 4 + layer * 2 + mip) % 4;
let rgba = match format {
BcFormat::Bc1 | BcFormat::BcAlpha(_) => PIXELS[variant],
BcFormat::BcChannel(BcChannelFormat::Bc4Unorm) => [PIXELS[variant][0], 0, 0, 255],
BcFormat::BcChannel(BcChannelFormat::Bc5Unorm) => {
[PIXELS[variant][0], PIXELS[variant][1], 0, 255]
}
BcFormat::BcChannel(BcChannelFormat::Bc4Snorm) => {
[[129, 127, 0, 64][variant], 0, 0, 127]
}
BcFormat::BcChannel(BcChannelFormat::Bc5Snorm) => [
[129, 127, 0, 64][variant],
[127, 129, 64, 0][variant],
0,
127,
],
_ => unreachable!("native readback fixture covers BC1–BC5"),
};
result.push(u32::from_le_bytes(rgba));
}
}
result
}
fn read(
gpu: &NativeCompute,
upload: &PackedBcUpload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
match upload.format() {
BcFormat::Bc1 => gpu.read_bc1_upload(&upload.as_bc1(layer, mip).unwrap(), 0, 0),
BcFormat::BcAlpha(_) => {
gpu.read_bc_alpha_upload(&upload.as_bc_alpha(layer, mip).unwrap(), 0, 0)
}
BcFormat::BcChannel(_) => {
gpu.read_bc_channel_upload(&upload.as_bc_channel(layer, mip).unwrap(), 0, 0)
}
_ => unreachable!("native readback fixture covers BC1–BC5"),
}
}
#[test]
fn packed_and_aligned_bc_uploads_return_known_pixels_on_metal() {
let gpu = NativeCompute::new().expect("native Metal device and queue");
for format in [
BcFormat::Bc1,
BcFormat::BcAlpha(BcAlphaFormat::Bc2),
BcFormat::BcAlpha(BcAlphaFormat::Bc3),
BcFormat::BcChannel(BcChannelFormat::Bc4Unorm),
BcFormat::BcChannel(BcChannelFormat::Bc4Snorm),
BcFormat::BcChannel(BcChannelFormat::Bc5Unorm),
BcFormat::BcChannel(BcChannelFormat::Bc5Snorm),
] {
let desc = BcTextureDesc {
width: 9,
height: 5,
mips: 4,
layers: 2,
format,
};
let tight = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
let aligned = BcTextureLayout::new(
desc,
BcCopyAlignment {
row: 256,
placement: 512,
},
)
.unwrap();
let mut source = Vec::new();
for layer in 0..2 {
for (mip, block_count) in BLOCK_COUNTS.into_iter().enumerate() {
for n in 0..block_count {
append_block(&mut source, format, (n + layer * 2 + mip) % 4);
}
}
}
let tight_upload = PackedBcUpload::new(&tight, &source).unwrap();
let mut staged = vec![0xff; aligned.byte_len()];
tight_upload.repack_into(&aligned, &mut staged).unwrap();
let aligned_upload = PackedBcUpload::new(&aligned, &staged).unwrap();
for (name, upload) in [("tight", &tight_upload), ("aligned", &aligned_upload)] {
for layer in 0..2 {
for mip in 0..EXTENTS.len() {
let actual = read(&gpu, upload, layer, mip as u32).unwrap_or_else(|error| {
if error.is_capability_unavailable() {
panic!("CAPABILITY UNAVAILABLE: {error}");
}
panic!("IMPLEMENTATION FAILURE: {format:?} {name} {layer}/{mip}: {error}");
});
assert_eq!(
actual,
expected_words(format, layer, mip),
"{format:?} {name} layer {layer}, mip {mip}"
);
}
}
}
}
}
+348
View File
@@ -0,0 +1,348 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Linear copy footprints for independently authored block-compressed textures.
//!
//! For example, a 5×3 BC1 level has two 8-byte blocks forming one 16-byte row.
//! Its 2×1 mip takes a single 8-byte block. In a tight layout the levels occupy
//! 24 bytes; either can be borrowed directly from the same payload.
//!
//! ```
//! use xenora_texture::{BcCopyAlignment, BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload};
//!
//! let layout = BcTextureLayout::new(
//! BcTextureDesc { width: 5, height: 3, mips: 2, layers: 1, format: BcFormat::Bc1 },
//! BcCopyAlignment::TIGHT,
//! )?;
//! let mut bytes = vec![0; layout.byte_len()];
//! layout.write_tight(&mut bytes, 0, 1, &[0x55; 8])?;
//! let upload = PackedBcUpload::new(&layout, &bytes)?;
//! assert_eq!(upload.subresource(0, 1)?.bytes, &[0x55; 8]);
//! # Ok::<(), xenora_texture::TextureError>(())
//! ```
use super::{
BLOCK_BYTES, Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload,
BcAlphaUploadDesc, BcChannelFormat, BcChannelUpload, BcChannelUploadDesc, TextureError,
mip_blocks,
};
/// Block encoding carried by the layout. The layout handles bytes without decoding texels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BcFormat {
Bc1,
BcAlpha(BcAlphaFormat),
BcChannel(BcChannelFormat),
Bc6hUfloat,
Bc6hSfloat,
Bc7,
}
impl BcFormat {
pub const fn block_bytes(self) -> usize {
match self {
Self::Bc1 => BLOCK_BYTES,
Self::BcChannel(format) => format.block_bytes(),
Self::BcAlpha(_) => BcAlphaUpload::BLOCK_BYTES,
Self::Bc6hUfloat | Self::Bc6hSfloat | Self::Bc7 => 16,
}
}
}
/// Dimensions and encoding of a 2D texture or texture array.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BcTextureDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
pub layers: usize,
pub format: BcFormat,
}
/// Row and subresource placement alignments, in bytes. Each must be a nonzero
/// power of two. Alignments smaller than a block are raised to its size.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BcCopyAlignment {
pub row: usize,
pub placement: usize,
}
impl BcCopyAlignment {
pub const TIGHT: Self = Self {
row: 1,
placement: 1,
};
}
/// Logical dimensions and physical storage for one mip in one layer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BcFootprint {
pub width: usize,
pub height: usize,
pub offset: usize,
pub row_bytes: usize,
pub row_pitch: usize,
pub block_rows: usize,
/// Full pitched rows, including the final row's padding.
pub byte_len: usize,
}
/// Layer-major storage with one footprint per mip. Layers share the same
/// layout. Placement padding precedes each subresource as needed and there
/// is no trailing placement padding at the end of the final layer.
#[derive(Debug)]
pub struct BcTextureLayout {
desc: BcTextureDesc,
mips: Vec<BcFootprint>,
layer_stride: usize,
byte_len: usize,
}
impl BcTextureLayout {
pub fn new(desc: BcTextureDesc, alignment: BcCopyAlignment) -> Result<Self, TextureError> {
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
if desc.width == 0
|| desc.height == 0
|| desc.layers == 0
|| desc.mips == 0
|| desc.mips > max_mips
|| !alignment.row.is_power_of_two()
|| !alignment.placement.is_power_of_two()
{
return Err(TextureError::InvalidLayout);
}
let block_bytes = desc.format.block_bytes();
let row_alignment = alignment.row.max(block_bytes);
let placement_alignment = alignment.placement.max(block_bytes);
let mut mips = Vec::new();
mips.try_reserve_exact(desc.mips as usize)
.map_err(|_| TextureError::AllocationFailed)?;
let mut layer_len: usize = 0;
for mip in 0..desc.mips {
let (blocks_x, block_rows) = mip_blocks(desc.width, desc.height, mip);
let row_bytes = blocks_x
.checked_mul(block_bytes)
.ok_or(TextureError::SizeOverflow)?;
let row_pitch = align_up(row_bytes, row_alignment)?;
let offset = align_up(layer_len, placement_alignment)?;
let byte_len = row_pitch
.checked_mul(block_rows)
.ok_or(TextureError::SizeOverflow)?;
layer_len = offset
.checked_add(byte_len)
.ok_or(TextureError::SizeOverflow)?;
mips.push(BcFootprint {
width: (desc.width >> mip).max(1),
height: (desc.height >> mip).max(1),
offset,
row_bytes,
row_pitch,
block_rows,
byte_len,
});
}
// A single layer never needs padding after its last mip.
let layer_stride = if desc.layers == 1 {
layer_len
} else {
align_up(layer_len, placement_alignment)?
};
let byte_len = layer_stride
.checked_mul(desc.layers - 1)
.and_then(|prefix| prefix.checked_add(layer_len))
.ok_or(TextureError::SizeOverflow)?;
Ok(Self {
desc,
mips,
layer_stride,
byte_len,
})
}
pub fn byte_len(&self) -> usize {
self.byte_len
}
pub fn footprint(&self, layer: usize, mip: u32) -> Result<BcFootprint, TextureError> {
if layer >= self.desc.layers {
return Err(TextureError::OutOfBounds);
}
let footprint = self
.mips
.get(mip as usize)
.ok_or(TextureError::OutOfBounds)?;
Ok(self.at_layer(*footprint, layer))
}
/// Writes tightly packed block rows to one subresource. Clears that
/// subresource's row padding and leaves the rest of the payload alone.
/// The destination must include exactly this layout's full byte span.
pub fn write_tight(
&self,
dst: &mut [u8],
layer: usize,
mip: u32,
src: &[u8],
) -> Result<(), TextureError> {
let fp = self.footprint(layer, mip)?;
if dst.len() != self.byte_len || src.len() != fp.row_bytes * fp.block_rows {
return Err(TextureError::InvalidByteLength);
}
let dst = &mut dst[fp.offset..fp.offset + fp.byte_len];
dst.fill(0);
copy_rows(src, fp.row_bytes, dst, fp.row_pitch, fp.row_bytes);
Ok(())
}
fn at_layer(&self, mut footprint: BcFootprint, layer: usize) -> BcFootprint {
// Construction checked the span through the end of the final layer.
footprint.offset += self.layer_stride * layer;
footprint
}
}
/// A validated, borrowed payload. Padding bytes in its input may be arbitrary.
#[derive(Debug)]
pub struct PackedBcUpload<'a> {
layout: &'a BcTextureLayout,
bytes: &'a [u8],
}
impl<'a> PackedBcUpload<'a> {
pub fn new(layout: &'a BcTextureLayout, bytes: &'a [u8]) -> Result<Self, TextureError> {
if bytes.len() != layout.byte_len {
return Err(TextureError::InvalidByteLength);
}
Ok(Self { layout, bytes })
}
pub fn format(&self) -> BcFormat {
self.layout.desc.format
}
/// Borrows the selected block rows, including their row padding.
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
let fp = self.layout.footprint(layer, mip)?;
Ok(Bc1Subresource {
bytes: &self.bytes[fp.offset..fp.offset + fp.byte_len],
width: fp.width,
height: fp.height,
row_pitch: fp.row_pitch,
})
}
/// Copies every logical block to an equivalent layout and zeroes its padding.
/// The source and destination must have the same dimensions, mip and layer
/// counts, and block encoding. A rejected copy leaves the destination intact.
pub fn repack_into(
&self,
layout: &BcTextureLayout,
dst: &mut [u8],
) -> Result<(), TextureError> {
if self.layout.desc != layout.desc {
return Err(TextureError::InvalidLayout);
}
if dst.len() != layout.byte_len {
return Err(TextureError::InvalidByteLength);
}
dst.fill(0);
for layer in 0..layout.desc.layers {
for (&source, &target) in self.layout.mips.iter().zip(&layout.mips) {
let source = self.layout.at_layer(source, layer);
let target = layout.at_layer(target, layer);
copy_rows(
&self.bytes[source.offset..source.offset + source.byte_len],
source.row_pitch,
&mut dst[target.offset..target.offset + target.byte_len],
target.row_pitch,
source.row_bytes,
);
}
}
Ok(())
}
/// Adapts one BC1 subresource to the existing single-upload reader, without copying.
pub fn as_bc1(&self, layer: usize, mip: u32) -> Result<Bc1Upload<'a>, TextureError> {
if self.layout.desc.format != BcFormat::Bc1 {
return Err(TextureError::InvalidLayout);
}
let view = self.subresource(layer, mip)?;
Bc1Upload::new(
view.bytes,
Bc1UploadDesc {
width: view.width,
height: view.height,
mips: 1,
layers: 1,
format: 1,
usage: 1,
row_pitch: view.row_pitch,
slice_pitch: view.bytes.len(),
},
)
}
/// Adapts one BC2 or BC3 subresource to the existing reader, without copying.
pub fn as_bc_alpha(&self, layer: usize, mip: u32) -> Result<BcAlphaUpload<'a>, TextureError> {
let BcFormat::BcAlpha(format) = self.layout.desc.format else {
return Err(TextureError::InvalidLayout);
};
let view = self.subresource(layer, mip)?;
BcAlphaUpload::new(
view.bytes,
BcAlphaUploadDesc {
width: view.width,
height: view.height,
mips: 1,
layers: 1,
format,
row_pitch: view.row_pitch,
slice_pitch: view.bytes.len(),
},
)
}
/// Adapts one BC4 or BC5 subresource to the existing reader, without copying.
pub fn as_bc_channel(
&self,
layer: usize,
mip: u32,
) -> Result<BcChannelUpload<'a>, TextureError> {
let BcFormat::BcChannel(format) = self.layout.desc.format else {
return Err(TextureError::InvalidLayout);
};
let view = self.subresource(layer, mip)?;
BcChannelUpload::new(
view.bytes,
BcChannelUploadDesc {
width: view.width,
height: view.height,
mips: 1,
layers: 1,
format,
row_pitch: view.row_pitch,
slice_pitch: view.bytes.len(),
},
)
}
}
fn align_up(value: usize, alignment: usize) -> Result<usize, TextureError> {
value
.checked_next_multiple_of(alignment)
.ok_or(TextureError::SizeOverflow)
}
fn copy_rows(src: &[u8], src_pitch: usize, dst: &mut [u8], dst_pitch: usize, row_bytes: usize) {
for (src_row, dst_row) in src
.chunks_exact(src_pitch)
.zip(dst.chunks_exact_mut(dst_pitch))
{
dst_row[..row_bytes].copy_from_slice(&src_row[..row_bytes]);
}
}
+4
View File
@@ -10,6 +10,7 @@
mod bc;
mod bc6h;
mod bc7;
mod footprint;
pub mod sampler;
mod upload;
pub use bc::{
@@ -19,6 +20,9 @@ pub use bc6h::{
BC6H_SUPPORTED_MODES, Bc6hError, bc6h_mode, decode_bc6h_sfloat, decode_bc6h_ufloat,
};
pub use bc7::{BC7_SUPPORTED_MODES, bc7_mode, decode_bc7};
pub use footprint::{
BcCopyAlignment, BcFootprint, BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload,
};
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
pub use upload::{
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
+375
View File
@@ -0,0 +1,375 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_texture::{
Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcChannelFormat, BcCopyAlignment, BcFootprint,
BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload, TextureError,
};
const DESC: BcTextureDesc = BcTextureDesc {
width: 13,
height: 9,
mips: 4,
layers: 2,
format: BcFormat::Bc1,
};
const ALIGNED: BcCopyAlignment = BcCopyAlignment {
row: 32,
placement: 128,
};
#[test]
fn hand_calculated_footprints_cover_partial_blocks_and_layer_padding() {
let tight = BcTextureLayout::new(DESC, BcCopyAlignment::TIGHT).unwrap();
let aligned = BcTextureLayout::new(DESC, ALIGNED).unwrap();
// 13×9 has four blocks across and three down. 6×4 takes two blocks.
// Both 3×2 and 1×1 take one block each.
let levels = [(13, 9, 32, 3), (6, 4, 16, 1), (3, 2, 8, 1), (1, 1, 8, 1)];
for (layout, offsets, stride, pitches) in [
(&tight, [0, 96, 112, 120], 128, [32, 16, 8, 8]),
(&aligned, [0, 128, 256, 384], 512, [32; 4]),
] {
for layer in 0..2 {
for (mip, (width, height, row_bytes, block_rows)) in levels.into_iter().enumerate() {
let row_pitch = pitches[mip];
assert_eq!(
layout.footprint(layer, mip as u32),
Ok(BcFootprint {
width,
height,
offset: stride * layer + offsets[mip],
row_bytes,
row_pitch,
block_rows,
byte_len: row_pitch * block_rows,
})
);
}
}
}
assert_eq!(tight.byte_len(), 256);
assert_eq!(aligned.byte_len(), 928);
assert_eq!(aligned.footprint(2, 0), Err(TextureError::OutOfBounds));
assert_eq!(aligned.footprint(0, 4), Err(TextureError::OutOfBounds));
}
#[test]
fn compact_chain_uses_block_rows_instead_of_reserving_base_size_for_every_mip() {
let desc = BcTextureDesc {
width: 1024,
height: 1024,
mips: 11,
layers: 1,
..DESC
};
let layout = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
assert_eq!(layout.byte_len(), 699_064);
assert_eq!(layout.footprint(0, 10).unwrap().offset, 699_056);
let compact = vec![0; layout.byte_len()];
PackedBcUpload::new(&layout, &compact).unwrap();
let fixed_slice = Bc1UploadDesc {
width: 1024,
height: 1024,
mips: 11,
layers: 1,
format: 1,
usage: 1,
row_pitch: 2048,
slice_pitch: 524_288,
};
assert_eq!(
Bc1Upload::new(&compact, fixed_slice).unwrap_err(),
TextureError::InvalidByteLength
);
let fixed = vec![0; 5_767_168];
let fixed_upload = Bc1Upload::new(&fixed, fixed_slice).unwrap();
assert_eq!(fixed_upload.subresource(0, 10).unwrap().bytes.len(), 2048);
let aligned = BcTextureLayout::new(
desc,
BcCopyAlignment {
row: 256,
placement: 512,
},
)
.unwrap();
assert_eq!(aligned.byte_len(), 705_280);
assert_eq!(aligned.footprint(0, 10).unwrap().offset, 705_024);
}
#[test]
fn selected_write_clears_its_row_padding_and_preserves_neighbors() {
let layout = BcTextureLayout::new(BcTextureDesc { width: 9, ..DESC }, ALIGNED).unwrap();
let src: Vec<u8> = (1..=72).collect(); // Three 24-byte rows.
let mut dst = vec![0xcc; layout.byte_len()];
layout.write_tight(&mut dst, 1, 0, &src).unwrap();
let mut expected = vec![0xcc; dst.len()];
expected[512..608].fill(0);
expected[512..536].copy_from_slice(&src[..24]);
expected[544..568].copy_from_slice(&src[24..48]);
expected[576..600].copy_from_slice(&src[48..]);
assert_eq!(dst, expected);
let view = PackedBcUpload::new(&layout, &dst).unwrap();
let level = view.subresource(1, 0).unwrap();
assert_eq!(level.bytes, &dst[512..608]);
assert!(std::ptr::eq(level.bytes.as_ptr(), dst[512..].as_ptr()));
assert_eq!((level.width, level.height, level.row_pitch), (9, 9, 32));
let legacy = view.as_bc1(1, 0).unwrap().subresource(0, 0).unwrap();
assert!(std::ptr::eq(legacy.bytes.as_ptr(), level.bytes.as_ptr()));
assert_eq!(legacy.bytes.len(), 96);
}
#[test]
fn repack_ignores_dirty_source_padding_and_zeroes_both_kinds_of_target_padding() {
let tight = BcTextureLayout::new(DESC, BcCopyAlignment::TIGHT).unwrap();
let aligned = BcTextureLayout::new(DESC, ALIGNED).unwrap();
let tight_bytes: Vec<u8> = (0..=255).collect();
// Independent byte map from the paper footprints above.
let spans = [
(0, 0, 96),
(96, 128, 16),
(112, 256, 8),
(120, 384, 8),
(128, 512, 96),
(224, 640, 16),
(240, 768, 8),
(248, 896, 8),
];
let mut dirty_aligned = vec![0xab; 928];
let mut clean_aligned = vec![0; 928];
for (src, dst, len) in spans {
dirty_aligned[dst..dst + len].copy_from_slice(&tight_bytes[src..src + len]);
clean_aligned[dst..dst + len].copy_from_slice(&tight_bytes[src..src + len]);
}
let input = PackedBcUpload::new(&aligned, &dirty_aligned).unwrap();
let mut compact = vec![0xcc; tight.byte_len()];
input.repack_into(&tight, &mut compact).unwrap();
assert_eq!(compact, tight_bytes);
let mut output = vec![0xcc; aligned.byte_len()];
input.repack_into(&aligned, &mut output).unwrap();
assert_eq!(output, clean_aligned);
output.fill(0xcc);
PackedBcUpload::new(&tight, &compact)
.unwrap()
.repack_into(&aligned, &mut output)
.unwrap();
assert_eq!(output, clean_aligned);
}
#[test]
fn validates_sizes_before_writing_and_requires_the_same_encoding() {
let layout = BcTextureLayout::new(DESC, ALIGNED).unwrap();
let mut bytes = vec![0xab; layout.byte_len()];
assert_eq!(
layout.write_tight(&mut bytes, 0, 3, &[0; 7]),
Err(TextureError::InvalidByteLength)
);
assert_eq!(
layout.write_tight(&mut bytes, 0, 3, &[0; 9]),
Err(TextureError::InvalidByteLength)
);
assert_eq!(
layout.write_tight(&mut bytes[..927], 0, 3, &[0; 8]),
Err(TextureError::InvalidByteLength)
);
assert_eq!(
layout.write_tight(&mut bytes, 2, 3, &[0; 8]),
Err(TextureError::OutOfBounds)
);
assert!(bytes.iter().all(|byte| *byte == 0xab));
for len in [0, 927, 929] {
assert_eq!(
PackedBcUpload::new(&layout, &vec![0; len]).unwrap_err(),
TextureError::InvalidByteLength
);
}
let upload = PackedBcUpload::new(&layout, &bytes).unwrap();
for incompatible in [
BcTextureDesc {
format: BcFormat::BcChannel(BcChannelFormat::Bc4Unorm),
..DESC
},
BcTextureDesc { width: 14, ..DESC },
BcTextureDesc { height: 10, ..DESC },
BcTextureDesc { mips: 3, ..DESC },
BcTextureDesc { layers: 1, ..DESC },
] {
let target = BcTextureLayout::new(incompatible, ALIGNED).unwrap();
let mut dst = vec![0xcc; target.byte_len()];
assert_eq!(
upload.repack_into(&target, &mut dst),
Err(TextureError::InvalidLayout)
);
assert!(dst.iter().all(|byte| *byte == 0xcc));
}
let mut short = vec![0xcc; 927];
assert_eq!(
upload.repack_into(&layout, &mut short),
Err(TextureError::InvalidByteLength)
);
assert!(short.iter().all(|byte| *byte == 0xcc));
assert_eq!(
upload.as_bc_alpha(0, 0).unwrap_err(),
TextureError::InvalidLayout
);
assert_eq!(
upload.as_bc_channel(0, 0).unwrap_err(),
TextureError::InvalidLayout
);
assert_eq!(upload.as_bc1(0, 4).unwrap_err(), TextureError::OutOfBounds);
}
#[test]
fn rejects_invalid_descriptors_and_overflowing_footprints() {
for desc in [
BcTextureDesc { width: 0, ..DESC },
BcTextureDesc { height: 0, ..DESC },
BcTextureDesc { mips: 0, ..DESC },
BcTextureDesc { mips: 5, ..DESC },
BcTextureDesc { layers: 0, ..DESC },
] {
assert_eq!(
BcTextureLayout::new(desc, ALIGNED).unwrap_err(),
TextureError::InvalidLayout
);
}
for (row, placement) in [(0, 1), (1, 0), (3, 1), (1, 3)] {
assert_eq!(
BcTextureLayout::new(DESC, BcCopyAlignment { row, placement }).unwrap_err(),
TextureError::InvalidLayout
);
}
for desc in [
BcTextureDesc {
width: usize::MAX,
..DESC
},
BcTextureDesc {
height: usize::MAX,
..DESC
},
BcTextureDesc {
layers: usize::MAX,
..DESC
},
] {
assert_eq!(
BcTextureLayout::new(desc, ALIGNED).unwrap_err(),
TextureError::SizeOverflow
);
}
let highest_bit = 1 << (usize::BITS - 1);
for alignment in [
BcCopyAlignment {
row: highest_bit,
placement: 1,
},
BcCopyAlignment {
row: 1,
placement: highest_bit,
},
] {
assert_eq!(
BcTextureLayout::new(DESC, alignment).unwrap_err(),
TextureError::SizeOverflow
);
}
// Even an unusually large placement alignment needs no trailing space
// after a sole subresource.
let one = BcTextureDesc {
mips: 1,
layers: 1,
..DESC
};
let layout = BcTextureLayout::new(
one,
BcCopyAlignment {
row: 1,
placement: highest_bit,
},
)
.unwrap();
assert_eq!(layout.byte_len(), 96);
}
#[test]
fn all_block_sizes_match_a_byte_by_byte_layout_oracle() {
let formats = [
(BcFormat::Bc1, 8),
(BcFormat::BcAlpha(BcAlphaFormat::Bc2), 16),
(BcFormat::BcAlpha(BcAlphaFormat::Bc3), 16),
(BcFormat::BcChannel(BcChannelFormat::Bc4Unorm), 8),
(BcFormat::BcChannel(BcChannelFormat::Bc4Snorm), 8),
(BcFormat::BcChannel(BcChannelFormat::Bc5Unorm), 16),
(BcFormat::BcChannel(BcChannelFormat::Bc5Snorm), 16),
(BcFormat::Bc6hUfloat, 16),
(BcFormat::Bc6hSfloat, 16),
(BcFormat::Bc7, 16),
];
for (format, block_bytes) in formats {
for (width, height) in [
(1_usize, 1_usize),
(1, 37),
(37, 1),
(4, 4),
(5, 9),
(17, 13),
] {
for (row, placement) in [(1, 1), (32, 16), (16, 128), (64, 512)] {
let mips = usize::BITS - width.max(height).leading_zeros();
let desc = BcTextureDesc {
width,
height,
mips,
layers: 3,
format,
};
let layout =
BcTextureLayout::new(desc, BcCopyAlignment { row, placement }).unwrap();
let tight = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
let mut expected = Vec::new();
let mut source = Vec::new();
for layer in 0..3 {
let (mut w, mut h) = (width, height);
for mip in 0..mips {
while expected.len() % placement != 0 {
expected.push(0);
}
let start = expected.len();
let mut tight_level = Vec::new();
for y in (0..h).step_by(4) {
let row_start = expected.len();
for x in (0..w).step_by(4) {
for i in 0..block_bytes {
let byte =
(1 + layer * 51 + mip as usize * 7 + x + 3 * y + i) as u8;
expected.push(byte);
tight_level.push(byte);
}
}
while (expected.len() - row_start) % row != 0 {
expected.push(0);
}
}
let fp = layout.footprint(layer, mip).unwrap();
assert_eq!(
(fp.offset, fp.offset + fp.byte_len),
(start, expected.len())
);
source.extend(tight_level);
(w, h) = ((w / 2).max(1), (h / 2).max(1));
}
}
let upload = PackedBcUpload::new(&tight, &source).unwrap();
let mut bytes = vec![0xff; layout.byte_len()];
upload.repack_into(&layout, &mut bytes).unwrap();
assert_eq!(
bytes, expected,
"{format:?}, {width}×{height}, {row}/{placement}"
);
}
}
}
}
+6 -2
View File
@@ -38,6 +38,7 @@ Historical phase checkpoints retain their original evidence scope.
- [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.
- [Proposed AVX and AVX2 guest contract](cpu/avx-contract.md) — VEX decoding, vector state, fault behavior and an original integer fixture specification.
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
- [Guest threads](runtime/threads.md) — Deterministic scheduler, thread services, limits and tests.
- [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements.
@@ -45,20 +46,23 @@ Historical phase checkpoints retain their original evidence scope.
## Testing, validation, and benchmarks
- [Migrated pull-request integration review](testing/migration-pr-review.md) — Merge decisions, integration fixes, native verification and excluded concurrent work.
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
- [CPU test runtime and shard selection](testing/cpu-coverage.md) — Measured CPU gate cost and deterministic test-target shards.
- [CPU test runtime, shards and coverage map](testing/cpu-coverage.md) — Measured CPU gate cost, deterministic test-target shards, and a verified per-operation CPU/loader coverage map with exact test evidence.
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
- [Gate A: a compiled C program](testing/gate-a.md) — The two milestones, what the A1 test checks and what it does not show.
- [Gate A: a compiled C program](testing/gate-a.md) — The two milestones, what the A1 and A2 tests check and what they do not show.
- [Mutation testing](testing/mutation.md) and [benchmark protocol](testing/benchmarks.md) — Test sensitivity, benchmark inputs, and timing requirements.
## Research and engineering decisions
- [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.
- [Texture format inventory](research/texture-formats.md) — Formats and layouts by stage (decode, layout, native upload, sampling, guest), their public specifications, unknowns and ranked follow-ups.
- [PortWatch native macOS research](research/portwatch-native-macos.md) — Screening of public Xbox-on-Windows port projects for native macOS planning; discovery only.
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
## Security, licensing, and contributions
+136
View File
@@ -0,0 +1,136 @@
# Proposed AVX and AVX2 guest contract
[Issue #299](https://github.com/MacosPorters/betterxen/issues/299) defines a
reviewable first step for Advanced Vector Extensions (AVX) in the x86-64 guest.
The current [instruction registry](instruction-registry.md) rejects VEX prefixes.
[`CpuState`](../../crates/loader/src/cpu.rs) holds 16 XMM registers and MXCSR,
the SIMD floating-point control and status register. The synthetic `CPUID`
advertises basic leaves through 1 and reports no AVX or extended-state support.
The architectural expectations come from the public Intel Software Developer's
Manual and apply to BetterXen's synthetic x86-64 guest profile. Which AVX and
AVX2 features Xbox Series X|S CPUs expose, and which extended register state
the console OS enables for applications, remain open research questions.
Resolving them requires public platform documentation or authorized hardware
evidence.
## Architectural state and encoding
In 64-bit mode, XMM0–XMM15 alias bits 127:0 of YMM0–YMM15. A legacy SSE
instruction that writes an XMM destination preserves bits 255:128. For the
packed VEX.128 forms in this proposal, writing an XMM destination clears that
register's upper 128 bits. A VEX.256 register destination replaces all 256 bits.
A store to memory leaves its source vector register intact. The proposed moves
and integer add leave RFLAGS and MXCSR unchanged. [Intel SDM Vol. 1, §14.8,
Accessing YMM Registers][sdm-ymm]. [Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b].
The shared [decoder](../../crates/loader/src/x86_decode.rs) should retain the
prefix family, opcode map, mandatory prefix, operand width and register
extensions until it selects the form. In 64-bit mode the VEX lead byte
identifies the prefix length. The table lists each payload byte's fields
from bit 7 to bit 0.
| Lead byte | Payload byte 1 | Payload byte 2 | Implied fields |
| --- | --- | --- | --- |
| `C5` | `~R ~vvvv L pp` | — | Map `0F`, `W=0`, logical `X=B=0` |
| `C4` | `~R ~X ~B mmmmm` | `W ~vvvv L pp` | Map selected by `mmmmm` |
The tilde indicates an inverted encoding. `R` extends ModRM.reg, while `X`
and `B` extend the applicable index and r/m or base fields. `vvvv` supplies
the first source of `VPADDD`. For `VMOVDQU` its encoded bits must be `1111b`.
`L=0` selects 128 bits and `L=1` selects 256 bits for these forms. The three
standard VEX maps are `00001b` (`0F`), `00010b` (`0F 38`) and `00011b`
(`0F 3A`). `pp` values 0 through 3 represent no mandatory prefix, `66`, `F3`
and `F2`. Both initial opcodes are in `0F`, with `W` ignored (`WIG`). Decode
both valid prefix lengths for them. Reject reserved maps and encodings,
including a physical `LOCK`, `66`, `F2`, `F3` or REX prefix before VEX, through
the existing illegal-instruction path. Legal forms outside the implemented
subset also stop explicitly. Keep the existing register and effective-address
rules and 15-byte fetch limit. [Intel SDM Vol. 2A, §2.3, VEX encoding][sdm-2a].
[Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b].
## First implementation increments
1. Append one upper 128-bit half per vector register to `CpuState`, retaining
the existing XMM storage as the low halves. Add layout assertions for the
offsets the dynamic binary translator (DBT) uses. Initialize both halves
in a fresh guest thread and carry them with the thread state when switching
or resuming. Add the shared VEX decoder and encoding controls before execution.
2. Implement `VMOVDQU` (128 and 256 bits, `F3.0F`, `6F /r` and `7F /r`,
register and checked memory forms) and `VPADDD` (128 and 256 bits,
`66.0F`, `FE /r`, register sources initially). The instruction entries
assign both move widths and 128-bit `VPADDD` to AVX, and 256-bit `VPADDD`
to AVX2. Read all sources before publishing the destination, including
when the destination aliases a source. Compare both engines with the
[original fixture specification](../../tests/compat_fixtures/avx/README.md).
3. After shared semantics pass, lower register moves and `VPADDD` to native
ARM64 vector operations on one or two 128-bit halves. Each `VPADDD` half
is four independent 32-bit additions modulo 2³². Use the checked-memory
helper for loads and stores. Check the DBT's fallback counter so a run
through that helper establishes only helper coverage for those forms.
Stage memory-source `VPADDD` and aligned moves separately. Reject masked
moves, gathers, cross-half permutations, floating-point forms, FMA, EVEX
and guest extended-state instructions in the initial slice. AMD64 bytes
remain guest data. All host execution uses native ARM64 code or checked
Rust helpers.
## Memory, faults and instruction budget
`VMOVDQU` permits unaligned operands. Check the complete 16- or 32-byte
guest span before publishing a load result or writing a store. A split
span across adjacent permitted mappings succeeds. A missing or protected
mapping produces the existing guest memory fault at the first inaccessible
byte. For a later `VMOVDQA` form, a memory operand must be aligned to its
width (16 or 32 bytes), with a misaligned operand raising
`GeneralProtection`. [Intel SDM Vol. 2B, MOVDQU and MOVDQA][sdm-2b].
Intel's Type 4 rules for `VMOVDQU` specify `#SS(0)` when a memory reference
through the stack segment (SS) has a noncanonical address and `#GP(0)`
for other noncanonical references. The initial BetterXen profile uses the
[existing 48-bit guest address check](../../crates/loader/src/x86_exec.rs)
and reports `GeneralProtection` for either segment case, including a span
whose first byte is canonical and whose last byte is noncanonical. Check
canonicality before guest memory lookup and before committing the move.
Distinct stack-segment exception reporting remains outside this profile.
[Intel SDM Vol. 2A, Table 2-21, Type 4 exceptions][sdm-2a].
Before adding masked moves, use a separate per-lane access contract. For
`VPMASKMOVD`, only lanes with the high mask bit set may access memory or
report a memory fault. A clear bit zeroes a load lane and leaves a store
lane untouched. A test with lane 4 on an unmapped page must pass with that
lane disabled and fault with it enabled. A full-width span check would
incorrectly reject the disabled case. Specify store commit behavior before
admitting that form. [Intel SDM Vol. 2C, VPMASKMOV][sdm-2c].
Require interpreter and DBT parity for the exit reason, fault address when
reported, RIP, instruction count and complete guest register and memory
state. A rejected move or add has no partial destination update and does
not retire. A successful 256-bit instruction consumes one guest step even
when the DBT emits two halves. With an exhausted budget, stop at the next
guest RIP before decoding or executing that instruction. Check cold and warm
DBT paths and resume in the middle of the same sequence.
## Feature exposure
Run the initial forms only in explicitly enabled synthetic test cases.
Keep normal guest `CPUID` and extended-state behavior at the current baseline.
Before guest-visible AVX support, the guest OS model needs coherent reporting
for `CPUID.1:ECX` bits 26 (XSAVE), 27 (OSXSAVE) and 28 (AVX), and `XGETBV`
with `ECX=0` must report both XMM and YMM state enabled in `XCR0[2:1]`. The
extended-state layout reported by `CPUID.0Dh`, save and restore behavior,
and per-thread ownership must agree. Verify the exception behavior for
disabled state and invalid `XGETBV` selectors before exposing the facility.
AVX2 separately requires `CPUID.(7,0):EBX[5]` and the same OS state. Gate
each advertised feature on its full instruction and state contract,
with probes for enabled and disabled combinations. [Intel SDM Vol. 1,
§14.3, AVX detection][sdm-avx]. [Intel SDM Vol. 1, §14.7.1, AVX2 detection][sdm-avx2].
[Intel SDM Vol. 2A, CPUID][sdm-2a]. [Intel SDM Vol. 2D, XGETBV, XSAVE and XRSTOR][sdm-2d].
[sdm-ymm]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=376
[sdm-avx]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=359
[sdm-avx2]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=375
[sdm-2a]: https://cdrdv2-public.intel.com/929353/253666-093-sdm-vol-2a.pdf
[sdm-2b]: https://cdrdv2-public.intel.com/929354/253667-093-sdm-vol-2b.pdf
[sdm-2c]: https://cdrdv2-public.intel.com/929355/326018-093-sdm-vol-2c.pdf
[sdm-2d]: https://cdrdv2-public.intel.com/929356/334569-093-sdm-vol-2d.pdf
+158 -3
View File
@@ -78,11 +78,35 @@ Windows while the process has one thread. The exit closes every guest handle:
kernel objects, Winsock sockets and task-queue handles, which
`ServicesState::open_handle_count` counts together. Files stay on the synthetic `C:` drive, guest memory stays mapped so the host
can inspect it, and `atexit` functions are not run: that belongs to the C
runtime's `exit`, which is not implemented. `ServicesState::exit_status`
runtime's `exit`, described below. `ServicesState::exit_status`
reports the status. After an exit the `DbtEngine` that ran the guest executes
no further guest instruction and answers every later `run` with the same
`ProcessExit`. A service callback that was in progress is never resumed.
A C program ends through the C runtime instead. `ucrtbase.dll` and
`api-ms-win-crt-runtime-l1-1-0.dll` provide three ways out, each ending the
guest with the same `ProcessExit` and the same cleanup as `ExitProcess`:
| Service | Behaviour |
| --- | --- |
| `exit(status)` | Calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, then ends the process with `status` |
| `_exit(status)` | Ends the process with `status` and calls no registered function |
| `abort()` | Ends the process with exit code 3 and calls no registered function |
`exit` takes one function at a time from the registered list. A function
registered while `exit` runs is therefore called next, before the older ones
that have not run yet, which is ISO C's rule. A registered function that calls
`exit` again is undefined in ISO C; here the functions that have not run yet
run once each and the process ends with the status of the later call.
Functions that `_cexit` has already run are not run again.
All three are partial. `exit` flushes no stream, because there are none, and
runs no thread-local destructor. It does not walk a module's own `_onexit`
table; that module's startup code runs it through `_execute_onexit_table`.
`abort` prints no message and does not call a `SIGABRT` handler, which the
documentation says it does when one is set. `_Exit`, `quick_exit` and
`_c_exit` are not provided. None of this has been compared with Windows.
A TLS callback may end the process too. Startup then reports the exit as its
outcome, with the status, and runs neither the remaining callbacks nor the
entry point; `StartupResult::tls_callbacks` counts the callbacks that finished.
@@ -117,6 +141,31 @@ pages count toward the 256 MiB mapping budget of one image, which is checked
before anything is mapped. `ParsedPe::parse` does not make these checks, so
static inspection of a file is unchanged.
`betterxen run --experimental --pe <trusted-fixture> --startup-report <path>`
writes a versioned JSON summary after the worker stops. The supervisor creates the new report path before launching the worker.
The report is optional and uses the same exact-byte fixture admission, startup
observer and wall deadline as an ordinary run.
Schema version 1 lists the observed stages in order in `stages` and copies
the last valid stage to `last_completed_stage` (null if none). The order is
`parsed`, `mapped`, `relocated`, `imports_bound`, `tls_completed`, `entry`,
`exit`, and `framebuffer`. `entry` records the handoff to guest entry.
`exit` records the fixture halt, and `framebuffer` records verification of its
offscreen readback. The supervisor reports an `outcome` of `verified`,
`stage_failure`, `early_exit`, `timeout`, or `unknown`. It includes the
worker exit code when available, termination detail when applicable, and the
original reported error when available. Errors are capped at 2 KiB of UTF-8
and carry an `error_truncated` flag.
The supervisor reads at most 8 KiB plus one byte from the worker journal.
`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized`,
`unreadable`, or `unwritable`. Worker exit codes 124 and 125 are reserved for
its watchdog and journal I/O errors, respectively. `--startup-journal` is an
internal worker option. Only the valid ordered prefix counts toward progress. A
complete journal may still contain only a partial startup if the worker
stopped between records. These records describe runtime observations from
the trusted fixtures.
`betterxen probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. Without `--report` it writes to `diagnostics/probe`,
where `betterxen imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
@@ -319,6 +368,112 @@ Allocation failures also set the synthetic main thread's CRT `errno` to
and CRT parameter or new-handler callbacks remain unsupported. See
[Microsoft CRT allocation documentation](https://learn.microsoft.com/cpp/c-runtime-library/memory-allocation).
### Standard output and formatted printing
A hosted C program prints through the C runtime. Six services give it the
standard streams, and what it writes to `stdout` and to `stderr` is captured
where a host or a test can read it: `ServicesState::standard_output()` and
`ServicesState::standard_error()`.
| Service | Behaviour |
| --- | --- |
| `__acrt_iob_func(index)` | The `FILE` object of `stdin` (0), `stdout` (1) or `stderr` (2) |
| `__stdio_common_vfprintf(options, stream, format, locale, arguments)` | Formats with the arguments in the guest's `va_list`, writes to `stdout` or `stderr`, and returns the number of characters written. This is what `printf` and `fprintf` call |
| `fwrite(buffer, size, count, stream)` | Writes `size * count` bytes and returns `count` |
| `fputs(string, stream)` | Writes the string without its terminator and returns 0 |
| `fflush(stream)` | Returns 0. A null stream means every stream |
| `setvbuf(stream, buffer, mode, size)` | Checks the mode and size and returns 0 |
The standard streams are text-mode streams, so each line feed a program
writes is captured as a carriage return and a line feed, as the Windows
documentation of text mode describes. Function results count the characters
before that replacement. Output is never held back: `fflush` has nothing to
do and `setvbuf` only validates. Each captured stream keeps at most 16 MiB
(`MAX_CAPTURED_OUTPUT`).
The formatting engine (`crates/loader/src/services/crt_format.rs`) follows
Microsoft's "Format specification syntax: printf and wprintf functions" and
ISO C:
- Flags `-`, `+`, blank, `#` and `0`; a width and a precision as digits or
`*`; size prefixes `hh`, `h`, `l`, `ll`, `j`, `z`, `t`, `I`, `I32`, `I64`.
- Types `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%`. An integer
without a size prefix, and a `long`, is 32 bits. A null string prints
`(null)`.
- Its output is compared with the host C library's `snprintf` on 2,600
generated cases whose result ISO C defines
(`crates/loader/tests/printf/reference.py`).
Documented failures return their documented result and set `errno` to
`EINVAL`: a null stream, format, buffer or string, and an invalid `setvbuf`
mode or size. An invalid format, which includes `%n` because Windows
disables it by default, also returns -1 with `EINVAL` and writes nothing;
on Windows the invalid parameter handler runs first.
Everything else that is not modelled stops the guest with the runtime-limit
fault and writes nothing, so that nothing is printed wrongly: the
floating-point types (`e`, `f`, `g`, `a`), wide characters and strings (`C`,
`S`, `lc`, `ls`), a locale object, option bits other than the three that do
not affect these conversions, a pointer that is no stream, writing `stdin`,
an index above 2, more than 1 MiB in one call, and output past the 16 MiB
bound.
Choices where the documentation leaves room, each marked in the source:
`%p` prints sixteen upper-case hexadecimal digits; `0` pads a character and
a string as it pads a number; a precision also limits `(null)`; `%#.0o` of
zero prints `0`, which is ISO C's rule. All six services are `partial`. None
of this has been compared with Windows.
### Files through the C runtime
`fopen`, `fclose` and `fgets` give a hosted C program files, and the output
services above (`__stdio_common_vfprintf`, `fwrite`, `fputs`, `fflush`,
`setvbuf`) accept a stream `fopen` returned as well as `stdout` and `stderr`.
The files are the ones on the in-memory `C:` drive described under
"Synthetic guest files": a file written through a C stream is the file
`ReadFile` reads, and the reverse.
| Service | Behaviour |
| --- | --- |
| `fopen(name, mode)` | Opens a file and returns its `FILE*`, or null with `errno` set. `r` needs the file to exist; `w` creates it or destroys its contents; `a` creates it and makes every write go to its end; `+` adds the other direction; `b` or `t` selects binary or text |
| `fclose(stream)` | Closes the stream and returns 0; `EOF` with `EINVAL` for a null stream |
| `fgets(buffer, count, stream)` | Reads up to `count - 1` characters, stopping after a newline, which it keeps, and adds a terminator. Returns the buffer, or null at end of file or on an error |
| `perror(message)` | Writes the message, `: `, the text for `errno` and a newline to `stderr`; only the text when the message is null or empty |
A stream is in text mode unless its mode has `b`: a line feed is stored as a
carriage return and a line feed, the pair is read back as a line feed, and
`CTRL+Z` ends the input. Names are ASCII, with either slash, in any case,
with or without `C:\`, as the drive accepts them.
`errno` after a failed `fopen`: `EINVAL` for a null or empty name or mode, a
mode this runtime does not open, and a name the drive rejects; `ENOENT` when
the file or its directory does not exist; `EACCES` for a directory; `EMFILE`
when 64 streams are already open; `ENOSPC` when the drive holds its 256
files; `ENOMEM` when the `FILE` object cannot be allocated. Output to a
stream that was not opened for writing, and reading one not opened for
reading, fail with `EBADF`; output the drive has no room for fails with
`ENOSPC`. A failed write writes nothing.
What is not provided, and what is Xenora's choice:
- **Not provided:** the mode characters `x`, `c`, `n`, `N`, `S`, `R`, `T`,
`D` and `ccs=`, which are refused; `fread`, `fseek`, `ftell`, `rewind`,
`feof`, `ferror`, `fscanf`; reading `stdin` and closing a standard stream,
which stop the guest.
- **No buffering.** A write reaches the drive at once, so the rule that a
`+` stream needs `fflush` or a seek between writing and reading does not
apply.
- **No sharing.** A C stream is not a Win32 handle. It does not stop
`DeleteFileW` or `MoveFileW`, and ignores a handle's sharing mode. After
its file is deleted a stream's reads and writes fail with `EBADF`.
- **Choices:** the `errno` values above other than `EINVAL` for a null or
empty argument, which is documented; an `a+` stream reads from the start;
every `perror` text except "No such file or directory", which is the one
Microsoft's page shows.
All four services are `partial`. None of this has been compared with
Windows.
### CRT integer conversion
UCRT and the CRT conversion API set expose strtol, strtoul, wcstol, and
@@ -505,8 +660,8 @@ The CRT uses this for:
on the default guest heap, and they hold at most 65,536 entries. Execution
resets the table first, then calls the functions in reverse order of
registration. `atexit` and `_crt_atexit` record process exit functions,
which `_cexit` runs in reverse order. Process termination through `exit` is
not modeled.
which `_cexit` runs in reverse order and returns. `exit` runs them and
then ends the process; see "PE32+ fixture startup" above.
Null comparators, null arrays with a nonzero count, and reversed or
misaligned tables would reach the CRT invalid-parameter handler. That
+4 -4
View File
@@ -19,16 +19,16 @@ Request original gfx1030 Wave64 assembly, a mask/lane design note and per-lane e
KyTx declares GPL-2.0. Tx's conditional GPL-2.0-or-later offer covers only material they own and can license. Require file-level authorship, explicit compatible terms (GPL-3.0-or-later preferred for new Xenora fixtures), preserved notices and DCO. Inherited GPL-2.0-only code cannot enter the GPL-3.0-or-later combined work under those terms. The separate Kyty MIT notice does not settle a derived file's full provenance. No KyTx submodule is justified for the fixture. [KyTx license and notices](https://github.com/TxCsOffc/KyTx/tree/10f50d3eff0c0df36ee5d7007848a7b0b15072eb/LICENSES), [KyTx license](https://github.com/TxCsOffc/KyTx/blob/10f50d3eff0c0df36ee5d7007848a7b0b15072eb/LICENSE)
## Leonida
## PE-Vulkan project
Public revision `2d3369a4c82e6f36c5190c4c534d3df600e135ec`. Candidate study surfaces and limits:
| Surface | Evidence and disposition |
| --- | --- |
| Decode and translation | `decode_bytes` decodes RDNA words with an explicit wave-mode argument. The SPIR-V generator exposes `Gen` and `assemble`. Compare supported operand forms on independent synthetic inputs. Keep Xenora's typed decoder and MSL backend. [Decoder](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/rdna2_decode.py#L1397), [Generator](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/rdna2spirv.py#L219) |
| Containers and GPU API | `wave_size` and `binding_table` expose Leonida's FSSM interpretation. The D3D12 Vulkan shim and its device test are concrete source paths. Their existence does not establish a public authoritative Xbox ABI or PM4 contract. Keep metadata and guest handles outside Xenora's decoder, with explicit wave size, checked byte ranges and validated resource bindings. [FSSM reader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/fssm_header.py#L155), [Device shim](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/shims/d3d12_vulkan_device.cpp), [Device test](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/test/d3d12_vulkan_device_test.cpp) |
| Containers and GPU API | `wave_size` and `binding_table` expose PE-Vulkan project's FSSM interpretation. The D3D12 Vulkan shim and its device test are concrete source paths. Their existence does not establish a public authoritative Xbox ABI or PM4 contract. Keep metadata and guest handles outside Xenora's decoder, with explicit wave size, checked byte ranges and validated resource bindings. [FSSM reader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/fssm_header.py#L155), [Device shim](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/shims/d3d12_vulkan_device.cpp), [Device test](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/test/d3d12_vulkan_device_test.cpp) |
| Executable and services | `Loader::load` and `Loader::load_runtime_module` establish an implemented Windows PE loading and shim boundary. CMake registers loader, bounds and TLS tests. The upstream stand-in run is reported. For Xenora, study the boundary using original PE fixtures, with checked image metadata, guest address translation and explicit service dispatch. Native Windows execution and the Vulkan runtime conflict with Xenora's host contract. [PE loader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/src/pe_loader.cpp#L608), [Test registration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/CMakeLists.txt#L516) |
The README reports 26,503 translations and SPIR-V validation at specific earlier revisions. It contains conflicting Wave64 counts, so leave that count unresolved. The linked GPU reports cover synthetic cases and include a MoltenVK path. Validation and pipeline creation do not check game shader output. The pinned status explicitly says the game does not boot. Xenora's GTA VI intro remains unverified, and no authorized test input was established in this review. [Pinned status](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/README.md#project-status), [Reported validator run](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586), [Upstream GPU reports](https://github.com/ItsNotRexed/Leonida/issues/166)
The README reports 26,503 translations and SPIR-V validation at specific earlier revisions. It contains conflicting Wave64 counts, so leave that count unresolved. The linked GPU reports cover synthetic cases and include a MoltenVK path. Validation and pipeline creation do not check game shader output. The pinned status explicitly says the game does not boot. Xenora's commercial-title intro remains unverified, and no authorized test input was established in this review. [Pinned status](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/README.md#project-status), [Reported validator run](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586), [Upstream GPU reports](https://github.com/ItsNotRexed/Leonida/issues/166)
Leonida carries GPL v3 text at the inspected pin. Any adoption still requires R1 to establish exact file terms and ownership, check generated tables and SDK-derived material, and review the separate `third_party/rpf9-explorer` gitlink at `e2939175c36a02d6ed25fa2c217b9d6ddcb8b516`. Game-derived metadata, shaders and asset outputs are outside this collaboration. Use public design references and original synthetic inputs. No Leonida submodule is justified. [Leonida license](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/LICENSE), [Submodule declaration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/.gitmodules)
PE-Vulkan project carries GPL v3 text at the inspected pin. Any adoption still requires R1 to establish exact file terms and ownership, check generated tables and SDK-derived material, and review the separate `third_party/rpf9-explorer` gitlink at `e2939175c36a02d6ed25fa2c217b9d6ddcb8b516`. Game-derived metadata, shaders and asset outputs are outside this collaboration. Use public design references and original synthetic inputs. No PE-Vulkan project submodule is justified. [PE-Vulkan project license](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/LICENSE), [Submodule declaration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/.gitmodules)
+1 -1
View File
@@ -5,7 +5,7 @@ Historical reuse discussion records the earlier survey. Xenora uses
public specifications and original fixtures, with other emulator
projects serving only as references for test selection.
Screened the eight A3 leads on 2026-11-23 against section 6 of the dual-track brief. The pins below identify the default-branch snapshots and their latest observed commits in UTC. The OpenScarlett tip changes documentation. A recent tip establishes activity, and its commit message records the subject of that activity. See the companion notes for [KyTx and Leonida](phase02-collaboration.md) and [CPU engine selection and original interpreter fixture](phase02-cpu-feasibility.md).
Screened the eight A3 leads on 2026-11-23 against section 6 of the dual-track brief. The pins below identify the default-branch snapshots and their latest observed commits in UTC. The OpenScarlett tip changes documentation. A recent tip establishes activity, and its commit message records the subject of that activity. See the companion notes for [KyTx and PE-Vulkan project](phase02-collaboration.md) and [CPU engine selection and original interpreter fixture](phase02-cpu-feasibility.md).
GitHub metadata and tree entries establish availability and paths. Pinned text inspection establishes what a selected function does in source. Upstream test counts, captures and README statements remain upstream reports. No upstream code, builds, fixtures or GPU workloads were executed here. Repository-level license labels are provisional for reuse. File-specific grants, origin and transitive terms remain unverified for every code surface below.
+354
View File
@@ -0,0 +1,354 @@
# 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.
Local documentation edits from this review do not install that newer runtime.
## 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 | README X10 and generic “no sampling” descriptions are stale for this bounded path. 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. |
| PE-Vulkan project (`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 PE-Vulkan project 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` | PE-Vulkan project 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 PE-Vulkan project; 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.
Nothing was committed, pushed, merged, released or installed by this review.
The GitHub research/follow-up issues were created at the user's request.
+3 -3
View File
@@ -11,8 +11,8 @@ in this checkout uses original fixtures and public specifications.
| Project and audited snapshot | Type and observed evidence | Claimed-only behavior or provenance risk | Xenora work and original acceptance fixture | Priority and owner |
| --- | --- | --- | --- | --- |
| [Xenora `3133d8e`](https://github.com/ranveersoni98/Xenora/tree/3133d8e) | Native Rust guest and shader research. X1–X4 fixtures and gfx1030 compiler in tree. | GPL-3.0-or-later. Console execution unsupported. | Re-run the guest and translated compute fixtures on ARM64. | Immediate, integration |
| [Leonida `3faac55`](https://github.com/ItsNotRexed/Leonida/tree/3faac55) | Windows PE mapping, service shims and Vulkan proxy tests. | GPL-3 family and Xenora no-port rule. Commercial boot absent in audit. | Original PE startup and GPU resource contracts. | Later, CPU and Metal |
| [Project ReCity `cb4840b`](https://github.com/pixl27/ProjectReCity/tree/cb4840b) | Windows/Vulkan implementation and PE tests. | GPL-3, Leonida-derived. Separate retail proof absent. | Same synthetic startup coverage as Leonida, no parallel benchmark. | Later, CPU |
| [PE-Vulkan project `3faac55`](https://github.com/ItsNotRexed/Leonida/tree/3faac55) | Windows PE mapping, service shims and Vulkan proxy tests. | GPL-3 family and Xenora no-port rule. Commercial boot absent in audit. | Original PE startup and GPU resource contracts. | Later, CPU and Metal |
| [Project ReCity `cb4840b`](https://github.com/pixl27/ProjectReCity/tree/cb4840b) | Windows/Vulkan implementation and PE tests. | GPL-3, PE-Vulkan project-derived. Separate retail proof absent. | Same synthetic startup coverage as PE-Vulkan project, no parallel benchmark. | Later, CPU |
| [Xbox2Windows `6de5738`](https://github.com/R0Y00/Xbox2Windows/tree/6de5738) | Static recompilation tests for imports, CPU startup, TLS and GPU output. See `tests/cpu/startup_exe.cpp`. | MIT at repository level. Full title startup unverified. | Build a source-authored PE guest and test exact service results. | Immediate, CPU |
| [americas-recomp `9bf220e`](https://github.com/realdody/americas-recomp/tree/9bf220e) | Audited main root had a license file. | GPL-2.0. Other branches uninspected. | No fixture justified by audited tree. | Deferred, research |
| [6stars `480d9a4`](https://github.com/meetox80/6stars/tree/480d9a4) | Swift/Metal renderer and sampler mapping in `Sources/SixStars`. | No verified root license. Guest CPU execution unverified. | Original translated shader, validated resource range and known readback. | Immediate, Metal |
@@ -63,7 +63,7 @@ in this checkout uses original fixtures and public specifications.
services, hardware queues, formats and memory initialization need their
own sources and tests. [Xbox GPU evidence](../research/xbox-gpu.md) ·
[PE format](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format)
- GTA VI startup and execution remain unsupported. No authorized retail
- Commercial-title startup and execution remain unsupported. No authorized retail
executable was loaded. Actual title imports, startup ordering, resource
bindings and pipeline behavior remain unverified. Relocation, thread-local
storage, process and thread services, dynamic shader execution and
+96
View File
@@ -0,0 +1,96 @@
# Texture format and layout inventory
This page records which texture formats and memory layouts BetterXen handles today, and at which stage. It also records which gaps are worth closing and which are deferred. It is an inventory of the repository at the time of writing, built from the code and tests it links. It is not a support claim: a format listed here works only for the original synthetic fixtures named, on desktop specifications, and nothing here says anything about Xbox hardware or commercial titles.
## Stages
A format can be handled at one stage and missing at the next. The columns below keep them apart:
- **Container**: recognising a file or package format that holds textures (DDS, KTX and similar).
- **CPU decode**: turning one compressed block into texels on the CPU, used as an independent reference.
- **Layout**: converting between a stored memory layout and the row-major layout Metal expects.
- **Native**: uploading to a Metal texture of that pixel format and reading it back on the GPU.
- **Sampling**: a translated RDNA 2 image instruction reading the texture inside a shader.
- **Host graphics API**: the D3D12-shaped `GraphicsContext` entry points, exercised by tests that call them directly from Rust. [The interface contract](../interfaces.md#guest-texture-binding-descriptor-tables) states they are not yet wired to guest imports, so this column is not guest evidence.
- **Guest**: an original guest program (PE fixture) reaching the path through imported services, with a test that runs it.
- **Specification**: the public sections the implementation and its expected values cite.
"—" means not implemented. "Rejected" means the input is refused with an error rather than handled.
## Formats
| Format | Container | CPU decode | Layout | Native | Sampling | Host graphics API | Guest | Specification |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| RGBA8 unorm | — | not needed | row-major mips, direct or budgeted staged upload ([`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs)) | upload and render target (`render_rgba8*`, [`crates/metal/tests/native/texture_sampling.rs`](../../crates/metal/tests/native/texture_sampling.rs)) | `image_sample_lz`, 2D, level 0 ([`crates/isa/src/lib.rs`](../../crates/isa/src/lib.rs), [`crates/metal/tests/native/translated_render.rs`](../../crates/metal/tests/native/translated_render.rs)) | one-level 2D SRV, `DXGI_FORMAT_R8G8B8A8_UNORM`, called from Rust ([`crates/loader/src/graphics.rs`](../../crates/loader/src/graphics.rs), [`crates/loader/tests/graphics_textures.rs`](../../crates/loader/tests/graphics_textures.rs)) | synthetic `xenora.dll` texture services (`texture_create`, `texture_update`, `frame_submit_textured`, `texture_destroy`) driven by the Gate 5 original PE fixture ([`crates/ffi/src/lib.rs`](../../crates/ffi/src/lib.rs), test `textured_pe_fixture_executes_dynamic_updates_and_retirement` in [`crates/ffi/tests/resources.rs`](../../crates/ffi/tests/resources.rs)); not through the descriptor-table API | [`MTLPixelFormat.rgba8Unorm`](https://developer.apple.com/documentation/metal/mtlpixelformat/rgba8unorm) |
| BC1 | — | `decode_bc1` ([`crates/texture/src/lib.rs`](../../crates/texture/src/lib.rs)) | synthetic tiled layout, pitched uploads (`TiledBc1`, `Bc1Upload`) and per-subresource packed footprints (`BcTextureLayout`, `PackedBcUpload`) | `read_tiled_bc1`, `read_bc1_upload`, including packed footprints ([`crates/metal/tests/native/texture.rs`](../../crates/metal/tests/native/texture.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | sampled by the translated `image_sample_lz` pixel stage (`render_rgba8_sampled_bc1`, [`crates/metal/tests/native/translated_bc1.rs`](../../crates/metal/tests/native/translated_bc1.rs)) | one-level 2D SRV, `DXGI_FORMAT_BC1_UNORM`, called from Rust (same files as RGBA8) | — | [Khronos DFS 1.3, S3TC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#S3TC) (BC1 with and without alpha); [Microsoft, BC1](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
| BC2, BC3 | — | `decode_bc2`, `decode_bc3` ([`crates/texture/src/bc.rs`](../../crates/texture/src/bc.rs), [`crates/texture/tests/bc_formats.rs`](../../crates/texture/tests/bc_formats.rs)) | pitched upload (`BcAlphaUpload`) and packed footprints | `read_bc_alpha_upload`, including packed footprints ([`crates/metal/tests/native/texture_bc_alpha.rs`](../../crates/metal/tests/native/texture_bc_alpha.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | — | — | — | [Khronos DFS 1.3, S3TC BC2](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#s3tc_bc2) and [BC3](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#s3tc_bc3); [Microsoft, BC2 and BC3](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
| BC4, BC5 (unorm, snorm) | — | `decode_bc4_*`, `decode_bc5_*` ([`crates/texture/src/bc.rs`](../../crates/texture/src/bc.rs), [`crates/texture/tests/bc_formats.rs`](../../crates/texture/tests/bc_formats.rs)) | pitched upload (`BcChannelUpload`) and packed footprints | `read_bc_channel_upload`, including packed footprints ([`crates/metal/tests/native/texture_bc_channel.rs`](../../crates/metal/tests/native/texture_bc_channel.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | — | — | — | [Khronos DFS 1.3, RGTC BC4](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#rgtc_bc4) and [BC5](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#rgtc_bc5); [Microsoft, BC4 and BC5](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
| BC6H (ufloat, sfloat) | — | single-subset modes only; two-subset modes rejected ([`crates/texture/src/bc6h.rs`](../../crates/texture/src/bc6h.rs), [`crates/texture/tests/bc6h.rs`](../../crates/texture/tests/bc6h.rs), vectors [`crates/texture/tests/fixtures/bc6h_vectors.txt`](../../crates/texture/tests/fixtures/bc6h_vectors.txt)) | packed footprints only, 16-byte blocks ([`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs)) | — | — | — | — | [Khronos DFS 1.3, BPTC BC6H](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc6h) (section 20.2, Tables 121 and 122); [Microsoft, BC6H Format](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format) |
| BC7 unorm | — | all eight modes ([`crates/texture/src/bc7.rs`](../../crates/texture/src/bc7.rs), [`crates/texture/tests/bc7.rs`](../../crates/texture/tests/bc7.rs), vectors [`crates/texture/tests/fixtures/bc7_vectors.txt`](../../crates/texture/tests/fixtures/bc7_vectors.txt)) | packed footprints only, 16-byte blocks ([`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs)) | — | — | — | — | [Khronos DFS 1.3, BPTC BC7](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc7) (section 20.1, Tables 109–120); [Microsoft, BC7 Format](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format) |
| BC7 sRGB | — | same bytes as BC7; the sRGB transfer function is outside the decoder | — | — | — | — | — | as BC7 |
| Depth32Float | — | not needed | render attachment | `render_depth` with depth readback ([`crates/metal/tests/native/depth.rs`](../../crates/metal/tests/native/depth.rs)) | — | — | — | [`MTLPixelFormat.depth32Float`](https://developer.apple.com/documentation/metal/mtlpixelformat/depth32float) |
Sampler state is limited to nearest filtering and clamp-to-edge addressing ([`crates/texture/src/sampler.rs`](../../crates/texture/src/sampler.rs)). Other filter or address modes are rejected.
Native BC paths require `supportsBCTextureCompression`. A device without it fails as a capability error ([`crates/metal/src/compute.rs`](../../crates/metal/src/compute.rs)), separately from implementation failures.
Known source differences, recorded where they are implemented:
- **BC6H:** the Khronos text and Microsoft's sample code disagree on whether a negative value that rounds to zero keeps its sign (`-0.0` against `0.0`). `bc6h.rs` follows Khronos.
- **BC1:** Apple's hardware rounds BC1's interpolated palette entries differently from the spec-exact decoder (171/84 against 170/85, see `CHANGELOG.md`). The sampled BC1 fixtures therefore use only endpoint colours.
## Layouts
| Layout | State | Where |
| --- | --- | --- |
| Row-major RGBA8 mips | implemented | [`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs) |
| Budgeted staged RGBA8 upload | implemented | `MetalRgba8Texture::upload_staged`, [`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs) |
| Pitched, layer-major BC uploads (one pitch for every mip, padded slices) | implemented for BC1–BC5 | [`crates/texture/src/upload.rs`](../../crates/texture/src/upload.rs) |
| Per-subresource packed footprints for block-compressed mip chains (tight or aligned rows) | layout implemented for BC1–BC7; native readback covers BC1–BC5 (#241, PR #278) | [`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs), [`crates/texture/tests/bc_footprint.rs`](../../crates/texture/tests/bc_footprint.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs) |
| The synthetic 2×2-tile BC1 layout | implemented; defined by the project's fixtures, not by any console | [`crates/texture/src/lib.rs`](../../crates/texture/src/lib.rs) |
| Desktop RDNA 2 surface tiling (swizzle modes) | unknown; not researched in this repository | — |
| Console texture memory layouts | unknown; no public source reviewed | — |
## Public specifications
These are the primary sources the implementations above cite. The format rows already name them in their source files.
- [Khronos Data Format Specification 1.3](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html): the [S3TC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#S3TC) section (BC1–BC3), the [RGTC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#RGTC) section (BC4, BC5), section 20.1 ["BC7"](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc7) and section 20.2 ["BC6H"](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc6h).
- Microsoft Direct3D documentation: ["Texture Block Compression in Direct3D 11"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11), ["Block Compression (Direct3D 10)"](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression), ["BC6H Format"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format) and ["BC7 Format"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format). These are used for the format definitions and DXGI format codes, not for console behaviour.
- Apple Metal documentation: [`MTLPixelFormat`](https://developer.apple.com/documentation/metal/mtlpixelformat) and [`MTLDevice.supportsBCTextureCompression`](https://developer.apple.com/documentation/metal/mtldevice/supportsbctexturecompression), for the native pixel formats and the capability check.
- AMD "RDNA 2" Instruction Set Architecture reference guide ([GPUOpen architecture documentation](https://gpuopen.com/amd-gpu-architecture-programming-documentation/)): MIMG instructions such as `image_sample_lz`, and the image resource and sampler descriptor formats. These cover desktop gfx1030 only. [Xbox GPU evidence](xbox-gpu.md) records why desktop statements do not transfer to the console without separate evidence.
## Unknowns
These are research questions, not missing features:
- **Console texture memory layouts and tiling.** No public specification has been reviewed. Desktop RDNA 2 tiling would be a separate research note and would still not establish console behaviour.
- **Console resource descriptor formats.** Unknown. See [Xbox GPU evidence](xbox-gpu.md), which lists descriptor layout among the unresolved items.
- **Asset and audio containers.** BetterXen parses none. The runtime's audio path accepts only raw PCM (`XENORA_AUDIO_FORMAT_PCM_S16LE` and `PCM_F32LE` in [`crates/ffi/include/xenora.h`](../../crates/ffi/include/xenora.h)). No original workload has shown a need for a container or a compressed audio format.
## Follow-ups
Ranked by how close each is to existing tested paths. The first item is already tracked; the others are proposals, so do not start them without an issue and a claim.
1. **BC6H two-subset modes and native BC6H/BC7.** Tracked in #208 (CPU decode, with an archived request to take it) and #209 (native upload and readback, whose imported proposal waits for maintainer approval). BC6H and BC7 already have packed footprints, so #209 can build on `PackedBcUpload`. Do not duplicate them.
2. **Translated sampling of BC2–BC5.**
- Fixture: original blocks with hand-chosen endpoints and indices, sampled by the existing `image_sample_lz` pixel stage.
- Expected values: derived by hand from the Khronos tables. The `bc.rs` decoders must not produce them, so that the decoder and the reference stay independent.
- Owners: Metal and Compiler.
3. **Additional sampler state** (linear filtering, wrap and mirror addressing).
- Fixture: a small original RGBA8 texture with distinct texels.
- Expected values: from the public Direct3D and Metal sampling equations, computed in exact fractions.
- Owners: Metal and Compiler.
4. **Desktop RDNA 2 image resource descriptor decoding.** Needed before guest-supplied descriptors can select formats.
- Fixture: original descriptor words for each supported format.
- Expected values: from the AMD RDNA 2 ISA guide's descriptor tables.
- Owner: ISA.
- This does not cover console descriptors.
Deferred, with no demonstrated need:
- BC7 sRGB
- DDS and KTX containers
- ASTC and ETC (not part of the desktop Direct3D 12 BC set this target uses)
- any compressed audio format
- console tiling, until a public source exists
+16 -6
View File
@@ -6,14 +6,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
| Measure | Count |
| --- | ---: |
| Services with a declared ABI | 37 |
| Generated adapters | 37 |
| Unique handler implementations | 37 |
| Services with a declared ABI | 47 |
| Generated adapters | 47 |
| Unique handler implementations | 47 |
| Implemented | 7 |
| Partial | 27 |
| Partial | 37 |
| Stub | 3 |
| Conformance-tested through guest dispatch | 37 |
| API-set aliases (not services) | 37 |
| Conformance-tested through guest dispatch | 47 |
| API-set aliases (not services) | 47 |
| Independently accepted | 0 |
| Service | Signature | Status | Failure |
@@ -30,6 +30,16 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
| `kernel32.dll!SetThreadPriority` | `(thread: handle, priority: i32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER |
| `kernel32.dll!CloseHandle` | `(object: handle) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE |
| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer |
| `ucrtbase.dll!__acrt_iob_func` | `(index: u32) -> ptr` | partial | stops the guest for an index above 2 or when the streams cannot be allocated |
| `ucrtbase.dll!__stdio_common_vfprintf` | `(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32` | partial | -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled |
| `ucrtbase.dll!fwrite` | `(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64` | partial | 0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream |
| `ucrtbase.dll!fputs` | `(text: ptr, stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream |
| `ucrtbase.dll!fflush` | `(stream: ptr) -> i32` | partial | stops the guest for a pointer that is no stream |
| `ucrtbase.dll!setvbuf` | `(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32` | partial | -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream |
| `ucrtbase.dll!fopen` | `(name: ptr, mode: ptr) -> ptr` | partial | null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM |
| `ucrtbase.dll!fclose` | `(stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream |
| `ucrtbase.dll!fgets` | `(buffer: ptr, count: i32, stream: ptr) -> ptr` | partial | null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream |
| `ucrtbase.dll!perror` | `(message: ptr) -> void` | partial | never |
| `kernel32.dll!GetLastError` | `() -> u32` | partial | never |
| `kernel32.dll!SetLastError` | `(code: u32) -> void` | partial | never |
| `ucrtbase.dll!__p___argc` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
+1
View File
@@ -1,5 +1,6 @@
# Testing and acceptance
- [Migrated pull-request integration review](migration-pr-review.md) — Merge decisions, fixes, native verification and remaining scope limits.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
+82
View File
@@ -76,6 +76,88 @@ cargo build --release -p xenora-benchmarks
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench --reps 7
```
## Startup distributions
`xenora-bench startup` measures what it costs to get one fixture result from
Metal, in two regimes:
- **Fresh process.** The harness launches its own executable `--processes`
times (default 30), one after another. Each child creates the Metal device and
queue, translates the fixture, runs it once and checks the output.
- **Repeated.** The harness process creates one device, runs the fixture once
(reported as *first in process*), then translates and runs it `--reps` more
times (default 100).
The fixture is the first one in `benchmarks/manifest.toml` unless `--fixture`
names another, at its smallest declared size unless `--words` sets one. The
independent reference must agree with the hand-derived expected values first,
and every sample in both regimes must produce the expected words. A wrong
output, a child that fails or does not exit within 60 seconds, or a damaged
sample line stops the run before anything is written.
| Phase | Source | Meaning |
| --- | --- | --- |
| `spawn_to_main` | wall clock, parent before spawn to child `main` | Process launch and Rust runtime start (fresh only) |
| `device` | host monotonic clock | `NativeCompute::new`: device and queue (fresh, and once in the repeated process) |
| `translate` | host monotonic clock | Read the fixture and run `xenora-shader::compile` |
| `library` | `RunProfile` | `newLibraryWithSource` |
| `pipeline` | `RunProfile` | Compute pipeline state creation |
| `submit` | `RunProfile` | `host` minus `library` and `pipeline`: buffers, encode, commit, wait |
| `gpu` | `GPUEndTime - GPUStartTime` | Command-buffer GPU execution |
| `readback` | `RunProfile` | Copy the output words back |
| process wall | host monotonic clock in the parent | Spawn to exit of one fresh child |
The report gives median, p90, p99 and maximum per phase. Percentiles
interpolate linearly, so with 30 processes p99 lies between the two largest
samples. `startup.json` also keeps every fresh sample in launch order.
Children inherit the parent's environment, so the `MTL_*` validation values in
`metadata.json` apply to both regimes. Results go to the ignored
`artifacts/startup/<hardware>/<run-id>/` unless `--output` says otherwise.
```sh
cargo build --release -p xenora-benchmarks
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench startup
```
### Recorded run
This is the imported contributor's record for the named source revision.
The integration review does not reproduce or independently accept the full
measurement protocol below.
Run `1795544761`, Apple M4, release build of `0fdb995` plus this harness, API
and shader validation off, AC power, no thermal warnings, started right after
the release build. Fixture `add`, 4 words, 30 fresh processes, 100 repeated
runs. All values in milliseconds.
| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `spawn_to_main` | 2.746 | 3.133 | 5.325 | 6.198 | – | – | – | – | – |
| `device` | 35.762 | 38.770 | 41.060 | 41.864 | 32.802 | – | – | – | – |
| `translate` | 0.061 | 0.071 | 0.084 | 0.089 | 0.067 | 0.016 | 0.023 | 0.041 | 0.043 |
| `library` | 0.402 | 0.434 | 18.595 | 25.976 | 0.399 | 0.006 | 0.010 | 0.018 | 0.019 |
| `pipeline` | 0.363 | 0.401 | 0.623 | 0.708 | 0.342 | 0.013 | 0.021 | 0.031 | 0.043 |
| `submit` | 1.665 | 1.894 | 1.951 | 1.953 | 1.647 | 0.214 | 0.384 | 0.440 | 3.941 |
| `gpu` | 0.007 | 0.008 | 0.010 | 0.011 | 0.008 | 0.007 | 0.008 | 0.061 | 1.742 |
| `readback` | 0.001 | 0.001 | 0.002 | 0.002 | 0.001 | < 0.001 | < 0.001 | < 0.001 | < 0.001 |
| process wall (spawn to exit) | 43.225 | 46.770 | 68.236 | 75.958 | – | – | – | – | – |
Observations, without causal claims:
- Device and queue creation is the largest fresh-process phase, about 36 ms of a
43 ms median process. Within one process it is paid once.
- The `library` tail came from the first child launched after the build
(25.976 ms; the other 29 were 0.36–0.45 ms). A second run immediately after,
`1795544763`, had a fresh `library` maximum of 0.446 ms, with `device` median
36.414 ms and process-wall median 44.111 ms. This fits an on-disk Metal
compilation cache, but the run does not show that.
- After the first run in a process, `library` and `pipeline` fall to about
0.01 ms and `submit` to about 0.2 ms. The `gpu` time for this 4-word kernel is
at timer scale in both regimes.
Two runs on one host do not describe other Apple GPU generations, sustained
load, other fixtures or larger word counts.
## Limitations
The corpus currently covers three synthetic gfx1030 compute fixtures under the
+171 -5
View File
@@ -1,9 +1,10 @@
# CPU test runtime and shard selection
# CPU test runtime, shards and coverage map
This page records what the CPU test gate costs and describes
`scripts/cpu-tests.sh`, which splits that gate into deterministic shards. The
shards are a convenience for local iteration and parallel runners. They do not
replace any gate: `cargo test --locked --workspace` stays the full CPU gate, and
This page records what the CPU test gate costs, describes
`scripts/cpu-tests.sh`, which splits that gate into deterministic shards, and
maps which x86-64 and loader behavior the tests verify. The shards are a
convenience for local iteration and parallel runners. They do not replace any
gate: `cargo test --locked --workspace` stays the full CPU gate, and
`scripts/test-gpu.sh` stays the GPU gate.
## What counts as a CPU test
@@ -96,3 +97,168 @@ than the full gate, because each target pays Cargo start-up.
different commits are not comparable.
- The experiment workspace `experiments/x1` is outside the selection. CI runs
it separately.
## CPU and loader coverage map
This map inventories what the CPU and loader tests verify, per operation
family, with the exact evidence commands and counts behind every number. It is
documentation of verified state, not a compatibility claim, and it contains no
percentages: every figure below is a count that a recorded command produced on
one machine. The behavioral rules behind the map (how forms are declared, what
"implemented" means, which forms are rejected on purpose) are documented in
[docs/cpu/instruction-registry.md](../cpu/instruction-registry.md) and are not
repeated here except where the map adds evidence.
### Method and revision
All commands ran on Apple M5, macOS 26.6.2, native arm64, Rust
`1.100.0-aarch64-apple-darwin` (the revision CI pins), `CARGO_BUILD_JOBS=2`,
on the branch holding this change, based on upstream `main` at
`67b8cff` (2026-11-25).
Recorded evidence commands:
```sh
python3 crates/loader/generate_x86.py validate # 213 operations, 403 forms, 498 opcode slots
python3 crates/loader/generate_x86.py --check # x86_table.rs is fresh
PYTHONPATH=scripts python3 -m qa cpu-inventory # advisory partitions, cross-checked below
cargo test --locked --workspace # 116 result lines: 1015 passed, 0 failed, 34 ignored
```
The registry numbers are the generator's own count, not a hand count. The
advisory `qa cpu-inventory` output was cross-checked against the code before
use, and one stale row is called out under "Intentionally rejected forms".
The default run recorded 34 ignored tests.
| Count | Category | Files |
| --- | --- | --- |
| 26 | Native Metal correctness | Five in `crates/loader/tests/` (`dbt_render.rs`, `graphics_d3d12.rs`, `graphics_textures.rs`, `runtime_x15.rs`), seven in `tests/validation/known_answers.rs`, and fourteen across `tests/validation/tests/` (`operand_domains.rs`, `sop1_unary.rs`, `sop2_arith.rs`, `sop2_stage_c.rs`, `sopc_stage_d.rs`, `sopk.rs`, `vop1_integer.rs`, `vop2_integer.rs`, `vop2_vcc.rs`, `vop3_compare.rs`, `vop3_integer.rs`, `vopc_f_t.rs`, `vopc_wide.rs`). |
| 5 | LLVM AMDGPU oracle | Two in `crates/decoder/tests/gfx1030.rs` and one each in `crates/isa/tests/extension_word_negative.rs`, `meta_corpus.rs` and `meta_llvm.rs`. |
| 3 | Manual CPU timing | Warm guest memory in `crates/loader/src/memory.rs`, relocation in `crates/loader/src/reloc.rs` and TLS templates in `crates/loader/src/tls.rs`. |
The two manual GPU timing tests in `crates/metal/tests/native_compute.rs`
are outside these totals. Cargo requires the `gpu-tests` feature to build
that target.
### Declared instruction inventory
`crates/loader/x86/instructions.toml` declares the decodable x86-64 surface.
`generate_x86.py validate` reports **213 operations, 403 forms, 498 opcode
slots** at this revision. By opcode map the slots split 235 one-byte and 263
`0F`; by mandatory prefix 352 none, 107 `66`, 16 `F2`, 23 `F3`; by operand size
96 byte (`b`), 139 variable 16/32/64 (`v`), 160 XMM 16-byte (`x`), 58 no
operand (`n`), 22 32/64-only (`y`), 23 64-bit (`q`).
A declared form is decodable, not implemented. A form counts as supported only
when it has semantics and fixture evidence. The fixture half is enforced:
`every_declared_form_is_executed_by_a_fixture` in
`crates/loader/tests/x86_integer.rs` decodes every line of the three assembly
corpora (`tests/x86/integer.txt`, `vector.txt`, `float.txt`) and fails if any
declared form is never executed. It lists the operations that are covered
elsewhere instead (control flow and exits, `LDMXCSR`, and the
`MOVS`/`STOS`/`CLD`/`STD` string family, which need their own memory layout and
are covered form by form in `tests/cpu_rep.rs` and the loop tests).
### Engine path per operation
Of the 213 declared operations, **93 have at least one ARM64-lowered form**.
Some other forms of those operations still use the shared interpreter helper.
**119 operations use the helper for every translated form**, and **one**,
`SYSCALL`, is decoded but refused by `is_translatable` in the DBT. Helper
calls count toward `DbtMetrics::interpreter_fallbacks`. The conditional gates
in `is_native` in `crates/loader/src/dbt.rs` apply at form level.
- `ADD`, `SUB`, `CMP`, `AND`, `OR`, `XOR`, `TEST`, `INC`, `DEC`, `NEG`, `NOT`
and `CMOV` are native only at 32- and 64-bit width; 8- and 16-bit forms use
the shared semantics.
- `ADC` and `SBB` are native only for register and immediate operands; a memory
destination stays on the helper path.
- `BT` is native only in the `0F A3` register-index form; the `0F BA /4`
immediate-index form can read a memory operand and uses the helper.
- `BSF` and `BSR` are native at 16/32/64-bit width.
- `POP` is native only in the opcode-register form.
`tests/x86_integer.rs` asserts the split both ways for every fixture: native
forms must never call the helper, and helper forms always must. The interpreter
runs all 213 operations through the shared semantics.
### Test evidence by artifact
Counts are from the full gate run recorded above (target name, tests run,
passed/ignored). Expectation sources are named so independence can be judged.
| Artifact (under `crates/loader/tests/`) | Expectations derived from | Run result |
| --- | --- | --- |
| `x86_integer.rs` + `x86/integer.txt` (1230 fixture lines) | LLVM-assembled encodings; byte-level references written from the SDM/APM operation text, independent of the production semantics | 16 passed, 0 failed |
| `x86_vector.rs` + `x86/vector.txt` (374 lines) | same method, SSE2 packed forms | 9 passed |
| `x86_float.rs` + `x86/float.txt` (172), `x86/float_vectors.txt` (6824), `x86/float_reference.py` | exact-fraction reference computed by script, following SDM Vol. 1 floating-point rules | 9 passed |
| `cpu_known_answers.rs` (50 tests, 838 named case lines) | Intel SDM and AMD APM sections cited per case; both engines run each case | 50 passed, 0 ignored |
| `movsxd.rs` | SDM operation text; modular arithmetic in the test; LLVM-assembled encodings | 9 passed |
| `x86_atomic.rs` | SDM LOCK/XADD/CMPXCHG rules; both compare outcomes, unaligned operands, faults | 5 passed |
| `x86_carry_chain.rs` | widening `u128`/`i128` reference arithmetic on 256-bit chains | 8 passed |
| `x86_prefix_length.rs` | SDM prefix and length rules | 8 passed |
| `cpu_loop.rs` | a loop-model reference over every count, match point and budget | 3 passed |
| `cpu_rep.rs` | a byte-array model over every MOVS/STOS form, direction and count, plus step accounting and faults | 7 passed |
| `cpu_features.rs` | CPUID feature-bit pairing per the SDM; each reported bit requires the feature's fixtures, each commonly-tested unreported bit requires a refused witness | 4 passed |
| `cpu_differential.rs` | interpreter and DBT must agree on shared fixtures | 5 passed |
| `arm64_encodings.rs` | LLVM encodings for the assembler's emitted ARM64 | 3 passed |
| `memory_page_boundaries.rs`, `memory_validation.rs` | mapping/permission/boundary contracts | 8 + 9 passed |
| `generated_conformance.rs`, `bootstrap.rs`, `gate_a1.rs`, `gate_a2.rs`, `indirect_control.rs`, `bswap.rs`, `dbt_render.rs`, `process_exit.rs` | per-file documented contracts (generated conformance vectors, startup gates, control flow) | all passed except one Metal-gated ignore in `dbt_render.rs` |
Count named known-answer rows, including both byte-encoded and decoded cases,
with the following command. This excludes section directives, format comments
and Rust match arms.
```sh
rg -c '^[A-Za-z0-9_]+:.*=>' crates/loader/tests/cpu_known_answers.rs
```
The cache revalidation change in [PR #269](https://github.com/MacosPorters/betterxen/pull/269)
restored `dbt_executes_modified_code_after_a_jump`. It passed in this run,
and `cpu_known_answers.rs` reported 50 passes and zero ignores.
### Operations covered by model tests instead of the fixture corpus
The mnemonic-level fixture scan behind the advisory
`PYTHONPATH=scripts python3 -m qa cpu-inventory` reports no assembly-text
fixture for eight operations: `cld`, `std`, `jrcxz`, `loop`, `loope`,
`loopne`, `movs`, `stos`. That is by design, not a gap: those operations need
their own memory layout or counter model and are covered form by form in
`tests/cpu_rep.rs` (MOVS/STOS/REP, the direction flag set by `STD` and cleared
by `CLD`) and `tests/cpu_loop.rs` (LOOP/LOOPE/LOOPNE, JRCXZ on zero RCX). The
declared-form enforcement test also exempts `LDMXCSR`, `Jcc`, `JMP`,
`CALL`, `RET`, `HLT` and `SYSCALL`. It checks the remaining forms against the
corpora.
### Intentionally rejected forms
The rejection list with its scope rules (LOCK limited to the memory forms of
XADD and CMPXCHG, every x87 instruction except FNINIT,
LODS/CMPS/SCAS/REPE/REPNE, MMX, RCP/RSQRT approximations, SSE3 and later,
VEX, address-size overrides, 16-bit stack/branch forms, 16-bit BSWAP and
MOVSXD, bit tests of memory by register index, CMPXCHG8B/16B, and the DBT
refusing raw SYSCALL) is maintained in
[docs/cpu/instruction-registry.md](../cpu/instruction-registry.md) and is
tested by refusal cases inside the files above; this map does not duplicate it.
One advisory-tool discrepancy is recorded for its owner: the hand-written
`unsupported_catalog` in `scripts/qa/cpu_inventory.py` lists "RCL/RCR/SHLD/
SHRD", "string instructions" and "atomics/fences", which is stale against the
code and tests at this revision — RCL/RCR/SHLD/SHRD are declared registry
forms with implemented semantics (`x86_exec.rs`), 9 named `rcl*` cases and 8 named `shld*` or `shrd*` cases using the rule above,
and 72 SHLD/SHRD assembly fixture lines; MOVS/STOS and the
LOCK forms of XADD/CMPXCHG and the fences are supported within the documented
scope. The catalog is advisory only and does not feed any gate.
### Map limitations
- Every count is pinned to the revision, host and single run named above.
- The fixture evidence is mnemonic-level where it comes from the assembly
corpora: it proves every declared form executes somewhere, not that every
encoding variant of a form has its own expected-value case. The known-answer
files carry the per-case expectations; their case lines are counted, not
audited one by one here.
- The native/shared partition is read from `is_native` at this revision and
asserted by the fixtures; it is not a promise for other revisions.
- Nothing here was compared with x86 hardware, no compatibility percentage is
implied, and this is local documentation evidence, not independent
acceptance.
+57 -5
View File
@@ -8,7 +8,7 @@ when both pass.
| Milestone | What it is | Status |
| --- | --- | --- |
| A1 | An original C program with no C library linked, importing documented `kernel32.dll` and `ucrtbase.dll` functions, run through the loader and the ARM64 DBT with proper process exit | Passes locally; awaiting independent review |
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | Not started |
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | Passes locally; awaiting independent review |
## A1
@@ -47,7 +47,59 @@ whose entry point returns its status gives the same result as `ExitProcess`.
## A2
Not started. It needs at least the C standard I/O functions, `exit` with
`atexit` handlers, command-line and environment access, and a decision on
which C runtime startup code may be linked and under what licence. None of
those are registered today.
The program is [`tests/compat_fixtures/gate_a2.c`](../../tests/compat_fixtures/gate_a2.c).
Its build configuration and provenance are in
[`tests/compat_fixtures/README.md`](../../tests/compat_fixtures/README.md#gate-a2-a-hosted-c-program).
The gate is `crates/loader/tests/gate_a2.rs`:
```sh
cargo test --locked -p xenora-loader --test gate_a2 -- --nocapture
```
"Hosted" means the program is linked with a real C runtime, whose own startup
code runs before `main`. Here that runtime is mingw-w64's, in its UCRT
flavour: the startup objects and a little of GCC's support library are linked
into the executable, and the C library itself is imported by name from the
Universal C Runtime's API-set DLLs and from `kernel32.dll`. Xenora's services
answer those imports. Nothing from Windows is loaded.
The test builds the program from source with `x86_64-w64-mingw32-gcc`. It
fails, and does not skip, when that compiler is missing. It then runs each
build through `run_synthetic_startup` with `register_standard_services`,
loaded away from its preferred base, with the command line
`gate-a2.exe 2026 xenora` set through `ServicesState::set_program_arguments`.
It checks, at `-O0`, `-O1`, `-O2` and `-Os`:
- every import is bound (50 at each level with the toolchain used locally; the test prints the count) and base relocations are applied;
- the guest ends with `ExitReason::ProcessExit(0)`: `main` returned and the runtime's startup code passed its result to `exit`;
- captured standard output equals, byte for byte, text recomputed in Rust from the description of the program, including the line a function registered with `atexit` prints after `main` has returned; standard error is empty;
- the report file the program wrote with `fprintf` and `fputs` is on the in-memory drive with the recomputed contents, the file it looked for was not created, and no handle is left open;
- it ran as translated code, with service calls.
The program checks its own results as well: it prints its arguments, fills
heap memory from a small generator, sorts it with `qsort` and a callback,
checksums it before and after, writes the report, reads it back with `fgets`,
`strtoul` and `strtoull`, and confirms that a missing file is reported. It
exits with the number of the first check that fails, and counts the checks
that passed; a complete run counts 76.
Seven more tests guard against a runtime that reports success for everything:
- another seed and label give another output and another report;
- four wrong command lines each fail the check that looks at them, with that check's number as the exit status and its message on standard error;
- a variant with one wrong expectation exits with 22;
- a variant that calls `exit(42)` half way ends with 42, its `atexit` function still runs, and the report is never written;
- a variant that calls `abort()` half way ends with 3 and its `atexit` function does not run;
- a step budget that is too small is not an exit;
- the Rust restatement of the program is itself checked not to be degenerate.
### What A2 does not show
- It is one program and one C runtime: mingw-w64 14.0.0 with GCC 16.2.0 locally. A program built with Microsoft's compiler starts differently and imports other functions; none has been tried. A larger program can need instructions and services this one does not.
- The same source built natively with Apple clang prints the same text once carriage returns are removed. That comparison was made by hand and is not part of the test. Nothing was compared with Windows or with x86 hardware.
- No floating point is formatted and no input is read. `printf` refuses the floating-point and wide-character conversions, and `stdin` and the `scanf` family do not exist.
- Most services the program calls are marked partial in the registry. No locale exists, no signal handler or exception filter is ever called, the environment table is empty, and a C stream is unbuffered and has no seek. They did what this program needs.
- `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` are stubs that stop the guest if called. The program imports them and never calls them.
- It runs in the DBT only, on one guest thread.
- It reaches the guest through a test, not through `xenora run`.
- Nothing here concerns a commercial game or an Xbox launch environment.
+96
View File
@@ -0,0 +1,96 @@
# Migrated pull-request integration review
Reviewed on November 24, 2026 (America/Chicago). The initial inventory contained
23 open pull requests under `Arths17`, including the development-plan PR.
Twenty-two were merged after their updated heads passed the applicable GitHub
checks. Imported records retain their original author attribution and commits.
The maintainer authorized per-merge admin overrides for the review restriction.
The ARM64 build/test requirement, one-approval rule, code-owner review requirement
and enforcement for admins remain configured. Failed or pending checks were
resolved before merging. The conditional `verify` comment job is normally skipped;
that skip is not independent semantic verification.
## Results
All links below refer to the BetterXen repository.
| PR | Result | Integration work |
| --- | --- | --- |
| [#263](https://github.com/MacosPorters/betterxen/pull/263) | Pending | Pending: overlaps the contributor's live PR #290, excluded by the maintainer. |
| [#264](https://github.com/MacosPorters/betterxen/pull/264) | Merged; checks passed | Identification fixture runs in ordinary tests; benchmark-harness lint fixed. |
| [#265](https://github.com/MacosPorters/betterxen/pull/265) | Merged; checks passed | Bounded native texture staging; planner and Metal readback tests. |
| [#266](https://github.com/MacosPorters/betterxen/pull/266) | Merged; checks passed | Startup measurement harness; unit tests and correctness smoke run. |
| [#267](https://github.com/MacosPorters/betterxen/pull/267) | Merged; checks passed | Bounded flat draws and repeated-frame regressions. |
| [#268](https://github.com/MacosPorters/betterxen/pull/268) | Merged; checks passed | Windows x64 calling conventions; writable-home-slot regression and nonvolatile vector-register negative controls. |
| [#269](https://github.com/MacosPorters/betterxen/pull/269) | Merged; checks passed | Executable generations with source revalidation; original cache assertions preserved. |
| [#270](https://github.com/MacosPorters/betterxen/pull/270) | Merged; checks passed | ARM64 shift encoding and operand checks; draft marked ready. |
| [#271](https://github.com/MacosPorters/betterxen/pull/271) | Merged; checks passed | Floating-point unit initialization, combined decoder generation and preserved tests. |
| [#272](https://github.com/MacosPorters/betterxen/pull/272) | Merged; checks passed | Dynamic binary translation (DBT) report comparison and input validation. |
| [#273](https://github.com/MacosPorters/betterxen/pull/273) | Merged; checks passed | C startup service integration and registry regeneration. |
| [#274](https://github.com/MacosPorters/betterxen/pull/274) | Merged; checks passed | Instruction-length faults and precise retirement. |
| [#275](https://github.com/MacosPorters/betterxen/pull/275) | Merged; checks passed | Flag-transfer instructions; combined fixtures and supported-case expectations retained. |
| [#276](https://github.com/MacosPorters/betterxen/pull/276) | Merged; checks passed | Explicitly unsupported service stubs and combined registry. |
| [#277](https://github.com/MacosPorters/betterxen/pull/277) | Merged; checks passed | Guest arguments and environment with combined services. |
| [#278](https://github.com/MacosPorters/betterxen/pull/278) | Merged; checks passed | Packed texture footprints; CPU and native GPU checks. |
| [#279](https://github.com/MacosPorters/betterxen/pull/279) | Merged; checks passed | Loop instructions; regenerated tables and corrected description to 3,600 comparisons. |
| [#280](https://github.com/MacosPorters/betterxen/pull/280) | Merged; checks passed | Process termination and exit callbacks. |
| [#281](https://github.com/MacosPorters/betterxen/pull/281) | Merged; checks passed | Formatted output integrated with startup and arguments. |
| [#282](https://github.com/MacosPorters/betterxen/pull/282) | Merged; checks passed | File streams; combined registry and dependency readiness. |
| [#283](https://github.com/MacosPorters/betterxen/pull/283) | Merged; checks passed | Hosted C fixture; driver architecture checked before execution. |
| [#284](https://github.com/MacosPorters/betterxen/pull/284) | Merged; checks passed | Thread-local storage (TLS) template-copy integration and preserved changelog entries. |
| [#288](https://github.com/MacosPorters/betterxen/pull/288) | Merged; checks passed | Development phases, README and migration-check record. |
PR #263 remains open to avoid competing with the contributor's live PR #290.
PR #290 was excluded from branch edits, reviews and merge operations as requested.
Its filesystem security and integration acceptance are left to that workstream.
## Verification and evidence scope
The integrated runtime candidate was
`5366b9398668128fdbb0b0879840dfa072bfa352`. Its GitHub native Rust workflow passed,
including workspace formatting, strict Clippy, tests and the hosted C fixture.
Local native results below concern the reported Apple M4 host running macOS 27.0
(class A host observations); they establish no Xbox-hardware or commercial-game
execution result.
| Check | Observed result |
| --- | --- |
| `scripts/test-gpu.sh` | 124 passed, 0 failed; 2 manual timing tests ignored. Metal API and GPU validation enabled. |
| Packed block-compressed texture GPU target | 1 passed, 0 failed, 0 ignored, with both validation layers enabled. |
| `scripts/demo.sh` | All three original fixtures matched Metal, reference and known-answer outputs. |
| `scripts/audit/native.sh` | 110 executables/loadable dependencies checked with `file`, `lipo` and `otool`; ARM64 architecture and permitted linkage checks passed. |
| Status, claims and dependency audits | Passed. |
The cache fix also passed an isolated local workspace run at `44ac976`: 917
passed, 0 failed, 35 ignored, plus strict Clippy. Its three alternating CPU
benchmark pairs used native release executables and identical original inputs:
per-run warm medians were 87.334–88.333 microseconds with per-byte validation and
15.625–18.791 microseconds with generation validation. Machine idleness was not
controlled. These measurements do not close the formal performance gate; their
candidate scope and cold results are recorded in PR #269.
A supplemental benchmark test-harness command exposed a missing initialization
for the newly added cache-invalidation counter. The follow-up initializes that
fixture and runs the existing report, JSON, comparison and percentile tests via
an ordinary integration-test target, preserving their assertions. This lets
workspace CI detect future benchmark-test compilation failures. All 14 existing
tests passed through both the ordinary integration target and the documented
manual harness command; strict workspace Clippy passed as well.
Raw final native logs, cache benchmark JSON and the PR-state inventory are kept
under ignored `artifacts/pr-integration/` in the lead checkout. PR checks and merge
records remain linked from each GitHub record.
## Remaining acceptance
This is an integration and execution record. Independent semantic and security
acceptance remains separate from implementer-run checks and administrative merge
permission. No release gates were redefined or releases created. Commercial Xbox
game execution remains unsupported.
Active-block self-modifying code is tracked separately in
[issue #291](https://github.com/MacosPorters/betterxen/issues/291); native-code cache
reclamation remains [issue #95](https://github.com/MacosPorters/betterxen/issues/95).
The source fixture programs, desktop instruction evidence and native Mac results
retain their existing boundaries.
+1 -1
View File
@@ -48,7 +48,7 @@ separate backend evidence. The [host evidence](../research/host-lab.md) records
| Gate | Baseline disposition |
| --- | --- |
| P2-01 | Baseline captured. Phase 01 evidence and blockers are linked above. |
| P2-02 | KyTx, Leonida and eight additional projects screened. Original fixtures and public specifications are the implementation source. No emulator code, tables or metadata are in scope for adoption. |
| P2-02 | KyTx, PE-Vulkan project and eight additional projects screened. Original fixtures and public specifications are the implementation source. No emulator code, tables or metadata are in scope for adoption. |
| P2-03 | VGPR-only OR verified on Apple M5. |
| P2-04 | Workspace, LLVM and native GPU regression runs passed after OR integration. |
| P2-05 | Independent OR expected values matched CPU execution and Metal readback. |
+5 -5
View File
@@ -8,7 +8,7 @@ limit. A CPU rejection pass does not certify GPU execution.
| Upstream reference | Tested behavior | Xenora equivalent | Current result | Blocker |
| --- | --- | --- | --- | --- |
| [Leonida compute](https://github.com/ItsNotRexed/Leonida/blob/3faac557b1584d39004357918e60325b4d4ff0fe/runtime/test/d3d12_compute_test.cpp) | Vulkan replay submits three distinct bindings and compares every readback word. Null, denied, malformed and out-of-bounds views decode to zero descriptors in separate controls. | Guest buffer view and original XOR readback. Persistent lifetime and snapshot tests extend this gate. | PASS for X8 view and readback | Xenora uses explicit faults for bad views. |
| [PE-Vulkan project compute](https://github.com/ItsNotRexed/Leonida/blob/3faac557b1584d39004357918e60325b4d4ff0fe/runtime/test/d3d12_compute_test.cpp) | Vulkan replay submits three distinct bindings and compares every readback word. Null, denied, malformed and out-of-bounds views decode to zero descriptors in separate controls. | Guest buffer view and original XOR readback. Persistent lifetime and snapshot tests extend this gate. | PASS for X8 view and readback | Xenora uses explicit faults for bad views. |
| [Xbox2Windows startup](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/cpu/startup_exe.cpp) | CPU startup exercises loading two DLLs, thread notifications and wait failures. | Original named-import PE32+ startup and missing import control. DLL and thread-local storage ordering are separate gates. | UNIMPLEMENTED for DLL and thread ordering | Bounded fixed-base guest profile. |
| [Xbox2Windows wave shuffle](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/wave_shuffle.cpp) | D3D12 dispatch maps output by reported wave and lane, checks affine and rotation shuffles plus mirror and uniform controls, and rejects duplicate lanes or wrong widths. Forced variants require device capability. | ARM64 CPU compiler rejects an original gfx1030 cross-lane permute with a supported compile control. Native Wave64 shuffle needs a two-wave exact oracle. | PASS for rejection. UNIMPLEMENTED for Wave64 Metal dispatch. | No cross-lane lowering or Wave64 execution contract. |
| [Xbox2Windows compute services](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/cpu/shim_compute_check.py) | Checks allocation, dispatch and free observations. Independently calculates four readback words. Provider rejection must produce zero output bytes. Native hardware is selected for the explicit hardware case. | Exact guest XOR readback, invalid import commands and observable destroy/reuse. | PASS for X8 XOR and malformed commands | Persistent resources have a separate X9 gate. |
@@ -57,9 +57,9 @@ data sections, and no native host pointer crosses that boundary.
| Upstream reference | Tested behavior | Xenora equivalent | Current result | Blocker |
| --- | --- | --- | --- | --- |
| Leonida compute and Xbox2Windows compute services | Repeat dispatch, update and release a resource with observable results | Original X9 PE repeats XOR with a nonzero view, updates words and destroys and reuses a slot. | PASS on Apple M5 | Device buffers are uploaded per completion. |
| Leonida compute | Submission bindings and lifetime are independent of later changes | X9 queues a view, changes or destroys its owner and still gets the captured output. A second queued submission is rejected. | PASS on Apple M5 for queued snapshots | Actual GPU work already in flight during release is UNIMPLEMENTED. |
| Leonida compute | Isolate guest runs and release resources at exit | X9 drops the table and any queued view at guest return. A queued-work exit returns guest status 73 and produces no GPU commands for that submission. | PASS for queued-work exit | Native Metal object residency across guest calls is UNIMPLEMENTED. |
| Leonida compute | Reject malformed resource ranges | X9 rejects invalid or stale handles, out-of-range views, offset overflow, writeback into read-only memory and invalid resource types. | PASS for guest fault controls | The guest profile exposes one bounded submission at a time. |
| PE-Vulkan project compute and Xbox2Windows compute services | Repeat dispatch, update and release a resource with observable results | Original X9 PE repeats XOR with a nonzero view, updates words and destroys and reuses a slot. | PASS on Apple M5 | Device buffers are uploaded per completion. |
| PE-Vulkan project compute | Submission bindings and lifetime are independent of later changes | X9 queues a view, changes or destroys its owner and still gets the captured output. A second queued submission is rejected. | PASS on Apple M5 for queued snapshots | Actual GPU work already in flight during release is UNIMPLEMENTED. |
| PE-Vulkan project compute | Isolate guest runs and release resources at exit | X9 drops the table and any queued view at guest return. A queued-work exit returns guest status 73 and produces no GPU commands for that submission. | PASS for queued-work exit | Native Metal object residency across guest calls is UNIMPLEMENTED. |
| PE-Vulkan project compute | Reject malformed resource ranges | X9 rejects invalid or stale handles, out-of-range views, offset overflow, writeback into read-only memory and invalid resource types. | PASS for guest fault controls | The guest profile exposes one bounded submission at a time. |
| Xbox2Windows pixel attributes | GPU pixels agree with a CPU expectation | X9 renders a constant or perspective-interpolated triangle through both translated stages. The PE checks every returned pixel. A separate host oracle checks exact values and the guest report. Changing the expected red byte of one interior pixel makes the PE return 93 after the same GPU readback. | PASS on Apple M5 | Shader selection uses original fixed fixture IDs. |
| bcpack-rs round trips and Xbox2Windows texture LOD | Edge data and malformed input distinguish valid subresources | X9 validates a pitched descriptor, rejects wrong usage, layer, size and update requests, and reads selected BC1 mips and layers back through Metal. | PASS on Apple M5 for selected subresource readback | Translated texture sampling and GPU texture lifetime across guest calls are UNIMPLEMENTED. |
+1 -1
View File
@@ -6,7 +6,7 @@ identified the arithmetic shift as a candidate. Xenora uses the public
and its existing pinned AMD XML generator for the VOP2 encoding. The lowering
uses signed integer shift from the
[Metal Shading Language Specification](https://developer.apple.com/metal/Metal-Shading-Language-Specification).
The implementation and fixture were authored in Xenora. No Leonida code, tables,
The implementation and fixture were authored in Xenora. No PE-Vulkan project code, tables,
dependencies or game material were imported.
The decoder accepts the VOP2 VGPR/VGPR form. The shader lifter retains the synthetic
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Fast, deterministic documentation and repository hygiene checks.
Checks only tracked files:
1. no merge-conflict markers in tracked text files;
2. every relative Markdown link points at a tracked file or directory;
3. every workflow file under .github/workflows parses as YAML.
External URLs and in-page anchors are not fetched or validated, so the result
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
when PyYAML is missing.
"""
import re
import subprocess
import sys
from pathlib import Path, PurePosixPath
from urllib.parse import unquote
ROOT = Path(__file__).resolve().parents[2]
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
FENCE = re.compile(r"^\s*(```|~~~)")
def tracked():
out = subprocess.run(["git", "ls-files", "-z"], cwd=ROOT, check=True,
capture_output=True).stdout.decode("utf-8", "replace")
return [p for p in out.split("\0") if p and (ROOT / p).is_file()]
def text(path):
data = (ROOT / path).read_bytes()
if b"\0" in data:
return None
return data.decode("utf-8", "replace")
def check_markers(files, problems):
for path in files:
if path.endswith((".patch", ".diff")):
continue
body = text(path)
if body is None:
continue
for number, line in enumerate(body.splitlines(), 1):
if MARKER.match(line):
problems.append(f"{path}:{number}: merge conflict marker")
def check_links(files, problems):
known = set(files)
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
for path in files:
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
continue
in_fence = False
for number, line in enumerate((text(path) or "").splitlines(), 1):
if FENCE.match(line):
in_fence = not in_fence
continue
if in_fence:
continue
line = re.sub(r"`[^`]*`", "", line)
for target in LINK.findall(line):
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
continue
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
if not target:
continue
base = PurePosixPath(path).parent
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
parts = []
for part in resolved.parts:
if part == "..":
if parts:
parts.pop()
elif part != ".":
parts.append(part)
norm = "/".join(parts)
if norm and norm not in known and norm not in dirs:
problems.append(f"{path}:{number}: broken relative link '{target}'")
def check_workflows(files, problems, require_yaml):
try:
import yaml
except ImportError:
if require_yaml:
problems.append("PyYAML is not installed but --require-yaml was given")
else:
print("note: PyYAML not installed; workflow YAML parse check skipped", file=sys.stderr)
return
for path in files:
if path.startswith(".github/workflows/") and path.endswith((".yml", ".yaml")):
try:
yaml.safe_load((ROOT / path).read_text(encoding="utf-8"))
except yaml.YAMLError as err:
problems.append(f"{path}: invalid YAML: {str(err).splitlines()[0]}")
def main():
files = tracked()
problems = []
check_markers(files, problems)
check_links(files, problems)
check_workflows(files, problems, "--require-yaml" in sys.argv[1:])
for problem in problems:
print(problem)
print(f"docs hygiene: {len(files)} tracked files checked, {len(problems)} problem(s)")
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())
+19
View File
@@ -54,5 +54,24 @@ codesign --force --sign - "$bundle"
binary="$bundle/Contents/MacOS/BetterXen"
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
file "$binary"
# Only system libraries may be linked: anything else would be a host dependency
# shipped or expected outside macOS, which this bundle does not carry. List the
# dependencies once, print that listing and check the same output.
dependencies=$(otool -L "$binary") || fail "otool -L failed for $binary"
printf '%s\n' "$dependencies"
dependencies=$(printf '%s\n' "$dependencies" | tail -n +2 | awk '{print $1}')
# Every Swift executable links at least libSystem, so an empty list is an error.
[ -n "$dependencies" ] || fail "otool -L listed no dependencies for $binary"
for dependency in $dependencies; do
case "$dependency" in
/System/Library/*|/usr/lib/*) ;;
@rpath/*|@executable_path/*|@loader_path/*)
fail "executable links a bundle-relative library, but this bundle ships none: $dependency" ;;
*) fail "executable links a non-system library: $dependency" ;;
esac
done
"$binary" --smoke
"$binary" --smoke-inspection-order
"$binary" --smoke-import-result
echo "build-app: built $bundle"
-105
View File
@@ -1,105 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Check that a pull request description follows .github/PULL_REQUEST_TEMPLATE.md.
Standard library only. The description is read as data from the GitHub event
file (or a plain text file with --body-file); it is never executed.
Exit status 0 when the description passes, 1 when something is missing.
"""
import argparse
import json
import re
import sys
SECTIONS = (
"Summary",
"Implementation and evidence",
"Verification",
"Compatibility and limitations",
"Checklist",
"AI assistance",
)
# Checklist items that must be ticked, found by the start of their text.
REQUIRED_TICKS = (
("I claimed the linked issue", "the claimed-first checkbox"),
("My commits are signed off under the DCO", "the DCO sign-off checkbox"),
)
ISSUE_LINK = re.compile(r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#\d+", re.I)
NO_ISSUE = re.compile(r"^\s*No linked issue:\s*\S", re.I | re.M)
COMMENT = re.compile(r"<!--.*?-->", re.S)
EMPTY_LINK = re.compile(r"^\s*(?:close|fix|resolve)\w*\s*#\s*$", re.I)
HEADING = re.compile(r"^##\s+(.+?)\s*$", re.M)
def sections(body):
"""Map each level-2 heading to its text, with HTML comments removed."""
text = COMMENT.sub("", body.replace("\r\n", "\n"))
found = {}
marks = list(HEADING.finditer(text))
for i, m in enumerate(marks):
end = marks[i + 1].start() if i + 1 < len(marks) else len(text)
found[m.group(1).strip().lower()] = text[m.end():end].strip()
return text, found
def has_content(name, value):
if name == "Verification":
# The empty table from the template does not count: some cell must be filled.
rows = [r for r in value.splitlines() if r.strip().startswith("|")]
filled = [r for r in rows[2:] if [c for c in r.strip().strip("|").split("|")[1:] if c.strip()]]
prose = [r for r in value.splitlines() if r.strip() and not r.strip().startswith("|")]
return bool(filled or prose)
if name == "Checklist":
return "- [" in value
# A bare "Closes #" left over from the template is not content.
rest = [l for l in value.splitlines() if l.strip() and not EMPTY_LINK.match(l)]
return bool(rest)
def check(body):
"""Return a list of human-readable problems; empty means the body passes."""
if not body or not body.strip():
return ["The description is empty. Copy .github/PULL_REQUEST_TEMPLATE.md into it and fill it in."]
text, found = sections(body)
problems = []
for name in SECTIONS:
if name.lower() not in found:
problems.append('Missing section "## %s".' % name)
elif not has_content(name, found[name.lower()]):
problems.append('Section "## %s" is empty.' % name)
if not ISSUE_LINK.search(text) and not NO_ISSUE.search(text):
problems.append('No linked issue: add "Closes #<number>", or a line "No linked issue: <reason>".')
checklist = found.get("checklist", "")
for prefix, label in REQUIRED_TICKS:
item = re.search(r"^\s*[-*]\s*\[( |x|X)\]\s*" + re.escape(prefix), checklist, re.M)
if not item:
problems.append("Checklist is missing %s." % label)
elif item.group(1) == " ":
problems.append("Tick %s." % label)
return problems
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__)
src = ap.add_mutually_exclusive_group(required=True)
src.add_argument("--event", help="GitHub event JSON file (pull_request or pull_request_target)")
src.add_argument("--body-file", help="file holding the description text")
args = ap.parse_args(argv)
if args.event:
with open(args.event, encoding="utf-8") as fh:
body = (json.load(fh).get("pull_request") or {}).get("body") or ""
else:
with open(args.body_file, encoding="utf-8") as fh:
body = fh.read()
problems = check(body)
if problems:
print("The pull request description does not follow .github/PULL_REQUEST_TEMPLATE.md:")
for p in problems:
print("- " + p)
print("Edit the description to fix this; the check runs again on every edit.")
return 1
print("The pull request description follows the template.")
return 0
if __name__ == "__main__":
sys.exit(main())
+51
View File
@@ -110,3 +110,54 @@ Provenance. The source, the name lists and the script were written for BetterXen
and are GPL-3.0-or-later. Nothing from a Windows SDK, a C runtime or another
project is compiled or linked. The compiler and linker are LLVM projects
under the Apache License 2.0 with LLVM exceptions; they are tools, not inputs.
## Gate A2: a hosted C program
`gate_a2.c` is an original C program that uses the standard C library as an
ordinary program does. It includes only `<stdio.h>`, `<stdlib.h>` and
`<string.h>`. It prints its arguments, fills heap memory from a small
generator, sorts it with `qsort` and a callback, checksums it, writes a
report with `fprintf` and `fputs`, reads it back with `fgets`, `strtoul` and
`strtoull`, confirms that a missing file is reported, registers a function
with `atexit`, and returns from `main`. It checks every result itself and
exits with the number of the first check that fails. It uses no floating
point and reads no input.
`build-gate-a2.sh [output directory]` builds it. `cargo test -p xenora-loader
--test gate_a2` runs that script and then runs the result through
`run_synthetic_startup`, the standard services and the DBT. No built
executable is committed: the test builds from source every time, in CI too.
The test fails, and does not skip, when the compiler is missing.
Compiler configuration:
| Step | Command |
| --- | --- |
| Compile and link | `x86_64-w64-mingw32-gcc -O<level> -Wall -Wextra -Werror -o <name>.exe gate_a2.c` |
It is built at `-O0`, `-O1`, `-O2` and `-Os`, and three more times at `-O1` as
controls: `GATE_BREAK` (one wrong expectation), `GATE_EXIT` (`exit(42)` half
way) and `GATE_ABORT` (`abort()` half way).
Tools. `MINGW_GCC` defaults to Homebrew's mingw-w64 when it is installed and
otherwise to the `x86_64-w64-mingw32-gcc` on `PATH`. The toolchain must use
the Universal C Runtime, which Homebrew's does; a toolchain built for the
older `msvcrt.dll` produces a program that imports other functions. On macOS
the script requires the compiler driver, the compiler proper, the assembler
and the linker, and every library they load that is a file on disk, to be
ARM64: it checks each with `file` and `lipo -archs`, and each library
`otool -L` lists with `lipo -archs`. It writes the compiler version to
`toolchain.txt`, which the test prints, and what the native checks looked at
to `toolchain-native.txt`. The test builds into a directory of its own for
each test process under the Cargo target directory.
Provenance. The source and the script were written for Xenora and are
GPL-3.0-or-later. Unlike the Gate A1 program, each built executable contains
code that is not Xenora's: mingw-w64's startup objects and a little of GCC's
support library, as any program built with that toolchain does. Neither is
stored in the repository or in its history; the executables are test output.
mingw-w64's `COPYING` file says its runtime is under the Zope Public License
2.1 except for parts marked as public domain, BSD or LGPL; GCC's support
library is GPL-3.0-or-later with the GCC Runtime Library Exception. The C
library itself is not linked: the program imports it by name, and Xenora's
own services answer.
+90
View File
@@ -0,0 +1,90 @@
# Original AVX integer fixture specification
This fixture is a proposed known-answer test for the
[guest AVX contract](../../../docs/cpu/avx-contract.md). It uses only the
source below, fixed register values and synthetic guest memory. Run the
eventual fixture in both guest engines on fresh copies of the same initial
state. Use the independent expected values below for each engine.
## Guest sequence
Set `r8` and `r9` to separate readable ranges containing arrays A and B.
Set `r10` to a writable 96-byte output region initialized to `0xA5` with
mapped sentinel bytes before and after it. Map the code separately as guest
executable memory. Initialize flags, MXCSR and untouched vector registers to
known nonzero values, then record their initial values. The sequence uses no
stack, imports or host calls.
```asm
.intel_syntax noprefix
.text
vmovdqu ymm1, ymmword ptr [r8]
vmovdqu ymm2, ymmword ptr [r9]
vpaddd ymm3, ymm1, ymm2
vmovdqu ymmword ptr [r10], ymm3
movdqu xmm3, xmm1
vmovdqu ymmword ptr [r10 + 32], ymm3
vmovdqu xmm3, xmm2
vmovdqu ymmword ptr [r10 + 64], ymm3
hlt
```
The high base registers require three-byte VEX for the memory moves, while
the low-register `VPADDD` and register `VMOVDQU` can use two-byte VEX.
Store each table row as eight little-endian 32-bit words, with lane 0 at
the lowest address. All entries are hexadecimal.
| Words | Lane 0 | Lane 1 | Lane 2 | Lane 3 | Lane 4 | Lane 5 | Lane 6 | Lane 7 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| A | `ffffffff` | `7fffffff` | `80000000` | `00000000` | `00000010` | `fffffffe` | `12345678` | `aaaaaaaa` |
| B | `00000001` | `00000001` | `80000000` | `ffffffff` | `00000020` | `00000003` | `11111111` | `55555556` |
| Output +0 | `00000000` | `80000000` | `00000000` | `ffffffff` | `00000030` | `00000001` | `23456789` | `00000000` |
| Output +32 | `ffffffff` | `7fffffff` | `80000000` | `00000000` | `00000030` | `00000001` | `23456789` | `00000000` |
| Output +64 | `00000001` | `00000001` | `80000000` | `ffffffff` | `00000000` | `00000000` | `00000000` | `00000000` |
For output +0, add corresponding words as unsigned integers and discard
bits above bit 31 in each sum. For example, lane 0 wraps `0x100000000` to
zero, so lane 1 has no incoming carry. At +32, the legacy move replaces the
low four words with A and retains the high four words of the sum. At +64,
the VEX.128 move replaces the low four words with B and clears the high
four. Final YMM1 and YMM2 equal A and B. Final YMM3 equals output +64.
All other vector registers, the input bytes, sentinels, general-purpose
registers, flags and MXCSR retain their initial values. Expect `Halt` with
nine steps, including the terminal `HLT`.
## Controls
| Case | Expected result |
| --- | --- |
| `VPADDD` writes to one of its input registers | Same eight-word sum using both inputs as they stood before the instruction. The other source survives. |
| 128-bit `VPADDD` with seeded destination upper half | Output +0's low four words and four zero words. Both sources survive when distinct from the destination. |
| 128-bit `VMOVDQU` store with sentinels | Exactly the low 16 bytes are stored. The entire source YMM and memory outside the operand survive. |
| 256-bit `VMOVDQU` at a 32-byte-aligned address, at an address offset by one byte, and at `P-16` across adjacent accessible mappings | Same 32 bytes at each address. `P` is the start of the second mapping. |
| Split load at `P-16`, with the second mapping unreadable or unmapped | Memory fault at `P`. Every destination bit retains its pre-instruction value. |
| Split store at `P-16`, with the second mapping read-only or unmapped | Memory fault at `P`. The 16 writable bytes before `P` retain their sentinels. |
| 256-bit `VMOVDQU` load and store at `0x0000_7fff_ffff_fff0` | Map the first 16 bytes read/write and leave the noncanonical half starting at `0x0000_8000_0000_0000` unmapped. Both operations report `GeneralProtection` under the BetterXen profile. The destination register and the mapped bytes retain their original values. |
| 256-bit `VMOVDQU` load from `[rsp]` with `rsp = 0x0000_8000_0000_0000` | The BetterXen profile reports `GeneralProtection` and preserves the destination. Intel's Type 4 rules specify `#SS(0)` for this SS-based operand. |
| Future `VMOVDQA` at aligned and misaligned addresses | An aligned, permitted span transfers the same bytes. A span misaligned by one byte produces `GeneralProtection` and has no data effects. Run at both widths. |
| Future masked dword load from `P-16` | With only lanes 0–3 enabled, load four words and zero lanes 4–7 even if the mapping at `P` is absent. Enabling lane 4 faults at `P`. An all-zero mask reads no lanes and returns an all-zero destination. |
| Future masked dword store to the same split span | With only lanes 0–3 enabled, write those four words; disabled lanes neither access the second mapping nor alter any bytes there when it is mapped. Enabling lane 4 with its mapping absent faults at `P`. |
| Reserved move `vvvv`, reserved VEX map, prohibited prefix before VEX | Illegal instruction at the offending instruction's RIP. No destination or memory update. |
| Equivalent legal `C5` and `C4` register forms, including both `W` values for `WIG` | Equal results and state, with RIP advancement matching each encoding length. Include a high ModRM.reg destination and high `vvvv` source. |
| Budget of two steps | Stop at `VPADDD` (`entry + 0xA` with the encoding shown below) with both inputs loaded, YMM3 and output untouched. Resume with seven steps and reach the same final state as a nine-step run. Repeat with a warm DBT cache. |
For faults, place a completed instruction before the failing instruction.
Assert that only the earlier instruction retires and its effects persist.
Check snapshots of the full destination or nearby memory as appropriate.
## Build provenance
Use native Apple Silicon LLVM tools to assemble the sequence as an x86-64
object, for example with `xcrun clang -arch x86_64 -c avx-fixture.s`.
Verify the resolved Clang and `llvm-objdump` executables support ARM64 before
running them. Record their versions and the output of disassembling the
object. Apple Clang 21.0.0 emits `C4 C1 7E 6F 08` for the first load and
`C5 F5 FE DA` for `VPADDD` at offset `0xA`. Keep generated sources and
objects under ignored `artifacts/`.
The test harness consumes only the object's verified instruction bytes
as guest data. Reserved encodings can be authored separately from Intel's
bit-field tables, since an assembler may reject them. Use source-derived
lane values and checked-memory expectations for the test oracle.
+96
View File
@@ -0,0 +1,96 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Build the Gate A2 program, tests/compat_fixtures/gate_a2.c, as x86-64 PE32+
# executables linked with the mingw-w64 C runtime (UCRT flavour). The
# runtime's own startup code runs before main, which is what makes the program
# "hosted".
#
# build-gate-a2.sh [output directory] default: artifacts/gate-a2
#
# Tool, native to the host:
# MINGW_GCC an x86_64-w64-mingw32-gcc. Default: Homebrew mingw-w64 if
# installed, otherwise the one on PATH.
#
# Nothing from mingw-w64 is stored in the repository. Each built executable
# contains that project's startup objects and a little of GCC's support
# library, as any program built with it does; the executables are test
# output and are not committed.
set -eu
cd "$(dirname "$0")/../.."
root=$PWD
src="$root/tests/compat_fixtures/gate_a2.c"
out=${1:-"$root/artifacts/gate-a2"}
gcc=${MINGW_GCC:-}
if [ -z "$gcc" ]; then
gcc=/opt/homebrew/opt/mingw-w64/bin/x86_64-w64-mingw32-gcc
[ -x "$gcc" ] || gcc=$(command -v x86_64-w64-mingw32-gcc || true)
fi
if [ -z "$gcc" ] || [ ! -x "$gcc" ]; then
echo "missing tool: x86_64-w64-mingw32-gcc (set MINGW_GCC, or install mingw-w64)" >&2
exit 1
fi
# AGENTS.md: host tools must be ARM64, checked with file, lipo -archs and
# otool -L. The driver is a symbolic link into the toolchain; the compiler
# proper, the assembler and the linker it runs are checked as well.
native=
check_native_tool() {
tool=$1
case "$(file -bL "$tool")" in
*arm64*) ;;
*) echo "ARM64 tool required (file): $tool" >&2; exit 1 ;;
esac
case "$(lipo -archs "$tool")" in
*arm64*) ;;
*) echo "ARM64 tool required (lipo): $tool" >&2; exit 1 ;;
esac
for library in $(otool -L "$tool" | awk 'NR > 1 { print $1 }'); do
[ -f "$library" ] || continue
case "$(lipo -archs "$library")" in
*arm64*) ;;
*) echo "ARM64 library required by $tool: $library" >&2; exit 1 ;;
esac
native="$native $library: $(lipo -archs "$library")
"
done
native="$native$tool: $(file -bL "$tool")
"
}
if [ "$(uname -s)" = Darwin ]; then
# Check the driver before asking it about helpers: even -print-prog-name
# executes the binary and must never start an Intel-only compiler.
check_native_tool "$gcc"
for helper in cc1 as ld collect2; do
path=$("$gcc" -print-prog-name="$helper")
case "$path" in
/*) ;;
*) path=$(command -v "$path" || true) ;;
esac
if [ -z "$path" ] || [ ! -x "$path" ]; then
echo "missing compiler helper: $helper" >&2
exit 1
fi
check_native_tool "$path"
done
fi
mkdir -p "$out"
cd "$out"
{
"$gcc" --version | head -1
printf 'target: %s\n' "$("$gcc" -dumpmachine)"
} > toolchain.txt
printf '%s' "$native" > toolchain-native.txt
# name, optimization level, extra definition
build() {
"$gcc" "-$2" -Wall -Wextra -Werror ${3:+"-D$3"} -o "$1.exe" "$src"
}
for level in O0 O1 O2 Os; do
build "gate-a2-$level" "$level" ""
done
# Controls: a wrong expectation, exit() half way, abort() half way.
build gate-a2-break O1 GATE_BREAK
build gate-a2-exit O1 GATE_EXIT
build gate-a2-abort O1 GATE_ABORT
+157
View File
@@ -0,0 +1,157 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* Gate A2 (issue #419): a hosted C program. Original code written for Xenora.
*
* It is built with a real C runtime's startup code, which runs before main,
* and uses the standard C library the way an ordinary program does:
* command-line arguments, heap memory, sorting with a callback, formatted
* output, a file written and read back, a function registered with atexit,
* and a normal return from main.
*
* Every result is checked by the program itself. The exit status is 0 when
* every check passed and otherwise names the first one that failed, so a
* runtime that computes something wrongly cannot report success.
*
* It needs no floating point and no input.
*
* Control variants, selected at build time, each end in a different way so
* that the test can tell a real pass from a runtime that reports success for
* everything:
* GATE_BREAK expects a wrong total, so check 22 fails
* GATE_EXIT calls exit(42) half way, without returning from main
* GATE_ABORT calls abort() half way
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COUNT 48
static unsigned checks_passed;
static const char *report_name = "gate-a2-report.txt";
static void say_goodbye(void) {
/* Runs from exit, after main has returned. */
printf("atexit: %u checks passed\n", checks_passed);
}
static int by_value(const void *left, const void *right) {
unsigned a = *(const unsigned *)left, b = *(const unsigned *)right;
return (a > b) - (a < b);
}
/* A linear congruential generator, so the data does not depend on a library. */
static unsigned next_value(unsigned *state) {
*state = *state * 1103515245u + 12345u;
return (*state >> 8) & 0xffffu;
}
static unsigned long long checksum(const unsigned *values, size_t count) {
unsigned long long sum = 14695981039346656037ull; /* FNV-1a, 64-bit */
for (size_t i = 0; i < count; i++) {
for (int shift = 0; shift < 32; shift += 8) {
sum ^= (values[i] >> shift) & 0xffu;
sum *= 1099511628211ull;
}
}
return sum;
}
#define CHECK(code, condition) \
do { \
if (!(condition)) { \
fprintf(stderr, "gate a2: check %d failed\n", (code)); \
return (code); \
} \
checks_passed++; \
} while (0)
int main(int argc, char **argv) {
CHECK(10, atexit(say_goodbye) == 0);
/* Arguments: a program name, a seed and a label. */
printf("gate a2: %d arguments\n", argc);
for (int i = 0; i < argc; i++) printf(" argv[%d] = \"%s\"\n", i, argv[i]);
CHECK(11, argc == 3);
CHECK(12, argv[argc] == NULL);
char *end = NULL;
unsigned long seed = strtoul(argv[1], &end, 10);
CHECK(13, end != argv[1] && *end == '\0');
const char *label = argv[2];
CHECK(14, strlen(label) > 0 && strlen(label) < 32);
/* Heap memory, filled, sorted through a callback and verified. */
unsigned *values = malloc(COUNT * sizeof *values);
CHECK(20, values != NULL);
unsigned state = (unsigned)seed;
unsigned long long total = 0;
for (size_t i = 0; i < COUNT; i++) {
values[i] = next_value(&state);
total += values[i];
}
unsigned long long before = checksum(values, COUNT);
qsort(values, COUNT, sizeof *values, by_value);
unsigned long long sorted_total = 0;
for (size_t i = 0; i < COUNT; i++) {
if (i > 0) CHECK(21, values[i - 1] <= values[i]);
sorted_total += values[i];
}
#ifdef GATE_BREAK
CHECK(22, sorted_total == total + 1);
#else
CHECK(22, sorted_total == total);
#endif
unsigned long long after = checksum(values, COUNT);
printf("sorted %d values: min %u, max %u, total %llu\n",
COUNT, values[0], values[COUNT - 1], total);
printf("checksum before %016llx, after %016llx\n", before, after);
#ifdef GATE_EXIT
/* The registered function still runs, and nothing after this does. */
exit(42);
#endif
#ifdef GATE_ABORT
/* Nothing registered runs, and the status is abort's. */
abort();
#endif
/* A file written with formatted output. */
FILE *report = fopen(report_name, "w");
if (report == NULL) {
perror(report_name);
return 30;
}
checks_passed++;
CHECK(31, fprintf(report, "label %s\n", label) > 0);
CHECK(32, fprintf(report, "total %llu\n", total) > 0);
CHECK(33, fprintf(report, "range %u %u\n", values[0], values[COUNT - 1]) > 0);
CHECK(34, fputs("end\n", report) >= 0);
CHECK(35, fclose(report) == 0);
/* The same file read back line by line and compared. */
report = fopen(report_name, "r");
CHECK(40, report != NULL);
char line[96];
CHECK(41, fgets(line, sizeof line, report) != NULL);
CHECK(42, strncmp(line, "label ", 6) == 0);
CHECK(43, strlen(line) == 6 + strlen(label) + 1);
CHECK(44, strncmp(line + 6, label, strlen(label)) == 0 && line[strlen(line) - 1] == '\n');
CHECK(45, fgets(line, sizeof line, report) != NULL);
CHECK(46, strncmp(line, "total ", 6) == 0);
CHECK(47, strtoull(line + 6, &end, 10) == total && *end == '\n');
CHECK(48, fgets(line, sizeof line, report) != NULL);
CHECK(49, strncmp(line, "range ", 6) == 0);
CHECK(50, strtoul(line + 6, &end, 10) == values[0] && *end == ' ');
CHECK(51, strtoul(end, &end, 10) == values[COUNT - 1] && *end == '\n');
CHECK(52, fgets(line, sizeof line, report) != NULL && strcmp(line, "end\n") == 0);
CHECK(53, fgets(line, sizeof line, report) == NULL);
CHECK(54, fclose(report) == 0);
/* A file that does not exist is reported, not opened. */
CHECK(60, fopen("gate-a2-missing.txt", "r") == NULL);
free(values);
printf("report %s read back and verified\n", report_name);
return 0;
}
-99
View File
@@ -1,99 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import subprocess
import sys
import tempfile
import unittest
import pr_template_check as c
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
TEMPLATE = open(os.path.join(ROOT, ".github", "PULL_REQUEST_TEMPLATE.md"), encoding="utf-8").read()
GOOD = """## Summary
Adds X.
Closes #12
## Implementation and evidence
Touches crates/texture only.
## Verification
| Check | Result / evidence |
| --- | --- |
| Formatting and lint | cargo fmt --check: clean |
| Unit / integration tests | cargo test -p xenora-texture: 40 passed |
## Compatibility and limitations
None known.
## Checklist
- [x] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
- [x] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [x] My commits are signed off under the DCO.
## AI assistance
None.
"""
class Check(unittest.TestCase):
def test_good_body_passes(self):
self.assertEqual(c.check(GOOD), [])
def test_unfilled_template_fails_on_every_rule(self):
problems = c.check(TEMPLATE)
text = "\n".join(problems)
for want in ('"## Summary" is empty', '"## Implementation and evidence" is empty',
'"## Verification" is empty', '"## Compatibility and limitations" is empty',
'"## AI assistance" is empty', "No linked issue", "claimed-first", "DCO"):
self.assertIn(want, text)
def test_empty_and_freeform_bodies_fail(self):
self.assertTrue(c.check(""))
self.assertTrue(c.check("Fixes a bug. Closes #3"))
def test_missing_section_is_named(self):
body = GOOD.replace("## Compatibility and limitations\n\nNone known.\n", "")
self.assertEqual(c.check(body), ['Missing section "## Compatibility and limitations".'])
def test_unticked_boxes_fail(self):
body = GOOD.replace("- [x] I claimed", "- [ ] I claimed").replace("- [x] My commits", "- [ ] My commits")
problems = c.check(body)
self.assertEqual(len(problems), 2)
self.assertIn("claimed-first", problems[0])
self.assertIn("DCO", problems[1])
def test_issue_link_forms(self):
for link in ("Fixes #4", "resolves #4", "Closed #4", "No linked issue: requested by the maintainer"):
self.assertEqual(c.check(GOOD.replace("Closes #12", link)), [], link)
self.assertIn("No linked issue", "\n".join(c.check(GOOD.replace("Closes #12", "See issue 12"))))
def test_link_inside_comment_does_not_count(self):
self.assertTrue(c.check(GOOD.replace("Closes #12", "<!-- Closes #12 -->")))
def test_new_claim_checkbox_wording_passes(self):
body = GOOD.replace("I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.",
"I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.")
self.assertEqual(c.check(body), [])
def test_cli_exit_codes_from_event_file(self):
script = os.path.join(ROOT, "scripts", "pr_template_check.py")
with tempfile.TemporaryDirectory() as d:
for body, want in ((GOOD, 0), (TEMPLATE, 1), (None, 1)):
path = os.path.join(d, "event.json")
with open(path, "w", encoding="utf-8") as fh:
json.dump({"pull_request": {"body": body}}, fh)
run = subprocess.run([sys.executable, script, "--event", path], capture_output=True, text=True)
self.assertEqual(run.returncode, want, run.stdout)
if __name__ == "__main__":
unittest.main()