Compare commits

..
Author SHA1 Message Date
atharvranjan ded1371b99 Correct the GPU-executed test counts in the victory-shader record using libtest JSON output 2026-11-25 15:36:33 -06:00
atharvranjan 6cebcc559e Add the shader GPU test runner script and the victory-shader integration record 2026-11-25 15:22:19 -06:00
atharvranjan 790061e7c0 Vendor victory-shader (GFX10 to DXIL recompiler) from skakwy/victory-mac and add translate_native with BetterXen fixture tests 2026-11-25 15:22:19 -06:00
atharvranjan 8e5856bbcf Detect stalled runs, wait for memory to settle after a stop, and stop bottles through WINEPREFIX (#385) 2026-11-25 15:08:42 -06:00
atharvranjan 566272082a Record the first CrossOver 26.3 execution baseline, backend comparison and licence entry 2026-11-25 14:55:51 -06:00
atharvranjan 64ba56079f Add the D3D11 frame-loop workload, negative controls and reproducible workload builds 2026-11-25 14:55:51 -06:00
atharvranjan e266670e87 Add betterxen-hybrid run and bench: supervised CrossOver launches with structured records and backend comparison 2026-11-25 14:55:50 -06:00
atharvranjan 54b06fea3e Record the victory-mac component review, registry, reuse matrix and notices 2026-11-25 14:41:24 -06:00
atharvranjan 8eb25fb9fe Add original Windows workloads and a checksum-pinned llvm-mingw build script 2026-11-25 14:41:24 -06:00
atharvranjan 40ffea2789 Add betterxen-hybrid guard: memory-pressure supervisor adapted from skakwy's victory-mac memory guard 2026-11-25 14:41:24 -06:00
atharvranjan 80eacf9ac2 Add the betterxen-hybrid crate: host receipt, CrossOver discovery, toolchain probe and frame statistics 2026-11-25 14:33:22 -06:00
atharvranjan d9816e4cb5 Record the upstream integration audit and extend the registry and reuse matrix 2026-11-25 14:33:22 -06:00
atharvranjan 39b628d60d Fix a link in the archived README milestones 2026-11-25 14:23:04 -06:00
atharvranjan 1d70633958 Keep the local Agent Spawning section out of the shared engineering rules
That section was an uncommitted local addition and is not part of main.
2026-11-25 14:22:57 -06:00
atharvranjan a9f55b51f7 State that the native-first-final tag marks the last main commit before the transition 2026-11-25 14:22:38 -06:00
atharvranjan 722388a46d Record the planning transition in the changelog
CrossOver-based hybrid direction, rewritten engineering rules, native work paused and archived, upstream registry and research records.
2026-11-25 14:22:17 -06:00
atharvranjan e7ff293eba Record primary-source verification and finalize the Phase 1 backlog
Add the hybrid research record and a primary-source re-check (CodeWeavers, Apple, DXMT, Wine, Rust toolchain), rename the roadmap's parked section to Parked ideas, and add the matching changelog and docs index entries. Unrelated local work stays uncommitted.
2026-11-25 14:22:09 -06:00
atharvranjan dfaaa07df4 Update README, CONTRIBUTING, docs index, changelog and template for progressive planning
Only this task's hunks are committed; unrelated local edits remain uncommitted.
2026-11-25 14:21:53 -06:00
atharvranjan 962b83c731 Extend the upstream registry with unreviewed candidates
llvm-mingw, Sikarugir, macOS Wine builds, Mythic and Playdock, metadata only.
2026-11-25 14:21:47 -06:00
atharvranjan 7fff77c801 Simplify the roadmap to one active phase and archive the native issue backlog
Five provisional phases with only Phase 1 active, parked ideas, Phase 1 completion criteria, a simple project board guide, the retired H0 to H7 breakdown, and an index of the closed native issues with preserved findings and contributor attribution.
2026-11-25 14:21:47 -06:00
atharvranjan c3684a1ae8 Add progressive planning rules to the engineering rules
Only the current phase has a milestone and open issues; future ideas are parked in the roadmap; issues carry evidence, reuse assessment and validation; no native-only issues.
2026-11-25 14:21:47 -06:00
atharvranjan d561595599 Replace issue templates and add a pull request template
Hybrid task, bug, research, performance, validation and documentation forms with problem, context, scope, dependencies, acceptance, validation and licensing sections. Fix invalid YAML in the agent-task template.
2026-11-25 14:21:47 -06:00
atharvranjan 8cab0b1de8 Describe the hybrid direction in README, CONTRIBUTING, docs index and changelog
Only this task's hunks are committed; unrelated local edits to CHANGELOG.md and docs/README.md remain uncommitted.
2026-11-25 14:21:40 -06:00
atharvranjan d2367dca30 Add the upstream research registry and component reuse matrix
Public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch with license, pin and reuse decisions. VIctory-family projects are excluded from reuse on provenance grounds.
2026-11-25 14:20:55 -06:00
atharvranjan 60ad6c779e Add the CrossOver-based hybrid roadmap and archive the native-first plan
Add docs/roadmap.md (phases H0 to H7, critical path), ADR 0005 (accepted direction; proposed architecture and unverified assumptions kept separate), the deferred native roadmap and the project board setup guide. Archive the native-first plan and the seven retired milestones. Mark the PortWatch review as superseded in part.
2026-11-25 14:20:55 -06:00
atharvranjan ffc7056d26 Rewrite engineering rules for the CrossOver-based hybrid direction
Replace the native-first prohibition on Wine, CrossOver, Rosetta and MoltenVK with dependency, reuse, licensing and provenance rules. Keep the honesty, independent-verification, clean-room, claiming, changelog and subagent rules. CLAUDE.md remains a symlink to AGENTS.md. Resolves #345 once reviewed.
2026-11-25 14:20:55 -06:00
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 f9d5838091 Integrate PR #277 with the combined typed runtime services
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:59:43 -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 4173a781af Integrate PR #273 and regenerate the combined runtime registry
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:48 -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 2f68ee9d4a Integrate PR #276 with explicit unsupported-service behavior
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:57:08 -06:00
atharvranjan e7a2159c82 Carry benchmark harness lint correction into the integration candidate
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:54:03 -06:00
atharvranjan 98e9420b7f Integrate PR #279 and retain all newly supported known answers
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:51:45 -06:00
atharvranjan 238b5a001b Keep benchmark fixture tests lint-clean without a benchmark harness
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:51:38 -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 99ed89787e Integrate PR #275 preserving FNINIT and existing shift expectations
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:49:30 -06:00
atharvranjan 522560d0a2 Integrate PR #271 while preserving BetterXen terminology
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:48:34 -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
atharvranjan d28d539a90 Integrate PR #274 instruction-length fault handling
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:54 -06:00
atharvranjan 8c4b2344df Integrate PR #272 benchmark comparison mode
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:50 -06:00
atharvranjan a75d018435 Integrate PR #264 and run identification fixture in workspace tests
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:15 -06:00
atharvranjan 4652eb08cb Integrate PR #267 with current native runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:45:36 -06:00
atharvranjan d1bcd0249d Integrate PR #268 and clarify Win64 shadow-space expectations
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:44:49 -06:00
atharvranjan 097bb0b5b8 Merge commit '19f63a0' into integration/pr-284
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:43:15 -06:00
atharvranjan 2d77b35e56 Merge remote-tracking branch 'origin/main' into integration/pr-284
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 21:43:15 -06:00
devil8blade f0c61c7a91 loader: copy mid-size TLS templates into the zeroed block (#111)
Templates from 64 KiB up to 1 MiB were staged in a second buffer and
copied again into the thread block. Proving those bytes readable, then
copying them into the block that is already zeroed, avoids that buffer
and still maps nothing when the template cannot be read. Smaller
templates and templates of 1 MiB or more keep the single staged read,
which measured as fast or faster.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-24 21:01:31 -05:00
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 42cdb7d122 Merge upstream main into task/382-crt-startup
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 e57386950b 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 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 d5fa319f56 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:00 +01:00
zachdoxsee e5d83e87ac 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:00 +01:00
zachdoxsee 985d3b9e78 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:00 +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 22425287e2 Merge upstream main into task/392-program-arguments
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +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 f30e4af4eb Merge upstream main into task/388-must-exist-stubs
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 501117c4d8 Merge upstream main into task/378-fninit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 3d796f51cf Merge upstream main into task/382-crt-startup
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 aae04a2956 Merge upstream main into task/392-program-arguments
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee 721073169c Merge upstream main into task/388-must-exist-stubs
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee 26148f49f6 Merge upstream main into task/378-fninit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee e81382de37 Merge upstream main into task/382-crt-startup
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +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
Bartosz Szczepański 149869a053 loader: run LOOP, LOOPE, LOOPNE and JRCXZ (#396)
The four rel8 forms E0 to E3 are declared in the instruction registry and
run through the shared semantics in both engines (Intel SDM Vol. 2A,
LOOP/LOOPcc and Jcc). The count is RCX: LOOP decrements it without
changing a flag and branches while the result is not zero, LOOPE also
needs ZF set and LOOPNE ZF clear, and JRCXZ branches on a zero RCX and
changes nothing. Each ends a translated block. The address-size prefix
stays rejected, so JECXZ and the ECX-counted forms are still refused.

The three known answers recorded as refused by #155 are verified, with
eleven more cases. 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, and JRCXZ against every single-bit RCX value.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-25 00:12: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
zachdoxsee 32251af4c8 loader: add program arguments for a hosted C program (#392)
A program built with the mingw-w64 runtime gets argc, argv and envp for
main from __p___argc, __p___argv, __p__environ, _configure_narrow_argv
and _initialize_narrow_environment. None resolved, so the loader refused
the program before its entry point, and a host could not say what the
program's arguments are.

The five services are added to the typed registry, and
ServicesState::set_program_arguments lets a host supply argv. The
environment table is empty.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:40:27 +01:00
Bartosz Szczepański 1c6bd25723 loader: run LAHF and SAHF and report them in CPUID (#387)
LAHF (9F) and SAHF (9E) are declared in the instruction registry and run
through the shared semantics in both engines (Intel SDM Vol. 2A LAHF,
Vol. 2B SAHF): LAHF writes AH = SF:ZF:0:AF:0:PF:1:CF and keeps the rest of
RAX, SAHF loads SF, ZF, AF, PF and CF from AH and leaves OF unchanged.
With both implemented, guest CPUID reports leaf 8000_0001h ECX bit 0.

The four known answers recorded as refused by #155 are verified, with
twelve more cases. Both instructions join the clang-assembled integer
fixtures and the independent bit-level reference, and cpu_features.rs
moves LAHF/SAHF from the refused witnesses to the reported features.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 23:32:17 +01:00
zachdoxsee 007ad360e9 loader: add VirtualProtect, VirtualQuery and __C_specific_handler as stubs (#388)
A program built with the mingw-w64 runtime imports all three and does not
call them on a normal run. Without them the loader refused the program
before its entry point.

They are declared stub in the typed registry. A call stops the guest with
the runtime-limit fault and writes nothing, so a program that needs one
stops there and cannot run on with a made-up result.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:30:09 +01:00
Bartosz Szczepański 0d6cef6c4e loader: raise #GP for instructions longer than 15 bytes (#384)
The shared decoder already stopped before fetching a 16th byte, but it
reported the instruction as unsupported, so both engines exited with an
illegal instruction. It now returns DecodeError::TooLong, which maps to
ExitReason::GeneralProtection (Intel SDM Vol. 3A, 7.15). The DBT retries a
block that fails this way one instruction at a time, as it already does for
illegal instructions and fetch faults, so earlier instructions in the block
complete and the fault reports the overlong instruction's RIP.

The known answer recorded as a defect by #155 is enabled, with three more
cases, and two page-end tests check that no 16th byte is fetched.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 23:16:49 +01:00
zachdoxsee 64a0cb1596 loader: add nine C runtime startup services a hosted C program imports (#382)
A program built with the mingw-w64 runtime imports _set_app_type,
_set_new_mode, _configthreadlocale, __setusermatherr,
_set_invalid_parameter_handler, __p__fmode, __p__commode, signal and
SetUnhandledExceptionFilter, and memcpy through
api-ms-win-crt-private-l1-1-0.dll. None resolved, so the loader refused
the program before its entry point.

Each service records what it is given and returns what its public
documentation says. Nothing acts on a recorded value yet, so all nine
are declared partial in the typed registry.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:14:10 +01:00
Bartosz Szczepański 53e5e38a4e bench: compare two dbt_bench JSON results (#114)
With XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json> set,
dbt_bench reads two documents written through XENORA_DBT_BENCH_JSON and
compares them instead of running. For the interpreter and cold and warm
DBT it prints both medians, the change, and whether the change exceeds
the larger recorded IQR, and it lists changed cold DBT counters.

It refuses, with exit status 1 and the differing field named, to compare
runs whose CPU, OS or architecture differ or are unknown, or whose
workload, sample or warmup counts, debug assertions or build label
differ. The new optional XENORA_DBT_BENCH_BUILD_LABEL records build
settings the benchmark cannot observe, such as LTO; version 1 documents
without it count as unlabelled.

The documents are read by a small RFC 8259 reader in the bench file, so
no dependency is added. Unit tests cover the reader, reading back an
exported document, the report lines, and every refusal rule.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 23:08:04 +01:00
zachdoxsee 47a819e05b loader: add FNINIT and the x87 control, status and tag words (#378)
The decoder refused FNINIT (DB E3), which the mingw-w64 C runtime runs
once before main. Guest state gains the x87 control, status and tag
words, and FNINIT sets them to the Intel SDM values 037F, 0 and FFFF.
Both engines run the shared semantics.

The registry gains a form key, rm, that pins a register-only form to one
ModRM byte: the other bytes of DB /4 are different instructions. No other
x87 instruction is added and CPUID still reports no FPU.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:01:33 +01:00
Arthur Lacoste af1b84ad75 loader: fix needless_range_loop in Win64 ABI tests (#201)
Address review feedback from zachdoxsee on PR #369: replace index-only XMM range loops with iterator-based loops so strict clippy passes on Rust 1.100.

Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 22:14:29 +01:00
Arthur Lacoste cf438e25aa Merge remote-tracking branch 'origin/main' into runtime/win64-service-abi-201
# Conflicts:
#	CHANGELOG.md
2026-11-24 22:13:14 +01:00
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
Arthur Lacoste 7246ab5ea6 loader: add Win64 service ABI preservation tests (#201)
Add dispatch and DBT-backed runtime service tests that verify Win64 callee entry alignment, caller-owned shadow space, return state, and preservation of nonvolatile GPRs/XMM registers across registered service calls.

AI-Assisted: Codex (GPT-5) helped draft the tests; I reviewed the diff and ran fmt/clippy(loader)/loader tests locally.
Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 20:57:41 +01:00
Swastickc 729e1b4cb1 loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
Flat DrawInstanced ignored InstanceCount, StartInstanceLocation and
StartVertexLocation, so a zero-instance draw still drew and a changed
start vertex drew the first triangle. Zero instances or fewer than three
vertices now draw nothing; other unsupported parameters fail with
GraphicsError::Unsupported. Vertex reads use the range-checked
read_resource, so a view past its buffer or an overflowing guest address
fails with IndexOutOfRange.

Add tests/repeated_frames.rs: repeated reset, record, close and execute
frames with hand-derived pixels on the software reference backend.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-25 00:34:19 +05:30
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
ates 1dcf722323 benchmarks: measure gfx1030 metadata identification
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 20:36:15 +03:00
183 changed files with 65264 additions and 1227 deletions

No files matched your search

+3 -2
View File
@@ -7,8 +7,9 @@ body:
id: area
attributes:
label: Area
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
description: "hybrid: CrossOver integration, configuration, diagnostics, benchmarks (active). The areas below are preserved native research unless hybrid work requires them. cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
options:
- hybrid
- cpu
- gpu
- runtime
@@ -43,7 +44,7 @@ body:
id: files
attributes:
label: Files
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
description: 'Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.'
render: text
validations:
required: true
+30 -15
View File
@@ -1,42 +1,57 @@
name: Bug report
description: Report a reproducible defect in Xenora or XenoMetal.
description: A reproducible defect.
title: "bug: "
labels: [bug]
body:
- type: markdown
attributes:
value: |
Use synthetic or authorized inputs only. For vulnerabilities, follow SECURITY.md. Remove personal paths, credentials and private data from logs.
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. For vulnerabilities follow SECURITY.md.'
- type: textarea
id: description
attributes:
label: Description
description: What went wrong? Identify the affected subsystem and expected behavior.
description: 'What went wrong and what you expected.'
validations:
required: true
- type: textarea
id: steps
attributes:
label: Reproduction steps
description: Include exact commands and a minimal, legally distributable input if applicable.
description: 'Exact commands and a minimal, legally distributable input.'
validations:
required: true
- type: textarea
id: environment
attributes:
label: Environment
description: Commit, macOS, Apple GPU, RAM, Rust, Xcode and relevant tool versions. Include sanitized doctor output if available.
description: 'Commit, macOS, chip, memory, CrossOver and Rosetta 2 versions, graphics backend. Remove personal paths and credentials.'
validations:
required: true
- type: textarea
id: output
id: scope
attributes:
label: Actual output and diagnostics
description: Include expected versus actual results, validation-layer messages and relevant logs.
- type: checkboxes
id: confirmation
label: Scope and dependencies
description: 'Affected area; related issues.'
validations:
required: false
- type: textarea
id: acceptance
attributes:
label: Confirmation
options:
- label: I searched for existing reports and have not included sensitive or unauthorized material.
required: true
label: Acceptance criteria
description: 'When is this fixed?'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How to confirm the fix independently.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: 'Only if third-party code or a dependency is involved.'
validations:
required: false
+50
View File
@@ -0,0 +1,50 @@
name: Documentation
description: Fix, add or restructure documentation.
title: "docs: "
labels: [documentation]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is unclear, wrong or missing.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Pages and sources involved.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'Files to change; update docs/README.md if pages are added or moved.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'None if none.'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Claims are scoped to their evidence; links work.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'scripts/audit/docs_hygiene.py and claims audit pass.'
validations:
required: true
-31
View File
@@ -1,31 +0,0 @@
name: Feature proposal
description: Propose a compiler, graphics, tooling or other project enhancement.
title: "feat: "
labels: [enhancement]
body:
- type: textarea
id: problem
attributes:
label: Problem or gap
description: Which limitation does this feature address?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed approach
description: Explain the intended behavior and affected components. Link relevant public specifications when available.
validations:
required: true
- type: textarea
id: criteria
attributes:
label: Acceptance criteria
description: What observable results and tests would demonstrate completion?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives and trade-offs
description: Include limitations, dependency costs or impacts on native ARM64 and Metal if relevant.
-31
View File
@@ -1,31 +0,0 @@
name: Hardware verification report
description: Submit real hardware test results for Xenora.
title: "hardware: "
labels: [needs-verification]
body:
- type: textarea
id: environment
attributes:
label: Test environment
description: Commit, Apple chip/GPU, RAM, macOS, Xcode/Metal version, Rust version, validation settings. Do not include serial numbers or registry IDs.
validations:
required: true
- type: textarea
id: commands
attributes:
label: Commands and inputs
description: Include exact commands and synthetic or authorized fixture identifiers.
validations:
required: true
- type: textarea
id: results
attributes:
label: Results
description: Report actual output, pass/fail/skip counts, and limitations. Compilation alone does not prove execution.
validations:
required: true
- type: textarea
id: performance
attributes:
label: Performance data (optional)
description: Include repetitions, warm-up, timing method, validation state and variability if reporting measurements.
+57
View File
@@ -0,0 +1,57 @@
name: Hybrid engineering task
description: Integration, configuration, diagnostics or tooling around CrossOver.
title: "task: "
labels: [track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: "Blocking issues or decisions; write 'none' if none."
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Observable, checkable results.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+57
View File
@@ -0,0 +1,57 @@
name: Performance investigation
description: Measure or improve performance with evidence.
title: "perf: "
labels: [performance,track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. Do not promise gains before measuring.'
- type: textarea
id: problem
attributes:
label: Problem and metric
description: 'Which metric (average FPS, 1% low, frame-time percentiles, CPU or GPU use, memory, startup, shader compile latency) and why.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Workload, hardware (reference: M4, 24 GB), software versions, settings.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'Measurement only, or change as well.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'Measurement protocol (#353) and baseline (#355).'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Measured before-and-after under equivalent conditions, with variance.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'Correctness and rendering equivalence verified before the result counts.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+37 -22
View File
@@ -1,42 +1,57 @@
name: Technical research
description: Record an ISA, Metal or publicly documented graphics research finding.
name: Upstream research or dependency evaluation
description: Assess a project, component or license from public sources.
title: "research: "
labels: [research]
labels: [research,track: hybrid]
body:
- type: markdown
attributes:
value: Use only public, authorized sources. Do not link to leaked SDKs, private documentation or unauthorized game content.
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: question
id: problem
attributes:
label: Research question or finding
label: Question
description: 'The decision this research informs.'
validations:
required: true
- type: textarea
id: sources
id: context
attributes:
label: Sources and applicability
description: URLs, specification sections or revision, exact architecture and license/provenance if relevant.
label: Technical context
description: 'What is already known; link docs/research/upstream-registry.md entries.'
validations:
required: true
- type: dropdown
id: evidence
- type: textarea
id: scope
attributes:
label: Evidence class (highest applicable)
options:
- A - Measured on named hardware
- B - Normative source for exact target
- C - Normative source for related target
- D - Non-normative official material
- E - Independent software behavior
- F - Uncorroborated community claim
- U - Unknown or assumption
label: Scope
description: 'Which versions or components; desk research or execution.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'Other issues or decisions; execution may need a maintainer-approved environment.'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Each claim cites vendor or upstream documentation, or a recorded observation of a stated version; unknowns stay marked unknown.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation, limitations and proposed next steps
description: Distinguish Apple or desktop RDNA observations from Xbox behavior.
label: Validation requirements
description: 'Independent re-derivation and evidence class (A to U).'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+57
View File
@@ -0,0 +1,57 @@
name: Testing and validation
description: Add or run a validation for a workload or behaviour.
title: "validate: "
labels: [needs-verification,track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: "Blocking issues or decisions; write 'none' if none."
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Observable, checkable results.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
-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. -->
+29
View File
@@ -0,0 +1,29 @@
## Related issue
Closes #
## Summary
## Technical changes
## Tests performed
Commands, versions, pass/fail/skip counts and hardware. A skipped test is not a pass.
## Performance impact
Measured before and after under equivalent conditions, or "none expected" with reason.
## Compatibility impact
Workloads, macOS or CrossOver versions and hardware affected. Do not claim support that was not tested.
## Known limitations
## Third-party code attribution
Source repository, exact commit, license, modifications. "None" if none.
## Dependency and licensing considerations
New or changed dependencies, license compatibility with GPL-3.0-or-later, redistribution limits (proprietary components are never bundled). DCO: commits are signed off.
+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/
+38 -18
View File
@@ -1,40 +1,60 @@
# BetterXen engineering rules
### Native Apple Silicon
These rules apply to every contributor and coding agent. They were rewritten on the `planning/hybrid-first-transition` branch when BetterXen moved from native-first to CrossOver-based hybrid development. `CLAUDE.md` is a symlink to this file. The decision is recorded in `docs/adr/0005-crossover-hybrid-direction.md`; the plan is `docs/roadmap.md`.
Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dependencies, Wine, CrossOver, Windows compatibility layers, OpenGL fallback rendering, or unnecessary graphics abstraction layers.
### Direction
- SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime.
- All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L.
- Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation.
- The guest architecture being decoded may be x86-64, but BetterXen itself runs natively on ARM64.
- BetterXen is hybrid-first Apple Silicon compatibility research. **CrossOver is the primary compatibility foundation and hybrid is the only active development direction.** CrossOver is an externally installed dependency unless its license explicitly permits another distribution model.
- BetterXen's own work is the layer around it: integration, configuration, environment management, diagnostics, reproducible testing, benchmarking and measured optimization. Reuse established infrastructure before writing an independent replacement; write one only for a demonstrated limitation.
- The independent native implementation (x86-64 decoder, ARM64 translator, runtime, gfx1030 shader compiler, Metal backend) is **preserved and paused**. Do not delete it, expand its roadmap, create speculative native issues or assign contributors to it by default. Native work is allowed only when hybrid development directly requires it, or after an explicit maintainer decision to resume (`docs/research/native-roadmap.md`). Keep its tests passing.
- This is the intended architecture, not a verified Xbox compatibility stack. Do not assume CrossOver, Rosetta 2 or D3DMetal provide Xbox runtime compatibility; verify the actual capabilities and integration boundaries of the installed versions.
### Planning
- Planning is progressive. Only the current phase has a milestone and open issues; the roadmap outlines later phases provisionally and `Parked ideas` holds future items. Do not create speculative issues, trackers or milestones for distant phases; promote an idea when its prerequisites are met.
- Every new issue states a specific problem, the evidence it is needed, a deliverable, upstream references, a reuse assessment, dependencies, acceptance criteria and a validation method. Do not create administrative issues to manage planning.
- Do not open native-only issues. If hybrid work needs a native component, file a focused hybrid issue.
### Dependencies and reuse
- Wine-based compatibility infrastructure, CrossOver, Rosetta 2 where supported and technically appropriate, and D3DMetal (subject to its license terms) are permitted. DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX and similar projects may be evaluated and used where appropriate. Legitimate external dependencies and open-source implementations are encouraged.
- Before integrating or copying anything: verify the exact license of the component (the file for copied source, not just the repository), check compatibility with GPL-3.0-or-later and with every other selected component, preserve copyright notices, record the source repository and exact commit or version, document modifications, and add the entry to `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved. Never remove upstream notices.
- Do not bundle, modify or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Do not assume a proprietary component can be incorporated into GPL-licensed source. Distinguish open-source parts from proprietary parts in every assessment.
- Do not bypass licensing or activation requirements of any dependency.
- Provenance first: exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds, including VIctory, its forks and similar efforts, are discovery references at documentation level; adopt nothing from them without a per-file provenance and license review recorded in the registry. Game-specific, asset-specific and decryption-related code is never adopted.
### Native Apple Silicon host
- BetterXen's own host executables, libraries and tools must support ARM64 natively; verify with file, lipo -archs and otool -L. Do not add x86-64 host executables that BetterXen itself builds or ships.
- Rosetta 2 may be used where Apple supports it and CrossOver or another selected component relies on it for x86-64 guest code. Record versions and its support status; do not depend on it for BetterXen's own code.
- Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities.
- Use aarch64-apple-darwin as the Rust target.
- Use aarch64-apple-darwin as the Rust target. Metal is the host graphics API. Do not add graphics abstraction layers beyond what a selected component or a measured need justifies.
- SPIR-V remains permitted as a compiler intermediate representation.
### Honesty and evidence
- Never report a test as passed unless it ran and passed. Never count a skipped test as GPU verification.
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities or implementation status.
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities, interface details, product capabilities or implementation status. Never promise a performance improvement before measuring it.
- Never claim a clean build unless the commands actually succeeded.
- Never present planned features as working. State clearly that game execution is not supported unless demonstrated.
- Never replace GPU tests with mocks and then claim GPU support.
- Unknown information is classified as unknown and becomes a documented research task.
- Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one.
- Unknown information is classified as unknown and becomes a documented research task. Facts about CrossOver, Rosetta 2, D3DMetal and other upstreams must cite vendor or upstream documentation, or a recorded observation of a stated version.
- Every hardware claim carries an evidence class (see docs/claims.toml). Never present a lower-class claim as if it were a higher-class one.
- Never claim "verified on Xbox hardware". BetterXen has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
- Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score.
- A phase is complete only with the evidence its exit conditions name. Do not derive progress from commits, lines of code, closed issues or isolated passing fixtures.
### Independence of verification
- The agent that writes a component does not certify it. The two independent reviewers (section 5) re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
- The agent that writes a component does not certify it. Independent reviewers re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
- The same faulty code must never produce both the expected and the actual values in a test.
### Legal and clean-room
- Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions.
- Use only publicly accessible documentation, publicly licensed software and authorized materials. All validation uses independently authored or authorized workloads. Never obtain or use leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections. Do not attempt to bypass documentation access restrictions.
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
- Include a plain statement in docs/legal.md: 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.
- docs/legal.md states: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. This is not legal advice; contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
- Keep BetterXen's own implementation original where it is original. Never copy, port, translate or adapt source from emulator projects built for leaked or unauthorized material (for example PE-Vulkan, KyTx, AnyPS5 and similar).
- 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.
@@ -43,7 +63,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
No AI slop (section 29).
Read docs/interfaces.md and docs/progress.md before implementation.
Read docs/roadmap.md, docs/interfaces.md and docs/progress.md before implementation.
## Claiming work before you start
@@ -84,7 +104,7 @@ A coding agent claims in the name of the person it works for and follows the sam
- Lint: `cargo clippy --workspace --all-targets -- -D warnings`
- Test: `cargo test --workspace`
- Verify the synthetic fixtures: `scripts/assemble-fixture.sh --check`
- Run native GPU correctness: `scripts/test-gpu.sh`
- Run native GPU correctness (preserved native research): `scripts/test-gpu.sh`
- Run the three RDNA-to-Metal fixtures: `scripts/demo.sh`
- Run independent CPU validation: `cargo test --locked -p xenora-semantic-review`
- Run the correctness-gated benchmark suite: `scripts/benchmark.sh` (idle machine, release, validation off)
@@ -101,4 +121,4 @@ Preserve the configured Git author and committer identity.
## Ownership
Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
These are responsibility areas, not personal assignments; do not assign people without their agreement. Hybrid integration owns the CrossOver assessment, integration boundary, configuration, diagnostics and benchmarks. Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
+80
View File
@@ -9,7 +9,35 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Added
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and run them on the Apple GPU through D3D12 under CrossOver 26.3 (D3DMetal), plus `scripts/hybrid/run-shader-gpu-tests.sh`, which runs them through `betterxen-hybrid run`. Local results on the M4, not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words (add, float-exact, bitwise-branch, or, shifts, ashr) matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed (wave-wide reductions), 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
- Added `--stall-timeout` and a memory-settle wait to `betterxen-hybrid run`/`bench` (#385): a run that prints nothing for the given time is stopped and classified `stalled`, and after any stop the supervisor waits (up to `--settle-bound`, default 60 s) until free memory is back above the start threshold and records whether it recovered. Based on supervision lessons from skakwy's victory-mac (reimplemented, not copied). Also fixes a defect found by the first real stall run: stopping a bottle used `CX_BOTTLE`, which does not select the bottle, so a stopped Windows process kept running; it now sets `WINEPREFIX`. Verified with 4 new unit tests (stub launcher) and a real CrossOver 26.3 run on the M4: a silent workload was stopped as `stalled` after 4.7 s of a 120 s timeout, nothing was left running, and the next run passed. The low-memory recovery path is only tested with an injected memory reader. Not independently reviewed.
- Added `betterxen-hybrid run` and `bench`: launch a Windows program through an installed CrossOver (`bin/wine --bottle`, an interface CodeWeavers does not document for macOS), with timeout, the memory guard, failure classification (passed, failed exit, timed out, stopped on low memory, cannot execute, no graphics device), sampled CrossOver process memory and CPU, thermal notes, recognised host-noise diagnostics and frame statistics, and write a JSON record; `bench` repeats a workload across graphics backends. Locally verified with 24 unit tests (stub launcher) and with real runs on CrossOver 26.3 on the Apple M4.
- Executed the original Windows workloads under CrossOver 26.3 for the first time (`docs/research/crossover-baseline-2026-11-25.md`). x86-64 C, Rust, Direct3D 11 clear and triangle/frame-loop programs passed; all four ARM64 builds were rejected by CrossOver (`cannot execute`). Five-repeat, 2000-frame comparison of default, D3DMetal, DXMT, DXVK and wined3d on a trivial offscreen workload: D3DMetal's median submit-and-wait was about 1.8 times the others; this is not rendering performance. Observed on one machine, not independently reproduced, using an undocumented backend variable.
- Added `workloads/d3d11-frameloop` (indexed triangle, shaders, event-query frame loop) and negative controls for both Direct3D programs; made workload builds byte-reproducible on one machine with `--no-insert-timestamp`.
- Added `betterxen-hybrid guard`, a memory-pressure supervisor: it refuses to start a command when system-wide free memory is below a threshold and stops it (SIGTERM, then SIGKILL) when memory drops below a limit, reporting why. It is adapted from the memory guard in contributor skakwy's `victory-mac` `mac/run-victory.sh` (GPL-3.0, used with his permission) and reimplemented in Rust. Locally verified with 6 unit tests and three end-to-end runs (refuse, pass-through, stop) on macOS 27.0; the `memory_pressure -Q` output format is not a documented interface; not independently reviewed.
- Added original Windows workloads and a build script (#364, #365): a C and a Rust self-checking console program and a Direct3D 11 clear-and-readback program (`workloads/`), built for x86-64 and ARM64 with a checksum-verified llvm-mingw 20261117 by `scripts/hybrid/build-windows-workloads.sh` (`docs/research/hybrid-toolchain.md`). All six outputs were confirmed as the right PE architecture with `file`. **The x86-64 outputs were later run under CrossOver (see below).**
- Extended `docs/research/upstream-integration-audit.md` with a component-level review of skakwy's `victory-mac`: the reported ~1 FPS is, in his own notes, 1 to 1.9 s per frame of a leaked console-game dump measured by his runtime, so it is not reproducible or adoptable here. His Windows cross-link wrapper failed with Homebrew `llvm@17` and was not integrated; his Metal swizzle and D3DMetal-internals fixes are rejected; game-specific loader patches are rejected.
- Added the `betterxen-hybrid` crate (`crates/hybrid`, no third-party dependencies, native arm64) with `host`, `crossover`, `toolchain`, `frames` and `receipt` commands that print JSON: a host receipt (macOS, chip, memory, core split, whether an x86_64 binary runs under Rosetta, GPU and Metal family), CrossOver discovery limited to `Info.plist` metadata, `lipo -archs` and the documented `BottleDir` and `ManagedBottleDirs` preferences, a Windows cross-compiler probe, and frame-time statistics (nearest-rank percentiles, 1 % and 0.1 % lows, stutter count). Locally verified: 13 unit tests, clippy with warnings denied, and a run on the Apple M4 reference machine, where CrossOver is **not installed** (the report says so) and only Homebrew mingw-w64 x86_64 and i686 compilers were found. CrossOver discovery has been tested on a synthetic bundle only and has never inspected a real CrossOver; nothing launches a program or measures a game. Not independently reviewed (#353, #350, #364, #145).
- Added `docs/research/upstream-integration-audit.md` and registry and reuse-matrix rows for skakwy/victory-mac, MacBox, ScarlettMac, ossover, Whisky and rum (source read through the GitHub API, nothing executed, no code copied). Findings: MacBox and ScarlettMac are GPL-2.0 and game-specific, so they are rejected; the Game Porting Toolkit licence text (a third-party copy of version 4.0) limits use to developing, testing or evaluating games and distribution to non-commercial; contributor-reported frame results (about 1 FPS, then two rendered frames) are recorded as unverified.
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
- 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 the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
- Replaced the issue templates with hybrid task, bug, research, performance, validation and documentation forms and added a pull request template. Fixed invalid YAML in the agent-task template. README, CONTRIBUTING and the docs index now describe the hybrid direction.
- 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.
- Repaired destination issue links in 20 migrated PR descriptions while retaining the imported text, attribution and contributor certifications. Template and review requirements remain in place.
@@ -19,6 +47,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`.
@@ -32,17 +61,52 @@ 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.
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 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).
@@ -85,6 +149,7 @@ remains unsupported.
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
- Added MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
- Added FNINIT (`DB E3`), the one instruction a C program built with the mingw-w64 runtime needs that the decoder refused (#378, part of Gate A2). Guest state gains the x87 control, status and tag words in `CpuState::x87`, and FNINIT sets them to the Intel SDM values `037F`, `0` and `FFFF`. Both engines run the shared semantics; nothing is lowered to ARM64 and the host's floating-point state is never touched. The registry gains a form key, `rm`, that pins a register-only form to one ModRM byte, because the other bytes of `DB /4` are different instructions. No other x87 instruction exists: FNSTCW, FLDCW, FNCLEX, FWAIT and all x87 arithmetic stay rejected, there are no x87 data registers, nothing can read the three words back, and CPUID still reports no FPU. Nine SDM-derived cases in `cpu_known_answers.rs`, whose harness now starts every case with the three words away from their reset values and requires every other instruction to keep them, one assembled fixture checked by the text-only reference in `x86_integer.rs`, and a sweep of every ModRM byte under opcodes `D8` to `DF` in both engines cover it. Not compared with x86 hardware; awaiting independent review.
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
@@ -119,22 +184,34 @@ 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.
- Added command-line arguments for a hosted C program (#392, part of Gate A2): the C runtime services `__p___argc`, `__p___argv`, `__p__environ`, `_configure_narrow_argv` and `_initialize_narrow_environment`, and a host method, `ServicesState::set_program_arguments`, that supplies the program's `argv`. A program built with the mingw-w64 runtime gets `argc`, `argv` and `envp` for `main` through these five, and the loader refused it before its entry point because they did not resolve. After configuration the guest finds the host's arguments in `__argc` and `__argv`, each NUL-terminated, with a null pointer after the last; with no host input it gets one empty argument, as ISO C specifies. The host method refuses a NUL byte, more than 32,767 bytes in all, and a call after the guest has built its table. The three variables are documented and the two initialization functions are not, so their behaviour is Xenora's: no code page, no wildcard expansion, and an empty environment table. All five are `partial`. Four tests in `runtime_services.rs` call the services from guest code and compare what the guest sees with what the test supplied. Not compared with Windows; awaiting independent review.
- 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.
- Added guest CRT allocation, zeroed array allocation, resizing, and release.
- Added private guest heap creation and destruction with per-heap allocation ownership.
@@ -143,6 +220,8 @@ remains unsupported.
- Added the synthetic default process heap with allocation, size queries, and release.
- Added `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` as `stub` services so that a C program built with the mingw-w64 runtime can bind its imports (#388, part of Gate A2). Such a program imports all three and does not call them on a normal run; without them the loader refused it before its entry point. A call to any of them stops the guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) and writes nothing, so a program that needs one stops there and cannot run on with a made-up result. No page protection is changed, no region is described and no exception is dispatched. The service generator's API-set table gains `api-ms-win-crt-private-l1-1-0.dll` for `ucrtbase.dll`, which is inferred and not taken from a document that names it. Two tests in `runtime_services.rs` call the stubs from guest code and check how they resolve. Not compared with Windows; awaiting independent review.
- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog.
- Added guest CRT wide-string length and comparison using Windows 16-bit code units.
@@ -241,6 +320,7 @@ remains unsupported.
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+6 -2
View File
@@ -1,6 +1,10 @@
# Contributing to BetterXen
BetterXen is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
BetterXen is hybrid-first Apple Silicon compatibility research built around an externally installed CrossOver, with a preserved but paused independent native implementation. Contributions should improve verified behavior rather than expand untested claims.
## Which work is active
The only active development track is the CrossOver-based hybrid architecture in [docs/roadmap.md](docs/roadmap.md). Planning is progressive: only the current milestone (Phase 1) has open issues; ideas for later phases are parked in the roadmap. Native research is paused, its backlog is closed and indexed in [docs/research/native-issue-archive.md](docs/research/native-issue-archive.md), and the few native issues still open only have assigned contributors with open pull requests. Do not start native work; if hybrid development needs a native component, file a focused hybrid issue. Pick an open issue in the current milestone and check its dependencies first. The engineering rules in `AGENTS.md` permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal (subject to licensing) and allow evaluating DXMT, DXVK, VKD3D-Proton and MoltenVK. CrossOver is proprietary: do not bundle or redistribute any of it, and record the exact versions you test. Before adopting or copying any upstream code, verify its license and provenance and add it to the [upstream registry](docs/research/upstream-registry.md); projects built around leaked or unauthorized game builds are not a source of code. Use the issue templates (hybrid task, bug, research, performance, validation, documentation) and fill in the licensing and provenance section.
## Getting started
@@ -44,7 +48,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.
Generated
+214 -8
View File
@@ -2,6 +2,23 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "betterxen"
version = "0.1.0"
dependencies = [
"xenora-decoder",
"xenora-import-gen",
"xenora-isa",
"xenora-loader",
"xenora-metal",
"xenora-ref",
"xenora-shader",
]
[[package]]
name = "betterxen-hybrid"
version = "0.1.0"
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -126,6 +143,24 @@ dependencies = [
"objc2-foundation",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "sha2"
version = "0.10.9"
@@ -137,12 +172,60 @@ dependencies = [
"digest",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -150,22 +233,139 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "betterxen"
name = "victory-shader"
version = "0.1.0"
dependencies = [
"xenora-decoder",
"xenora-import-gen",
"xenora-isa",
"xenora-loader",
"xenora-metal",
"xenora-ref",
"xenora-shader",
"thiserror",
"windows",
"windows-sys",
"zlib-rs",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
]
[[package]]
name = "xenora-benchmarks"
version = "0.1.0"
dependencies = [
"xenora-isa",
"xenora-metal",
"xenora-ref",
"xenora-shader",
@@ -242,3 +442,9 @@ dependencies = [
[[package]]
name = "xenora-texture"
version = "0.1.0"
[[package]]
name = "zlib-rs"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
+126 -48
View File
@@ -1,62 +1,119 @@
<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.
**Hybrid-first Apple Silicon compatibility research built around CrossOver, with preserved independent native ARM64 and Metal research (paused).**
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
[![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)
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.
**The paused native implementation described below uses no Wine, CrossOver, Rosetta or Vulkan runtime. The active hybrid direction intends to use CrossOver and Rosetta 2, subject to research and licensing review.**
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
> [!IMPORTANT]
> **Current direction.** BetterXen's only active development track is a CrossOver-based hybrid architecture: CrossOver (installed externally) as the compatibility foundation, with BetterXen providing whatever integration, configuration, diagnostics, benchmarking and optimization research shows is missing. This is the *intended* architecture, **not a verified Xbox compatibility stack**: no Xbox title has been shown to run through it, and CrossOver is not assumed to provide Xbox runtime compatibility. Work is at the research stage (Phase 1). Planning is progressive: only the current phase has open issues. The independent native implementation described below is **preserved but paused indefinitely**. See the [roadmap](docs/roadmap.md), [ADR 0005](docs/adr/0005-crossover-hybrid-direction.md), the [upstream research registry](docs/research/upstream-registry.md) and the [deferred native roadmap](docs/research/native-roadmap.md). The rewritten engineering rules are in [AGENTS.md](AGENTS.md).
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. Its native research implementation (paused) 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?
## Roadmap
BetterXen has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
The active plan is the [roadmap](docs/roadmap.md): **Phase 1 — CrossOver Research, Feasibility and Baseline** is the only active phase, and later phases are provisional and will be defined from its findings. The current issues are in the [Phase 1 milestone](https://github.com/MacosPorters/betterxen/milestone/9). The native implementation's six phases and the X1 to X25 capability map are archived in [docs/archive/readme-native-milestones.md](docs/archive/readme-native-milestones.md) and the [native-first plan](docs/archive/development-phases-native-first.md). Native work is paused indefinitely and resumes only after an explicit maintainer decision.
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
### Development milestones
| Milestone | Implementation | Status |
| --- | --- | --- |
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Follow the [BetterXen development phases](docs/development-phases.md) for the current work order and existing issue/PR dependencies. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
---
## 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 +234,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 +287,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 +320,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 +417,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 [roadmap](docs/roadmap.md) for the current phase and the [changelog](CHANGELOG.md) for unreleased additions. The paused native implementation's open research items are listed under [current limitations](#current-limitations).
---
@@ -367,6 +445,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.
---
+4
View File
@@ -15,3 +15,7 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission. The stall detection and memory-settle logic in `crates/hybrid/src/run.rs` follows supervision lessons from the same repository (`mac/PROGRESS.md`, `crates/victory-core/src/notes.rs`) and is reimplemented, not copied.
`crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`.
+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()
+7
View File
@@ -17,3 +17,10 @@ path = "src/main.rs"
xenora-shader = { path = "../crates/shader" }
xenora-ref = { path = "../crates/ref" }
xenora-metal = { path = "../crates/metal" }
[dev-dependencies]
xenora-isa = { path = "../crates/isa" }
[[bench]]
name = "gfx1030_identify"
harness = false
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original gfx1030 Wave32 instruction stream for metadata identification.
s_mov_b32 s12, 0x89abcdef
v_add_f32_e32 v4, v5, v9
s_cmp_lt_u32 s12, s13
ds_read_b32 v8, v2 offset:12
v_mov_b32_dpp v9, v6 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf
s_add_u32 s16, s17, s18
buffer_store_dword v7, off, s[4:7], 0
v_fma_f32 v5, v8, v10, 0x3f800003
s_movk_i32 s19, 0x2345
global_load_dword v3, v[10:11], off
v_cmp_lt_u32_e32 vcc_lo, v3, v7
s_load_dword s20, s[22:23], 0x20
v_pk_add_f16 v3, v4, v6
s_waitcnt vmcnt(0)
+143
View File
@@ -0,0 +1,143 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU-only gfx1030 metadata benchmark.
//!
//! Run `cargo bench --locked -p xenora-benchmarks --bench gfx1030_identify`
//! from the repository root. Repeat the command to collect independent
//! first-pass samples. The first pass is the first identification in a fresh
//! process with the input already in memory. It does not measure process
//! startup or guarantee cold hardware caches. Repeated passes use the same
//! stream after the untimed correctness check.
//!
//! To verify the fixture bytes and instruction lengths independently, run:
//! ```sh
//! llvm-mc -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
//! -show-encoding benchmarks/benches/fixtures/gfx1030_mixed.s
//! ```
use std::hint::black_box;
use std::time::{Duration, Instant};
use xenora_isa::meta::{EncodingFamily, Identified, identify};
const COPIES: usize = 4096;
const WARM_PASSES: usize = 9;
// Encodings and lengths come from llvm-mc, one row per instruction in
// fixtures/gfx1030_mixed.s. Each word is stored in little-endian order.
const FIXTURE: &[(&str, EncodingFamily, &[u32])] = {
use EncodingFamily::*;
&[
("S_MOV_B32", Sop1, &[0xbe8c03ff, 0x89abcdef]),
("V_ADD_F32", Vop2, &[0x06081305]),
("S_CMP_LT_U32", Sopc, &[0xbf0a0d0c]),
("DS_READ_B32", Ds, &[0xd8d8000c, 0x08000002]),
("V_MOV_B32", Vop1, &[0x7e1202fa, 0xff004e06]),
("S_ADD_U32", Sop2, &[0x80101211]),
("BUFFER_STORE_DWORD", Mubuf, &[0xe0700000, 0x80010700]),
("V_FMA_F32", Vop3, &[0xd54b0005, 0x03fe1508, 0x3f800003]),
("S_MOVK_I32", Sopk, &[0xb0132345]),
("GLOBAL_LOAD_DWORD", Global, &[0xdc308000, 0x037d000a]),
("V_CMP_LT_U32", Vopc, &[0x7d820f03]),
("S_LOAD_DWORD", Smem, &[0xf400050b, 0xfa000020]),
("V_PK_ADD_F16", Vop3p, &[0xcc0f4003, 0x1a020d04]),
("S_WAITCNT", Sopp, &[0xbf8c3f70]),
]
};
fn walk(stream: &[u8], mut observe: impl FnMut(usize, Identified)) -> usize {
let mut offset = 0;
let mut count = 0;
while offset < stream.len() {
let identified = identify(&stream[offset..])
.unwrap_or_else(|error| panic!("identification failed at byte {offset}: {error}"));
observe(offset, identified);
offset += identified.len;
count += 1;
}
count
}
fn verify(stream: &[u8]) {
let mut expected_offset = 0;
let mut expected = FIXTURE.iter().cycle();
let count = walk(stream, |offset, identified| {
let &(name, family, words) = expected.next().expect("fixture is nonempty");
let len = std::mem::size_of_val(words);
assert_eq!(offset, expected_offset, "byte boundary for {name}");
assert_eq!(identified.len, len, "length of {name} at byte {offset}");
assert_eq!(identified.form.name, name, "mnemonic at byte {offset}");
assert_eq!(identified.form.family, family, "family at byte {offset}");
expected_offset += len;
});
assert_eq!(expected_offset, stream.len());
assert_eq!(count, COPIES * FIXTURE.len());
}
fn measure(stream: &[u8]) -> Duration {
let start = Instant::now();
let count = walk(black_box(stream), |_, identified| {
black_box(identified);
});
let elapsed = start.elapsed();
assert_eq!(count, COPIES * FIXTURE.len());
elapsed
}
fn report(label: &str, elapsed: Duration, byte_count: usize) {
let seconds = elapsed.as_secs_f64();
let count = (COPIES * FIXTURE.len()) as f64;
println!(
"{label}: {:.3} ms, {:.2} ns/instruction, {:.2} MiB/s",
seconds * 1e3,
seconds * 1e9 / count,
byte_count as f64 / (1024.0 * 1024.0) / seconds
);
}
fn main() {
let block: Vec<u8> = FIXTURE
.iter()
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
.collect();
let stream = block.repeat(COPIES);
// 'cargo test --all-targets' checks the fixture without timing it.
if !std::env::args().any(|arg| arg == "--bench") {
verify(&stream);
return;
}
// Keep the first pass ahead of any metadata lookups. Validate the entire
// stream before reporting any timings. That validation also warms the path.
let first = measure(&stream);
verify(&stream);
let mut warm = [Duration::ZERO; WARM_PASSES];
for sample in &mut warm {
*sample = measure(&stream);
}
warm.sort_unstable();
println!(
"gfx1030 metadata identification: {} instructions, {} bytes, {} repeated passes",
COPIES * FIXTURE.len(),
stream.len(),
WARM_PASSES
);
report("First pass in a fresh process", first, stream.len());
report("Repeated minimum", warm[0], stream.len());
report("Repeated median", warm[WARM_PASSES / 2], stream.len());
report("Repeated maximum", warm[WARM_PASSES - 1], stream.len());
}
#[cfg(test)]
mod tests {
#[test]
fn mixed_llvm_fixture_preserves_names_families_lengths_and_boundaries() {
let block: Vec<u8> = super::FIXTURE
.iter()
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
.collect();
super::verify(&block.repeat(super::COPIES));
}
}
+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
}
}
+5
View File
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Exercise the benchmark's LLVM-derived fixture during ordinary workspace tests.
#[allow(dead_code)]
#[path = "../benches/gfx1030_identify.rs"]
mod benchmark;
+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}");
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "betterxen-hybrid"
description = "Host receipt, CrossOver discovery, frame-time statistics and Windows cross-toolchain probes for the hybrid direction"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[[bin]]
name = "betterxen-hybrid"
path = "src/main.rs"
+13
View File
@@ -0,0 +1,13 @@
//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`,
//! never a guessed value.
use std::process::Command;
pub fn run(program: &str, args: &[&str]) -> Option<String> {
let out = Command::new(program).args(args).output().ok()?;
if !out.status.success() {
return None;
}
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
Some(s)
}
+162
View File
@@ -0,0 +1,162 @@
//! Discover installed CrossOver bundles and read standard bundle metadata.
//!
//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist`
//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the
//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration"
//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such
//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable
//! interface (#350). The graphics backend of a bottle is deliberately not read.
use crate::cmdutil::run;
use crate::json::Json;
use std::path::{Path, PathBuf};
pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver";
#[derive(Debug, Clone, PartialEq)]
pub struct Install {
pub path: PathBuf,
pub bundle_id: Option<String>,
pub short_version: Option<String>,
pub build_version: Option<String>,
pub executable_archs: Option<Vec<String>>,
pub minimum_macos: Option<String>,
}
/// Candidate bundle locations: standard application directories. Spotlight is consulted too.
pub fn candidate_paths(home: &Path) -> Vec<PathBuf> {
let mut v = vec![
PathBuf::from("/Applications/CrossOver.app"),
home.join("Applications/CrossOver.app"),
];
if let Some(found) = run(
"/usr/bin/mdfind",
&[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")],
) {
for line in found.lines().filter(|l| !l.is_empty()) {
let p = PathBuf::from(line);
if !v.contains(&p) {
v.push(p);
}
}
}
v
}
pub fn discover(candidates: &[PathBuf]) -> Vec<Install> {
candidates.iter().filter_map(|p| inspect(p)).collect()
}
/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`.
pub fn inspect(app: &Path) -> Option<Install> {
let plist = app.join("Contents/Info.plist");
if !plist.is_file() {
return None;
}
let json = run(
"/usr/bin/plutil",
&["-convert", "json", "-o", "-", plist.to_str()?],
)?;
let exe = crate::host_string(&json, "CFBundleExecutable");
let archs = exe.and_then(|e| {
let p = app.join("Contents/MacOS").join(e);
run("/usr/bin/lipo", &["-archs", p.to_str()?])
.map(|s| s.split_whitespace().map(String::from).collect())
});
Some(Install {
path: app.to_path_buf(),
bundle_id: crate::host_string(&json, "CFBundleIdentifier"),
short_version: crate::host_string(&json, "CFBundleShortVersionString"),
build_version: crate::host_string(&json, "CFBundleVersion"),
executable_archs: archs,
minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"),
})
}
/// A documented CrossOver preference, or None when unset or unreadable.
pub fn preference(key: &str) -> Option<String> {
run("/usr/bin/defaults", &["read", BUNDLE_ID, key])
}
impl Install {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("path", Json::str(self.path.display().to_string())),
("bundle_id", Json::opt_str(self.bundle_id.clone())),
("short_version", Json::opt_str(self.short_version.clone())),
("build_version", Json::opt_str(self.build_version.clone())),
(
"executable_archs",
self.executable_archs.as_ref().map_or(Json::Null, |a| {
Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect())
}),
),
("minimum_macos", Json::opt_str(self.minimum_macos.clone())),
(
"bundle_id_is_codeweavers_crossover",
Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
// A synthetic bundle written by the test: it proves the metadata path, not that
// any real CrossOver build has this layout.
fn fake_bundle(dir: &Path) -> PathBuf {
let app = dir.join("CrossOver.app");
fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
fs::write(
app.join("Contents/Info.plist"),
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleExecutable</key><string>CrossOver</string>
<key>CFBundleIdentifier</key><string>com.codeweavers.CrossOver</string>
<key>CFBundleShortVersionString</key><string>99.1.2</string>
<key>CFBundleVersion</key><string>12345</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
</dict></plist>"#,
)
.unwrap();
// Copy a real system executable so `lipo -archs` has a Mach-O to read.
fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap();
app
}
#[test]
fn reads_bundle_metadata() {
if !cfg!(target_os = "macos") {
return;
}
let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id()));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp).unwrap();
let app = fake_bundle(&tmp);
let i = inspect(&app).expect("inspect");
assert_eq!(i.short_version.as_deref(), Some("99.1.2"));
assert_eq!(i.build_version.as_deref(), Some("12345"));
assert_eq!(i.minimum_macos.as_deref(), Some("14.0"));
assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID));
assert!(
i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()),
"{:?}",
i.executable_archs
);
assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1);
fs::remove_dir_all(&tmp).unwrap();
}
#[test]
fn missing_or_plistless_bundle_is_none() {
let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id()));
fs::create_dir_all(tmp.join("X.app/Contents")).unwrap();
assert!(inspect(&tmp.join("X.app")).is_none());
assert!(inspect(&tmp.join("Nope.app")).is_none());
fs::remove_dir_all(&tmp).unwrap();
}
}
+192
View File
@@ -0,0 +1,192 @@
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
//!
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
//! percentile interval. These definitions are fixed here so reports are comparable; other
//! tools define lows differently (for example as the mean of the worst 1 %).
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct FrameStats {
pub frames: usize,
pub total_ms: f64,
pub mean_ms: f64,
pub avg_fps: f64,
pub min_ms: f64,
pub max_ms: f64,
pub p50_ms: f64,
pub p95_ms: f64,
pub p99_ms: f64,
pub p999_ms: f64,
pub low_1pct_fps: f64,
pub low_01pct_fps: f64,
/// Frames longer than twice the median interval.
pub stutters: usize,
}
#[derive(Debug, PartialEq)]
pub enum FrameError {
Empty,
Invalid { index: usize, value: f64 },
Parse { line: usize, text: String },
}
impl std::fmt::Display for FrameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FrameError::Empty => write!(f, "no frame intervals"),
FrameError::Invalid { index, value } => {
write!(
f,
"frame {index}: interval {value} is not a positive finite number of milliseconds"
)
}
FrameError::Parse { line, text } => {
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
}
}
}
}
impl std::error::Error for FrameError {}
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
let n = sorted.len();
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
sorted[rank.min(n) - 1]
}
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
if intervals_ms.is_empty() {
return Err(FrameError::Empty);
}
for (index, &value) in intervals_ms.iter().enumerate() {
if !value.is_finite() || value <= 0.0 {
return Err(FrameError::Invalid { index, value });
}
}
let mut sorted = intervals_ms.to_vec();
sorted.sort_by(|a, b| a.total_cmp(b));
let total: f64 = intervals_ms.iter().sum();
let n = sorted.len();
let p50 = nearest_rank(&sorted, 50.0);
let p99 = nearest_rank(&sorted, 99.0);
let p999 = nearest_rank(&sorted, 99.9);
Ok(FrameStats {
frames: n,
total_ms: total,
mean_ms: total / n as f64,
avg_fps: n as f64 / (total / 1000.0),
min_ms: sorted[0],
max_ms: sorted[n - 1],
p50_ms: p50,
p95_ms: nearest_rank(&sorted, 95.0),
p99_ms: p99,
p999_ms: p999,
low_1pct_fps: 1000.0 / p99,
low_01pct_fps: 1000.0 / p999,
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
})
}
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
let mut out = Vec::new();
for (i, line) in text.lines().enumerate() {
let t = line.trim();
if t.is_empty() || t.starts_with('#') {
continue;
}
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
line: i + 1,
text: t.to_string(),
})?;
out.push(v);
}
Ok(out)
}
impl FrameStats {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("frames", Json::Num(self.frames as f64)),
("total_ms", Json::Num(self.total_ms)),
("mean_ms", Json::Num(self.mean_ms)),
("avg_fps", Json::Num(self.avg_fps)),
("min_ms", Json::Num(self.min_ms)),
("max_ms", Json::Num(self.max_ms)),
("p50_ms", Json::Num(self.p50_ms)),
("p95_ms", Json::Num(self.p95_ms)),
("p99_ms", Json::Num(self.p99_ms)),
("p999_ms", Json::Num(self.p999_ms)),
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
("percentile_method", Json::str("nearest-rank")),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
// Expected values below are worked out by hand, not produced by analyze().
#[test]
fn known_answer_ten_frames() {
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
let s = analyze(&v).unwrap();
assert_eq!(s.frames, 10);
assert_eq!(s.total_ms, 200.0);
assert_eq!(s.mean_ms, 20.0);
assert_eq!(s.avg_fps, 50.0);
assert_eq!(s.p50_ms, 10.0); // rank 5
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
assert_eq!(s.p99_ms, 100.0);
assert_eq!(s.low_1pct_fps, 10.0);
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
}
#[test]
fn stutter_threshold_is_strict() {
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
assert_eq!(s.stutters, 1);
}
#[test]
fn one_frame_per_second() {
let s = analyze(&[1000.0, 1000.0]).unwrap();
assert_eq!(s.avg_fps, 1.0);
}
#[test]
fn rejects_bad_input() {
assert_eq!(analyze(&[]), Err(FrameError::Empty));
assert!(matches!(
analyze(&[1.0, 0.0]),
Err(FrameError::Invalid { index: 1, .. })
));
assert!(matches!(
analyze(&[f64::NAN]),
Err(FrameError::Invalid { .. })
));
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
}
#[test]
fn parses_text() {
assert_eq!(
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
vec![16.5, 8.0]
);
assert_eq!(
parse_intervals("1\nabc\n"),
Err(FrameError::Parse {
line: 2,
text: "abc".into()
})
);
}
}
+140
View File
@@ -0,0 +1,140 @@
//! Host receipt: what this Mac is, from documented system interfaces (issue #353).
//!
//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed.
use crate::cmdutil::run;
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct HostReceipt {
pub macos_version: Option<String>,
pub macos_build: Option<String>,
pub chip: Option<String>,
pub apple_silicon: Option<bool>,
pub memory_bytes: Option<u64>,
pub logical_cpus: Option<u32>,
pub performance_cores: Option<u32>,
pub efficiency_cores: Option<u32>,
/// True only if an x86_64 slice of a system binary actually executed.
pub rosetta_executes_x86_64: Option<bool>,
pub gpu_name: Option<String>,
pub gpu_cores: Option<String>,
pub metal_support: Option<String>,
pub host_arch_of_this_binary: &'static str,
}
fn sysctl(name: &str) -> Option<String> {
run("/usr/sbin/sysctl", &["-n", name])
}
pub fn collect() -> HostReceipt {
let gpu = run(
"/usr/sbin/system_profiler",
&["SPDisplaysDataType", "-json"],
)
.and_then(|j| parse_gpu(&j));
HostReceipt {
macos_version: run("/usr/bin/sw_vers", &["-productVersion"]),
macos_build: sysctl("kern.osversion"),
chip: sysctl("machdep.cpu.brand_string"),
apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"),
memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()),
logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()),
performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()),
efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()),
// Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it
// now; it does not distinguish "not installed" from "disabled".
rosetta_executes_x86_64: Some(
run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(),
),
gpu_name: gpu.as_ref().map(|g| g.0.clone()),
gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()),
metal_support: gpu.as_ref().and_then(|g| g.2.clone()),
host_arch_of_this_binary: std::env::consts::ARCH,
}
}
/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display
/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model
/// key is absent. Uses a small string scan because this crate has no JSON parser dependency.
pub fn parse_gpu(json: &str) -> Option<(String, Option<String>, Option<String>)> {
let model = string_value(json, "sppci_model")?;
Some((
model,
string_value(json, "sppci_cores"),
string_value(json, "spdisplays_mtlgpufamilysupport"),
))
}
fn string_value(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..].trim_start().strip_prefix(':')?.trim_start();
let rest = rest.strip_prefix('"')?;
let end = rest.find('"')?;
Some(rest[..end].to_string())
}
impl HostReceipt {
pub fn to_json(&self) -> Json {
let n = |v: Option<u32>| v.map_or(Json::Null, |x| Json::Num(x as f64));
Json::obj(vec![
("macos_version", Json::opt_str(self.macos_version.clone())),
("macos_build", Json::opt_str(self.macos_build.clone())),
("chip", Json::opt_str(self.chip.clone())),
(
"apple_silicon",
self.apple_silicon.map_or(Json::Null, Json::Bool),
),
(
"memory_bytes",
self.memory_bytes
.map_or(Json::Null, |x| Json::Num(x as f64)),
),
("logical_cpus", n(self.logical_cpus)),
("performance_cores", n(self.performance_cores)),
("efficiency_cores", n(self.efficiency_cores)),
(
"rosetta_executes_x86_64",
self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool),
),
("gpu_name", Json::opt_str(self.gpu_name.clone())),
("gpu_cores", Json::opt_str(self.gpu_cores.clone())),
("metal_support", Json::opt_str(self.metal_support.clone())),
(
"receipt_binary_arch",
Json::str(self.host_arch_of_this_binary),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_gpu_fixture() {
let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4",
"spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#;
let g = parse_gpu(j).unwrap();
assert_eq!(g.0, "Apple M4");
assert_eq!(g.1.as_deref(), Some("10"));
assert_eq!(g.2.as_deref(), Some("spdisplays_metal4"));
}
#[test]
fn missing_gpu_is_none() {
assert!(parse_gpu("{}").is_none());
}
#[test]
fn collect_runs_on_this_host() {
let r = collect();
if cfg!(target_os = "macos") {
assert!(r.macos_version.is_some());
assert!(r.memory_bytes.unwrap() > 0);
}
assert!(r.to_json().render().contains("receipt_binary_arch"));
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
#[derive(Debug, Clone, PartialEq)]
pub enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
impl Json {
pub fn str(s: impl Into<String>) -> Json {
Json::Str(s.into())
}
pub fn opt_str(s: Option<String>) -> Json {
s.map_or(Json::Null, Json::Str)
}
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
pub fn render(&self) -> String {
let mut out = String::new();
self.write(&mut out, 0);
out.push('\n');
out
}
fn write(&self, out: &mut String, depth: usize) {
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
match self {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) if n.is_finite() => {
if n.fract() == 0.0 && n.abs() < 1e15 {
out.push_str(&format!("{}", *n as i64));
} else {
out.push_str(&format!("{n}"));
}
}
// JSON has no NaN or infinity; refuse to invent a number.
Json::Num(_) => out.push_str("null"),
Json::Str(s) => escape(s, out),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
pad(out, depth + 1);
item.write(out, depth + 1);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push(']');
}
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (k, v)) in fields.iter().enumerate() {
pad(out, depth + 1);
escape(k, out);
out.push_str(": ");
v.write(out, depth + 1);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push('}');
}
}
}
}
fn escape(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_and_nests() {
let j = Json::obj(vec![
("a", Json::str("q\"\\\n\u{1}")),
(
"b",
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
),
("c", Json::Num(f64::NAN)),
]);
let r = j.render();
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
assert!(r.contains("0.5"));
assert!(r.contains(r#""c": null"#));
}
}
+32
View File
@@ -0,0 +1,32 @@
//! BetterXen hybrid tooling: read-only inspection and measurement helpers around an
//! externally installed CrossOver. Nothing here launches a game or claims compatibility.
pub mod cmdutil;
pub mod crossover;
pub mod frames;
pub mod host;
pub mod json;
pub mod memory;
pub mod run;
pub mod toolchain;
/// Value of a top-level string key in flat JSON produced by `plutil -convert json`.
pub fn host_string(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..]
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => out.push(chars.next()?),
c => out.push(c),
}
}
None
}
+325
View File
@@ -0,0 +1,325 @@
use betterxen_hybrid::{crossover, frames, host, json::Json, memory, run, toolchain};
use std::path::PathBuf;
use std::process::ExitCode;
const USAGE: &str = "usage: betterxen-hybrid <command>
host host receipt (JSON)
crossover [--app P] CrossOver installs and documented preferences (JSON)
toolchain Windows cross-compilers found on PATH (JSON)
frames <file> frame-time statistics; file has one interval in ms per line (JSON)
guard [--min-start-free N] [--min-free N] -- CMD ARGS...
run CMD; refuse to start / stop it when free memory is low
run --bottle B [--backend X] [--timeout S] [--stall-timeout S] [--settle-bound S] [--expect TEXT] [--out DIR]
[--min-start-free N] [--min-free N] -- EXE [ARGS...]
run a Windows program through CrossOver; write a JSON record
bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...]
run the program per backend N times; summarise frame times
receipt host + crossover + toolchain in one JSON document";
fn crossover_json(app: Option<PathBuf>) -> Json {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let cands = match app {
Some(p) => vec![p],
None => crossover::candidate_paths(&home),
};
let installs = crossover::discover(&cands);
Json::obj(vec![
("installed", Json::Bool(!installs.is_empty())),
(
"installs",
Json::Arr(installs.iter().map(|i| i.to_json()).collect()),
),
(
"bottle_dir_preference",
Json::opt_str(crossover::preference("BottleDir")),
),
(
"managed_bottle_dirs_preference",
Json::opt_str(crossover::preference("ManagedBottleDirs")),
),
(
"searched",
Json::Arr(
cands
.iter()
.map(|p| Json::str(p.display().to_string()))
.collect(),
),
),
(
"note",
Json::str(
"Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).",
),
),
])
}
fn toolchain_json() -> Json {
let path = std::env::var("PATH").unwrap_or_default();
Json::Arr(
toolchain::probe(&path)
.iter()
.map(|c| c.to_json())
.collect(),
)
}
fn guard(args: &[String]) -> ExitCode {
let mut limits = memory::Limits {
min_start_free: 70,
min_free: 20,
poll: std::time::Duration::from_secs(1),
grace: std::time::Duration::from_secs(10),
};
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args.get(i + 1).and_then(|v| v.parse::<u8>().ok());
match (args[i].as_str(), v) {
("--min-start-free", Some(v)) => limits.min_start_free = v,
("--min-free", Some(v)) => limits.min_free = v,
_ => {
eprintln!("{USAGE}");
return ExitCode::from(2);
}
}
i += 2;
}
let Some(cmd) = args.get(i + 1) else {
eprintln!("{USAGE}");
return ExitCode::from(2);
};
match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) {
memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS,
memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8),
other => {
eprintln!("guard: {other:?}");
ExitCode::from(3)
}
}
}
struct RunArgs {
cfg: run::RunConfig,
backends: Vec<String>,
repeat: u32,
out: Option<PathBuf>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut bottle = None;
let mut backend = None;
let mut backends = Vec::new();
let mut repeat = 1u32;
let mut timeout = 300u64;
let mut stall = None;
let mut settle = 60u64;
let mut expect = None;
let mut out = None;
let (mut min_start, mut min_free) = (50u8, 15u8);
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args
.get(i + 1)
.ok_or_else(|| format!("{} needs a value", args[i]))?
.clone();
match args[i].as_str() {
"--bottle" => bottle = Some(v),
"--backend" => backend = Some(v),
"--backends" => backends = v.split(',').map(String::from).collect(),
"--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?,
"--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?,
"--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?),
"--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?,
"--expect" => expect = Some(v),
"--out" => out = Some(PathBuf::from(v)),
"--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?,
"--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?,
o => return Err(format!("unknown option {o}")),
}
i += 2;
}
let program = args.get(i + 1).ok_or("missing program after --")?.clone();
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let installs = crossover::discover(&crossover::candidate_paths(&home));
let install = installs.first().ok_or("no CrossOver installation found")?;
let wine = run::wine_path(&install.path);
if !wine.is_file() {
return Err(format!(
"{} not found in this CrossOver build",
wine.display()
));
}
let work = out
.clone()
.unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs"));
Ok(RunArgs {
cfg: run::RunConfig {
wine,
bottle: bottle.ok_or("--bottle is required")?,
backend,
program,
args: args[i + 2..].to_vec(),
timeout: std::time::Duration::from_secs(timeout),
limits: memory::Limits {
min_start_free: min_start,
min_free,
poll: std::time::Duration::from_millis(250),
grace: std::time::Duration::from_secs(10),
},
expect,
work_dir: work,
stall_timeout: stall.map(std::time::Duration::from_secs),
settle_bound: std::time::Duration::from_secs(settle),
read_free: memory::free_percentage,
},
backends,
repeat,
out,
})
}
fn crossover_build() -> Option<String> {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
crossover::discover(&crossover::candidate_paths(&home))
.first()
.and_then(|i| {
Some(format!(
"{} ({})",
i.short_version.clone()?,
i.build_version.clone()?
))
})
}
fn save(dir: &std::path::Path, name: &str, j: &Json) {
let _ = std::fs::create_dir_all(dir);
let _ = std::fs::write(dir.join(name), j.render());
}
fn run_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) => a,
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let r = run::execute(&a.cfg, crossover_build());
print!("{}", r.json.render());
if let Some(dir) = &a.out {
save(
dir,
&format!(
"run-{}.json",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
),
&r.json,
);
}
if r.class == run::Class::Passed {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn bench_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) if !a.backends.is_empty() => a,
Ok(_) => {
eprintln!("bench needs --backends\n{USAGE}");
return ExitCode::from(2);
}
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let build = crossover_build();
let mut per_backend = Vec::new();
let mut all_ok = true;
for b in &a.backends {
let mut runs = Vec::new();
for _ in 0..a.repeat {
let mut cfg = a.cfg.clone();
cfg.backend = if b == "default" {
None
} else {
Some(b.clone())
};
let r = run::execute(&cfg, build.clone());
all_ok &= r.class == run::Class::Passed;
runs.push(r.json);
}
per_backend.push(Json::obj(vec![
("backend", Json::str(b.clone())),
("runs", Json::Arr(runs)),
]));
}
let doc = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-bench/0")),
("repeat", Json::Num(a.repeat as f64)),
("host", host::collect().to_json()),
("results", Json::Arr(per_backend)),
]);
print!("{}", doc.render());
if let Some(dir) = &a.out {
save(dir, "bench.json", &doc);
}
if all_ok {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("run") => return run_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
Some("bench") => return bench_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
_ => {}
}
if std::env::args().nth(1).as_deref() == Some("guard") {
return guard(&std::env::args().skip(2).collect::<Vec<_>>());
}
let args: Vec<String> = std::env::args().skip(1).collect();
let result: Result<Json, String> = match args.first().map(String::as_str) {
Some("host") => Ok(host::collect().to_json()),
Some("crossover") => {
let app = match args.get(1).map(String::as_str) {
Some("--app") => args.get(2).map(PathBuf::from),
_ => None,
};
Ok(crossover_json(app))
}
Some("toolchain") => Ok(toolchain_json()),
Some("frames") => match args.get(1) {
None => Err("frames needs a file".into()),
Some(f) => std::fs::read_to_string(f)
.map_err(|e| format!("{f}: {e}"))
.and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string()))
.and_then(|v| frames::analyze(&v).map_err(|e| e.to_string()))
.map(|s| s.to_json()),
},
Some("receipt") => Ok(Json::obj(vec![
("schema", Json::str("betterxen-hybrid-receipt/0")),
("host", host::collect().to_json()),
("crossover", crossover_json(None)),
("windows_cross_compilers", toolchain_json()),
])),
_ => Err(USAGE.into()),
};
match result {
Ok(j) => {
print!("{}", j.render());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("{e}");
ExitCode::from(2)
}
}
}
+210
View File
@@ -0,0 +1,210 @@
//! Memory-pressure supervision of a child process.
//!
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
//! the author's permission): do not start a workload when little memory is free, and stop it
//! when system-wide free memory falls below a limit, because GPU memory is wired under
//! unified memory and a runaway workload can take the whole Mac down. This version is
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
//! stopped. It supervises any command; it contains nothing game-specific.
//!
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
//! stable interface, so an unreadable value is an error, never "assume enough memory".
use crate::cmdutil::run;
use std::process::{Child, Command};
use std::time::{Duration, Instant};
pub fn parse_free_percentage(output: &str) -> Option<u8> {
let line = output
.lines()
.find(|l| l.contains("System-wide memory free percentage"))?;
let digits: String = line
.split(':')
.nth(1)?
.trim()
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
let v: u8 = digits.parse().ok()?;
(v <= 100).then_some(v)
}
pub fn free_percentage() -> Option<u8> {
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Limits {
/// Refuse to start below this percent free.
pub min_start_free: u8,
/// Stop the child when free memory drops below this percent.
pub min_free: u8,
pub poll: Duration,
/// Time between SIGTERM and SIGKILL.
pub grace: Duration,
}
#[derive(Debug, PartialEq)]
pub enum Outcome {
/// The child ran to completion; `None` means it ended by a signal.
Exited(Option<i32>),
RefusedToStart {
free: u8,
need: u8,
},
StoppedLowMemory {
free: u8,
limit: u8,
},
/// Memory could not be read, so no guarantee can be given.
MemoryUnreadable,
SpawnFailed(String),
}
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
let _ = Command::new("/bin/kill")
.args(["-TERM", &child.id().to_string()])
.status();
let t0 = Instant::now();
while t0.elapsed() < grace {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let _ = child.wait();
}
/// Run `program` under `limits`, reading memory through `read_free`.
pub fn supervise(
program: &str,
args: &[String],
limits: Limits,
read_free: &mut dyn FnMut() -> Option<u8>,
) -> Outcome {
match read_free() {
None => return Outcome::MemoryUnreadable,
Some(free) if free < limits.min_start_free => {
return Outcome::RefusedToStart {
free,
need: limits.min_start_free,
};
}
Some(_) => {}
}
let mut child = match Command::new(program).args(args).spawn() {
Ok(c) => c,
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
};
loop {
match child.try_wait() {
Ok(Some(status)) => return Outcome::Exited(status.code()),
Ok(None) => {}
Err(e) => return Outcome::SpawnFailed(e.to_string()),
}
match read_free() {
None => {
terminate(&mut child, limits.grace);
return Outcome::MemoryUnreadable;
}
Some(free) if free < limits.min_free => {
terminate(&mut child, limits.grace);
return Outcome::StoppedLowMemory {
free,
limit: limits.min_free,
};
}
Some(_) => {}
}
std::thread::sleep(limits.poll);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> Limits {
Limits {
min_start_free: 50,
min_free: 20,
poll: Duration::from_millis(20),
grace: Duration::from_millis(500),
}
}
#[test]
fn parses_memory_pressure_output() {
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
assert_eq!(parse_free_percentage(real), Some(71));
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 100%"),
Some(100)
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 101%"),
None
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: x"),
None
);
assert_eq!(parse_free_percentage("nothing"), None);
}
#[test]
fn refuses_to_start_when_low() {
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
}
#[test]
fn unreadable_memory_is_an_error() {
assert_eq!(
supervise("/usr/bin/true", &[], limits(), &mut || None),
Outcome::MemoryUnreadable
);
}
#[test]
fn child_exit_code_is_reported() {
let out = supervise(
"/bin/sh",
&["-c".into(), "exit 7".into()],
limits(),
&mut || Some(90),
);
assert_eq!(out, Outcome::Exited(Some(7)));
}
#[test]
fn stops_child_when_memory_drops() {
let mut calls = 0;
let t0 = Instant::now();
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
calls += 1;
Some(if calls < 4 { 90 } else { 10 })
});
assert_eq!(
out,
Outcome::StoppedLowMemory {
free: 10,
limit: 20
}
);
assert!(
t0.elapsed() < Duration::from_secs(10),
"child was not stopped promptly"
);
}
#[test]
fn real_reading_is_available_on_macos() {
if cfg!(target_os = "macos") {
assert!(free_percentage().is_some());
}
}
}
+685
View File
@@ -0,0 +1,685 @@
//! Launch a Windows program through an installed CrossOver, supervise it, and write a
//! structured record of what happened.
//!
//! Interface used: `<CrossOver.app>/Contents/SharedSupport/CrossOver/bin/wine --bottle B EXE`
//! and `.../bin/wineserver -k`. These are **not documented by CodeWeavers** for macOS; they
//! exist in the installed build and answer `--help` (cxbottle, cxstart) as observed on build
//! 26.3.0.39832. Every record therefore carries the CrossOver build and a flag saying the
//! launcher interface is vendor-help-only. The graphics backend is selected through the
//! `CX_GRAPHICS_BACKEND` environment variable, which appears in third-party launch scripts and
//! is likewise undocumented; an unrecognised value was observed to be ignored silently, so a
//!
//! Stall detection and the wait for memory to settle after a stop follow the supervision
//! lessons in skakwy's <https://github.com/skakwy/victory-mac> (`mac/PROGRESS.md`,
//! `mac/run-victory.sh`, `crates/victory-core/src/notes.rs` at commit 22b3f8e45a59; his own
//! work, GPL-3.0, used with his permission): detect a hung run by absence of progress, stop a
//! bottle with `wineserver -k` and its prefix, and do not start the next run until memory has
//! been returned. Reimplemented here; none of his code is copied.
//!
//! A record names the backend *requested* and relies on the workload's own diagnostics
//! (adapter name, backend log lines) to show what actually ran.
use crate::frames;
use crate::json::Json;
use crate::memory;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone)]
pub struct RunConfig {
pub wine: PathBuf,
pub bottle: String,
pub backend: Option<String>,
pub program: String,
pub args: Vec<String>,
pub timeout: Duration,
pub limits: memory::Limits,
/// Text that must appear in stdout for a zero exit to count as a pass.
pub expect: Option<String>,
pub work_dir: PathBuf,
/// Stop the run when neither stdout nor stderr has grown for this long.
pub stall_timeout: Option<Duration>,
/// After a stop, wait at most this long for free memory to return to `min_start_free`.
pub settle_bound: Duration,
/// Free-memory reader; `memory::free_percentage` outside tests.
pub read_free: fn() -> Option<u8>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Class {
Passed,
FailedExit(i32),
MissingExpectedMarker,
TimedOut,
/// No output on stdout or stderr for the stall timeout.
Stalled,
StoppedLowMemory,
RefusedToStart,
/// The Windows loader did not accept the file (for example an ARM64 PE this build cannot run).
CannotExecute,
/// The workload reported that no graphics device could be created.
NoDevice,
MemoryUnreadable,
LaunchFailed,
}
impl Class {
pub fn name(&self) -> String {
match self {
Class::Passed => "passed".into(),
Class::FailedExit(c) => format!("failed_exit_{c}"),
Class::MissingExpectedMarker => "missing_expected_marker".into(),
Class::TimedOut => "timed_out".into(),
Class::Stalled => "stalled".into(),
Class::StoppedLowMemory => "stopped_low_memory".into(),
Class::RefusedToStart => "refused_to_start_low_memory".into(),
Class::CannotExecute => "cannot_execute".into(),
Class::NoDevice => "no_graphics_device".into(),
Class::MemoryUnreadable => "memory_unreadable".into(),
Class::LaunchFailed => "launch_failed".into(),
}
}
}
/// Classify a finished (or stopped) run from observable facts only.
pub fn classify(exit: Option<i32>, stdout: &str, stderr: &str, expect: Option<&str>) -> Class {
if stderr.contains("cannot execute") {
return Class::CannotExecute;
}
if stdout.contains("NO DEVICE") && exit == Some(2) {
return Class::NoDevice;
}
match exit {
Some(0) => match expect {
Some(m) if !stdout.contains(m) => Class::MissingExpectedMarker,
_ => Class::Passed,
},
Some(c) => Class::FailedExit(c),
None => Class::FailedExit(-1),
}
}
/// Known host-environment noise in CrossOver output, reported as diagnostics instead of
/// silently dropped. Returns (kind, line) for each recognised line.
pub fn diagnostics(text: &str) -> Vec<(&'static str, String)> {
let mut out = Vec::new();
for line in text.lines() {
if line.contains("LibClamAV Error") || line.contains("Can't open file or directory") {
out.push(("clamav-database-missing", line.to_string()));
} else if line.starts_with("warn:") && line.contains("DXVK") {
out.push(("dxvk-warning", line.to_string()));
}
}
out
}
/// Which graphics layer announced itself, judged from the workload's stdout and stderr.
pub fn detected_backend(output: &str) -> &'static str {
if output.contains("DXVK:") {
"dxvk"
} else if output.contains("DXMT") || output.contains("D3D_FEATURE_LEVEL_11_1\ninfo: Using") {
"dxmt"
} else if output.contains("adapter=AMD Compatibility Mode") {
"d3dmetal (inferred: Apple-reported adapter identity)"
} else if output.contains("adapter=Apple M") {
"wined3d (inferred: native adapter name, no layer banner)"
} else {
"unknown"
}
}
#[derive(Debug, Default, Clone)]
pub struct Samples {
pub peak_rss_kb: u64,
pub mean_cpu_percent_of_core: f64,
pub min_free_percent: Option<u8>,
pub samples: u32,
}
/// Sum RSS (KB) and CPU % of processes whose command line mentions the CrossOver bundle or the
/// bottle directory. Heuristic: processes not started from those paths are not counted.
fn sample_processes(needles: &[String]) -> (u64, f64) {
let Some(out) = crate::cmdutil::run("/bin/ps", &["-axo", "rss=,pcpu=,command="]) else {
return (0, 0.0);
};
let (mut rss, mut cpu) = (0u64, 0f64);
for l in out.lines() {
if !needles.iter().any(|n| l.contains(n.as_str())) {
continue;
}
let mut it = l.split_whitespace();
rss += it.next().and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
cpu += it.next().and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
}
(rss, cpu)
}
fn thermal() -> Json {
match crate::cmdutil::run("/usr/bin/pmset", &["-g", "therm"]) {
Some(t) => Json::Arr(
t.lines()
.map(|l| Json::str(l.trim()))
.filter(|j| *j != Json::str(""))
.collect(),
),
None => Json::Null,
}
}
pub struct RunRecord {
pub class: Class,
pub duration: Duration,
pub exit: Option<i32>,
pub stdout: String,
pub stderr: String,
pub samples: Samples,
pub json: Json,
}
pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
let t_wall = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let _ = std::fs::create_dir_all(&cfg.work_dir);
let out_path = cfg
.work_dir
.join(format!("stdout-{t_wall}-{}.txt", std::process::id()));
let err_path = cfg
.work_dir
.join(format!("stderr-{t_wall}-{}.txt", std::process::id()));
let mut settle: Option<(Duration, bool)> = None;
let thermal_before = thermal();
let free_start = (cfg.read_free)();
let mut result = RunRecord {
class: Class::LaunchFailed,
duration: Duration::ZERO,
exit: None,
stdout: String::new(),
stderr: String::new(),
samples: Samples::default(),
json: Json::Null,
};
match free_start {
None => result.class = Class::MemoryUnreadable,
Some(f) if f < cfg.limits.min_start_free => result.class = Class::RefusedToStart,
Some(_) => {
let files = std::fs::File::create(&out_path)
.and_then(|o| std::fs::File::create(&err_path).map(|e| (o, e)));
if let Ok((o, e)) = files {
let mut cmd = Command::new(&cfg.wine);
cmd.arg("--bottle")
.arg(&cfg.bottle)
.arg(&cfg.program)
.args(&cfg.args);
cmd.stdout(Stdio::from(o)).stderr(Stdio::from(e));
if let Some(b) = &cfg.backend {
cmd.env("CX_GRAPHICS_BACKEND", b);
}
let started = Instant::now();
if let Ok(mut child) = cmd.spawn() {
let bundle = cfg
.wine
.to_string_lossy()
.split("/Contents/")
.next()
.unwrap_or("")
.to_string();
let needles = vec![bundle, format!("Bottles/{}", cfg.bottle)];
let (mut cpu_sum, mut n) = (0f64, 0u32);
let mut stop: Option<Class> = None;
let mut last_len = 0u64;
let mut last_growth = Instant::now();
loop {
match child.try_wait() {
Ok(Some(st)) => {
result.exit = st.code();
break;
}
Ok(None) => {}
Err(_) => break,
}
let (rss, cpu) = sample_processes(&needles);
result.samples.peak_rss_kb = result.samples.peak_rss_kb.max(rss);
cpu_sum += cpu;
n += 1;
match (cfg.read_free)() {
Some(f) => {
let m = result.samples.min_free_percent.map_or(f, |x| x.min(f));
result.samples.min_free_percent = Some(m);
if f < cfg.limits.min_free {
stop = Some(Class::StoppedLowMemory);
}
}
None => stop = Some(Class::MemoryUnreadable),
}
let len = [&out_path, &err_path]
.iter()
.map(|p| std::fs::metadata(p).map_or(0, |m| m.len()))
.sum::<u64>();
if len != last_len {
last_len = len;
last_growth = Instant::now();
}
if stop.is_none() && started.elapsed() > cfg.timeout {
stop = Some(Class::TimedOut);
}
if stop.is_none()
&& cfg.stall_timeout.is_some_and(|d| last_growth.elapsed() > d)
{
stop = Some(Class::Stalled);
}
if stop.is_some() {
memory::terminate(&mut child, cfg.limits.grace);
stop_bottle(&cfg.wine, &cfg.bottle);
break;
}
std::thread::sleep(cfg.limits.poll);
}
result.duration = started.elapsed();
if stop.is_some() {
let t = Instant::now();
let need = cfg.limits.min_start_free;
let mut recovered = false;
loop {
if (cfg.read_free)().is_some_and(|f| f >= need) {
recovered = true;
break;
}
if t.elapsed() >= cfg.settle_bound {
break;
}
std::thread::sleep(cfg.limits.poll);
}
settle = Some((t.elapsed(), recovered));
}
result.samples.samples = n;
result.samples.mean_cpu_percent_of_core =
if n > 0 { cpu_sum / n as f64 } else { 0.0 };
result.stdout = std::fs::read_to_string(&out_path).unwrap_or_default();
result.stderr = std::fs::read_to_string(&err_path).unwrap_or_default();
result.class = stop.unwrap_or_else(|| {
classify(
result.exit,
&result.stdout,
&result.stderr,
cfg.expect.as_deref(),
)
});
}
}
}
}
let intervals: Vec<f64> = result
.stdout
.lines()
.filter_map(|l| l.strip_prefix("frame_ms "))
.filter_map(|v| v.trim().parse().ok())
.collect();
let frame_stats = frames::analyze(&intervals).ok().map(|s| s.to_json());
let combined = format!("{}\n{}", result.stdout, result.stderr);
let diags: Vec<Json> = diagnostics(&combined)
.into_iter()
.map(|(k, l)| Json::obj(vec![("kind", Json::str(k)), ("line", Json::str(l))]))
.collect();
let tail = |s: &str| -> Json {
let lines: Vec<&str> = s.lines().filter(|l| !l.starts_with("frame_ms ")).collect();
let keep = if lines.len() > 40 {
&lines[lines.len() - 40..]
} else {
&lines[..]
};
Json::Arr(keep.iter().map(|l| Json::str(*l)).collect())
};
result.json = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-run/0")),
("unix_time", Json::Num(t_wall as f64)),
("crossover_build", Json::opt_str(crossover_build)),
(
"launcher_interface",
Json::str(
"CrossOver bin/wine --bottle (vendor --help only; not documented by CodeWeavers for macOS)",
),
),
("bottle", Json::str(cfg.bottle.clone())),
("backend_requested", Json::opt_str(cfg.backend.clone())),
("backend_variable_documented", Json::Bool(false)),
("backend_detected", Json::str(detected_backend(&combined))),
("program", Json::str(cfg.program.clone())),
(
"args",
Json::Arr(cfg.args.iter().map(|a| Json::str(a.clone())).collect()),
),
("classification", Json::str(result.class.name())),
(
"exit_code",
result.exit.map_or(Json::Null, |c| Json::Num(c as f64)),
),
(
"duration_ms",
Json::Num(result.duration.as_secs_f64() * 1000.0),
),
("timeout_s", Json::Num(cfg.timeout.as_secs_f64())),
(
"stall_timeout_s",
cfg.stall_timeout
.map_or(Json::Null, |d| Json::Num(d.as_secs_f64())),
),
(
"memory_settle_after_stop",
settle.map_or(Json::Null, |(d, ok)| {
Json::obj(vec![
("waited_ms", Json::Num(d.as_secs_f64() * 1000.0)),
("recovered_to_start_threshold", Json::Bool(ok)),
("bound_s", Json::Num(cfg.settle_bound.as_secs_f64())),
])
}),
),
(
"free_memory_percent_at_start",
free_start.map_or(Json::Null, |f| Json::Num(f as f64)),
),
(
"min_free_memory_percent_during_run",
result
.samples
.min_free_percent
.map_or(Json::Null, |f| Json::Num(f as f64)),
),
(
"peak_crossover_rss_kb_sampled",
Json::Num(result.samples.peak_rss_kb as f64),
),
(
"mean_crossover_cpu_percent_of_one_core_sampled",
Json::Num(result.samples.mean_cpu_percent_of_core),
),
("process_samples", Json::Num(result.samples.samples as f64)),
(
"gpu_utilization",
Json::str("not collected: no unprivileged documented source on this host"),
),
("thermal_before", thermal_before),
("thermal_after", thermal()),
("diagnostics", Json::Arr(diags)),
("frame_stats", frame_stats.unwrap_or(Json::Null)),
("stdout_tail", tail(&result.stdout)),
("stderr_tail", tail(&result.stderr)),
]);
let _ = std::fs::remove_file(&out_path);
let _ = std::fs::remove_file(&err_path);
result
}
/// Prefix directory of a bottle. CrossOver documents `BottleDir` in its preferences; otherwise
/// the default location under Application Support is used.
pub fn bottle_prefix(bottle: &str) -> PathBuf {
let base = crate::crossover::preference("BottleDir")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(std::env::var("HOME").unwrap_or_default())
.join("Library/Application Support/CrossOver/Bottles")
});
base.join(bottle)
}
/// Stop every process of one bottle with `wineserver -k`, selecting the bottle through
/// `WINEPREFIX`. Setting `CX_BOTTLE` instead was tried first and observed NOT to select the
/// bottle: the Windows process kept running after the supervisor reported it stopped.
pub fn stop_bottle(wine: &Path, bottle: &str) {
if let Some(dir) = wine.parent() {
let _ = Command::new(dir.join("wineserver"))
.arg("-k")
.env("WINEPREFIX", bottle_prefix(bottle))
.status();
}
}
pub fn wine_path(app: &Path) -> PathBuf {
app.join("Contents/SharedSupport/CrossOver/bin/wine")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_from_observed_facts() {
assert_eq!(classify(Some(0), "PASS", "", Some("PASS")), Class::Passed);
assert_eq!(
classify(Some(0), "ok", "", Some("PASS")),
Class::MissingExpectedMarker
);
assert_eq!(classify(Some(0), "", "", None), Class::Passed);
assert_eq!(classify(Some(1), "FAIL", "", None), Class::FailedExit(1));
assert_eq!(
classify(Some(2), "NO DEVICE hr=0x1", "", None),
Class::NoDevice
);
assert_eq!(classify(Some(2), "other", "", None), Class::FailedExit(2));
assert_eq!(
classify(
Some(1),
"",
"winewrapper.exe:error: cannot execute L\"a.exe\"",
None
),
Class::CannotExecute
);
}
#[test]
fn recognises_noise_and_backends() {
let d = diagnostics(
"LibClamAV Error: x\nERROR: Can't open file or directory\nwarn: DXVK: No state cache\nfine",
);
assert_eq!(d.len(), 3);
assert_eq!(d[0].0, "clamav-database-missing");
assert!(detected_backend("info: DXVK: cxaddon\nadapter=Apple M4").starts_with("dxvk"));
assert!(detected_backend("adapter=AMD Compatibility Mode").starts_with("d3dmetal"));
assert_eq!(detected_backend("nothing"), "unknown");
}
fn stub(dir: &Path, body: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(dir).unwrap();
let p = dir.join("wine");
std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
p
}
fn cfg(wine: PathBuf, timeout_ms: u64, tag: &str) -> RunConfig {
RunConfig {
wine,
bottle: "t".into(),
backend: None,
program: "x.exe".into(),
args: vec![],
timeout: Duration::from_millis(timeout_ms),
limits: memory::Limits {
min_start_free: 0,
min_free: 0,
poll: Duration::from_millis(30),
grace: Duration::from_millis(500),
},
expect: Some("PASS".into()),
work_dir: std::env::temp_dir().join(format!("bxrun-{tag}-{}", std::process::id())),
stall_timeout: None,
settle_bound: Duration::from_millis(200),
read_free: memory::free_percentage,
}
}
// These use a stub standing in for the launcher: they prove the supervision and record
// logic, not anything about CrossOver.
#[test]
fn stub_run_records_pass_frames_and_env() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub1-{}", std::process::id()));
let w = stub(
&dir,
"echo \"backend=$CX_GRAPHICS_BACKEND\"; echo 'frame_ms 10'; echo 'frame_ms 20'; echo PASS",
);
let mut c = cfg(w, 10_000, "a");
c.backend = Some("dxmt".into());
let r = execute(&c, Some("test".into()));
assert_eq!(r.class, Class::Passed);
let j = r.json.render();
assert!(j.contains("\"frames\": 2"), "{j}");
assert!(j.contains("backend=dxmt"), "{j}");
assert!(j.contains("\"backend_requested\": \"dxmt\""));
assert!(
!j.contains("frame_ms 10"),
"frame lines belong in frame_stats, not the tail"
);
}
#[test]
fn stub_run_times_out_and_is_stopped() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub2-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let t0 = Instant::now();
let r = execute(&cfg(w, 300, "b"), None);
assert_eq!(r.class, Class::TimedOut);
assert!(t0.elapsed() < Duration::from_secs(10));
}
#[test]
fn stub_failure_is_classified_with_exit_code() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub3-{}", std::process::id()));
let w = stub(&dir, "echo FAIL; exit 3");
assert_eq!(
execute(&cfg(w, 10_000, "c"), None).class,
Class::FailedExit(3)
);
}
#[test]
fn silent_workload_is_stopped_as_stalled_before_the_timeout() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall1-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 20_000, "d");
c.stall_timeout = Some(Duration::from_millis(300));
let t0 = Instant::now();
let r = execute(&c, None);
assert_eq!(r.class, Class::Stalled);
assert!(
t0.elapsed() < Duration::from_secs(5),
"stall must fire long before the 20 s timeout"
);
assert!(r.json.render().contains("\"classification\": \"stalled\""));
}
#[test]
fn workload_that_keeps_printing_is_not_stalled() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall2-{}", std::process::id()));
// Prints every 0.1 s for about 1.2 s: longer than the 0.5 s stall timeout in total.
let w = stub(
&dir,
"i=0; while [ $i -lt 12 ]; do echo tick; i=$((i+1)); sleep 0.1; done; echo PASS",
);
let mut c = cfg(w, 20_000, "e");
c.stall_timeout = Some(Duration::from_millis(500));
assert_eq!(execute(&c, None).class, Class::Passed);
}
static FREE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(90);
fn fake_free() -> Option<u8> {
Some(FREE.load(std::sync::atomic::Ordering::SeqCst))
}
// One test owns the shared `FREE` value, so it does not race with the others.
#[test]
fn after_a_stop_the_run_waits_for_memory_to_return() {
use std::sync::atomic::Ordering::SeqCst;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-settle-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 300, "f");
c.read_free = fake_free;
c.limits.min_start_free = 50;
c.limits.min_free = 0; // only the timeout stops the run
c.settle_bound = Duration::from_secs(5);
// Memory drops 100 ms in and returns 900 ms in; the timeout stop happens at about 300 ms.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
std::thread::sleep(Duration::from_millis(800));
FREE.store(90, SeqCst);
});
let r = execute(&c, None);
h.join().unwrap();
assert_eq!(r.class, Class::TimedOut);
let j = r.json.render();
assert!(j.contains("\"recovered_to_start_threshold\": true"), "{j}");
assert!(r.duration >= Duration::from_millis(300));
// Memory never returns: the wait gives up at the bound and says so.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
});
c.settle_bound = Duration::from_millis(400);
let t0 = Instant::now();
let r = execute(&c, None);
h.join().unwrap();
assert!(t0.elapsed() < Duration::from_secs(5));
assert!(
r.json
.render()
.contains("\"recovered_to_start_threshold\": false")
);
FREE.store(90, SeqCst);
}
#[test]
fn stopping_a_bottle_selects_it_through_wineprefix() {
use std::os::unix::fs::PermissionsExt;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stop-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let log = dir.join("wineserver.log");
let ws = dir.join("wineserver");
std::fs::write(
&ws,
format!(
"#!/bin/sh\necho \"args=$* WINEPREFIX=$WINEPREFIX\" > '{}'\n",
log.display()
),
)
.unwrap();
std::fs::set_permissions(&ws, std::fs::Permissions::from_mode(0o755)).unwrap();
stop_bottle(&dir.join("wine"), "my-bottle");
let got = std::fs::read_to_string(&log).unwrap();
assert!(got.contains("args=-k"), "{got}");
assert!(
got.contains("Bottles/my-bottle") || got.contains("/my-bottle"),
"{got}"
);
}
}
+82
View File
@@ -0,0 +1,82 @@
//! Probe Windows cross-compilers for original test programs (issue #364).
//!
//! Reports what is installed and what each compiler targets; it does not install anything.
use crate::cmdutil::run;
use crate::json::Json;
/// (name, kind). Order is the discovery order only, not a preference.
pub const CANDIDATES: &[&str] = &[
"aarch64-w64-mingw32-clang",
"x86_64-w64-mingw32-clang",
"x86_64-w64-mingw32-gcc",
"i686-w64-mingw32-gcc",
];
#[derive(Debug, Clone, PartialEq)]
pub struct Compiler {
pub name: String,
pub path: String,
pub version_line: Option<String>,
pub target_machine: Option<String>,
}
pub fn probe(search_path: &str) -> Vec<Compiler> {
CANDIDATES
.iter()
.filter_map(|name| {
let path = search_path
.split(':')
.map(|d| std::path::Path::new(d).join(name))
.find(|p| p.is_file())?;
let p = path.to_str()?.to_string();
Some(Compiler {
name: name.to_string(),
version_line: run(&p, &["--version"])
.and_then(|s| s.lines().next().map(String::from)),
target_machine: run(&p, &["-dumpmachine"]),
path: p,
})
})
.collect()
}
impl Compiler {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("name", Json::str(self.name.clone())),
("path", Json::str(self.path.clone())),
("version", Json::opt_str(self.version_line.clone())),
("target_machine", Json::opt_str(self.target_machine.clone())),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_path_finds_nothing() {
assert!(probe("").is_empty());
assert!(probe("/nonexistent-dir").is_empty());
}
#[test]
fn finds_a_stub_compiler_and_reports_its_output() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("bxhybrid-tc-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let f = dir.join("x86_64-w64-mingw32-gcc");
std::fs::write(&f, "#!/bin/sh\nif [ \"$1\" = -dumpmachine ]; then echo x86_64-w64-mingw32; else echo stub 1.0; fi\n").unwrap();
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
let found = probe(dir.to_str().unwrap());
assert_eq!(found.len(), 1);
assert_eq!(
found[0].target_machine.as_deref(),
Some("x86_64-w64-mingw32")
);
assert_eq!(found[0].version_line.as_deref(), Some("stub 1.0"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+7
View File
@@ -71,6 +71,13 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
"api-ms-win-crt-filesystem-l1-1-0.dll",
"api-ms-win-crt-locale-l1-1-0.dll",
"api-ms-win-crt-environment-l1-1-0.dll",
// The API set a program built with the mingw-w64 UCRT runtime
// imports `memcpy` and `__C_specific_handler` from. That it
// forwards to ucrtbase.dll is inferred from its name and from
// Microsoft's "Universal CRT deployment" page, which says the
// Universal CRT ships as ucrtbase.dll plus `api-ms-win-*.dll`
// forwarders. No document naming this set was found.
"api-ms-win-crt-private-l1-1-0.dll",
],
_ => &[],
}
+782 -5
View File
@@ -5,10 +5,18 @@
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
//! document (format version 1). The text output does not change. Values the
//! benchmark cannot determine, such as the git revision outside a checkout,
//! are written as `null`.
//! are written as `null`. The benchmark cannot see build settings such as LTO,
//! so `XENORA_DBT_BENCH_BUILD_LABEL=<text>` records a label of your choosing
//! for them.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! Set `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` to compare
//! two such documents instead of running the benchmark. The comparison is
//! refused, with exit status 1, unless both runs used the same host, workload,
//! build settings and sample counts.
//!
//! 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.
@@ -154,6 +162,7 @@ struct RunInfo {
revision: Option<String>,
dirty: Option<bool>,
debug_assertions: bool,
build_label: Option<String>,
guest_code_bytes: usize,
warmup: usize,
}
@@ -187,6 +196,7 @@ fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
.map(|status| !status.is_empty()),
debug_assertions: cfg!(debug_assertions),
build_label: non_empty(std::env::var("XENORA_DBT_BENCH_BUILD_LABEL").ok()),
guest_code_bytes,
warmup,
}
@@ -274,7 +284,10 @@ fn json_document(
),
(
"build",
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
json_object(&[
("debug_assertions", info.debug_assertions.to_string()),
("label", json_option(info.build_label.as_ref(), string)),
]),
),
(
"workload",
@@ -319,7 +332,471 @@ fn json_document(
])
}
/// A parsed JSON value. Numbers keep their source text, so integers compare exactly.
#[derive(Clone, Debug, PartialEq)]
enum Json {
Null,
Bool(bool),
Number(String),
String(String),
Array(Vec<Json>),
Object(Vec<(String, Json)>),
}
impl Json {
/// The value at a dotted path such as `host.cpu`, if every step is an object key.
fn get(&self, path: &str) -> Option<&Json> {
path.split('.').try_fold(self, |value, key| match value {
Json::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
})
}
}
const MAX_JSON_DEPTH: usize = 32;
/// Reads one JSON document (RFC 8259) and rejects anything after it.
fn parse_json(text: &str) -> Result<Json, String> {
let mut reader = JsonReader {
bytes: text.as_bytes(),
pos: 0,
};
let value = reader.value(0)?;
reader.skip_whitespace();
if reader.pos != reader.bytes.len() {
return reader.error("unexpected data after the document");
}
Ok(value)
}
struct JsonReader<'a> {
bytes: &'a [u8],
pos: usize,
}
impl JsonReader<'_> {
fn error<T>(&self, what: &str) -> Result<T, String> {
Err(format!("{what} at byte {}", self.pos))
}
fn peek(&self) -> Option<u8> {
self.bytes.get(self.pos).copied()
}
fn skip_whitespace(&mut self) {
while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
self.pos += 1;
}
}
fn expect(&mut self, byte: u8) -> Result<(), String> {
if self.peek() == Some(byte) {
self.pos += 1;
Ok(())
} else {
self.error(&format!("expected '{}'", byte as char))
}
}
fn value(&mut self, depth: usize) -> Result<Json, String> {
if depth > MAX_JSON_DEPTH {
return self.error("nesting too deep");
}
self.skip_whitespace();
match self.peek() {
None => self.error("unexpected end of input"),
Some(b'n') => self.literal("null", Json::Null),
Some(b't') => self.literal("true", Json::Bool(true)),
Some(b'f') => self.literal("false", Json::Bool(false)),
Some(b'"') => Ok(Json::String(self.string()?)),
Some(b'[') => self.array(depth),
Some(b'{') => self.object(depth),
Some(b'-' | b'0'..=b'9') => self.number(),
Some(_) => self.error("unexpected character"),
}
}
fn literal(&mut self, word: &str, value: Json) -> Result<Json, String> {
if self.bytes[self.pos..].starts_with(word.as_bytes()) {
self.pos += word.len();
Ok(value)
} else {
self.error("invalid literal")
}
}
fn array(&mut self, depth: usize) -> Result<Json, String> {
self.expect(b'[')?;
let mut items = Vec::new();
self.skip_whitespace();
if self.peek() == Some(b']') {
self.pos += 1;
return Ok(Json::Array(items));
}
loop {
items.push(self.value(depth + 1)?);
self.skip_whitespace();
match self.peek() {
Some(b',') => self.pos += 1,
Some(b']') => {
self.pos += 1;
return Ok(Json::Array(items));
}
_ => return self.error("expected ',' or ']'"),
}
}
}
fn object(&mut self, depth: usize) -> Result<Json, String> {
self.expect(b'{')?;
let mut fields: Vec<(String, Json)> = Vec::new();
self.skip_whitespace();
if self.peek() == Some(b'}') {
self.pos += 1;
return Ok(Json::Object(fields));
}
loop {
self.skip_whitespace();
let key = self.string()?;
if fields.iter().any(|(k, _)| *k == key) {
return self.error(&format!("duplicate key `{key}`"));
}
self.skip_whitespace();
self.expect(b':')?;
let value = self.value(depth + 1)?;
fields.push((key, value));
self.skip_whitespace();
match self.peek() {
Some(b',') => self.pos += 1,
Some(b'}') => {
self.pos += 1;
return Ok(Json::Object(fields));
}
_ => return self.error("expected ',' or '}'"),
}
}
}
fn digits(&mut self) -> usize {
let start = self.pos;
while matches!(self.peek(), Some(b'0'..=b'9')) {
self.pos += 1;
}
self.pos - start
}
fn number(&mut self) -> Result<Json, String> {
let start = self.pos;
if self.peek() == Some(b'-') {
self.pos += 1;
}
match self.peek() {
Some(b'0') => self.pos += 1,
Some(b'1'..=b'9') => {
self.digits();
}
_ => return self.error("invalid number"),
}
if self.peek() == Some(b'.') {
self.pos += 1;
if self.digits() == 0 {
return self.error("invalid number");
}
}
if matches!(self.peek(), Some(b'e' | b'E')) {
self.pos += 1;
if matches!(self.peek(), Some(b'+' | b'-')) {
self.pos += 1;
}
if self.digits() == 0 {
return self.error("invalid number");
}
}
// Only ASCII digits and signs were consumed.
Ok(Json::Number(
String::from_utf8_lossy(&self.bytes[start..self.pos]).into_owned(),
))
}
fn hex4(&mut self) -> Result<u32, String> {
let digits = self.bytes.get(self.pos..self.pos + 4);
let value = digits
.and_then(|d| std::str::from_utf8(d).ok())
.and_then(|d| u32::from_str_radix(d, 16).ok());
match value {
Some(value) if digits.is_some_and(|d| d.iter().all(u8::is_ascii_hexdigit)) => {
self.pos += 4;
Ok(value)
}
_ => self.error("invalid \\u escape"),
}
}
fn unicode_escape(&mut self) -> Result<char, String> {
let first = self.hex4()?;
let code = match first {
0xD800..=0xDBFF => {
if !self.bytes[self.pos..].starts_with(b"\\u") {
return self.error("unpaired surrogate");
}
self.pos += 2;
let second = self.hex4()?;
if !(0xDC00..=0xDFFF).contains(&second) {
return self.error("unpaired surrogate");
}
0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00)
}
0xDC00..=0xDFFF => return self.error("unpaired surrogate"),
code => code,
};
char::from_u32(code).map_or_else(|| self.error("invalid code point"), Ok)
}
fn string(&mut self) -> Result<String, String> {
self.expect(b'"')?;
let mut out = String::new();
loop {
// Copy the run up to the next quote, backslash or control byte. Those
// are ASCII, so the run never ends inside a multi-byte character.
let start = self.pos;
while matches!(self.peek(), Some(b) if b != b'"' && b != b'\\' && b >= 0x20) {
self.pos += 1;
}
match std::str::from_utf8(&self.bytes[start..self.pos]) {
Ok(run) => out.push_str(run),
Err(_) => return self.error("invalid UTF-8"),
}
match self.peek() {
Some(b'"') => {
self.pos += 1;
return Ok(out);
}
Some(b'\\') => {
self.pos += 1;
let escaped = self.peek();
self.pos += 1;
out.push(match escaped {
Some(b'"') => '"',
Some(b'\\') => '\\',
Some(b'/') => '/',
Some(b'b') => '\u{8}',
Some(b'f') => '\u{c}',
Some(b'n') => '\n',
Some(b'r') => '\r',
Some(b't') => '\t',
Some(b'u') => self.unicode_escape()?,
_ => {
self.pos -= 1;
return self.error("invalid escape");
}
});
}
Some(_) => return self.error("control character in string"),
None => return self.error("unterminated string"),
}
}
}
}
/// Fields that must be equal for two runs to be compared. A field listed in
/// `OPTIONAL_FIELDS` counts as `null` when a document does not have it.
const MATCHING_FIELDS: [&str; 15] = [
"format_version",
"benchmark",
"host.cpu",
"host.os",
"host.arch",
"build.debug_assertions",
"build.label",
"workload.name",
"workload.guest_instructions",
"workload.guest_code_bytes",
"workload.instruction_budget",
"workload.warmup_rounds",
"timings.interpreter.samples",
"timings.cold_dbt.samples",
"timings.warm_dbt.samples",
];
/// Older version 1 documents predate the build label.
const OPTIONAL_FIELDS: [&str; 1] = ["build.label"];
/// Host fields that must be known: two unknown CPUs are not the same CPU.
const KNOWN_FIELDS: [&str; 3] = ["host.cpu", "host.os", "host.arch"];
const SERIES: [(&str, &str); 3] = [
("interpreter", "Interpreter"),
("cold_dbt", "Cold DBT"),
("warm_dbt", "Warm DBT"),
];
const COUNTERS: [&str; 8] = [
"blocks_compiled",
"cache_hits",
"cache_misses",
"native_bytes_emitted",
"dbt_dispatches",
"instructions_executed",
"interpreter_fallbacks",
"service_calls",
];
fn field<'a>(doc: &'a Json, path: &str) -> Result<&'a Json, String> {
match doc.get(path) {
Some(value) => Ok(value),
None if OPTIONAL_FIELDS.contains(&path) => Ok(&Json::Null),
None => Err(format!("missing field `{path}`")),
}
}
fn integer(doc: &Json, path: &str) -> Result<u128, String> {
match field(doc, path)? {
Json::Number(text) => text
.parse()
.map_err(|_| format!("`{path}` is not a non-negative integer")),
_ => Err(format!("`{path}` is not a number")),
}
}
fn text(doc: &Json, path: &str) -> String {
match doc.get(path) {
Some(Json::String(value)) => value.clone(),
Some(Json::Bool(value)) => value.to_string(),
Some(Json::Number(value)) => value.clone(),
// The build label is optional, so its absence is not an unknown value.
_ if OPTIONAL_FIELDS.contains(&path) => "none".to_owned(),
_ => "unknown".to_owned(),
}
}
fn duration(ns: u128) -> Duration {
Duration::from_nanos(u64::try_from(ns).unwrap_or(u64::MAX))
}
fn change(before: u128, after: u128) -> String {
if before == 0 {
return "n/a".to_owned();
}
format!(
"{:+.2}%",
(after as f64 - before as f64) / before as f64 * 100.0
)
}
fn source(doc: &Json) -> String {
let dirty = match doc.get("source.dirty") {
Some(Json::Bool(true)) => " with local changes",
Some(Json::Bool(false)) => "",
_ => ", local changes unknown",
};
format!("{}{dirty}", text(doc, "source.revision"))
}
/// Compares two exported documents. Returns the report lines, or why the runs
/// cannot be compared.
fn compare_documents(baseline: &Json, candidate: &Json) -> Result<Vec<String>, String> {
for doc in [baseline, candidate] {
if field(doc, "format_version")? != &Json::Number("1".to_owned()) {
return Err("only format version 1 is supported".to_owned());
}
}
for path in KNOWN_FIELDS {
for (name, doc) in [("baseline", baseline), ("candidate", candidate)] {
if field(doc, path)? == &Json::Null {
return Err(format!(
"`{path}` is unknown in the {name}, so the hosts cannot be shown to match"
));
}
}
}
for path in MATCHING_FIELDS {
if field(baseline, path)? != field(candidate, path)? {
return Err(format!(
"`{path}` differs: baseline {}, candidate {}",
text(baseline, path),
text(candidate, path)
));
}
}
let mut lines = vec![
format!("Baseline: {}", source(baseline)),
format!("Candidate: {}", source(candidate)),
format!(
"Host: {}, {} {}; debug assertions {}; build label {}",
text(baseline, "host.cpu"),
text(baseline, "host.os"),
text(baseline, "host.arch"),
text(baseline, "build.debug_assertions"),
text(baseline, "build.label"),
),
];
if field(baseline, "host.os_version")? != field(candidate, "host.os_version")? {
lines.push(format!(
"Note: OS version differs: baseline {}, candidate {}",
text(baseline, "host.os_version"),
text(candidate, "host.os_version")
));
}
for (key, label) in SERIES {
let path = |stat: &str| format!("timings.{key}.{stat}");
let before = integer(baseline, &path("median_ns"))?;
let after = integer(candidate, &path("median_ns"))?;
let spread = integer(baseline, &path("iqr_ns"))?.max(integer(candidate, &path("iqr_ns"))?);
let verdict = if before.abs_diff(after) > spread {
"larger than"
} else {
"within"
};
lines.push(format!(
"{label}: median {:?} -> {:?} ({}), {verdict} the larger IQR {:?}",
duration(before),
duration(after),
change(before, after),
duration(spread)
));
}
let mut counters_changed = false;
for counter in COUNTERS {
let path = format!("cold_dbt_metrics.{counter}");
let (before, after) = (integer(baseline, &path)?, integer(candidate, &path)?);
if before != after {
counters_changed = true;
lines.push(format!(
"Cold DBT {counter}: {before} -> {after} ({})",
change(before, after)
));
}
}
if !counters_changed {
lines.push("Cold DBT counters are identical".to_owned());
}
Ok(lines)
}
fn compare_files(spec: &str) -> Result<Vec<String>, String> {
let (baseline, candidate) = spec
.split_once(',')
.ok_or("expected <baseline.json>,<candidate.json>")?;
let read = |path: &str| {
let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
parse_json(&text).map_err(|e| format!("{path}: {e}"))
};
compare_documents(&read(baseline)?, &read(candidate)?)
}
fn main() {
if let Ok(spec) = std::env::var("XENORA_DBT_BENCH_COMPARE") {
match compare_files(&spec) {
Ok(lines) => lines.iter().for_each(|line| println!("{line}")),
Err(reason) => {
eprintln!("dbt_bench: cannot compare: {reason}");
std::process::exit(1);
}
}
return;
}
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
assert!(sample_count > 0);
@@ -494,6 +971,7 @@ mod tests {
revision: Some("0123abcd".to_owned()),
dirty: Some(false),
debug_assertions: false,
build_label: Some("fat-lto".to_owned()),
guest_code_bytes: 40_011,
warmup: 10,
}
@@ -505,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,
@@ -528,7 +1007,7 @@ mod tests {
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
r#""build":{{"debug_assertions":false}},"#,
r#""build":{{"debug_assertions":false,"label":"fat-lto"}},"#,
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
@@ -580,4 +1059,302 @@ mod tests {
assert_eq!(s.iqr, Duration::from_micros(30));
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
}
// `cargo bench` builds this target with `--cfg test` but without `--test`,
// so this module is compiled with its #[test] functions removed and shared
// helpers look unused there.
#[allow(dead_code)]
fn comparable_document() -> super::Json {
super::parse_json(concat!(
r#"{"format_version":1,"benchmark":"dbt_bench","unix_time":1,"#,
r#""host":{"cpu":"Apple M5","os":"macos","os_version":"27.2.1","arch":"aarch64"},"#,
r#""source":{"revision":"aaaa","dirty":false},"#,
r#""build":{"debug_assertions":false,"label":null},"#,
r#""workload":{"name":"add_rax_chain","guest_instructions":10002,"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10},"#,
r#""timings":{"#,
r#""interpreter":{"samples":101,"median_ns":900000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":20000,"median_mips":11.1},"#,
r#""cold_dbt":{"samples":101,"median_ns":1100000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":40000,"median_mips":9.1},"#,
r#""warm_dbt":{"samples":101,"median_ns":22000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":500,"median_mips":454.6}},"#,
r#""cold_dbt_metrics":{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":0,"service_calls":0}}"#,
))
.expect("fixture parses")
}
/// Replaces the value at a dotted path, which must exist except for its last key.
#[allow(dead_code)]
fn set(doc: &mut super::Json, path: &str, value: super::Json) {
let (parent, key) = path.rsplit_once('.').map_or(("", path), |(p, k)| (p, k));
let mut node = doc;
for step in parent.split('.').filter(|s| !s.is_empty()) {
let super::Json::Object(fields) = node else {
panic!("{step} is not in an object")
};
node = &mut fields.iter_mut().find(|(k, _)| k == step).expect(step).1;
}
let super::Json::Object(fields) = node else {
panic!("{path} has no parent object")
};
match fields.iter_mut().find(|(k, _)| k == key) {
Some(entry) => entry.1 = value,
None => fields.push((key.to_owned(), value)),
}
}
#[test]
fn reader_accepts_json_values() {
use super::{Json, parse_json};
let doc = parse_json(
r#" { "a" : [1, -0.5, 2e3, 3E-2, true, false, null, {}, []], "s": "q\"b\\s\/n\n\té😀 Zażółć" } "#,
)
.unwrap();
assert_eq!(
doc.get("a"),
Some(&Json::Array(vec![
Json::Number("1".to_owned()),
Json::Number("-0.5".to_owned()),
Json::Number("2e3".to_owned()),
Json::Number("3E-2".to_owned()),
Json::Bool(true),
Json::Bool(false),
Json::Null,
Json::Object(vec![]),
Json::Array(vec![]),
]))
);
assert_eq!(
doc.get("s"),
Some(&Json::String("q\"b\\s/n\n\té😀 Zażółć".to_owned()))
);
assert_eq!(doc.get("a.b"), None);
assert_eq!(doc.get("missing"), None);
}
#[test]
fn reader_rejects_malformed_json() {
use super::parse_json;
let deep = "[".repeat(40) + &"]".repeat(40);
for bad in [
"",
"{",
r#"{"a":1,}"#,
r#"{"a" 1}"#,
r#"{"a":1,"a":2}"#,
"[1 2]",
"01",
"1.",
"-",
"1e",
"+1",
"tru",
r#""open"#,
"\"tab\tinside\"",
r#""\x""#,
r#""\u12g4""#,
r#""\u+123""#,
r#""\ud83d""#,
r#""\ude00""#,
r#""\ud83dA""#,
"{} {}",
deep.as_str(),
] {
assert!(parse_json(bad).is_err(), "accepted {bad:?}");
}
}
#[test]
fn exported_document_reads_back() {
use super::{DbtMetrics, Duration, Json, RunInfo, Summary, json_document, parse_json};
let summary = Summary {
samples: 7,
median: Duration::from_nanos(1_234_567),
min: Duration::from_nanos(1),
max: Duration::from_nanos(9),
p95: Duration::from_nanos(8),
p99: Duration::from_nanos(9),
iqr: Duration::from_nanos(3),
mips: 8.25,
};
let info = RunInfo {
unix_time: None,
cpu: Some("CPU \"x\" \\ \u{1}".to_owned()),
os: "macos",
os_version: None,
arch: "aarch64",
revision: None,
dirty: Some(true),
debug_assertions: true,
build_label: Some("é label".to_owned()),
guest_code_bytes: 5,
warmup: 2,
};
let metrics = DbtMetrics {
native_bytes_emitted: 42,
..DbtMetrics::default()
};
let doc = parse_json(&json_document(
&info, &summary, &summary, &summary, &metrics,
))
.unwrap();
let string = |s: &str| Some(Json::String(s.to_owned()));
assert_eq!(doc.get("host.cpu").cloned(), string("CPU \"x\" \\ \u{1}"));
assert_eq!(doc.get("build.label").cloned(), string("é label"));
assert_eq!(doc.get("host.os_version"), Some(&Json::Null));
assert_eq!(doc.get("source.dirty"), Some(&Json::Bool(true)));
assert_eq!(
doc.get("timings.cold_dbt.median_ns"),
Some(&Json::Number("1234567".to_owned()))
);
assert_eq!(
doc.get("cold_dbt_metrics.native_bytes_emitted"),
Some(&Json::Number("42".to_owned()))
);
}
#[test]
fn comparison_reports_changes_against_the_spread() {
use super::{Json, compare_documents};
let baseline = comparable_document();
let mut candidate = comparable_document();
set(
&mut candidate,
"source.revision",
Json::String("bbbb".to_owned()),
);
set(&mut candidate, "source.dirty", Json::Bool(true));
// 900 µs -> 846 µs is 54 µs, beyond the larger IQR of 20 µs.
set(
&mut candidate,
"timings.interpreter.median_ns",
Json::Number("846000".to_owned()),
);
// 1.1 ms -> 1.12 ms is 20 µs, within the larger IQR of 45 µs.
set(
&mut candidate,
"timings.cold_dbt.median_ns",
Json::Number("1120000".to_owned()),
);
set(
&mut candidate,
"timings.cold_dbt.iqr_ns",
Json::Number("45000".to_owned()),
);
set(
&mut candidate,
"cold_dbt_metrics.native_bytes_emitted",
Json::Number("290184".to_owned()),
);
set(
&mut candidate,
"host.os_version",
Json::String("27.3".to_owned()),
);
let lines = compare_documents(&baseline, &candidate).unwrap();
assert_eq!(
lines,
[
"Baseline: aaaa",
"Candidate: bbbb with local changes",
"Host: Apple M5, macos aarch64; debug assertions false; build label none",
"Note: OS version differs: baseline 27.2.1, candidate 27.3",
"Interpreter: median 900µs -> 846µs (-6.00%), larger than the larger IQR 20µs",
"Cold DBT: median 1.1ms -> 1.12ms (+1.82%), within the larger IQR 45µs",
"Warm DBT: median 22µs -> 22µs (+0.00%), within the larger IQR 500ns",
"Cold DBT native_bytes_emitted: 245168 -> 290184 (+18.36%)",
]
);
let same = compare_documents(&baseline, &baseline).unwrap();
assert_eq!(same.last().unwrap(), "Cold DBT counters are identical");
}
#[test]
fn comparison_rejects_every_mismatching_field() {
use super::{Json, compare_documents};
// Written out independently of MATCHING_FIELDS, so dropping a field
// there fails this test.
for path in [
"format_version",
"benchmark",
"host.cpu",
"host.os",
"host.arch",
"build.debug_assertions",
"build.label",
"workload.name",
"workload.guest_instructions",
"workload.guest_code_bytes",
"workload.instruction_budget",
"workload.warmup_rounds",
"timings.interpreter.samples",
"timings.cold_dbt.samples",
"timings.warm_dbt.samples",
] {
let mut candidate = comparable_document();
let other = match path {
"build.debug_assertions" => Json::Bool(true),
"build.label" => Json::String("fat-lto".to_owned()),
// A valid but different version is refused as unsupported first.
"format_version" => Json::Number("2".to_owned()),
p if p.contains("samples")
|| p.starts_with("workload.") && p != "workload.name" =>
{
Json::Number("7".to_owned())
}
_ => Json::String("other".to_owned()),
};
set(&mut candidate, path, other);
let error = compare_documents(&comparable_document(), &candidate).expect_err(path);
assert!(
error.contains(path) || path == "format_version" && error.contains("version"),
"{path}: {error}"
);
}
}
#[test]
fn comparison_needs_known_hosts_and_matching_labels() {
use super::{Json, compare_documents};
for path in ["host.cpu", "host.os", "host.arch"] {
let mut unknown = comparable_document();
set(&mut unknown, path, Json::Null);
let error = compare_documents(&unknown, &unknown).expect_err(path);
assert!(error.contains("unknown in the baseline"), "{error}");
}
// A document written before the label existed counts as having no label.
let mut old = comparable_document();
let Json::Object(fields) = &mut old else {
unreachable!()
};
let build = &mut fields.iter_mut().find(|(k, _)| k == "build").unwrap().1;
let Json::Object(build) = build else {
unreachable!()
};
build.retain(|(k, _)| k != "label");
assert!(compare_documents(&old, &comparable_document()).is_ok());
let mut labelled = comparable_document();
set(
&mut labelled,
"build.label",
Json::String("fat-lto".to_owned()),
);
assert!(compare_documents(&old, &labelled).is_err());
assert!(compare_documents(&labelled, &labelled).is_ok());
let mut missing = comparable_document();
let Json::Object(fields) = &mut missing else {
unreachable!()
};
fields.retain(|(k, _)| k != "workload");
let error = compare_documents(&comparable_document(), &missing).unwrap_err();
assert!(error.contains("missing field `workload.name`"), "{error}");
}
}
+12 -4
View File
@@ -7,9 +7,9 @@
differs. Never writes.
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
forms sharing an opcode, operand constraints that contradict each other, LOCK
on a form that cannot write memory, and flags declared both written and
undefined. Standard library only (Python 3.11+).
forms sharing an opcode, operand constraints that contradict each other, a
fixed r/m field on a form that could take memory, LOCK on a form that cannot
write memory, and flags declared both written and undefined. Standard library only (Python 3.11+).
"""
import sys
@@ -27,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
"memory_only", "register_only", "rm", "no_rex_b", "unaligned", "lock"}
GROUP_KEYS = {"map", "opcodes", "digits"}
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
@@ -169,6 +169,13 @@ def load(text):
fail(f"{where}: memory_only and register_only contradict")
if (form.get("memory_only") or form.get("register_only")) and not modrm:
fail(f"{where}: operand restriction without ModRM")
form.setdefault("rm", None)
if form["rm"] is not None:
# bool is an int in Python; `rm = true` is not a field value.
if type(form["rm"]) is not int or not 0 <= form["rm"] <= 7:
fail(f"{where}: rm must be a ModRM r/m field value 0-7")
if not form.get("register_only") or form["digit"] is None:
fail(f"{where}: a fixed r/m field needs register_only and a digit")
sourced = form["enc"] in XMM_RM or form["enc"] == "xmm_gpr_imm"
if sourced != bool(form["src"]) and form["enc"] not in ("reg_rm", "rm"):
fail(f"{where}: source size does not match the encoding")
@@ -273,6 +280,7 @@ def generate(operations, forms):
f"source: {SRCS[form['src']]}, has_modrm: {str(ENCS[form['enc']][1]).lower()}, "
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
f"fixed_rm: {'None' if form['rm'] is None else 'Some(%d)' % form['rm']}, "
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
+235
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
@@ -132,6 +219,51 @@ service kernel32.dll SetLastError(code: u32) -> void
ref errhandlingapi.h SetLastError
test last_error_is_set_by_failures_and_by_the_guest
# What a hosted C program's startup code hands to `main`. The three pointer
# functions and the two initialization functions are listed by Microsoft only
# by name; crates/loader/src/services/crt_arguments.rs says what is documented,
# inferred and Xenora's choice.
service ucrtbase.dll __p___argc() -> ptr
handler argc_pointer
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails stops the guest when the variable cannot be allocated
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
test program_arguments_reach_the_guest_as_argc_and_argv
service ucrtbase.dll __p___argv() -> ptr
handler argv_pointer
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails stops the guest when the variable cannot be allocated
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
test program_arguments_reach_the_guest_as_argc_and_argv
service ucrtbase.dll __p__environ() -> ptr
handler environ_pointer
status partial
alias api-ms-win-crt-environment-l1-1-0.dll
fails stops the guest when the variable cannot be allocated
ref Microsoft Learn, C runtime library reference, _environ, _wenviron
test the_environment_table_is_empty_and_ends_with_a_null_pointer
service ucrtbase.dll _configure_narrow_argv(mode: i32) -> i32
handler configure_narrow_argv
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated
ref corecrt_startup.h _configure_narrow_argv
test program_arguments_reach_the_guest_as_argc_and_argv
service ucrtbase.dll _initialize_narrow_environment() -> i32
handler initialize_narrow_environment
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails stops the guest when the table cannot be allocated
ref corecrt_startup.h _initialize_narrow_environment
test the_environment_table_is_empty_and_ends_with_a_null_pointer
service kernel32.dll VirtualAlloc(address: ptr, size: u64, kind: u32, protect: u32) -> ptr
handler virtual_alloc
status partial
@@ -148,6 +280,34 @@ service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32
ref memoryapi.h VirtualFree
test virtual_memory_is_mapped_released_and_bounded
# Stubs. A program built with the mingw-w64 runtime imports these three and
# does not call them on a normal run. They exist so that its imports bind. A
# call stops the guest with the runtime-limit fault and changes nothing.
service kernel32.dll VirtualProtect(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32
handler virtual_protect
status stub
alias api-ms-win-core-memory-l1-1-0.dll
fails always: stops the guest with the runtime-limit fault; no protection changes
ref memoryapi.h VirtualProtect
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
service kernel32.dll VirtualQuery(address: ptr, information: out<48>, length: u64) -> u64
handler virtual_query
status stub
alias api-ms-win-core-memory-l1-1-0.dll
fails always: stops the guest with the runtime-limit fault; nothing is written
ref memoryapi.h VirtualQuery
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
service ucrtbase.dll __C_specific_handler(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32
handler c_specific_handler
status stub
alias api-ms-win-crt-private-l1-1-0.dll
fails always: stops the guest with the runtime-limit fault; no exception is dispatched
ref Microsoft Learn, x64 exception handling, language-specific handler
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
service ucrtbase.dll sqrt(x: f64) -> f64
handler sqrt
status partial
@@ -179,3 +339,78 @@ service ucrtbase.dll fabsf(x: f32) -> f32
fails never
ref math.h fabsf (ISO C, IEC 60559 abs)
test floating_arguments_and_results_use_xmm_registers
# What a C program's startup code configures before `main`. Each value is
# recorded and returned as documented; nothing in the runtime acts on it.
service ucrtbase.dll _set_app_type(kind: i32) -> void
handler set_app_type
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails never
ref corecrt_startup.h _set_app_type
test crt_app_type_and_math_error_handler_are_recorded
service ucrtbase.dll _set_new_mode(mode: i32) -> i32
handler set_new_mode
status partial
alias api-ms-win-crt-heap-l1-1-0.dll
fails -1 with errno EINVAL for a mode other than 0 or 1
ref new.h _set_new_mode
test crt_startup_modes_return_the_previous_setting
service ucrtbase.dll _configthreadlocale(request: i32) -> i32
handler configure_thread_locale
status partial
alias api-ms-win-crt-locale-l1-1-0.dll
fails -1 with errno EINVAL for a request other than 0, 1 or 2
ref locale.h _configthreadlocale
test crt_startup_modes_return_the_previous_setting
service ucrtbase.dll __setusermatherr(handler: ptr) -> void
handler set_user_math_error
status partial
alias api-ms-win-crt-math-l1-1-0.dll
fails never
ref corecrt_startup.h __setusermatherr
test crt_app_type_and_math_error_handler_are_recorded
service ucrtbase.dll _set_invalid_parameter_handler(handler: ptr) -> ptr
handler set_invalid_parameter_handler
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails never
ref stdlib.h _set_invalid_parameter_handler
test crt_startup_handlers_return_the_previous_handler
service ucrtbase.dll __p__fmode() -> ptr
handler file_mode_pointer
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails stops the guest when the variable cannot be allocated
ref Microsoft Learn, C runtime library reference, __p__fmode
test crt_file_mode_variables_are_guest_memory
service ucrtbase.dll __p__commode() -> ptr
handler commit_mode_pointer
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails stops the guest when the variable cannot be allocated
ref Microsoft Learn, C runtime library reference, __p__commode
test crt_file_mode_variables_are_guest_memory
service ucrtbase.dll signal(signal: i32, handler: ptr) -> ptr
handler signal
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails SIG_ERR with errno EINVAL for a signal the documentation does not list
ref signal.h signal
test crt_startup_handlers_return_the_previous_handler
service kernel32.dll SetUnhandledExceptionFilter(filter: ptr) -> ptr
handler set_unhandled_exception_filter
status partial
alias api-ms-win-core-errorhandling-l1-1-0.dll
fails never
ref errhandlingapi.h SetUnhandledExceptionFilter
test crt_startup_handlers_return_the_previous_handler
+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}"
);
+54 -2
View File
@@ -85,6 +85,36 @@ impl Default for Mxcsr {
}
}
/// x87 FPU control, status and tag words.
///
/// FNINIT is the only instruction that writes them and nothing reads them yet.
/// The x87 data registers and every other x87 instruction are not modelled.
/// The host's floating-point state is never involved.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct X87State {
pub control: u16,
pub status: u16,
pub tag: u16,
}
impl X87State {
/// What FINIT and FNINIT set (Intel SDM Vol. 2A, "FINIT/FNINIT"; Vol. 1,
/// 8.1.3 to 8.1.7): every exception masked, 64-bit precision, round to
/// nearest; no flag, top of stack 0; every register tagged empty.
pub const INIT: Self = Self {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
}
impl Default for X87State {
fn default() -> Self {
Self::INIT
}
}
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
#[repr(C)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -99,6 +129,9 @@ pub struct CpuState {
pub mxcsr: Mxcsr,
/// Direction flag: string instructions step RSI and RDI down when set.
pub df: bool,
/// Starts as FNINIT leaves it. The value an operating system gives a new
/// thread is not modelled.
pub x87: X87State,
}
impl CpuState {
@@ -114,6 +147,7 @@ impl CpuState {
xmm: [0; 16],
mxcsr: Mxcsr::default(),
df: false,
x87: X87State::INIT,
}
}
@@ -130,6 +164,8 @@ impl CpuState {
pub const CPUID_CMOV: u32 = 1 << 15;
/// CPUID leaf 1, ECX: POPCNT.
pub const CPUID_POPCNT: u32 = 1 << 23;
/// CPUID leaf 0x8000_0001, ECX: LAHF and SAHF in 64-bit mode.
pub const CPUID_LAHF_SAHF: u32 = 1;
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
pub const CPUID_LZCNT: u32 = 1 << 5;
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
@@ -150,7 +186,7 @@ pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
// Highest extended leaf.
0x8000_0000 => [0x8000_0001, 0, 0, 0],
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
0x8000_0001 => [0, 0, CPUID_LAHF_SAHF | CPUID_LZCNT, CPUID_LONG_MODE],
_ => [0; 4],
}
}
@@ -212,7 +248,21 @@ impl std::error::Error for ExitReason {}
#[cfg(test)]
mod layout_tests {
use super::{CpuState, RFlags, Register};
use super::{CpuState, RFlags, Register, X87State};
/// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation.
#[test]
fn a_new_guest_starts_with_the_x87_words_fninit_sets() {
let init = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
assert_eq!(X87State::INIT, init);
assert_eq!(X87State::default(), init);
assert_eq!(CpuState::default().x87, init);
assert_eq!(CpuState::new(0x1000, 0x2000).x87, init);
}
/// The native translator addresses guest registers and RIP by raw byte
/// offset. Keep these assertions next to the struct so a layout change
@@ -483,6 +533,8 @@ impl From<DecodeError<MemoryError>> for ExitReason {
match error {
DecodeError::Fetch(fault) => Self::MemoryFault(fault),
DecodeError::Unsupported(byte) => Self::IllegalInstruction(byte),
// Intel SDM Vol. 3A, 7.15: exceeding the 15-byte limit is #GP(0).
DecodeError::TooLong => Self::GeneralProtection,
}
}
}
+281 -18
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]>>,
@@ -184,7 +218,9 @@ impl DbtEngine {
if block_limit > 1
&& matches!(
block,
Err(ExitReason::IllegalInstruction(_) | ExitReason::MemoryFault(_))
Err(ExitReason::IllegalInstruction(_)
| ExitReason::MemoryFault(_)
| ExitReason::GeneralProtection)
)
{
block = self.get_or_compile_block(cpu.rip, memory, 1);
@@ -243,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(
@@ -270,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);
@@ -349,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,
})
}
}
@@ -1567,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 = [
+24 -15
View File
@@ -120,10 +120,11 @@ pub enum GraphicsError {
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
InvalidIndexFormat(u32),
/// An indexed draw reads past its index buffer or fetches a vertex,
/// after applying the base vertex, outside its vertex buffer.
/// after applying the base vertex, outside its vertex buffer, or a flat
/// draw reads its vertices outside the vertex buffer.
IndexOutOfRange,
/// A descriptor heap, view, sampler, root signature or binding outside
/// the supported texture-binding subset. Nothing is drawn.
/// A descriptor heap, view, sampler, root signature, binding or draw
/// outside the supported subset. Nothing is drawn.
Unsupported(&'static str),
}
@@ -151,8 +152,8 @@ impl std::fmt::Display for GraphicsError {
Self::InvalidIndexFormat(format) => {
write!(f, "unsupported index buffer format {format}")
}
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
Self::Unsupported(what) => write!(f, "unsupported texture binding: {what}"),
Self::IndexOutOfRange => write!(f, "draw outside its index or vertex buffer"),
Self::Unsupported(what) => write!(f, "unsupported graphics operation: {what}"),
}
}
}
@@ -1673,9 +1674,22 @@ impl GraphicsContext {
rendered_output = Some(pixels);
continue;
}
if *vertex_count_per_instance < 3 {
// Zero instances, or fewer vertices than one triangle,
// draw nothing. The flat path draws only the first
// triangle of the view, once; anything else is rejected
// rather than drawn as a different triangle.
if *vertex_count_per_instance < 3 || *instance_count == 0 {
continue;
}
if *vertex_count_per_instance != 3
|| *instance_count != 1
|| *start_vertex_location != 0
|| *start_instance_location != 0
{
return Err(GraphicsError::Unsupported(
"flat draw other than one instance of the view's first three vertices",
));
}
draw_count += 1;
let v_res_handle =
vertex_resource.ok_or(GraphicsError::InvalidResourceHandle)?;
@@ -1684,15 +1698,10 @@ impl GraphicsContext {
.get(&v_res_handle)
.ok_or(GraphicsError::InvalidResourceHandle)?;
// Read vertices from guest memory backing or resource data
let mut raw_vtx = [0u8; 48]; // 3 * 4 * float32
if let Some(guest_addr) = v_res.guest_backing_addr {
memory.read_bytes(guest_addr + vertex_offset as u64, &mut raw_vtx)?;
} else if v_res.data.len() >= vertex_offset + 48 {
raw_vtx.copy_from_slice(&v_res.data[vertex_offset..vertex_offset + 48]);
} else {
return Err(GraphicsError::InvalidDescriptor);
}
// Three float4 positions, inside the resource whether it
// is backed by guest memory or by its own bytes.
let mut raw_vtx = [0u8; 48];
Self::read_resource(v_res, memory, vertex_offset, &mut raw_vtx)?;
let mut vertices = [[0.0f32; 4]; 3];
for (i, row) in vertices.iter_mut().enumerate() {
+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"))
+531 -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; 20] = [
pub static SERVICES: [ServiceMetadata; 47] = [
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetProcessPriorityBoost",
@@ -141,6 +141,116 @@ pub static SERVICES: [ServiceMetadata; 20] = [
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",
@@ -163,6 +273,61 @@ pub static SERVICES: [ServiceMetadata; 20] = [
reference: "errhandlingapi.h SetLastError",
tests: &["last_error_is_set_by_failures_and_by_the_guest"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__p___argc",
parameters: &[],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "stops the guest when the variable cannot be allocated",
reference: "Microsoft Learn, C runtime library reference, __argc, __argv, __wargv",
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__p___argv",
parameters: &[],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "stops the guest when the variable cannot be allocated",
reference: "Microsoft Learn, C runtime library reference, __argc, __argv, __wargv",
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__p__environ",
parameters: &[],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-environment-l1-1-0.dll"],
failure: "stops the guest when the variable cannot be allocated",
reference: "Microsoft Learn, C runtime library reference, _environ, _wenviron",
tests: &["the_environment_table_is_empty_and_ends_with_a_null_pointer"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "_configure_narrow_argv",
parameters: &[Parameter { name: "mode", kind: "i32" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated",
reference: "corecrt_startup.h _configure_narrow_argv",
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "_initialize_narrow_environment",
parameters: &[],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "stops the guest when the table cannot be allocated",
reference: "corecrt_startup.h _initialize_narrow_environment",
tests: &["the_environment_table_is_empty_and_ends_with_a_null_pointer"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "VirtualAlloc",
@@ -185,6 +350,39 @@ pub static SERVICES: [ServiceMetadata; 20] = [
reference: "memoryapi.h VirtualFree",
tests: &["virtual_memory_is_mapped_released_and_bounded"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "VirtualProtect",
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "protect", kind: "u32" }, Parameter { name: "old", kind: "out<4>" }],
result: "bool32",
status: ServiceStatus::Stub,
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
failure: "always: stops the guest with the runtime-limit fault; no protection changes",
reference: "memoryapi.h VirtualProtect",
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "VirtualQuery",
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "information", kind: "out<48>" }, Parameter { name: "length", kind: "u64" }],
result: "u64",
status: ServiceStatus::Stub,
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
failure: "always: stops the guest with the runtime-limit fault; nothing is written",
reference: "memoryapi.h VirtualQuery",
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__C_specific_handler",
parameters: &[Parameter { name: "record", kind: "ptr" }, Parameter { name: "frame", kind: "ptr" }, Parameter { name: "context", kind: "ptr" }, Parameter { name: "dispatcher", kind: "ptr" }],
result: "i32",
status: ServiceStatus::Stub,
aliases: &["api-ms-win-crt-private-l1-1-0.dll"],
failure: "always: stops the guest with the runtime-limit fault; no exception is dispatched",
reference: "Microsoft Learn, x64 exception handling, language-specific handler",
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "sqrt",
@@ -229,6 +427,105 @@ pub static SERVICES: [ServiceMetadata; 20] = [
reference: "math.h fabsf (ISO C, IEC 60559 abs)",
tests: &["floating_arguments_and_results_use_xmm_registers"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "_set_app_type",
parameters: &[Parameter { name: "kind", kind: "i32" }],
result: "void",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "never",
reference: "corecrt_startup.h _set_app_type",
tests: &["crt_app_type_and_math_error_handler_are_recorded"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "_set_new_mode",
parameters: &[Parameter { name: "mode", kind: "i32" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-heap-l1-1-0.dll"],
failure: "-1 with errno EINVAL for a mode other than 0 or 1",
reference: "new.h _set_new_mode",
tests: &["crt_startup_modes_return_the_previous_setting"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "_configthreadlocale",
parameters: &[Parameter { name: "request", kind: "i32" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-locale-l1-1-0.dll"],
failure: "-1 with errno EINVAL for a request other than 0, 1 or 2",
reference: "locale.h _configthreadlocale",
tests: &["crt_startup_modes_return_the_previous_setting"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__setusermatherr",
parameters: &[Parameter { name: "handler", kind: "ptr" }],
result: "void",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
failure: "never",
reference: "corecrt_startup.h __setusermatherr",
tests: &["crt_app_type_and_math_error_handler_are_recorded"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "_set_invalid_parameter_handler",
parameters: &[Parameter { name: "handler", kind: "ptr" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "never",
reference: "stdlib.h _set_invalid_parameter_handler",
tests: &["crt_startup_handlers_return_the_previous_handler"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__p__fmode",
parameters: &[],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "stops the guest when the variable cannot be allocated",
reference: "Microsoft Learn, C runtime library reference, __p__fmode",
tests: &["crt_file_mode_variables_are_guest_memory"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__p__commode",
parameters: &[],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "stops the guest when the variable cannot be allocated",
reference: "Microsoft Learn, C runtime library reference, __p__commode",
tests: &["crt_file_mode_variables_are_guest_memory"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "signal",
parameters: &[Parameter { name: "signal", kind: "i32" }, Parameter { name: "handler", kind: "ptr" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "SIG_ERR with errno EINVAL for a signal the documentation does not list",
reference: "signal.h signal",
tests: &["crt_startup_handlers_return_the_previous_handler"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetUnhandledExceptionFilter",
parameters: &[Parameter { name: "filter", kind: "ptr" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"],
failure: "never",
reference: "errhandlingapi.h SetUnhandledExceptionFilter",
tests: &["crt_startup_handlers_return_the_previous_handler"],
},
];
/// Register every generated service and its API-set aliases.
@@ -331,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 };
@@ -346,6 +737,42 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
Ok(0)
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__p___argc", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::argc_pointer(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__p___argv", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::argv_pointer(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__p__environ", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::environ_pointer(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "_configure_narrow_argv", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.i32(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::configure_narrow_argv(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "_initialize_narrow_environment", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::initialize_narrow_environment(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "VirtualAlloc", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
@@ -367,6 +794,38 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "VirtualProtect", ServiceStatus::Stub, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let a2 = call.u32(2)?;
let a3 = call.out::<4>(3)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: bool = handlers::virtual_protect(&mut context, a0, a1, a2, a3)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "VirtualQuery", ServiceStatus::Stub, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.out::<48>(1)?;
let a2 = call.u64(2)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::virtual_query(&mut context, a0, a1, a2)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__C_specific_handler", ServiceStatus::Stub, 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: i32 = handlers::c_specific_handler(&mut context, a0, a1, a2, a3)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "sqrt", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.f64(0)?;
@@ -398,6 +857,77 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "_set_app_type", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.i32(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let () = handlers::set_app_type(&mut context, a0)?;
Ok(0)
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "_set_new_mode", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.i32(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::set_new_mode(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "_configthreadlocale", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.i32(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::configure_thread_locale(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__setusermatherr", 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::set_user_math_error(&mut context, a0)?;
Ok(0)
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "_set_invalid_parameter_handler", 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: u64 = handlers::set_invalid_parameter_handler(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__p__fmode", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::file_mode_pointer(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__p__commode", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::commit_mode_pointer(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "signal", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.i32(0)?;
let a1 = call.u64(1)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::signal(&mut context, a0, a1)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "SetUnhandledExceptionFilter", 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: u64 = handlers::set_unhandled_exception_filter(&mut context, a0)?;
Ok(result.place(cpu))
});
for service in &SERVICES {
for alias in service.aliases {
if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {
+339
View File
@@ -10,7 +10,12 @@
//! - Xbox physical memory: `XMemAlloc`, `XMemFree`
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;
@@ -25,6 +30,8 @@ pub(crate) mod threads;
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};
@@ -200,13 +207,16 @@ pub struct ServicesState {
pub guest_profile: sysinfo::GuestSystemProfile,
objects: Mutex<ObjectState>,
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`.
atexit: Mutex<Vec<u64>>,
/// The status the guest process exited with. Set once.
exit_status: Mutex<Option<u32>>,
crt_startup: Mutex<crt_startup::CrtStartup>,
winsock: Mutex<winsock::Winsock>,
task_fixture: Mutex<task_fixture::TaskFixture>,
platform_fixture: Mutex<platform_fixture::PlatformFixture>,
@@ -228,11 +238,14 @@ impl ServicesState {
guest_profile: sysinfo::GuestSystemProfile::default(),
objects: Mutex::new(ObjectState::default()),
last_errors: Mutex::default(),
crt_arguments: Mutex::default(),
synch: Mutex::default(),
crt_streams: Mutex::default(),
threads: Mutex::default(),
hooks: Arc::default(),
atexit: Mutex::default(),
exit_status: Mutex::default(),
crt_startup: Mutex::default(),
winsock: Mutex::default(),
task_fixture: Mutex::default(),
platform_fixture: Mutex::default(),
@@ -243,6 +256,21 @@ impl ServicesState {
graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())),
}
}
/// Give a hosted C program the arguments its `main` receives in `argv`,
/// program name first. Call it before running the guest: the C runtime's
/// startup code builds `argv` once, and a call after that is refused.
///
/// The strings reach the guest as their bytes; no code page is applied.
/// A host that never calls this gives the program one argument, the empty
/// string. An empty slice gives it none.
pub fn set_program_arguments(&self, arguments: &[&str]) -> Result<(), ProgramArgumentsError> {
self.crt_arguments().supply(arguments)
}
fn crt_arguments(&self) -> std::sync::MutexGuard<'_, crt_arguments::CrtArguments> {
self.crt_arguments.lock().expect("program arguments")
}
fn uptime_millis(&self) -> u64 {
let ticks = self
.clock
@@ -326,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
@@ -360,6 +405,22 @@ impl ServicesState {
}
}
fn crt_startup(&self) -> std::sync::MutexGuard<'_, crt_startup::CrtStartup> {
self.crt_startup.lock().expect("C runtime startup state")
}
/// The application type the guest passed to `_set_app_type`, zero until it
/// does. Nothing in the runtime depends on it.
pub fn crt_app_type(&self) -> i32 {
self.crt_startup().app_type()
}
/// The guest function passed to `__setusermatherr`, zero until one is. It
/// is never called.
pub fn crt_user_math_error(&self) -> u64 {
self.crt_startup().user_math_error()
}
/// Record a guest error and return the documented failure value.
fn fail<T>(&self, teb: u64, error: u32, value: T) -> Result<T, ExitReason> {
self.set_last_error(teb, error);
@@ -722,6 +783,9 @@ pub(crate) mod handlers {
type Outcome<T> = Result<T, ExitReason>;
/// The exit for a request the runtime does not model.
const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
pub fn set_process_priority_boost(
context: &mut ServiceContext<'_>,
process: u64,
@@ -874,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))
}
@@ -883,6 +1073,38 @@ pub(crate) mod handlers {
Ok(())
}
// What a hosted C program's startup code hands to `main` (#392).
// `crt_arguments.rs` says what is documented, inferred and Xenora's choice.
pub fn argc_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
let mut arguments = context.state.crt_arguments();
arguments.address(context.memory, crt_arguments::Variable::Argc)
}
pub fn argv_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
let mut arguments = context.state.crt_arguments();
arguments.address(context.memory, crt_arguments::Variable::Argv)
}
pub fn environ_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
let mut arguments = context.state.crt_arguments();
arguments.address(context.memory, crt_arguments::Variable::Environ)
}
pub fn configure_narrow_argv(context: &mut ServiceContext<'_>, mode: i32) -> Outcome<i32> {
context
.state
.crt_arguments()
.configure(context.memory, mode)
}
pub fn initialize_narrow_environment(context: &mut ServiceContext<'_>) -> Outcome<i32> {
context
.state
.crt_arguments()
.initialize_environment(context.memory)
}
pub fn virtual_alloc(
context: &mut ServiceContext<'_>,
requested: u64,
@@ -946,6 +1168,42 @@ pub(crate) mod handlers {
Ok(true)
}
// Stubs (#388). A program built with the mingw-w64 runtime imports these
// three and does not call them on a normal run: the first two serve its
// runtime pseudo-relocations and the third is the language handler Windows
// calls while dispatching a structured exception. None is modelled, so a
// call stops the guest with the runtime-limit fault. Returning a made-up
// result would let the program run on with wrong state.
pub fn virtual_protect(
_: &mut ServiceContext<'_>,
_address: u64,
_size: u64,
_protect: u32,
_old: OutPtr<4>,
) -> Outcome<bool> {
Err(RUNTIME_LIMIT)
}
pub fn virtual_query(
_: &mut ServiceContext<'_>,
_address: u64,
_information: OutPtr<48>,
_length: u64,
) -> Outcome<u64> {
Err(RUNTIME_LIMIT)
}
pub fn c_specific_handler(
_: &mut ServiceContext<'_>,
_record: u64,
_frame: u64,
_context: u64,
_dispatcher: u64,
) -> Outcome<i32> {
Err(RUNTIME_LIMIT)
}
/// The guest MXCSR is not visible to a service, so results use the default
/// rounding and raise no guest flags; the registry marks them partial.
const DEFAULT_MXCSR: u32 = crate::cpu::Mxcsr::RESET;
@@ -968,4 +1226,85 @@ pub(crate) mod handlers {
pub fn fabsf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome<Float32> {
Ok(Float32(x.0 & !(1 << 31)))
}
// What a C program's startup code configures (#382). Each value is
// recorded and returned; `crt_startup.rs` says what does not act on it.
pub fn set_app_type(context: &mut ServiceContext<'_>, kind: i32) -> Outcome<()> {
context.state.crt_startup().set_app_type(kind);
Ok(())
}
pub fn set_new_mode(context: &mut ServiceContext<'_>, mode: i32) -> Outcome<i32> {
let previous = context.state.crt_startup().set_new_mode(mode);
match previous {
Some(previous) => Ok(previous),
None => {
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
Ok(-1)
}
}
}
pub fn configure_thread_locale(context: &mut ServiceContext<'_>, request: i32) -> Outcome<i32> {
let previous = context.state.crt_startup().configure_thread_locale(request);
match previous {
Some(previous) => Ok(previous),
None => {
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
Ok(-1)
}
}
}
pub fn set_user_math_error(context: &mut ServiceContext<'_>, handler: u64) -> Outcome<()> {
context.state.crt_startup().set_user_math_error(handler);
Ok(())
}
pub fn set_invalid_parameter_handler(
context: &mut ServiceContext<'_>,
handler: u64,
) -> Outcome<u64> {
Ok(context
.state
.crt_startup()
.set_invalid_parameter_handler(handler))
}
pub fn file_mode_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
context
.state
.crt_startup()
.file_mode_address(context.memory, 0)
}
pub fn commit_mode_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
context
.state
.crt_startup()
.file_mode_address(context.memory, 1)
}
pub fn signal(context: &mut ServiceContext<'_>, signal: i32, handler: u64) -> Outcome<u64> {
let previous = context.state.crt_startup().signal(signal, handler);
match previous {
Some(previous) => Ok(previous),
None => {
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
// SIG_ERR is (void (*)(int))-1.
Ok(u64::MAX)
}
}
}
pub fn set_unhandled_exception_filter(
context: &mut ServiceContext<'_>,
filter: u64,
) -> Outcome<u64> {
Ok(context
.state
.crt_startup()
.set_unhandled_exception_filter(filter))
}
}
+4 -2
View File
@@ -190,12 +190,14 @@ pub(super) fn register(registry: &mut ImportRegistry) {
registry.alias(CRT_STRING_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
// The mingw-w64 C runtime imports `memcpy` through this API set.
registry.alias("api-ms-win-crt-private-l1-1-0.dll", UCRT, "memcpy");
}
const ENOMEM: u32 = 12;
const EINVAL: u32 = 22;
pub(super) const EINVAL: u32 = 22;
fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
pub(super) fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
let address = memory
.crt_errno_address(teb)
.map_err(ExitReason::MemoryFault)?;
+182
View File
@@ -0,0 +1,182 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The arguments and environment a hosted C program's startup code hands to
//! `main`.
//!
//! Documented: the global variables `__argc` (the argument count), `__argv` (a
//! pointer to the array of argument strings) and `_environ` (a pointer to the
//! array of environment strings), and ISO C's rule that a null pointer follows
//! the last argument.
//!
//! Inferred: that `__p___argc`, `__p___argv` and `__p__environ` return the
//! address of those variables, as the documented `__p__fmode` does for
//! `_fmode`. Microsoft lists all five functions here only by name.
//!
//! Xenora's choice, because nothing public describes it: what
//! `_configure_narrow_argv` and `_initialize_narrow_environment` do. The
//! arguments come from the host, as bytes with no code page; wildcards are not
//! expanded; and the environment table is empty.
use crate::cpu::ExitReason;
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
use std::fmt;
const EINVAL: i32 = 22;
/// `_crt_argv_no_arguments`, `_crt_argv_unexpanded_arguments` and
/// `_crt_argv_expanded_arguments` (corecrt_startup.h).
const NO_ARGUMENTS: i32 = 0;
const UNEXPANDED_ARGUMENTS: i32 = 1;
const EXPANDED_ARGUMENTS: i32 = 2;
/// Windows limits a command line to 32,767 characters including its
/// terminator (`CreateProcess`). The same bound is applied here to the
/// arguments with their terminators.
pub const MAX_PROGRAM_ARGUMENT_BYTES: usize = 32_767;
/// Why [`super::ServicesState::set_program_arguments`] refused its input.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProgramArgumentsError {
/// An argument holds a NUL byte, which would end it early in the guest.
ContainsNul,
/// The arguments and their terminators exceed
/// [`MAX_PROGRAM_ARGUMENT_BYTES`].
TooLong,
/// The guest has already built `__argv`; it would not see a change.
AlreadyConfigured,
}
impl fmt::Display for ProgramArgumentsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::ContainsNul => "a program argument contains a NUL byte",
Self::TooLong => "the program arguments exceed 32,767 bytes",
Self::AlreadyConfigured => "the guest has already configured its arguments",
})
}
}
impl std::error::Error for ProgramArgumentsError {}
/// Which of the three guest variables a `__p_` function points at. The value
/// is the variable's offset in their shared block.
#[derive(Clone, Copy)]
pub(super) enum Variable {
Argc = 0,
Argv = 8,
Environ = 16,
}
#[derive(Default)]
pub(super) struct CrtArguments {
/// What the host supplied, program name first.
supplied: Option<Vec<Vec<u8>>>,
/// Guest address of the block holding `__argc`, `__argv` and `_environ`.
variables: Option<u64>,
configured: bool,
environment_initialized: bool,
}
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
impl CrtArguments {
pub(super) fn supply(&mut self, arguments: &[&str]) -> Result<(), ProgramArgumentsError> {
if self.configured {
return Err(ProgramArgumentsError::AlreadyConfigured);
}
if arguments.iter().any(|argument| argument.contains('\0')) {
return Err(ProgramArgumentsError::ContainsNul);
}
let bytes: usize = arguments.iter().map(|argument| argument.len() + 1).sum();
if bytes > MAX_PROGRAM_ARGUMENT_BYTES {
return Err(ProgramArgumentsError::TooLong);
}
self.supplied = Some(
arguments
.iter()
.map(|argument| argument.as_bytes().to_vec())
.collect(),
);
Ok(())
}
/// Guest address of one of the three variables. They are allocated
/// together from the process heap on first use, as zeros: no arguments,
/// and null `__argv` and `_environ`.
pub(super) fn address(
&mut self,
memory: &mut GuestMemory,
variable: Variable,
) -> Result<u64, ExitReason> {
let base = match self.variables {
Some(base) => base,
None => {
let base = memory
.map_heap_allocation(PROCESS_HEAP, 24)
.map_err(fault)?;
self.variables = Some(base);
base
}
};
Ok(base + variable as u64)
}
/// `_configure_narrow_argv`. Modes 1 and 2 build `__argc` and `__argv`
/// once; a later call changes nothing. Mode 0 builds nothing. Any other
/// mode is refused with `EINVAL`.
pub(super) fn configure(
&mut self,
memory: &mut GuestMemory,
mode: i32,
) -> Result<i32, ExitReason> {
match mode {
NO_ARGUMENTS => return Ok(0),
UNEXPANDED_ARGUMENTS | EXPANDED_ARGUMENTS => {}
_ => return Ok(EINVAL),
}
if self.configured {
return Ok(0);
}
// With no host input the program name is not available, and ISO C
// then makes argv[0] the empty string.
let default = [Vec::new()];
let arguments = self.supplied.as_deref().unwrap_or(&default);
let table_bytes = 8 * (arguments.len() + 1);
let string_bytes: usize = arguments.iter().map(|argument| argument.len() + 1).sum();
let table = memory
.map_heap_allocation(PROCESS_HEAP, table_bytes + string_bytes)
.map_err(fault)?;
// The pointers first, then the strings. The block starts as zeros, so
// the pointer after the last argument and every terminator are in place.
let mut string = table + table_bytes as u64;
for (index, argument) in arguments.iter().enumerate() {
memory
.write_u64(table + 8 * index as u64, string)
.map_err(fault)?;
memory.write_bytes(string, argument).map_err(fault)?;
string += argument.len() as u64 + 1;
}
let count = arguments.len() as u32;
let argc = self.address(memory, Variable::Argc)?;
let argv = self.address(memory, Variable::Argv)?;
memory.write_u32(argc, count).map_err(fault)?;
memory.write_u64(argv, table).map_err(fault)?;
self.configured = true;
Ok(0)
}
/// `_initialize_narrow_environment`. Points `_environ` at an empty table,
/// one null pointer, once.
pub(super) fn initialize_environment(
&mut self,
memory: &mut GuestMemory,
) -> Result<i32, ExitReason> {
if !self.environment_initialized {
let table = memory.map_heap_allocation(PROCESS_HEAP, 8).map_err(fault)?;
let environ = self.address(memory, Variable::Environ)?;
memory.write_u64(environ, table).map_err(fault)?;
self.environment_initialized = true;
}
Ok(0)
}
}
@@ -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
)))
);
}
}
+116
View File
@@ -0,0 +1,116 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! What a C program's startup code configures in the C runtime before `main`.
//!
//! Each value is recorded and returned as its public documentation says, and
//! nothing acts on any of them yet. No invalid-parameter handler, signal
//! handler, exception filter, math-error handler or new handler is ever called,
//! there is no locale, and nothing reads `_fmode` or `_commode` until stdio
//! exists. The registry therefore declares every service here `partial`.
use crate::cpu::ExitReason;
use crate::memory::{GuestMemory, PROCESS_HEAP};
use std::collections::BTreeMap;
/// `_O_TEXT` (fcntl.h), the documented initial value of `_fmode`.
const O_TEXT: u32 = 0x4000;
/// `_ENABLE_PER_THREAD_LOCALE` and `_DISABLE_PER_THREAD_LOCALE` (locale.h).
const ENABLE_PER_THREAD_LOCALE: i32 = 1;
const DISABLE_PER_THREAD_LOCALE: i32 = 2;
/// The signals the documentation of `signal` lists, by their signal.h values:
/// SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM and SIGABRT.
const SIGNALS: [i32; 6] = [2, 4, 8, 11, 15, 22];
#[derive(Default)]
pub(super) struct CrtStartup {
app_type: i32,
/// Whether `malloc` would call the new handler on failure. It never does.
new_mode: i32,
per_thread_locale: bool,
user_math_error: u64,
invalid_parameter_handler: u64,
unhandled_exception_filter: u64,
/// Handlers other than the default, `SIG_DFL`, which is zero.
signals: BTreeMap<i32, u64>,
/// Guest address of `_fmode`. `_commode` is the `int` after it.
file_modes: Option<u64>,
}
impl CrtStartup {
pub(super) fn app_type(&self) -> i32 {
self.app_type
}
pub(super) fn set_app_type(&mut self, kind: i32) {
self.app_type = kind;
}
/// The previous mode, or `None` for a mode that is neither 0 nor 1.
pub(super) fn set_new_mode(&mut self, mode: i32) -> Option<i32> {
matches!(mode, 0 | 1).then(|| std::mem::replace(&mut self.new_mode, mode))
}
/// The setting before the call, or `None` for a request that is not 0
/// (query), enable or disable. A new process uses the global locale.
pub(super) fn configure_thread_locale(&mut self, request: i32) -> Option<i32> {
let before = if self.per_thread_locale {
ENABLE_PER_THREAD_LOCALE
} else {
DISABLE_PER_THREAD_LOCALE
};
match request {
0 => {}
ENABLE_PER_THREAD_LOCALE => self.per_thread_locale = true,
DISABLE_PER_THREAD_LOCALE => self.per_thread_locale = false,
_ => return None,
}
Some(before)
}
pub(super) fn user_math_error(&self) -> u64 {
self.user_math_error
}
pub(super) fn set_user_math_error(&mut self, handler: u64) {
self.user_math_error = handler;
}
pub(super) fn set_invalid_parameter_handler(&mut self, handler: u64) -> u64 {
std::mem::replace(&mut self.invalid_parameter_handler, handler)
}
pub(super) fn set_unhandled_exception_filter(&mut self, filter: u64) -> u64 {
std::mem::replace(&mut self.unhandled_exception_filter, filter)
}
/// The previous handler, or `None` for a signal the documentation does not
/// list. One table serves the whole process.
pub(super) fn signal(&mut self, signal: i32, handler: u64) -> Option<u64> {
SIGNALS
.contains(&signal)
.then(|| self.signals.insert(signal, handler).unwrap_or(0))
}
/// Guest address of `_fmode` (`index` 0) or `_commode` (`index` 1). Both
/// are allocated together from the process heap on first use. `_fmode`
/// starts as `_O_TEXT`, as documented. `_commode` starts as zero: its
/// documentation gives no initial value, and zero is "no commit".
pub(super) fn file_mode_address(
&mut self,
memory: &mut GuestMemory,
index: u64,
) -> Result<u64, ExitReason> {
let base = match self.file_modes {
Some(base) => base,
None => {
let base = memory
.map_heap_allocation(PROCESS_HEAP, 8)
.and_then(|base| memory.write_u32(base, O_TEXT).map(|()| base))
.map_err(ExitReason::MemoryFault)?;
self.file_modes = Some(base);
base
}
};
Ok(base + 4 * index)
}
}
+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);
}
}
+440 -11
View File
@@ -233,6 +233,22 @@ fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>,
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
const TLS_ARRAY_SIZE: usize = 0x1000;
/// Bytes read per step when a template is checked and then copied into its
/// block.
const TEMPLATE_COPY_CHUNK: usize = 4096;
/// Smallest template copied into the zeroed block instead of a staging buffer.
///
/// Release timings of original synthetic templates on an Apple M2 Pro put the
/// point where a second buffer dominates at 64 KiB. Below that, one read into
/// a staging buffer is as fast or faster.
const DIRECT_TEMPLATE_MIN: usize = 64 * 1024;
/// Templates at least this big keep the single staged read. On the same
/// machine, proving the bytes readable and then copying them was no faster
/// than the staging buffer once the template reached 1 MiB.
const DIRECT_TEMPLATE_LIMIT: usize = 1024 * 1024;
/// Set up TLS runtime state in guest memory:
/// 1. Assign TLS index 0 at `index_address`.
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
@@ -244,6 +260,12 @@ const TLS_ARRAY_SIZE: usize = 0x1000;
/// TLS pointer. Compiled code loads that pointer, indexes it by the module's
/// TLS index to find the data block, and then adds a variable's offset, so the
/// array and the data are separate regions.
///
/// The block is the template followed by `SizeOfZeroFill` zero bytes. A
/// template of at least 64 KiB and below 1 MiB is proved readable and then
/// copied into a zeroed block. Every other size is read once into a staging
/// buffer that initializes the block. Either way, a template that cannot be
/// read leaves the pointer array unmapped.
pub fn setup_tls(
tls: &TlsDirectory,
loaded_base: u64,
@@ -278,11 +300,19 @@ pub fn setup_tls(
let total_size = template_size + (tls.size_of_zero_fill as usize);
if total_size > 0 {
// Read template bytes from image
let mut template_data = vec![0u8; template_size];
if template_size > 0 {
memory.read_bytes(actual_start, &mut template_data)?;
}
let direct = (DIRECT_TEMPLATE_MIN..DIRECT_TEMPLATE_LIMIT).contains(&template_size);
// The read happens before anything is mapped, so a missing or
// unreadable template does not leave a pointer array behind.
let staged = if direct {
prove_template_readable(memory, actual_start, template_size)?;
None
} else {
let mut staged = vec![0u8; template_size];
if template_size > 0 {
memory.read_bytes(actual_start, &mut staged)?;
}
Some(staged)
};
// Allocate the pointer array and the per-thread TLS block.
let block_base = thread_tls_base
@@ -295,12 +325,17 @@ pub fn setup_tls(
TLS_ARRAY_SIZE,
MemoryPermissions::READ_WRITE,
)?;
memory.map_region_with_data(
block_base,
map_size,
MemoryPermissions::READ_WRITE,
&template_data,
)?;
if let Some(staged) = staged.as_deref() {
memory.map_region_with_data(
block_base,
map_size,
MemoryPermissions::READ_WRITE,
staged,
)?;
} else {
memory.map_region(block_base, map_size, MemoryPermissions::READ_WRITE)?;
copy_template(memory, actual_start, block_base, template_size)?;
}
// Slot 0 belongs to the index assigned above.
memory.write_u64(thread_tls_base, block_base)?;
}
@@ -308,6 +343,44 @@ pub fn setup_tls(
Ok(())
}
/// Read every template byte, discarding the contents.
///
/// Failure here means the template is not available. Callers map the block
/// only after this returns.
fn prove_template_readable(memory: &GuestMemory, addr: u64, len: usize) -> Result<(), TlsError> {
let mut chunk = [0u8; TEMPLATE_COPY_CHUNK];
let mut offset = 0usize;
while offset < len {
let n = (len - offset).min(TEMPLATE_COPY_CHUNK);
let at = addr
.checked_add(offset as u64)
.ok_or(MemoryError::Overflow)?;
memory.read_bytes(at, &mut chunk[..n])?;
offset += n;
}
Ok(())
}
/// Copy `len` bytes from `src` to `dst`. `dst` is already zeroed, which is the
/// template's `SizeOfZeroFill` and the rounded tail of the block.
fn copy_template(memory: &mut GuestMemory, src: u64, dst: u64, len: usize) -> Result<(), TlsError> {
let mut chunk = [0u8; TEMPLATE_COPY_CHUNK];
let mut offset = 0usize;
while offset < len {
let n = (len - offset).min(TEMPLATE_COPY_CHUNK);
let from = src
.checked_add(offset as u64)
.ok_or(MemoryError::Overflow)?;
let to = dst
.checked_add(offset as u64)
.ok_or(MemoryError::Overflow)?;
memory.read_bytes(from, &mut chunk[..n])?;
memory.write_bytes(to, &chunk[..n])?;
offset += n;
}
Ok(())
}
/// Execute all registered TLS callbacks in sequence.
/// Signature: void (NTAPI *PIMAGE_TLS_CALLBACK)(PVOID DllHandle, DWORD Reason, PVOID Reserved);
/// - RCX = DllHandle (loaded_base)
@@ -392,6 +465,8 @@ mod tests {
use super::*;
use crate::pe::PeSection;
use std::hint::black_box;
use std::time::Instant;
const IMAGE_BASE: u64 = 0x1_4000_0000;
const SECTION_RVA: u32 = 0x1000;
@@ -680,4 +755,358 @@ mod tests {
assert_eq!(none, Ok(0));
}
}
/// Bytes that do not repeat every 256 or every 4096 bytes, so a chunk
/// copied from the wrong offset cannot match.
fn synthetic_template(len: usize) -> Vec<u8> {
(0..len)
.map(|index| {
let mixed = index ^ (index >> 8) ^ (index >> 16);
mixed.wrapping_mul(131).wrapping_add(17) as u8
})
.collect()
}
/// Image template at `template_at`, with `sentinel` 0xA5 bytes after it, and
/// a writable index that does not start at zero.
fn template_memory(
template_at: u64,
template: &[u8],
sentinel: usize,
index_at: u64,
) -> GuestMemory {
let mut image = template.to_vec();
image.extend(std::iter::repeat_n(0xA5, sentinel));
let map = (image.len() + 0xFFF) & !0xFFF;
image.resize(map, 0);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(template_at, map, MemoryPermissions::READ_ONLY, &image)
.unwrap();
memory
.map_region_with_data(index_at, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
memory
}
fn directory_at(
template_at: u64,
template_len: u64,
index_at: u64,
zero_fill: u32,
) -> TlsDirectory {
TlsDirectory {
raw_data_start_va: template_at,
raw_data_end_va: template_at + template_len,
index_address: index_at,
size_of_zero_fill: zero_fill,
..TlsDirectory::default()
}
}
fn assert_block(
memory: &GuestMemory,
thread: u64,
index: u64,
template: &[u8],
zero_fill: usize,
) {
assert_eq!(memory.read_u32(index).unwrap(), 0);
let block = memory.read_u64(thread).unwrap();
assert_eq!(block, thread + 0x1000, "the data block is the next page");
// The block is mapped up to the next page boundary and no further.
let mapped = (template.len() + zero_fill + 0xFFF) & !0xFFF;
let mut got = vec![0xEEu8; mapped];
memory.read_bytes(block, &mut got).unwrap();
assert_eq!(&got[..template.len()], template);
assert!(got[template.len()..].iter().all(|byte| *byte == 0));
let end = block + mapped as u64;
assert_eq!(memory.read_u8(end), Err(MemoryError::UnmappedAddress(end)));
}
const TEMPLATE_AT: u64 = 0x2_0020_0000;
const INDEX_AT: u64 = 0x2_0000_1000;
const THREAD_AT: u64 = 0x5_0000_0000;
#[test]
fn a_small_template_is_copied_and_zero_fill_does_not_take_the_following_bytes() {
let template = synthetic_template(48);
let mut memory = template_memory(TEMPLATE_AT, &template, 16, INDEX_AT);
setup_tls(
&directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 16),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_block(&memory, THREAD_AT, INDEX_AT, &template, 16);
let mut tail = [0u8; 16];
memory
.read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail)
.unwrap();
assert_eq!(tail, [0xA5; 16]);
let block = memory.read_u64(THREAD_AT).unwrap();
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
let mut image = [0u8; 8];
memory.read_bytes(TEMPLATE_AT + 8, &mut image).unwrap();
assert_eq!(image, template[8..16]);
}
#[test]
fn the_staged_and_direct_copy_boundaries_keep_every_template_byte() {
for len in [
DIRECT_TEMPLATE_MIN - 1,
DIRECT_TEMPLATE_MIN,
DIRECT_TEMPLATE_MIN + TEMPLATE_COPY_CHUNK + 100,
DIRECT_TEMPLATE_LIMIT - 1,
DIRECT_TEMPLATE_LIMIT,
] {
let template = synthetic_template(len);
let mut memory = template_memory(TEMPLATE_AT, &template, 24, INDEX_AT);
setup_tls(
&directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 24),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_block(&memory, THREAD_AT, INDEX_AT, &template, 24);
let mut tail = [0u8; 24];
memory
.read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail)
.unwrap();
assert_eq!(tail, [0xA5; 24], "len {len}");
}
}
#[test]
fn a_rebased_direct_copy_reads_the_loaded_image() {
let template = synthetic_template(DIRECT_TEMPLATE_MIN);
let preferred = 0x1_4000_0000u64;
let loaded = preferred + 0x80_0000;
let template_at = preferred + 0x20_0000;
let index_at = preferred + 0x1000;
let mut memory =
template_memory(template_at + 0x80_0000, &template, 0, index_at + 0x80_0000);
setup_tls(
&directory_at(template_at, template.len() as u64, index_at, 8),
loaded,
preferred,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_block(&memory, THREAD_AT, index_at + 0x80_0000, &template, 8);
}
#[test]
fn an_unreadable_template_maps_no_pointer_array() {
for len in [32usize, DIRECT_TEMPLATE_MIN, DIRECT_TEMPLATE_MIN + 50] {
let mut missing = GuestMemory::new();
missing
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
let missing_result = setup_tls(
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
IMAGE_BASE,
IMAGE_BASE,
&mut missing,
THREAD_AT,
);
assert_eq!(
missing_result,
Err(TlsError::Memory(MemoryError::UnmappedAddress(TEMPLATE_AT))),
"{len}"
);
assert_eq!(missing.read_u32(INDEX_AT).unwrap(), 0);
assert!(matches!(
missing.read_u64(THREAD_AT),
Err(MemoryError::UnmappedAddress(_))
));
let mut denied = GuestMemory::new();
denied
.map_region(TEMPLATE_AT, len.max(0x1000), MemoryPermissions::NO_ACCESS)
.unwrap();
denied
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
let denied_result = setup_tls(
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
IMAGE_BASE,
IMAGE_BASE,
&mut denied,
THREAD_AT,
);
assert_eq!(
denied_result,
Err(TlsError::Memory(MemoryError::PermissionViolation {
address: TEMPLATE_AT,
required: "read",
})),
"{len}"
);
assert_eq!(denied.read_u32(INDEX_AT).unwrap(), 0);
assert!(matches!(
denied.read_u64(THREAD_AT),
Err(MemoryError::UnmappedAddress(_))
));
}
}
#[test]
fn a_direct_copy_template_that_runs_out_of_its_mapping_maps_nothing() {
let len = DIRECT_TEMPLATE_MIN + 100;
let mut memory = GuestMemory::new();
// Only the first chunk is mapped. The rest of the template is not.
memory
.map_region_with_data(
TEMPLATE_AT,
TEMPLATE_COPY_CHUNK,
MemoryPermissions::READ_ONLY,
&synthetic_template(TEMPLATE_COPY_CHUNK),
)
.unwrap();
memory
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
let result = setup_tls(
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
);
// The same first unreadable byte the single staged read reports.
assert_eq!(
result,
Err(TlsError::Memory(MemoryError::UnmappedAddress(
TEMPLATE_AT + TEMPLATE_COPY_CHUNK as u64
)))
);
assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0);
assert!(matches!(
memory.read_u64(THREAD_AT),
Err(MemoryError::UnmappedAddress(_))
));
}
#[test]
fn an_empty_template_and_zero_fill_only_assigns_the_index() {
let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT);
setup_tls(
&directory_at(TEMPLATE_AT, 0, INDEX_AT, 0),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0);
assert!(matches!(
memory.read_u64(THREAD_AT),
Err(MemoryError::UnmappedAddress(_))
));
}
#[test]
fn a_zero_fill_only_block_is_zero_and_separate_from_the_array() {
let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT);
setup_tls(
&directory_at(TEMPLATE_AT, 0, INDEX_AT, 24),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_block(&memory, THREAD_AT, INDEX_AT, &[], 24);
}
/// Byte pattern from the before/after timing runs. It is not the pattern
/// the correctness tests use to catch a chunk copied from the wrong offset.
fn timed_template(len: usize) -> Vec<u8> {
(0..len)
.map(|index| (index.wrapping_mul(131).wrapping_add(17)) as u8)
.collect()
}
fn timed_guest(template_len: usize, zero_fill: u32) -> (GuestMemory, TlsDirectory) {
let template = timed_template(template_len);
let mut memory = GuestMemory::new();
if template_len > 0 {
let map = (template_len + 0xFFF) & !0xFFF;
memory
.map_region_with_data(TEMPLATE_AT, map, MemoryPermissions::READ_ONLY, &template)
.unwrap();
}
memory
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
(
memory,
directory_at(TEMPLATE_AT, template_len as u64, INDEX_AT, zero_fill),
)
}
#[test]
#[ignore = "manual TLS template timing run; release build on an otherwise idle host"]
fn tls_template_initialization_profile() {
// Sizes, zero fill and batch counts from the interleaved before/after runs.
let cases = [
(64usize, 0u32, 80usize),
(4096, 0, 40),
(65535, 0, 20),
(65536, 128, 16),
(262144, 0, 6),
(786432, 0, 4),
(1048576, 0, 4),
(0, 1048576, 4),
];
for (template_len, zero_fill, batch) in cases {
let (mut memory, directory) = timed_guest(template_len, zero_fill);
setup_tls(&directory, IMAGE_BASE, IMAGE_BASE, &mut memory, THREAD_AT).unwrap();
if template_len > 0 {
let template = timed_template(template_len);
let block = memory.read_u64(THREAD_AT).unwrap();
let mut byte = [0u8; 1];
memory.read_bytes(block, &mut byte).unwrap();
assert_eq!(byte[0], template[0]);
memory
.read_bytes(block + template_len as u64 - 1, &mut byte)
.unwrap();
assert_eq!(byte[0], template[template_len - 1]);
}
let mut samples = Vec::new();
for run in 0..33 {
let mut guests: Vec<_> = (0..batch)
.map(|_| timed_guest(template_len, zero_fill))
.collect();
let start = Instant::now();
for (memory, directory) in &mut guests {
setup_tls(directory, IMAGE_BASE, IMAGE_BASE, memory, THREAD_AT).unwrap();
black_box(memory);
}
if run >= 2 {
let per_ns = start.elapsed().as_secs_f64() * 1e9 / batch as f64;
samples.push(per_ns);
}
}
samples.sort_by(f64::total_cmp);
let n = samples.len();
let mean = samples.iter().sum::<f64>() / n as f64;
let sample_variance = samples
.iter()
.map(|sample| (sample - mean).powi(2))
.sum::<f64>()
/ (n - 1) as f64;
println!(
"template={template_len} zero_fill={zero_fill} batch={batch} n={n} median_ns={:.1} sample_variance_ns2={sample_variance:.1}",
samples[n / 2]
);
}
}
}
+11 -12
View File
@@ -14,8 +14,9 @@ use crate::x86_table::{
/// Architectural x86-64 instruction length limit, in bytes.
///
/// An instruction may not exceed 15 bytes (Intel SDM Vol. 2A, "Instruction
/// Length"). Sequences longer than this are not decodable and are rejected as
/// illegal instructions.
/// Length"). Decoding stops before a 16th byte would be fetched and reports
/// [`DecodeError::TooLong`], a general-protection fault (Intel SDM Vol. 3A,
/// 7.15).
pub const MAX_INSTRUCTION_LEN: usize = 15;
/// Number of leading legacy segment prefix bytes (0x64 FS, 0x65 GS) at the
@@ -47,6 +48,9 @@ pub struct Form {
pub has_modrm: bool,
pub memory_only: bool,
pub register_only: bool,
/// The only ModRM r/m field value the form accepts. Set only on
/// register-only forms, so such a form matches exactly one ModRM byte.
pub fixed_rm: Option<u8>,
pub no_rex_b: bool,
/// A 16-byte memory operand may have any alignment.
pub unaligned: bool,
@@ -204,24 +208,24 @@ pub enum DecodeError<E> {
Fetch(E),
/// No declared form matches; carries the byte that decided it.
Unsupported(u8),
/// The instruction would be longer than [`MAX_INSTRUCTION_LEN`] bytes.
TooLong,
}
struct Cursor<F> {
fetch: F,
rip: u64,
len: usize,
last: u8,
}
impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
fn u8(&mut self) -> Result<u8, DecodeError<E>> {
if self.len == MAX_INSTRUCTION_LEN {
return Err(DecodeError::Unsupported(self.last));
return Err(DecodeError::TooLong);
}
let byte =
(self.fetch)(self.rip.wrapping_add(self.len as u64)).map_err(DecodeError::Fetch)?;
self.len += 1;
self.last = byte;
Ok(byte)
}
@@ -260,12 +264,7 @@ pub fn decode<E>(
rip: u64,
fetch: impl FnMut(u64) -> Result<u8, E>,
) -> Result<Insn, DecodeError<E>> {
let mut cursor = Cursor {
fetch,
rip,
len: 0,
last: 0,
};
let mut cursor = Cursor { fetch, rip, len: 0 };
let mut operand_size = false;
let mut rep = false;
let mut repne = false;
@@ -430,7 +429,7 @@ pub fn decode<E>(
reg = register((modrm >> 3) & 7, rex_r, size);
let mode = modrm >> 6;
if mode == 3 {
if form.memory_only {
if form.memory_only || form.fixed_rm.is_some_and(|field| field != modrm & 7) {
return Err(DecodeError::Unsupported(opcode));
}
rm = Some(RmOperand::Reg(register(modrm & 7, rex_b, rm_size)));
+49 -1
View File
@@ -10,7 +10,7 @@
//! the state unchanged. Flags that the architecture leaves undefined keep their
//! previous value, which is permitted but not something guests may rely on.
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
use crate::cpu::{CpuState, ExitReason, RFlags, Register, X87State, cpuid};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
use crate::x86_simd;
@@ -690,6 +690,26 @@ pub fn execute(
next = insn.imm;
}
}
// The count is RCX, decremented without changing any flag; LOOPE and
// LOOPNE also test ZF (Intel SDM Vol. 2A, LOOP/LOOPcc).
Op::Loop | Op::Loope | Op::Loopne => {
let count = cpu.gpr[RCX].wrapping_sub(1);
cpu.gpr[RCX] = count;
let zf_holds = match insn.op {
Op::Loope => cpu.flags.zf,
Op::Loopne => !cpu.flags.zf,
_ => true,
};
if count != 0 && zf_holds {
next = insn.imm;
}
}
// JRCXZ reads RCX and changes nothing (Intel SDM Vol. 2A, Jcc).
Op::Jrcxz => {
if cpu.gpr[RCX] == 0 {
next = insn.imm;
}
}
Op::Ret => {
let sp = cpu.gpr[RSP];
next = read_mem(memory, sp, 8)?;
@@ -700,6 +720,12 @@ pub fn execute(
// instruction starts, on one host thread, so guest accesses are already
// totally ordered and a fence has nothing further to enforce.
Op::Lfence | Op::Mfence | Op::Sfence => {}
// The control, status and tag words take their initial values. The
// no-wait form checks no pending exception, and the data registers,
// which Xenora does not model, are left alone and only tagged empty
// (Intel SDM Vol. 2A, "FINIT/FNINIT"). FNINIT also clears the x87
// instruction and data pointers and last opcode, which are not modelled.
Op::Fninit => cpu.x87 = X87State::INIT,
Op::Cpuid => {
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
// register write, so the upper halves are cleared.
@@ -742,6 +768,28 @@ pub fn execute(
Op::Clc => cpu.flags.cf = false,
Op::Stc => cpu.flags.cf = true,
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
// AH = SF:ZF:0:AF:0:PF:1:CF (Intel SDM Vol. 2A, LAHF).
Op::Lahf => {
let f = cpu.flags;
let ah = u64::from(f.sf) << 7
| u64::from(f.zf) << 6
| u64::from(f.af) << 4
| u64::from(f.pf) << 2
| 1 << 1
| u64::from(f.cf);
cpu.gpr[RAX] = cpu.gpr[RAX] & !0xFF00 | ah << 8;
}
// SF, ZF, AF, PF and CF from AH bits 7, 6, 4, 2 and 0; OF is
// unchanged (Intel SDM Vol. 2B, SAHF).
Op::Sahf => {
let ah = (cpu.gpr[RAX] >> 8) as u8;
let flags = &mut cpu.flags;
flags.sf = ah & 0x80 != 0;
flags.zf = ah & 0x40 != 0;
flags.af = ah & 0x10 != 0;
flags.pf = ah & 0x04 != 0;
flags.cf = ah & 0x01 != 0;
}
Op::Hlt => {
cpu.rip = next;
return Ok(Some(ExitReason::Halt));
File diff suppressed because it is too large. Load diff
+17 -8
View File
@@ -13,8 +13,8 @@
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
use xenora_loader::cpu::{
CPUID_CMOV, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason, Interpreter,
RFlags, cpuid,
CPUID_CMOV, CPUID_LAHF_SAHF, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason,
Interpreter, RFlags, cpuid,
};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
@@ -79,9 +79,9 @@ fn every_leaf_returns_its_documented_values() {
(1, 0xFFFF_FFFF, [0, 0, 0x0080_0000, 0x0000_8000]),
// Highest extended leaf.
(0x8000_0000, 0, [0x8000_0001, 0, 0, 0]),
// LZCNT is ECX bit 5 and long mode is EDX bit 29.
(0x8000_0001, 0, [0, 0, 0x0000_0020, 0x2000_0000]),
(0x8000_0001, 7, [0, 0, 0x0000_0020, 0x2000_0000]),
// LAHF/SAHF is ECX bit 0, LZCNT ECX bit 5 and long mode EDX bit 29.
(0x8000_0001, 0, [0, 0, 0x0000_0021, 0x2000_0000]),
(0x8000_0001, 7, [0, 0, 0x0000_0021, 0x2000_0000]),
// Everything else, above or between the highest leaves, is zeros.
(2, 0, [0; 4]),
(4, 0, [0; 4]),
@@ -129,8 +129,14 @@ fn every_leaf_returns_its_documented_values() {
.collect();
assert_eq!(vendor, b"Xenora guest");
assert_eq!(
(CPUID_POPCNT, CPUID_CMOV, CPUID_LZCNT, CPUID_LONG_MODE),
(1 << 23, 1 << 15, 1 << 5, 1 << 29)
(
CPUID_POPCNT,
CPUID_CMOV,
CPUID_LAHF_SAHF,
CPUID_LZCNT,
CPUID_LONG_MODE
),
(1 << 23, 1 << 15, 1, 1 << 5, 1 << 29)
);
}
@@ -189,6 +195,10 @@ fn reported_features_have_all_their_instructions_in_the_fixtures() {
decodable(&format!("{name} {high}, {}", memory(bits)));
}
}
// LAHF and SAHF have one form each and no operands.
assert_ne!(cpuid(0x8000_0001, 0)[ECX] & CPUID_LAHF_SAHF, 0);
decodable("lahf");
decodable("sahf");
// Long mode: 64-bit operands and the registers only it has.
assert_ne!(cpuid(0x8000_0001, 0)[EDX] & CPUID_LONG_MODE, 0);
decodable("add r9, r12");
@@ -232,7 +242,6 @@ fn unreported_features_each_have_an_instruction_that_is_refused() {
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
+109 -16
View File
@@ -41,6 +41,8 @@
//! `f=*` and `keep=` require the initial value. A case without `f=` on the
//! left runs with all flags clear and again with all flags set.
//! * `mx=` is MXCSR; `mx=~20:1b88` ignores the bits in `20`. `=?` ignores a value.
//! * `fcw=`, `fsw=` and `ftw=` are the x87 control, status and tag words. Every
//! case starts with all three away from their FNINIT values.
//! * Symbols: `D` writable data, `U` the unmapped page after it, `R` read-only
//! data, `S` stack, `C` code, `FSB` and `GSB` segment bases.
//! * Faults: `DE`, `GP`, `UD`, `XM`, and page faults `PFR`, `PFW`, `PFX` with
@@ -50,7 +52,7 @@
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags, X87State};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
use xenora_loader::x86_decode::decode;
@@ -598,6 +600,15 @@ const FLAG_MOVES: &str = r"
SDM 2A LAHF
lahf: rax=8877665544332211 f=CPASO => rax=8877665544339711 f=*
lahf_zero: rax=8877665544332211 f=Z => rax=8877665544334211 f=*
lahf_carry_only: rax=ffffffffffffffff f=C => rax=ffffffffffff03ff f=*
lahf_parity_only: rax=ffffffffffffffff f=P => rax=ffffffffffff06ff f=*
lahf_adjust_only: rax=ffffffffffffffff f=A => rax=ffffffffffff12ff f=*
lahf_sign_only: rax=ffffffffffffffff f=S => rax=ffffffffffff82ff f=*
lahf_does_not_store_of: rax=ffffffffffffffff f=O => rax=ffffffffffff02ff f=*
@ rex.w lahf
489f
SDM 2A LAHF; 2A 2.2.1.2
lahf_rex_w_changes_nothing: rax=ffffffffffffffff f=CO => rax=ffffffffffff03ff f=*
@ sahf; lahf
9e 9f
SDM 2B SAHF
@@ -606,6 +617,12 @@ sahf_ignores_bits_1_3_5: rax=ff00 f=O => rax=d700 f=CPAZSO
9e
SDM 2B SAHF
sahf_clear_keeps_of: rax=2800 f=OC => f=cpazsO
sahf_carry_only: rax=100 f=O => f=CpazsO
sahf_parity_only: rax=400 f=O => f=cPazsO
sahf_adjust_only: rax=1000 f=O => f=cpAzsO
sahf_zero_only: rax=4000 f=O => f=cpaZsO
sahf_sign_only: rax=8000 f=O => f=cpazSO
sahf_reads_only_ah: rax=ffffffffffff00ff f=CPAZS => f=cpazso
@ stc
f9
SDM 2B STC
@@ -1082,6 +1099,8 @@ cmov_all_unsigned_below_signed_greater: rax=1 rbx=80000000 => rcx=1 r8=1 r9=0 r1
b800000000 e305 b801000000 90
SDM 2A Jcc
jrcxz_tests_all_64_bits: rcx=100000000 => rax=1 f=*
jrcxz_sees_bit_63: rcx=8000000000000000 => rax=1 f=*
jrcxz_taken_at_zero_keeps_rcx: rcx=0 => rax=0 rcx=0 f=*
@ mov eax, 0; jecxz 1f; mov eax, 1; 1: nop
b800000000 67e305 b801000000 90
SDM 2A Jcc
@@ -1094,6 +1113,24 @@ loop_decrements_rcx_without_flags: rax=0 rcx=3 => rax=3 rcx=0 f=*
488d4001 e0fa
SDM 2A LOOP
loopne_stops_on_zero_flag: rax=0 rcx=5 f=Z => rax=1 rcx=4 f=*
@ mov eax, 0; loop 1f; mov eax, 1; 1: nop
b800000000 e205 b801000000 90
SDM 2A LOOP
loop_from_zero_wraps_and_branches: rcx=0 => rax=0 rcx=ffffffffffffffff f=*
loop_at_one_falls_through: rcx=1 => rax=1 rcx=0 f=*
loop_counts_all_64_bits: rcx=100000000 => rax=0 rcx=ffffffff f=*
@ mov eax, 0; loope 1f; mov eax, 1; 1: nop
b800000000 e105 b801000000 90
SDM 2A LOOP
loope_taken_with_zf: rcx=2 f=Z => rax=0 rcx=1 f=*
loope_not_taken_without_zf: rcx=2 f=CPASO => rax=1 rcx=1 f=*
loope_count_expires_with_zf: rcx=1 f=Z => rax=1 rcx=0 f=*
@ mov eax, 0; loopne 1f; mov eax, 1; 1: nop
b800000000 e005 b801000000 90
SDM 2A LOOP
loopne_taken_without_zf: rcx=2 f=CPASO => rax=0 rcx=1 f=*
loopne_not_taken_with_zf: rcx=2 f=Z => rax=1 rcx=1 f=*
loopne_count_expires_without_zf: rcx=1 => rax=1 rcx=0 f=*
";
const STACK_AND_CALLS: &str = r"
@@ -1533,6 +1570,36 @@ fences_change_no_register_or_flag: rax=1122334455667788 rbx=99aabbccddeeff00 =>
fences_ignore_the_rm_field: rax=1122334455667788 => f=*
";
/// FNINIT, the only x87 instruction (#378). The three words it sets are all the
/// x87 state there is: no data register, pointer or last opcode is modelled, and
/// nothing can read the words back yet, so the cases look at guest state.
const X87_INIT: &str = r"
@ fninit
dbe3
SDM 2A FINIT/FNINIT (Operation); 1 8.1.5 (control word 037FH); 1 8.1.7 (tag FFFFH)
fninit_sets_control_status_and_tag: fcw=0040 fsw=3a41 ftw=0000 => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_every_bit_set: fcw=ffff fsw=ffff ftw=0000 => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_every_bit_clear: fcw=0 fsw=0 ftw=0 => fcw=037f fsw=0 ftw=ffff f=*
fninit_twice_is_the_same: fcw=037f fsw=0 ftw=ffff => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_the_harness_default: => fcw=037f fsw=0 ftw=ffff f=*
@ fninit
dbe3
SDM 2A FINIT/FNINIT (the x87 words only; Flags Affected: C0 to C3 cleared, which are status-word bits)
fninit_keeps_registers_flags_xmm_and_mxcsr: rax=1122334455667788 rbx=99aabbccddeeff00 x3=q:0123456789abcdef,fedcba9876543210 mx=5fbf => fcw=037f fsw=0 ftw=ffff f=*
@ mov [rdi], rax; fninit; mov rbx, [rdi]
488907 dbe3 488b1f
SDM 2A FINIT/FNINIT
fninit_touches_no_memory: rdi=D rax=1122334455667788 m0=0000000000000000 => rbx=1122334455667788 m0=8877665544332211 fcw=037f fsw=0 ftw=ffff f=*
@ fninit; add al, bl
dbe3 00d8
SDM 2A FINIT/FNINIT; 2A ADD
fninit_then_integer_code_runs_on: rax=7f rbx=1 => rax=80 fcw=037f fsw=0 ftw=ffff f=cpAzSO
@ add al, bl
00d8
SDM 2A ADD (no x87 state is named)
integer_code_keeps_the_x87_words: rax=7f rbx=1 fcw=1a2b fsw=3c4d ftw=5e6f => rax=80 f=cpAzSO
";
const MEMORY_FAULTS: &str = r"
@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2
41b801000000 00d8 !488b0e 41b902000000
@@ -2814,11 +2881,23 @@ dpps_mask: x1=d:3f800000,40000000,40400000,40800000 x2=d:3f800000,3f800000,3f800
movddup_movsldup_movshdup: x2=d:7f800001,2,3,4 => x1=d:7f800001,2,7f800001,2 x3=d:7f800001,7f800001,3,3 x4=d:2,2,4,4 f=*
";
const DEFECT_OVERLONG_INSTRUCTION: &str = r"
const INSTRUCTION_LENGTH: &str = r"
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x01,0xd8
!666666666666666666666666666601d8
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
sixteen_byte_redundant_operand_size_prefixes: => ! GP
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
666666666666666666666666053412
SDM 2A 2.2.1 (15-byte limit); 2A ADD
fifteen_bytes_ending_in_the_immediate_execute: rax=ffffffffffff0001 => rax=ffffffffffff1235 f=cPazso
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
!66666666666666666666666666053412
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
sixteenth_byte_in_the_immediate_is_gp: rax=1 => ! GP
@ mov eax, 1; .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
b801000000 !66666666666666666666666666053412
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
overlong_after_an_instruction_retires_it_first: rax=ffffffffffffffff => rax=1 ! GP
";
const PAGE_CROSSING: &str = r"
@@ -2875,6 +2954,7 @@ const GROUPS: &[(&str, &str)] = &[
("fs_gs", FS_GS),
("decoding", DECODING),
("fences", FENCES),
("x87_init", X87_INIT),
("memory_faults", MEMORY_FAULTS),
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
("noncanonical_address", NONCANONICAL_ADDRESS),
@@ -2889,7 +2969,7 @@ const GROUPS: &[(&str, &str)] = &[
("fp_packed_and_sticky", FP_PACKED_AND_STICKY),
("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED),
("fp_beyond_sse2", FP_BEYOND_SSE2),
("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION),
("instruction_length", INSTRUCTION_LENGTH),
("exact_unmasked_overflow", EXACT_UNMASKED_OVERFLOW),
("page_crossing", PAGE_CROSSING),
];
@@ -2922,16 +3002,11 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("haddps_hsubpd_addsubps", 0),
("insertps_zero_mask", 0),
("jecxz_tests_low_32_bits", 1),
("jrcxz_tests_all_64_bits", 1),
("lahf", 0),
("lahf_zero", 0),
("lea64_addr32_truncates_effective_address", 0),
("lock_btc_memory", 0),
("lodsd_zero_extends", 1),
("lodsd_zero_extends_df_clear", 0),
("lodsw_preserves_upper48", 1),
("loop_decrements_rcx_without_flags", 1),
("loopne_stops_on_zero_flag", 1),
("maskmovdqu_selects_bytes", 0),
("mov_moffs64_load", 0),
("mov_moffs8_store", 0),
@@ -2973,8 +3048,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("roundps_uses_mxcsr_rc", 0),
("roundsd_suppress_precision", 0),
("roundss_imm_modes", 0),
("sahf_clear_keeps_of", 0),
("sahf_ignores_bits_1_3_5", 0),
];
// ---------------------------------------------------------------------------
@@ -3219,6 +3292,13 @@ fn initial_cpu() -> CpuState {
}
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
// None of the three is what FNINIT sets, so a reset is always visible and
// an instruction that wrongly resets one is caught by any case.
cpu.x87 = X87State {
control: 0x0c40,
status: 0x2b05,
tag: 0x5a5a,
};
cpu
}
@@ -3279,6 +3359,13 @@ fn apply(text: &str, expected: &mut Expected) {
expected.cpu.rip = value(data);
} else if key == "gsbase" {
expected.cpu.gs_base = value(data);
} else if let Some(word) = match key {
"fcw" => Some(&mut expected.cpu.x87.control),
"fsw" => Some(&mut expected.cpu.x87.status),
"ftw" => Some(&mut expected.cpu.x87.tag),
_ => None,
} {
*word = u16::try_from(value(data)).expect("a 16-bit x87 word");
} else if key == "mx" {
if data == "?" {
expected.mxcsr_mask = 0;
@@ -3513,6 +3600,9 @@ fn check(case: &Case, engine: Engine, initial_flags: u8) -> Result<(), String> {
if (cpu.fs_base, cpu.gs_base) != (want.cpu.fs_base, want.cpu.gs_base) {
text.push_str(" segment base changed;");
}
if cpu.x87 != want.cpu.x87 {
let _ = write!(text, " x87={:04x?} want {:04x?};", cpu.x87, want.cpu.x87);
}
let memory_text = Image::store(&memory).differences(&want.image);
if !memory_text.is_empty() {
let _ = write!(text, " memory{memory_text};");
@@ -3655,6 +3745,11 @@ fn fences() {
check_group(FENCES);
}
#[test]
fn x87_init() {
check_group(X87_INIT);
}
#[test]
fn memory_faults() {
check_group(MEMORY_FAULTS);
@@ -3726,9 +3821,8 @@ fn fp_beyond_sse2() {
}
#[test]
#[ignore = "known defect (#155): an instruction over 15 bytes is illegal, not #GP"]
fn defect_overlong_instruction() {
check_group(DEFECT_OVERLONG_INSTRUCTION);
fn instruction_length() {
check_group(INSTRUCTION_LENGTH);
}
#[test]
@@ -5629,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:?}");
+261
View File
@@ -0,0 +1,261 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! LOOP, LOOPE, LOOPNE and JRCXZ (issue #396).
//!
//! Expected results come from a step-by-step model written from the operation
//! sections of the Intel SDM Vol. 2A for LOOP/LOOPcc and Jcc. The model never
//! decodes or calls the production semantics. Encodings were assembled with
//! `clang -target x86_64-apple-macos` and read with `objdump`. Nothing was
//! compared with x86 hardware.
//!
//! In 64-bit mode with the default address size the count is RCX. LOOP
//! decrements it without changing a flag and branches while the result is not
//! zero; LOOPE also needs ZF set and LOOPNE ZF clear. JRCXZ branches when RCX is
//! zero and changes nothing.
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
const ENTRY: u64 = 0x1000;
const RAX: usize = 0;
const RCX: usize = 1;
const RBX: usize = 3;
const RDI: usize = 7;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
Loop,
Loope,
Loopne,
}
impl Kind {
fn opcode(self) -> u8 {
match self {
Kind::Loopne => 0xE0,
Kind::Loope => 0xE1,
Kind::Loop => 0xE2,
}
}
}
/// ```text
/// top: inc rbx 48 ff c3
/// cmp rbx, rdi 48 39 fb
/// jmp next eb 00 ; ends a translated block
/// next: loop/loope/loopne top
/// hlt f4
/// ```
fn loop_program(kind: Kind) -> Vec<u8> {
vec![
0x48,
0xFF,
0xC3,
0x48,
0x39,
0xFB,
0xEB,
0x00,
kind.opcode(),
0xF6,
0xF4,
]
}
/// Start of each instruction of [`loop_program`], and the end of HLT.
const OFFSETS: [u64; 6] = [0, 3, 6, 8, 10, 11];
fn image(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
}
/// The interpreter and the DBT, each from its own copy of the state. The DBT
/// result carries the state it left in its own copy.
fn both(cpu: &CpuState, code: &[u8], budget: usize) -> [(&'static str, ExecutionResult); 2] {
let mut interpreted = image(code);
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
let mut translated = image(code);
let mut state = cpu.clone();
let mut native = DbtEngine::new(64 * 1024)
.unwrap()
.run(&mut state, &mut translated, budget);
native.final_state = state;
[("interpreter", result), ("DBT", native)]
}
/// What the model predicts after at most `budget` instructions.
#[derive(Debug, PartialEq, Eq)]
struct Outcome {
exit: ExitReason,
executed: usize,
rip: u64,
rcx: u64,
rbx: u64,
zf: bool,
}
fn model(kind: Kind, rcx: u64, rbx: u64, rdi: u64, zf: bool, budget: usize) -> Outcome {
let (mut rcx, mut rbx, mut zf) = (rcx, rbx, zf);
let mut at = 0;
let mut executed = 0;
while executed < budget {
executed += 1;
at = match at {
// INC writes ZF too (Intel SDM Vol. 2A, INC).
0 => {
rbx = rbx.wrapping_add(1);
zf = rbx == 0;
1
}
1 => {
zf = rbx == rdi;
2
}
2 => 3,
3 => {
rcx = rcx.wrapping_sub(1);
let condition = match kind {
Kind::Loop => true,
Kind::Loope => zf,
Kind::Loopne => !zf,
};
if rcx != 0 && condition { 0 } else { 4 }
}
_ => {
return Outcome {
exit: ExitReason::Halt,
executed,
rip: ENTRY + OFFSETS[5],
rcx,
rbx,
zf,
};
}
};
}
Outcome {
exit: ExitReason::StepLimitExceeded,
executed,
rip: ENTRY + OFFSETS[at],
rcx,
rbx,
zf,
}
}
#[test]
fn loops_match_the_model_for_every_count_match_point_and_budget() {
let mut checked = 0;
for kind in [Kind::Loop, Kind::Loope, Kind::Loopne] {
let code = loop_program(kind);
for rcx in [0, 1, 2, 3, 5, 0x1_0000_0000] {
// RDI is the value of RBX after the iteration whose CMP sets ZF;
// 0 never matches within these counts.
for rdi in [0, 1, 2, 3, 4] {
for zf in [false, true] {
// Budgets that stop before, inside and after the loop.
for budget in [1, 3, 4, 5, 8, 9, 11, 13, 22, 200] {
let wanted = model(kind, rcx, 0, rdi, zf, budget);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RCX] = rcx;
cpu.gpr[RDI] = rdi;
cpu.flags.zf = zf;
for (engine, result) in both(&cpu, &code, budget) {
let state = &result.final_state;
let found = Outcome {
exit: result.exit_reason,
executed: result.instructions_executed,
rip: state.rip,
rcx: state.gpr[RCX],
rbx: state.gpr[RBX],
zf: state.flags.zf,
};
assert_eq!(
found, wanted,
"{kind:?} rcx={rcx:#x} rdi={rdi} zf={zf} budget={budget} on the {engine}"
);
checked += 1;
}
}
}
}
}
}
assert_eq!(checked, 3 * 6 * 5 * 2 * 10 * 2);
}
/// ```text
/// mov eax, 7 b8 07 00 00 00
/// jrcxz done e3 05
/// mov eax, 1 b8 01 00 00 00
/// done: hlt f4
/// ```
#[test]
fn jrcxz_branches_only_on_a_zero_rcx_and_changes_nothing() {
let code = [
0xB8, 0x07, 0x00, 0x00, 0x00, 0xE3, 0x05, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xF4,
];
let mut values = vec![0, 1, u64::MAX];
values.extend((0..64).map(|bit| 1u64 << bit));
for rcx in values {
for flags in [RFlags::default(), all_flags()] {
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RCX] = rcx;
cpu.flags = flags;
let mut wanted = cpu.clone();
wanted.gpr[RAX] = if rcx == 0 { 7 } else { 1 };
wanted.rip = ENTRY + code.len() as u64;
for (engine, result) in both(&cpu, &code, 8) {
assert_eq!(
result.exit_reason,
ExitReason::Halt,
"rcx={rcx:#x} {engine}"
);
let executed = if rcx == 0 { 3 } else { 4 };
assert_eq!(
result.instructions_executed, executed,
"rcx={rcx:#x} {engine}"
);
assert_eq!(result.final_state, wanted, "rcx={rcx:#x} {engine}");
}
}
}
}
/// LOOP from RCX = 0 wraps to 2^64 - 1 and branches. With a budget the loop
/// stops early, and both engines agree on the whole state.
#[test]
fn loop_from_zero_wraps_and_keeps_every_flag() {
let code = loop_program(Kind::Loop);
for flags in [RFlags::default(), all_flags()] {
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RDI] = 1;
cpu.flags = flags;
let [(_, interpreted), (_, translated)] = both(&cpu, &code, 4);
assert_eq!(interpreted.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(interpreted.final_state.gpr[RCX], u64::MAX);
assert_eq!(interpreted.final_state.rip, ENTRY);
// INC and CMP set the flags; LOOP leaves them as CMP left them.
let after_cmp = model(Kind::Loop, 0, 0, 1, flags.zf, 2).zf;
assert_eq!(interpreted.final_state.flags.zf, after_cmp);
assert_eq!(interpreted.final_state, translated.final_state);
assert_eq!(interpreted.exit_reason, translated.exit_reason);
}
}
fn all_flags() -> RFlags {
RFlags {
cf: true,
zf: true,
sf: true,
of: true,
pf: true,
af: true,
}
}
+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
+325
View File
@@ -0,0 +1,325 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Repeated-frame regression for the guest graphics context (issue #148).
//!
//! One device, queue, allocator and command list are driven through the
//! per-frame loop a D3D12 guest uses: reset, record, close, execute. Each
//! frame changes the guest-backed vertex data, the clear colour or the draw
//! parameters. Expected pixels are written out by hand below for triangles
//! chosen so their coverage of a 4×3 viewport is obvious; they are not
//! computed by the rasterizer under test. These tests use the software
//! reference backend only; no native Metal result is claimed here.
use xenora_loader::graphics::{
CommandListType, GraphicsBackendId, GraphicsContext, GraphicsError, GraphicsHandle,
ResourceDesc, ResourceDimension, ResourceStates,
};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
const WIDTH: usize = 4;
const HEIGHT: usize = 3;
const VERTICES: u64 = 0x0010_0000;
/// Two triangles of three float4 positions each.
const VERTEX_BYTES: usize = 96;
const RED: [u8; 4] = [255, 0, 0, 255];
/// Covers every pixel centre of the viewport.
const FULL: [[f32; 4]; 3] = [
[-1.0, -1.0, 0.0, 1.0],
[3.0, -1.0, 0.0, 1.0],
[-1.0, 3.0, 0.0, 1.0],
];
/// Its right edge is x = 0 in clip space, so it covers the two left columns
/// (centres at x = -0.75 and -0.25) and none of the two right ones.
const LEFT_HALF: [[f32; 4]; 3] = [
[0.0, 10.0, 0.0, 1.0],
[0.0, -10.0, 0.0, 1.0],
[-30.0, 0.0, 0.0, 1.0],
];
/// Lies wholly outside the viewport.
const OFFSCREEN: [[f32; 4]; 3] = [
[2.0, 2.0, 0.0, 1.0],
[3.0, 2.0, 0.0, 1.0],
[2.0, 3.0, 0.0, 1.0],
];
struct Rig {
ctx: GraphicsContext,
memory: GuestMemory,
queue: GraphicsHandle,
alloc: GraphicsHandle,
list: GraphicsHandle,
vertices: GraphicsHandle,
target: GraphicsHandle,
}
fn rig() -> Rig {
let mut ctx = GraphicsContext::new();
let device = ctx.create_device().unwrap();
let queue = ctx
.create_command_queue(device, CommandListType::Direct)
.unwrap();
let alloc = ctx
.create_command_allocator(device, CommandListType::Direct)
.unwrap();
let list = ctx
.create_command_list(device, alloc, CommandListType::Direct)
.unwrap();
// A new list starts open; close it so every frame begins with a reset.
ctx.close_command_list(list).unwrap();
let mut memory = GuestMemory::new();
memory
.map_region(VERTICES, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let buffer = ResourceDesc {
dimension: ResourceDimension::Buffer,
width: VERTEX_BYTES as u64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
};
let vertices = ctx
.create_committed_resource(
device,
buffer,
ResourceStates::VERTEX_AND_CONSTANT_BUFFER,
Some(VERTICES),
)
.unwrap();
let texture = ResourceDesc {
dimension: ResourceDimension::Texture2D,
width: WIDTH as u64,
height: HEIGHT as u32,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: true,
};
let target = ctx
.create_committed_resource(device, texture, ResourceStates::PRESENT, None)
.unwrap();
Rig {
ctx,
memory,
queue,
alloc,
list,
vertices,
target,
}
}
fn write_triangle(memory: &mut GuestMemory, slot: u64, triangle: [[f32; 4]; 3]) {
let bytes: Vec<u8> = triangle
.iter()
.flatten()
.flat_map(|value| value.to_le_bytes())
.collect();
memory.write_bytes(VERTICES + slot * 48, &bytes).unwrap();
}
/// Pixels with `columns` red from the left and the rest in `clear`.
fn expected(columns: usize, clear: [u8; 4]) -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(|pixel| if pixel % WIDTH < columns { RED } else { clear })
.collect()
}
struct Draw {
clear: [u8; 4],
offset: usize,
vertex_count: u32,
instance_count: u32,
start_vertex: u32,
start_instance: u32,
}
impl Draw {
fn one(clear: [u8; 4]) -> Self {
Self {
clear,
offset: 0,
vertex_count: 3,
instance_count: 1,
start_vertex: 0,
start_instance: 0,
}
}
}
/// Record one frame: target to RENDER_TARGET, draw, back to PRESENT.
fn record(rig: &mut Rig, draw: &Draw) -> Result<(), GraphicsError> {
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc)?;
ctx.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::PRESENT,
ResourceStates::RENDER_TARGET,
)?;
ctx.cmd_set_viewport(rig.list, WIDTH, HEIGHT)?;
ctx.cmd_set_render_targets(rig.list, Some(rig.target), draw.clear)?;
ctx.cmd_set_vertex_buffer(rig.list, rig.vertices, draw.offset, 48)?;
ctx.cmd_draw_instanced(
rig.list,
draw.vertex_count,
draw.instance_count,
draw.start_vertex,
draw.start_instance,
)?;
ctx.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)?;
ctx.close_command_list(rig.list)
}
fn frame(rig: &mut Rig, draw: &Draw) -> Result<(Vec<u8>, usize), GraphicsError> {
record(rig, draw)?;
let outcome = rig
.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)?;
assert_eq!(outcome.backend, GraphicsBackendId::SoftwareReference);
assert_eq!((outcome.width, outcome.height), (WIDTH, HEIGHT));
Ok((outcome.pixels, outcome.draw_count))
}
fn frame_index(rig: &Rig) -> u64 {
rig.ctx.last_presentation.lock().unwrap().frame_index
}
#[test]
fn each_frame_reflects_its_own_guest_vertices_and_clear_colour() {
let mut rig = rig();
let frames = [
(LEFT_HALF, [0, 0, 64, 255], 2),
(FULL, [10, 20, 30, 255], WIDTH),
(OFFSCREEN, [1, 2, 3, 4], 0),
(LEFT_HALF, [9, 9, 9, 255], 2),
];
for (index, (triangle, clear, columns)) in frames.into_iter().enumerate() {
write_triangle(&mut rig.memory, 0, triangle);
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
let want = expected(columns, clear);
assert_eq!(pixels, want, "frame {index}");
assert_eq!(draws, 1, "frame {index}");
assert_eq!(frame_index(&rig), index as u64 + 1);
// The presentation holds this frame's pixels, not an earlier one's.
let presented = rig.ctx.last_presentation.lock().unwrap().pixels.clone();
assert_eq!(presented, want, "presented frame {index}");
}
}
#[test]
fn a_zero_instance_or_zero_vertex_frame_draws_nothing() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, FULL);
let clear = [5, 6, 7, 255];
for (vertices, instances) in [(3, 0), (0, 1), (2, 1)] {
let draw = Draw {
vertex_count: vertices,
instance_count: instances,
..Draw::one(clear)
};
let (pixels, draws) = frame(&mut rig, &draw).unwrap();
assert_eq!(pixels, expected(0, clear), "{vertices} x {instances}");
assert_eq!(draws, 0, "{vertices} x {instances}");
}
// The next ordinary frame still draws.
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
assert_eq!((pixels, draws), (expected(WIDTH, clear), 1));
}
#[test]
fn unsupported_draw_parameters_fail_and_the_next_frame_recovers() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, LEFT_HALF);
write_triangle(&mut rig.memory, 1, FULL);
let clear = [0, 0, 0, 255];
frame(&mut rig, &Draw::one(clear)).unwrap();
let rejected = [
Draw {
start_vertex: 3,
..Draw::one(clear)
},
Draw {
instance_count: 2,
..Draw::one(clear)
},
Draw {
start_instance: 1,
..Draw::one(clear)
},
Draw {
vertex_count: 6,
..Draw::one(clear)
},
];
for draw in &rejected {
// Only the draw is rejected. The barrier before it already ran, so
// the target is left in RENDER_TARGET, as a guest would see it.
let before = frame_index(&rig);
let result = frame(&mut rig, draw);
assert!(
matches!(result, Err(GraphicsError::Unsupported(_))),
"{result:?}"
);
assert_eq!(frame_index(&rig), before, "a failed frame is not presented");
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
rig.ctx
.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)
.unwrap();
rig.ctx.close_command_list(rig.list).unwrap();
rig.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.unwrap();
}
// The second triangle is still reachable through the view offset.
let draw = Draw {
offset: 48,
..Draw::one(clear)
};
let (pixels, _) = frame(&mut rig, &draw).unwrap();
assert_eq!(pixels, expected(WIDTH, clear));
}
#[test]
fn a_vertex_view_outside_its_buffer_fails_without_reading_past_it() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, FULL);
write_triangle(&mut rig.memory, 1, FULL);
// Mapped guest memory continues past the buffer; the view must not.
write_triangle(&mut rig.memory, 2, FULL);
let clear = [0, 0, 0, 255];
for offset in [VERTEX_BYTES - 47, VERTEX_BYTES, usize::MAX - 100] {
let draw = Draw {
offset,
..Draw::one(clear)
};
assert_eq!(
frame(&mut rig, &draw),
Err(GraphicsError::IndexOutOfRange),
"offset {offset}"
);
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
rig.ctx
.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)
.unwrap();
rig.ctx.close_command_list(rig.list).unwrap();
rig.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.unwrap();
}
}
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -102,8 +102,8 @@ def cases():
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop", "cpuid",
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence",
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "lahf", "sahf",
"nop", "cpuid", "nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence", "fninit",
f"movnti {mem(32)}, ebx", f"movnti {mem(64)}, rbx",
f"movnti {mem(32)}, r9d", f"movnti {mem(64)}, r14", "push r9", "push rbx", "push -5", "push 0x12345678",
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
+3
View File
@@ -1185,6 +1185,8 @@ b7 21 | mov bh, 0x21
f8 | clc
f9 | stc
f5 | cmc
9f | lahf
9e | sahf
90 | nop
0f a2 | cpuid
0f 1f 40 08 | nop dword ptr [rax + 8]
@@ -1192,6 +1194,7 @@ f3 90 | pause
0f ae e8 | lfence
0f ae f0 | mfence
0f ae f8 | sfence
db e3 | fninit
0f c3 5c be 10 | movnti dword ptr [rsi + 4*rdi + 16], ebx
48 0f c3 5c be 10 | movnti qword ptr [rsi + 4*rdi + 16], rbx
44 0f c3 4c be 10 | movnti dword ptr [rsi + 4*rdi + 16], r9d
+140 -4
View File
@@ -11,7 +11,7 @@
//! but the interpreter and the DBT must still agree on the complete state.
use std::collections::{BTreeMap, BTreeSet};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags, X87State};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
use xenora_loader::x86_decode::decode;
@@ -67,6 +67,8 @@ struct Machine {
/// Stack qwords at STACK_TOP - 8 and STACK_TOP.
pushed: u64,
top: u64,
/// x87 control, status and tag words.
x87: [u16; 3],
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -329,6 +331,11 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
bits,
high: false,
};
let ah = Place::Reg {
index: RAX,
bits: 8,
high: true,
};
if let Some(code) = name.strip_prefix("cmov") {
let value = read(
@@ -787,18 +794,46 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
m.flags.cf = !m.flags.cf;
Outcome::Done(none)
}
// AH bits 7 to 0 are SF, ZF, 0, AF, 0, PF, 1 and CF; OF has no bit.
"lahf" => {
let f = m.flags;
let bits = [f.cf, true, f.pf, false, f.af, false, f.zf, f.sf];
let value = (0..8)
.filter(|&index| bits[index])
.map(|index| 1u128 << index)
.sum();
write(m, ah, value);
Outcome::Done(none)
}
"sahf" => {
let value = read(m, ah, 8);
m.flags.cf = bit(value, 0);
m.flags.pf = bit(value, 2);
m.flags.af = bit(value, 4);
m.flags.zf = bit(value, 6);
m.flags.sf = bit(value, 7);
Outcome::Done(none)
}
// The fences order memory accesses and compute nothing.
"nop" | "pause" | "lfence" | "mfence" | "sfence" => Outcome::Done(none),
"fninit" => {
// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation: FPUControlWord :=
// 037FH, FPUStatusWord := 0, FPUTagWord := FFFFH. Nothing else here
// is x87 state.
m.x87 = [0x037F, 0, 0xFFFF];
Outcome::Done(none)
}
"cpuid" => {
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
// and the four features whose every instruction exists, CMOV and
// POPCNT in leaf 1, LZCNT and long mode in leaf 0x8000_0001.
// and the five features whose every instruction exists, CMOV and
// POPCNT in leaf 1, LAHF/SAHF, LZCNT and long mode in leaf
// 0x8000_0001.
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
let values = match m.gpr[RAX] as u32 {
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
1 => [0, 0, 1 << 23, 1 << 15],
0x8000_0000 => [0x8000_0001, 0, 0, 0],
0x8000_0001 => [0, 0, 1 << 5, 1 << 29],
0x8000_0001 => [0, 0, 1 | 1 << 5, 1 << 29],
_ => [0; 4],
};
// EAX, EBX, ECX and EDX, each zero-extended.
@@ -898,6 +933,8 @@ impl Random {
operand: self.value(),
pushed: self.next(),
top: self.value(),
// Any bit pattern: nothing interprets these words.
x87: [self.next() as u16, self.next() as u16, self.next() as u16],
}
}
}
@@ -926,6 +963,12 @@ fn load(machine: &Machine, code: &[u8]) -> (CpuState, GuestMemory) {
pf: f.pf,
af: f.af,
};
let [control, status, tag] = machine.x87;
cpu.x87 = X87State {
control,
status,
tag,
};
(cpu, memory)
}
@@ -984,6 +1027,13 @@ fn every_fixture_instruction_matches_the_reference_in_both_engines() {
"{text}"
);
assert_eq!(state.rip, ENTRY + case.code.len() as u64, "{text}");
let x87 = state.x87;
assert_eq!(
[x87.control, x87.status, x87.tag],
expected.x87,
"{text}: x87 words from {:04x?}",
machine.x87
);
if !undefined.destination {
assert_eq!(state.gpr, expected.gpr, "{text} from {cpu:x?}");
assert_eq!(
@@ -1043,6 +1093,10 @@ fn every_declared_form_is_executed_by_a_fixture() {
let separate = [
Op::Ldmxcsr,
Op::Jcc,
Op::Loop,
Op::Loope,
Op::Loopne,
Op::Jrcxz,
Op::Jmp,
Op::Call,
Op::Ret,
@@ -1289,6 +1343,12 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
&[0x0F, 0xC3, 0xC1], // movnti with a register destination
&[0x66, 0x0F, 0xC3, 0x06], // 66 with movnti
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
&[0x9B], // fwait
&[0x9B, 0xDB, 0xE3], // finit: fwait, then fninit
&[0x66, 0xDB, 0xE3], // 66 with fninit
&[0xF3, 0xDB, 0xE3], // F3 with fninit
&[0xF2, 0xDB, 0xE3], // F2 with fninit
&[0xF0, 0xDB, 0xE3], // lock fninit
&[0xC6, 0xC8, 0x01], // C6 /1
&[0xFF, 0xF8], // FF /7
&[0xFE, 0xD0], // FE /2
@@ -1321,6 +1381,81 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
}
}
/// FNINIT (DB E3) is the only x87 instruction. Every other ModRM byte under the
/// eight x87 escape opcodes, D8 to DF, stops both engines and changes nothing.
/// That includes FNINIT's neighbours of the same digit, such as FNCLEX (DB E2),
/// and the memory forms of that digit.
#[test]
fn fninit_is_the_only_x87_encoding_accepted() {
let machine = Random(7).machine();
assert_ne!(
machine.x87,
[0x037F, 0, 0xFFFF],
"the reset must be visible"
);
let mut accepted = Vec::new();
for opcode in 0xD8..=0xDF_u8 {
for modrm in 0..=0xFF_u8 {
// The padding is a SIB byte and displacement for the memory forms.
let code = [opcode, modrm, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90];
for native in [false, true] {
let (mut cpu, mut memory) = load(&machine, &code);
let before = cpu.clone();
let data = bytes(&memory);
let result = if native {
DbtEngine::new(16 * 1024)
.unwrap()
.run(&mut cpu, &mut memory, 1)
} else {
Interpreter::new(cpu, &mut memory, 1).run()
};
let what = format!("{opcode:02X} {modrm:02X}, native {native}");
assert_eq!(bytes(&memory), data, "{what}");
if matches!(result.exit_reason, ExitReason::IllegalInstruction(_)) {
assert_eq!(result.final_state, before, "{what}");
continue;
}
accepted.push((opcode, modrm, native));
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{what}");
// Only RIP and the three x87 words may differ.
let mut wanted = before;
wanted.rip = ENTRY + 2;
wanted.x87 = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
assert_eq!(result.final_state, wanted, "{what}");
}
}
}
assert_eq!(accepted, [(0xDB, 0xE3, false), (0xDB, 0xE3, true)]);
}
/// A local rule, pinned so it cannot change unnoticed: a segment override or a
/// REX prefix before FNINIT is accepted and has no effect, as the decoder
/// treats them before any form without operands. It is not derived from a
/// manual statement. The prefixes that are refused are in
/// `undeclared_and_ambiguous_encodings_are_rejected`.
#[test]
fn prefixes_accepted_before_fninit_have_no_effect() {
let machine = Random(11).machine();
for prefix in [0x2E_u8, 0x64, 0x65, 0x40, 0x41, 0x48, 0x4F] {
let code = [prefix, 0xDB, 0xE3, 0x90];
let (cpu, _) = load(&machine, &code);
let mut wanted = cpu;
wanted.rip = ENTRY + 3;
wanted.x87 = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
let (state, exit, _) = run_both(&machine, &code, 1);
assert_eq!(exit, ExitReason::StepLimitExceeded, "{prefix:02X}");
assert_eq!(state, wanted, "{prefix:02X}");
}
}
#[test]
fn raw_syscalls_are_refused_by_the_dbt_only() {
let machine = Random(9).machine();
@@ -1447,6 +1582,7 @@ fn bit_scans_and_bit_tests_follow_the_architecture() {
operand: 0,
pushed: 0,
top: STACK_TOP,
x87: [0x037F, 0, 0xFFFF],
}
}
+58 -6
View File
@@ -178,7 +178,7 @@ fn interpreter_rejects_overlong_segment_prefix_run() {
.unwrap();
let cpu = CpuState::new(ENTRY, 0);
let result = Interpreter::new(cpu, &mut memory, 8).run();
assert_eq!(result.exit_reason, ExitReason::IllegalInstruction(0x65));
assert_eq!(result.exit_reason, ExitReason::GeneralProtection);
assert_eq!(result.instructions_executed, 0);
assert_eq!(result.final_state.rip, ENTRY);
}
@@ -195,9 +195,61 @@ fn dbt_rejects_overlong_segment_prefix_run() {
let result = DbtEngine::new(1024 * 1024)
.expect("JIT memory allocation")
.run(&mut cpu, &mut memory, 8);
assert!(
matches!(result.exit_reason, ExitReason::IllegalInstruction(_)),
"expected IllegalInstruction, got {:?}",
result.exit_reason
);
assert_eq!(result.exit_reason, ExitReason::GeneralProtection);
assert_eq!(result.instructions_executed, 0);
assert_eq!(cpu.rip, ENTRY);
}
/// Runs `prefixes` bytes of 0x66 that end exactly at the end of a mapped page,
/// with nothing mapped after it, on both engines.
fn run_prefixes_at_page_end(prefixes: usize) -> [(ExitReason, u64, u64); 2] {
const PAGE: u64 = 0x2000;
const PAGE_LEN: usize = 0x1000;
let mut data = vec![0x90; PAGE_LEN];
data[PAGE_LEN - prefixes..].fill(0x66);
let entry = PAGE + (PAGE_LEN - prefixes) as u64;
let mut memory = GuestMemory::new();
memory
.map_region_with_data(PAGE, PAGE_LEN, MemoryPermissions::READ_EXECUTE, &data)
.unwrap();
let interpreted = Interpreter::new(CpuState::new(entry, 0), &mut memory, 8).run();
let mut cpu = CpuState::new(entry, 0);
let translated = DbtEngine::new(1024 * 1024)
.expect("JIT memory allocation")
.run(&mut cpu, &mut memory, 8);
[
(
interpreted.exit_reason,
interpreted.final_state.rip,
interpreted.instructions_executed,
),
(
translated.exit_reason,
cpu.rip,
translated.instructions_executed,
),
]
.map(|(exit, rip, count)| (exit, rip.wrapping_sub(entry), count as u64))
}
/// Fifteen prefixes are already too long whatever follows, so the 16th byte is
/// never fetched: #GP, not a fetch fault on the unmapped page after them
/// (Intel SDM Vol. 3A, 7.15).
#[test]
fn overlong_instruction_is_gp_without_fetching_the_sixteenth_byte() {
for (exit, rip_offset, count) in run_prefixes_at_page_end(MAX_INSTRUCTION_LEN) {
assert_eq!(exit, ExitReason::GeneralProtection);
assert_eq!((rip_offset, count), (0, 0));
}
}
/// Control for the test above: fourteen prefixes leave room for an opcode, so
/// the fetch of the 15th byte is what fails.
#[test]
fn fourteen_prefixes_at_a_page_end_fault_on_the_fetch() {
for (exit, rip_offset, count) in run_prefixes_at_page_end(MAX_INSTRUCTION_LEN - 1) {
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
assert_eq!((rip_offset, count), (0, 0));
}
}
+65
View File
@@ -16,6 +16,9 @@
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
# Every other use of LOCK is rejected, as the architecture's #UD.
#
# rm = N requires the ModRM r/m field to be N. It needs register_only, so the
# form matches exactly one ModRM byte. At most one form per opcode and digit.
#
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
# A 16-byte memory operand must be aligned unless unaligned = true.
@@ -90,6 +93,11 @@ leave = { ref = "sdm LEAVE" }
call = { terminator = true, ref = "sdm CALL" }
jmp = { terminator = true, ref = "sdm JMP" }
jcc = { reads = "cf zf sf of pf", terminator = true, ref = "sdm Jcc" }
# The count is RCX: the address-size prefix that would select ECX is rejected.
loopne = { reads = "zf", terminator = true, ref = "sdm LOOP/LOOPcc" }
loope = { reads = "zf", terminator = true, ref = "sdm LOOP/LOOPcc" }
loop = { terminator = true, ref = "sdm LOOP/LOOPcc" }
jrcxz = { terminator = true, ref = "sdm Jcc" }
ret = { terminator = true, ref = "sdm RET" }
nop = { ref = "sdm NOP" }
hlt = { terminator = true, ref = "sdm HLT" }
@@ -97,9 +105,14 @@ syscall = { terminator = true, ref = "sdm SYSCALL" }
clc = { writes = "cf", ref = "sdm CLC" }
stc = { writes = "cf", ref = "sdm STC" }
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
# AH holds SF, ZF, AF, PF and CF; valid in 64-bit mode when CPUID
# 8000_0001h ECX bit 0 is set.
lahf = { reads = "cf zf sf pf af", ref = "sdm LAHF" }
sahf = { writes = "cf zf sf pf af", ref = "sdm SAHF" }
cpuid = { ref = "sdm CPUID" }
cld = { ref = "sdm CLD" }
std = { ref = "sdm STD" }
fninit = { ref = "sdm FINIT/FNINIT" }
# A REP form repeats by leaving RIP on itself, so these end a translated block.
movs = { terminator = true, ref = "sdm MOVS/MOVSB/MOVSW/MOVSD/MOVSQ" }
stos = { terminator = true, ref = "sdm STOS/STOSB/STOSW/STOSD/STOSQ" }
@@ -512,6 +525,18 @@ opcode = 0x99
enc = "none"
size = "v"
[[form]]
op = "sahf"
opcode = 0x9E
enc = "none"
size = "n"
[[form]]
op = "lahf"
opcode = 0x9F
enc = "none"
size = "n"
[[form]]
op = "mov"
opcode = 0xB0
@@ -563,6 +588,34 @@ opcode = 0xC9
enc = "none"
size = "q"
[[form]]
op = "loopne"
opcode = 0xE0
enc = "rel"
size = "n"
imm = "rel8"
[[form]]
op = "loope"
opcode = 0xE1
enc = "rel"
size = "n"
imm = "rel8"
[[form]]
op = "loop"
opcode = 0xE2
enc = "rel"
size = "n"
imm = "rel8"
[[form]]
op = "jrcxz"
opcode = 0xE3
enc = "rel"
size = "n"
imm = "rel8"
[[form]]
op = "call"
opcode = 0xE8
@@ -672,6 +725,18 @@ opcode = 0xFD
enc = "none"
size = "n"
# FNINIT is DB E3 and nothing else: the other register bytes of digit 4 are
# different instructions (DB E2 is FNCLEX) and the memory forms are not x87
# initialisation at all. No other x87 form is declared.
[[form]]
op = "fninit"
opcode = 0xDB
digit = 4
enc = "rm_unread"
size = "n"
register_only = true
rm = 3
[[form]]
op = "movzx"
map = "0f"
+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}"
);
}
}
}
}
+54
View File
@@ -0,0 +1,54 @@
[package]
name = "victory-shader"
description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders. Vendored from skakwy/victory-mac; see UPSTREAM.md."
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
publish = false
[dependencies]
thiserror = "2.0.21"
zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] }
[features]
# Host D3D12 pipeline checks (`emit::host`); Windows targets only.
host = ["dep:windows"]
# Debugging switches (emitted-module dumps and the like).
diagnostics = []
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_System_LibraryLoader"] }
windows = { version = "0.62.2", optional = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[target.'cfg(windows)'.dev-dependencies]
windows = { version = "0.62.2", features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[lints.rust]
unsafe_op_in_unsafe_fn = "deny"
unused_must_use = "deny"
[lints.clippy]
all = { level = "warn", priority = -1 }
# Same allowances as the upstream workspace (victory-mac Cargo.toml [workspace.lints.clippy]).
type_complexity = "allow"
needless_range_loop = "allow"
chunks_exact_to_as_chunks = "allow"
sliced_string_as_bytes = "allow"
collapsible_match = "allow"
manual_clamp = "allow"
implicit_saturating_sub = "allow"
min_max = "allow"
undocumented_unsafe_blocks = "allow"
+26
View File
@@ -0,0 +1,26 @@
# Upstream provenance: victory-shader
| | |
| --- | --- |
| Source | <https://github.com/skakwy/victory-mac>, directory `crates/victory-shader/` (Cargo.toml and `src/`) |
| Repository head when copied | `22b3f8e45a59` (2026-11-25); the directory's last change is commit `559357432b41` |
| Licence | GPL-3.0 (repository `LICENSE`); workspace manifest declares `GPL-3.0-or-later`, the same as BetterXen. No file in the crate carries a different licence |
| Third-party notice kept in place | `src/gfx10/opcodes.rs`: opcode names generated from Mesa's `aco_opcodes.py` (tag mesa-22.3.0), MIT, Copyright (c) 2018 Valve Corporation; the notice is in the file header |
| Authorization | skakwy and the VIctory-macOS maintainer authorize reuse of their contributions (relayed by the BetterXen maintainer). Other authors' lines are used under the repository's GPL-3.0 |
| Authors (commits touching this directory, from `git shortlog`) | Marvis (33), skakwy (12), fxceless (11), r4. (6), Duff (4), 9hvn9yt2vk-netizen (3), tedin7 (3), DexNom (2), Luiz Neves (2), Saitken91 (2), others; some commits are credited to an AI assistant |
| What it is | Xbox Series shader containers (DXBC with Xbox additions) and precompiled GFX10 (RDNA 2) machine code translated to PC DXIL (SM 6.6): GFX10 decoder and SP3 printer, control-flow structurizer, IR, register spilling, wave emulation, fp64 by integer operations, an own LLVM 3.7 bitcode writer and container signing |
| Upstream commit-level history | Not carried; see the upstream repository. This directory is a snapshot, so later upstream fixes must be merged by comparing with the pinned commit |
## Modifications made by BetterXen
Changes to upstream files (19 lines, nothing functional) and files BetterXen added (marked `BetterXen addition`, GPL-3.0-or-later): `src/emit/betterxen.rs` (a public `translate_native` for raw compute programs, same stages as `translate`) and `src/emit/betterxen_tests.rs` (BetterXen gfx1030 fixtures through the recompiler, and on the GPU under CrossOver). Two lines in `src/emit/mod.rs` declare them. Validation record: `docs/research/victory-shader-integration.md`.
### Edits to upstream files
- `Cargo.toml` rewritten: workspace-inherited dependency versions replaced by explicit ones (`thiserror` 2.0.21, `zlib-rs` 0.6.8, `windows` 0.62.2, `windows-sys` 0.61.2), same features and lint allowances as upstream's workspace.
- `src/lib.rs`: `#[rustfmt::skip]` on each `mod` so the vendored files stay byte-comparable with upstream.
- `src/emit/mod.rs`, `src/emit/f64.rs`, `src/emit/lower.rs`: `#[allow(...)]` attributes only, so the crate passes `clippy -D warnings` here. They silence imports and variables used only by Windows-only tests, an unused trait method, a test constant that looks like pi, and two dead duplicate match arms in `lower.rs` that exist upstream (an earlier arm already handles `v_cvt_f32_f64` and `v_permlanex16_b32`).
## Not carried
The upstream repository's other crates (`victory-gpu`, `victory-loader`, `victory-hle`, ...), which are tied to one console title and its runtime, and `mac/`, `tools/`. The shader inputs the upstream project was built for are not included; BetterXen validates this crate only with its own synthetic fixtures (see `docs/research/` for the validation record).
+696
View File
@@ -0,0 +1,696 @@
//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and
//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the
//! instruction returns for one ray and one node. The emitter lowers the
//! instruction to the same arithmetic in the same order
//! (`emit/intersect.rs`), so its code can be compared against this dword
//! for dword.
//!
//! The instruction tests one ray against one 64-byte node of a bounding
//! volume hierarchy and returns four dwords. Traversal (the stack, instance
//! transforms, culling, the hit distance `numerator / denominator`) is the
//! program's own code.
//!
//! # Node pointers
//!
//! A node pointer's low three bits are the node's kind, the rest its byte
//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the
//! base address of the descriptor (40 bits in dword 0 and the low byte of
//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer;
//! the 64-bit form a 64-bit one, with which a program uses one descriptor
//! with base 0 for every structure and adds `address >> 3` itself.
//!
//! | kind | node |
//! |---|---|
//! | 0-3 | triangle 0-3 of a triangle node |
//! | 4 | box node, 16-bit floats (64 bytes) |
//! | 5 | box node, 32-bit floats (128 bytes) |
//! | 6 | instance: not read by the instruction |
//! | 7 | procedural primitive: not read by the instruction |
//!
//! # Box nodes
//!
//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four
//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16
//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes
//! 112-127 are not read). The result is the pointers of the children whose
//! box the ray enters before its extent, nearest entry first when the
//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest.
//!
//! # Triangle nodes
//!
//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte
//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that
//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an
//! input triangle's second vertex at the former, its third at the latter
//! and its first at the remaining one, so I and J are the weights of the
//! input triangle's second and third vertices). Triangle `k` of the node
//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that
//! keeps fewer triangles in a node uses the bytes of the unused vertices
//! for its own data.
//!
//! With the descriptor's triangle return mode set (bit 120) the result is
//! the hit distance's numerator, its denominator, and the numerators of I
//! and J over the same denominator, as floats. The denominator is positive
//! for a triangle whose vertices run clockwise seen from the ray's origin
//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0.
//! The ray's extent is not tested for triangles.
//!
//! # Where this comes from
//!
//! The node formats, the descriptor bits and the tests are those of the
//! public software emulation of this instruction in the open-source Vulkan
//! driver for this GPU family (box test and sorting network as there; the
//! triangle test is the watertight one it uses, Woop, Benthin and Wald,
//! JCGT 2013), and agree with what the title's own structure
//! builder writes and its trace programs read. Not known from either: how
//! the console rounds, which of two boxes entered at the same distance it
//! returns first, and what it returns for a ray exactly through an edge
//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here:
//! a triangle miss; the title's programs do not read it).
/// The result dword for a box the ray misses, or a child that is not there.
pub const NONE: u32 = 0xffff_ffff;
/// The node's vertices that make triangle 0-3, by the triangle's own
/// vertex numbers 0-2.
pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]];
/// Descriptor dword 1: boxes are returned nearest first.
pub const BOX_SORT: u32 = 1 << 31;
/// Descriptor dword 3: triangles return the numerators of I and J (clear:
/// a triangle id and a hit status, which nothing here produces).
pub const RETURN_BARYCENTRICS: u32 = 1 << 24;
/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing
/// structure.
pub const DESCRIPTOR_TYPE: u32 = 8;
/// The ray as the instruction takes it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ray {
pub extent: f32,
pub origin: [f32; 3],
pub direction: [f32; 3],
/// What the program computed as `1 / direction`.
pub inverse: [f32; 3],
}
impl Ray {
/// A ray with the inverse direction a program computes by division.
pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self {
Self {
extent,
origin,
direction,
inverse: direction.map(|d| 1.0 / d),
}
}
}
/// The kind of the node a pointer names.
pub fn kind(pointer: u64) -> u32 {
(pointer & 7) as u32
}
/// The byte address of the node `pointer` names, for a descriptor whose
/// first two dwords are `word0` and `word1`.
pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 {
let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8;
base.wrapping_add((pointer >> 3) << 6)
}
/// What the instruction returns for the node at `words` (its first 28
/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer
/// of this `kind`, with box sorting as `sort` says and the triangle return
/// mode set.
pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] {
match kind & 7 {
4 => boxes(&children(words), &boxes16(words), ray, sort),
5 => boxes(&children(words), &boxes32(words), ray, sort),
k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits),
_ => MISS.map(f32::to_bits),
}
}
/// A box node's four child pointers.
pub fn children(words: &[u32; 28]) -> [u32; 4] {
[words[0], words[1], words[2], words[3]]
}
/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z.
pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] {
std::array::from_fn(|b| {
std::array::from_fn(|k| {
let half = 6 * b + k;
half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16)
})
})
}
/// The four boxes of a 32-bit box node.
pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] {
std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k])))
}
/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest
/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432,
/// 0x042).
pub fn vertex_map(k: u32) -> u32 {
let v = TRIANGLE_VERTICES[(k & 3) as usize];
v[0] | v[1] << 4 | v[2] << 8
}
/// The vertices of triangle `k` (0-3) of a triangle node, the first being
/// the one neither barycentric weighs, then I's, then J's.
pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] {
let id = words[15] >> (8 * k);
let (i, j) = (id & 3, id >> 2 & 3);
// An id naming one vertex twice, or a vertex 3, is malformed; it reads
// what this arithmetic lands on (a vertex of the node), as the emitted
// code does.
let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3;
[first, i, j].map(|n| {
let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize;
std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c]))
})
}
/// The box test: child pointers of the boxes the ray enters, `NONE` for
/// the others; sorted by entry distance when `sort`, in child order
/// otherwise.
pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] {
// An infinite inverse (a direction component of 0) would turn an
// origin exactly on a box's face into a NaN. (Maximum then minimum, as
// the emitted code: a NaN becomes the lower bound, where `clamp` would
// keep it.)
#[allow(clippy::manual_clamp)]
let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX));
let mut ids = [NONE; 4];
let mut distances = [f32::INFINITY; 4];
for (n, b) in boxes.iter().enumerate() {
let (mut near, mut far) = ([0f32; 3], [0f32; 3]);
for a in 0..3 {
let low = (b[a] - ray.origin[a]) * inverse[a];
let high = (b[3 + a] - ray.origin[a]) * inverse[a];
near[a] = low.min(high);
far[a] = low.max(high);
}
let enter = near[0].max(near[1]).max(near[2]);
let leave = far[0].min(far[1]).min(far[2]);
// A box whose minimum x is NaN is switched off.
if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
ids[n] = children[n];
distances[n] = enter;
}
}
if sort {
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
if distances[b] < distances[a] {
distances.swap(a, b);
ids.swap(a, b);
}
}
}
ids
}
/// What a triangle the ray misses returns.
pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0];
/// The triangle test: the hit distance's numerator, the denominator, and
/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise.
/// Watertight: the vertices are sheared so the ray runs along its largest
/// axis, and the signs of the three edge functions decide, so a ray
/// between two triangles that share an edge cannot miss both. Any NaN
/// misses, and so does a triangle seen edge-on.
pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] {
let d = ray.direction;
let size = d.map(f32::abs);
// The largest axis, and the other two in an order that keeps the
// triangle's winding.
let kz = if size[0] >= size[1] {
if size[0] >= size[2] { 0 } else { 2 }
} else if size[1] >= size[2] {
1
} else {
2
};
let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3);
if d[kz] < 0.0 {
std::mem::swap(&mut kx, &mut ky);
}
let sz = ray.inverse[kz];
let (sx, sy) = (d[kx] * sz, d[ky] * sz);
let sheared = |v: &[f32; 3]| {
let r = [
v[0] - ray.origin[0],
v[1] - ray.origin[1],
v[2] - ray.origin[2],
];
(r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz])
};
let (ax, ay, az) = sheared(&p[0]);
let (bx, by, bz) = sheared(&p[1]);
let (cx, cy, cz) = sheared(&p[2]);
let u = cx * by - cy * bx;
let v = ax * cy - ay * cx;
let w = bx * ay - by * ax;
let behind = u < 0.0 || v < 0.0 || w < 0.0;
let before = u > 0.0 || v > 0.0 || w > 0.0;
let det = u + (v + w);
let t = (u * az + v * bz) + w * cz;
let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0;
if !(behind && before) && ahead {
[t, det, v, w]
} else {
MISS
}
}
/// A 16-bit float as a 32-bit one (exact).
pub fn half_to_f32(h: u16) -> f32 {
let sign = u32::from(h >> 15) << 31;
let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff));
let bits = match exponent {
0 if mantissa == 0 => sign,
0 => {
// Subnormal: normalise.
let shift = mantissa.leading_zeros() - 21;
sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13
}
0x1f => sign | 0xff << 23 | mantissa << 13,
e => sign | (e + 112) << 23 | mantissa << 13,
};
f32::from_bits(bits)
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
/// The smallest 16-bit float not below `x` (`up`) or not above it.
pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
let mut best: Option<u16> = None;
for h in 0..=0xffffu16 {
let f = half_to_f32(h);
if f.is_nan() || if up { f < x } else { f > x } {
continue;
}
best = match best {
Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b),
_ => Some(h),
};
}
best.expect("a half")
}
/// A 32-bit box node.
pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
let mut w = [0u32; 28];
w[..4].copy_from_slice(&children);
for (b, bx) in boxes.iter().enumerate() {
for (k, x) in bx.iter().enumerate() {
w[4 + 6 * b + k] = x.to_bits();
}
}
w
}
/// A 16-bit box node holding `boxes` rounded outward.
pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
let mut w = [0u32; 28];
w[..4].copy_from_slice(&children);
for (b, bx) in boxes.iter().enumerate() {
for (k, x) in bx.iter().enumerate() {
let half = 6 * b + k;
let h = if x.is_nan() {
0x7e00
} else {
f32_to_half(*x, k >= 3)
};
w[4 + half / 2] |= u32::from(h) << (16 * (half % 2));
}
}
w
}
/// A triangle node: up to five vertices, and the dword at byte 60.
pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] {
let mut w = [0u32; 28];
for (n, v) in vertices.iter().enumerate() {
for (c, x) in v.iter().enumerate() {
w[3 * n + c] = x.to_bits();
}
}
w[15] = id;
w
}
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] {
std::array::from_fn(|k| b[k] + by[k % 3])
}
const OFF: [f32; 6] = [f32::NAN; 6];
#[test]
fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() {
// The 64-bit form as the title uses it: base 0, the structure's
// address folded into the pointer.
let structure = 0x12_3456_7800u64;
let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5);
assert_eq!(kind(pointer), 5);
assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40);
// The 32-bit form: the base in the descriptor.
let word0 = (structure >> 8) as u32;
let word1 = (structure >> 40) as u32 | BOX_SORT;
assert_eq!(
node_address(word0, word1, 0x1000 >> 3 | 4),
structure + 0x1000
);
// A base past 4 GiB of 256-byte units.
assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64);
}
#[test]
fn halves_convert_exactly() {
assert_eq!(half_to_f32(0x3c00), 1.0);
assert_eq!(half_to_f32(0xc000), -2.0);
assert_eq!(half_to_f32(0x7c00), f32::INFINITY);
assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24));
assert_eq!(half_to_f32(0x7bff), 65504.0);
assert!(half_to_f32(0x7e00).is_nan());
assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000);
// Outward rounding of the test helper.
assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1);
assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1);
}
#[test]
fn boxes_are_returned_nearest_first_and_misses_last() {
let children = [0x105, 0x20c, 0x304, 0x400];
// Along +x from the origin: boxes at x = 30, 10, (off axis), 20.
let node = box32(
children,
[
moved(UNIT, [30.0, 0.0, 0.0]),
moved(UNIT, [10.0, 0.0, 0.0]),
moved(UNIT, [10.0, 5.0, 0.0]),
moved(UNIT, [20.0, 0.0, 0.0]),
],
);
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]);
// Without sorting: child order, the miss in its place.
assert_eq!(
intersect(&node, 5, &ray, false),
[0x105, 0x20c, NONE, 0x400]
);
// The extent cuts the far ones off (entered at 9, 19, 29).
let short = Ray {
extent: 19.5,
..ray
};
assert_eq!(
intersect(&node, 5, &short, true),
[0x20c, 0x400, NONE, NONE]
);
// An entry exactly at the extent is no hit.
let exact = Ray {
extent: 19.0,
..ray
};
assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]);
// Backwards: nothing.
let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]);
}
#[test]
fn a_ray_starting_inside_a_box_enters_it_at_its_origin() {
let node = box32(
[8, 16, NONE, NONE],
[UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF],
);
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
// Box 0 is entered at -1 (behind the origin), box 1 at 2.
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]);
// Even with a tiny extent the box around the origin is a hit.
let tiny = Ray {
extent: 1e-6,
..ray
};
assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]);
}
#[test]
fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() {
let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]);
// Direction components of 0: the inverse is infinite.
let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert!(ray.inverse[1].is_infinite());
// The origin lies in the plane of the box's -y face: (-1 - -1) x inf
// would be a NaN; with the inverse held finite it is 0, and the ray
// running along the face is inside.
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
// Along the +y face it is outside: the face's plane is left at 0
// and the box is entered at 4 (as the public emulation has it).
let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]);
let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]);
// -0 gives -infinity.
let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0);
assert_eq!(minus.inverse[1], f32::NEG_INFINITY);
assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]);
}
#[test]
fn a_box_switched_off_and_a_missing_child_return_none() {
let node = box32(
[8, NONE, 24, 32],
[UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF],
);
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
// Child 1 is hit but is not there: its pointer is what "none" is.
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
}
#[test]
fn equal_distances_keep_child_order() {
let node = box32([8, 16, 24, 32], [UNIT; 4]);
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]);
}
#[test]
fn half_float_boxes_test_like_their_widened_values() {
let boxes = [
moved(UNIT, [30.0, 0.1, 0.0]),
moved(UNIT, [10.0, 0.0, 0.3]),
moved(UNIT, [10.0, 5.0, 0.0]),
moved(UNIT, [20.7, 0.0, 0.0]),
];
let children = [0x105, 0x20c, 0x304, 0x400];
let node = box16(children, boxes);
let wide = boxes16(&node);
for (w, b) in wide.iter().zip(&boxes) {
for k in 0..3 {
assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward");
}
}
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]);
assert_eq!(
intersect(&node, 4, &ray, true),
intersect(&box32(children, wide), 5, &ray, true)
);
}
/// The hit a result describes: distance, I, J, front face.
fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> {
let [t, det, i, j] = r.map(f32::from_bits);
(t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0))
}
/// Clockwise seen from the origin looking down +z in a left-handed
/// system (x right, y up): the front face.
const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
#[test]
fn a_triangle_returns_distance_and_weights_over_one_denominator() {
let node = triangles(&TRIANGLE, 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert_eq!(t, 5.0);
// (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2.
assert_eq!((i, j), (0.25, 0.25));
assert!(front);
// Near vertex 1: I near 1.
let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0);
let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert!(i > 0.85 && j < 0.1, "{i} {j}");
// From behind: the same weights, the back face.
let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0);
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false));
// An unnormalised direction: the distance is in its units.
let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0);
assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25);
}
#[test]
fn a_triangle_is_missed_beside_behind_and_edge_on() {
let node = triangles(&TRIANGLE, 9);
let miss = MISS.map(f32::to_bits);
// Beside it.
let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// It lies behind the origin.
let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// In its plane.
let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// A triangle with no area.
let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9);
let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&flat, 0, &ray, true), miss);
// A vertex that is not a number, a direction of zero.
let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&nan, 0, &ray, true), miss);
let still = Ray::new([0.0; 3], [0.0; 3], 100.0);
assert_eq!(intersect(&node, 0, &still, true), miss);
// The extent is the program's to test: a far triangle is a hit.
let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0);
assert!(hit(intersect(&node, 0, &short, true)).is_some());
}
#[test]
fn a_ray_through_a_shared_edge_misses_neither_triangle() {
// Two triangles of a quad sharing the diagonal, wound alike.
let quad = [
[-1.0, -1.0, 4.0],
[-1.0, 1.0, 4.0],
[1.0, 1.0, 4.0],
[1.0, -1.0, 4.0],
];
let first = triangles(&[quad[0], quad[1], quad[2]], 9);
let second = triangles(&[quad[0], quad[2], quad[3]], 9);
// A fan of rays crossing the diagonal, some exactly on it.
for n in -40..=40 {
let x = n as f32 / 64.0;
for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] {
for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] {
// Aim at (ox, oy, 4).
let s = 4.0 / d[2];
let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0);
let a = hit(intersect(&first, 0, &ray, true));
let b = hit(intersect(&second, 0, &ray, true));
assert!(
a.is_some() || b.is_some(),
"a hole at {ox} {oy} along {d:?}"
);
for h in [a, b].into_iter().flatten() {
assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}");
}
}
}
}
}
#[test]
fn the_id_dword_says_which_vertices_the_weights_belong_to() {
// What the title's builder does with an input triangle (a, b, c)
// and an id byte: a at the vertex neither field names, b at I's,
// c at J's.
let [a, b, c] = TRIANGLE;
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] {
let mut stored = [[0f32; 3]; 3];
stored[(3 - i - j) as usize] = a;
stored[i as usize] = b;
stored[j as usize] = c;
let node = triangles(&stored, i | j << 2);
assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}");
}
// The higher bits of the byte (opaque and the like) change nothing.
let node = triangles(&[a, b, c], 9 | 0x80);
assert_eq!(intersect(&node, 0, &ray, true), plain);
}
#[test]
fn triangles_one_to_three_take_their_vertices_and_their_id_byte() {
let [a, b, c] = TRIANGLE;
let far = [50.0, 50.0, 50.0];
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
for k in 1..4u32 {
// Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`.
let mut vertices = [far; 5];
let at = TRIANGLE_VERTICES[k as usize];
vertices[at[0] as usize] = a;
vertices[at[1] as usize] = b;
vertices[at[2] as usize] = c;
// Triangle 0's byte would be malformed here; only byte k counts.
let node = triangles(&vertices, 9 << (8 * k));
assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}");
}
// A pair as the title's builder stores it: the second triangle's
// own vertex at node vertex 3, named by I.
let d = [2.0, 2.0, 5.0];
// Input triangles (a, b, c) and (a, d, b): they share a and b.
let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8);
// Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2.
let got = triangle_vertices(&node, 1);
assert_eq!(got, [b, d, c]);
}
#[test]
fn instances_and_procedural_nodes_return_a_triangle_miss() {
let node = triangles(&TRIANGLE, 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
for k in [6, 7] {
assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits));
}
}
#[test]
fn the_largest_axis_and_its_sign_do_not_change_the_answer() {
// The same triangle and ray turned so the ray's largest axis is each
// of the three, forwards and backwards. Both turns are rotations,
// so the facing stays.
let turn = |v: [f32; 3], axis: usize, flip: bool| {
let mut r = v;
for _ in 0..axis {
r = [r[2], r[0], r[1]];
}
if flip {
// Half a turn about the axis after the largest one's next.
let largest = (2 + axis) % 3;
r[largest] = -r[largest];
r[(largest + 1) % 3] = -r[(largest + 1) % 3];
}
r
};
let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0);
let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit");
for axis in 0..3 {
for flip in [false, true] {
let p = TRIANGLE.map(|v| turn(v, axis, flip));
let r = Ray::new(
turn(ray.origin, axis, flip),
turn(ray.direction, axis, flip),
100.0,
);
let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit");
assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}");
assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5);
assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}");
}
}
}
}
+181
View File
@@ -0,0 +1,181 @@
//! The DXBC container: a header, then a table of FourCC-tagged parts.
//!
//! ```text
//! 0x00 "DXBC"
//! 0x04 digest[16]
//! 0x14 version major u16, minor u16
//! 0x18 total size u32
//! 0x1C part count u32
//! 0x20 part offsets u32[count]
//! part: fourcc[4], size u32, data[size]
//! ```
use crate::ShaderError;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FourCC(pub [u8; 4]);
impl FourCC {
pub const DXIL: FourCC = FourCC(*b"DXIL");
pub const STAT: FourCC = FourCC(*b"STAT");
pub const RTS0: FourCC = FourCC(*b"RTS0");
pub const PSV0: FourCC = FourCC(*b"PSV0");
pub const ISG1: FourCC = FourCC(*b"ISG1");
pub const OSG1: FourCC = FourCC(*b"OSG1");
/// Per-primitive outputs of a mesh shader.
pub const PSG1: FourCC = FourCC(*b"PSG1");
pub const SFI0: FourCC = FourCC(*b"SFI0");
pub const HASH: FourCC = FourCC(*b"HASH");
pub const ILDB: FourCC = FourCC(*b"ILDB");
pub const ILDN: FourCC = FourCC(*b"ILDN");
}
impl std::fmt::Debug for FourCC {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self)
}
}
impl std::fmt::Display for FourCC {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for &b in &self.0 {
let c = if b.is_ascii_graphic() { b as char } else { '.' };
write!(f, "{c}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Part<'a> {
pub fourcc: FourCC,
/// Offset of the part header within the container.
pub offset: usize,
pub data: &'a [u8],
}
#[derive(Debug, Clone)]
pub struct Container<'a> {
pub digest: [u8; 16],
pub version: (u16, u16),
pub parts: Vec<Part<'a>>,
}
const HEADER_SIZE: usize = 0x20;
const MAX_PARTS: usize = 256;
impl<'a> Container<'a> {
pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> {
if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" {
return Err(ShaderError::NotDxbc);
}
let digest = data[4..20].try_into().expect("16 bytes");
let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?);
let total = u32_at(data, 0x18)? as usize;
if total > data.len() || total < HEADER_SIZE {
return Err(ShaderError::Malformed("container size disagrees with data"));
}
let data = &data[..total];
let count = u32_at(data, 0x1C)? as usize;
if count > MAX_PARTS {
return Err(ShaderError::Malformed("implausible part count"));
}
let mut parts = Vec::with_capacity(count);
for i in 0..count {
let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize;
let fourcc = FourCC(
data.get(offset..offset + 4)
.ok_or(ShaderError::Malformed("part header out of bounds"))?
.try_into()
.expect("4 bytes"),
);
let size = u32_at(data, offset + 4)? as usize;
let body = data
.get(offset + 8..offset + 8 + size)
.ok_or(ShaderError::Malformed("part data out of bounds"))?;
parts.push(Part {
fourcc,
offset,
data: body,
});
}
Ok(Container {
digest,
version,
parts,
})
}
pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> {
self.parts.iter().find(|p| p.fourcc == fourcc)
}
}
pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
data.get(at..at + 2)
.map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
pub(crate) fn u32_at(data: &[u8], at: usize) -> Result<u32, ShaderError> {
data.get(at..at + 4)
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
pub(crate) fn u64_at(data: &[u8], at: usize) -> Result<u64, ShaderError> {
data.get(at..at + 8)
.map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
/// Builds a container from parts (test helper).
#[cfg(test)]
pub fn build(parts: &[(FourCC, &[u8])]) -> Vec<u8> {
let table = HEADER_SIZE + 4 * parts.len();
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
let mut out = Vec::with_capacity(total);
out.extend_from_slice(b"DXBC");
out.extend_from_slice(&[0; 16]);
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&(total as u32).to_le_bytes());
out.extend_from_slice(&(parts.len() as u32).to_le_bytes());
let mut offset = table;
for (_, d) in parts {
out.extend_from_slice(&(offset as u32).to_le_bytes());
offset += 8 + d.len();
}
for (fourcc, d) in parts {
out.extend_from_slice(&fourcc.0);
out.extend_from_slice(&(d.len() as u32).to_le_bytes());
out.extend_from_slice(d);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_parts() {
let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]);
let c = Container::parse(&bytes).unwrap();
assert_eq!(c.parts.len(), 2);
assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]);
assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20);
assert!(c.part(FourCC::DXIL).is_none());
}
#[test]
fn rejects_bad_input() {
assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc);
let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]);
let last = bytes.len() - 1;
bytes[0x20] = 0xFF; // corrupt the first part offset
assert!(Container::parse(&bytes).is_err());
bytes.truncate(last);
assert!(Container::parse(&bytes).is_err());
}
}
+211
View File
@@ -0,0 +1,211 @@
//! The DXIL program inside a container's `DXIL` (or `STAT`) part.
//!
//! ```text
//! 0x00 program version u32 (kind << 16 | major << 4 | minor)
//! 0x04 size in dwords u32
//! 0x08 "DXIL" <- bitcode offset is relative to here
//! 0x0C dxil version u32
//! 0x10 bitcode offset u32 (16 in standard PC DXIL)
//! 0x14 bitcode size u32
//! ```
use crate::ShaderError;
use crate::dxbc::u32_at;
const LLVM_BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xC0, 0xDE];
#[cfg(test)]
const STANDARD_BITCODE_OFFSET: u32 = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShaderKind {
Pixel,
Vertex,
Geometry,
Hull,
Domain,
Compute,
Library,
RayGeneration,
Intersection,
AnyHit,
ClosestHit,
Miss,
Callable,
Mesh,
Amplification,
Node,
Unknown(u16),
}
impl ShaderKind {
fn from_raw(v: u16) -> Self {
use ShaderKind::*;
match v {
0 => Pixel,
1 => Vertex,
2 => Geometry,
3 => Hull,
4 => Domain,
5 => Compute,
6 => Library,
7 => RayGeneration,
8 => Intersection,
9 => AnyHit,
10 => ClosestHit,
11 => Miss,
12 => Callable,
13 => Mesh,
14 => Amplification,
15 => Node,
other => Unknown(other),
}
}
}
#[derive(Debug, Clone)]
pub struct DxilProgram<'a> {
pub kind: ShaderKind,
pub shader_model: (u8, u8),
pub dxil_version: u32,
/// LLVM bitcode (starts with `BC C0 DE`).
pub bitcode: &'a [u8],
/// Bytes between the bitcode header and the bitcode. Empty on PC.
pub prefix: &'a [u8],
/// Bytes after the bitcode, up to the program size. Empty on PC.
pub trailer: &'a [u8],
}
/// Xbox additions recognised around the bitcode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct XboxExtras {
/// The prefix starts with an `XDAT` table.
pub xdat: bool,
/// The trailer contains an `xbop` blob (compiler options).
pub xbop: bool,
}
impl<'a> DxilProgram<'a> {
pub fn parse(part: &'a [u8]) -> Result<Self, ShaderError> {
let version = u32_at(part, 0)?;
let size = (u32_at(part, 4)? as usize)
.checked_mul(4)
.filter(|&s| s <= part.len() && s >= 24)
.ok_or(ShaderError::Malformed(
"program size disagrees with part size",
))?;
let part = &part[..size];
if part.get(8..12) != Some(b"DXIL") {
return Err(ShaderError::Malformed("missing DXIL magic"));
}
let dxil_version = u32_at(part, 12)?;
let offset = u32_at(part, 16)?;
let len = u32_at(part, 20)? as usize;
let start = 8 + offset as usize;
let bitcode = part
.get(start..start + len)
.ok_or(ShaderError::Malformed("bitcode out of bounds"))?;
if bitcode.get(0..4) != Some(&LLVM_BITCODE_MAGIC) {
return Err(ShaderError::Malformed("bitcode lacks LLVM magic"));
}
let prefix = part
.get(24..start)
.ok_or(ShaderError::Malformed("bitcode offset too small"))?;
Ok(DxilProgram {
kind: ShaderKind::from_raw((version >> 16) as u16),
shader_model: (((version >> 4) & 0xF) as u8, (version & 0xF) as u8),
dxil_version,
bitcode,
prefix,
trailer: &part[start + len..],
})
}
/// True for a program laid out exactly like PC DXIL.
pub fn is_standard_layout(&self) -> bool {
self.prefix.is_empty() && self.trailer.is_empty()
}
pub fn xbox_extras(&self) -> XboxExtras {
XboxExtras {
xdat: self.prefix.starts_with(b"XDAT"),
xbop: self.trailer.windows(4).any(|w| w == b"xbop"),
}
}
}
/// Builds a standard PC-layout program around `bitcode` (test helper).
#[cfg(test)]
pub fn build_standard(kind: u16, sm: (u8, u8), dxil_version: u32, bitcode: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let version = (u32::from(kind) << 16) | (u32::from(sm.0) << 4) | u32::from(sm.1);
let padded = bitcode.len().next_multiple_of(4);
let size_dwords = (24 + padded) / 4;
out.extend_from_slice(&version.to_le_bytes());
out.extend_from_slice(&(size_dwords as u32).to_le_bytes());
out.extend_from_slice(b"DXIL");
out.extend_from_slice(&dxil_version.to_le_bytes());
out.extend_from_slice(&STANDARD_BITCODE_OFFSET.to_le_bytes());
out.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
out.extend_from_slice(bitcode);
out.resize(24 + padded, 0);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn fake_bitcode() -> Vec<u8> {
let mut b = LLVM_BITCODE_MAGIC.to_vec();
b.extend_from_slice(&[0xAA; 12]);
b
}
#[test]
fn parses_standard_layout() {
let bytes = build_standard(0, (6, 0), 0x100, &fake_bitcode());
let p = DxilProgram::parse(&bytes).unwrap();
assert_eq!(p.kind, ShaderKind::Pixel);
assert_eq!(p.shader_model, (6, 0));
assert!(p.is_standard_layout());
assert_eq!(p.xbox_extras(), XboxExtras::default());
}
#[test]
fn detects_xbox_layout() {
// Xbox layout: XDAT table before the bitcode, xbop blob after it.
let bitcode = fake_bitcode();
let xdat = b"XDAT\x01\x00\x00\x00";
let trailer = b"xbop\x02\x00\x00\x00";
let mut bytes = Vec::new();
let size = 24 + xdat.len() + bitcode.len() + trailer.len();
bytes.extend_from_slice(&((5u32 << 16) | 0x65).to_le_bytes()); // cs_6_5
bytes.extend_from_slice(&((size / 4) as u32).to_le_bytes());
bytes.extend_from_slice(b"DXIL");
bytes.extend_from_slice(&0x105u32.to_le_bytes());
bytes.extend_from_slice(&(16 + xdat.len() as u32).to_le_bytes());
bytes.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
bytes.extend_from_slice(xdat);
bytes.extend_from_slice(&bitcode);
bytes.extend_from_slice(trailer);
let p = DxilProgram::parse(&bytes).unwrap();
assert_eq!(p.kind, ShaderKind::Compute);
assert_eq!(p.shader_model, (6, 5));
assert!(!p.is_standard_layout());
assert_eq!(
p.xbox_extras(),
XboxExtras {
xdat: true,
xbop: true
}
);
assert_eq!(p.bitcode, &bitcode[..]);
}
#[test]
fn rejects_missing_bitcode_magic() {
let bytes = build_standard(0, (6, 0), 0x100, &[0u8; 16]);
assert!(DxilProgram::parse(&bytes).is_err());
}
}
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen addition to the vendored victory-shader crate (see ../../UPSTREAM.md): a public
// entry point for a raw compute program, with the same stages `translate` runs for a container.
use super::{HostShader, lower};
use crate::native::{HwStage, NativeProgram};
use crate::{ShaderError, io, resource, spill, structure};
/// Translates a compute program that is already a [`NativeProgram`] (machine code plus its
/// root layout) instead of one stored in a console shader container. Only the compute stage is
/// accepted: graphics stages need signatures that only a container carries.
pub fn translate_native(native: &NativeProgram) -> Result<HostShader, ShaderError> {
if native.stage != HwStage::Cs {
return Err(ShaderError::Unsupported {
offset: 0,
what: "translate_native takes compute programs only",
});
}
// (what an earlier program's lowering on this thread left behind)
lower::take_needs();
let p = spill::build(native)?;
let st = structure::structure(&p);
let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
let io = io::raise(&p, native)?;
let st = st?;
let lowered = lower::lower(&lower::Parts {
native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})?;
Ok(HostShader {
stage: native.stage,
dxil: lowered.dxil,
user_data: lowered.user_data,
samplers: lowered.samplers,
static_samplers: Vec::new(),
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
})
}
@@ -0,0 +1,222 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen tests for the vendored victory-shader crate (see ../../UPSTREAM.md).
//
// BetterXen's own synthetic gfx1030 Wave32 fixtures (`fixtures/rdna2/*.bin`, original, assembled
// with LLVM's llvm-mc) are translated to DXIL by the vendored recompiler. Their expected output
// words come from `fixtures/manifest.toml`, derived by hand there and checked by BetterXen's own
// independent reference; nothing in this file derives an expectation from the recompiler.
//
// Fixture ABI (docs/interfaces.md): v0 = grid index, V# of the input buffer in s[0:3], of the
// output buffer in s[4:7]. The vendored recompiler instead gets descriptors from a table, so
// the program is wrapped in a prologue that loads both from a descriptor table into s[0:3] and
// s[4:7] and then continues into the fixture's code unchanged.
use super::translate_native;
use crate::native::{
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
};
const MANIFEST: &str = include_str!("../../../../fixtures/manifest.toml");
/// Fixtures that bind an input and an output buffer and have expected words in the manifest.
/// Keyed by the file name in the manifest's `path`.
const BINARIES: &[(&str, &[u8])] = &[
("add.bin", include_bytes!("../../../../fixtures/rdna2/add.bin")),
("float-exact.bin", include_bytes!("../../../../fixtures/rdna2/float-exact.bin")),
("bitwise-branch.bin", include_bytes!("../../../../fixtures/rdna2/bitwise-branch.bin")),
("or.bin", include_bytes!("../../../../fixtures/rdna2/or.bin")),
("shifts.bin", include_bytes!("../../../../fixtures/rdna2/shifts.bin")),
("ashr.bin", include_bytes!("../../../../fixtures/rdna2/ashr.bin")),
];
struct Fixture {
id: String,
code: &'static [u8],
input: Vec<u32>,
expected: Vec<u32>,
}
fn words(line: &str) -> Vec<u32> {
line.trim()
.trim_start_matches('[')
.trim_end_matches(']')
.split(',')
.filter(|t| !t.trim().is_empty())
.map(|t| t.trim().parse().expect("a decimal word"))
.collect()
}
/// Fixtures with input and expected words in the manifest. A fixture the manifest lists with
/// expected words but that is not embedded above fails the test instead of being skipped.
fn fixtures() -> Vec<Fixture> {
let mut out = Vec::new();
for block in MANIFEST.split("[[fixture]]").skip(1) {
let get = |key: &str| {
block
.lines()
.find_map(|l| l.strip_prefix(&format!("{key} = ")))
.map(str::to_owned)
};
let (Some(input), Some(expected)) = (get("input"), get("expected")) else { continue };
let (input, expected) = (words(&input), words(&expected));
if input.is_empty() || expected.is_empty() {
continue;
}
let id = get("id").unwrap().trim_matches('"').to_owned();
let path = get("path").unwrap().trim_matches('"').to_owned();
let name = path.rsplit('/').next().unwrap();
let code = BINARIES
.iter()
.find(|(n, _)| *n == name)
.unwrap_or_else(|| panic!("fixture {id} ({name}) is in the manifest but not embedded"))
.1;
out.push(Fixture { id, code, input, expected });
}
out
}
/// `s_mov_b32 sdst, 0` (inline constant 0 is source 0x80).
const fn s_mov_b32_zero(sdst: u32) -> u32 {
0xBE80_0000 | sdst << 16 | 0x03 << 8 | 0x80
}
/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
const fn s_load_dwordx4(dst: u32, base: u32, byte_offset: u32) -> [u32; 2] {
[0x3D << 26 | 0x02 << 18 | dst << 6 | base >> 1, 125 << 25 | byte_offset]
}
/// `s_waitcnt lgkmcnt(0)` with the other counters left alone.
const S_WAITCNT_LGKM0: u32 = 0xBF8C_C07F;
/// Wraps a fixture so its descriptors arrive through a descriptor table. The table's two
/// 32-byte slots hold the input SRV (heap index 0) and the output UAV (heap index 1).
fn program(code: &[u8], threads: u32) -> NativeProgram {
let mut w: Vec<u32> = Vec::new();
w.push(s_mov_b32_zero(9)); // upper half of the table address; the lower half is user data s8
w.extend(s_load_dwordx4(0, 8, 0x00)); // input V# -> s[0:3]
w.extend(s_load_dwordx4(4, 8, 0x20)); // output V# -> s[4:7]
w.push(S_WAITCNT_LGKM0);
let mut bytes: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
bytes.extend_from_slice(code);
NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 32,
layout: vec![RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 8,
slot: 0,
}],
used: vec![
UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 4, // 4-byte elements, as the fixtures index them (idxen)
dwords: 4,
user_data: 8,
slot: 0,
},
UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 8,
lower_bound: 0,
stride: 4, // 4-byte elements, as the fixtures index them (idxen)
dwords: 4,
user_data: 8,
slot: 0,
},
],
io: StageIo::Cs(ComputeIo { rsrc2: 9 << 1, threads: [threads, 1, 1] }),
code: bytes,
}
}
#[test]
fn every_embedded_fixture_is_listed_in_the_manifest() {
let listed = fixtures();
assert_eq!(listed.len(), BINARIES.len(), "embedded list and manifest disagree");
}
#[test]
fn fixtures_translate_to_a_dxil_container() {
for f in fixtures() {
assert!(!f.expected.is_empty(), "{}: no expected words", f.id);
let native = program(f.code, f.input.len() as u32);
let shader = translate_native(&native)
.unwrap_or_else(|e| panic!("{}: translate_native failed: {e}", f.id));
assert_eq!(&shader.dxil[..4], b"DXBC", "{}: not a DXBC/DXIL container", f.id);
assert!(shader.dxil.len() > 100, "{}: container too small", f.id);
}
}
#[cfg(windows)]
mod on_the_gpu {
use super::*;
use crate::emit::host::{Dispatch, Host, Root, Stride, View};
fn run_on_gpu(host: &Host, f: &Fixture) -> Vec<u32> {
let shader = translate_native(&program(f.code, f.input.len() as u32)).expect("translate");
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
// The table parameter's value is the heap offset: both views start at heap index 0.
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Buffer { data: &f.input, stride: Stride::Raw },
View::RawUav(f.input.len() as u32),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{}: dispatch failed: {e}", f.id));
out[0][..f.expected.len()].to_vec()
}
/// Runs each fixture on the default D3D12 device and compares every output word with the
/// manifest. If no suitable device exists the test fails loudly rather than passing: a
/// skipped run is not GPU verification.
#[test]
fn fixtures_on_the_default_d3d12_device_match_the_manifest() {
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
let host = Host::new(false).expect("no SM 6.6 D3D12 hardware device: not verified");
let mut ran = 0;
for f in fixtures() {
let got = run_on_gpu(&host, &f);
assert_eq!(got, f.expected, "{}: output words differ from the manifest", f.id);
eprintln!("betterxen fixture {} ran on the GPU and matched the manifest", f.id);
ran += 1;
}
assert_eq!(ran, fixtures().len());
}
/// Negative control: the comparison above must be able to fail. A copy of each expected
/// output with one bit flipped must not equal what the GPU produced, and the output must
/// not be the untouched zeroed buffer or an echo of the input (unless the manifest says so).
#[test]
fn a_wrong_expectation_is_detected() {
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
let host = Host::new(false).expect("no SM 6.6 D3D12 hardware device: not verified");
for f in fixtures() {
let got = run_on_gpu(&host, &f);
let mut wrong = f.expected.clone();
wrong[0] ^= 1;
assert_ne!(got, wrong, "{}: a flipped expectation was accepted", f.id);
assert!(got.iter().any(|&w| w != 0) || f.expected.iter().all(|&w| w == 0), "{}: output is the zeroed buffer", f.id);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,174 @@
//! Counts of a module's instructions by kind (a diagnostic): what a
//! translated program costs before the driver's compiler sees it.
//!
//! `VICTORY_SHADER_CENSUS` (any value) turns the counting on; the counts of
//! the module a thread wrote last are read with [`take`]. The `translate`
//! command writes them as a table (see `apps/victory/src/translate.rs`).
use super::{Cast, Module, Op, Tag, Term, V};
use std::cell::RefCell;
/// The kinds, in the order of [`Census::counts`].
pub const KINDS: [&str; 26] = [
"total",
"arith",
"math_call",
"bitcast",
"cast",
"select",
"guard_select",
"phi",
"extract",
"buffer_load",
"cbuffer_load",
"texture_read",
"lds_load",
"buffer_store",
"lds_store",
"atomic",
"handle",
"annotate",
"dimensions",
"barrier",
"wave_op",
"io_other",
"gep",
"clamp",
"loop_counter",
"blocks",
];
/// Instruction counts of one written module, by [`KINDS`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Census {
pub counts: [u32; KINDS.len()],
}
thread_local! {
/// The modules this thread wrote since the last [`take`]: the length and
/// a hash of each one's bitcode, with its counts (a program may be
/// emitted in several forms before one is kept).
static WRITTEN: RefCell<Vec<(usize, u64, Census)>> = const { RefCell::new(Vec::new()) };
}
fn fnv(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
})
}
/// Whether modules are counted (`VICTORY_SHADER_CENSUS` set).
pub fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_CENSUS").is_some())
}
/// The counts of the module whose bitcode the container `dxil` holds, if
/// this thread wrote it since the last call (which forgets the others).
pub fn take(dxil: &[u8]) -> Option<Census> {
let written = WRITTEN.with(|l| std::mem::take(&mut *l.borrow_mut()));
let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?;
written
.into_iter()
.rev()
.find(|(len, hash, _)| dxil.get(at..at + len).is_some_and(|b| fnv(b) == *hash))
.map(|w| w.2)
}
/// Counts `m`, whose written form is `bitcode`, and keeps the result for
/// [`take`].
pub(crate) fn note(m: &Module, bitcode: &[u8]) {
if !enabled() {
return;
}
let c = m.census();
WRITTEN.with(|l| l.borrow_mut().push((bitcode.len(), fnv(bitcode), c)));
}
fn kind(name: &str) -> usize {
let n = name.strip_prefix("dx.op.").unwrap_or(name);
let n = n.split('.').next().unwrap_or(n);
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
match n {
"unary" | "binary" | "tertiary" | "unaryBits" | "legacyF16ToF32" | "legacyF32ToF16"
| "isSpecialFloat" | "dot2" | "dot3" | "dot4" | "quaternary" => k("math_call"),
"bufferLoad" | "rawBufferLoad" => k("buffer_load"),
"cbufferLoadLegacy" | "cbufferLoad" => k("cbuffer_load"),
"bufferStore" | "rawBufferStore" | "textureStore" => k("buffer_store"),
"atomicBinOp" | "atomicCompareExchange" => k("atomic"),
"createHandle" | "createHandleFromBinding" | "createHandleFromHeap" => k("handle"),
"annotateHandle" => k("annotate"),
"getDimensions" => k("dimensions"),
"barrier" => k("barrier"),
_ if n.starts_with("wave") || n.starts_with("quad") => k("wave_op"),
_ if n.starts_with("textureLoad")
|| n.starts_with("sample")
|| n.starts_with("textureGather")
|| n.starts_with("calculateLOD") =>
{
k("texture_read")
}
_ => k("io_other"),
}
}
impl Module {
/// The instructions [`Module::write`] writes, by kind.
pub(crate) fn census(&self) -> Census {
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
let call_kind: Vec<usize> = self.funcs.iter().map(|f| kind(&f.name)).collect();
let live = self.live();
// The blocks `write` lays out: those reached from the entry.
let mut seen = vec![false; self.blocks.len()];
let mut stack = vec![0usize];
if !self.blocks.is_empty() {
seen[0] = true;
}
while let Some(b) = stack.pop() {
for &s in super::successors(self.blocks[b].term).iter() {
if !seen[s] {
seen[s] = true;
stack.push(s);
}
}
}
let mut c = Census::default();
for (b, blk) in self.blocks.iter().enumerate() {
if !seen[b] {
continue;
}
c.counts[k("blocks")] += 1;
let _: Option<Term> = blk.term;
for &i in blk
.phis
.iter()
.filter(|&&i| live[i as usize])
.chain(&blk.body)
{
c.counts[0] += 1;
let at = match &self.insts[i as usize].op {
Op::Bin(..) | Op::Cmp(..) => k("arith"),
Op::Cast(Cast::Bitcast, _) => k("bitcast"),
Op::Cast(..) => k("cast"),
Op::Select(..) => k("select"),
Op::Extract(..) => k("extract"),
Op::Phi(_) => k("phi"),
Op::Gep(..) => k("gep"),
Op::Load(_) => k("lds_load"),
Op::Store(..) => k("lds_store"),
Op::AtomicRmw(..) | Op::CmpXchg(..) => k("atomic"),
Op::Call(f, _) => call_kind[*f as usize],
};
c.counts[at] += 1;
match self.tags.get(&i) {
Some(Tag::Guard) => c.counts[k("guard_select")] += 1,
Some(Tag::Clamp) => c.counts[k("clamp")] += 1,
Some(Tag::Counter) => c.counts[k("loop_counter")] += 1,
None => {}
}
let _ = V::Inst(i);
}
}
c
}
}
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more