mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 21:11:12 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c512afb2b | ||
|
|
d2ad5808ab | ||
|
|
66804f25b4 | ||
|
|
f34750f353 | ||
|
|
fadd742e63 | ||
|
|
d0d10c97cf | ||
|
|
25ba80e1eb | ||
|
|
78be10c187 | ||
|
|
9713018db6 | ||
|
|
7451f0f2ae | ||
|
|
1beef47c6f | ||
|
|
6ff97b98ec | ||
|
|
53c4380b3e | ||
|
|
c1e958194c | ||
|
|
1be97f2536 | ||
|
|
a9d7bc000b | ||
|
|
b9469aa22d | ||
|
|
bba0851e44 |
No files matched your search
@@ -31,7 +31,7 @@ jobs:
|
||||
test "$(sysctl -n sysctl.proc_translated)" = 0
|
||||
- name: Install Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --target x86_64-pc-windows-gnu
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
|
||||
rustc -vV
|
||||
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
run: |
|
||||
@@ -42,6 +42,10 @@ jobs:
|
||||
binary=target/aarch64-apple-darwin/debug/bx-cli
|
||||
file "$binary"
|
||||
test "$(lipo -archs "$binary")" = arm64
|
||||
- name: Check hybrid script syntax (no CrossOver on the runner, nothing launched)
|
||||
run: |
|
||||
for script in scripts/hybrid/*.sh tests/conformance/test_*/build.sh; do sh -n "$script"; done
|
||||
python3 -c 'import ast, glob; [ast.parse(open(f).read(), f) for f in glob.glob("scripts/hybrid/*.py") + glob.glob("tests/conformance/test_*/*.py")]'
|
||||
- name: Install mingw-w64 and CMake
|
||||
env:
|
||||
HOMEBREW_NO_AUTO_UPDATE: 1
|
||||
|
||||
@@ -29,8 +29,6 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Install PyYAML
|
||||
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
|
||||
- name: Unit-test the hygiene checks
|
||||
run: python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
- name: Check documentation and workflow files
|
||||
run: python3 scripts/audit/docs_hygiene.py --require-yaml
|
||||
- name: Remind about the changelog (advisory)
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
name: Merge policy audit
|
||||
|
||||
# Detects a pull request merged by its own author (AGENTS.md §7, "Merge
|
||||
# eligibility"). GitHub rulesets cannot block this, so the run fails after the
|
||||
# merge. It is not a required check and never checks out pull request code.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [closed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
author-merge:
|
||||
name: Author did not merge
|
||||
if: github.event.pull_request.merged == true && github.event.pull_request.merged_by.login == github.event.pull_request.user.login
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: Report a self-merge
|
||||
env:
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
AUTHOR: ${{ github.event.pull_request.user.login }}
|
||||
run: |
|
||||
echo "::error::Pull request #$PR was merged by its own author, $AUTHOR. A maintainer other than the author must merge (AGENTS.md section 7)."
|
||||
exit 1
|
||||
@@ -4,9 +4,9 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
|
||||
## 0. First-Time Contributor Onboarding
|
||||
|
||||
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
|
||||
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
|
||||
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
@@ -14,33 +14,21 @@ Whenever a user points their agent at BetterXen to contribute, get started, or p
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
|
||||
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
2. **Select work in strict priority order:**
|
||||
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
|
||||
- **Priority 2 — Pick an unclaimed open issue:**
|
||||
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
|
||||
2. **Discover & pick an unclaimed issue:**
|
||||
- Query ready issues in the active milestone:
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
|
||||
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
|
||||
```
|
||||
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
|
||||
- **Priority 3 — Review & independently verify open PRs needing review:**
|
||||
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
|
||||
```
|
||||
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
|
||||
3. **Claim & isolate (for Priority 2 issue work):**
|
||||
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
|
||||
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
|
||||
3. **Claim & isolate:**
|
||||
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
|
||||
4. **Implement strictly in scope:**
|
||||
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
|
||||
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
|
||||
5. **Verify locally (including hosts without CrossOver):**
|
||||
- Run every command in Section 8 and fix all warnings/failures before stopping.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
6. **Review & submit PR:**
|
||||
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
|
||||
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
@@ -76,8 +64,8 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
|
||||
|
||||
### Cross-Track `[ABI]` Rule
|
||||
- For issue-claimed contributor work, stay inside your issue's track directory; if your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first so provider and consumer tracks can implement in parallel.
|
||||
- Maintainer-directed compatibility and startup-unblocking tasks may touch the required shim and `tests/conformance/` directories across tracks without a pre-existing issue claim. They must not overlap another contributor's active claim or open PR without that contributor's or a maintainer's recorded agreement, any new cross-DLL helper or export still goes through an `abi/`-only `[ABI]` PR first, and independent review (Section 5) still applies.
|
||||
- Never edit another track's directory inside a feature PR.
|
||||
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
|
||||
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
|
||||
|
||||
---
|
||||
@@ -93,7 +81,9 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
|
||||
## 4. Dependencies, Licensing & Provenance
|
||||
|
||||
_Reserved — policy migration in progress._
|
||||
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
|
||||
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never 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, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
|
||||
|
||||
---
|
||||
|
||||
@@ -107,34 +97,26 @@ _Reserved — policy migration in progress._
|
||||
|
||||
---
|
||||
|
||||
## 6. Compatibility Evidence & Legal Boundaries
|
||||
## 6. Legal & Clean-Room Rules
|
||||
|
||||
- **Authorized compatibility evidence:** Contributors and agents may use publicly accessible documentation, publicly licensed software, synthetic workloads, and **project-authorized target builds** (via local call-site inspection and runtime diagnostics) to establish undocumented Xbox OS, graphics, memory, storage, and runtime ABI contracts (struct layouts, flags, COM IIDs, vtable slot orders, and expected return/error semantics). Separate direct observations from inferences and verify every implemented contract with a synthetic conformance test under `tests/conformance/`. Such a test shows that a shim matches the recorded inference, not that the inference is correct.
|
||||
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit 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.
|
||||
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
|
||||
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
|
||||
|
||||
---
|
||||
|
||||
## 7. Claiming, Git Safety & Changelog
|
||||
|
||||
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
2. **Isolate with branches or worktrees:**
|
||||
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
|
||||
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
|
||||
3. **Isolate with branches or worktrees:**
|
||||
```sh
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
```
|
||||
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
|
||||
### Merge eligibility
|
||||
|
||||
Four roles are separate: the **original author** (who opened the PR), **corrective contributors** (who later push to its branch), **independent approvers**, and the **merger**.
|
||||
|
||||
- The original author never merges their own PR. Any other maintainer may merge once required checks pass, at least one approval is current and blocking review conversations are resolved.
|
||||
- Maintainers may resolve conflicts, correct defects, update documentation and push fixes to a contributor's PR branch where GitHub permissions allow. Doing so does not disqualify them from merging.
|
||||
- Any push that changes the PR dismisses earlier approvals. After a **routine** push (conflict resolution that changes no behaviour, changelog correction, minor documentation fix), one new approval is enough and may come from the maintainer who pushed it, if they are not the original author. No further approval is required beyond the ruleset.
|
||||
- **Substantive** implementation changes need independent review (Section 5): the approval must come from someone who did not write them. A maintainer who wrote substantive corrections may merge after another person has approved those corrections, but may not approve them. If in doubt, treat a change as substantive.
|
||||
- A coding agent acts as the person it works for and merges only with that person's authorization.
|
||||
|
||||
The `Protect main` ruleset enforces pull requests, one approval, dismissal of stale approvals, resolved conversations, the required CI checks and no force push or deletion, with no bypass actors. GitHub cannot enforce two rules above: who may merge (`Merge policy audit` only fails after an author self-merge) and whether an approver wrote part of the change.
|
||||
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
|
||||
|
||||
---
|
||||
|
||||
@@ -147,9 +129,8 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli # must print: arm64
|
||||
|
||||
# 2. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust bx_shader_bridge.dll, and
|
||||
# build the auto-discovered conformance EXEs
|
||||
# (strictly verifies all 17 .edata Export Directories: names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
|
||||
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
|
||||
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
|
||||
@@ -160,20 +141,3 @@ target/debug/bx-cli trace /tmp/bx-test.jsonl
|
||||
# 4. Repository Markdown link & hygiene check
|
||||
python3 scripts/audit/docs_hygiene.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. AI Agent Efficiency & Resource Management
|
||||
|
||||
These rules apply to every coding agent, whatever its model, vendor or plan. Saving resources never justifies skipping necessary verification, fabricating or assuming results, weakening a security, legal or provenance safeguard, or bypassing independent review. Where this section and Sections 4–8 appear to conflict, Sections 4–8 win.
|
||||
|
||||
- **Spend in proportion:** Keep token consumption, API usage, reasoning effort and compute cost as low as correctness allows.
|
||||
- **Reuse what is still valid:** Reuse conversation context, repository knowledge, review findings and verification evidence. Evidence is valid only for the revision and environment it was recorded on; re-run whatever a later change could affect.
|
||||
- **Read narrowly:** Inspect relevant files and incremental diffs instead of rescanning the repository. Batch independent tool calls and GitHub API requests where practical.
|
||||
- **Delegate sparingly:** Avoid unnecessary subagents, duplicate investigations and overlapping responsibilities. Independent review (Section 5) is not duplicate work.
|
||||
- **Reasoning effort:** Default to low for routine tasks and for helper subagents; raise it only when technical complexity justifies it or the user asks.
|
||||
- **Verify without redundancy:** Use targeted checks while iterating and for small changes. This does not replace Section 8 or required CI. Do not repeat builds, tests or CI runs when nothing relevant has changed, and do not poll workflows repeatedly.
|
||||
- **Communicate concisely:** Report outcomes, blockers and what is needed next; skip lengthy status reports and repeated summaries.
|
||||
- **Blocked work:** Do not re-review an unchanged PR that is waiting on an unresolved external blocker.
|
||||
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and eligible (Section 7), instead of stopping at intermediate reports. This grants no permission beyond Section 7.
|
||||
- **Escalate real uncertainty:** Raise genuine doubt about ABI compatibility, memory safety, concurrency, security, GPU synchronization, licensing or architecture with a maintainer rather than guessing.
|
||||
+13
-183
@@ -9,164 +9,23 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
### Fixed
|
||||
- Fixed `bx-cli stop` failing on an idle environment, leaving its session marker in place: `wineserver -k` exits 1 when no server is running.
|
||||
- `bx-cli run` again configures the shim overrides from `build-shims/bin` when `--shims` is not given, as `main` does.
|
||||
- `bx-cli run --log` now prints the trace summary to stderr when the run ends, leaving the JSON record alone on stdout (#408).
|
||||
- `bx-cli run` and `bench` now refuse a CrossOver build they have not been run against unless `--allow-untested-crossover` is given, and records carry `crossover_build_tested`. The notices record the contributor work carried from #405.
|
||||
- Fixed `bx-cli run --bottle` losing DLL overrides, including those set for `--shims`: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll`. A requested `--backend` is also passed with `--env`, so a backend saved in the bottle's settings no longer replaces it. First found by jelly013 on #425.
|
||||
- Fixed unattended crash handling in new test bottles: `create-test-bottle.py` now turns off Wine's crash dialog, which otherwise waits for a click until the run times out (observed: timeout at 240 s with the dialog, 2.8 s without).
|
||||
- The acceptance suite now soaks Direct3D 12 as well as the Direct3D 11 control. One D3D11 soak stalled on a GPU event query after 9,183 frames; three reruns passed and the cause is unknown.
|
||||
|
||||
### Added
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves the runtime objects behind **`XSystemGetAnalyticsInfo`** and **`XDisplayTryEnableHdrMode`**, which a project-authorized target title requests during System Init (previously logged as unsupported `B884675D-…` and `03F0FE74-…/35F07670-…`). The keys and slots (analytics slot 3, which returns `XSystemAnalyticsInfo` by value; HDR slot 4) were derived from authorized GDK material, and no GDK files are in the repository. The function contracts follow Microsoft's public `XSystem.h` / `XDisplay.h` documentation. `XSystemGetAnalyticsInfo` reports family `Xbox`, a form that follows the profile (`Xbox Series S` for Lockhart, `Xbox Series X` for Anaconda) and BetterXen's synthetic OS version `10.0.26100.0` (logged with `synthetic=1`). `XDisplayTryEnableHdrMode` returns `XDisplayHdrModeResult::Disabled`, the documented success answer when HDR is not enabled, because BetterXen presents SDR. It clears the optional luminance output and logs the preference. `test_xgameruntime` calls both through `QueryApiImpl` and checks the public contract. The target title now gets past both calls; its next stops are fixed by #643 and #640.
|
||||
- `xmem.dll` exports two new internal cross-DLL hooks, `bx_xmem_try_charge_external` and `bx_xmem_release_charge_external` (`abi/defs/xmem.def` grows 15 → 17; `scripts/build-shims.sh` now reports 113 exact exports) (#550). They admit and release bytes against the combined Lockhart/Anaconda title cap under the same `usage_lock` `can_commit` takes, and `can_commit` now counts a new `external_bytes` counter in `used`. `XMemGetWorkingSetStatistics` / `bx_xmem_get_internal_stats` report external charges inside `committed_virtual_bytes`, so reported usage matches what the cap counts. A release larger than the outstanding external charge is refused and logged (the counter is left unchanged, so other owners' charges survive), and a failed bookkeeping refresh during a charge is logged as `external_charge` instead of being reported silently as a budget rejection. New `test_xmem_external_charge` charges externally and checks that `XMemVirtualAlloc` is then refused at the cap, that the stats include the charge, that an over-release is refused, and that the allocation is admitted again after release. `d3d12_xs` switches to the hook in the same change (#552, below).
|
||||
- `bx-cli run` maps the Xbox title drives before launch: `G:` to the executable's directory and `T:` to `drive_c/bx_temp` in the prefix or bottle (`launcher/crates/bx-cli/src/drives.rs`). An Xbox title opens its package on `G:` and writes crash logs to `T:`, and stops at startup when either is missing (observed on a project-authorized target build; the drive roles are an inference). Ownership is recorded before creating or retargeting links, so a failed manifest write cannot leave an unrecorded mapping; temporary links use per-process names and manifest targets use lossless path-byte encoding. A prefix lock prevents another `bx-cli run` from changing its drive mappings while a guest is active. The `.bx-drives` manifest is written to a temporary file and renamed into place without following an existing temporary symlink, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. **Behaviour change:** `bx-cli run` takes a prefix-wide lock before system32 staging and holds it until the guest exits, so runs sharing a prefix or bottle are serial: a second launcher on the same prefix is refused, before it stages anything. `test_xbox_drives` checks the resulting layout, not who created the links.
|
||||
- **Ownership:** like system32 staging (#474), a `.bx-drives` manifest in `dosdevices` records each link the tool made. Only those are re-pointed. A drive letter mapped elsewhere by anything else is left unchanged and reported as a warning. A prefix without `dosdevices` is reported and the run continues.
|
||||
- **Test:** `tests/conformance/test_xbox_drives/` reads its own executable through `G:` and compares it byte for byte with the copy at its module path, then creates, reads back and deletes a file on `T:`. Unit tests in `drives.rs` cover creation, reruns, re-pointing an own link, foreign links and entries, a missing `dosdevices`, malformed manifests, a failed manifest write, lock contention and non-UTF-8 path round-tripping.
|
||||
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
|
||||
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
|
||||
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
|
||||
- **What is parsed:** the stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, and `AS`/`MS`) are classified with `BxShaderGate::admit`; every other payload is copied verbatim. An unknown type, a duplicated type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim works on its own copy, so the gate can substitute prepared DXIL without writing to the caller's memory.
|
||||
- **Layout correction (review):** the first version assumed every payload sat at offset 8. `alignas(void*)` on the subobject class aligns the *record*, not the payload, so 4-byte-aligned payloads (`BLEND`, `SAMPLE_MASK`, `RASTERIZER`, `DEPTH_STENCIL`, `DEPTH_STENCIL1`, `IB_STRIP_CUT_VALUE`, `PRIMITIVE_TOPOLOGY`, `RENDER_TARGET_FORMATS`, `DEPTH_STENCIL_FORMAT`, `SAMPLE_DESC`, `NODE_MASK`, `FLAGS`) sit at **offset 4**. The table now derives `payload_at<T>()` and `record_size<T>()` from a `struct alignas(void*)` record, with `static_assert`s pinning the measured offsets (shader 8/24, UINT 4/8, BLEND/RASTERIZER/RT_FORMAT_ARRAY/DEPTH_STENCIL1 at 4). A valid graphics stream with those tags was desynced and rejected before the fix. `test_shader_gate`'s `StreamBuilder` now encodes the same real layout and adds a graphics stream with 4-byte-aligned payloads, so the tests can catch a desync instead of asserting the shim's own assumption.
|
||||
- **Logging:** `pso_stream` keeps its record and now reports `shaders_not_parsed=0` when it parsed the stages; each stage adds its own `shader_gate` record with `pso=stream`.
|
||||
- **Tests:** `test_shader_gate` adds a stream PSO whose CS is the synthetic ACCC-only container (`E_NOTIMPL`, `*ppv == nullptr`), the same stream with the SM 6.6 DXIL blob (succeeds and its 256 output words are verified), a truncated stream, an unknown subobject type, and a duplicated `CS` (`E_INVALIDARG` each), plus the `--no-bridge` child refusing ACCC-only through the stream. It also asserts the new `pso=stream` `shader_gate` records and `shaders_not_parsed=0`. The stream walker's accept/reject decisions were checked on the host with a native `clang++` harness (valid, truncated, unknown-tag and out-of-range-tag cases).
|
||||
- `abi/` unchanged; `d3d12_xs.dll` still exports 4. **`test_shader_gate.exe` was not executed** — no CrossOver on this host. The ADR 0008 wording recording stream PSOs as covered by the shader gate now lands with this stream-PSO gate change (#578 / PR #607).
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
|
||||
- A recognized BetterXen `BXVM` configuration is validated before an unwritable output can trigger the logged fallback. Invalid sizes still return `E_INVALIDARG` on read-only pages.
|
||||
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
|
||||
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
|
||||
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
|
||||
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
|
||||
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
|
||||
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
|
||||
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
|
||||
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
|
||||
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
|
||||
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
|
||||
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
|
||||
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
|
||||
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
|
||||
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
|
||||
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
|
||||
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
|
||||
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
|
||||
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
|
||||
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
|
||||
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
|
||||
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
|
||||
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
|
||||
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
|
||||
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
|
||||
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
|
||||
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
|
||||
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
|
||||
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
|
||||
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
|
||||
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
|
||||
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
|
||||
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
|
||||
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
|
||||
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
|
||||
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
|
||||
- **Not from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
|
||||
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
|
||||
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
|
||||
- `bx-cli`'s `cleanup_runs_outside_the_callers_process_group` test now observes the fake `wineserver`'s PGID with macOS's bundled Perl and its built-in `getpgrp` instead of `/bin/ps` (#558). `/bin/ps -o pgid= -p $$` returns `Operation not permitted` on restricted macOS hosts, making the fake server exit 126 and failing an otherwise unrelated supervision test. The test still records one PGID for each `-k` and `-w` invocation and asserts both differ from the caller's group. Test-only change; no supervision behavior changed.
|
||||
- `AcpHal.dll` now rejects `ApuCreateHeap(0, 0)` with `E_INVALIDARG` (#580). The call previously reported `S_OK` and set `heap_created = true` with `capacity == 0`, representing a heap that could never satisfy an allocation; `ApuAlloc` still rejected requests with `E_OUTOFMEMORY`. `ERROR_BUSY` is still returned first when allocations are live, so the existing busy-path assertion is unchanged. `test_audio_input` now asserts the zero-capacity call is rejected and that `ApuAlloc` still fails with `E_OUTOFMEMORY` before a real heap is created. `abi/` unchanged (9 exports). **`test_audio_input.exe` was not executed** — no CrossOver on this host.
|
||||
- `docs/claims.toml` now defines evidence classes A, B, D, E and U in a legend derived from their existing claims and prose usages (#549). `docs/README.md` now lists the complete vocabulary and describes the file as a claim ledger. No claim's class was changed. The legend records that the in-tree `AGENTS.md` §5 refers to `claims.toml` and does not contain the longer vocabulary named in the issue. Class E explicitly covers both public tool/format documentation and observed tool behavior, with the claim's `test` field distinguishing documentation review from execution; `CLAIM-DXCONTAINER-PAYLOAD` and `CLAIM-LLVM-GFX1030` are documentation-only examples and are not reclassified here.
|
||||
- Documented the conformance exit-status contract: `bx-cli run` returns the guest's status unchanged, and fixtures that cannot reach a conclusion exit **77** with a `SKIP: <reason>` line (#563). `tests/conformance/README.md` now gives a `case` recipe that records PASS / UNAVAILABLE / FAIL separately, so a skip is never counted as a pass (AGENTS.md §5). `docs/research/d3dmetal-gpu-limits.md` states the fixture's 0/1/77 outcomes and links the recipe. Documentation only; no fixture or runner behaviour changed.
|
||||
- `bx-cli run` now propagates the guest's numeric exit code instead of collapsing every nonzero status to 1 (#565). `Outcome::exit_code` returned `u8::from(!status.success())`, so a conformance fixture's documented **exit 77** skip (see #563) arrived as 1 and was indistinguishable from a failure; a `case $status in 77)` recorder could never fire. Timeout (124) and signal (128+N) codes are unchanged, a failed cleanup or misplaced staging still turns success into failure with `code.max(1)`, and a signalled guest still has no code. `classifies_exit_timeout_and_signal` now asserts 7 for `exit 7` and 77 for `exit 77`; it previously asserted 1 for `exit 7`, which is why the collapse was invisible. No CrossOver run was needed for the tests that ran; live `bx-cli run` under CrossOver was not performed on this host.
|
||||
- ADR 0005 now points at `docs/progress.md` **at tag `native-first-final`** rather than a bare path that no longer exists on `main` (#569). The file was deleted with the native workspace (`30e551a`) and survives only at that tag, which ADR 0006 makes the canonical archive. The ADR's meaning is unchanged: no hybrid capability is claimed, and every listed item remains synthetic evidence. `docs_hygiene.py` cannot catch this class of error because it validates Markdown links only, and this reference is inline code.
|
||||
- `scripts/audit/docs_hygiene.py` now detects the **diff3** conflict marker `||||||| merged common ancestors` (#583). `MARKER` matched `<<<<<<<`, `=======` and `>>>>>>>` only, so a `git merge --diff3` conflict resolved down to just its base line passed the Repository hygiene gate. Added `MarkerTests` (all four markers, a full diff3 block, and negative controls for table/prose lines) and `WorkflowTests` (valid and invalid YAML, using temporary fixtures). `.github/workflows/hygiene.yml` now runs `python3 -m unittest scripts/audit/test_docs_hygiene.py` as a CI step, so the suite is gated rather than advisory. Fault injection: removing the `\|{7}` alternative makes 3 of the 25 tests fail; with it, all 25 pass. `python3 scripts/audit/docs_hygiene.py --require-yaml` reports 199 tracked files, 0 problems. **Stacked on PR #538**, which creates `test_docs_hygiene.py`.
|
||||
- `tests/conformance/test_veh_clwb` now verifies the `clwb` decoded instruction length (`len=`) that `bx_runtime_veh.dll` logs and uses to advance RIP (#539). The fixture reads `BX_LOG_FILE` (it fails with a clear message when `BX_LOG_FILE` is unset: the EXE imports `bx_runtime_veh.dll`, which reads the variable in `DLL_PROCESS_ATTACH`, so a temp log set in `main` would never be written) and asserts the `len=` values on the sampled `clwb_trapped` records. `log_sampled_trap` logs only traps 1, 2, 4, 8, …, so six `clwb` forms produce exactly three records (`total_traps=1, 2, 4`); the assertions cover **only those sampled records** — `total_traps=1` → `clwb (%rax)` → len 4, `total_traps=2` → `clwb 0x40(%rax)` → len 5, `total_traps=4` → `clwb (%r8)` → len 5 — plus a `len >= 4` floor on every observed record. Forms 3, 5, 6 (`clwb 0x100(%rax)`, `clwb 0x40(%rax,%rcx,4)`, `clwb 0x0(%rip)`) are **not** covered by a `len=` assertion. Expected lengths were re-derived by assembling with `x86_64-w64-mingw32-as` and disassembling with `x86_64-w64-mingw32-objdump -d`. The existing `delta == 6` trap-count check is unchanged. `test_veh_clwb.exe` passes live on CrossOver 26.3 under `bx-cli run --log` (records `len=4` and `len=5`), and fails with a clear message when `BX_LOG_FILE` is unset. Record fields are parsed with a checked `strtoull`, so a malformed record cannot throw past the failure message.
|
||||
- `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` no longer return a bare `S_OK` for work they did not do (#509). They logged a stub and reported success while ignoring their arguments: `Allocate` discarded its only parameter (unnamed) and `Release` takes no parameter at all, so neither could be held to anything. Both now return `E_NOTIMPL` and keep their `BX_STUB_LOG` record, so `bx-cli trace` still surfaces the call and a caller is told to fall back rather than being told the work happened.
|
||||
- **NDA constraint:** the public Microsoft Learn page for `AcpHal` returns HTTP 200 with only the membership gate, so the true signatures and the shape-context layout are **unknown** from public sources, including whether `Release` should take an argument. `E_NOTIMPL` is therefore BetterXen's choice, not the console's; no signature was invented and `abi/defs/AcpHal.def` is unchanged (9 exports).
|
||||
- **Tests:** `test_audio_input.exe` calls both through the DLL: null and sentinel pointers must not crash and must return `E_NOTIMPL`; calling `Release` twice must also return `E_NOTIMPL` (idempotent); and when `BX_LOG_FILE` is set it asserts both symbols still appear on `unimpl_api` lines, printing an explicit `SKIP` rather than a pass when the variable is unset.
|
||||
- `test_win32_bridge.exe` now asserts that the PSM **context pointer round-trips** through the JSONL (#519). #514 stored `(token, callback, context)` and logs `context=0x%llx`, so the context is observable — but the test only counted `callback_unfired` records, so a dropped (`context=0x0`), swapped or mis-tagged context would have passed unnoticed, leaving the storage decorative. The context field is parsed from the value after `context=`. The original version of this check parsed from the key, read the hex digit `c` and got `0xc` for every record, so it could never pass.
|
||||
- **What is checked:** every logged `context=` on **both** families must be non-zero and present in the set of `&entry` pointers the test actually passed; at least **two distinct** pointers must appear per family, so one registration cannot overwrite another's; and each family's set must cover the whole `&entry` set, which is what catches a swap or mis-tag between families. A record with a missing or malformed `context=` fails.
|
||||
- **Limit, stated rather than asserted:** the shim's unregister records carry only a detail string (`unregistered` / `foreign_token` / `unknown_token`), so **context-drop on unregister is not observable** in the log. The test documents that and prints a note if a future shim starts logging context there.
|
||||
- **Base:** this sits on #514, which introduces the `context=` field; it rebases cleanly once that merges.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `win32_bridge`'s PSM notifications now **store** the callback and context they accept, and **say** that they never fire it (#513). `register_notification` in `shims/win32_bridge/psm_appnotify.cpp` validated `callback` for null and then dropped it: nothing stored it, nothing ever invoked it, and the context pointer was discarded as `PVOID /*context*/`. So `ERROR_SUCCESS` meant "token allocated", not "you will be notified", and neither the code nor the log said so.
|
||||
- **What changed:** each registration now keeps a `(token, callback, context)` record in the process-heap-backed open-addressed table under the existing `SRWLOCK`; it starts at 64 slots and grows as needed, with allocation failure reported as `ERROR_NOT_ENOUGH_MEMORY`. The exported wrappers thread `context` through instead of discarding it; unregistering drops the record so no later event can reach a retired registration.
|
||||
- **Honesty:** a comment on `register_notification` and the JSONL detail (now `registered_offline callback_unfired`) both state that the callbacks are accepted and currently **never invoked**, because this shim has no source of app-state or constrained-change events and the console firing contract is not publicly documented. **No firing policy was invented** — the callback is deliberately left unfired rather than called spuriously to look implemented.
|
||||
- **Test:** `test_win32_bridge.exe` now also asserts that no callback fires, and that every registration's log detail carries `callback_unfired` (state and constrained counted separately). The existing per-event JSONL counts still pass unchanged, since the detail grep is a substring match.
|
||||
- **ABI:** `abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def` and `-l1-1-1.def` unchanged (2 exports each); all six API-set DLLs keep their original export counts.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `dxbc-accc` now exposes a **bounds-checked chunk-lookup API** on `ShaderInspection` (#521). `chunk_payload(&container, &fourcc)` returns the payload of the first chunk tagged `fourcc`, and `has_chunk_tag(&fourcc)` answers presence **without** trusting the declared size. Both **reuse the already-parsed `chunks` vector** rather than re-walking the raw table; `chunk_payload` rejects offsets inside the DXBC header/offset table and validates `offset + 8 + size` against **both** `container_size` and `container.len()` with checked arithmetic, returning `None` instead of panicking.
|
||||
- **Why:** `dxbc-accc` already parsed the table into `ChunkInfo { fourcc, offset, size }` but exposed **no public lookup**, so `shims/d3d12_xs/shader_gate.cpp:94` re-implements the same bounds-checked walk in C++ (`find_chunk`), plus a second variant `has_chunk_tag` that ignores the declared size. Two parsers for one container is how a fix lands in one and not the other.
|
||||
- **Semantics:** `offset` points at the 8-byte chunk header (fourcc + size), so the payload begins at `offset + 8`. A zero-size chunk yields `Some(&[])` (the header is present and in-bounds); callers needing a minimum size must check the returned length. When several chunks share a FourCC, the **first** in table order wins, matching the C++ `find_chunk`.
|
||||
- **Scope:** the C++ gate is **not** migrated here — `find_chunk`/`has_chunk_tag` in `shader_gate.cpp` stay for now, and the PR names the migration as a follow-up, since it is a larger change needing a live run. `abi/defs/bx_shader_bridge.def` unchanged (3 exports).
|
||||
- **Tests:** 7 new unit tests: `SFI0` and `PSV0` payloads returned exactly; a declared size past the container → `None`; an absent FourCC → `None` and `has_chunk_tag == false`; a zero-size chunk → `Some(&[])`; an exact-fit chunk at the container end (no off-by-one); a truncated container slice → `None`; and duplicate FourCCs → first wins.
|
||||
- `test_shader_gate.exe` now asserts the **shape** of the JSONL it writes, so the `bx-cli trace` fixtures stop resting on a hand reading of `shader_gate.cpp` (#535). It checks, against the log the fixture actually produced: that at least one `shader_gate` and one `shader_d3dmetal_gap` record exist; that every gate record writes `pso=`, `stage=`, `decision=`, `hr=` **in that order**; that an `*_unclassified` record carries **no** `kind=`; that every gap record has `pso=`, `stage=`, `wave_lanes_min=` and the colon that ends its structured part; and that no `key=value` value is split by a space — the assumption `parse_key_values(..., false)` rests on.
|
||||
- **Why shape, not counts:** decision and kind totals vary by GPU, so they are not asserted. What is asserted is the field order and the token boundaries the summarizer depends on, which a hand-typed fixture could get wrong without any test noticing.
|
||||
- **Executed natively, not under CrossOver:** the assertions compile and link, and their logic was checked in a native harness against a sample log — including a **negative control** where an `atomic64=typed, raw` value containing a space correctly trips the check. `test_shader_gate.exe` itself was **not** run here; that still needs a CrossOver host.
|
||||
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
|
||||
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
|
||||
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
|
||||
- `XCRDAPI.dll` completes a multi-request batch from one `Submit()` in queue order into CPU memory, mapped D3D12 upload buffers, and default buffers (a copy on the resource's device when the heap is not CPU-visible). If that copy has been submitted and its GPU completion is not confirmed, the shim keeps the destination and the copy's GPU objects alive and logs a warning, unless the device was removed or the fence already reached the waited value. The request still returns the failure HRESULT. LZ, BCPack, and GDeflate requests finish as `E_NOTIMPL` and log `BX_VTABLE_STUB_LOG`. `DStorageGetFactory` remains the only export (#467).
|
||||
- M2 Shader Format Gate (#466). `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` classify every stage through `bx_shader_bridge.dll` (#445) and log one `shader_gate` JSONL record per stage: kind, stage, shader model, chunk sizes, `SFI0` feature flags and `PSV0` wave lane range.
|
||||
- **Decisions:** DXIL and dual containers go to the host as the bridge's prepared copy. ACCC-only containers are refused with `E_NOTIMPL` before the host is called. Legacy DXBC and unclassifiable input pass unchanged. The bridge is loaded only by full path from `d3d12_xs.dll`'s directory. A missing bridge is logged once as `shader_bridge_missing`. Shaders then pass unclassified, but a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it.
|
||||
- **D3DMetal gaps:** stages needing a wave wider than 32 lanes or 64-bit atomics also log `shader_d3dmetal_gap`, the cases #453 measured as created but not run. The structural check now counts an `ACCC` chunk as a shader chunk, so the gate decides it.
|
||||
- **Test:** `tests/conformance/test_shader_gate/` runs a real DXC SM 6.6 compute shader through `d3d12_xs` and checks 256/256 output words. It requires `E_NOTIMPL` for an ACCC-only compute and graphics shader, and checks the logged wave64 and typed 64-bit-atomic constraints and every JSONL record. It then reruns itself from a directory without the bridge, which must still run DXIL and refuse ACCC-only. It passed on one Apple M5 Pro in a CrossOver 26.3 D3DMetal bottle. A bare prefix's vkd3d cannot load a DXIL converter, so the DXIL part needs the D3DMetal backend. `scripts/build-shims.sh` stages the bridge it needs (#484).
|
||||
- **ADR:** [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) proposes Branch D1 for M3, with the evidence; it is pending maintainer acceptance.
|
||||
- `scripts/build-shims.sh` now builds and verifies `bx_shader_bridge.dll` with the shims (#484). It builds the Windows version of `shader-transpiler/crates/dxbc-accc` (#445), linked with the new frozen export list `abi/defs/bx_shader_bridge.def`, so its export directory name is `bx_shader_bridge.dll`. It places the DLL in `build-shims/bin` and checks it with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. The script now reports 17 DLLs and 111 exports.
|
||||
- **Toolchain:** `cargo` and `rustc` come from rustup when available. The build always uses `<repo>/target`, and a missing `x86_64-pc-windows-gnu` target stops the script with `rustup target add x86_64-pc-windows-gnu` (it is never skipped). The CI job installs that target with its pinned toolchain.
|
||||
- **Effect:** `d3d12_xs`'s shader gate (#466) finds the bridge in `build-shims/bin` without a manual copy.
|
||||
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
|
||||
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
|
||||
- **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\<hash>\saves\<SCID hash>\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`.
|
||||
- **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory.
|
||||
- **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running.
|
||||
- **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized.
|
||||
- **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks:
|
||||
- name rules, the write and read round trip, and the size limits;
|
||||
- SCID isolation and enumeration;
|
||||
- crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file;
|
||||
- 64 threaded and 160 cross-process concurrent submits;
|
||||
- uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory.
|
||||
|
||||
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
|
||||
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
|
||||
- `QueryApiImpl` also serves offline XGameSave and XPackage on the public COM class and interface ids, with slot order from [xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) commit `7090008692569aa6081e30dfdd9de58237741e24` (#468). The ids and slot order come from that documentation; its provenance is recorded in `docs/research/upstream-registry.md` and the component reuse matrix, pending maintainer acceptance. `XPackageMountWithUiAsync` / `XPackageMountWithUiResult` (`IXPackageImpl2` slots 37–38) now mount through the XAsync engine, like `XPackageMount`. `IXError` slot 3 now returns `false`, following the #492 review's observation that the GDK's static library continues only on `false`; that source lists the slot as unknown.
|
||||
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
|
||||
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
|
||||
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
|
||||
|
||||
Everything else is printed as `OBSERVED:` lines. On one Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from source, D3DMetal 4.0b3), three runs gave the same outcomes, with 4/4 required checks passing each time:
|
||||
- the `[WaveSize(64)]` pipeline is created but never runs;
|
||||
- kernels using SM 6.6 64-bit atomics, on a typed UAV or a raw buffer, are created but never run, although the device reports support for them; a plain-store marker beside the atomics shows the skip;
|
||||
- a 64-try lock cap drops 96–108 of 512 updates.
|
||||
|
||||
The note links only these measured items from the M2 and M3 roadmap rows. Observations reported from a commercial title are kept in a separate "not evidence" section, each with the synthetic workload that would verify it. This is a local implementer run, not on CrossOver 26.3 and not independently reproduced.
|
||||
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
|
||||
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
|
||||
- `bx_runtime_veh.dll` handles illegal-instruction traps for CLZERO, MONITORX, MWAITX, RDPRU, EXTRQ and INSERTQ (#451). The decoder and fixture derive the encodings and expected results from the AMD Architecture Programmer’s Manual [volume 3](https://kib.kiev.ua/x86docs/AMD/AMD64/24594_APM_v3-r3.36.pdf) (24594, rev. 3.36) and [volume 4](https://kib.kiev.ua/x86docs/AMD/AMD64/26568_APM_v4-r3.25.pdf) (26568, rev. 3.25, EXTRQ pp. 139–140 and INSERTQ pp. 154–155).
|
||||
- CLZERO clears a 64-byte cache line selected by RAX or, with the `67` prefix, EAX. An unwritable target is reported as a write access violation at the line address and the guest can repair the page and retry. One-shot Windows guard-page behavior is outside this emulation.
|
||||
- MONITORX arms no host monitor. MWAITX yields once, so the EBX timer and ECX extensions have no effect. RDPRU approximates MPERF and APERF with the same timestamp rate and returns zero for unknown selectors. It clears the five flags specified by AMD and chooses zero for CF, whose value the manual leaves open.
|
||||
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
|
||||
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
|
||||
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
|
||||
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
|
||||
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` rejects zero and infinite timeouts with E_INVALIDARG and shares one budget between lock acquisition, fence signaling, event registration and fence waiting (returning `ERROR_TIMEOUT` without signaling if lock acquisition uses the whole budget), and re-entering either call on one thread is refused. `Present` never waits for another thread's call on the swapchain: it returns `BX_PRESENT_E_BUSY` with nothing presented, so a host `Present` that depends on the caller cannot deadlock with it. On a live device, if the fence signal after a host `Present` fails, it returns `BX_PRESENT_E_COMPLETION_UNCONFIRMED` (the frame was presented); if waiting on the next back buffer after a host `Present` fails for a reason other than timeout, it logs the underlying wait `HRESULT` and returns `BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED` (the frame was presented). Post-present synchronization failures on a live device refuse further presents with `BX_PRESENT_E_NEEDS_IDLE` until `WaitForIdle` succeeds. Device-removal HRESULTs (`DXGI_ERROR_DEVICE_REMOVED` / `DXGI_ERROR_DEVICE_RESET` / `GetDeviceRemovedReason()`) are logged and returned unchanged. The recovery requirement still applies if the device reports itself as live. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
|
||||
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
|
||||
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits (including rejection of `WaitForIdle(0)` and slow-`Signal` budgets) and the leak path with the queue deliberately blocked, a concurrent `Present`, a failed post-present signal, pre- and post-present `SetEventOnCompletion` failures, post-present device-removal passthrough (`GetCompletedValue() == UINT64_MAX`, `DXGI_ERROR_DEVICE_RESET` wait, `DXGI_ERROR_DEVICE_REMOVED` signal) injected through copied vtables, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each of 6 negative controls. It reads the back buffer before presentation; it does not capture the window.
|
||||
- **Local result:** the earlier `8245c30b` revision passed 332 checks with 0 skipped on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0) and was independently verified on one Apple M5 (332 checks passed, `run_controls.sh` passed). Not a check of what reached the screen, and not an Xbox hardware result.
|
||||
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
|
||||
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
|
||||
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
|
||||
- **Uninitialized environments:** a bare `--prefix` without `system32` is initialized with `wineboot --init` under the same isolated environment. A bottle without one fails with a hint. Neither case is ever skipped silently.
|
||||
- **Partial shim folders:** a `--shims` folder without `xgameruntime.dll` prints a notice and the run continues without staging, as it did before staging existed.
|
||||
- **Supervision:** `--timeout`, SIGINT, SIGTERM and SIGHUP also cover the `wineboot --init` step, so an interrupted first run does not leave `wineserver` running.
|
||||
- **Tests:** 8 unit tests cover staging and the dependency walk. `tests/conformance/test_system32_staging/` makes the `LOAD_LIBRARY_SEARCH_SYSTEM32` load and requires BetterXen's shim, from `system32`, exporting `QueryApiImpl`, and the same module for `SYSTEM32 | APPLICATION_DIR`. `--expect-missing` is the negative control for an unstaged prefix.
|
||||
- **Local result:** on one Apple M3 Pro (macOS 27.2.1) with CodeWeavers Wine 11.0 built from source, so not CrossOver 26.3, and with the staging done by hand: the control passed and the unstaged run failed as expected. Staging the runtime alone still failed, which is how the dependency rule was found. Staging both passed 4/4 in two runs. `bx-cli run` itself was not run, since CrossOver is not installed on that host.
|
||||
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP (including re-resolving managed bottles whose first launch creates a private stub), `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408).
|
||||
- Added `test_apiset_resolution`, a conformance fixture that statically imports the six API-set `win32_bridge` names and reports which module serves each (`--expect host|shim`), and accepted ADR 0007 recording that CrossOver 26.0 and 26.3 answer them via built-ins (`twinapi.appcore.dll` / `user32.dll`) (#437).
|
||||
- Added `docs/maintainer-testing.md` (build, acceptance, expected graphics, known limitations, cleanup) and a CI syntax check for the hybrid scripts.
|
||||
- Strengthened the hybrid acceptance suite (#407): every injected rendering fault must now fail the specific gate it targets, the crash control allows for slow `winedbg` start-up, the suite includes the swapchain lifetime probe and the Shader Model 6 readback check (reported `NOT-RUN` without DXC, never as a pass), and a window hidden on another macOS Space is reported as such. `bx-cli doctor` again reports the recommended memory profile, D3DMetal presence and the shim cross-compiler.
|
||||
- Recorded two local findings on Apple M4 with CrossOver 26.3, neither independently reproduced: under D3DMetal a new D3D12 swapchain starts with two references and survives the application's release, while the same binary on the `vkd3d` path starts with one and is freed; on the `vkd3d` path frames after about 437 each spend 2000 ms inside `Present`, and teardown then hangs.
|
||||
- The migrated #405 work includes Adeeb Rahman's D3D11 compute-buffer readback workload (`ce9c10a`) and Bartosz Szczepański's GPU wired-memory fields in host receipts and run records (`0427465`).
|
||||
- Moved #405's supervised runtime onto the six-track layout (#407): `bx-cli run`, `doctor`, `bench`, `stop` and the evidence commands now share one engine in `launcher/crates/bx-runtime`, replacing the unsupervised launch path. It adds timeout, stall, memory and output limits, a per-environment session lock with explicit recovery, cleanup limited to the selected environment, and JSON run records; `probe`, `shader` and `trace` are unchanged. `bx-cli run` now requires `--bottle` or `--prefix` (there is no shared `/tmp` default). The D3D11 and D3D12 workloads moved to `tests/conformance/`. Verified locally only; no independent reproduction.
|
||||
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
|
||||
- Added Win32 bridge conformance coverage for a hidden window, message dispatch, concurrent PSM registrations, and per-event JSONL log verification. Offline PSM registration tokens are tracked without C++ exceptions using disjoint family tags so cross-family unregisters log `foreign_token` and retired or invalid tokens log `unknown_token` (#410).
|
||||
- `xgameruntime.dll` exports BetterXen-defined `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, `UninitializeApiImpl`, `QueryApiImpl`, and `XErrorReport` so a static loader can resolve them. No public prototype for those six names was found. The documented `XGameRuntimeInitialize`, `XGameRuntimeUninitialize`, `XGameRuntimeInitializeWithOptions`, and `XGameRuntimeOptions` behavior is what the shared refcount follows. `QueryApiImpl` rejects a missing output or id, clears the output pointer on failure, dispatches the offline families this DLL already implements, and logs any other class through `BX_STUB_LOG` before `E_NOINTERFACE`. `XErrorReport` is `void` and writes only valid UTF-8, replacing an invalid byte with `\u00XX` and truncating on a character boundary. The DLL has 49 exports. This is not an Xbox hardware result (#439).
|
||||
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
|
||||
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
|
||||
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
|
||||
@@ -192,19 +51,11 @@ remains unsupported.
|
||||
- Added `tests/conformance/test_integration_boot/` (#420, M1-F1): an original synthetic x86-64 PE32+ boot fixture whose import directory names all 16 shim DLLs and which walks a startup-shaped sequence (AVX2 + FMA, three `clwb` forms, `xmem.dll`, `xgameruntime.dll`, PSM notifications, a hidden window pumped through the `ntuser` forwarders, `XCRDAPI.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, `GameInput.dll` ordinal 1, `xg_xs.dll`, `d3d12_xs.dll`) followed by reverse-order shutdown. Each of 21 stages prints a JSON checkpoint and a `bx_log_emit` record with status `pass`, `pending` or `fail`; `pending` marks an M0 stub's `E_NOTIMPL`/null answer or a host-answered import, is never counted as a pass, and becomes a failure with `--strict` or `BX_INTEGRATION_STRICT=1`. `scripts/build-shims.sh` builds it and still verifies all 16 DLLs. Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the same isolated environment `bx-cli run` sets: 13 pass, 8 pending, 0 fail, exit 0; `--strict` exits 1. It was not run through `bx-cli run` (the CLI only looks for `/Applications/CrossOver.app`) and not on CrossOver 26.3. That run found that this Wine build answers the two `api-ms-win-core-psm-appnotify-*` and four `ext-ms-win-rtcore-ntuser-*` import names itself instead of loading the BetterXen shims: the window stage still passes through `user32`, while PSM registration returns `ERROR_CALL_NOT_IMPLEMENTED` (reported as pending). The device, DirectStorage, AcpHal, GameInput and texture-computer stages are pending on their M0 stubs, and `D3D12XboxCreateDevice` and `XGCreateTextureComputer` are only probed with a null descriptor because no descriptor layout is defined in `abi/`.
|
||||
|
||||
### Removed
|
||||
- Removed the repository-wide provenance, third-party licensing and legal-boundary rules from `AGENTS.md`: §4's per-file license audit and proprietary-component restrictions, §6's "Conditions for target builds" (including lawful acquisition, no leaked or unauthorized builds, no decryption or circumvention, and "If any condition is unknown, do not use the build"), the §6 "Repository & clean-tree boundary" and "Legal boundary" rules, plus the earlier removals of §4's "Provenance first" and §6's "Never obtain or use" bullets. §4 is left as a placeholder pending a replacement policy; the §6 "Authorized compatibility evidence" and §5 honesty rules stay. Nothing in `CONTRIBUTING.md`, `docs/legal.md`, `docs/claims.toml`, the ADRs or the research registry was changed, so those documents still describe the previous policy.
|
||||
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
|
||||
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
|
||||
- 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
|
||||
- Updated the roadmap with the startup checkpoint, synthetic first-frame backing contract, and shared-budget correction. M3 and M6 memory work now has explicit eligibility and measurement criteria.
|
||||
- Recorded the target-workload shader-corpus scan in the roadmap and [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) (2026-11-28). A read-only container scan of an authorized local test workload — structure only, no run, no extraction, not redistributed — found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, and 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable; its packaged shader archive exposes no plaintext `DXBC` and remains unclassified. `dxbc-accc` accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers with `FspxSectionOutOfBounds` because their section tables do not match the clean-room layout. The roadmap keeps D1, treats the upscaler's ACCC-only containers as a concrete D2 candidate gated on runtime submission (first-frame blocker before the first presented frame, M4 upscaling if only upscaling needs them), and records both parser gaps as Track D prerequisites. Build-specific details stay in a local evidence note. Runtime use is unmeasured: the recorded startup run wrote no `shader_gate` records.
|
||||
- `dxbc-accc` reports an `FSPX` descriptor whose offset lands inside the 16-byte header or the descriptor table as `ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }`, not `FspxSectionOutOfBounds` (#599). The reserved region cannot hold section data under BetterXen's synthetic layout, so such a table does not follow that layout; it is not merely truncated. A section that runs past the payload end is still `FspxSectionOutOfBounds`. Both `inspect_dxbc` and the C ABI's `summarize_dxbc` path classify it the same way. The container is still refused: `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` keep returning `BX_SHADER_ERR_INVALID_BLOB` with output cleared, and the C ABI is unchanged, so the distinction does not yet reach `d3d12_xs` gate telemetry. One existing test case (offset 0 in a one-section table) now expects the new variant. New unit tests cover the reserved-region boundary, the out-of-bounds case, the unchanged C ABI refusal, and 4,096 seeded random `FSPX` tables without a panic. Synthetic bytes only; the `FSPX` layout itself is unchanged and remains synthetic (`CLAIM-XBOX-ISA-ABI`, class U).
|
||||
- Added a model-agnostic "AI Agent Efficiency & Resource Management" section to `AGENTS.md` (§9), absorbing the earlier subagent reasoning rule: agents reuse valid evidence, read and verify narrowly and avoid redundant work, without weakening required verification, safeguards or independent review.
|
||||
- Changed contributor and agent rules (`AGENTS.md`, `CONTRIBUTING.md`, `docs/legal.md`): agents now pick work in priority order (fix their own open PRs, then take an unclaimed issue, then review others' PRs); lawfully obtained, maintainer-approved target builds may be inspected locally as compatibility evidence where license terms and law permit, with no decryption or circumvention, and leaked or unauthorized material stays excluded; maintainer-directed tasks may cross track directories without a prior issue claim, while active claims, `[ABI]`-first changes and independent review still apply. Policy only; no compatibility claim.
|
||||
- Corrected `shader-transpiler/crates/dxbc-accc/README.md` (#498): its "Not done here" section listed the export list, the `build-shims.sh` staging and the `d3d12_xs` PSO hook as outstanding, but those shipped (#445, #484, #466). The section now describes each one and credits the issue that delivered it. Documentation only.
|
||||
- Documented independent Direct3D acceptance results on CrossOver 26.3 and CrossOver Preview 27, including D3D12 swapchain retention and Wine presentation stalls (#450).
|
||||
- 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.
|
||||
@@ -234,24 +85,6 @@ 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
|
||||
- `d3d12_xs` now charges its private host heaps through **`bx_xmem_try_charge_external` / `bx_xmem_release_charge_external`**, so `xmem::can_commit` sees graphics usage and **both allocation orders** obey one combined title cap (#552). Before this, `shims/d3d12_xs/vmem.cpp` kept a private `g_record.charged_private_bytes` ledger that `xmem` could not see, so **graphics-first (6) then CPU (3) admitted 9 against a cap of 8**, while xmem-first was rejected correctly. `try_charge` now lets the xmem hook decide on its own, because it admits atomically under `usage_lock` against every owner; the removed local pre-check worked from a snapshot taken outside that lock and, once the stats included external charges, would have counted every live graphics heap twice. `release_charge` checks its diagnostic mirror before crediting xmem, so a double release is refused instead of erasing another heap's charge. The graphics-first pairing check in `test_d3d12_placed` runs only at a 512 MiB cap; run it with `BX_MEM_LIMIT_MB=512`. At other caps the fixture reports the pairing check as skipped in its summary.
|
||||
- **The local pre-check is gone.** `try_charge` lets the xmem hook decide; it admits under `usage_lock` against every owner, so no overflow guards are needed on the d3d12_xs side.
|
||||
- **`g_record.charged_private_bytes` is retained as a diagnostic mirror**, labelled as such; `xmem`'s `external_bytes` is authoritative. Each heap wrapper releases its own charge exactly once, on its final `Release`. `release_charge` checks the mirror before crediting xmem and refuses a release larger than the **total** outstanding graphics charge. Because the mirror is one global total, it is not a per-heap guard: it cannot catch a double release of one heap while another heap is alive. The once-per-wrapper release is what prevents that.
|
||||
- **Lock order checked:** `try_charge`/`release_charge` hold `g_section` and then call into `xmem`, which takes `usage_lock`. `grep` over both files shows `xmem` never calls back into `d3d12_xs` (the only mention is a comment), so `g_section -> usage_lock` is never inverted.
|
||||
- `xmem.dll` exports 17 and `d3d12_xs.dll` exports 4. `test_d3d12_placed.exe` was run live on CrossOver 26.3. At the default cap the pairing check does not run and prints a `SKIP` line. With `BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env` it runs and passes, and the same fixture against the pre-hook DLLs fails the pairing check. The `D3D12ConfigureVirtualMemoryX` log record's `xmem_used=` field is renamed `cap_used=`: it already includes graphics heaps, so it must not be added to `gpu_heap_bytes=`.
|
||||
- **Test:** `tests/conformance/test_d3d12_placed/` gained `check_graphics_xmem_pairing`, which uses only public exports: at a 512 MiB cap (`BX_MEM_LIMIT_MB=512`) a 300 MiB `CreateHeap` must make a 300 MiB `XMemAlloc` fail (300+300 > 512) while a 200 MiB `XMemAlloc` succeeds (300+200 <= 512), and after the heap is released the 300 MiB `XMemAlloc` must succeed. This is the graphics-first overcommit the private ledger allowed. It is a no-op unless the cap is exactly 512 MiB, and it was **not executed** here (no CrossOver).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed — removing `delete this` would leak the dispatcher while every existing check still passed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. A `delete this` removal that leaks the object would leave `live_dispatchers=1` behind and fail. The fixture also creates its own temp `BX_LOG_FILE` when the runner has not set one, so the assertions work standalone rather than reading an empty file. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none; the same offset-slicing works whether the path came from the runner or from the fixture's temp file.
|
||||
- `test_audio_input.exe` now fails with a clear message when `BX_LOG_FILE` is unset, instead of creating a temp log it can never fill. `AcpHal.dll` imports `bx_runtime_veh.dll`, which reads `BX_LOG_FILE` once in `DLL_PROCESS_ATTACH`, before `main` runs, so setting the variable in `main` left the dispatcher log checks reading an empty file and failing for the wrong reason. Run it under `bx-cli run --log`, as before. The comments on those checks no longer claim they catch a dispatcher that leaks: `Release` updates the live-dispatcher counter before `delete this`, so a missing `delete this` leaves the log unchanged. Not run live here (no CrossOver host).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none.
|
||||
- `test_shim_exports.exe` now loads `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), closing the gap #526 documented (#527). The fixture covers **17 DLLs / 28 checks** (16 mingw-w64 C++ shims + the 1 cargo-built Rust bridge; 25 + 3 checks), and its summary line reports the counted DLL number. `abi/` is unchanged. A load-and-resolve check does not show the bridge *works* — `test_shader_gate.exe` is what exercises it functionally. `scripts/build-shims.sh` still verifies 17 PE32+ DLLs / 111 exact exports.
|
||||
- `scripts/audit/docs_hygiene.py` now validates Markdown link fragments (`#heading`) against the target file's headings, using GitHub's slug algorithm with duplicate-heading `-1`/`-2` suffixes and fenced-code-block exclusion. In-page `](#foo)` links are checked against the same file. External URLs and bare `#` links remain unchecked. Covered by the new `scripts/audit/test_docs_hygiene.py` (23 tests) (#537). Repeated heading bases now advance their numeric suffix past *any* slug already emitted, so a literal `# Foo-1` heading no longer lets a later `# Foo` reuse `foo-1`: headings `Foo`, `Foo-1`, `Foo` yield `foo`, `foo-1`, `foo-2`.
|
||||
- Corrected the stale shim-DLL counts in `AGENTS.md`, `README.md`, `docs/roadmap.md` and `docs/architecture/parallel-tracks.md` (#525). `scripts/build-shims.sh` verifies **17** PE32+ DLLs with **111** exact exports, not 16 with 102. The wording now distinguishes the **16 mingw-w64 C++ shims** (built by the CMake superbuild) from the **Rust `bx_shader_bridge.dll`** (built by `cargo` for `x86_64-pc-windows-gnu`, added by #484), rather than calling all 17 "cross-compiled C++ shims". `test_shim_exports.exe` still loads only the 16 C++ shims (25 checks); it does not load the bridge, which `test_shader_gate.exe` covers. The `docs/roadmap.md` M0 exit-gate text is a stale-count correction to a *recorded* gate (`#406`), not a re-opening of M0. Follow-up (not done here): `test_shim_exports` could also load `bx_shader_bridge.dll`.
|
||||
- `bx-cli`'s usage paths were exactly inverted, and are now right (#532). `--help` and `-h` were never matched, so they fell into the unknown-subcommand arm: usage text on **stderr** and exit **1**. Meanwhile a bare `bx-cli` with no arguments printed usage and returned **0**. `--help`/`-h`/`help` now print usage on **stdout** and exit **0**, so `bx-cli --help | less` and `bx-cli --help && ...` both work; a bare invocation is a usage error with text on **stderr** and exit **1**; an unknown subcommand still exits **1**. The choice is factored into a `Dispatch::classify` so it is testable without spawning a process. `launcher/crates/bx-cli/tests/usage.rs` runs the built binary and checks the real exit code and output stream for `--help`/`-h`/`help`, a bare invocation and an unknown subcommand.
|
||||
- **Tests:** `help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error` (exit and stream for `--help`, `-h`, `help`, no arguments, a bogus subcommand, and that the five real subcommands are not usage errors) and `the_usage_text_names_every_subcommand`.
|
||||
- **Not run:** live CrossOver execution — no CLI path here reaches a guest. Synthetic evidence only.
|
||||
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
|
||||
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
|
||||
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
|
||||
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
|
||||
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
|
||||
- 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.
|
||||
@@ -263,9 +96,6 @@ remains unsupported.
|
||||
- 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.
|
||||
- `bx-cli run` signal handling (#461). The environment's `wineserver` is now stopped before anything is reported on the stop path, and those reports and the trace summary no longer use panicking print macros, so Ctrl-C through `| tee` or a closed terminal can no longer skip cleanup. A signal inherited as ignored (`nohup`, a background job of a non-interactive shell) stays ignored. SIGQUIT (Ctrl-\\) stops the guest group and the environment like SIGINT. SIGTSTP (Ctrl-Z) is passed to the guest group, which is continued when `bx-cli` is, and suspended time does not count against `--timeout`. The cleanup `wineserver -k`/`-w` run in their own process group so a second Ctrl-C cannot kill them. The trace summary covers only what this run appended to the log; a log replaced or rewritten during the run (recognized by file identity and by the bytes before the old end, not by size) is summarized in full. A pause during prefix initialization is not charged to the guest's share of `--timeout` either. `THIRD_PARTY_NOTICES.md` no longer claims zero crates.io dependencies and now includes the `libc` MIT text. The stop messages changed from "stopping the environment" to "stopped the environment" because they are printed afterwards. Covered by 10 new unit tests with stub launchers and servers; each fix was removed in turn and its test failed. A reviewer confirmed Ctrl-C through `| tee` on a real terminal under CrossOver 26.3. The author then ran seven scenarios under CrossOver Preview build 20261006 (Ctrl-C through `tee`, an inherited-ignored SIGHUP, Ctrl-\\, Ctrl-Z and continue, repeated Ctrl-C during cleanup, a pause during prefix setup, a log replaced mid-run) with signals sent to the process group rather than typed, using a build that differs only in where it looks for CrossOver; each showed the old behaviour before the change and the fixed behaviour after. Not confirmed with real key presses, and not on CrossOver 26.3 for anything but the first. The same pattern in the unmerged #425 is not touched.
|
||||
- `d3dmetal-harness` runner tests no longer give a freshly written script only 300–500 ms to start (#479); both use a 2 s deadline. The kill test now also checks that the probe ran until the deadline and that its process is gone, which catches a timeout path that neither kills nor waits for the probe. It passes the PID-file path as a script argument so temporary directory names containing apostrophes work. Test-only change. Slow script start-up as the cause of the earlier failures is inferred, not measured. `output_complete` is not asserted for the killed probe, because a child spawned by a parallel test may inherit its pipe.
|
||||
- `bx-cli run` no longer blocks when `--log` names something other than a regular file (#502). The trace-log reads added for #461 opened the path and read it to the end, which waits forever on a FIFO nobody writes to; the log is now opened without waiting and only a regular file is summarized (anything else gets no summary). Also added the missing test for the file-identity half of the replaced-log check (a different file that begins with the old log's bytes), which a reviewer found untested, and documented that Ctrl-Z typed between supervised phases takes effect when the next phase starts. Covered by 2 new unit tests; three deliberate breakages each failed a test. Not run under CrossOver.
|
||||
|
||||
### 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).
|
||||
|
||||
+2
-11
@@ -8,7 +8,7 @@ The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones
|
||||
|
||||
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
|
||||
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. Maintainer-directed tasks have a narrow exception ([AGENTS.md](AGENTS.md) §2).
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
|
||||
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
|
||||
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
|
||||
|
||||
@@ -33,7 +33,7 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
|
||||
|
||||
## Clean-Room, Licensing & Provenance Policy
|
||||
|
||||
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Use publicly accessible specifications, publicly licensed software, and independently authored synthetic workloads only. Never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
|
||||
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
|
||||
@@ -49,13 +49,4 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
|
||||
git commit -s -m "Describe the change"
|
||||
```
|
||||
|
||||
## Review and Merging
|
||||
|
||||
- A PR needs at least one current approval, passing required checks and resolved blocking conversations. Any later push that changes the PR dismisses earlier approvals.
|
||||
- You do not merge your own PR. A maintainer other than the original author merges it.
|
||||
- Please leave **Allow edits by maintainers** enabled on fork PRs (GitHub does not offer it for organization-owned forks). Maintainers may then resolve conflicts and push fixes to your branch, and may still merge it.
|
||||
- A maintainer may re-approve after their own routine fix (conflicts, changelog, minor docs). Substantive changes need approval from someone who did not write them.
|
||||
|
||||
The full rule, including what GitHub does not enforce, is in [AGENTS.md](AGENTS.md) §7, "Merge eligibility".
|
||||
|
||||
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
|
||||
Generated
+8
-1
@@ -7,15 +7,22 @@ name = "bx-cli"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bx-probe",
|
||||
"bx-runtime",
|
||||
"bx-telemetry",
|
||||
"dxbc-accc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bx-probe"
|
||||
version = "0.2.0"
|
||||
|
||||
[[package]]
|
||||
name = "bx-runtime"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bx-telemetry"
|
||||
version = "0.2.0"
|
||||
|
||||
@@ -3,6 +3,7 @@ members = [
|
||||
"launcher/crates/bx-cli",
|
||||
"launcher/crates/bx-probe",
|
||||
"launcher/crates/bx-telemetry",
|
||||
"launcher/crates/bx-runtime",
|
||||
"shader-transpiler/crates/d3dmetal-harness",
|
||||
"shader-transpiler/crates/dxbc-accc",
|
||||
]
|
||||
|
||||
@@ -9,13 +9,13 @@
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

|
||||
-0969da)
|
||||
-d29922)
|
||||

|
||||
|
||||
</div>
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
|
||||
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
|
||||
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
|
||||
@@ -33,9 +33,9 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
|
||||
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
|
||||
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
|
||||
M2["M2: First Frame &\nShader Gate"]:::planned
|
||||
M3["M3: Shaders &\nTexture Tiling"]:::planned
|
||||
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
|
||||
M5["M5: Audio, Saves\n& Stability"]:::planned
|
||||
@@ -50,16 +50,16 @@ flowchart LR
|
||||
|
||||
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
|
||||
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
|
||||
|
||||
| Track | Focus | Visual Status | Live Issues |
|
||||
| --- | --- | --- | --- |
|
||||
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
|
||||
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
|
||||
|
||||
@@ -67,9 +67,9 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 mingw-w64 C++ PE32+ shims plus the Rust `bx_shader_bridge.dll` (17 verified DLLs), live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Merged (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
|
||||
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
|
||||
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
|
||||
@@ -129,10 +129,10 @@ The repository is organized into disjoint track directories around a single froz
|
||||
|
||||
| Directory | Track | Stack | Contents |
|
||||
| --- | --- | --- | --- |
|
||||
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) |
|
||||
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
|
||||
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
|
||||
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
|
||||
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
|
||||
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
|
||||
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
|
||||
@@ -165,9 +165,8 @@ cargo build -p bx-cli
|
||||
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
|
||||
target/debug/bx-cli doctor
|
||||
|
||||
# 3. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust
|
||||
# bx_shader_bridge.dll with cargo, and build the conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export across all 17 DLLs and zero MinGW runtime DLL deps)
|
||||
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
|
||||
@@ -186,7 +185,8 @@ python3 scripts/audit/docs_hygiene.py
|
||||
| `bx-cli doctor` | Inspects Apple Silicon host, RAM (recommends `lockhart` on 16 GB Macs or `anaconda` on 32 GB+), Rosetta 2, CrossOver, D3DMetal, and `mingw-w64` |
|
||||
| `bx-cli probe <pe32+>` | Static PE32+ import scanner that classifies every imported DLL into Tracks A–E or Wine built-ins |
|
||||
| `bx-cli shader <blob>` | Classifies a `DXBC` shader container (`DXIL` vs. legacy `SHDR`/`SHEX` vs. `ACCC`/`FSPX`) |
|
||||
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture |
|
||||
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture. Needs `--bottle` or `--prefix`; supervised with timeout, stall, memory and output limits and writes a JSON record |
|
||||
| `bx-cli stop (--bottle B \| --prefix P)` | Recovers an environment after a supervisor was force-killed |
|
||||
| `bx-cli trace <log.jsonl>` | Aggregates `bx_runtime_veh.dll` logs (unimplemented API counts, COM vtable misses, `clwb` VEH traps, ADX tripwires) |
|
||||
|
||||
---
|
||||
@@ -209,11 +209,9 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
|
||||
|
||||
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
|
||||
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
|
||||
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
|
||||
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
|
||||
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
|
||||
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
|
||||
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
|
||||
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet implemented (M1–M6):**
|
||||
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
|
||||
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
|
||||
|
||||
+15
-61
@@ -1,14 +1,24 @@
|
||||
# Third-party notices
|
||||
|
||||
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `GPL-3.0-or-later` source with **one external crates.io dependency**: `libc`, used only by `bx-cli`.
|
||||
BetterXen's own source is `GPL-3.0-or-later`. The active launcher uses `libc` 0.2.191 (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX signals and file locks, under its MIT option. Preserve the Rust Project Developers notice and permission text. Private build bundles include the unmodified locked libc source and notices.
|
||||
|
||||
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. The crate is licensed `MIT OR Apache-2.0`; its notice and permission text (`LICENSE-MIT` in the 0.2.191 crate) are reproduced under [libc MIT license text](#libc-mit-license-text) below.
|
||||
The memory guard and stall/memory-settle concepts in `launcher/crates/bx-runtime` are inherited from BetterXen #405: attributed Rust reimplementations of contributor-owned supervision concepts from skakwy/victory-mac at `22b3f8e45a59`, GPL-3.0, used with the author's permission as recorded in the [donor per-component audit](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/upstream-integration-audit.md). No game-facing implementation is copied. The excluded `victory-shader` compiler is not imported.
|
||||
|
||||
## Vendored source files
|
||||
Original conformance workloads are built with external llvm-mingw 20261117 (archive SHA-256 `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`). Its wrappers are ISC; LLVM and MinGW compiler/runtime components carry separate terms. Compiler binaries are not bundled. Windows workload bundles preserve the unmodified LLVM/MinGW notices for linked runtime support. Microsoft DXC v1.9.2609 is an external, checksum-pinned Windows guest tool; its executable and DLLs are never bundled. Details: [selected source review](docs/research/maintainer-upstream-review.md).
|
||||
|
||||
| Files | Origin | License |
|
||||
## BetterXen contributor work carried from #405
|
||||
|
||||
These are contributions to BetterXen under `GPL-3.0-or-later`, not third-party code. They were moved onto the six-track layout, so their original commits are not in the new history. The sign-offs recorded in the original commits are:
|
||||
|
||||
```text
|
||||
ce9c10a Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
|
||||
0427465 Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
|
||||
```
|
||||
|
||||
| Contributor | Original commit | Carried to |
|
||||
| --- | --- | --- |
|
||||
| `shims/xcrdapi/dstorage/dstorage.h`, `shims/xcrdapi/dstorage/dstorageerr.h` | Microsoft DirectStorage SDK headers, NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0, unmodified (#483). Provenance and hashes: [shims/xcrdapi/dstorage/README.md](shims/xcrdapi/dstorage/README.md). | MIT, per-file notice. The package's `LICENSE-CODE.txt` is kept next to the headers and reproduced under [DirectStorage headers MIT license text](#directstorage-headers-mit-license-text) below. |
|
||||
| Adeeb Rahman | [`ce9c10a`](https://github.com/MacosPorters/betterxen/commit/ce9c10a3ab4e2c476bf8ab568688089e1edbd19e) | `tests/conformance/optional/d3d11-compute/` (D3D11 compute-buffer readback workload) |
|
||||
| Bartosz Szczepański | [`0427465`](https://github.com/MacosPorters/betterxen/commit/042746554c808dafe48b76b765efd872545429bd) | `launcher/crates/bx-runtime/src/host.rs` and `run.rs` (GPU wired-memory fields in receipts and run records) |
|
||||
|
||||
## External Host Tools & Runtime Dependencies (Never Bundled)
|
||||
|
||||
@@ -19,59 +29,3 @@ The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `G
|
||||
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
|
||||
|
||||
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
|
||||
|
||||
## libc MIT license text
|
||||
|
||||
```text
|
||||
Copyright (c) The Rust Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
```
|
||||
|
||||
## DirectStorage headers MIT license text
|
||||
|
||||
```text
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
+1
-1
@@ -7,4 +7,4 @@ This directory holds the **only shared interface boundary** across BetterXen's s
|
||||
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
|
||||
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
|
||||
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
|
||||
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files. One entry is not under `shims/`: `bx_shader_bridge.def` is the export list of `bx_shader_bridge.dll`, the x86-64 Windows build of `shader-transpiler/crates/dxbc-accc` (#445). `scripts/build-shims.sh` links it into that build and verifies it with the shims (#484).
|
||||
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
|
||||
@@ -1,5 +0,0 @@
|
||||
LIBRARY bx_shader_bridge.dll
|
||||
EXPORTS
|
||||
bx_shader_inspect
|
||||
bx_shader_prepare_for_d3dmetal
|
||||
bx_shader_free_buffer
|
||||
@@ -43,9 +43,3 @@ EXPORTS
|
||||
XGameUiShowTextEntryAsync
|
||||
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
|
||||
XNetworkingQuerySecurityInformationForUrlAsync
|
||||
InitializeApiImpl
|
||||
InitializeApiImplEx
|
||||
InitializeApiImplEx2
|
||||
UninitializeApiImpl
|
||||
QueryApiImpl
|
||||
XErrorReport
|
||||
@@ -15,5 +15,3 @@ EXPORTS
|
||||
XMemVirtualQuery
|
||||
bx_xmem_query_region
|
||||
bx_xmem_get_internal_stats
|
||||
bx_xmem_try_charge_external
|
||||
bx_xmem_release_charge_external
|
||||
@@ -33,24 +33,9 @@ typedef struct bx_xmem_stats {
|
||||
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
|
||||
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
|
||||
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap.
|
||||
* committed_virtual_bytes includes bytes admitted through
|
||||
* bx_xmem_try_charge_external(), so committed + physical is everything the
|
||||
* cap counts and peak_committed_bytes never exceeds what was reported. */
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
|
||||
|
||||
/* Admit `bytes` against the combined title cap, counting every owner.
|
||||
* Returns 1 on success, 0 when the cap would be exceeded or xmem's own
|
||||
* bookkeeping could not be refreshed (logged as external_charge). On success the
|
||||
* caller owns the charge and must release it exactly once with
|
||||
* bx_xmem_release_charge_external(). Never silently succeeds on failure. */
|
||||
int bx_xmem_try_charge_external(uint64_t bytes);
|
||||
|
||||
/* Release a charge previously admitted by bx_xmem_try_charge_external().
|
||||
* Releasing more than is outstanding is refused: the counter is left
|
||||
* unchanged and an external_charge error is logged. */
|
||||
void bx_xmem_release_charge_external(uint64_t bytes);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
+3
-5
@@ -8,14 +8,13 @@
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
- [Synthetic Conformance Suite](../tests/conformance/README.md) — Auto-discovered PE32+ conformance binaries.
|
||||
- [Maintainer Testing Guide](maintainer-testing.md) — Build, acceptance, expected graphics, known limitations and cleanup for the hybrid runtime.
|
||||
- [Changelog](../CHANGELOG.md) — Unreleased and historical changes.
|
||||
|
||||
## Architecture Decision Records
|
||||
|
||||
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
|
||||
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
|
||||
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
|
||||
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
@@ -23,14 +22,13 @@
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Runtime Integration Source Review](research/maintainer-upstream-review.md) and its [reference revisions](research/maintainer-reference-heads.json) — Upstream source inspected for the supervised runtime; nothing adopted.
|
||||
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
|
||||
|
||||
## Governance, Security & Legal
|
||||
|
||||
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
|
||||
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
|
||||
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
|
||||
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
|
||||
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
|
||||
@@ -26,7 +26,7 @@ BetterXen provides integration, configuration, environment management, diagnosti
|
||||
|
||||
## Verified implementation capabilities
|
||||
|
||||
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md` at tag `native-first-final`, the archive ADR 0006 makes canonical; the file is retired from `main`.
|
||||
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
|
||||
|
||||
## Planning consequence
|
||||
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
# ADR 0007: API-set win32_bridge shims are not reached under CrossOver
|
||||
|
||||
Status: **Accepted** (2026-11-26, issue #437). Independently verified on CrossOver 26.0 and CrossOver 26.3 on Apple Silicon.
|
||||
|
||||
## Context
|
||||
|
||||
`shims/win32_bridge/` builds six DLLs named after Windows API sets:
|
||||
`api-ms-win-core-psm-appnotify-l1-1-0`, `api-ms-win-core-psm-appnotify-l1-1-1` and four `ext-ms-win-rtcore-ntuser-*` forwarders to `user32.dll`. A guest that imports those names statically is expected to load the BetterXen files placed next to the EXE. #437 reports that under CrossOver 26.3 it does not: Wine answers the names itself, even with `WINEDLLOVERRIDES=<name>=n,b` and the shim files in the EXE's directory.
|
||||
|
||||
## Evidence
|
||||
|
||||
`tests/conformance/test_apiset_resolution` imports one export from each of the six DLLs through the PE import directory, then reports for every name the module that owns the name and the module the loader bound the import address table slot to.
|
||||
|
||||
Run on an Apple M-series Mac, macOS 27.2.1, Rosetta 2, **CrossOver 26.0 (`26.0.0.39794`)**, bare prefix, with the override list from `bx-cli` (`SHIM_DLL_OVERRIDES`) and `build-shims/bin` as the EXE directory:
|
||||
|
||||
| Import name | Served by | Module that owns the name | Module the import is bound to |
|
||||
| --- | --- | --- | --- |
|
||||
| `api-ms-win-core-psm-appnotify-l1-1-0` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
|
||||
| `api-ms-win-core-psm-appnotify-l1-1-1` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-message-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-window-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
|
||||
`WINEDEBUG=+loaddll` shows `Loaded` records for `user32.dll` and `twinapi.appcore.dll` (both builtin) and none for any of the six shim files. `--expect shim` fails 0/6, so the fixture does distinguish the two outcomes.
|
||||
|
||||
This behaviour was independently reproduced on **CrossOver 26.3** on Apple Silicon (`bx-cli run` with the shim directory and direct loader runs with `WINEDEBUG=+loaddll`), yielding the exact same 6/6 host resolution (`twinapi.appcore.dll` and `user32.dll`, both builtin, with no `Loaded` records for the six shim files) and `--expect shim` exiting 1. The internal Wine mechanism is not claimed here; this records observed loader behaviour.
|
||||
|
||||
## Decision
|
||||
|
||||
Rely on Wine's built-ins. Under CrossOver the six API-set shims are not part of the supported path: the host answers window and message calls through `user32.dll` and PSM registration through `twinapi.appcore.dll`.
|
||||
|
||||
- The six DLLs stay in the tree, built and export-checked, and are still exercised by explicit full-path loads (#431).
|
||||
- No attempt is made to make them win name resolution. That would depend on undocumented Wine API-set behaviour (#350) and, within this issue's scope, on patching or redistributing CrossOver or Wine components, which is out of scope.
|
||||
- Offline PSM behaviour that a title needs must live somewhere a static import actually reaches. This ADR does not choose that place.
|
||||
|
||||
## Consequences
|
||||
|
||||
- `test_apiset_resolution` records the current behaviour (`--expect host`) and fails when it changes. If a CrossOver build starts loading the shims, run it with `--expect shim` and revisit this ADR.
|
||||
- `test_integration_boot` continues to report `shim_backing` as pending for these six names under CrossOver.
|
||||
- Documentation describes the bridges as Windows-only stubs that CrossOver does not load for static imports.
|
||||
|
||||
## Not claimed
|
||||
|
||||
Nothing here shows Xbox title compatibility, behaviour on Xbox hardware, or behaviour on CrossOver builds outside 26.0 and 26.3. Evidence class: local Apple Silicon runs.
|
||||
@@ -1,78 +0,0 @@
|
||||
# ADR 0008: M2 Shader Format Gate — Branch D1 (DXIL normalization) for M3
|
||||
|
||||
Status: **Proposed** (2026-11-26, issue #466). The choice for M3 is the maintainers' to accept. The evidence below is from local Apple Silicon runs by the implementer and has not been independently reproduced.
|
||||
|
||||
## Context
|
||||
|
||||
The roadmap's M2 gate asks which shader path M3 builds:
|
||||
- **Branch D1, DXIL normalization:** shaders reach D3DMetal as DXIL, and BetterXen rewrites only what D3DMetal cannot run.
|
||||
- **Branch D2, `ACCC`/`FSPX` translation:** console-compiled RDNA 2 code in `ACCC` chunks is translated to DXIL or MSL.
|
||||
|
||||
The gate needs a classifier that guest pipeline creation actually reaches, plus measurements of what D3DMetal does with each form.
|
||||
|
||||
## What M2 built
|
||||
|
||||
- **Bridge (#445):** `bx_shader_bridge.dll` is the x86-64 Windows build of `dxbc-accc`, so guest code can call the inspector.
|
||||
- **Gate (#466):** `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` pass every stage through `bx_shader_inspect`. One `shader_gate` JSONL record per stage gives:
|
||||
- the container kind, stage, shader model and chunk sizes;
|
||||
- the `SFI0` feature flags (`D3D_SHADER_FEATURE_*` values from DirectX-Headers `d3dcommon.h`);
|
||||
- the `PSV0` wave lane range.
|
||||
- **Decisions:**
|
||||
- **DXIL and dual containers:** go to the host as the bridge's prepared copy (`bx_shader_prepare_for_d3dmetal`).
|
||||
- **ACCC-only containers:** are refused with `E_NOTIMPL` before the host device is called.
|
||||
- **Legacy DXBC and unclassifiable input:** pass unchanged.
|
||||
- **A missing bridge:** is logged once (`shader_bridge_missing`). Shaders then pass unclassified, except that a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it. The bridge is loaded only by full path from `d3d12_xs.dll`'s own directory.
|
||||
- **Known D3DMetal gaps:** a stage that needs a wave wider than 32 lanes, or 64-bit atomics, also gets a `shader_d3dmetal_gap` record.
|
||||
|
||||
`tests/conformance/test_shader_gate` exercises all of this.
|
||||
|
||||
## Evidence
|
||||
|
||||
| Observation | Source | Host and class |
|
||||
| --- | --- | --- |
|
||||
| A real DXC 1.9.2609 SM 6.6 compute shader (`fill_cs66`) creates a PSO through `d3d12_xs`, runs, and all 256 output words match the CPU reference. | `test_shader_gate` | Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 (`26.3.0.39832`) bottle with `CX_GRAPHICS_BACKEND=d3dmetal`; class A, this host only |
|
||||
| The same shader, run outside Wine through `d3dmetal-native` against CrossOver's D3DMetal 3.0, matches 256/256. | [d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) (#417) | Same host; class A |
|
||||
| An ACCC-only container is refused with `E_NOTIMPL` for compute and graphics, no host object is created, and the device stays usable. | `test_shader_gate` | Same bottle; class A |
|
||||
| In a bare CrossOver 26.3 prefix (vkd3d), SM 6.6 DXIL PSOs fail with `E_FAIL`. vkd3d reports `Cannot load DXIL conversion library`. | `test_shader_gate`, same host | Class A; DXIL needs the D3DMetal backend under CrossOver |
|
||||
| `[WaveSize(64)]` kernels and kernels with SM 6.6 64-bit atomics are created but never run on D3DMetal. | [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints) (#453) | Apple M3 Pro, Wine 11.0 source build, D3DMetal 4.0b3; class A for that host |
|
||||
| DXC records `[WaveSize(64)]` as `PSV0` lanes 64/64, and 64-bit atomics on typed resources as `SFI0` `0x400000`. 64-bit atomics on raw buffers set only `INT64_OPS` (`0x8000`), the same as other 64-bit integer use. | The #453 blobs, read by the gate and by a script | Class A |
|
||||
| Public sources do not establish a console-native shader container layout. BetterXen's `FSPX` is a clean-room synthetic layout, not a description of a console compiler's format. | `CLAIM-XBOX-ISA-ABI` (class U) in [claims.toml](../claims.toml); `shader-transpiler/crates/dxbc-accc/src/fspx.rs` | Source review |
|
||||
| A serialized console pipeline path exists for Series X\|S, with no public version-independent format. | `CLAIM-XBOX-ACO-SAMPLE` (class D) | Source review |
|
||||
| A read-only structural scan of an authorized local test workload (2026-11-28) found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable, and no plaintext `DXBC` in its packaged shader archive. | Static container scan on this host, re-run through `dxbc-accc`; private evidence note, workload not redistributed | This host; structure only, runtime use unmeasured |
|
||||
|
||||
Runtime gate telemetry still covers only synthetic programs; no target-workload run has reached pipeline creation, so what a run submits remains unmeasured. One static measurement now exists (2026-11-28): a read-only container scan of an authorized local test workload, re-run through `dxbc-accc`, with the counts in the table above. The scan measures what shipped components contain, not what any run submits, and the workload is not redistributed. Wherever the gate runs, its `shader_gate` records count it.
|
||||
|
||||
## Decision
|
||||
|
||||
Branch **D1** is proposed for M3:
|
||||
|
||||
1. **Pass DXIL through the gate to D3DMetal.** This is the only path with measured, end-to-end execution evidence.
|
||||
2. **Spend M3 shader work on the two measured gaps,** within the [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints):
|
||||
- lower `WaveSize(64)` programs to 32-lane code;
|
||||
- lower SM 6.6 64-bit atomics to 32-bit operations or bounded lock emulation.
|
||||
|
||||
The gate's `shader_d3dmetal_gap` records show which pipelines need this.
|
||||
3. **Keep refusing ACCC-only containers** with `E_NOTIMPL` and a structured log.
|
||||
|
||||
Branch **D2** is deferred. It needs a documented, lawfully available description of console-compiled containers and their RDNA 2 code, and none exists (`CLAIM-XBOX-ISA-ABI`). A translator built against the synthetic `FSPX` layout would prove nothing about real inputs.
|
||||
|
||||
Revisit this ADR in any of these cases:
|
||||
- an authorized public source for that format appears;
|
||||
- gate telemetry shows a required pipeline-creation path refusing an ACCC-only container at runtime — a static scan already established that the target workload's upscaler component embeds 29, so the open question is submission, not existence;
|
||||
- D3DMetal starts running the gap cases.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
|
||||
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
|
||||
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
|
||||
- **Not covered by the gate yet:**
|
||||
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
|
||||
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
|
||||
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
|
||||
- **`NOBC` programs:** the classifier validates the `DXIL` program header's sizes but not the LLVM bitcode signature, so a container whose bitcode payload is the four-byte placeholder `NOBC` still classifies as executable DXIL and is prepared for the host unchanged. The target workload's main executable embeds 10 such containers (nine pixel, one vertex, SM 6.6). They carry no bitcode, so D1 cannot run them as-is; their signature and validation chunks are intact.
|
||||
- **Wave size:** the gate logs constraints but changes no shader. A pipeline that D3DMetal creates but does not run still behaves that way.
|
||||
|
||||
## Not claimed
|
||||
|
||||
Nothing here describes any Xbox title's shaders, behaviour on Xbox hardware, or D3DMetal versions other than those named. Evidence class: local Apple Silicon runs, one local static container scan of an authorized test workload, and public-source review. The scan counts containers embedded in shipped components on this host; it does not establish what any run submits, and it documents no console-compiled format layout beyond the stated mismatch.
|
||||
@@ -9,7 +9,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
|
||||
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
|
||||
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
|
||||
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
|
||||
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
|
||||
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
|
||||
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
|
||||
@@ -25,7 +25,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
|
||||
## Milestones (M0 → M6)
|
||||
|
||||
1. **M0 — Repo, ABI & Cross-Build:** One-command ARM64 + x86-64 PE32+ build, export verification, and `test_veh_clwb.exe` passing under CrossOver + Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`).
|
||||
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 16 shim DLLs load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
3. **M2 — First Frame & Shader Format Gate:** Present real frames through D3DMetal 3.0 (`PresentX` → `IDXGISwapChain3::Present`) and classify runtime shaders (`DXIL` fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation).
|
||||
4. **M3 — Full Shaders, Streaming & Texture Correctness:** Async DirectStorage decompression, accurate RDNA 2 `xg_xs` tiling/deswizzling, full shader pipeline.
|
||||
5. **M4 — 3D World, Ray Tracing & Input:** BVH4 rehydration → live D3DMetal 3.0 DXR build, FidelityFX/MetalFX upscaling shim, full `GameInput` controller/KB/M mapping.
|
||||
|
||||
@@ -1,30 +1,4 @@
|
||||
# Source review is distinct from a Xenora test run.
|
||||
#
|
||||
# Evidence classes (derived from existing usage; claim classes are unchanged):
|
||||
# A — Executed measurement on a named Apple Silicon host, with an independent
|
||||
# CPU/reference expectation. Valid only for the named host/software versions;
|
||||
# implementer-run unless independently reproduced. Never Xbox verification.
|
||||
# B — Source-derived semantics from a public vendor specification, scoped to the
|
||||
# documented target (e.g. desktop RDNA 2, public D3D12, Metal/MSL). May be
|
||||
# exercised by synthetic tests, but does not establish console applicability.
|
||||
# D — Public documentation or sample-source inspection (Microsoft/Xbox/Apple),
|
||||
# without console execution. Establishes only what the reviewed source states.
|
||||
# E — Public tool/format documentation or observed behavior of a public
|
||||
# software tool (e.g. LLVM's gfx1030 documentation, or its assembler/
|
||||
# disassembler accepting gfx1030 forms), scoped to the pinned tool version.
|
||||
# Documentation review and execution are distinct; the claim's test field
|
||||
# records which one applies.
|
||||
# U — Unknown/unestablished by the reviewed public sources: a bounded statement
|
||||
# about the evidence reviewed, not proof that no authorized source exists.
|
||||
#
|
||||
# Use B for semantics from a specification, D for a claim about what a public
|
||||
# document or sample says, and E for a claim about a tool or its format support.
|
||||
# The current registry does not assign class C.
|
||||
#
|
||||
# These are the repository's evidence classes. AGENTS.md §5 refers to this
|
||||
# file and does not define a second vocabulary; the longer VERIFIED /
|
||||
# REPRODUCED / SOURCE-DERIVED / ... vocabulary named in issue #549 is not
|
||||
# present in the in-tree AGENTS.md, so no mapping is invented here.
|
||||
schema_version = 1
|
||||
|
||||
[[claim]]
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Clean-room scope
|
||||
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation.
|
||||
|
||||
## User-provided game files
|
||||
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
The workspace is GPL-3.0-or-later. The following is the lead's preliminary compatibility inventory. The independent license audit is pending.
|
||||
|
||||
## Active hybrid launcher
|
||||
|
||||
The migrated `bx-cli` uses only `libc` 0.2.191 as an external Rust dependency (revision `ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`, MIT selected). Its MIT notice was read at the locked source and is compatible with GPL-3.0-or-later; source and notices are retained in private bundles. Rust 1.100.0, llvm-mingw 20261117 and optional Microsoft DXC v1.9.2609 are external build tools. Their compiler/runtime notices remain applicable to compiled output and are preserved as described in [third-party notices](../THIRD_PARTY_NOTICES.md).
|
||||
|
||||
The native-first dependency inventory and redistribution discussion below are historical, preserved for the retired code at `native-first-final`. Those objc2/native graphics packages are not dependencies of the active hybrid launcher.
|
||||
|
||||
## Historical native-first inventory
|
||||
|
||||
| Component | Version and upstream revision | License used | Scope |
|
||||
|---|---|---|---|
|
||||
| objc2 | 0.6.5, `d7d2fa23ceaa5e6096c923b081040e5d81b3b9df` | MIT | Runtime bindings |
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
# Maintainer testing guide
|
||||
|
||||
How to build and independently test the supervised hybrid runtime and its Direct3D
|
||||
workloads (issue #407). The workloads are original Windows programs. Passing them shows
|
||||
narrow Windows API behaviour under CrossOver on one Mac. It says nothing about Xbox
|
||||
software, game compatibility or performance, and no maintainer has reproduced these
|
||||
results yet.
|
||||
|
||||
The D3D11 and D3D12 workloads are Track F acceptance inputs for the launcher. They are not a
|
||||
second graphics pipeline and do not exercise the `d3d12_xs` shim.
|
||||
|
||||
`bx-cli` has been run only against CrossOver 26.3 (26.3.0.39832). On any other build `run` and
|
||||
`bench` refuse to start unless given `--allow-untested-crossover`, and `doctor` reports
|
||||
`crossover_build_tested: false`. `stop` is never refused.
|
||||
|
||||
## What has been run
|
||||
|
||||
On commit `7451f0f2ae27b19313015d1ee529b69a755ef12f`, from an existing checkout rebuilt with
|
||||
`build-maintainer.sh`, on one Apple M4 with CrossOver 26.3, by the author's coding agent.
|
||||
This is not independent verification.
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| fmt, clippy, tests | clean; 109 passed, 0 failed, 1 ignored (opt-in live D3DMetal test) |
|
||||
| Shim build | 16 DLLs, 102 exports |
|
||||
| `test_*.exe` fixtures, through `--bottle` and `--prefix` | passed, except `test_veh_unhandled.exe`, which crashes on purpose |
|
||||
| Full acceptance suite | exit 2: 50 `ok`, 2 `KNOWN`, 0 `FAIL`, 0 `NOT-RUN` |
|
||||
| On-screen capture checks | passed |
|
||||
|
||||
The two `KNOWN` lines are the D3D12 swapchain retention below. A clean-clone run and a
|
||||
private-bundle run were last done on earlier source, before `main` was merged.
|
||||
|
||||
`main` at `02b8924` (`xmem` physical pages) was merged afterwards. The Rust checks, shim
|
||||
build and all fixtures, now including `test_xmem_physical.exe`, were rerun with the same
|
||||
results; the full acceptance suite was not.
|
||||
|
||||
After merging `main` at `bfa80de` (`bx-cli trace` reporting), the Rust checks (113 passed, 0
|
||||
failed, 1 ignored), shim build and the shim export, CLWB and crash fixtures with their traces
|
||||
were rerun.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Apple Silicon Mac. Developed on an M4 with 24 GB and macOS 27; nothing else was tried.
|
||||
- CrossOver 26.3 installed from CodeWeavers, and Rosetta 2. Neither is bundled.
|
||||
- Xcode command line tools, `rustup`, Python 3.12 or newer.
|
||||
- For the shim superbuild: `brew install mingw-w64 cmake`.
|
||||
- At least 50% free memory (`memory_pressure -Q`) for the whole run. The runner refuses to
|
||||
start below that; close browsers and other large applications first.
|
||||
- For the on-screen and keyboard checks: a desktop Space in front (not a full-screen app),
|
||||
an unlocked display, and Screen Recording and Accessibility permission for the terminal.
|
||||
Do not type while the keyboard check runs.
|
||||
|
||||
## Build
|
||||
|
||||
From a fresh clone of the branch under test:
|
||||
|
||||
```sh
|
||||
TC=$(scripts/hybrid/install-dependencies.sh) # pinned llvm-mingw and Rust 1.100.0
|
||||
DXC=$(python3 scripts/hybrid/install-dxc.py) # pinned Microsoft DXC, for Shader Model 6
|
||||
export RUSTUP_TOOLCHAIN=1.100.0-aarch64-apple-darwin
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
scripts/build-shims.sh # 16 shim DLLs, 102 exports
|
||||
scripts/hybrid/build-maintainer.sh "$TC" # arm64 bx-cli and workloads
|
||||
BX=$PWD/artifacts/maintainer/bin/bx-cli
|
||||
```
|
||||
|
||||
Both installers download over the network, check a pinned SHA-256 and refuse to overwrite
|
||||
an existing installation.
|
||||
|
||||
## Run
|
||||
|
||||
Use a new bottle that nothing else uses. Stopping a run stops everything in its bottle.
|
||||
|
||||
```sh
|
||||
python3 scripts/hybrid/create-test-bottle.py "$BX" betterxen-maintainer-test
|
||||
"$BX" doctor --bottle betterxen-maintainer-test
|
||||
```
|
||||
|
||||
Shim fixtures (an explicit Wine prefix, separate from the bottle):
|
||||
|
||||
```sh
|
||||
for t in test_veh_clwb test_shim_exports; do
|
||||
"$BX" run --prefix "$PWD/artifacts/m0-prefix" --shims build-shims/bin \
|
||||
--log "$PWD/artifacts/m0-shim.jsonl" --exe build-shims/bin/$t.exe
|
||||
done
|
||||
"$BX" trace artifacts/m0-shim.jsonl # expect "clwb VEH traps : at least 4 (sampled)", ADX 0
|
||||
```
|
||||
|
||||
Full acceptance (Direct3D 12 and 11 workloads, negative controls, lifecycle, soak):
|
||||
|
||||
```sh
|
||||
BETTERXEN_DXC_DIR="$DXC" scripts/hybrid/accept-integrated.sh "$TC" betterxen-maintainer-test
|
||||
```
|
||||
|
||||
Each line is `ok`, `FAIL`, `KNOWN` or `NOT-RUN`. Records, logs and `summary.json` are
|
||||
written under `artifacts/acceptance/<timestamp>/`.
|
||||
|
||||
| Exit status | Meaning |
|
||||
| --- | --- |
|
||||
| 0 | Every check ran and passed |
|
||||
| 1 | At least one check failed |
|
||||
| 2 | No failures, but the known D3D12 retention was seen or a check did not run |
|
||||
|
||||
On CrossOver 26.3 with D3DMetal, 2 is the best result available today.
|
||||
|
||||
## See the graphics
|
||||
|
||||
```sh
|
||||
"$BX" run --bottle betterxen-maintainer-test -- \
|
||||
"$PWD/artifacts/maintainer/workloads/d3d12-integrated.exe" --frames 128 --hold-ms 15000
|
||||
```
|
||||
|
||||
A small window titled "BetterXen D3D12 workload" appears on a black background:
|
||||
|
||||
- a 16-row purple band across the top (the frame number, encoded as a colour);
|
||||
- an upper-left square split into green, blue (top) and red, white (bottom);
|
||||
- a lower-right square split into cyan, magenta (top) and yellow, grey (bottom),
|
||||
overlapping the first and drawn in front of it.
|
||||
|
||||
The command then reports `failed_exit_1` with only the `shutdown` gate failed. That is the
|
||||
known issue below, not a broken build. Any other failed gate is a new problem.
|
||||
|
||||
## Package (optional)
|
||||
|
||||
From a clean committed checkout, after `build-maintainer.sh`:
|
||||
|
||||
```sh
|
||||
scripts/hybrid/package-maintainer.sh
|
||||
```
|
||||
|
||||
It writes `artifacts/packages/betterxen-maintainer-<commit>.tar.gz` and its SHA-256. The
|
||||
bundle contains `bx-cli`, the original workloads, source and licence notices. On another
|
||||
Mac: check the SHA-256, unpack, and run `./test.sh NEW_BOTTLE_NAME` (set
|
||||
`BETTERXEN_DXC_DIR` to include Shader Model 6). The binaries are not signed or notarized.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- **API-set bridge shims (#437).** Under CrossOver, statically imported `api-ms-win-*` and
|
||||
`ext-ms-win-*` names are answered by Wine, not by the `win32_bridge` shims.
|
||||
- **Bottle settings.** `[EnvironmentVariables]` in a bottle apply over variables given with
|
||||
`--env`; only `--backend` and DLL overrides are protected from this.
|
||||
- **Intermittent D3D11 control stall.** One 20,000-frame soak stopped after 9,183 frames
|
||||
because a GPU event query did not complete within 10 s. Three reruns passed. The cause is
|
||||
unknown. The two D3D12 soaks of the same length did not show it.
|
||||
- **Keyboard negative control.** It failed once inside a full run and passed twice on its
|
||||
own. The cause of that one failure was not captured.
|
||||
- **D3D12 swapchain retention (D3DMetal).** A new swapchain starts with two references and
|
||||
survives the application's release, with no application GPU work. The same binary on the
|
||||
`vkd3d` path starts with one and is freed. Observed on one Mac; the cause inside D3DMetal
|
||||
is unknown and BetterXen has no mitigation. Programs that recreate swapchains will grow.
|
||||
- **D3D12 on the `wined3d`/`dxvk` settings (`vkd3d`).** After about 437 frames every
|
||||
`Present` takes 2000 ms and teardown hangs. A 2000 ms wait in public Wine DXGI source is
|
||||
a likely explanation, not a confirmed one. Use the default D3DMetal path for D3D12.
|
||||
- The earlier two-hour D3D12 run presented 844,497 frames with no mismatch in the verified
|
||||
frames, but failed the shutdown gate. It used a pre-migration build, so it does not
|
||||
certify this one.
|
||||
- Double-precision shader operations are not exercised.
|
||||
- Pixel checks read back what was handed to `Present`. Only the window-capture checks
|
||||
observe the macOS compositor.
|
||||
|
||||
## Security limits
|
||||
|
||||
A bottle or prefix is not a sandbox. A Windows program started this way can read and write
|
||||
your files and use the network. `bx-cli` passes only a short list of environment variables
|
||||
(`--inherit-env` opts out), supervises time, output and memory, and stops the selected
|
||||
environment. Run only programs you trust.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Action |
|
||||
| --- | --- |
|
||||
| `refused_to_start_low_memory` | Free memory and rerun; do not run other heavy work alongside |
|
||||
| `bottle has an active BetterXen runner` | Stop that runner with Ctrl-C or SIGTERM |
|
||||
| `bottle has an unfinished session` | `bx-cli stop --bottle NAME` (or `--prefix PATH`) |
|
||||
| `the window exists but is not on the active Space` | Bring a desktop to the front and rerun |
|
||||
| `NOT-RUN Shader Model 6` | Install DXC and set `BETTERXEN_DXC_DIR` |
|
||||
| Crash control reports `timed_out` | Wine's crash dialog is waiting for a click. Create the bottle with `create-test-bottle.py`, which turns it off |
|
||||
|
||||
## Clean up
|
||||
|
||||
Stop any run with `bx-cli stop --bottle NAME`, then delete the test bottle from CrossOver.
|
||||
Build output lives in `artifacts/`, `target/` and `build-shims/` inside the checkout;
|
||||
installers use `~/Library/Caches/BetterXen/`.
|
||||
@@ -20,9 +20,5 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
|
||||
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
|
||||
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
|
||||
| Process groups and signals for `bx-cli run` | rust-lang/libc 0.2.191 (MIT) | **Reuse** | Unmodified crates.io dependency (#408). |
|
||||
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
|
||||
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
|
||||
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
|
||||
|
||||
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
|
||||
@@ -1,175 +0,0 @@
|
||||
# D3DMetal and Apple GPU limits for a shader translator
|
||||
|
||||
Constraints that a translator emitting shaders for D3DMetal on Apple Silicon has to
|
||||
handle (#453). Writing the translator is out of scope.
|
||||
|
||||
The note has two parts:
|
||||
|
||||
- [Measured constraints](#measured-constraints) come from
|
||||
`tests/conformance/test_d3dmetal_gpu_limits`, an original synthetic D3D12 compute
|
||||
fixture checked against values computed on the CPU. These are the only items the
|
||||
roadmap links to. They are a local Apple Silicon run by the implementer, class A for
|
||||
the stated host only, not independently reproduced.
|
||||
- [Unverified reports](#unverified-reports-not-evidence) are observations a contributor
|
||||
posted on #453 from local builds of another project running a commercial title. They are
|
||||
**not evidence** under [AGENTS.md](../../AGENTS.md) §5–6 and must not steer the plan
|
||||
until a synthetic workload reproduces them. They are kept only as leads for writing such
|
||||
workloads.
|
||||
|
||||
Nothing here is an Xbox hardware result, and nothing generalizes beyond the D3DMetal
|
||||
version named.
|
||||
|
||||
## Measured constraints
|
||||
|
||||
### `WaveSize(64)` is created but not run
|
||||
|
||||
`wave.control` (no `WaveSize`) and `wave.wavesize64` (`[WaveSize(64)]`, SM 6.6) record,
|
||||
for each thread, the wave width, its lane index and the dispatch index of its wave's first
|
||||
lane.
|
||||
|
||||
The control passes the check D3D12 actually guarantees: every thread reports the same
|
||||
width, and within each wave the lane indices are a permutation of `0..W-1`. No particular
|
||||
thread-to-lane order is assumed. On D3DMetal 4.0b3:
|
||||
|
||||
- the device reports `WaveLaneCountMin = WaveLaneCountMax = 32`;
|
||||
- the control runs at width 32;
|
||||
- the wave64 pipeline is **created without error but never runs**: its output buffer keeps
|
||||
the sentinel.
|
||||
|
||||
So a translator cannot rely on pipeline creation failing. A program written for a 64-lane
|
||||
wave has to be emitted as 32-lane code, with its two halves made to agree wherever the
|
||||
original wave acted as one.
|
||||
|
||||
### Kernels using SM 6.6 64-bit atomics are created but not run
|
||||
|
||||
`atomic64.image` runs a 64-bit `InterlockedAdd` (low halves carrying into the high half)
|
||||
and an `InterlockedMax` (decided by the high half) on a `RWTexture2D<uint64_t>` over
|
||||
`DXGI_FORMAT_R32G32_UINT`. `atomic64.buffer` runs the same operations on a raw buffer. Each
|
||||
kernel also writes a plain 64-bit marker next to its atomics, which shows whether the kernel
|
||||
ran at all. On D3DMetal 4.0b3:
|
||||
|
||||
- The device reports `AtomicInt64OnTypedResourceSupported` and
|
||||
`AtomicInt64OnDescriptorHeapResourceSupported` as supported, and both pipelines are
|
||||
created without error.
|
||||
- Neither kernel runs. The atomic results and the markers all read back as their initial
|
||||
zeros, on the texture and on the raw buffer alike.
|
||||
- A throwaway variant with the atomics removed but the markers kept wrote 8/8 markers.
|
||||
That shows the readback path is sound and the skip comes from the atomics.
|
||||
|
||||
So these kernels are silently skipped, on raw buffers as well as images. This is
|
||||
consistent with d3dmetal-native's `d3d12-atomic64-test` reading back zeros in the
|
||||
[d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) evaluation
|
||||
on D3DMetal 3.0. A translator has to lower 64-bit atomics to 32-bit operations.
|
||||
|
||||
### Lock-based emulation needs a sufficient retry cap and both fences
|
||||
|
||||
`lock64.cap64` and `lock64.cap1024` emulate both operations with a per-texel lock word,
|
||||
with 32 contending threads per texel and a bounded number of tries:
|
||||
|
||||
1. take the lock with `InterlockedCompareExchange` 0→1;
|
||||
2. `DeviceMemoryBarrier()` (**acquire**: the data reads are ordered after taking the lock;
|
||||
`globallycoherent` gives visibility, not ordering);
|
||||
3. update the two 32-bit halves;
|
||||
4. `DeviceMemoryBarrier()` (**release**);
|
||||
5. free the lock with `InterlockedExchange`.
|
||||
|
||||
A thread that runs out of tries counts a drop instead of spinning on. The 1024-try run is
|
||||
required to drop nothing and to match the CPU reference exactly. The 64-try run is
|
||||
reported. On D3DMetal 4.0b3, in three runs each:
|
||||
|
||||
- **1024 tries:** nothing dropped, 16/16 values exact, about 15,000–18,000 tries in all.
|
||||
- **64 tries:** 96–108 of 512 updates dropped.
|
||||
|
||||
So a low cap trades a hang for silently lost updates. With 32 contending threads, 64 tries
|
||||
is already too low.
|
||||
|
||||
The loop shape matters. The critical section sits **inside** the retry loop, so a lane
|
||||
that wins finishes it in the same iteration, and no lane waits for another lane to leave a
|
||||
loop. The fixture does not run the classic shape (`while (!acquire()) {}` followed by the
|
||||
critical section). There, the winning lane can be parked at the loop's reconvergence point
|
||||
behind the lanes still spinning, and on a GPU without independent forward progress for
|
||||
each thread that could hang the queue. Apple's shader converter prints `Warning:
|
||||
Undefined: Shader might rely on forward progress/persistent thread` even for the safe
|
||||
shape.
|
||||
|
||||
## Fixture results
|
||||
|
||||
A local run by the implementer on 2026-11-26. Class A for this host only; not
|
||||
independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Host | Apple M3 Pro, macOS 27.2.1 (26B131), Rosetta 2 |
|
||||
| Wine | CodeWeavers Wine 11.0 built from CodeWeavers' published source; CrossOver itself was not installed |
|
||||
| D3DMetal | 4.0b3 from Apple's Game Porting Toolkit (x86_64; SHA-256 of the binary starts with `b16aab78127d`), user-supplied |
|
||||
| Shaders | DXC 1.9.2609 via `shaders/compile.sh`; the same DXC reproduces the d3dmetal-harness `fill_cs66` container byte for byte (SHA-256 `7df11b63…`) |
|
||||
| Command | `ROSETTA_ADVERTISE_AVX=1 WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=b" wine build-shims/bin/test_d3dmetal_gpu_limits.exe` in a fresh prefix |
|
||||
| Runs | 3, identical outcomes apart from the 64-try drop counts; exit 0, `SUMMARY: 4 required checks, 0 failed` each time |
|
||||
|
||||
| Check | Outcome |
|
||||
| --- | --- |
|
||||
| `device.shader_model` | 6.6 |
|
||||
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
|
||||
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
|
||||
| `wave.wavesize64` | created but not run (output still sentinel) |
|
||||
| `atomic64.reported` | typed and descriptor-heap 64-bit atomics reported as supported |
|
||||
| `atomic64.buffer` | not run: marker 0/8, atomic values 16/16 still zero |
|
||||
| `atomic64.image` | not run: marker 0/8, atomic values 16/16 still zero |
|
||||
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
|
||||
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
|
||||
|
||||
**Exit codes.** The fixture exits **0** with every required check passed, **1** on a failed
|
||||
required check, and **77** with a `SKIP: <reason>` line when `d3d12.dll`, its exports, device
|
||||
creation, or shader model 6.6 is unavailable. 77 is not a pass; see the exit-status section of
|
||||
[`tests/conformance/README.md`](../../tests/conformance/README.md#exit-status-pass-fail-and-unavailable)
|
||||
for a recording recipe. Through `bx-cli run` the guest status is returned unchanged.
|
||||
|
||||
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
|
||||
(D3DMetal 3.0) by another contributor.
|
||||
|
||||
## Unverified reports (not evidence)
|
||||
|
||||
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
|
||||
host. None of this is a BetterXen measurement, no code or shader from that project is
|
||||
used, and none of it may be cited by the roadmap or a milestone gate. Each item names the
|
||||
synthetic workload that would turn it into evidence.
|
||||
|
||||
- **Splitting wave64 programs.** Operations that need care when the two halves must agree:
|
||||
- wave reductions;
|
||||
- first-lane and indexed lane reads;
|
||||
- the 64-bit lane mask read as data;
|
||||
- cross-half permutes;
|
||||
- scalar values spilled into vector lanes;
|
||||
- group barriers, which are only safe where both halves provably reach them.
|
||||
|
||||
The reporter found a uniformity analysis of the program's values, with barriers placed
|
||||
only after uniform branches, made most such programs translate exactly. Where agreement
|
||||
cannot be proven and each half runs as its own wave, a group sync that not every lane
|
||||
reaches must become a memory fence without the group wait. *Workload needed:* SM 6.6
|
||||
wave64-style kernels with each of these patterns, checked half by half.
|
||||
- **Helper lanes in a spin lock.** In a pixel shader, helper lanes must not take part in
|
||||
such a lock: their atomics have no effect, so they never win and spin to the cap. This
|
||||
was reported as a hard queue hang with no macOS GPU timeout logged. A cap of 2^16 was
|
||||
reported to hang while 2^10 did not; whether the cap or the helper lanes caused it was not
|
||||
separated. *Workload needed:* a pixel shader with a lock-protected 64-bit update across
|
||||
triangle edges.
|
||||
- **Mesh output size.** Metal refuses mesh pipelines whose per-vertex outputs exceed 32,768
|
||||
bytes, counting the aligned layout (distances, position, then outputs in register order,
|
||||
each aligned to its own size). A refused pipeline submitted anyway was reported to hang
|
||||
the queue under Wine. *Workload needed:* mesh shaders whose output size crosses 32 KiB
|
||||
only once alignment is counted.
|
||||
- **Apple shader compiler crash.** `MTLCompilerService` was reported to crash in register
|
||||
allocation on mesh pipelines whose pixel shader writes several render targets. The
|
||||
reported cause was output stores merged before all their values are defined, and the
|
||||
reported fix was emitting each output row's stores after its values. *Workload needed:* a
|
||||
mesh and pixel pair with several render targets and late-computed outputs.
|
||||
- **No zero-copy heaps.** D3DMetal 4.0b3 was reported to answer
|
||||
`ID3D12Device3::OpenExistingHeapFromAddress` with "Not implemented". *Workload needed:*
|
||||
a fixture that calls it on a page-aligned allocation.
|
||||
|
||||
## Regenerating the shaders
|
||||
|
||||
`tests/conformance/test_d3dmetal_gpu_limits/shaders/compile.sh` regenerates the committed
|
||||
headers with Microsoft's DXC release v1.9.2609 (`dxc_2026_09_29.zip`, SHA-256
|
||||
`ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1`, the same package the
|
||||
d3dmetal-harness records), running `bin/x64/dxc.exe` under a Wine loader.
|
||||
@@ -1,88 +0,0 @@
|
||||
# D3D12 swapchain references under D3DMetal
|
||||
|
||||
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
|
||||
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. See the independent Apple M2 Pro run below.
|
||||
|
||||
| | D3DMetal | Wine `vkd3d` path |
|
||||
| --- | --- | --- |
|
||||
| References on the swapchain right after creation | 2 | 1 |
|
||||
| Count returned by the application's final `Release` | 1 | 0 |
|
||||
| Swapchains still referenced after 12 create/release cycles | 12 | 0 |
|
||||
|
||||
The same program was used for both, and it submitted no GPU work of its own. Under D3DMetal
|
||||
each retained swapchain also kept a device reference. The cause inside D3DMetal is unknown. A
|
||||
program that recreates swapchains (for example on resize) should be expected to grow until this
|
||||
is explained.
|
||||
|
||||
The probe is
|
||||
[`lifetime.c` at `7c512af`](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_lifetime/lifetime.c)
|
||||
on the branch of #425; it is not part of this branch. Tracked in #450.
|
||||
|
||||
## Independent run on Apple M2 Pro
|
||||
|
||||
On 2026-11-26, an Apple M2 Pro (16 GiB, macOS 27.3 build 26C5035r) reproduced
|
||||
the swapchain retention in CrossOver 26.3.0.39832 with D3DMetal 3.0. The
|
||||
same x86-64 probe under Rosetta 2 released all swapchains in CrossOver
|
||||
Preview 27.0.0.41303. Each CrossOver build used a fresh Windows 11
|
||||
64-bit bottle. The Direct3D 12 workload loaded the `apple_gptk` D3D12
|
||||
and DXGI modules in both builds. The bundled framework in the Preview
|
||||
build's `apple_gptk` directory reports version 4.0b3.
|
||||
|
||||
| Swapchain lifetime probe | Initial reference count | Application release returned | Witnesses retained |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 26.3 D3DMetal | 2 | 1 | 12 of 12 |
|
||||
| 26.3 Wine D3D12 | 1 | 0 | 0 of 12 |
|
||||
| Preview D3DMetal | 1 | 0 | 0 of 12 |
|
||||
| Preview Wine D3D12 | 1 | 0 | 0 of 12 |
|
||||
|
||||
Destroying the window before releasing the swapchain and calling
|
||||
`ResizeBuffers` before teardown each left 3 of 3 witnesses retained on
|
||||
26.3 D3DMetal. Explicitly detaching the witness released the probe's
|
||||
private data, while the swapchain's release still returned 1. The
|
||||
deliberately retained witness control failed as expected. An extra
|
||||
application-side `Release` would drop a reference the application
|
||||
does not own.
|
||||
|
||||
The separate D3D12 integrated workload presented 600 frames and verified
|
||||
eight readbacks with zero mismatches on both D3DMetal builds. It failed
|
||||
only the shutdown gate on 26.3, where the final device release returned
|
||||
2. Preview passed shutdown with a final device release of 0. These runs
|
||||
used the direct host D3D12 path without BetterXen's D3D12 shim. The
|
||||
comparison establishes behavior for these two CrossOver builds on this
|
||||
host. The underlying ownership change is unknown.
|
||||
|
||||
Build the probe from the pinned source linked above with
|
||||
`x86_64-w64-mingw32-clang -std=c11 -O2 -Wall -Wextra -Werror lifetime.c -o d3d12-lifetime.exe -ld3d12 -ldxgi -ldxguid -luser32`
|
||||
(LLVM-MinGW 20261117 in this run). Run in a clean bottle using
|
||||
`ROSETTA_ADVERTISE_AVX=1 CX_GRAPHICS_BACKEND=d3dmetal wine --bottle <bottle> <absolute-path-to-exe> --cycles 12`
|
||||
and repeat with `CX_GRAPHICS_BACKEND=wined3d`. The two witness controls
|
||||
use `--cycles 3 --detach-witness` with and without `--retain-app-reference`.
|
||||
|
||||
## Related Direct3D acceptance failures
|
||||
|
||||
The [integrated D3D12 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_integrated/integrated12.c)
|
||||
also reproduced the presentation slowdown on the Wine D3D12 path on
|
||||
26.3. With `CX_GRAPHICS_BACKEND=wined3d` and a 600-frame target, the
|
||||
workload logged approximately 2,000 ms inside `Present` on frames
|
||||
12–38, then exited 3 after a 10-second GPU completion wait failed. The
|
||||
previous M4 report saw the slowdown around frame 437. This run exited
|
||||
before reaching normal teardown. Preview completed the same 600-frame
|
||||
workload on the Wine path with eight verified readbacks, no mismatches
|
||||
and clean shutdown. A 600-frame repeat on 26.3 passed with `--vsync`
|
||||
enabled. A subsequent 600-frame repeat also passed with the flag off,
|
||||
so the slowdown remains intermittent and the successful vsync run
|
||||
does not establish a workaround.
|
||||
|
||||
The [integrated D3D11 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d11_integrated/integrated.c)
|
||||
completed the 20,000-frame soak on 26.3 with 46 verified readbacks,
|
||||
zero mismatches and a clean shutdown. The intermittent GPU event
|
||||
stall did not recur in this run. Preview also completed all 20,000
|
||||
frames and all 46 readbacks, then failed the shutdown gate with one
|
||||
device reference remaining. A separate 600-frame Preview run
|
||||
reproduced that shutdown result.
|
||||
|
||||
The 26.3 keyboard check delivered five macOS events to the workload and
|
||||
reached the expected offset (16, 32). The negative control delivered
|
||||
two Up events and reached (0, -32), which the input gate rejected as
|
||||
expected. These were isolated runs, so they do not reproduce the
|
||||
intermittent failure observed inside the full acceptance suite.
|
||||
@@ -0,0 +1,196 @@
|
||||
{
|
||||
"evidence_class": "D",
|
||||
"observed_date_local": "2026-11-25",
|
||||
"scope": "Public repository accessibility/head metadata only; authenticated private repository metadata remains in ignored local evidence. Source review scope is separate.",
|
||||
"repositories": [
|
||||
{
|
||||
"repo": "MacosPorters/VIctory-macOS",
|
||||
"url": "https://github.com/MacosPorters/VIctory-macOS",
|
||||
"branch": "main",
|
||||
"head": "d6fc0620f53a5c9073b9d08d0910c8d6aa5d0bdf",
|
||||
"license": "GPL-3.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "pragyaangaur/VIctory-macOS",
|
||||
"url": "https://github.com/pragyaangaur/VIctory-macOS",
|
||||
"branch": "main",
|
||||
"head": "b6dd0b184277fc307b93a4cc90d23dca9f05e7b3",
|
||||
"license": "GPL-3.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "utmapp/d3dmetal-native",
|
||||
"url": "https://github.com/utmapp/d3dmetal-native",
|
||||
"branch": "main",
|
||||
"head": "af1ee1710711fadff41dead87960d0f1336c1047",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "ProhorovIlja/NativeX-Runtime",
|
||||
"url": "https://github.com/ProhorovIlja/NativeX-Runtime",
|
||||
"branch": "main",
|
||||
"head": "b3087ce0ab191227dc9e7af37cab97a0b097bb98",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "wine-mirror/wine",
|
||||
"url": "https://github.com/wine-mirror/wine",
|
||||
"branch": "master",
|
||||
"head": "274fcfa9691bf3b7f24c0833ad33e9d57c3df65f",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "doitsujin/dxvk",
|
||||
"url": "https://github.com/doitsujin/dxvk",
|
||||
"branch": "master",
|
||||
"head": "6e25a5e7af5a05e5729e7abc5bf1184df9242e2a",
|
||||
"license": "Zlib",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "HansKristian-Work/vkd3d-proton",
|
||||
"url": "https://github.com/HansKristian-Work/vkd3d-proton",
|
||||
"branch": "master",
|
||||
"head": "71cae091b06571e51446cf2a937f0b04c237c04d",
|
||||
"license": "LGPL-2.1",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "3Shain/dxmt",
|
||||
"url": "https://github.com/3Shain/dxmt",
|
||||
"branch": "main",
|
||||
"head": "faa73e4a0686e432ce5d3bb99a02b5363d76885c",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "KhronosGroup/MoltenVK",
|
||||
"url": "https://github.com/KhronosGroup/MoltenVK",
|
||||
"branch": "main",
|
||||
"head": "5189f8de86ec365860f63bf1da736815cfaea5cd",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "llvm/llvm-project",
|
||||
"url": "https://github.com/llvm/llvm-project",
|
||||
"branch": "main",
|
||||
"head": "0cae57720c3ca7cb09b5ba48d199f1ba04e3aae2",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "mstorsjo/llvm-mingw",
|
||||
"url": "https://github.com/mstorsjo/llvm-mingw",
|
||||
"branch": "master",
|
||||
"head": "903f4cf7faa24e30c8e0c4615f8ce61a0f3d80f8",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "microsoft/DirectXShaderCompiler",
|
||||
"url": "https://github.com/microsoft/DirectXShaderCompiler",
|
||||
"branch": "main",
|
||||
"head": "2600ae89a6153302421b13b4db7d3bd1bd0d9385",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "microsoft/DirectX-Graphics-Samples",
|
||||
"url": "https://github.com/microsoft/DirectX-Graphics-Samples",
|
||||
"branch": "master",
|
||||
"head": "68a2b1e97f71642924e74c7757ca21756ad221b5",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "microsoft/DirectX-Headers",
|
||||
"url": "https://github.com/microsoft/DirectX-Headers",
|
||||
"branch": "main",
|
||||
"head": "61c7718954ec73dbdd43c723240fe1a0452a3724",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "microsoft/DirectXTex",
|
||||
"url": "https://github.com/microsoft/DirectXTex",
|
||||
"branch": "main",
|
||||
"head": "a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "KhronosGroup/SPIRV-Cross",
|
||||
"url": "https://github.com/KhronosGroup/SPIRV-Cross",
|
||||
"branch": "main",
|
||||
"head": "57e4efcc84112abcd426dc5ec248b5339bee04f2",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "gfx-rs/wgpu",
|
||||
"url": "https://github.com/gfx-rs/wgpu",
|
||||
"branch": "trunk",
|
||||
"head": "60cef2be828e03ba54e2e1598001b4625c0c2163",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "LIEF-project/LIEF",
|
||||
"url": "https://github.com/lief-project/LIEF",
|
||||
"branch": "main",
|
||||
"head": "2a6fdbc5a3af9b7ac797514ca38b1175c78f3fcf",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "FEX-Emu/FEX",
|
||||
"url": "https://github.com/FEX-Emu/FEX",
|
||||
"branch": "main",
|
||||
"head": "3ee25399232a6431c77c6314c437ea523ec29d0c",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "apitrace/apitrace",
|
||||
"url": "https://github.com/apitrace/apitrace",
|
||||
"branch": "master",
|
||||
"head": "28bb3aba57f3f9df4932867496308f4fc0a2b423",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "apple/game-porting-toolkit",
|
||||
"url": "https://github.com/apple/game-porting-toolkit",
|
||||
"branch": "main",
|
||||
"head": "4f42344c90be22112f46becc3fb9687f423f2f88",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
# Runtime integration source review
|
||||
|
||||
This continues the existing [donor audit ledger](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/audit-ledger.tsv), [donor reference assessment](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/reference-projects-2026-11-25.md) and [donor integration audit](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/hybrid-runtime-audit-2026-11-25.md). It does not recertify their execution results. Source review is evidence class D; newly run workloads must have separate execution records. No reference-project implementation was added to BetterXen source. A private bundle includes unmodified source/notices for the already selected libc dependency.
|
||||
|
||||
## Components affecting demonstrated blockers
|
||||
|
||||
| Component and exact revision | Source actually inspected | Finding and integration decision |
|
||||
| --- | --- | --- |
|
||||
| Wine `274fcfa9691bf3b7f24c0833ad33e9d57c3df65f` | `dlls/dxgi/swapchain.c`: D3D12 `Present`, worker presentation, destruction and release functions; LGPL-2.1-or-later header and `COPYING.LIB` | `d3d12_swapchain_present` waits up to 2000 ms on the frame-latency semaphore. The worker releases it after successful Vulkan presentation. This is a testable explanation for two-second frames, not proof of the installed CrossOver failure. Destruction joins the worker, destroys graphics resources and releases the command queue, device and factory. Do not replace CrossOver with this moving upstream head. |
|
||||
| VKD3D-Proton `71cae091b06571e51446cf2a937f0b04c237c04d` | `libs/vkd3d/swapchain.c`: frame-latency wait/signal sites; `COPYING` | Separate internal and application latency events. LGPL-2.1-or-later. This is not proof CrossOver ships this implementation: its official source list names Vkd3d. No integration or performance claim. |
|
||||
| DXMT `faa73e4a0686e432ce5d3bb99a02b5363d76885c` | `src/d3d12/d3d12_swapchain.cpp`: constructor/destructor and latency sites; `LICENSE` | Current source contains D3D12 development code despite older D3D11-only descriptions. Presence is not backend availability in installed CrossOver 26.3. LGPL-2.1-or-later, CodeWeavers attribution. Do not silently substitute an untested build. |
|
||||
| NativeX Runtime `b3087ce0ab191227dc9e7af37cab97a0b097bb98` | Entire `fixtures/native_win_dxgi_multiframe.cpp` and `src/native_upload_arena.cpp`; tiled-resource fixture through its GPU copy/readback path; `LICENSE`, `docs/PUBLIC_SCOPE.md` | MIT at repository root; fixture says original synthetic Win32/WARP work. Multiframe fixture uses explicit pacing and fences, releases per-frame resources before resizing, and disclaims physical-GPU/pixel verification. Upload arena bounds allocations and recycles only completed fence ranges. Windows/WARP assumptions and project-local timing/upload headers prevent treating these as turnkey Mac tests. Historical title-specific planning is disclosed; independent origin is not certified by a licence label. Source-level comparison only; nothing adopted or executed. |
|
||||
| d3dmetal-native `af1ee1710711fadff41dead87960d0f1336c1047` | Prior source/build record reused; no repeat build | See [donor evaluation](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/d3dmetal-native-evaluation.md), including exact dependencies and unverified framework rights. An x86-64 native graphics host does not replace Wine's Windows runtime and does not satisfy BetterXen's ARM64 host rule. No framework extraction, patching or new execution. |
|
||||
|
||||
Primary source links: [Wine swapchain](https://github.com/wine-mirror/wine/blob/274fcfa9691bf3b7f24c0833ad33e9d57c3df65f/dlls/dxgi/swapchain.c), [VKD3D-Proton](https://github.com/HansKristian-Work/vkd3d-proton/blob/71cae091b06571e51446cf2a937f0b04c237c04d/libs/vkd3d/swapchain.c), [DXMT](https://github.com/3Shain/dxmt/blob/faa73e4a0686e432ce5d3bb99a02b5363d76885c/src/d3d12/d3d12_swapchain.cpp), [NativeX fixture](https://github.com/ProhorovIlja/NativeX-Runtime/blob/b3087ce0ab191227dc9e7af37cab97a0b097bb98/fixtures/native_win_dxgi_multiframe.cpp).
|
||||
|
||||
## Shader decision and legitimate compiler path
|
||||
|
||||
The runtime consumes ordinary Windows shaders through CrossOver. `launcher/crates/bx-runtime` has no dependency on the console shader import. #394's compiler therefore solves no demonstrated requirement of this execution path. The complete per-file [independent #399 review](https://github.com/MacosPorters/betterxen/issues/399) and [donor decision proposal](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/shader-import-decision.md) identify unresolved origin and explicit project-policy exclusions. This candidate excludes #394 and the dependent #395 runner. Passing compiler tests cannot resolve those exclusions; no replacement console compiler is required.
|
||||
|
||||
Only the seven original `tests/conformance/test_d3d12_wave/` files from BetterXen commit `d8c7a398492c483599f02766ebf5707f38dc6128` are retained. The C runner has bounded inputs and releases successful-run resources; the build adds the missing GUID library. Numeric acceptance compares GPU words with independent arithmetic constants and checks a one-bit wrong expectation. Unsupported double precision is not counted as a pass.
|
||||
|
||||
Microsoft DXC is an external open-source **Windows guest build tool**, not a BetterXen x86-64 host executable. The selected release is [v1.9.2609](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609), asset `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` (verified against GitHub release metadata). Its LLVM/MIT/Microsoft notices stay with the external installation. No compiler DLL or executable is packaged. Original HLSL and its compiled output are separate from the excluded console compiler. The installer must verify the archive before use.
|
||||
|
||||
The external llvm-mingw pin remains release `20261117`, SHA-256 `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`, LLVM commit `5b10d2d74929eae78912771222c9855af97496f4`. Its wrappers are ISC; compiler, builtins, headers and runtime carry their own notices. The universal compiler is run natively on ARM64 and is not distributed. Build notices include the unmodified LLVM and MinGW runtime terms. Rust Windows COFF timestamps are explicitly disabled; source paths are remapped. The original independent #364 build review remains separate from this task.
|
||||
|
||||
## Provenance restrictions and permission scope
|
||||
|
||||
The reachable heads for skakwy/victory-mac and MacosPorters/victory-mac-new remain identical at `3ecbb8f96956513df71343ad9de41aa48b0b8008`. MacosPorters/VIctory-macOS is `d6fc0620f53a5c9073b9d08d0910c8d6aa5d0bdf`; pragyaangaur/VIctory-macOS is `b6dd0b184277fc307b93a4cc90d23dca9f05e7b3`. Existing inventories and permission records are reused. Contributor permission covers only independently owned contributions; it does not clear other contributors' lines or underlying third-party material. No broader permission document was established by this task.
|
||||
|
||||
The current engineering rules require a recorded per-file provenance and licence audit before taking any code or tooling from leaked-build derivatives, and exclude game-, asset- and decryption-specific code. Contributor permission covers only contributions the contributor owns. This candidate takes no additional source from those projects; the inherited Rust memory guard is an attributed conceptual reimplementation from #405, with the original per-component review preserved in its donor audit. The current Track D shader-format gate remains separate from the excluded #394 import. No policy amendment is needed for the current Windows shader probes.
|
||||
|
||||
## Accessibility check and limits
|
||||
|
||||
All 23 requested GitHub repositories were reachable during this task; public heads are saved in the [accessibility snapshot](maintainer-reference-heads.json), with authenticated private metadata kept in ignored local evidence. The existing 84-entry PortWatch inventory was not repeated. Except for the source files identified above, those checks are metadata only, not implementation review. LLVM, llvm-mingw, DXC, DirectX-Headers, DirectXTex, DirectX-Graphics-Samples, SPIRV-Cross, wgpu, LIEF, FEX and apitrace remain available references; none supplies a demonstrated missing loader, translator or backend for this candidate merely by being available.
|
||||
|
||||
The [CodeWeavers source page](https://www.codeweavers.com/crossover/source) publishes `crossover-sources-26.3.0.tar.gz`. This task downloads that official archive for targeted source comparison; downloading is not a rebuilt or validated replacement runtime. CodeWeavers' [graphics documentation](https://support.codeweavers.com/advanced-settings-in-crossover-mac?kb_language=en_US) separates D3DMetal's D3D11/12 support from DXVK's D3D10/11 role. A `dxvk` or `wined3d` selection must not be labelled proof of the active D3D12 implementation.
|
||||
|
||||
Apple's [Metal command execution documentation](https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/Cmd-Submiss/Cmd-Submiss.html) distinguishes submission, completion and presentation. Accordingly, an application fence and matching readback do not establish that pixels reached the compositor; screen capture remains a separate check. None of this establishes Xbox execution, commercial-game compatibility or performance.
|
||||
@@ -84,91 +84,3 @@ Identification is not execution. `xenora shaders coverage` reports forms
|
||||
discovered in metadata against forms the semantic decoder accepts
|
||||
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
|
||||
per form remains in `docs/status.toml`.
|
||||
|
||||
## 64 KiB swizzle (`SW_64KB_S`) — public sources (#505)
|
||||
|
||||
`xg_xs.dll` implements `SW_64KB_S` tile addressing for `TEXTURE2D`, one array
|
||||
slice and one mip, over the element sizes the RB+ tables specify: 32-bpp RGBA8
|
||||
(4-byte elements) and the BC family — BC1/BC4 with 8-byte blocks and
|
||||
BC2/3/5/6H/7 with 16-byte blocks, where one "texel" element is a 4x4 block and
|
||||
`elemLog2 = log2(block_bytes)`. At 32 bpp the two public sources below agree
|
||||
bit-for-bit, which is why this is the mode implemented first; the 8- and 16-byte
|
||||
rows come from AddrLib alone.
|
||||
|
||||
**Microsoft, `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE`** (public, no NDA):
|
||||
<https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout>.
|
||||
The page gives the 32-bpp masks `xBytesMask = 0xAA8F` and `yMask = 0x5570`,
|
||||
combined with `_pdep_u32`. It states that tail-mip packing is **adapter-specific**,
|
||||
which is why only the single-mip case is implemented. It has no `D` or `R` variant.
|
||||
|
||||
**AMD AddrLib (MIT)** — the authoritative public implementation, in both
|
||||
[Mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib)
|
||||
and [AMD PAL](https://github.com/GPUOpen-Drivers/pal/tree/dev/src/core/imported/addrlib)
|
||||
(`SPDX-License-Identifier: MIT`, AMD copyright; PAL `LICENSE.txt` is MIT):
|
||||
|
||||
- `src/amd/addrlib/inc/addrtypes.h` — `AddrSwizzleMode`: `ADDR_SW_64KB_S` = 9,
|
||||
`_D` = 10, `_R` = 11 (Reserved on GFX10).
|
||||
- `src/amd/addrlib/src/gfx10/gfx10SwizzlePattern.h` — `GFX10_SW_64K_S_PATINFO`
|
||||
and `GFX10_SW_64K_S_RBPLUS_PATINFO`, plus the `GFX10_SW_PATTERN_NIBBLE01/2/3/4`
|
||||
tables. The RB+ variant is used because `gfx1030` is Navi2x.
|
||||
- `src/amd/addrlib/src/gfx10/gfx10addrlib.h` — `GetSwizzlePatternFromPatternInfo`,
|
||||
`IsInMipTail`.
|
||||
- `src/amd/addrlib/src/gfx10/gfx10addrlib.cpp` — `GetSwizzlePatternInfo`,
|
||||
`HwlComputeSurfaceAddrFromCoordTiled`, `ComputeSurfaceAddrFromCoordMacroTiled`.
|
||||
- `src/amd/addrlib/src/core/addrlib2.cpp` — `ComputeThinBlockDimension`,
|
||||
`Block256_2d`.
|
||||
|
||||
There is **no** standalone GPUOpen `addrlib` repository (404). The public
|
||||
[RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf)
|
||||
only names a 5-bit "SW mode" field in the T# descriptor (bits 120:116) and does
|
||||
not define the patterns.
|
||||
|
||||
### S versus D versus R
|
||||
|
||||
- **S and D are not interchangeable.** At 32 bpp RB+, D uses nibble01 index 39
|
||||
(`[0,0,X0,X1,Y0,Y1,X2,Y2]`) while S uses index 2
|
||||
(`[0,0,X0,X1,Y0,Y1,Y2,X2]`) — address bits 6 and 7 swapped.
|
||||
- **`SW_64KB_R` has no public GFX10 form.** Mesa's `SwizzleModeTable` marks
|
||||
`ADDR_SW_64KB_R` (enum 11) as Reserved; the render-target mode is
|
||||
`ADDR_SW_64KB_R_X`, whose pipe/packer XOR depends on the console
|
||||
`GB_ADDR_CONFIG`, which is not public.
|
||||
|
||||
### Xbox `XG` tile modes are NDA
|
||||
|
||||
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
|
||||
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
|
||||
not public, so BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are **local** constants,
|
||||
not the console's.
|
||||
|
||||
### Element sizes and the derived masks
|
||||
|
||||
For a 64 KiB tile the intra-tile byte offset of element (x, y) is
|
||||
`pdep(x, x_mask) | pdep(y, y_mask)`, where x and y are **block** indices (one
|
||||
4x4 block for BC, one texel for 32 bpp). The masks were expanded by hand from
|
||||
`GFX10_SW_PATTERN_NIBBLE01/2/3` at the patinfo indices
|
||||
`GFX10_SW_64K_S_RBPLUS_PATINFO` selects for each `elemLog2`:
|
||||
|
||||
| block bytes | formats | `elemLog2` | x mask | y mask | tile (blocks) |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 4 | R8G8B8A8_* | 2 | `0xAA8C` | `0x5570` | 128 x 128 |
|
||||
| 8 | BC1, BC4 | 3 | `0xAAC8` | `0x5530` | 128 x 64 |
|
||||
| 16 | BC2, BC3, BC5, BC6H, BC7 | 4 | `0xAAC0` | `0x5530` | 64 x 64 |
|
||||
|
||||
At 32 bpp the x mask `0xAA8C` is Microsoft's public `xBytesMask` `0xAA8F` with
|
||||
the two intra-texel byte bits cleared (`0xAA8F & ~0x3`), and the y mask matches
|
||||
`0x5570` exactly. The 8- and 16-byte rows have no D3D12 page to cross-check
|
||||
against; they are AddrLib-only, which is stated in the PR risks. All three rows
|
||||
were checked to be bijections over their 64 KiB tile (16384 / 8192 / 4096
|
||||
distinct offsets, each block-aligned and inside the tile).
|
||||
|
||||
### Verification
|
||||
|
||||
The three masks above were expanded and their bijectivity checked against an
|
||||
independently written `pdep` reference, outside the shim. `test_xg_xs.exe`
|
||||
re-derives its expected offsets from those masks (and, at 32 bpp, from the
|
||||
D3D12 page) rather than reading them back from the shim: one test per block
|
||||
size, covering intra-block offsets (the 16 texels of a BC block share one byte
|
||||
offset), independently derived absolute offsets, and an offset -> texel -> offset
|
||||
round trip. It keeps asserting `E_NOTIMPL` for `SW_64KB_D`, `SW_64KB_R`, 1D/3D,
|
||||
MSAA, and every multi-mip or multi-slice case. Synthetic evidence only; no
|
||||
Xbox-hardware claim.
|
||||
@@ -14,7 +14,6 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
|
||||
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
|
||||
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
|
||||
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
|
||||
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
|
||||
|
||||
## Built and run for M1-D2 (#417)
|
||||
|
||||
@@ -26,22 +25,6 @@ Unlike the table above, these entries were cloned at the stated pin, built and r
|
||||
| directx-native | [osy/directx-native](https://github.com/osy/directx-native) | `7258be1c56cdbf1e55c56b1bc4a866169c8ca0da` (pinned by d3dmetal-native's `subprojects/directx-native.wrap`) | Apache-2.0: repository `LICENSE`, plus `SPDX-License-Identifier: Apache-2.0` in 22 of its 25 files | Build dependency of d3dmetal-native, statically linked into the dylib; nothing is copied into BetterXen | Supplies the shared-resource and embedder headers that `d3dmetal_native.h` includes. Apache-2.0 is compatible with GPL-3.0, not GPL-2.0. |
|
||||
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The package ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
|
||||
|
||||
## Interface facts for XGameSave and XPackage (#468, #492)
|
||||
|
||||
Facts only, no text or code copied. **Pending maintainer provenance acceptance** under AGENTS.md §4.
|
||||
|
||||
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| xgameruntime-docs | [xodus-gaming/xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) | `7090008692569aa6081e30dfdd9de58237741e24` | Repository `LICENSE` is the unmodified GNU GPL version 3 text. No project copyright holder is named, nothing states "only" or "or later", and the documentation files checked (`README.md`, `COM/XErrorImpl/IXErrorImpl.md`, `COM/XPackageImpl/IXPackageImpl.md`, `IXPackageImpl2.md`, `XErrorReport.md`) carry no licence or copyright header. | Source of the interface facts behind the public `QueryApiImpl` entries in `shims/xgameruntime/com_dispatch.cpp`: class and interface ids, interface inheritance, and vtable slot order for `IXGameSaveImpl`–`IXGameSaveImpl3` and `IXPackageImpl`–`IXPackageImpl4`. | Its README says the information "was found using black box reverse engineering" following Wine's clean-room guidelines. It states no use of Microsoft binaries, leaked material or the GDK EULA either way, and the COM notes say the listing is incomplete. It lists `IXErrorImpl` slot 3 only as unknown. BetterXen's answer for that slot (return `false`) instead follows an interop observation in the #492 review (2026-11-26), not this repository. Function signatures come from Microsoft Learn. |
|
||||
|
||||
## Vendored for the public PC DirectStorage interfaces (#483)
|
||||
|
||||
Checked on 2026-11-26 by reading the package files, not just its metadata. Not legal advice. Details and file hashes: [`shims/xcrdapi/dstorage/README.md`](../../shims/xcrdapi/dstorage/README.md).
|
||||
|
||||
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| DirectStorage SDK headers | NuGet [`Microsoft.Direct3D.DirectStorage`](https://www.nuget.org/packages/Microsoft.Direct3D.DirectStorage/1.4.0) | `1.4.0`, package SHA-256 `0838e7f71b14acfbd1ac7ecc5e943f6c95e4f4e679e8a67f8ff6e7c102414321` | `native/include/dstorage.h` and `dstorageerr.h` each carry `Copyright (c) Microsoft Corporation` / `Licensed under the MIT license`; the package's `LICENSE-CODE.txt` is the MIT text. The package as a whole is under the proprietary *Microsoft DirectStorage SDK* terms, whose distributables are only `dstorage.dll` and `dstoragecore.dll`. | The two headers are vendored unmodified in `shims/xcrdapi/dstorage/` for the public `IDStorage*` interfaces in `XCRDAPI.dll` and `test_xcrdapi`. No DLL or other package file is used or redistributed. | The headers are not in the MIT `microsoft/DirectStorage` repository; they ship only in this package. Microsoft Learn documents the same API but gives neither IIDs nor vtable order. The Xbox `IDStorage*X` interfaces (`dstorage_xs.h`) ship only in the GDK with Xbox Extensions, "only available to licensed partners", so they are excluded. |
|
||||
|
||||
## Additional candidates found by search (not reviewed)
|
||||
|
||||
Found by GitHub search on 2026-11-25. Only repository metadata was read; none was evaluated, installed or run, and none is a recommendation. Licenses are what GitHub reported.
|
||||
|
||||
+6
-23
@@ -9,8 +9,7 @@ BetterXen builds a modular **Xbox Series (`Scarlett`) compatibility layer for Ap
|
||||
```text
|
||||
BetterXen (in-tree):
|
||||
launcher/ (ARM64 CLI, probe, telemetry) + abi/ (frozen contracts)
|
||||
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs
|
||||
+ the Rust-built bx_shader_bridge.dll)
|
||||
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs)
|
||||
shader-transpiler/ (DXBC / DXIL / ACCC / FSPX classifier & RDNA 2 pipeline)
|
||||
|
|
||||
External Foundation (user-installed, never bundled):
|
||||
@@ -25,13 +24,11 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
---
|
||||
|
||||
## Research Inputs
|
||||
## Completed Research Inputs (Carried Forward)
|
||||
|
||||
- **Licensing & redistribution boundaries:** [docs/research/crossover-licensing.md](research/crossover-licensing.md) and [docs/licenses.md](licenses.md) (#354). CrossOver, D3DMetal, and Rosetta 2 stay strictly external and unbundled.
|
||||
- **Primary-source verification & upstream registry:** [docs/research/primary-source-verification-2026-11-25.md](research/primary-source-verification-2026-11-25.md), [docs/research/upstream-registry.md](research/upstream-registry.md), and [docs/research/component-reuse-matrix.md](research/component-reuse-matrix.md).
|
||||
- **Hybrid measurement protocol:** [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) (#353).
|
||||
- **Buffer ownership on CrossOver 26.3.0.39832 and D3DMetal 3.0 (#473).** On the tested M4 (24 GiB) and M5 (16 GiB), the two existing-memory heap imports returned `E_NOTIMPL`. A D3D12-owned persistent buffer mapping supported fence-separated CPU/GPU access and ordered virtual aliasing (BASE-2, BASE-4, A-8). The actual CPU address could miss 64 KiB alignment (A-6). Inside the timed small-copy window, no serialized copy cost as much as the explicit full copy to READBACK. The other workstream accepted 13 of 29 register entries within stated scopes, mostly through same-source reruns. #473 remains open. Physical page identity, hidden copies, workload memory savings and speedups remain open. [Report 001](https://github.com/MacosPorters/betterxen/blob/0aaa81ab81309d64432d97d3005284c8b13cd285/docs/research/publications/001-unified-memory/technical-findings.md) · [Evidence register](https://github.com/MacosPorters/betterxen/blob/f8810a48af384d13c594b9fba954200bfdb944f1/docs/research/d3dmetal-zero-copy/allocation-profiling/consolidation-draft/evidence-register.md) · [Review corrections](https://github.com/MacosPorters/betterxen/discussions/493)
|
||||
- **Target-workload shader corpus (static scan, 2026-11-28).** A read-only container scan of an authorized local test workload measured what its shipped components embed — structure only, no run, no extraction, and the workload is not redistributed. Its `XboxBvhBuilder` component carries **52 DXIL compute containers, all Shader Model 6.5, with valid LLVM bitcode**; its AMD FidelityFX upscaler component carries **29 ACCC-only containers** whose payloads start with `FSPX`, none with a `DXIL` chunk; its main executable carries **10 DXIL containers (nine pixel, one vertex, Shader Model 6.6) whose `DXIL` chunks hold four-byte `NOBC` payloads** — valid program headers, no executable bitcode. Its packaged shader archive exposes no plaintext `DXBC` signatures and remains unclassified. BetterXen's classifier accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers because their section tables do not match the clean-room `FSPX` layout (`FspxSectionOutOfBounds` at the time of the scan; that cause is `FspxLayoutMismatch` since #599, not re-measured). Runtime use is unmeasured: the recorded startup run stopped before pipeline creation and wrote no `shader_gate` records. [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
|
||||
---
|
||||
|
||||
@@ -39,28 +36,14 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
| Milestone | Objective | Exit Gate | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), integrate the shipped xmem-configured D3D12 placed heap (#464) into the first-frame fixture (#469), bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 16/16 PE32+ DLLs pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **In validation (PR #406)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime`, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, and combined synthetic integration boot fixture | All 13 Wave 1 conformance binaries pass under CrossOver + Rosetta 2; combined `integration_boot.exe` initializes every subsystem cleanly | **Next (Wave 1 ready)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, and `dxbc-accc` shader inspection to establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)** | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | Planned |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
|
||||
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
|
||||
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
|
||||
|
||||
### Startup diagnosis
|
||||
|
||||
The product goal is to reach a frame presented by the target software. Under the current [contribution rules](../CONTRIBUTING.md), project runs use original synthetic workloads. Start with `test_integration_boot.exe` for startup and `test_veh_unhandled.exe` as a crash-logging control. Use a focused synthetic reproducer once a failing contract is identified.
|
||||
|
||||
Before treating either startup warning as causal, add diagnostics that record the requested DirectStorage factory IID and returned HRESULT (#483) and distinguish null, unrecognized and supported BetterXen virtual-memory configurations (#464 follow-up). On a pinned launcher, shim set and backend, repeat the synthetic case before and after a fix. Record normal exit, crash or timeout, the last completed checkpoint, and the exception thread and module offset when available. Progress means reaching the next named checkpoint in the same reproducer. Startup diagnosis and the budget fix proceed alongside the M2 exit gates.
|
||||
|
||||
### M2 first-frame acceptance and parallel memory work
|
||||
|
||||
- **First frame (#465, #469).** The synthetic placement criterion uses BetterXen's `BXVM` block to configure the separate D3D12-owned WRITE_BACK heap shipped in #486. On the recorded overlay, #494 copied the backbuffer before the flip, counted one host `Present`, then compared 256 RGBA8 pixels through the D3D12 mapping after waiting. The xmem sentinel shows that the original page remained separate. Visibility through the original xmem address remains an open compatibility question for M3, informed by #473. Displayed-image verification is outside this fixture's measurements. Record a single `main` commit containing the integrated presentation and fixture changes, confirm that the fixture executable built, and have someone who authored neither the fixture nor the presentation bridge verify the D3DMetal run and pixel-mismatch control. The shader gate still requires a recorded D1/D2 selection. [Fixture and receipts](https://github.com/MacosPorters/betterxen/pull/494) · [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Shader format gate (#466, ADR 0008).** D1 remains the only branch with end-to-end execution evidence, and the static scan gives it measured inputs in the target workload: 52 DXIL SM 6.5 compute containers with LLVM bitcode. The same scan makes D2 a concrete compatibility candidate rather than a hypothesis: the workload's FidelityFX upscaler component embeds 29 ACCC-only containers. Select D2 work only when a required pipeline-creation path refuses an ACCC-only container at runtime — if that refusal precedes the first presented frame, treat it as a first-frame blocker; if it appears only with upscaling enabled, track it under M4 upscaling. Two Track D parser prerequisites precede any D2 trial: extend the clean-room `FSPX` section-table layout to accept the observed tables (a maintainer provenance decision, since no public format description exists), and stop the classifier from treating a `NOBC` header-only program as executable DXIL. The first `shader_gate` record the target workload writes names the shader path its first pipeline creation actually submits. [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Title budget (#550, #552).** Keep current allocation ownership and give xmem atomic admission authority through an ABI-first contract. The initial scope combines xmem usage with the existing charged `CreateHeap` path. Under a 512 MiB cap, an xmem allocation of 256 MiB followed by a 384 MiB heap was refused, while the reverse admitted 640 MiB. Test both orders, concurrent admission and rollback. Charge a backing allocation once across aliases. Accounting for `CreateHeap1`, committed and reserved resources, and internal buffers such as XCRDAPI staging remains an open scope decision. Placement and wrapper lifetime have separate checks (#554, #572). [Merged-base reproduction](https://github.com/MacosPorters/betterxen/pull/486#issuecomment-7209751182)
|
||||
- **M3 resource handling.** Keep explicit paths for fixed addresses, existing contents, pre-device allocations, sections/scatter and opaque textures. The draft eligibility analysis found no reliable end-to-end classifier. Resolve the `XMemVirtualAlloc` argument-count question (#518) before using graphics flags as evidence. A mapped-buffer trial is optional and opt-in, with the existing path as fallback. Require a known consumer before returning a pointer, verify its alignment and lifetime, and confirm completion on every participating queue before reusing memory for work BetterXen submits. #483 retains its DirectStorage interface scope. [Draft eligibility analysis](https://github.com/MacosPorters/betterxen/blob/7e0b515131150fec6b5117c9498b6c0faf0ca382/docs/architecture/proposals/001-unified-memory/appendix/eligibility.md)
|
||||
- **M6 optimization.** Compare the existing path with a candidate allocator or bounded pool on the same 16 GB host and backend. Check correct output for both paths across repeated matched workloads. Include cold setup, transfers, fragmentation, pending retirements, post-release footprint and whole-frame time. Require a repeatable workload benefit before choosing a default.
|
||||
|
||||
---
|
||||
|
||||
## How Progress Is Reported
|
||||
|
||||
@@ -7,6 +7,11 @@ It adds no runner and reports no new Windows or GPU execution results.
|
||||
|
||||
## Implementation checkpoint
|
||||
|
||||
Current runner: the same commands are `bx-cli` subcommands (`receipt`, `run`, `bench`,
|
||||
`stop`, `frames`) and the workloads are under `tests/conformance/`; see
|
||||
[maintainer testing](../maintainer-testing.md). The text below records the protocol as
|
||||
first written against the earlier candidate and is kept for its provenance.
|
||||
|
||||
The commands below refer to [PR #384](https://github.com/MacosPorters/betterxen/pull/384),
|
||||
reviewed at commit `566272082a74d8b45fcec37edd00f4f6703df3ab` on 2026-11-25.
|
||||
Its `betterxen-hybrid` command, build script and Windows workloads are not on
|
||||
|
||||
@@ -13,8 +13,7 @@ path = "src/main.rs"
|
||||
bx-probe = { path = "../bx-probe" }
|
||||
bx-telemetry = { path = "../bx-telemetry" }
|
||||
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
|
||||
# POSIX signals and process groups for `run` supervision.
|
||||
libc = "=0.2.191"
|
||||
bx-runtime = { path = "../bx-runtime" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,548 +0,0 @@
|
||||
//! Xbox title drive letters, linked in the prefix's `dosdevices` before launch.
|
||||
//!
|
||||
//! The project-authorized target title we traced reads its package from `G:` and writes
|
||||
//! temporary files such as crash logs to `T:`. That is an observation of one title at startup;
|
||||
//! that `G:` is the package root and `T:` temporary storage for Xbox titles in general is an
|
||||
//! inference. A Wine prefix has neither drive, so that title's first `G:\...` open fails with
|
||||
//! `STATUS_OBJECT_PATH_NOT_FOUND`. `bx-cli run` links `g:` to the executable's directory and
|
||||
//! `t:` to `drive_c/bx_temp`.
|
||||
//!
|
||||
//! As with system32 staging (#474), a drive letter the prefix already uses is not ours. A
|
||||
//! `.bx-drives` manifest in `dosdevices` records each link this tool made, and only a link that
|
||||
//! is listed and still points where it was pointed is replaced. Any other mapping to a
|
||||
//! different target is reported and left unchanged.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::ffi::{OsStrExt, OsStringExt};
|
||||
use std::os::unix::fs::{OpenOptionsExt, symlink};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MANIFEST: &str = ".bx-drives";
|
||||
const LOCK_FILE: &str = ".bx-drive-mapping.lock";
|
||||
|
||||
/// The prefix-relative target of `t:`, in the form Wine itself uses for `c:`.
|
||||
pub const TEMP_TARGET: &str = "../drive_c/bx_temp";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DriveMappingLock {
|
||||
_file: fs::File,
|
||||
}
|
||||
|
||||
/// Holds the prefix's drive mappings stable until the returned lock is dropped.
|
||||
pub fn lock_drive_mappings(prefix: &Path) -> Result<DriveMappingLock, String> {
|
||||
fs::create_dir_all(prefix).map_err(|e| {
|
||||
format!(
|
||||
"cannot prepare prefix {} for drive lock: {e}",
|
||||
prefix.display()
|
||||
)
|
||||
})?;
|
||||
let prefix = fs::canonicalize(prefix).map_err(|e| {
|
||||
format!(
|
||||
"cannot resolve prefix {} for drive lock: {e}",
|
||||
prefix.display()
|
||||
)
|
||||
})?;
|
||||
let path = prefix.join(LOCK_FILE);
|
||||
let file = fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open drive lock {}: {e}", path.display()))?;
|
||||
|
||||
loop {
|
||||
// The open file descriptor stays alive in DriveMappingLock for the full launch.
|
||||
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
|
||||
if result == 0 {
|
||||
return Ok(DriveMappingLock { _file: file });
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.kind() == io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
if error.kind() == io::ErrorKind::WouldBlock {
|
||||
return Err(format!(
|
||||
"another bx-cli run is active for prefix {}; refusing to launch with shared Xbox drive mappings",
|
||||
prefix.display()
|
||||
));
|
||||
}
|
||||
return Err(format!("cannot lock {}: {error}", path.display()));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Mapping {
|
||||
Created(char, PathBuf),
|
||||
/// A link this tool made earlier, pointed at a new target.
|
||||
Retargeted(char, PathBuf),
|
||||
Unchanged(char, PathBuf),
|
||||
/// A mapping this tool did not make, to a different target; left as it is.
|
||||
Foreign {
|
||||
letter: char,
|
||||
existing: String,
|
||||
wanted: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
impl Mapping {
|
||||
pub fn describe(&self) -> String {
|
||||
match self {
|
||||
Mapping::Created(l, t) => {
|
||||
format!("mapped {}: to {}", l.to_ascii_uppercase(), t.display())
|
||||
}
|
||||
Mapping::Retargeted(l, t) => {
|
||||
format!(
|
||||
"remapped own {}: to {}",
|
||||
l.to_ascii_uppercase(),
|
||||
t.display()
|
||||
)
|
||||
}
|
||||
Mapping::Unchanged(l, t) => {
|
||||
format!(
|
||||
"{}: already maps to {}",
|
||||
l.to_ascii_uppercase(),
|
||||
t.display()
|
||||
)
|
||||
}
|
||||
Mapping::Foreign {
|
||||
letter,
|
||||
existing,
|
||||
wanted,
|
||||
} => format!(
|
||||
"warning: {}: already maps to {existing}, not {}; left unchanged, so the guest \
|
||||
may not find its files there",
|
||||
letter.to_ascii_uppercase(),
|
||||
wanted.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_manifest(dosdevices: &Path) -> Result<BTreeMap<char, PathBuf>, String> {
|
||||
let path = dosdevices.join(MANIFEST);
|
||||
let text = match fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
|
||||
};
|
||||
let mut owned = BTreeMap::new();
|
||||
for line in text.lines().filter(|l| !l.is_empty()) {
|
||||
let mut chars = line.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(letter), Some('\t')) if letter.is_ascii_lowercase() => {
|
||||
let encoded = chars.as_str();
|
||||
let target = match encoded.strip_prefix('@') {
|
||||
Some(hex) => decode_path(hex)
|
||||
.ok_or_else(|| format!("malformed path in {}: {line:?}", path.display()))?,
|
||||
None => PathBuf::from(encoded),
|
||||
};
|
||||
owned.insert(letter, target);
|
||||
}
|
||||
_ => return Err(format!("malformed line in {}: {line:?}", path.display())),
|
||||
}
|
||||
}
|
||||
Ok(owned)
|
||||
}
|
||||
|
||||
fn write_manifest(dosdevices: &Path, owned: &BTreeMap<char, PathBuf>) -> Result<(), String> {
|
||||
let path = dosdevices.join(MANIFEST);
|
||||
let mut text = String::new();
|
||||
for (letter, target) in owned {
|
||||
text.push_str(&format!("{letter}\t@{}\n", encode_path(target)));
|
||||
}
|
||||
// Written to a temporary file and renamed over the manifest, like `relink`, so an
|
||||
// interrupted write can never leave a truncated manifest that later runs refuse to parse.
|
||||
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp)
|
||||
.map_err(|e| format!("cannot create {}: {e}", tmp.display()))?;
|
||||
let written = file.write_all(text.as_bytes()).and_then(|()| {
|
||||
drop(file);
|
||||
fs::rename(&tmp, &path)
|
||||
});
|
||||
if written.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
written.map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
fn encode_path(path: &Path) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let bytes = path.as_os_str().as_bytes();
|
||||
let mut encoded = String::with_capacity(bytes.len() * 2);
|
||||
for &byte in bytes {
|
||||
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
|
||||
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn decode_path(hex: &str) -> Option<PathBuf> {
|
||||
fn nibble(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = hex.as_bytes();
|
||||
if bytes.len() % 2 != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut decoded = Vec::with_capacity(bytes.len() / 2);
|
||||
for pair in bytes.chunks_exact(2) {
|
||||
decoded.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(decoded)))
|
||||
}
|
||||
|
||||
/// Points `link` at `target`, replacing what is there through a rename so the link never
|
||||
/// disappears in between.
|
||||
fn relink(dosdevices: &Path, link: &Path, target: &Path) -> io::Result<()> {
|
||||
let tmp = dosdevices.join(format!(".bx-drive-tmp.{}", std::process::id()));
|
||||
let _ = fs::remove_file(&tmp);
|
||||
symlink(target, &tmp)?;
|
||||
let result = fs::rename(&tmp, link);
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Links `g:` to `package_dir` and `t:` to [`TEMP_TARGET`] in `prefix`'s `dosdevices`.
|
||||
pub fn map_xbox_drives(prefix: &Path, package_dir: &Path) -> Result<Vec<Mapping>, String> {
|
||||
let dosdevices = prefix.join("dosdevices");
|
||||
if !dosdevices.is_dir() {
|
||||
return Err(format!(
|
||||
"{} does not exist (start the prefix once so Wine creates it)",
|
||||
dosdevices.display()
|
||||
));
|
||||
}
|
||||
let temp_dir = prefix.join("drive_c/bx_temp");
|
||||
fs::create_dir_all(&temp_dir)
|
||||
.map_err(|e| format!("cannot create {}: {e}", temp_dir.display()))?;
|
||||
|
||||
let mut owned = read_manifest(&dosdevices)?;
|
||||
let mut mappings = Vec::new();
|
||||
for (letter, target) in [
|
||||
('g', package_dir.to_path_buf()),
|
||||
('t', PathBuf::from(TEMP_TARGET)),
|
||||
] {
|
||||
let link = dosdevices.join(format!("{letter}:"));
|
||||
let current = match fs::symlink_metadata(&link) {
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(format!("cannot inspect {}: {e}", link.display())),
|
||||
Ok(meta) if meta.file_type().is_symlink() => Some(
|
||||
fs::read_link(&link).map_err(|e| format!("cannot read {}: {e}", link.display()))?,
|
||||
),
|
||||
Ok(_) => {
|
||||
mappings.push(Mapping::Foreign {
|
||||
letter,
|
||||
existing: format!("a non-link entry {}", link.display()),
|
||||
wanted: target,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mapping = match current {
|
||||
None => {
|
||||
owned.insert(letter, target.clone());
|
||||
write_manifest(&dosdevices, &owned)?;
|
||||
relink(&dosdevices, &link, &target)
|
||||
.map_err(|e| format!("cannot create {}: {e}", link.display()))?;
|
||||
Mapping::Created(letter, target.clone())
|
||||
}
|
||||
Some(current) if current == target => Mapping::Unchanged(letter, target.clone()),
|
||||
Some(current) if owned.get(&letter) == Some(¤t) => {
|
||||
owned.insert(letter, target.clone());
|
||||
write_manifest(&dosdevices, &owned)?;
|
||||
if let Err(error) = relink(&dosdevices, &link, &target) {
|
||||
owned.insert(letter, current);
|
||||
let restore = write_manifest(&dosdevices, &owned);
|
||||
let detail = restore
|
||||
.err()
|
||||
.map(|e| format!("; also could not restore the drive manifest: {e}"))
|
||||
.unwrap_or_default();
|
||||
return Err(format!(
|
||||
"cannot replace {}: {error}{detail}",
|
||||
link.display()
|
||||
));
|
||||
}
|
||||
Mapping::Retargeted(letter, target.clone())
|
||||
}
|
||||
Some(current) => {
|
||||
mappings.push(Mapping::Foreign {
|
||||
letter,
|
||||
existing: current.display().to_string(),
|
||||
wanted: target,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
mappings.push(mapping);
|
||||
}
|
||||
Ok(mappings)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"bx-drives-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&p);
|
||||
fs::create_dir_all(p.join("prefix/dosdevices")).unwrap();
|
||||
fs::create_dir_all(p.join("game")).unwrap();
|
||||
TempDir(p)
|
||||
}
|
||||
fn prefix(&self) -> PathBuf {
|
||||
self.0.join("prefix")
|
||||
}
|
||||
fn game(&self) -> PathBuf {
|
||||
self.0.join("game")
|
||||
}
|
||||
fn link(&self, letter: char) -> PathBuf {
|
||||
self.0.join(format!("prefix/dosdevices/{letter}:"))
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_drives_are_created_and_resolve() {
|
||||
let t = TempDir::new("create");
|
||||
fs::write(t.game().join("package.bin"), b"pkg").unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(
|
||||
mappings[..],
|
||||
[Mapping::Created('g', _), Mapping::Created('t', _)]
|
||||
));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
|
||||
assert_eq!(
|
||||
fs::read_link(t.link('t')).unwrap(),
|
||||
PathBuf::from(TEMP_TARGET)
|
||||
);
|
||||
// Both links resolve the way Wine resolves them, from inside dosdevices.
|
||||
assert_eq!(fs::read(t.link('g').join("package.bin")).unwrap(), b"pkg");
|
||||
assert!(t.link('t').is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_run_changes_nothing() {
|
||||
let t = TempDir::new("rerun");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(
|
||||
mappings[..],
|
||||
[Mapping::Unchanged('g', _), Mapping::Unchanged('t', _)]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_link_follows_a_new_package_directory() {
|
||||
let t = TempDir::new("retarget");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(mappings[0], Mapping::Retargeted('g', _)));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_mapping_is_reported_and_kept() {
|
||||
let t = TempDir::new("foreign");
|
||||
let elsewhere = t.0.join("elsewhere");
|
||||
symlink(&elsewhere, t.link('g')).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
assert!(mappings[0].describe().starts_with("warning: G:"));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
|
||||
// A link this tool did not record is never treated as its own on a later run.
|
||||
let again = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_link_changed_by_someone_else_becomes_foreign() {
|
||||
let t = TempDir::new("changed");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
fs::remove_file(t.link('g')).unwrap();
|
||||
let elsewhere = t.0.join("elsewhere");
|
||||
symlink(&elsewhere, t.link('g')).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_link_entry_is_never_touched() {
|
||||
let t = TempDir::new("nonlink");
|
||||
fs::create_dir_all(t.link('t')).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&mappings[1], Mapping::Foreign { letter: 't', .. }));
|
||||
assert!(t.link('t').is_dir() && !fs::symlink_metadata(t.link('t')).unwrap().is_symlink());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_without_dosdevices_is_an_error() {
|
||||
let t = TempDir::new("nodos");
|
||||
fs::remove_dir_all(t.prefix().join("dosdevices")).unwrap();
|
||||
let e = map_xbox_drives(&t.prefix(), &t.game()).unwrap_err();
|
||||
assert!(e.contains("dosdevices"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_manifest_is_an_error_not_an_ownership_claim() {
|
||||
let t = TempDir::new("badmanifest");
|
||||
fs::write(t.prefix().join("dosdevices").join(MANIFEST), "g /x\n").unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_manifest_write_leaves_no_unrecorded_link() {
|
||||
let t = TempDir::new("orphan");
|
||||
// A directory where the manifest's temporary file goes makes the write fail.
|
||||
let tmp = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
fs::create_dir(&tmp).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
|
||||
assert!(
|
||||
fs::symlink_metadata(t.link('g')).is_err(),
|
||||
"g: must not be created before ownership is recorded"
|
||||
);
|
||||
|
||||
fs::remove_dir(&tmp).unwrap();
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interrupted_manifest_write_keeps_the_previous_manifest() {
|
||||
let t = TempDir::new("atomic");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let manifest = t.prefix().join("dosdevices").join(MANIFEST);
|
||||
let before = fs::read(&manifest).unwrap();
|
||||
// Fail the next write after the new contents would have been produced: the old
|
||||
// manifest must survive whole, never truncated or half written.
|
||||
let tmp = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
fs::create_dir(&tmp).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
|
||||
assert_eq!(
|
||||
fs::read(&manifest).unwrap(),
|
||||
before,
|
||||
"previous manifest kept intact"
|
||||
);
|
||||
fs::remove_dir(&tmp).unwrap();
|
||||
// The intact manifest still proves ownership, so the retry re-points g:.
|
||||
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
|
||||
assert!(
|
||||
fs::read_dir(t.prefix().join("dosdevices"))
|
||||
.unwrap()
|
||||
.all(|e| !e.unwrap().file_name().to_string_lossy().contains(".tmp."))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_temp_does_not_follow_an_existing_symlink() {
|
||||
let t = TempDir::new("manifest-symlink");
|
||||
let dosdevices = t.prefix().join("dosdevices");
|
||||
let target = t.0.join("outside-manifest");
|
||||
fs::write(&target, b"unchanged").unwrap();
|
||||
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
symlink(&target, &tmp).unwrap();
|
||||
|
||||
assert!(write_manifest(&dosdevices, &BTreeMap::new()).is_err());
|
||||
assert_eq!(fs::read(&target).unwrap(), b"unchanged");
|
||||
assert_eq!(fs::read_link(&tmp).unwrap(), target);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_retarget_restores_the_previous_manifest_and_link() {
|
||||
let t = TempDir::new("retarget-failure");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
|
||||
let temp_link = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!(".bx-drive-tmp.{}", std::process::id()));
|
||||
fs::create_dir(&temp_link).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
t.game()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_lock_rejects_another_launcher_until_released() {
|
||||
let t = TempDir::new("lock");
|
||||
let lock = lock_drive_mappings(&t.prefix()).unwrap();
|
||||
let error = lock_drive_mappings(&t.prefix()).unwrap_err();
|
||||
assert!(error.contains("another bx-cli run"), "{error}");
|
||||
|
||||
drop(lock);
|
||||
assert!(lock_drive_mappings(&t.prefix()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_utf8_target_round_trips_through_the_manifest() {
|
||||
let t = TempDir::new("non-utf8");
|
||||
let mut game_bytes = t.0.as_os_str().as_bytes().to_vec();
|
||||
game_bytes.extend_from_slice(b"/game-\xff");
|
||||
let game = PathBuf::from(std::ffi::OsString::from_vec(game_bytes));
|
||||
let owned = BTreeMap::from([('g', game.clone())]);
|
||||
write_manifest(&t.prefix().join("dosdevices"), &owned).unwrap();
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
game
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_plain_text_target_still_reads() {
|
||||
let t = TempDir::new("legacy-manifest");
|
||||
let legacy_target = t.0.join("old-game");
|
||||
fs::write(
|
||||
t.prefix().join("dosdevices").join(MANIFEST),
|
||||
format!("g\t{}\n", legacy_target.display()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
legacy_target
|
||||
);
|
||||
}
|
||||
}
|
||||
+86
-1723
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,492 +0,0 @@
|
||||
//! Supervision for `bx-cli run` (#408): the launcher gets its own process group, and a timeout
|
||||
//! or signal stops that group and then the environment's `wineserver`.
|
||||
//!
|
||||
//! The `wineserver` is stopped only after a timeout or signal, never after a normal exit,
|
||||
//! because it ends every program in that bottle or prefix, not only this run's.
|
||||
|
||||
use std::io::IsTerminal;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const POLL: Duration = Duration::from_millis(50);
|
||||
/// How long the launcher group has to exit after SIGTERM before SIGKILL.
|
||||
const GRACE: Duration = Duration::from_secs(5);
|
||||
const SERVER_WAIT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// Signals that stop the run: the guest group is terminated and the environment cleaned up.
|
||||
/// SIGQUIT (Ctrl-\) is included so it cannot kill `bx-cli` and leave the guest running (#461).
|
||||
const STOP_SIGNALS: [libc::c_int; 4] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT];
|
||||
|
||||
static SIGNAL: AtomicI32 = AtomicI32::new(0);
|
||||
static SUSPEND: AtomicBool = AtomicBool::new(false);
|
||||
/// Total time this process has spent suspended inside [`supervise`], in nanoseconds.
|
||||
static SUSPENDED_NANOS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
extern "C" fn note_signal(signal: libc::c_int) {
|
||||
SIGNAL.store(signal, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
extern "C" fn note_suspend(_signal: libc::c_int) {
|
||||
SUSPEND.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Installs `handler` for `signal` unless the disposition this process inherited is `SIG_IGN`.
|
||||
/// Returns whether the handler was installed.
|
||||
///
|
||||
/// A signal the caller chose to ignore (`nohup`, or a `&` job of a non-interactive shell) stays
|
||||
/// ignored, so it cannot stop the run or the bottle (#461).
|
||||
fn install_unless_ignored(signal: libc::c_int, handler: extern "C" fn(libc::c_int)) -> bool {
|
||||
// SAFETY: `current` is a valid, writable sigaction; a null new action only queries. The
|
||||
// handlers passed here only store to an atomic, which is async-signal-safe.
|
||||
unsafe {
|
||||
let mut current: libc::sigaction = std::mem::zeroed();
|
||||
if libc::sigaction(signal, std::ptr::null(), &mut current) == 0
|
||||
&& current.sa_sigaction == libc::SIG_IGN
|
||||
{
|
||||
return false;
|
||||
}
|
||||
libc::signal(signal, handler as libc::sighandler_t) != libc::SIG_ERR
|
||||
}
|
||||
}
|
||||
|
||||
/// Records SIGINT, SIGTERM, SIGHUP and SIGQUIT instead of dying, so the run can be cleaned up,
|
||||
/// and records SIGTSTP (Ctrl-Z) so the guest group can be suspended together with `bx-cli`.
|
||||
/// Signals that were inherited as ignored are left ignored.
|
||||
///
|
||||
/// SIGTSTP is only acted on inside [`supervise`]. A Ctrl-Z typed while nothing is being
|
||||
/// supervised (for example while shims are copied) has no visible effect until the next
|
||||
/// supervised phase starts, which is then suspended at once.
|
||||
pub fn install_signal_handlers() {
|
||||
for signal in STOP_SIGNALS {
|
||||
install_unless_ignored(signal, note_signal);
|
||||
}
|
||||
install_unless_ignored(libc::SIGTSTP, note_suspend);
|
||||
}
|
||||
|
||||
pub fn received_signal() -> i32 {
|
||||
SIGNAL.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Total time spent suspended (Ctrl-Z until continued) across every [`supervise`] call so far.
|
||||
///
|
||||
/// A caller that budgets one `--timeout` over several supervised phases subtracts this from its
|
||||
/// own wall-clock measurement, so a pause during an earlier phase is not charged to a later one.
|
||||
pub fn suspended_time() -> Duration {
|
||||
Duration::from_nanos(SUSPENDED_NANOS.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
/// True once per SIGTSTP received since the last call.
|
||||
fn take_suspend_request() -> bool {
|
||||
SUSPEND.swap(false, Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Stops this process the way the terminal's Ctrl-Z would; returns when it is continued.
|
||||
fn suspend_self(_guest: libc::pid_t) {
|
||||
// SAFETY: raise takes no pointers. SIGSTOP cannot be caught, so this stops the process.
|
||||
unsafe {
|
||||
libc::raise(libc::SIGSTOP);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum Stop {
|
||||
TimedOut,
|
||||
Signalled(i32),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Outcome {
|
||||
Exited(ExitStatus),
|
||||
Stopped(Stop),
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
/// The guest's own numeric exit code (so a conformance fixture's documented exit-77 skip
|
||||
/// stays distinguishable from a failure, #565), 124 for a timeout (as `timeout(1)`),
|
||||
/// 128 + N for a signal.
|
||||
pub fn exit_code(&self) -> u8 {
|
||||
match self {
|
||||
// Unix guest codes are already 0-255; a signalled guest has no code, which is a
|
||||
// failure. `code.max(1)` at the call sites still turns a failed cleanup into 1.
|
||||
Outcome::Exited(status) => status.code().map_or(1, |code| code.clamp(0, 255) as u8),
|
||||
Outcome::Stopped(Stop::TimedOut) => 124,
|
||||
Outcome::Stopped(Stop::Signalled(signal)) => 128u8.saturating_add(*signal as u8),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn signal_group(child: &Child, signal: libc::c_int) {
|
||||
// SAFETY: kill takes no pointers. The child leads its own group and has not been reaped,
|
||||
// so the group id cannot have been reused.
|
||||
unsafe {
|
||||
libc::kill(-(child.id() as libc::pid_t), signal);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<ExitStatus>> {
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Ok(None);
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `command` in a new process group until it exits, `timeout` passes, or `signal`
|
||||
/// returns non-zero. On a stop the whole group is terminated before this returns.
|
||||
///
|
||||
/// The guest is not in the terminal's foreground group, so Ctrl-Z reaches only `bx-cli`. It is
|
||||
/// passed on: the guest group gets SIGTSTP, `bx-cli` stops itself, and when `bx-cli` is continued
|
||||
/// the guest group gets SIGCONT. Time spent suspended does not count against `timeout`.
|
||||
pub fn supervise(
|
||||
command: Command,
|
||||
timeout: Option<Duration>,
|
||||
signal: impl Fn() -> i32,
|
||||
) -> std::io::Result<Outcome> {
|
||||
supervise_with(command, timeout, signal, take_suspend_request, suspend_self)
|
||||
}
|
||||
|
||||
/// [`supervise`] with the suspend request and the self-stop injected, so tests can exercise the
|
||||
/// job-control path without stopping the test process. `suspend` is called with the guest
|
||||
/// group's id after that group was sent SIGTSTP and returns when the launcher may continue.
|
||||
fn supervise_with(
|
||||
mut command: Command,
|
||||
timeout: Option<Duration>,
|
||||
signal: impl Fn() -> i32,
|
||||
suspend_requested: impl Fn() -> bool,
|
||||
mut suspend: impl FnMut(libc::pid_t),
|
||||
) -> std::io::Result<Outcome> {
|
||||
// A background process group is stopped by SIGTTIN if it reads the terminal, so a terminal
|
||||
// is replaced by end-of-file. Piped and redirected input is passed through.
|
||||
if std::io::stdin().is_terminal() {
|
||||
command.stdin(Stdio::null());
|
||||
}
|
||||
let mut child = command.process_group(0).spawn()?;
|
||||
let started = Instant::now();
|
||||
let mut suspended = Duration::ZERO;
|
||||
let stop = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Outcome::Exited(status));
|
||||
}
|
||||
let received = signal();
|
||||
if received != 0 {
|
||||
break Stop::Signalled(received);
|
||||
}
|
||||
if suspend_requested() {
|
||||
let paused = Instant::now();
|
||||
signal_group(&child, libc::SIGTSTP);
|
||||
suspend(child.id() as libc::pid_t);
|
||||
signal_group(&child, libc::SIGCONT);
|
||||
let pause = paused.elapsed();
|
||||
suspended += pause;
|
||||
SUSPENDED_NANOS.fetch_add(
|
||||
u64::try_from(pause.as_nanos()).unwrap_or(u64::MAX),
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if timeout.is_some_and(|limit| started.elapsed().saturating_sub(suspended) >= limit) {
|
||||
break Stop::TimedOut;
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
};
|
||||
signal_group(&child, libc::SIGTERM);
|
||||
// Wait without reaping first, so SIGKILL still reaches members that outlive the leader.
|
||||
std::thread::sleep(POLL);
|
||||
let deadline = Instant::now() + GRACE;
|
||||
while Instant::now() < deadline && group_leader_running(&child) {
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
signal_group(&child, libc::SIGKILL);
|
||||
wait_until(&mut child, Instant::now() + GRACE)?;
|
||||
Ok(Outcome::Stopped(stop))
|
||||
}
|
||||
|
||||
/// True while the leader has not exited; does not reap it.
|
||||
fn group_leader_running(child: &Child) -> bool {
|
||||
// SAFETY: `info` is a valid, writable siginfo_t and WNOWAIT leaves the child unreaped.
|
||||
unsafe {
|
||||
let mut info: libc::siginfo_t = std::mem::zeroed();
|
||||
libc::waitid(
|
||||
libc::P_PID,
|
||||
child.id() as libc::id_t,
|
||||
&mut info,
|
||||
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
|
||||
) == 0
|
||||
&& info.si_pid() == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// `wineserver -k` then `-w` for the environment at `prefix`.
|
||||
///
|
||||
/// `-k` exits 1 when no server is running (observed on CrossOver 26.3), so 1 is accepted
|
||||
/// there; `-w` must still succeed, which a surviving server prevents.
|
||||
///
|
||||
/// Each `wineserver` runs in its own process group with no terminal input, so a second Ctrl-C
|
||||
/// typed while cleanup is running reaches only `bx-cli` (which records it) and cannot kill the
|
||||
/// cleanup itself (#461).
|
||||
pub fn stop_server(
|
||||
wineserver: &Path,
|
||||
prefix: &Path,
|
||||
environment: &[(String, String)],
|
||||
) -> Result<(), String> {
|
||||
for (flag, idle_code) in [("-k", Some(1)), ("-w", None)] {
|
||||
let mut child = Command::new(wineserver)
|
||||
.arg(flag)
|
||||
.env_clear()
|
||||
.envs(environment.iter().map(|(k, v)| (k, v)))
|
||||
.env("WINEPREFIX", prefix)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.process_group(0)
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start wineserver {flag}: {e}"))?;
|
||||
match wait_until(&mut child, Instant::now() + SERVER_WAIT) {
|
||||
Ok(Some(status)) if status.success() => {}
|
||||
Ok(Some(status)) if idle_code.is_some() && status.code() == idle_code => {}
|
||||
other => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!("wineserver {flag} did not succeed: {other:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
fn shell(script: &str) -> Command {
|
||||
let mut command = Command::new("/bin/sh");
|
||||
command.args(["-c", script]);
|
||||
command
|
||||
}
|
||||
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("bx-cli-{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_exit_timeout_and_signal() {
|
||||
let ok = supervise(shell("exit 0"), None, || 0).unwrap();
|
||||
assert_eq!(ok.exit_code(), 0);
|
||||
let failed = supervise(shell("exit 7"), Some(Duration::from_secs(10)), || 0).unwrap();
|
||||
assert_eq!(failed.exit_code(), 7);
|
||||
// A conformance fixture's documented skip must stay distinguishable from a failure
|
||||
// through `bx-cli run` (#565); the old `!status.success()` collapsed it to 1.
|
||||
let skipped = supervise(shell("exit 77"), Some(Duration::from_secs(10)), || 0).unwrap();
|
||||
assert_eq!(skipped.exit_code(), 77);
|
||||
let slow = supervise(shell("sleep 30"), Some(Duration::from_millis(200)), || 0).unwrap();
|
||||
assert!(matches!(slow, Outcome::Stopped(Stop::TimedOut)));
|
||||
assert_eq!(slow.exit_code(), 124);
|
||||
let interrupted = supervise(shell("sleep 30"), None, || libc::SIGTERM).unwrap();
|
||||
assert_eq!(interrupted.exit_code(), 128 + libc::SIGTERM as u8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeout_stops_children_that_ignore_sigterm() {
|
||||
let dir = scratch("group");
|
||||
let pid_file = dir.join("child.pid");
|
||||
let script = format!(
|
||||
"(trap '' TERM; exec sleep 30) & echo $! > '{}'; wait",
|
||||
pid_file.display()
|
||||
);
|
||||
supervise(shell(&script), Some(Duration::from_millis(500)), || 0).unwrap();
|
||||
let pid: libc::pid_t = std::fs::read_to_string(&pid_file)
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap();
|
||||
let gone = (0..100).any(|_| {
|
||||
std::thread::sleep(POLL);
|
||||
// SAFETY: signal 0 only checks whether the process exists.
|
||||
unsafe { libc::kill(pid, 0) != 0 }
|
||||
});
|
||||
assert!(gone, "grandchild {pid} survived the timeout");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Signal dispositions and the recorded signal are process-wide: tests that touch them run
|
||||
/// one at a time and use signals no other test raises.
|
||||
static SIGNAL_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn set_disposition(signal: libc::c_int, action: libc::sighandler_t) {
|
||||
// SAFETY: SIG_DFL and SIG_IGN are valid dispositions for these signals.
|
||||
unsafe {
|
||||
libc::signal(signal, action);
|
||||
}
|
||||
}
|
||||
|
||||
fn disposition(signal: libc::c_int) -> libc::sighandler_t {
|
||||
// SAFETY: a null new action only queries; `current` is valid and writable.
|
||||
unsafe {
|
||||
let mut current: libc::sigaction = std::mem::zeroed();
|
||||
assert_eq!(libc::sigaction(signal, std::ptr::null(), &mut current), 0);
|
||||
current.sa_sigaction
|
||||
}
|
||||
}
|
||||
|
||||
fn raise(signal: libc::c_int) {
|
||||
// SAFETY: raise takes no pointers.
|
||||
unsafe {
|
||||
libc::raise(signal);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_ignored_signal_stays_ignored() {
|
||||
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// As under nohup: the signal arrives already ignored.
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_IGN);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
assert!(!install_unless_ignored(libc::SIGUSR2, note_signal));
|
||||
assert_eq!(disposition(libc::SIGUSR2), libc::SIG_IGN);
|
||||
raise(libc::SIGUSR2);
|
||||
assert_eq!(
|
||||
received_signal(),
|
||||
0,
|
||||
"an ignored signal must not stop the run"
|
||||
);
|
||||
|
||||
// Control: the same signal with the default disposition is recorded.
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
|
||||
assert!(install_unless_ignored(libc::SIGUSR2, note_signal));
|
||||
raise(libc::SIGUSR2);
|
||||
assert_eq!(received_signal(), libc::SIGUSR2);
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sigquit_is_recorded_and_stops_the_guest_group() {
|
||||
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
assert!(STOP_SIGNALS.contains(&libc::SIGQUIT));
|
||||
let before = disposition(libc::SIGQUIT);
|
||||
set_disposition(libc::SIGQUIT, libc::SIG_DFL);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
assert!(install_unless_ignored(libc::SIGQUIT, note_signal));
|
||||
// Without the handler this would kill the test process, as it killed bx-cli.
|
||||
raise(libc::SIGQUIT);
|
||||
assert_eq!(received_signal(), libc::SIGQUIT);
|
||||
set_disposition(libc::SIGQUIT, before);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
|
||||
let stopped = supervise(shell("sleep 30"), None, || libc::SIGQUIT).unwrap();
|
||||
assert!(matches!(
|
||||
stopped,
|
||||
Outcome::Stopped(Stop::Signalled(libc::SIGQUIT))
|
||||
));
|
||||
assert_eq!(stopped.exit_code(), 128 + libc::SIGQUIT as u8);
|
||||
}
|
||||
|
||||
/// True once `pid` is reported stopped; leaves the status in place.
|
||||
fn is_stopped(pid: libc::pid_t) -> bool {
|
||||
(0..100).any(|_| {
|
||||
// SAFETY: `info` is valid and writable; WNOWAIT leaves the child's state in place.
|
||||
let stopped = unsafe {
|
||||
let mut info: libc::siginfo_t = std::mem::zeroed();
|
||||
libc::waitid(
|
||||
libc::P_PID,
|
||||
pid as libc::id_t,
|
||||
&mut info,
|
||||
libc::WSTOPPED | libc::WNOHANG | libc::WNOWAIT,
|
||||
) == 0
|
||||
&& info.si_pid() == pid
|
||||
};
|
||||
if !stopped {
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
stopped
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspend_request_stops_and_resumes_the_guest_without_using_up_the_timeout() {
|
||||
let requested = std::cell::Cell::new(false);
|
||||
let guest_was_stopped = std::cell::Cell::new(false);
|
||||
let suspended_before = suspended_time();
|
||||
let outcome = supervise_with(
|
||||
shell("sleep 0.4; exit 0"),
|
||||
// Shorter than the suspension below: only running time may count.
|
||||
Some(Duration::from_millis(1500)),
|
||||
|| 0,
|
||||
|| !requested.replace(true),
|
||||
|guest| {
|
||||
guest_was_stopped.set(is_stopped(guest));
|
||||
std::thread::sleep(Duration::from_millis(2000));
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(guest_was_stopped.get(), "the guest group was not stopped");
|
||||
// The pause is also reported to callers that budget a timeout across several phases.
|
||||
let reported = suspended_time() - suspended_before;
|
||||
assert!(reported >= Duration::from_millis(2000), "{reported:?}");
|
||||
match outcome {
|
||||
Outcome::Exited(status) => assert!(status.success(), "{status}"),
|
||||
other => panic!("the resumed guest should have finished on its own: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_runs_outside_the_callers_process_group() {
|
||||
let dir = scratch("cleanup-group");
|
||||
let server = dir.join("wineserver");
|
||||
let seen = dir.join("pgid");
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!(
|
||||
"#!/bin/sh\n/usr/bin/perl -MPOSIX -e 'print getpgrp(), \"\\n\"' >> '{}'\n",
|
||||
seen.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
stop_server(&server, &dir, &[]).unwrap();
|
||||
// SAFETY: getpgrp takes no arguments and cannot fail.
|
||||
let ours = unsafe { libc::getpgrp() };
|
||||
let groups: Vec<libc::pid_t> = std::fs::read_to_string(&seen)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|line| line.trim().parse().unwrap())
|
||||
.collect();
|
||||
assert_eq!(groups.len(), 2, "-k and -w should both have run");
|
||||
for group in groups {
|
||||
// A terminal signal goes to the foreground group, which these are not part of.
|
||||
assert_ne!(group, ours, "cleanup shares the caller's process group");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_server_is_accepted_only_when_the_wait_succeeds() {
|
||||
let dir = scratch("server");
|
||||
for (name, kill, wait, ok) in [
|
||||
("running", 0, 0, true),
|
||||
("idle", 1, 0, true),
|
||||
("stuck", 1, 1, false),
|
||||
("broken", 2, 0, false),
|
||||
] {
|
||||
let server = dir.join(name);
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!("#!/bin/sh\n[ \"$1\" = -k ] && exit {kill}\nexit {wait}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(stop_server(&server, &dir, &[]).is_ok(), ok, "{name}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
//! Runs the built `bx-cli` binary to check what `main` prints and returns for the
|
||||
//! usage paths (#532). The unit tests cover `Dispatch::classify`; these cover the
|
||||
//! mapping from that classification to the real exit code and output stream.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn run(args: &[&str]) -> std::process::Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_bx-cli"))
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.output()
|
||||
.expect("bx-cli must start")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_prints_usage_on_stdout_and_succeeds() {
|
||||
for flag in ["--help", "-h", "help"] {
|
||||
let out = run(&[flag]);
|
||||
assert!(out.status.success(), "{flag}: {:?}", out.status);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
stdout.contains("bx-cli run --exe"),
|
||||
"{flag}: usage on stdout: {stdout}"
|
||||
);
|
||||
assert!(out.stderr.is_empty(), "{flag}: nothing on stderr");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_invocation_is_a_usage_error_on_stderr() {
|
||||
let out = run(&[]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "nothing on stdout");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_subcommand_is_a_usage_error_on_stderr() {
|
||||
let out = run(&["frobnicate"]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "nothing on stdout");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub fn classify_dll(dll_name: &str) -> ShimTrack {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PeSummary {
|
||||
pub image_base: u64,
|
||||
pub size_of_image: u32,
|
||||
@@ -128,21 +128,12 @@ struct Section {
|
||||
}
|
||||
|
||||
fn rva_to_off(sections: &[Section], rva: u32) -> Option<usize> {
|
||||
rva_to_off_bounded(sections, rva).map(|(off, _)| off)
|
||||
}
|
||||
|
||||
/// Map an RVA to a file offset and report how many raw bytes remain in that
|
||||
/// section from the mapped offset. The bound lets callers walk a table without
|
||||
/// leaving the section that contains it.
|
||||
fn rva_to_off_bounded(sections: &[Section], rva: u32) -> Option<(usize, usize)> {
|
||||
for s in sections {
|
||||
let span = s.vsize.max(s.raw_size);
|
||||
if rva >= s.vaddr && rva < s.vaddr.saturating_add(span) {
|
||||
let delta = rva - s.vaddr;
|
||||
if delta < s.raw_size {
|
||||
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
|
||||
let remaining = (s.raw_size as usize).checked_sub(delta as usize)?;
|
||||
return Some((off, remaining));
|
||||
return Some((s.raw_ptr + delta) as usize);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -176,36 +167,8 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
let size_of_image = u32_le(bytes, opt + 56).ok_or(ProbeError::NotPe32Plus("size_of_image"))?;
|
||||
let num_rvas = u32_le(bytes, opt + 108).ok_or(ProbeError::NotPe32Plus("num_rvas"))?;
|
||||
|
||||
// The import data directory is entry index 1, an 8-byte RVA/size pair at
|
||||
// optional-header offset 112 + 8. Microsoft's PE format requires probes to
|
||||
// honour both NumberOfRvaAndSizes and SizeOfOptionalHeader, so the entry is
|
||||
// validated while the optional header is read: a short optional header must
|
||||
// not let the read fall through into the section table.
|
||||
const IMPORT_DIR_INDEX: u32 = 1;
|
||||
const IMPORT_DIR_OFF: usize = 112 + 8;
|
||||
let mut import_dir: Option<(u32, u32)> = None;
|
||||
if num_rvas > IMPORT_DIR_INDEX {
|
||||
let entry = bytes
|
||||
.get(opt + IMPORT_DIR_OFF..opt + IMPORT_DIR_OFF + 8)
|
||||
.ok_or(ProbeError::NotPe32Plus("truncated import directory"))?;
|
||||
if IMPORT_DIR_OFF + 8 > opt_size {
|
||||
return Err(ProbeError::NotPe32Plus(
|
||||
"import directory outside SizeOfOptionalHeader",
|
||||
));
|
||||
}
|
||||
let rva = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
|
||||
let size = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
|
||||
import_dir = Some((rva, size));
|
||||
}
|
||||
|
||||
let sec_base = opt + opt_size;
|
||||
let section_table_size = (section_count as usize)
|
||||
.checked_mul(40)
|
||||
.ok_or(ProbeError::NotPe32Plus("section table size overflow"))?;
|
||||
bytes
|
||||
.get(sec_base..sec_base + section_table_size)
|
||||
.ok_or(ProbeError::NotPe32Plus("truncated section table"))?;
|
||||
let mut sections = Vec::with_capacity(section_count as usize);
|
||||
let sec_base = opt + opt_size;
|
||||
for i in 0..section_count as usize {
|
||||
let so = sec_base + i * 40;
|
||||
let vsize = u32_le(bytes, so + 8).ok_or(ProbeError::NotPe32Plus("sec vsize"))?;
|
||||
@@ -221,22 +184,16 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
}
|
||||
|
||||
let mut imports: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
if let Some((imp_rva, imp_size)) = import_dir {
|
||||
if num_rvas > 1 {
|
||||
let imp_rva = u32_le(bytes, opt + 112 + 8).unwrap_or(0);
|
||||
if imp_rva != 0
|
||||
&& let Some((mut desc_off, section_bytes_left)) = rva_to_off_bounded(§ions, imp_rva)
|
||||
&& let Some(mut desc_off) = rva_to_off(§ions, imp_rva)
|
||||
{
|
||||
// Bound the 20-byte IMAGE_IMPORT_DESCRIPTOR walk by BOTH the
|
||||
// declared directory Size and the section's raw bytes, whichever
|
||||
// ends first, so descriptors past the directory are not reported.
|
||||
let mut desc_bytes_left = section_bytes_left.min(imp_size as usize);
|
||||
while desc_bytes_left >= 20 {
|
||||
let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
|
||||
u32_le(bytes, desc_off),
|
||||
u32_le(bytes, desc_off + 12),
|
||||
u32_le(bytes, desc_off + 16),
|
||||
) else {
|
||||
break;
|
||||
};
|
||||
while let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
|
||||
u32_le(bytes, desc_off),
|
||||
u32_le(bytes, desc_off + 12),
|
||||
u32_le(bytes, desc_off + 16),
|
||||
) {
|
||||
if orig_thunk == 0 && name_rva == 0 && first_thunk == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -268,7 +225,6 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
imports.entry(dll).or_default().extend(syms);
|
||||
}
|
||||
desc_off += 20;
|
||||
desc_bytes_left -= 20;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -286,129 +242,6 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PE_OFF: usize = 0x80;
|
||||
const COFF: usize = PE_OFF + 4;
|
||||
const OPT: usize = COFF + 20;
|
||||
const OPT_SIZE: usize = 0xF0;
|
||||
const SEC: usize = OPT + OPT_SIZE;
|
||||
const SECTION_RVA: u32 = 0x1000;
|
||||
const RAW_PTR: u32 = 0x200;
|
||||
|
||||
fn put_u16(bytes: &mut [u8], off: usize, value: u16) {
|
||||
bytes[off..off + 2].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put_u32(bytes: &mut [u8], off: usize, value: u32) {
|
||||
bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put_u64(bytes: &mut [u8], off: usize, value: u64) {
|
||||
bytes[off..off + 8].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn write_section(bytes: &mut [u8], base: usize, rva: u32, raw_ptr: u32, raw_size: u32) {
|
||||
bytes[base..base + 8].copy_from_slice(b".rdata\0\0");
|
||||
put_u32(bytes, base + 8, raw_size);
|
||||
put_u32(bytes, base + 12, rva);
|
||||
put_u32(bytes, base + 16, raw_size);
|
||||
put_u32(bytes, base + 20, raw_ptr);
|
||||
}
|
||||
|
||||
fn minimal_pe32_plus() -> Vec<u8> {
|
||||
let mut bytes = vec![0u8; 0x400];
|
||||
bytes[0..2].copy_from_slice(b"MZ");
|
||||
put_u32(&mut bytes, 0x3C, PE_OFF as u32);
|
||||
bytes[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
|
||||
put_u16(&mut bytes, COFF, 0x8664);
|
||||
put_u16(&mut bytes, COFF + 2, 1);
|
||||
put_u16(&mut bytes, COFF + 16, OPT_SIZE as u16);
|
||||
put_u16(&mut bytes, OPT, 0x020B);
|
||||
put_u32(&mut bytes, OPT + 16, 0x1234);
|
||||
put_u64(&mut bytes, OPT + 24, 0x0000_0001_4000_0000);
|
||||
put_u32(&mut bytes, OPT + 56, 0x2000);
|
||||
put_u32(&mut bytes, OPT + 108, 16);
|
||||
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 0x200);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn two_import_pe32_plus() -> Vec<u8> {
|
||||
let mut bytes = minimal_pe32_plus();
|
||||
let import_rva = SECTION_RVA;
|
||||
put_u32(&mut bytes, OPT + 112 + 8, import_rva);
|
||||
put_u32(&mut bytes, OPT + 112 + 12, 0x140);
|
||||
|
||||
// Two descriptors followed by the required all-zero terminator.
|
||||
put_u32(&mut bytes, RAW_PTR as usize, SECTION_RVA + 0x80);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 12, SECTION_RVA + 0x40);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 16, SECTION_RVA + 0x80);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 20, SECTION_RVA + 0xA0);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 32, SECTION_RVA + 0x50);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 36, SECTION_RVA + 0xA0);
|
||||
|
||||
bytes[RAW_PTR as usize + 0x40..RAW_PTR as usize + 0x4A].copy_from_slice(b"ALPHA.DLL\0");
|
||||
bytes[RAW_PTR as usize + 0x50..RAW_PTR as usize + 0x59].copy_from_slice(b"BETA.DLL\0");
|
||||
|
||||
put_u64(
|
||||
&mut bytes,
|
||||
RAW_PTR as usize + 0x80,
|
||||
u64::from(SECTION_RVA + 0x60),
|
||||
);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0x88, 0);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0xA0, (1u64 << 63) | 7);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0xA8, 0);
|
||||
|
||||
put_u16(&mut bytes, RAW_PTR as usize + 0x60, 0x1234);
|
||||
bytes[RAW_PTR as usize + 0x62..RAW_PTR as usize + 0x6C].copy_from_slice(b"NamedFunc\0");
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Two sections: an import-descriptor section holding exactly two
|
||||
/// descriptors and no terminator, and a data section for names and thunks.
|
||||
/// Ellipsis bytes just past the descriptor section spell a third valid
|
||||
/// descriptor, so an unbounded walk reports a DLL that is not imported.
|
||||
fn import_table_without_terminator_pe32_plus() -> Vec<u8> {
|
||||
const DATA_RVA: u32 = SECTION_RVA + 0x1000;
|
||||
const DATA_PTR: u32 = 0x300;
|
||||
|
||||
let mut bytes = minimal_pe32_plus();
|
||||
put_u16(&mut bytes, COFF + 2, 2);
|
||||
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 40);
|
||||
write_section(&mut bytes, SEC + 40, DATA_RVA, DATA_PTR, 0x100);
|
||||
put_u32(&mut bytes, OPT + 112 + 8, SECTION_RVA);
|
||||
// Declare the directory to cover the whole descriptor section, so the
|
||||
// section bound (not the Size) is what this fixture exercises.
|
||||
put_u32(&mut bytes, OPT + 112 + 12, 40);
|
||||
|
||||
for (base, dll_rva, thunk_rva) in [
|
||||
(RAW_PTR as usize, DATA_RVA, DATA_RVA + 0x80),
|
||||
(RAW_PTR as usize + 20, DATA_RVA + 0x20, DATA_RVA + 0xA0),
|
||||
] {
|
||||
put_u32(&mut bytes, base, thunk_rva);
|
||||
put_u32(&mut bytes, base + 12, dll_rva);
|
||||
put_u32(&mut bytes, base + 16, thunk_rva);
|
||||
}
|
||||
|
||||
// A third, entirely valid descriptor just past the section boundary.
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 40, DATA_RVA + 0xC0);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 52, DATA_RVA + 0x40);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 56, DATA_RVA + 0xC0);
|
||||
|
||||
for (delta, name) in [
|
||||
(0x00, &b"ONE.DLL\0"[..]),
|
||||
(0x20, &b"TWO.DLL\0"[..]),
|
||||
(0x40, &b"THREE.DLL\0"[..]),
|
||||
] {
|
||||
let off = DATA_PTR as usize + delta;
|
||||
bytes[off..off + name.len()].copy_from_slice(name);
|
||||
}
|
||||
for (delta, ordinal) in [(0x80, 1u64), (0xA0, 2), (0xC0, 3)] {
|
||||
let off = DATA_PTR as usize + delta;
|
||||
put_u64(&mut bytes, off, (1u64 << 63) | ordinal);
|
||||
put_u64(&mut bytes, off + 8, 0);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_tracks_accurately() {
|
||||
assert_eq!(classify_dll("d3d12_xs.dll"), ShimTrack::TrackCGraphics);
|
||||
@@ -430,175 +263,4 @@ mod tests {
|
||||
);
|
||||
assert_eq!(classify_dll("KERNEL32.dll"), ShimTrack::WineBuiltin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_minimal_pe32_plus_without_imports() {
|
||||
let summary = probe_pe32_plus(&minimal_pe32_plus()).unwrap();
|
||||
assert_eq!(summary.entry_point_rva, 0x1234);
|
||||
assert_eq!(summary.image_base, 0x0000_0001_4000_0000);
|
||||
assert_eq!(summary.size_of_image, 0x2000);
|
||||
assert_eq!(summary.section_count, 1);
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_named_and_ordinal_imports_from_two_dlls() {
|
||||
let summary = probe_pe32_plus(&two_import_pe32_plus()).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ALPHA.DLL".to_owned(), vec!["NamedFunc".to_owned()]),
|
||||
("BETA.DLL".to_owned(), vec!["ORDINAL:7".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncation_at_every_header_boundary() {
|
||||
let image = minimal_pe32_plus();
|
||||
for len in 0..=0x100 {
|
||||
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image[..len]));
|
||||
assert!(result.is_ok(), "panic at truncation 0x{len:X}");
|
||||
assert!(result.unwrap().is_err(), "accepted truncation 0x{len:X}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_section_rva_mapping_that_would_wrap_u32() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 8, SECTION_RVA + 1);
|
||||
put_u32(&mut image, SEC + 20, u32::MAX);
|
||||
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image));
|
||||
assert!(result.is_ok(), "raw pointer addition panicked");
|
||||
assert!(result.unwrap().unwrap().imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_section_count_larger_than_file() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u16(&mut image, COFF + 2, u16::MAX);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("truncated section table")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_pe32_magic() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u16(&mut image, OPT, 0x010B);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("not PE32+ (0x020B)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_directory_outside_all_sections_is_safe() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 8, 0x8000);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_import_directory() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
// An empty section table that fits, an optional header long enough to
|
||||
// declare the import entry, and a file cut after two of the entry's
|
||||
// RVA bytes.
|
||||
put_u16(&mut image, COFF + 2, 0);
|
||||
put_u16(&mut image, COFF + 16, 0xE0);
|
||||
image.truncate(OPT + 112 + 8 + 2);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("truncated import directory")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_unterminated_import_descriptor_walk() {
|
||||
let summary = probe_pe32_plus(&import_table_without_terminator_pe32_plus()).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
|
||||
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
|
||||
/// (a) A short SizeOfOptionalHeader puts the import data-directory entry
|
||||
/// past the end of the optional header, so its 8 bytes would otherwise be
|
||||
/// read from the section table. The entry index is still within
|
||||
/// NumberOfRvaAndSizes, so only the SizeOfOptionalHeader check rejects it.
|
||||
#[test]
|
||||
fn rejects_import_directory_outside_short_optional_header() {
|
||||
let mut image = two_import_pe32_plus();
|
||||
// Import entry spans optional-header offsets 120..128; declare the
|
||||
// optional header to end at 120, inside the entry.
|
||||
put_u16(&mut image, COFF + 16, 120);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
|
||||
);
|
||||
|
||||
// One byte short of the full 8-byte entry is still out of range.
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u16(&mut image, COFF + 16, 127);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
|
||||
);
|
||||
|
||||
// Exactly 128 bytes covers the whole entry, so the import directory is
|
||||
// read normally. The section table now starts at OPT + 128, so write it
|
||||
// there for this size.
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u16(&mut image, COFF + 16, 128);
|
||||
write_section(&mut image, OPT + 128, SECTION_RVA, RAW_PTR, 0x200);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.contains_key("ALPHA.DLL"));
|
||||
assert!(summary.imports.contains_key("BETA.DLL"));
|
||||
}
|
||||
|
||||
/// NumberOfRvaAndSizes == 1 means only entry 0 (export) is declared, so the
|
||||
/// import entry (index 1) must not be probed even though its bytes are
|
||||
/// present and inside SizeOfOptionalHeader.
|
||||
#[test]
|
||||
fn ignores_import_directory_beyond_number_of_rva_and_sizes() {
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u32(&mut image, OPT + 108, 1);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
/// (b) The declared import directory Size is shorter than the containing
|
||||
/// section, so descriptors past the declared size must not be reported even
|
||||
/// though they are valid and inside the section's raw bytes.
|
||||
#[test]
|
||||
fn bounds_import_descriptor_walk_by_declared_directory_size() {
|
||||
// Size 40 covers exactly the two real descriptors; the third valid
|
||||
// descriptor at +40 lies outside the directory but inside the section.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 40);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
|
||||
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
assert!(!summary.imports.contains_key("THREE.DLL"));
|
||||
|
||||
// Size 20 reports only the first descriptor.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 20);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
|
||||
// A size that is not a multiple of 20 stops before the next descriptor
|
||||
// would exceed the directory.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 39);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "bx-runtime"
|
||||
description = "Shared CrossOver launch supervision, environment checks and run evidence"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
libc = "=0.2.191"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,7 @@
|
||||
# Shared hybrid runtime
|
||||
|
||||
`bx-cli` is the executable. This library supplies its single supervised execution path for named CrossOver bottles and explicit Wine prefixes, environment preflight, PE validation, process/session lifecycle, memory and output limits, and JSON run evidence. `bx-cli probe`, `shader` and `trace` retain the original #406 classifiers and telemetry aggregator.
|
||||
|
||||
The implementation is migrated from BetterXen #405 (`b42133a`) and the maintainer draft preserved at `2645c42`, with #406 (`30e551a`, merged as `f2c42ba`) prefix/shim/profile/log contracts integrated. Original attribution remains in each source file; no retired native crate is a dependency and no alternate runner binary is built.
|
||||
|
||||
CrossOver, Rosetta 2 and graphics backends remain external. A dedicated Wine environment is required for safe cleanup: stopping one run stops that environment's server. Session locking coordinates BetterXen launchers; it does not prevent CrossOver's UI or another launcher from using the same environment. A bottle is not a security sandbox.
|
||||
@@ -0,0 +1,928 @@
|
||||
//! Command-line interface of the hybrid tooling.
|
||||
|
||||
use crate::session::BottleSession;
|
||||
use crate::{crossover, frames, host, json::Json, memory, pe, preflight, run, toolchain};
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
const USAGE: &str = "usage: bx-cli <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
|
||||
doctor [--bottle B] [--min-start-free N]
|
||||
check that a run could start here (JSON); non-zero exit if not
|
||||
inspect <file.exe> identify a Windows executable: machine, subsystem, imports (JSON)
|
||||
run (--bottle B | --prefix P) [--exe FILE] [--shims DIR (default build-shims/bin)] [--profile lockhart|anaconda] [--log FILE] [--backend d3dmetal|dxmt|dxvk|wined3d] [--timeout S] [--stall-timeout S]
|
||||
[--settle-bound S] [--expect TEXT] [--require-gates a,b,c] [--out DIR]
|
||||
[--min-start-free N] [--min-free N] [--allow-untested-crossover] -- 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
|
||||
stop (--bottle B | --prefix P) recover a dedicated environment; SIGTERM an active runner first
|
||||
receipt host + crossover + toolchain in one JSON document
|
||||
|
||||
run and bench also accept: --env NAME=VALUE (repeatable), --inherit-env true, --keep-output true.
|
||||
The child otherwise receives only a short allowlist of host variables. A bottle is not a sandbox.";
|
||||
|
||||
/// Set by the signal handler; every run polls it.
|
||||
static INTERRUPTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
extern "C" fn on_signal(_: libc::c_int) {
|
||||
// Storing to an atomic is async-signal-safe.
|
||||
INTERRUPTED.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn install_signal_handlers() {
|
||||
let handler = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;
|
||||
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
|
||||
// SAFETY: `on_signal` has the required signature and only touches an atomic.
|
||||
unsafe { libc::signal(signal, handler) };
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
allow_untested: bool,
|
||||
cfg: run::RunConfig,
|
||||
backends: Vec<String>,
|
||||
repeat: u32,
|
||||
out: Option<PathBuf>,
|
||||
/// What the program file is, recorded with every run.
|
||||
executable: Json,
|
||||
}
|
||||
|
||||
// Environment contract preserved from #406; frozen C headers remain unchanged.
|
||||
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,XCRDAPI,xgameruntime,AcpHal,xapu,chad,GameInput,\
|
||||
api-ms-win-core-psm-appnotify-l1-1-0,api-ms-win-core-psm-appnotify-l1-1-1,\
|
||||
ext-ms-win-rtcore-ntuser-message-l1-1-0,ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0,\
|
||||
ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0=n,b";
|
||||
|
||||
fn unix_to_wine_z_path(path: &std::path::Path) -> String {
|
||||
format!("Z:{}", path.to_string_lossy().replace('/', "\\"))
|
||||
}
|
||||
|
||||
/// #406's launch contract: shim overrides and `WINEPATH` are always configured, from
|
||||
/// `build-shims/bin` unless `--shims` names another directory. An explicit `--shims` wins over
|
||||
/// `--env`; the default does not replace a value the caller passed with `--env`.
|
||||
fn shim_environment(
|
||||
explicit: Option<&std::path::Path>,
|
||||
user: &[(String, String)],
|
||||
) -> Result<Vec<(String, String)>, String> {
|
||||
let dir = match explicit {
|
||||
Some(path) => {
|
||||
let path = std::fs::canonicalize(path)
|
||||
.map_err(|e| format!("cannot open shims {}: {e}", path.display()))?;
|
||||
if !path.is_dir() {
|
||||
return Err("--shims must name a directory".into());
|
||||
}
|
||||
path
|
||||
}
|
||||
None => std::fs::canonicalize(DEFAULT_SHIMS).unwrap_or_else(|_| DEFAULT_SHIMS.into()),
|
||||
};
|
||||
Ok([
|
||||
("WINEDLLOVERRIDES", SHIM_DLL_OVERRIDES.to_string()),
|
||||
("WINEPATH", unix_to_wine_z_path(&dir)),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(name, _)| explicit.is_some() || !user.iter().any(|(k, _)| k == name))
|
||||
.map(|(name, value)| (name.to_string(), value))
|
||||
.collect())
|
||||
}
|
||||
|
||||
const DEFAULT_SHIMS: &str = "build-shims/bin";
|
||||
|
||||
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
|
||||
let (mut bottle, mut prefix, mut exe, mut shims, mut log) = (None, None, None, None, None);
|
||||
let mut profile = "lockhart".to_string();
|
||||
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 require_gates = Vec::new();
|
||||
let mut out = None;
|
||||
let (mut min_start, mut min_free) = (50u8, 15u8);
|
||||
let (mut inherit_env, mut keep_output) = (false, false);
|
||||
let mut allow_untested = false;
|
||||
let mut env = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < args.len() && args[i] != "--" {
|
||||
let key = args[i].as_str();
|
||||
if matches!(
|
||||
key,
|
||||
"--inherit-env" | "--keep-output" | "--allow-untested-crossover"
|
||||
) {
|
||||
let value = args
|
||||
.get(i + 1)
|
||||
.filter(|v| matches!(v.as_str(), "true" | "false"));
|
||||
let enabled = value
|
||||
.map_or(Ok(true), |v| v.parse::<bool>())
|
||||
.map_err(|_| "invalid boolean")?;
|
||||
match key {
|
||||
"--inherit-env" => inherit_env = enabled,
|
||||
"--keep-output" => keep_output = enabled,
|
||||
_ => allow_untested = enabled,
|
||||
}
|
||||
i += if value.is_some() { 2 } else { 1 };
|
||||
continue;
|
||||
}
|
||||
let v = args
|
||||
.get(i + 1)
|
||||
.ok_or_else(|| format!("{key} needs a value"))?
|
||||
.clone();
|
||||
match key {
|
||||
"--bottle" => bottle = Some(v),
|
||||
"--prefix" => prefix = Some(PathBuf::from(v)),
|
||||
"--exe" => exe = Some(v),
|
||||
"--shims" => shims = Some(PathBuf::from(v)),
|
||||
"--profile" => profile = v,
|
||||
"--log" => log = Some(PathBuf::from(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),
|
||||
"--env" => {
|
||||
let (name, value) = v.split_once('=').ok_or("--env needs NAME=VALUE")?;
|
||||
if !valid_environment_name(name) || value.contains('\0') {
|
||||
return Err("--env needs NAME=VALUE".into());
|
||||
}
|
||||
if [
|
||||
"HOME",
|
||||
"USER",
|
||||
"LOGNAME",
|
||||
"WINEPREFIX",
|
||||
"WINESERVER",
|
||||
"WINELOADER",
|
||||
"WINEDLLPATH",
|
||||
"CX_BOTTLE",
|
||||
"CX_BOTTLE_PATH",
|
||||
"CX_ROOT",
|
||||
]
|
||||
.contains(&name)
|
||||
{
|
||||
return Err(format!(
|
||||
"{name} controls launcher identity or bottle selection and cannot be overridden"
|
||||
));
|
||||
}
|
||||
if name.starts_with("CX_GRAPHICS_BACKEND") {
|
||||
return Err("select the backend with --backend, not --env".into());
|
||||
}
|
||||
if name.starts_with("DYLD_") {
|
||||
return Err("DYLD_ variables are not passed to the launcher".into());
|
||||
}
|
||||
env.push((name.to_string(), value.to_string()));
|
||||
}
|
||||
"--require-gates" => require_gates = v.split(',').map(String::from).collect(),
|
||||
"--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, guest_args) = if let Some(exe) = exe {
|
||||
(
|
||||
exe,
|
||||
if args.get(i).map(String::as_str) == Some("--") {
|
||||
args[i + 1..].to_vec()
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
)
|
||||
} else {
|
||||
(
|
||||
args.get(i + 1)
|
||||
.ok_or("use --exe FILE or -- FILE [ARGS...]")?
|
||||
.clone(),
|
||||
args[i + 2..].to_vec(),
|
||||
)
|
||||
};
|
||||
if bottle.is_some() && prefix.is_some() {
|
||||
return Err("choose --bottle or --prefix, not both".into());
|
||||
}
|
||||
if bottle.is_none() && prefix.is_none() {
|
||||
return Err("--bottle or --prefix is required; use a dedicated test environment".into());
|
||||
}
|
||||
let bottle = bottle.unwrap_or_default();
|
||||
if prefix.is_none() && !preflight::valid_bottle_name(&bottle) {
|
||||
return Err(format!("invalid bottle name {bottle:?}"));
|
||||
}
|
||||
if !matches!(profile.as_str(), "lockhart" | "anaconda") {
|
||||
return Err("profile must be lockhart or anaconda".into());
|
||||
}
|
||||
if min_start > 100 || min_free > 100 {
|
||||
return Err("memory percentages must be 0..100".into());
|
||||
}
|
||||
if let Some(unknown) = backend
|
||||
.iter()
|
||||
.chain(backends.iter().filter(|b| *b != "default"))
|
||||
.find(|b| !run::BACKENDS.contains(&b.as_str()))
|
||||
{
|
||||
return Err(format!(
|
||||
"unknown backend {unknown:?}; use one of {}",
|
||||
run::BACKENDS.join(", ")
|
||||
));
|
||||
}
|
||||
if program.starts_with('-') {
|
||||
return Err("the program path must not start with '-' (write ./name.exe)".into());
|
||||
}
|
||||
let executable = identify(std::path::Path::new(&program))?;
|
||||
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 mut wine = run::wine_path(&install.path);
|
||||
let prefix = if let Some(path) = prefix {
|
||||
std::fs::create_dir_all(&path)
|
||||
.map_err(|e| format!("cannot create prefix {}: {e}", path.display()))?;
|
||||
wine.set_file_name("wineloader");
|
||||
Some(std::fs::canonicalize(path).map_err(|e| e.to_string())?)
|
||||
} else {
|
||||
if !run::bottle_prefix(&bottle).join("drive_c").is_dir() {
|
||||
return Err(format!("bottle {bottle:?} not found"));
|
||||
}
|
||||
None
|
||||
};
|
||||
if !wine.is_file() {
|
||||
return Err(format!(
|
||||
"{} not found in this CrossOver build",
|
||||
wine.display()
|
||||
));
|
||||
}
|
||||
env.push(("ROSETTA_ADVERTISE_AVX".into(), "1".into()));
|
||||
env.push(("BX_PROFILE".into(), profile));
|
||||
let shim_env = shim_environment(shims.as_deref(), &env)?;
|
||||
env.extend(shim_env);
|
||||
if let Some(path) = log {
|
||||
let path = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map_err(|e| e.to_string())?
|
||||
.join(path)
|
||||
};
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
env.push(("BX_LOG_FILE".into(), unix_to_wine_z_path(&path)));
|
||||
}
|
||||
Ok(RunArgs {
|
||||
allow_untested,
|
||||
cfg: run::RunConfig {
|
||||
wine,
|
||||
bottle,
|
||||
prefix,
|
||||
backend,
|
||||
program,
|
||||
args: guest_args,
|
||||
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: out
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs")),
|
||||
stall_timeout: stall.map(std::time::Duration::from_secs),
|
||||
settle_bound: std::time::Duration::from_secs(settle),
|
||||
read_free: memory::free_percentage,
|
||||
require_gates,
|
||||
max_output: 64 << 20,
|
||||
inherit_env,
|
||||
env,
|
||||
keep_output,
|
||||
interrupted: &INTERRUPTED,
|
||||
},
|
||||
backends,
|
||||
repeat,
|
||||
out,
|
||||
executable,
|
||||
})
|
||||
}
|
||||
|
||||
/// Refuse anything that is not a launchable Windows program, and describe what is.
|
||||
fn identify(path: &std::path::Path) -> Result<Json, String> {
|
||||
let image = pe::inspect(path)?;
|
||||
image
|
||||
.check_launchable()
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let sha256 = crate::cmdutil::run(
|
||||
"/usr/bin/shasum",
|
||||
&["-a", "256", &path.display().to_string()],
|
||||
)
|
||||
.and_then(|o| o.split_whitespace().next().map(String::from));
|
||||
Ok(Json::obj(vec![
|
||||
("path", Json::str(path.display().to_string())),
|
||||
("sha256", Json::opt_str(sha256)),
|
||||
("image", image.to_json()),
|
||||
]))
|
||||
}
|
||||
|
||||
fn with_executable(mut record: Json, executable: &Json) -> Json {
|
||||
if let Json::Obj(fields) = &mut record {
|
||||
fields.push(("executable".into(), executable.clone()));
|
||||
}
|
||||
record
|
||||
}
|
||||
|
||||
fn doctor(args: &[String]) -> ExitCode {
|
||||
let (mut bottle, mut prefix, mut min_start) = (None, None, 50u8);
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match (a.as_str(), it.next()) {
|
||||
("--bottle", Some(v)) => bottle = Some(v.clone()),
|
||||
("--prefix", Some(v)) => prefix = Some(PathBuf::from(v)),
|
||||
("--min-start-free", Some(v)) if v.parse::<u8>().is_ok() => {
|
||||
min_start = v.parse().unwrap_or(min_start)
|
||||
}
|
||||
_ => {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
if bottle.is_some() && prefix.is_some() {
|
||||
eprintln!("choose --bottle or --prefix");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
let install = crossover::discover(&crossover::candidate_paths(&home))
|
||||
.into_iter()
|
||||
.next();
|
||||
let wine = install.as_ref().map(|i| run::wine_path(&i.path));
|
||||
let mut facts = preflight::gather(
|
||||
bottle.as_deref(),
|
||||
wine.as_deref()
|
||||
.map(|w| (crossover_build().unwrap_or_else(|| "unknown".into()), w)),
|
||||
min_start,
|
||||
);
|
||||
if let Some(path) = prefix {
|
||||
facts.bottle = Some(("prefix".into(), path));
|
||||
}
|
||||
let checks = preflight::evaluate(&facts);
|
||||
let mut report = preflight::to_json(&checks);
|
||||
if let Json::Obj(fields) = &mut report {
|
||||
fields.push(("host_info".into(), host_info(install.as_ref())));
|
||||
}
|
||||
print!("{}", report.render());
|
||||
if checks.iter().all(|c| c.ok) {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reported, never gating: running a prebuilt program needs none of these. Preserves what
|
||||
/// #406's `doctor` showed (memory profile, D3DMetal presence, the shim cross-compiler).
|
||||
fn host_info(install: Option<&crossover::Install>) -> Json {
|
||||
let memory_gib = host::collect().memory_bytes.map(|b| b >> 30);
|
||||
let d3dmetal = install.map(|i| {
|
||||
i.path
|
||||
.join("Contents/SharedSupport/CrossOver/lib64/apple_gptk/external/D3DMetal.framework")
|
||||
.exists()
|
||||
});
|
||||
let mingw = std::env::var_os("PATH").and_then(|path| {
|
||||
std::env::split_paths(&path)
|
||||
.map(|dir| dir.join("x86_64-w64-mingw32-g++"))
|
||||
.find(|candidate| candidate.is_file())
|
||||
});
|
||||
Json::obj(vec![
|
||||
(
|
||||
"memory_gib",
|
||||
memory_gib.map_or(Json::Null, |g| Json::Num(g as f64)),
|
||||
),
|
||||
(
|
||||
"recommended_profile",
|
||||
Json::opt_str(memory_gib.map(|g| recommended_profile(g).to_string())),
|
||||
),
|
||||
(
|
||||
"crossover_build_tested",
|
||||
install.map_or(Json::Null, |_| {
|
||||
Json::Bool(run::tested_crossover_build(crossover_build().as_deref()))
|
||||
}),
|
||||
),
|
||||
(
|
||||
"d3dmetal_framework_present",
|
||||
d3dmetal.map_or(Json::Null, Json::Bool),
|
||||
),
|
||||
(
|
||||
"shim_cross_compiler",
|
||||
Json::opt_str(mingw.map(|p| p.display().to_string())),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn recommended_profile(memory_gib: u64) -> &'static str {
|
||||
if memory_gib >= 32 {
|
||||
"anaconda"
|
||||
} else {
|
||||
"lockhart"
|
||||
}
|
||||
}
|
||||
|
||||
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()?
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// The launcher options are observed behaviour of specific builds, so an unlisted build is
|
||||
/// refused unless the caller opts in. `stop` is not gated: recovery must always work.
|
||||
fn check_build(build: Option<&str>, allow_untested: bool) -> Result<(), String> {
|
||||
if run::tested_crossover_build(build) {
|
||||
return Ok(());
|
||||
}
|
||||
let message = format!(
|
||||
"CrossOver {} has not been tested with this launcher (tested: {})",
|
||||
build.unwrap_or("of unknown version"),
|
||||
run::TESTED_CROSSOVER_BUILDS.join(", ")
|
||||
);
|
||||
if allow_untested {
|
||||
eprintln!("warning: {message}");
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"{message}; pass --allow-untested-crossover to run anyway"
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn save(dir: &std::path::Path, kind: &str, j: &Json) -> Result<(), String> {
|
||||
crate::records::save(dir, kind, j)
|
||||
.map(|path| eprintln!("report saved: {}", path.display()))
|
||||
.map_err(|error| format!("cannot save {kind} report in {}: {error}", dir.display()))
|
||||
}
|
||||
|
||||
fn finish_report(passed: bool, out: Option<&std::path::Path>, kind: &str, j: &Json) -> ExitCode {
|
||||
print!("{}", j.render());
|
||||
if let Some(dir) = out
|
||||
&& let Err(error) = save(dir, kind, j)
|
||||
{
|
||||
eprintln!("{error}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
if passed {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
|
||||
fn run_cmd(args: &[String]) -> ExitCode {
|
||||
if args == ["--help"] {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
let a = match parse_run_args(args) {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
eprintln!("{e}\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let build = crossover_build();
|
||||
if let Err(e) = check_build(build.as_deref(), a.allow_untested) {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let mut session = match BottleSession::acquire(&a.cfg.prefix_path(), false) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let mut r = run::execute(&a.cfg, build);
|
||||
if r.class != run::Class::CleanupFailed
|
||||
&& let Err(e) = session.complete()
|
||||
{
|
||||
eprintln!("cannot finish bottle session: {e}");
|
||||
r.class = run::Class::CleanupFailed;
|
||||
if let Json::Obj(fields) = &mut r.json {
|
||||
fields.retain(|(name, _)| name != "classification");
|
||||
fields.push(("classification".into(), Json::str("cleanup_failed")));
|
||||
fields.push(("session_error".into(), Json::str(e)));
|
||||
}
|
||||
}
|
||||
if r.class != run::Class::Passed {
|
||||
eprintln!("run: {}", r.class.name());
|
||||
for g in r.gates.iter().filter(|g| !g.passed) {
|
||||
eprintln!(" gate {} failed: {}", g.name, g.detail);
|
||||
}
|
||||
if let Some(e) = &r.error {
|
||||
eprintln!(" {e}");
|
||||
}
|
||||
}
|
||||
finish_report(
|
||||
r.class == run::Class::Passed,
|
||||
a.out.as_deref(),
|
||||
"run",
|
||||
&with_executable(r.json, &a.executable),
|
||||
)
|
||||
}
|
||||
|
||||
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();
|
||||
if let Err(e) = check_build(build.as_deref(), a.allow_untested) {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let mut session = match BottleSession::acquire(&a.cfg.prefix_path(), false) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let mut per_backend = Vec::new();
|
||||
let mut all_ok = true;
|
||||
let mut cleanup_failed = false;
|
||||
for b in &a.backends {
|
||||
let mut runs = Vec::new();
|
||||
for _ in 0..a.repeat {
|
||||
if INTERRUPTED.load(Ordering::SeqCst) || cleanup_failed {
|
||||
all_ok = false;
|
||||
break;
|
||||
}
|
||||
let mut cfg = a.cfg.clone();
|
||||
cfg.backend = if b == "default" {
|
||||
None
|
||||
} else {
|
||||
Some(b.clone())
|
||||
};
|
||||
let r = run::execute(&cfg, build.clone());
|
||||
cleanup_failed |= r.class == run::Class::CleanupFailed;
|
||||
all_ok &= r.class == run::Class::Passed;
|
||||
runs.push(with_executable(r.json, &a.executable));
|
||||
}
|
||||
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)),
|
||||
]);
|
||||
if !cleanup_failed && let Err(e) = session.complete() {
|
||||
eprintln!("cannot finish bottle session: {e}");
|
||||
all_ok = false;
|
||||
}
|
||||
finish_report(all_ok, a.out.as_deref(), "bench", &doc)
|
||||
}
|
||||
|
||||
fn stop(args: &[String]) -> ExitCode {
|
||||
let [flag, target] = args else {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let prefix = match flag.as_str() {
|
||||
"--bottle" if preflight::valid_bottle_name(target) => run::bottle_prefix(target),
|
||||
"--prefix" => PathBuf::from(target),
|
||||
_ => {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
if !prefix.join("drive_c").is_dir() {
|
||||
eprintln!("initialized environment not found at {}", prefix.display());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
let prefix = match std::fs::canonicalize(&prefix) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
eprintln!("cannot resolve prefix {}: {error}", prefix.display());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
let Some(install) = crossover::discover(&crossover::candidate_paths(&home))
|
||||
.into_iter()
|
||||
.next()
|
||||
else {
|
||||
eprintln!("no CrossOver installation found");
|
||||
return ExitCode::from(1);
|
||||
};
|
||||
let mut session = match BottleSession::acquire(&prefix, true) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
if let Err(e) =
|
||||
run::stop_prefix(&run::wine_path(&install.path), &prefix).and_then(|()| session.complete())
|
||||
{
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-stop/0")),
|
||||
("prefix", Json::str(prefix.display().to_string())),
|
||||
("stopped", Json::Bool(true))
|
||||
])
|
||||
.render()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn valid_environment_name(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
chars
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod foundation_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn profile_recommendation_matches_the_foundation_threshold() {
|
||||
assert_eq!(recommended_profile(16), "lockhart");
|
||||
assert_eq!(recommended_profile(24), "lockhart");
|
||||
assert_eq!(recommended_profile(32), "anaconda");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untested_crossover_builds_are_refused_unless_allowed() {
|
||||
assert!(check_build(Some("26.3 (26.3.0.39832)"), false).is_ok());
|
||||
for build in [Some("26.2 (26.2.0.39821)"), None] {
|
||||
let refused = check_build(build, false).unwrap_err();
|
||||
assert!(refused.contains("--allow-untested-crossover"));
|
||||
assert!(check_build(build, true).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shims_are_configured_by_default_without_replacing_env_values() {
|
||||
let names =
|
||||
|env: Vec<(String, String)>| env.into_iter().map(|(k, _)| k).collect::<Vec<_>>();
|
||||
let default = shim_environment(None, &[]).unwrap();
|
||||
assert!(
|
||||
default[1].1.ends_with("build-shims\\bin"),
|
||||
"{}",
|
||||
default[1].1
|
||||
);
|
||||
assert_eq!(names(default), ["WINEDLLOVERRIDES", "WINEPATH"]);
|
||||
let user = [("WINEDLLOVERRIDES".to_string(), "xmem=".to_string())];
|
||||
assert_eq!(names(shim_environment(None, &user).unwrap()), ["WINEPATH"]);
|
||||
let dir = std::env::temp_dir();
|
||||
assert_eq!(
|
||||
names(shim_environment(Some(&dir), &user).unwrap()),
|
||||
["WINEDLLOVERRIDES", "WINEPATH"]
|
||||
);
|
||||
assert!(shim_environment(Some(std::path::Path::new("/nonexistent")), &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_unix_path_to_wine_z_drive() {
|
||||
assert_eq!(
|
||||
unix_to_wine_z_path(std::path::Path::new("/tmp/bx-test.jsonl")),
|
||||
"Z:\\tmp\\bx-test.jsonl"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry point for the runtime subcommands of `bx-cli`. `args` excludes the program name; a
|
||||
/// leading `hybrid` word (the #405 spelling) is accepted and ignored.
|
||||
pub fn run_cli(args: &[String]) -> ExitCode {
|
||||
// The standalone maintainer bundle accepts the same `hybrid ...` argument vector as
|
||||
// the full CLI. Both enter this implementation; no wrapper or native research runtime
|
||||
// needs to be distributed for the acceptance tools.
|
||||
let args = if args.first().map(String::as_str) == Some("hybrid") {
|
||||
&args[1..]
|
||||
} else {
|
||||
args
|
||||
};
|
||||
let rest = args.get(1..).unwrap_or_default();
|
||||
match args.first().map(String::as_str) {
|
||||
Some("run") => {
|
||||
install_signal_handlers();
|
||||
return run_cmd(rest);
|
||||
}
|
||||
Some("bench") => {
|
||||
install_signal_handlers();
|
||||
return bench_cmd(rest);
|
||||
}
|
||||
Some("doctor") => return doctor(rest),
|
||||
Some("guard") => return guard(rest),
|
||||
Some("stop") => return stop(rest),
|
||||
_ => {}
|
||||
}
|
||||
let result: Result<Json, String> = match args.first().map(String::as_str) {
|
||||
Some("host") => Ok(host::collect().to_json()),
|
||||
Some("inspect") => match args.get(1) {
|
||||
None => Err("inspect needs a file".into()),
|
||||
Some(f) => pe::inspect(std::path::Path::new(f)).map(|i| i.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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod report_tests {
|
||||
use super::*;
|
||||
|
||||
fn args(a: &[&str]) -> Vec<String> {
|
||||
a.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
// These fail before CrossOver discovery, so they run on hosts without CrossOver.
|
||||
#[test]
|
||||
fn bad_backend_bottle_or_program_is_refused_before_launch() {
|
||||
let err = |a: &[&str]| parse_run_args(&args(a)).err().unwrap();
|
||||
assert!(
|
||||
err(&["--bottle", "b", "--backend", "dmxt", "--", "x.exe"]).contains("unknown backend")
|
||||
);
|
||||
assert!(
|
||||
err(&["--bottle", "b", "--backends", "default,typo", "--", "x.exe"])
|
||||
.contains("unknown backend")
|
||||
);
|
||||
assert!(err(&["--bottle", "../b", "--", "x.exe"]).contains("invalid bottle"));
|
||||
assert!(err(&["--bottle", "b", "--", "/nonexistent/x.exe"]).contains("/nonexistent/x.exe"));
|
||||
assert!(err(&["--bottle", "b", "--", "/bin/sh"]).contains("not a PE"));
|
||||
assert!(err(&["--bottle", "b", "--", "--help"]).contains("must not start with"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requested_evidence_failure_overrides_a_passing_workload() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"bx-report-invalid-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::write(&path, "keep this file").unwrap();
|
||||
for kind in ["run", "bench"] {
|
||||
assert_eq!(
|
||||
finish_report(true, Some(&path), kind, &Json::Null),
|
||||
ExitCode::from(1)
|
||||
);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep this file");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_only_reporting_preserves_workload_status() {
|
||||
assert_eq!(
|
||||
finish_report(true, None, "run", &Json::Null),
|
||||
ExitCode::SUCCESS
|
||||
);
|
||||
assert_eq!(
|
||||
finish_report(false, None, "bench", &Json::Null),
|
||||
ExitCode::from(1)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! 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 gpu_wired: GpuWired,
|
||||
pub host_arch_of_this_binary: &'static str,
|
||||
}
|
||||
|
||||
fn sysctl(name: &str) -> Option<String> {
|
||||
run("/usr/sbin/sysctl", &["-n", name])
|
||||
}
|
||||
|
||||
/// GPU wired-memory sysctls (issue #386), recorded as the raw integers `sysctl -n` prints.
|
||||
///
|
||||
/// Read only: nothing in BetterXen writes these keys. `None` means the key is absent (the
|
||||
/// command failed) or its output is not an unsigned integer. A value of 0 was observed on an
|
||||
/// M4 and an M5; Apple does not document what 0 means in anything reviewed for #386, so it is
|
||||
/// reported as observed and never interpreted (for example as "system default" or "no limit").
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct GpuWired {
|
||||
/// `iogpu.wired_limit_mb`.
|
||||
pub limit_mb: Option<u64>,
|
||||
/// `iogpu.wired_lwm_mb`.
|
||||
pub lwm_mb: Option<u64>,
|
||||
}
|
||||
|
||||
pub const GPU_WIRED_SOURCE: &str = "sysctl -n iogpu.wired_limit_mb, iogpu.wired_lwm_mb (read-only; raw values, meaning of 0 undocumented)";
|
||||
|
||||
/// Read the GPU wired-memory keys through `read`, which returns a key's trimmed output or
|
||||
/// `None` when the key cannot be read. Injected so tests do not depend on this Mac.
|
||||
pub fn gpu_wired_with(read: impl Fn(&str) -> Option<String>) -> GpuWired {
|
||||
let num = |key: &str| read(key).and_then(|v| v.trim().parse::<u64>().ok());
|
||||
GpuWired {
|
||||
limit_mb: num("iogpu.wired_limit_mb"),
|
||||
lwm_mb: num("iogpu.wired_lwm_mb"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gpu_wired() -> GpuWired {
|
||||
gpu_wired_with(sysctl)
|
||||
}
|
||||
|
||||
impl GpuWired {
|
||||
/// The record fields shared by the host receipt and every run record.
|
||||
pub fn json_fields(&self) -> Vec<(&'static str, Json)> {
|
||||
let n = |v: Option<u64>| v.map_or(Json::Null, |x| Json::Num(x as f64));
|
||||
vec![
|
||||
("gpu_wired_limit_mb", n(self.limit_mb)),
|
||||
("gpu_wired_lwm_mb", n(self.lwm_mb)),
|
||||
("gpu_wired_source", Json::str(GPU_WIRED_SOURCE)),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
gpu_wired: gpu_wired(),
|
||||
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));
|
||||
let mut fields = 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())),
|
||||
];
|
||||
fields.extend(self.gpu_wired.json_fields());
|
||||
fields.push((
|
||||
"receipt_binary_arch",
|
||||
Json::str(self.host_arch_of_this_binary),
|
||||
));
|
||||
Json::obj(fields)
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
|
||||
fn reader<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
|
||||
move |key| {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_wired_values_are_reported_raw() {
|
||||
let w = gpu_wired_with(reader(&[
|
||||
("iogpu.wired_limit_mb", "24576"),
|
||||
("iogpu.wired_lwm_mb", "0"),
|
||||
]));
|
||||
assert_eq!(w.limit_mb, Some(24576));
|
||||
// 0 is a value like any other, not "absent".
|
||||
assert_eq!(w.lwm_mb, Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_unparsable_gpu_wired_keys_are_null() {
|
||||
let w = gpu_wired_with(reader(&[("iogpu.wired_limit_mb", "unlimited")]));
|
||||
assert_eq!(w, GpuWired::default());
|
||||
let j = Json::obj(w.json_fields()).render();
|
||||
assert!(j.contains("\"gpu_wired_limit_mb\": null"), "{j}");
|
||||
assert!(j.contains("\"gpu_wired_lwm_mb\": null"), "{j}");
|
||||
assert!(j.contains("\"gpu_wired_source\": \"sysctl -n"), "{j}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipt_carries_gpu_wired_fields() {
|
||||
let mut r = collect();
|
||||
r.gpu_wired = GpuWired {
|
||||
limit_mb: Some(0),
|
||||
lwm_mb: None,
|
||||
};
|
||||
let j = r.to_json().render();
|
||||
assert!(j.contains("\"gpu_wired_limit_mb\": 0"), "{j}");
|
||||
assert!(j.contains("\"gpu_wired_lwm_mb\": null"), "{j}");
|
||||
}
|
||||
|
||||
#[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"));
|
||||
}
|
||||
}
|
||||
@@ -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"#));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! BetterXen hybrid tooling: environment checks, executable identification, supervised
|
||||
//! launches and measurement around an externally installed CrossOver. Nothing here claims
|
||||
//! game or console compatibility.
|
||||
|
||||
pub mod cli;
|
||||
pub mod cmdutil;
|
||||
pub mod crossover;
|
||||
pub mod frames;
|
||||
pub mod host;
|
||||
pub mod json;
|
||||
pub mod memory;
|
||||
pub mod pe;
|
||||
pub mod preflight;
|
||||
pub mod records;
|
||||
pub mod run;
|
||||
pub mod session;
|
||||
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
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! Identify a Windows executable before it is handed to CrossOver.
|
||||
//!
|
||||
//! Reads only the headers and the import directory names of a PE/COFF image, following
|
||||
//! Microsoft's published "PE Format" specification. The file is untrusted input: every
|
||||
//! offset is checked, counts are capped, and nothing is executed. This answers "is this a
|
||||
//! launchable x86 Windows program, and which DLLs does it import"; it does not prove that
|
||||
//! the program will run.
|
||||
|
||||
use crate::json::Json;
|
||||
|
||||
/// Largest file this will read. Larger programs are refused rather than partly checked.
|
||||
pub const MAX_BYTES: u64 = 1 << 30;
|
||||
const MAX_SECTIONS: usize = 96;
|
||||
const MAX_IMPORTS: usize = 512;
|
||||
const MAX_NAME: usize = 256;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Machine {
|
||||
X86_64,
|
||||
I386,
|
||||
Arm64,
|
||||
Other(u16),
|
||||
}
|
||||
|
||||
impl Machine {
|
||||
pub fn name(self) -> String {
|
||||
match self {
|
||||
Machine::X86_64 => "x86_64".into(),
|
||||
Machine::I386 => "i386".into(),
|
||||
Machine::Arm64 => "arm64".into(),
|
||||
Machine::Other(m) => format!("unknown_0x{m:04x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Image {
|
||||
pub machine: Machine,
|
||||
pub pe32_plus: bool,
|
||||
pub subsystem: u16,
|
||||
pub is_dll: bool,
|
||||
/// Imported DLL names, lower-cased, from the (non-delayed) import directory.
|
||||
pub imports: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Error {
|
||||
NotPe(&'static str),
|
||||
Truncated(&'static str),
|
||||
Unsupported(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Error::NotPe(why) => write!(f, "not a PE executable: {why}"),
|
||||
Error::Truncated(what) => write!(f, "truncated or inconsistent PE: {what}"),
|
||||
Error::Unsupported(why) => write!(f, "unsupported executable: {why}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes<'a>(d: &'a [u8], at: usize, n: usize, what: &'static str) -> Result<&'a [u8], Error> {
|
||||
at.checked_add(n)
|
||||
.and_then(|end| d.get(at..end))
|
||||
.ok_or(Error::Truncated(what))
|
||||
}
|
||||
|
||||
fn u16_at(d: &[u8], at: usize, what: &'static str) -> Result<u16, Error> {
|
||||
let b = bytes(d, at, 2, what)?;
|
||||
Ok(u16::from_le_bytes([b[0], b[1]]))
|
||||
}
|
||||
|
||||
fn u32_at(d: &[u8], at: usize, what: &'static str) -> Result<u32, Error> {
|
||||
let b = bytes(d, at, 4, what)?;
|
||||
Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
|
||||
struct Section {
|
||||
va: u32,
|
||||
size: u32,
|
||||
file: u32,
|
||||
}
|
||||
|
||||
fn file_offset(sections: &[Section], rva: u32) -> Option<usize> {
|
||||
sections.iter().find_map(|s| {
|
||||
let into = rva.checked_sub(s.va)?;
|
||||
(into < s.size).then(|| s.file.checked_add(into).map(|v| v as usize))?
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse(d: &[u8]) -> Result<Image, Error> {
|
||||
if bytes(d, 0, 2, "DOS magic").map_err(|_| Error::NotPe("file too small"))? != b"MZ" {
|
||||
return Err(Error::NotPe("missing MZ magic"));
|
||||
}
|
||||
let pe = u32_at(d, 0x3c, "e_lfanew")? as usize;
|
||||
if bytes(d, pe, 4, "PE signature")? != b"PE\0\0" {
|
||||
return Err(Error::NotPe("missing PE signature"));
|
||||
}
|
||||
let coff = pe.checked_add(4).ok_or(Error::Truncated("COFF header"))?;
|
||||
let machine = match u16_at(d, coff, "machine")? {
|
||||
0x8664 => Machine::X86_64,
|
||||
0x014c => Machine::I386,
|
||||
0xaa64 => Machine::Arm64,
|
||||
m => Machine::Other(m),
|
||||
};
|
||||
let section_count = u16_at(d, coff + 2, "section count")? as usize;
|
||||
let optional_size = u16_at(d, coff + 16, "optional header size")? as usize;
|
||||
let characteristics = u16_at(d, coff + 18, "characteristics")?;
|
||||
if characteristics & 0x0002 == 0 {
|
||||
return Err(Error::NotPe("not marked as an executable image"));
|
||||
}
|
||||
if section_count > MAX_SECTIONS {
|
||||
return Err(Error::Truncated("implausible section count"));
|
||||
}
|
||||
let opt = coff + 20;
|
||||
let optional = bytes(d, opt, optional_size, "optional header")?;
|
||||
let (pe32_plus, count_at, dirs_at) = match u16_at(optional, 0, "optional magic")? {
|
||||
0x20b => (true, 108, 112),
|
||||
0x10b => (false, 92, 96),
|
||||
_ => return Err(Error::NotPe("unknown optional header magic")),
|
||||
};
|
||||
let subsystem = u16_at(optional, 68, "subsystem")?;
|
||||
|
||||
let mut sections = Vec::with_capacity(section_count);
|
||||
let table = opt + optional_size;
|
||||
for i in 0..section_count {
|
||||
let at = table + i * 40;
|
||||
sections.push(Section {
|
||||
va: u32_at(d, at + 12, "section address")?,
|
||||
size: u32_at(d, at + 16, "section raw size")?,
|
||||
file: u32_at(d, at + 20, "section raw pointer")?,
|
||||
});
|
||||
}
|
||||
|
||||
let mut imports = Vec::new();
|
||||
let directories = u32_at(optional, count_at, "directory count")?;
|
||||
let import_rva = if directories >= 2 {
|
||||
u32_at(optional, dirs_at + 8, "import directory")?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if import_rva != 0 {
|
||||
let start = file_offset(§ions, import_rva)
|
||||
.ok_or(Error::Truncated("import directory outside sections"))?;
|
||||
let mut terminated = false;
|
||||
for i in 0..=MAX_IMPORTS {
|
||||
let entry = bytes(d, start + i * 20, 20, "import descriptor")?;
|
||||
if entry.iter().all(|b| *b == 0) {
|
||||
terminated = true;
|
||||
break;
|
||||
}
|
||||
let name_rva = u32_at(entry, 12, "import name")?;
|
||||
let at = file_offset(§ions, name_rva)
|
||||
.ok_or(Error::Truncated("import name outside sections"))?;
|
||||
let rest = d.get(at..).ok_or(Error::Truncated("import name"))?;
|
||||
let len = rest
|
||||
.iter()
|
||||
.take(MAX_NAME)
|
||||
.position(|b| *b == 0)
|
||||
.ok_or(Error::Truncated("unterminated import name"))?;
|
||||
imports.push(String::from_utf8_lossy(&rest[..len]).to_ascii_lowercase());
|
||||
}
|
||||
if !terminated {
|
||||
return Err(Error::Truncated("import directory has no terminator"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Image {
|
||||
machine,
|
||||
pe32_plus,
|
||||
subsystem,
|
||||
is_dll: characteristics & 0x2000 != 0,
|
||||
imports,
|
||||
})
|
||||
}
|
||||
|
||||
impl Image {
|
||||
/// Refuse what is known not to launch. ARM64 programs were observed to be rejected by
|
||||
/// CrossOver 26.3 on macOS ("cannot execute").
|
||||
pub fn check_launchable(&self) -> Result<(), Error> {
|
||||
if self.is_dll {
|
||||
return Err(Error::Unsupported(
|
||||
"the file is a DLL, not a program".into(),
|
||||
));
|
||||
}
|
||||
if !matches!(self.machine, Machine::X86_64 | Machine::I386) {
|
||||
return Err(Error::Unsupported(format!(
|
||||
"machine {} (CrossOver on macOS runs x86 and x86_64 Windows programs)",
|
||||
self.machine.name()
|
||||
)));
|
||||
}
|
||||
// 2 = Windows GUI, 3 = Windows console.
|
||||
if !matches!(self.subsystem, 2 | 3) {
|
||||
return Err(Error::Unsupported(format!("subsystem {}", self.subsystem)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("machine", Json::str(self.machine.name())),
|
||||
("pe32_plus", Json::Bool(self.pe32_plus)),
|
||||
("subsystem", Json::Num(self.subsystem as f64)),
|
||||
(
|
||||
"imports",
|
||||
Json::Arr(self.imports.iter().map(|s| Json::str(s.clone())).collect()),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and identify a program file, refusing anything that is not a regular file of a
|
||||
/// plausible size.
|
||||
pub fn inspect(path: &std::path::Path) -> Result<Image, String> {
|
||||
let meta = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if !meta.is_file() {
|
||||
return Err(format!("{}: not a regular file", path.display()));
|
||||
}
|
||||
if meta.len() > MAX_BYTES {
|
||||
return Err(format!("{}: larger than {MAX_BYTES} bytes", path.display()));
|
||||
}
|
||||
let data = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
parse(&data).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
fn put16(d: &mut [u8], at: usize, v: u16) {
|
||||
d[at..at + 2].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
fn put32(d: &mut [u8], at: usize, v: u32) {
|
||||
d[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
/// A minimal image written field by field from the PE Format specification: one section
|
||||
/// at RVA 0x1000 holding one import descriptor and its name.
|
||||
pub(crate) fn synthetic(machine: u16, characteristics: u16) -> Vec<u8> {
|
||||
let mut d = vec![0u8; 0x400];
|
||||
d[0..2].copy_from_slice(b"MZ");
|
||||
put32(&mut d, 0x3c, 0x40);
|
||||
d[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
put16(&mut d, 0x44, machine);
|
||||
put16(&mut d, 0x46, 1); // one section
|
||||
put16(&mut d, 0x54, 240); // PE32+ optional header with 16 directories
|
||||
put16(&mut d, 0x56, characteristics);
|
||||
let opt = 0x58;
|
||||
put16(&mut d, opt, 0x20b);
|
||||
put16(&mut d, opt + 68, 3);
|
||||
put32(&mut d, opt + 108, 16);
|
||||
put32(&mut d, opt + 120, 0x1000); // directory 1: imports
|
||||
let section = opt + 240;
|
||||
put32(&mut d, section + 12, 0x1000);
|
||||
put32(&mut d, section + 16, 0x100);
|
||||
put32(&mut d, section + 20, 0x200);
|
||||
put32(&mut d, 0x200 + 12, 0x1080); // name of descriptor 0
|
||||
d[0x280..0x28a].copy_from_slice(b"D3D11.dll\0");
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_machine_subsystem_and_imports() {
|
||||
let i = parse(&synthetic(0x8664, 0x0022)).unwrap();
|
||||
assert_eq!(i.machine, Machine::X86_64);
|
||||
assert!(i.pe32_plus);
|
||||
assert_eq!(i.subsystem, 3);
|
||||
assert_eq!(i.imports, ["d3d11.dll"]);
|
||||
assert_eq!(i.check_launchable(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_arm64_dlls_and_unknown_machines() {
|
||||
let arm = parse(&synthetic(0xaa64, 0x0022)).unwrap();
|
||||
assert!(matches!(arm.check_launchable(), Err(Error::Unsupported(_))));
|
||||
let dll = parse(&synthetic(0x8664, 0x2022)).unwrap();
|
||||
assert!(matches!(dll.check_launchable(), Err(Error::Unsupported(_))));
|
||||
let other = parse(&synthetic(0x1f0, 0x0022)).unwrap();
|
||||
assert!(other.check_launchable().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_pe_input_is_an_error() {
|
||||
assert!(matches!(parse(b""), Err(Error::NotPe(_))));
|
||||
assert!(matches!(parse(b"#!/bin/sh\n"), Err(Error::NotPe(_))));
|
||||
let mut d = synthetic(0x8664, 0x0022);
|
||||
d[0x40] = b'X';
|
||||
assert!(matches!(parse(&d), Err(Error::NotPe(_))));
|
||||
assert!(parse(&synthetic(0x8664, 0)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_offsets_and_truncation_never_panic() {
|
||||
let good = synthetic(0x8664, 0x0022);
|
||||
for n in 0..good.len() {
|
||||
let _ = parse(&good[..n]);
|
||||
}
|
||||
// Every aligned word replaced by extreme values: must return, never panic.
|
||||
for at in (0..good.len() - 4).step_by(2) {
|
||||
for v in [u32::MAX, 0x7fff_ffff, 0x1000] {
|
||||
let mut d = good.clone();
|
||||
put32(&mut d, at, v);
|
||||
let _ = parse(&d);
|
||||
}
|
||||
}
|
||||
let mut far = good.clone();
|
||||
put32(&mut far, 0x58 + 120, 0xdead_0000);
|
||||
assert!(matches!(parse(&far), Err(Error::Truncated(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Read-only environment checks before a run (`bx-cli doctor`).
|
||||
//!
|
||||
//! Each check is something observed on this host. A pass means the pieces the runner needs
|
||||
//! are present; it does not mean any program will run.
|
||||
|
||||
use crate::json::Json;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Check {
|
||||
pub name: &'static str,
|
||||
pub ok: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Facts {
|
||||
pub host_arch: &'static str,
|
||||
/// None when no CrossOver bundle was found.
|
||||
pub crossover: Option<(String, std::path::PathBuf)>,
|
||||
pub rosetta_runs_x86_64: bool,
|
||||
pub bottle: Option<(String, std::path::PathBuf)>,
|
||||
pub free_percent: Option<u8>,
|
||||
pub min_start_free: u8,
|
||||
}
|
||||
|
||||
pub fn evaluate(f: &Facts) -> Vec<Check> {
|
||||
let mut out = vec![Check {
|
||||
name: "host_arm64",
|
||||
ok: f.host_arch == "aarch64",
|
||||
detail: f.host_arch.to_string(),
|
||||
}];
|
||||
match &f.crossover {
|
||||
None => out.push(Check {
|
||||
name: "crossover_installed",
|
||||
ok: false,
|
||||
detail: "no CrossOver bundle found; install it from CodeWeavers".into(),
|
||||
}),
|
||||
Some((version, wine)) => {
|
||||
out.push(Check {
|
||||
name: "crossover_installed",
|
||||
ok: true,
|
||||
detail: version.clone(),
|
||||
});
|
||||
for (name, path) in [
|
||||
("wine_launcher", wine.clone()),
|
||||
("wineserver", wine.with_file_name("wineserver")),
|
||||
] {
|
||||
out.push(Check {
|
||||
name,
|
||||
ok: path.is_file(),
|
||||
detail: path.display().to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(Check {
|
||||
name: "rosetta",
|
||||
ok: f.rosetta_runs_x86_64,
|
||||
detail: "whether an x86_64 binary executes (CrossOver 26.3's Wine is x86_64-only)".into(),
|
||||
});
|
||||
if let Some((name, dir)) = &f.bottle {
|
||||
out.push(Check {
|
||||
name: "bottle",
|
||||
ok: valid_bottle_name(name) && dir.join("drive_c").is_dir(),
|
||||
detail: dir.display().to_string(),
|
||||
});
|
||||
if dir.join("drive_c").is_dir() {
|
||||
let marker = dir.join(".betterxen-session");
|
||||
let clean = match std::fs::symlink_metadata(&marker) {
|
||||
Ok(meta) => meta.is_file() && !meta.file_type().is_symlink() && meta.len() == 0,
|
||||
Err(e) => e.kind() == std::io::ErrorKind::NotFound,
|
||||
};
|
||||
out.push(Check {
|
||||
name: "bottle_session",
|
||||
ok: clean,
|
||||
detail: if clean { "no unfinished BetterXen session".into() } else {
|
||||
"active, unfinished or invalid session marker; SIGTERM an active runner, or use `bx-cli stop` for abandoned sessions".into()
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
out.push(match f.free_percent {
|
||||
Some(p) => Check {
|
||||
name: "free_memory",
|
||||
ok: p >= f.min_start_free,
|
||||
detail: format!("{p}% free, {}% required", f.min_start_free),
|
||||
},
|
||||
None => Check {
|
||||
name: "free_memory",
|
||||
ok: false,
|
||||
detail: "could not be read".into(),
|
||||
},
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// A bottle name becomes a path component and a command argument, so it must be neither a
|
||||
/// path nor something the launcher could read as an option.
|
||||
pub fn valid_bottle_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& !name.starts_with('-')
|
||||
&& !name.contains(['/', '\\'])
|
||||
&& !name.chars().any(char::is_control)
|
||||
&& name != "."
|
||||
&& name != ".."
|
||||
}
|
||||
|
||||
pub fn rosetta_runs_x86_64() -> bool {
|
||||
crate::cmdutil::run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some()
|
||||
}
|
||||
|
||||
pub fn gather(bottle: Option<&str>, wine: Option<(String, &Path)>, min_start_free: u8) -> Facts {
|
||||
Facts {
|
||||
host_arch: std::env::consts::ARCH,
|
||||
crossover: wine.map(|(v, p)| (v, p.to_path_buf())),
|
||||
rosetta_runs_x86_64: rosetta_runs_x86_64(),
|
||||
bottle: bottle.map(|b| (b.to_string(), crate::run::bottle_prefix(b))),
|
||||
free_percent: crate::memory::free_percentage(),
|
||||
min_start_free,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_json(checks: &[Check]) -> Json {
|
||||
Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-doctor/0")),
|
||||
("ready", Json::Bool(checks.iter().all(|c| c.ok))),
|
||||
(
|
||||
"checks",
|
||||
Json::Arr(
|
||||
checks
|
||||
.iter()
|
||||
.map(|c| {
|
||||
Json::obj(vec![
|
||||
("name", Json::str(c.name)),
|
||||
("ok", Json::Bool(c.ok)),
|
||||
("detail", Json::str(c.detail.clone())),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn failing(checks: &[Check]) -> Vec<&str> {
|
||||
checks.iter().filter(|c| !c.ok).map(|c| c.name).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_pieces_are_named() {
|
||||
let f = Facts {
|
||||
host_arch: "aarch64",
|
||||
crossover: None,
|
||||
rosetta_runs_x86_64: false,
|
||||
bottle: Some(("nope".into(), "/nonexistent/nope".into())),
|
||||
free_percent: Some(10),
|
||||
min_start_free: 50,
|
||||
};
|
||||
assert_eq!(
|
||||
failing(&evaluate(&f)),
|
||||
["crossover_installed", "rosetta", "bottle", "free_memory"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_synthetic_environment_passes() {
|
||||
let dir = std::env::temp_dir().join(format!("bx-preflight-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join("bottle/drive_c")).unwrap();
|
||||
std::fs::write(dir.join("wine"), "").unwrap();
|
||||
std::fs::write(dir.join("wineserver"), "").unwrap();
|
||||
let f = Facts {
|
||||
host_arch: "aarch64",
|
||||
crossover: Some(("1.0".into(), dir.join("wine"))),
|
||||
rosetta_runs_x86_64: true,
|
||||
bottle: Some(("bottle".into(), dir.join("bottle"))),
|
||||
free_percent: Some(80),
|
||||
min_start_free: 50,
|
||||
};
|
||||
assert!(failing(&evaluate(&f)).is_empty());
|
||||
std::fs::write(dir.join("bottle/.betterxen-session"), "pid=123").unwrap();
|
||||
assert_eq!(failing(&evaluate(&f)), ["bottle_session"]);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bottle_names_that_are_paths_or_options_are_invalid() {
|
||||
for bad in ["", "..", ".", "a/b", "a\\b", "a\nb", "--bottle"] {
|
||||
assert!(!valid_bottle_name(bad), "{bad}");
|
||||
}
|
||||
assert!(valid_bottle_name("betterxen-test"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Exclusive report creation: previous evidence is never replaced.
|
||||
|
||||
use crate::json::Json;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Save a run or benchmark report under a unique name, reporting all I/O errors.
|
||||
pub fn save(dir: &Path, kind: &str, report: &Json) -> io::Result<PathBuf> {
|
||||
if !matches!(kind, "run" | "bench") {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"unknown report kind",
|
||||
));
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(io::Error::other)?
|
||||
.as_nanos();
|
||||
let bytes = report.render();
|
||||
loop {
|
||||
let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let path = dir.join(format!(
|
||||
"{kind}-{nanos}-{}-{sequence}.json",
|
||||
std::process::id()
|
||||
));
|
||||
match write_new(&path, bytes.as_bytes(), |file, bytes| file.write_all(bytes)) {
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
Ok(()) => return Ok(path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_new(
|
||||
path: &Path,
|
||||
bytes: &[u8],
|
||||
write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
|
||||
) -> io::Result<()> {
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(path)?;
|
||||
if let Err(error) = write(&mut file, bytes).and_then(|()| file.sync_all()) {
|
||||
drop(file);
|
||||
// Remove only the incomplete file this call exclusively created.
|
||||
return match std::fs::remove_file(path) {
|
||||
Ok(()) => Err(error),
|
||||
Err(cleanup) => Err(io::Error::new(
|
||||
error.kind(),
|
||||
format!(
|
||||
"{error}; cannot remove incomplete report {}: {cleanup}",
|
||||
path.display()
|
||||
),
|
||||
)),
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn directory() -> PathBuf {
|
||||
let id = SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("bx-records-{}-{id}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_run_and_bench_reports_preserve_prior_evidence() {
|
||||
let dir = directory();
|
||||
std::fs::write(dir.join("bench.json"), "previous evidence").unwrap();
|
||||
let first = save(&dir, "run", &Json::str("first")).unwrap();
|
||||
let second = save(&dir, "run", &Json::str("second")).unwrap();
|
||||
let bench1 = save(&dir, "bench", &Json::str("bench one")).unwrap();
|
||||
let bench2 = save(&dir, "bench", &Json::str("bench two")).unwrap();
|
||||
assert_ne!(first, second);
|
||||
assert_ne!(bench1, bench2);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(first).unwrap(),
|
||||
Json::str("first").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(second).unwrap(),
|
||||
Json::str("second").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(bench1).unwrap(),
|
||||
Json::str("bench one").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(bench2).unwrap(),
|
||||
Json::str("bench two").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("bench.json")).unwrap(),
|
||||
"previous evidence"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_destination_is_never_truncated() {
|
||||
let dir = directory();
|
||||
let path = dir.join("record.json");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
let error =
|
||||
write_new(&path, b"replacement", |file, bytes| file.write_all(bytes)).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "original");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_directory_is_an_error() {
|
||||
let dir = directory();
|
||||
let path = dir.join("not-a-directory");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
assert!(save(&path, "run", &Json::Null).is_err());
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "original");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_write_failure_is_reported_and_incomplete_file_removed() {
|
||||
let dir = directory();
|
||||
let path = dir.join("record.json");
|
||||
let error = write_new(&path, b"a complete report", |file, _| {
|
||||
file.write_all(b"partial")?;
|
||||
Err(io::Error::other("injected write failure"))
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("injected write failure"));
|
||||
assert!(!path.exists());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,128 @@
|
||||
//! Coordinate BetterXen runners for one bottle. This does not lock out CrossOver's UI or
|
||||
//! other launchers: maintainers must dedicate the bottle to BetterXen tests.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct BottleSession {
|
||||
file: File,
|
||||
}
|
||||
|
||||
impl BottleSession {
|
||||
pub fn acquire(prefix: &Path, recovery: bool) -> Result<Self, String> {
|
||||
let path = prefix.join(".betterxen-session");
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.mode(0o600)
|
||||
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||
let metadata = file.metadata().map_err(|e| e.to_string())?;
|
||||
// SAFETY: geteuid takes no pointers and has no memory preconditions.
|
||||
let uid = unsafe { libc::geteuid() };
|
||||
if !metadata.is_file() || metadata.nlink() != 1 || metadata.uid() != uid {
|
||||
return Err(format!(
|
||||
"{} must be a regular, singly linked file owned by the current user",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
// SAFETY: the descriptor remains owned by `file`; flock changes no Rust memory.
|
||||
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
|
||||
return Err(
|
||||
"bottle has an active BetterXen runner; stop that runner with SIGTERM first".into(),
|
||||
);
|
||||
}
|
||||
let mut previous = String::new();
|
||||
Read::by_ref(&mut file)
|
||||
.take(4096)
|
||||
.read_to_string(&mut previous)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !recovery && !previous.is_empty() {
|
||||
return Err(format!(
|
||||
"bottle has an unfinished session ({previous:?}); run `bx-cli stop --bottle B` (or `--prefix P`) before another run"
|
||||
));
|
||||
}
|
||||
file.set_len(0).map_err(|e| e.to_string())?;
|
||||
file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
|
||||
writeln!(file, "pid={} recovery={recovery}", std::process::id())
|
||||
.map_err(|e| e.to_string())?;
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
Ok(Self { file })
|
||||
}
|
||||
|
||||
/// Clear only after supervision or explicit bottle recovery completed successfully.
|
||||
pub fn complete(&mut self) -> Result<(), String> {
|
||||
self.file
|
||||
.set_len(0)
|
||||
.and_then(|()| self.file.sync_all())
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// The kernel releases the lock on close, including SIGKILL. Without `complete`, the
|
||||
// nonempty marker survives so a new runner cannot hide a surviving guest.
|
||||
impl Drop for BottleSession {
|
||||
fn drop(&mut self) {
|
||||
// A concurrent fork briefly inherits the open file description until exec closes
|
||||
// its CLOEXEC descriptor. Explicit unlock prevents that transient child reference
|
||||
// from keeping a completed parent session locked after this object is dropped.
|
||||
// SAFETY: the descriptor is still owned and open; flock changes no Rust memory.
|
||||
unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn active_and_abandoned_sessions_require_distinct_recovery() {
|
||||
let dir = std::env::temp_dir().join(format!("bx-session-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let first = BottleSession::acquire(&dir, false).unwrap();
|
||||
assert!(BottleSession::acquire(&dir, false).is_err());
|
||||
assert!(BottleSession::acquire(&dir, true).is_err());
|
||||
drop(first); // models a supervisor disappearing without completing cleanup
|
||||
assert!(BottleSession::acquire(&dir, false).is_err());
|
||||
BottleSession::acquire(&dir, true)
|
||||
.unwrap()
|
||||
.complete()
|
||||
.unwrap();
|
||||
BottleSession::acquire(&dir, false)
|
||||
.unwrap()
|
||||
.complete()
|
||||
.unwrap();
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_symlink_does_not_truncate_its_target() {
|
||||
let dir = std::env::temp_dir().join(format!("bx-session-link-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let target = dir.join("valuable");
|
||||
std::fs::write(&target, "preserve me").unwrap();
|
||||
std::os::unix::fs::symlink(&target, dir.join(".betterxen-session")).unwrap();
|
||||
assert!(BottleSession::acquire(&dir, true).is_err());
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), "preserve me");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hardlinked_marker_is_never_truncated_during_recovery() {
|
||||
let dir = std::env::temp_dir().join(format!("bx-session-hardlink-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let target = dir.join("valuable");
|
||||
std::fs::write(&target, "preserve me").unwrap();
|
||||
std::fs::hard_link(&target, dir.join(".betterxen-session")).unwrap();
|
||||
assert!(BottleSession::acquire(&dir, true).is_err());
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), "preserve me");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -13,165 +13,10 @@ pub struct TraceSummary {
|
||||
pub clwb_events: usize,
|
||||
/// Highest cumulative counter in the sampled CLWB records, if available.
|
||||
pub clwb_trap_lower_bound: Option<u64>,
|
||||
/// Sampled `<kind>_trapped` records for the other AMD-only instructions the
|
||||
/// VEH emulates (`clzero`, `monitorx`, `mwaitx`, `rdpru`, `extrq`, `insertq`).
|
||||
pub amd_traps: BTreeMap<String, TrapCount>,
|
||||
pub adx_errors: usize,
|
||||
pub unhandled_exceptions: Vec<UnhandledException>,
|
||||
pub unimpl_apis: BTreeMap<String, usize>,
|
||||
pub unimpl_vtables: BTreeMap<String, usize>,
|
||||
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
|
||||
pub shader_gate: ShaderGateSummary,
|
||||
/// `shader_d3dmetal_gap` records: pipelines D3DMetal creates but does not run (#453).
|
||||
pub shader_gaps: Vec<ShaderGap>,
|
||||
/// Those same gap records grouped by `(pso, stage)`, in first-seen order (#590).
|
||||
pub shader_gap_groups: Vec<ShaderGapGroup>,
|
||||
/// Gap records that carried no `pso` or no `stage` (or an empty value for one), so
|
||||
/// they are grouped under `unknown`. Counted here so the group counts reconcile
|
||||
/// with [`TraceSummary::shader_gaps`].
|
||||
pub shader_gaps_missing_identity: usize,
|
||||
/// Gap records that carried no `wave_lanes_min` or no `atomic64_flags` (or an empty
|
||||
/// value for one). Counted here rather than dropped or assumed.
|
||||
pub shader_gaps_missing_constraints: usize,
|
||||
/// `shader_bridge_missing` messages, in log order.
|
||||
pub shader_bridge_missing: Vec<String>,
|
||||
}
|
||||
|
||||
/// One `(pso, stage)` group of `shader_d3dmetal_gap` records (#590).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGapGroup {
|
||||
/// The emitted `pso=` value, or `None` when the record carried none (rendered as
|
||||
/// `unknown`).
|
||||
pub pso: Option<String>,
|
||||
/// The emitted `stage=` value, or `None` when the record carried none.
|
||||
pub stage: Option<String>,
|
||||
/// How many gap records this `(pso, stage)` pair covers.
|
||||
pub count: usize,
|
||||
/// The distinct `(wave_lanes_min, atomic64_flags)` pairs seen for this pair, in
|
||||
/// first-seen order. Two pipelines of the same kind and stage can need different
|
||||
/// wave widths or atomic features, so a group keeps each constraint set rather than
|
||||
/// reporting only the first and losing the rest.
|
||||
pub variants: Vec<ShaderGapVariant>,
|
||||
}
|
||||
|
||||
/// The constraints carried by one or more records of a [`ShaderGapGroup`].
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGapVariant {
|
||||
pub wave_lanes_min: Option<String>,
|
||||
pub atomic64_flags: Option<String>,
|
||||
/// How many records in the group carried exactly these constraints.
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// Aggregated `shader_gate` records. Decisions, kinds and stages are keyed by
|
||||
/// their emitted string so unknown values are counted rather than dropped.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGateSummary {
|
||||
pub total: usize,
|
||||
/// Gate records whose `detail` could not be parsed as `key=value` pairs.
|
||||
pub unparsed: usize,
|
||||
/// Parsed gate records that carry no `decision` field, so they appear in no
|
||||
/// `decisions` bucket. Counted here so the decision counts can be
|
||||
/// reconciled against `total` (#497 review). `kind` is legitimately absent
|
||||
/// on unclassified records and is not counted here.
|
||||
pub missing_decision: usize,
|
||||
pub decisions: BTreeMap<String, usize>,
|
||||
pub kinds: BTreeMap<String, usize>,
|
||||
pub stages: BTreeMap<String, usize>,
|
||||
/// Individual gate records, in log order.
|
||||
pub records: Vec<ShaderGateRecord>,
|
||||
}
|
||||
|
||||
/// One `shader_gate` record. Fields absent from the emitted `detail` (for
|
||||
/// example on unclassified records) are `None`; `atomic64` may be `Some("")`.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGateRecord {
|
||||
pub pso: Option<String>,
|
||||
pub stage: Option<String>,
|
||||
pub decision: Option<String>,
|
||||
pub hr: Option<String>,
|
||||
pub kind: Option<String>,
|
||||
pub shader_stage: Option<String>,
|
||||
pub sm: Option<String>,
|
||||
pub bytes: Option<String>,
|
||||
pub dxil: Option<String>,
|
||||
pub accc: Option<String>,
|
||||
pub sfi0: Option<String>,
|
||||
pub wave_ops: Option<String>,
|
||||
pub int64_ops: Option<String>,
|
||||
pub atomic64: Option<String>,
|
||||
pub wave_lanes: Option<String>,
|
||||
}
|
||||
|
||||
/// One `shader_d3dmetal_gap` record.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGap {
|
||||
pub pso: Option<String>,
|
||||
pub stage: Option<String>,
|
||||
pub wave_lanes_min: Option<String>,
|
||||
pub atomic64_flags: Option<String>,
|
||||
}
|
||||
|
||||
/// Tokenize a `detail` string of space-separated `key=value` pairs.
|
||||
///
|
||||
/// Only the `shader_d3dmetal_gap` record appends free text after its pairs
|
||||
/// (`... atomic64_flags=0x400000: D3DMetal ...`), so `stop_at_free_text`
|
||||
/// selects how a token without `=` is treated:
|
||||
///
|
||||
/// - `true` (gap records): the token ends the key=value section.
|
||||
/// - `false` (`shader_gate` records): a stray token is skipped and parsing
|
||||
/// continues, so one unexpected word cannot silently drop every later
|
||||
/// field (#497 review).
|
||||
///
|
||||
/// Values never contain spaces, so `atomic64=` followed by a space yields an
|
||||
/// empty value.
|
||||
/// Splits a log detail string into `key=value` pairs.
|
||||
///
|
||||
/// `stop_at_free_text` exists for records that end with prose after their
|
||||
/// fields (`shader_d3dmetal_gap` ends in a sentence), where the first token
|
||||
/// without `=` marks the end of the structured part.
|
||||
///
|
||||
/// For `shader_gate` the whole string is structured, so a token without `=`
|
||||
/// is skipped rather than treated as the end. Stopping there would silently
|
||||
/// drop every later field while the record still counted as parsed: with
|
||||
/// `atomic64=typed, raw, wave_lanes=64-64`, a `break` loses `wave_lanes`,
|
||||
/// whereas a `continue` keeps it. The emitter writes no spaces inside a value
|
||||
/// today, so this is robustness against a future value containing one, not a
|
||||
/// fix for current output.
|
||||
fn parse_key_values(detail: &str, stop_at_free_text: bool) -> Vec<(&str, &str)> {
|
||||
let mut pairs = Vec::new();
|
||||
for token in detail.split_ascii_whitespace() {
|
||||
match token.split_once('=') {
|
||||
Some((key, value)) if !key.is_empty() => pairs.push((key, value)),
|
||||
_ if stop_at_free_text => break,
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
pairs
|
||||
}
|
||||
|
||||
/// Sampled trap records of one instruction kind.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct TrapCount {
|
||||
pub events: usize,
|
||||
/// Highest cumulative counter in the sampled records, if available.
|
||||
pub lower_bound: Option<u64>,
|
||||
}
|
||||
|
||||
const AMD_TRAP_EVENTS: [(&str, &str); 6] = [
|
||||
("clzero_trapped", "clzero"),
|
||||
("monitorx_trapped", "monitorx"),
|
||||
("mwaitx_trapped", "mwaitx"),
|
||||
("rdpru_trapped", "rdpru"),
|
||||
("extrq_trapped", "extrq"),
|
||||
("insertq_trapped", "insertq"),
|
||||
];
|
||||
|
||||
fn sampled_counter(detail: &str) -> Option<u64> {
|
||||
detail
|
||||
.split_ascii_whitespace()
|
||||
.find_map(|field| field.strip_prefix("total_traps="))
|
||||
.and_then(|count| count.parse::<u64>().ok())
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -190,124 +35,6 @@ fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
Some(&rest[..end])
|
||||
}
|
||||
|
||||
fn get_field<'a>(pairs: &[(&'a str, &'a str)], key: &str) -> Option<String> {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| (*v).to_owned())
|
||||
}
|
||||
|
||||
fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
|
||||
let gate = &mut summary.shader_gate;
|
||||
gate.total += 1;
|
||||
let pairs = parse_key_values(detail, false);
|
||||
if pairs.is_empty() {
|
||||
gate.unparsed += 1;
|
||||
return;
|
||||
}
|
||||
let record = ShaderGateRecord {
|
||||
pso: get_field(&pairs, "pso"),
|
||||
stage: get_field(&pairs, "stage"),
|
||||
decision: get_field(&pairs, "decision"),
|
||||
hr: get_field(&pairs, "hr"),
|
||||
kind: get_field(&pairs, "kind"),
|
||||
shader_stage: get_field(&pairs, "shader_stage"),
|
||||
sm: get_field(&pairs, "sm"),
|
||||
bytes: get_field(&pairs, "bytes"),
|
||||
dxil: get_field(&pairs, "dxil"),
|
||||
accc: get_field(&pairs, "accc"),
|
||||
sfi0: get_field(&pairs, "sfi0"),
|
||||
wave_ops: get_field(&pairs, "wave_ops"),
|
||||
int64_ops: get_field(&pairs, "int64_ops"),
|
||||
atomic64: get_field(&pairs, "atomic64"),
|
||||
wave_lanes: get_field(&pairs, "wave_lanes"),
|
||||
};
|
||||
match &record.decision {
|
||||
Some(decision) => *gate.decisions.entry(decision.clone()).or_insert(0) += 1,
|
||||
None => gate.missing_decision += 1,
|
||||
}
|
||||
if let Some(kind) = &record.kind {
|
||||
*gate.kinds.entry(kind.clone()).or_insert(0) += 1;
|
||||
}
|
||||
if let Some(stage) = &record.stage {
|
||||
*gate.stages.entry(stage.clone()).or_insert(0) += 1;
|
||||
}
|
||||
gate.records.push(record);
|
||||
}
|
||||
|
||||
/// A field value, treating an empty value (`pso= stage=CS`) as absent. The emitter
|
||||
/// always writes a value, so an empty one means the record is malformed, not that the
|
||||
/// pipeline is named "".
|
||||
fn non_empty(value: Option<String>) -> Option<String> {
|
||||
value.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Adds one gap record to the per-`(pso, stage)` grouping, keeping first-seen order.
|
||||
///
|
||||
/// Nothing here panics: a record missing `pso`, `stage`, `wave_lanes_min` or
|
||||
/// `atomic64_flags` is grouped under `unknown` (and counted), never dropped or guessed.
|
||||
fn record_shader_gap_group(groups: &mut TraceSummary, gap: &ShaderGap) {
|
||||
let pso = non_empty(gap.pso.clone());
|
||||
let stage = non_empty(gap.stage.clone());
|
||||
let wave_lanes_min = non_empty(gap.wave_lanes_min.clone());
|
||||
let atomic64_flags = non_empty(gap.atomic64_flags.clone());
|
||||
if pso.is_none() || stage.is_none() {
|
||||
groups.shader_gaps_missing_identity += 1;
|
||||
}
|
||||
if wave_lanes_min.is_none() || atomic64_flags.is_none() {
|
||||
groups.shader_gaps_missing_constraints += 1;
|
||||
}
|
||||
|
||||
// The group list is small (one entry per affected pipeline stage), so a linear scan
|
||||
// keeps first-seen order without a second index to keep in sync.
|
||||
let group_index = match groups
|
||||
.shader_gap_groups
|
||||
.iter()
|
||||
.position(|g| g.pso == pso && g.stage == stage)
|
||||
{
|
||||
Some(index) => index,
|
||||
None => {
|
||||
groups.shader_gap_groups.push(ShaderGapGroup {
|
||||
pso,
|
||||
stage,
|
||||
count: 0,
|
||||
variants: Vec::new(),
|
||||
});
|
||||
groups.shader_gap_groups.len() - 1
|
||||
}
|
||||
};
|
||||
let group = &mut groups.shader_gap_groups[group_index];
|
||||
group.count += 1;
|
||||
match group
|
||||
.variants
|
||||
.iter()
|
||||
.position(|v| v.wave_lanes_min == wave_lanes_min && v.atomic64_flags == atomic64_flags)
|
||||
{
|
||||
Some(index) => group.variants[index].count += 1,
|
||||
None => group.variants.push(ShaderGapVariant {
|
||||
wave_lanes_min,
|
||||
atomic64_flags,
|
||||
count: 1,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
|
||||
let pairs = parse_key_values(detail, true);
|
||||
// The emitter appends `: D3DMetal creates such pipelines ...` directly
|
||||
// after the flags value, so strip the trailing colon.
|
||||
let atomic64_flags = get_field(&pairs, "atomic64_flags")
|
||||
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
|
||||
let gap = ShaderGap {
|
||||
pso: get_field(&pairs, "pso"),
|
||||
stage: get_field(&pairs, "stage"),
|
||||
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
|
||||
atomic64_flags,
|
||||
};
|
||||
record_shader_gap_group(summary, &gap);
|
||||
summary.shader_gaps.push(gap);
|
||||
}
|
||||
|
||||
pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
let mut summary = TraceSummary::default();
|
||||
for line in input.lines() {
|
||||
@@ -321,19 +48,11 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
match event {
|
||||
"clwb_trapped" => {
|
||||
summary.clwb_events += 1;
|
||||
summary.clwb_trap_lower_bound =
|
||||
summary.clwb_trap_lower_bound.max(sampled_counter(detail));
|
||||
}
|
||||
_ if AMD_TRAP_EVENTS.iter().any(|(e, _)| *e == event) => {
|
||||
let name = AMD_TRAP_EVENTS.iter().find(|(e, _)| *e == event).unwrap().1;
|
||||
let entry = summary.amd_traps.entry(name.to_string()).or_default();
|
||||
entry.events += 1;
|
||||
entry.lower_bound = entry.lower_bound.max(sampled_counter(detail));
|
||||
}
|
||||
"shader_gate" => record_shader_gate(&mut summary, detail),
|
||||
"shader_d3dmetal_gap" => record_shader_gap(&mut summary, detail),
|
||||
"shader_bridge_missing" => {
|
||||
summary.shader_bridge_missing.push(detail.to_owned());
|
||||
let sample = detail
|
||||
.split_ascii_whitespace()
|
||||
.find_map(|field| field.strip_prefix("total_traps="))
|
||||
.and_then(|count| count.parse::<u64>().ok());
|
||||
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
|
||||
}
|
||||
"adx_illegal_instruction" => summary.adx_errors += 1,
|
||||
"unhandled_exception" => {
|
||||
@@ -446,396 +165,4 @@ mod tests {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_amd_only_traps_per_kind() {
|
||||
let summary = summarize_jsonl(
|
||||
r#"{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=1"}
|
||||
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=2"}
|
||||
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=4"}
|
||||
{"event":"extrq_trapped","detail":"rip=0x2000 len=5 total_traps=1"}
|
||||
{"event":"rdpru_trapped","detail":"rip=0x3000 len=3"}"#,
|
||||
);
|
||||
assert_eq!(
|
||||
summary.amd_traps["clzero"],
|
||||
TrapCount {
|
||||
events: 3,
|
||||
lower_bound: Some(4)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
summary.amd_traps["extrq"],
|
||||
TrapCount {
|
||||
events: 1,
|
||||
lower_bound: Some(1)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
summary.amd_traps["rdpru"],
|
||||
TrapCount {
|
||||
events: 1,
|
||||
lower_bound: None
|
||||
}
|
||||
);
|
||||
assert!(!summary.amd_traps.contains_key("mwaitx"));
|
||||
assert_eq!(summary.clwb_events, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_full_pass_dxil_gate_record() {
|
||||
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert_eq!(summary.shader_gate.unparsed, 0);
|
||||
assert_eq!(summary.shader_gate.decisions["pass_dxil"], 1);
|
||||
assert_eq!(summary.shader_gate.kinds["dxil"], 1);
|
||||
assert_eq!(summary.shader_gate.stages["CS"], 1);
|
||||
assert_eq!(summary.shader_gate.records.len(), 1);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(r.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
|
||||
assert_eq!(r.hr.as_deref(), Some("0x00000000"));
|
||||
assert_eq!(r.kind.as_deref(), Some("dxil"));
|
||||
assert_eq!(r.shader_stage.as_deref(), Some("5"));
|
||||
assert_eq!(r.sm.as_deref(), Some("6.6"));
|
||||
assert_eq!(r.bytes.as_deref(), Some("1234"));
|
||||
assert_eq!(r.dxil.as_deref(), Some("800"));
|
||||
assert_eq!(r.accc.as_deref(), Some("0"));
|
||||
assert_eq!(r.sfi0.as_deref(), Some("0x4000"));
|
||||
assert_eq!(r.wave_ops.as_deref(), Some("1"));
|
||||
assert_eq!(r.int64_ops.as_deref(), Some("0"));
|
||||
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_reject_accc_only_gate_record() {
|
||||
let log = r#"{"ts_ms":12,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_gate","detail":"pso=graphics stage=VS decision=reject_accc_only hr=0x80004001 kind=accc_only shader_stage=0 sm=6.0 bytes=2048 dxil=0 accc=512 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=none"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert_eq!(summary.shader_gate.decisions["reject_accc_only"], 1);
|
||||
assert_eq!(summary.shader_gate.kinds["accc_only"], 1);
|
||||
assert_eq!(summary.shader_gate.stages["VS"], 1);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.hr.as_deref(), Some("0x80004001"));
|
||||
assert_eq!(r.sm.as_deref(), Some("6.0"));
|
||||
assert_eq!(r.accc.as_deref(), Some("512"));
|
||||
assert_eq!(r.atomic64.as_deref(), Some(""));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_unclassified_gate_record_without_kind() {
|
||||
let log = r#"{"ts_ms":14,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_unclassified hr=0x00000000 bytes=4096"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert_eq!(summary.shader_gate.decisions["pass_unclassified"], 1);
|
||||
assert_eq!(summary.shader_gate.stages["CS"], 1);
|
||||
assert!(summary.shader_gate.kinds.is_empty());
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.bytes.as_deref(), Some("4096"));
|
||||
assert_eq!(r.kind, None);
|
||||
assert_eq!(r.sm, None);
|
||||
assert_eq!(r.dxil, None);
|
||||
assert_eq!(r.atomic64, None);
|
||||
assert_eq!(r.wave_lanes, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_d3dmetal_gap_with_free_text_suffix() {
|
||||
let log = r#"{"ts_ms":16,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gaps.len(), 1);
|
||||
let gap = &summary.shader_gaps[0];
|
||||
assert_eq!(gap.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(gap.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(gap.wave_lanes_min.as_deref(), Some("64"));
|
||||
assert_eq!(gap.atomic64_flags.as_deref(), Some("0x400000"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_shader_bridge_missing_messages() {
|
||||
let log = r#"{"ts_ms":18,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_bridge_missing","detail":"bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, ACCC-only refused"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_bridge_missing.len(), 1);
|
||||
assert!(summary.shader_bridge_missing[0].contains("not found beside d3d12_xs.dll"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_shader_gate_detail_is_counted_not_dropped() {
|
||||
for detail in ["", "garbage", "=value", " "] {
|
||||
let log = format!(
|
||||
"{{\"ts_ms\":20,\"tid\":1,\"level\":\"INFO\",\"sub\":\"d3d12_xs\",\"event\":\"shader_gate\",\"detail\":\"{detail}\"}}"
|
||||
);
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gate.total, 1, "detail={detail:?}");
|
||||
assert_eq!(summary.shader_gate.unparsed, 1, "detail={detail:?}");
|
||||
assert!(summary.shader_gate.records.is_empty(), "detail={detail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_atomic64_value_is_preserved() {
|
||||
let log = r#"{"ts_ms":22,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=100 dxil=64 accc=0 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=0-4294967295"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.atomic64.as_deref(), Some(""));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("0-4294967295"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stray_token_does_not_drop_later_gate_fields() {
|
||||
// #497 review point 1: one value containing a space must not turn every
|
||||
// later field into None.
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil atomic64=typed, raw wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
|
||||
assert_eq!(summary.shader_gate.unparsed, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_atomic64_flags_are_parsed() {
|
||||
// #497 review point 1: the emitter concatenates flags with no separator,
|
||||
// but two flags must round-trip if they ever are spaced.
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil kind=dxil atomic64=typed, groupshared, wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gate_record_without_a_decision_is_counted_as_missing() {
|
||||
// #497 review point 2: decision counts must reconcile against total.
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert_eq!(summary.shader_gate.missing_decision, 1);
|
||||
assert_eq!(summary.shader_gate.unparsed, 0);
|
||||
assert!(summary.shader_gate.decisions.is_empty());
|
||||
assert_eq!(summary.shader_gate.stages["CS"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decision_buckets_plus_missing_reconcile_with_total() {
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil bytes=1"}
|
||||
{"event":"shader_gate","detail":"pso=compute stage=CS"}
|
||||
{"event":"shader_gate","detail":"garbage"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let gate = &summary.shader_gate;
|
||||
let bucketed: usize = gate.decisions.values().sum();
|
||||
assert_eq!(gate.total, 3);
|
||||
assert_eq!(gate.unparsed, 1);
|
||||
assert_eq!(gate.missing_decision, 1);
|
||||
assert_eq!(bucketed + gate.unparsed + gate.missing_decision, gate.total);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_decisions_and_kinds_are_counted() {
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=some_future_decision hr=0x00000000 kind=some_future_kind bytes=1"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.decisions["some_future_decision"], 1);
|
||||
assert_eq!(summary.shader_gate.kinds["some_future_kind"], 1);
|
||||
}
|
||||
|
||||
/// A stray token must not end the structured part of a `shader_gate`
|
||||
/// record: if it did, every later field would silently become `None`
|
||||
/// while the record still counted as parsed.
|
||||
#[test]
|
||||
fn a_record_without_a_decision_is_counted_as_missing() {
|
||||
let mut summary = TraceSummary::default();
|
||||
record_shader_gate(&mut summary, "pso=graphics stage=pixel");
|
||||
let gate = &summary.shader_gate;
|
||||
assert_eq!(gate.total, 1);
|
||||
assert_eq!(gate.unparsed, 0);
|
||||
assert_eq!(gate.missing_decision, 1);
|
||||
assert!(gate.decisions.is_empty());
|
||||
}
|
||||
|
||||
/// The free-text path is the opposite: `shader_d3dmetal_gap` ends in a
|
||||
/// sentence, so the first token without `=` ends the structured part.
|
||||
#[test]
|
||||
fn free_text_ends_the_structured_part_of_a_gap_record() {
|
||||
let pairs = parse_key_values("pso=graphics stage=pixel and then some prose", true);
|
||||
assert_eq!(pairs.len(), 2);
|
||||
assert_eq!(pairs[1], ("stage", "pixel"));
|
||||
}
|
||||
|
||||
/// #590: two gaps on different stages must stay two groups, in first-seen order, each
|
||||
/// with its own wave width and 64-bit-atomic flags.
|
||||
#[test]
|
||||
fn groups_gaps_on_different_stages_separately_in_first_seen_order() {
|
||||
// Same pso, different stages: grouping on pso alone would collapse these, so the
|
||||
// test discriminates the (pso, stage) key rather than only the pso.
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gaps.len(), 3);
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 3);
|
||||
|
||||
let first = &summary.shader_gap_groups[0];
|
||||
assert_eq!(first.pso.as_deref(), Some("graphics"));
|
||||
assert_eq!(first.stage.as_deref(), Some("VS"));
|
||||
assert_eq!(first.count, 1);
|
||||
assert_eq!(
|
||||
first.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x0".into()),
|
||||
count: 1,
|
||||
}]
|
||||
);
|
||||
|
||||
let second = &summary.shader_gap_groups[1];
|
||||
assert_eq!(second.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(second.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(second.count, 1);
|
||||
|
||||
// A second stage of the *same* pso stays its own group, which is what separates a
|
||||
// (pso, stage) key from a pso-only key.
|
||||
let third = &summary.shader_gap_groups[2];
|
||||
assert_eq!(third.pso.as_deref(), Some("graphics"));
|
||||
assert_eq!(third.stage.as_deref(), Some("PS"));
|
||||
assert_eq!(third.count, 1);
|
||||
}
|
||||
|
||||
/// #590: the same `(pso, stage)` twice is one group with a count of two, even when the
|
||||
/// identical records are not adjacent.
|
||||
#[test]
|
||||
fn groups_identical_gaps_together() {
|
||||
let record = r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let other = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=32 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let log = format!("{record}\n{other}\n{record}\n");
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gaps.len(), 3);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 2);
|
||||
let compute = &summary.shader_gap_groups[0];
|
||||
assert_eq!(compute.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(compute.count, 2);
|
||||
assert_eq!(
|
||||
compute.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x400000".into()),
|
||||
count: 2,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary.shader_gap_groups[1].count, 1);
|
||||
// Every record is in exactly one group.
|
||||
let grouped: usize = summary.shader_gap_groups.iter().map(|g| g.count).sum();
|
||||
assert_eq!(grouped, summary.shader_gaps.len());
|
||||
}
|
||||
|
||||
/// #590: one pipeline kind and stage can need different wave widths or atomic
|
||||
/// features, so a group keeps every distinct constraint set, not only the first.
|
||||
#[test]
|
||||
fn one_group_keeps_each_distinct_constraint_set() {
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 1);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.count, 3);
|
||||
assert_eq!(
|
||||
group.variants,
|
||||
[
|
||||
ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x0".into()),
|
||||
count: 2,
|
||||
},
|
||||
ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x400000".into()),
|
||||
count: 1,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
}
|
||||
|
||||
/// #590: a gap record with a missing or empty field must not panic. It is grouped
|
||||
/// under `unknown` and counted, never dropped or guessed.
|
||||
#[test]
|
||||
fn a_malformed_gap_record_is_grouped_under_unknown_and_counted() {
|
||||
for (detail, missing_identity, missing_constraints) in [
|
||||
("", 1, 1),
|
||||
("garbage", 1, 1),
|
||||
("pso=compute", 1, 1),
|
||||
("stage=CS", 1, 1),
|
||||
(
|
||||
"pso= stage=CS wave_lanes_min=64 atomic64_flags=0x400000",
|
||||
1,
|
||||
0,
|
||||
),
|
||||
("pso=compute stage=CS", 0, 1),
|
||||
(
|
||||
"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=",
|
||||
0,
|
||||
1,
|
||||
),
|
||||
] {
|
||||
let log = format!(r#"{{"event":"shader_d3dmetal_gap","detail":"{detail}"}}"#);
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gaps.len(), 1, "detail={detail:?}");
|
||||
assert_eq!(
|
||||
summary.shader_gap_groups.len(),
|
||||
1,
|
||||
"detail={detail:?} lost its record"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.shader_gaps_missing_identity, missing_identity,
|
||||
"detail={detail:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.shader_gaps_missing_constraints, missing_constraints,
|
||||
"detail={detail:?}"
|
||||
);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.count, 1, "detail={detail:?}");
|
||||
let recorded: usize = group.variants.iter().map(|v| v.count).sum();
|
||||
assert_eq!(recorded, 1, "detail={detail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #590: the fields a malformed record does carry are still reported.
|
||||
#[test]
|
||||
fn a_partly_malformed_gap_record_keeps_the_fields_it_has() {
|
||||
let log =
|
||||
r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(group.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(
|
||||
group.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: None,
|
||||
count: 1,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 1);
|
||||
}
|
||||
|
||||
/// #590: a run with no gap records produces no groups and no missing-field counts, so
|
||||
/// the trace renders as it did before the grouping existed.
|
||||
#[test]
|
||||
fn a_run_with_no_gaps_has_no_groups() {
|
||||
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert!(summary.shader_gaps.is_empty());
|
||||
assert!(summary.shader_gap_groups.is_empty());
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
[toolchain]
|
||||
channel = "1.100.0"
|
||||
profile = "minimal"
|
||||
components = ["rustfmt", "clippy"]
|
||||
targets = ["aarch64-apple-darwin"]
|
||||
+21
-117
@@ -4,15 +4,11 @@
|
||||
Checks only tracked files:
|
||||
1. no merge-conflict markers in tracked text files;
|
||||
2. every relative Markdown link points at a tracked file or directory;
|
||||
3. every fragment (``#heading``) in a Markdown link resolves to a real
|
||||
heading in the target Markdown file, including in-page ``](#foo)``
|
||||
links validated against the same file's headings;
|
||||
4. every workflow file under .github/workflows parses as YAML.
|
||||
3. every workflow file under .github/workflows parses as YAML.
|
||||
|
||||
External URLs (http:, https:, mailto:, //) and bare ``#`` links are not
|
||||
fetched or validated, so the result does not depend on the network.
|
||||
Exit status is 1 when a problem is found. Pass --require-yaml to fail,
|
||||
not skip, when PyYAML is missing.
|
||||
External URLs and in-page anchors are not fetched or validated, so the result
|
||||
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
|
||||
when PyYAML is missing.
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
@@ -21,16 +17,9 @@ from pathlib import Path, PurePosixPath
|
||||
from urllib.parse import unquote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MARKER = re.compile(r"^(<{7}( |$)|\|{7}( |$)|={7}$|>{7}( |$))")
|
||||
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
|
||||
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
|
||||
FENCE = re.compile(r"^\s*(```|~~~)")
|
||||
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
|
||||
# GitHub slugs the rendered heading, so an inline link contributes only its
|
||||
# text: ``## See [ADR](x.md)`` slugs as ``see-adr``, not ``see-adrxmd``.
|
||||
# Link syntax inside a code span stays literal, so those spans are set aside
|
||||
# before substituting and put back afterwards.
|
||||
INLINE_LINK = re.compile(r"(?<!\!)\[([^\]]*)\]\([^)]*\)")
|
||||
CODE_SPAN = re.compile(r"(`+)(.+?)\1")
|
||||
|
||||
|
||||
def tracked():
|
||||
@@ -46,63 +35,6 @@ def text(path):
|
||||
return data.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def _slug(text):
|
||||
"""GitHub-style slug: lowercase, strip non-alnum/-/_/space, spaces -> -."""
|
||||
text = text.lower()
|
||||
text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE)
|
||||
return text.replace(" ", "-")
|
||||
|
||||
|
||||
def _heading_text(text):
|
||||
"""Rendered text of a heading: link text in, code spans left literal."""
|
||||
spans = []
|
||||
|
||||
def stash(match):
|
||||
spans.append(match.group(0))
|
||||
return "\x00%d\x00" % (len(spans) - 1)
|
||||
|
||||
stashed = CODE_SPAN.sub(stash, text)
|
||||
substituted = INLINE_LINK.sub(r"\1", stashed)
|
||||
for index, span in enumerate(spans):
|
||||
substituted = substituted.replace("\x00%d\x00" % index, span)
|
||||
return substituted
|
||||
|
||||
|
||||
def markdown_slugs(body):
|
||||
"""Return the set of GitHub-style heading slugs in a Markdown document.
|
||||
|
||||
Duplicate headings get ``-1``, ``-2``, ... suffixes. Headings inside
|
||||
fenced code blocks are ignored.
|
||||
"""
|
||||
slugs = set()
|
||||
seen = {}
|
||||
in_fence = False
|
||||
for line in body.splitlines():
|
||||
if FENCE.match(line):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
m = HEADING.match(line)
|
||||
if not m:
|
||||
continue
|
||||
base = _slug(_heading_text(m.group(2)))
|
||||
if not base:
|
||||
continue
|
||||
# Advance the numeric suffix until we find a slug that has not
|
||||
# already been emitted. Counting only identical bases is not
|
||||
# enough: a literal heading such as ``Foo-1`` may already own
|
||||
# ``foo-1``, so the next ``Foo`` must become ``foo-2``.
|
||||
count = seen.get(base, 0)
|
||||
slug = base if count == 0 else f"{base}-{count}"
|
||||
while slug in slugs:
|
||||
count += 1
|
||||
slug = f"{base}-{count}"
|
||||
seen[base] = count + 1
|
||||
slugs.add(slug)
|
||||
return slugs
|
||||
|
||||
|
||||
def check_markers(files, problems):
|
||||
for path in files:
|
||||
if path.endswith((".patch", ".diff")):
|
||||
@@ -115,30 +47,9 @@ def check_markers(files, problems):
|
||||
problems.append(f"{path}:{number}: merge conflict marker")
|
||||
|
||||
|
||||
def _resolve_link(path, target):
|
||||
"""Resolve a relative link target to a repo-root-relative POSIX path."""
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def check_links(files, problems):
|
||||
known = set(files)
|
||||
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
|
||||
slug_cache = {}
|
||||
|
||||
def slugs_for(md_path):
|
||||
if md_path not in slug_cache:
|
||||
slug_cache[md_path] = markdown_slugs(text(md_path) or "")
|
||||
return slug_cache[md_path]
|
||||
|
||||
for path in files:
|
||||
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
|
||||
continue
|
||||
@@ -150,31 +61,24 @@ def check_links(files, problems):
|
||||
if in_fence:
|
||||
continue
|
||||
line = re.sub(r"`[^`]*`", "", line)
|
||||
for raw_target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|//)", raw_target, re.I):
|
||||
for target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
|
||||
continue
|
||||
if raw_target == "#":
|
||||
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target:
|
||||
continue
|
||||
fragment = ""
|
||||
if "#" in raw_target:
|
||||
fragment = unquote(raw_target.split("#", 1)[1])
|
||||
target = unquote(raw_target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target and not fragment:
|
||||
continue
|
||||
if target:
|
||||
norm = _resolve_link(path, target)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
continue
|
||||
else:
|
||||
norm = path
|
||||
if fragment and norm.endswith(".md") and norm in known:
|
||||
if fragment not in slugs_for(norm):
|
||||
shown = raw_target
|
||||
problems.append(
|
||||
f"{path}:{number}: broken fragment '#{fragment}' "
|
||||
f"in link '{shown}' (heading not found)"
|
||||
)
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
norm = "/".join(parts)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
|
||||
|
||||
def check_workflows(files, problems, require_yaml):
|
||||
|
||||
@@ -1,296 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for scripts/audit/docs_hygiene.py anchor validation.
|
||||
|
||||
Run with:
|
||||
python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
"""
|
||||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
_MODULE_PATH = Path(__file__).resolve().parent / "docs_hygiene.py"
|
||||
_spec = importlib.util.spec_from_file_location("docs_hygiene", _MODULE_PATH)
|
||||
docs_hygiene = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["docs_hygiene"] = docs_hygiene
|
||||
_spec.loader.exec_module(docs_hygiene)
|
||||
|
||||
|
||||
class SlugTests(unittest.TestCase):
|
||||
def test_basic_slug(self):
|
||||
slugs = docs_hygiene.markdown_slugs("# Hello World\n")
|
||||
self.assertIn("hello-world", slugs)
|
||||
|
||||
def test_strips_punctuation(self):
|
||||
slugs = docs_hygiene.markdown_slugs("## What's new? (2024)\n")
|
||||
self.assertIn("whats-new-2024", slugs)
|
||||
|
||||
def test_keeps_underscore_and_hyphen(self):
|
||||
slugs = docs_hygiene.markdown_slugs("### foo_bar-baz\n")
|
||||
self.assertIn("foo_bar-baz", slugs)
|
||||
|
||||
def test_duplicate_headings(self):
|
||||
body = "# Setup\n\n# Setup\n\n# Setup\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertIn("setup", slugs)
|
||||
self.assertIn("setup-1", slugs)
|
||||
self.assertIn("setup-2", slugs)
|
||||
|
||||
def test_suffix_skips_literal_heading_slug(self):
|
||||
# Regression: counting identical bases alone lets a generated
|
||||
# suffix collide with a literal heading slug, so the third `Foo`
|
||||
# also became `foo-1` and a link to the wrong heading validated.
|
||||
body = "# Foo\n\n# Foo-1\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
|
||||
|
||||
def test_suffix_skips_multiple_literal_heading_slugs(self):
|
||||
body = "# Foo\n\n# Foo-1\n\n# Foo-2\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2", "foo-3", "foo-4"})
|
||||
|
||||
def test_three_identical_headings(self):
|
||||
body = "# Foo\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
|
||||
|
||||
def test_literal_slug_before_duplicates(self):
|
||||
body = "# Foo-1\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo-1", "foo", "foo-2"})
|
||||
|
||||
def test_heading_link_contributes_only_its_text(self):
|
||||
# GitHub slugs the rendered heading, where the link's URL is gone.
|
||||
# Slugging the raw source appended the URL and made the first real
|
||||
# link to the anchor look broken.
|
||||
slugs = docs_hygiene.markdown_slugs("## Setup [guide](other.md) notes\n")
|
||||
self.assertEqual(slugs, {"setup-guide-notes"})
|
||||
|
||||
def test_heading_link_matches_github_for_the_readme_heading(self):
|
||||
# The exact heading at README.md:53; GitHub renders
|
||||
# `#active-milestone--m2-first-rendered-frame--shader-format-gate`.
|
||||
body = ("### Active Milestone \u2014 [M2: First Rendered Frame & Shader "
|
||||
"Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)\n")
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(
|
||||
slugs, {"active-milestone--m2-first-rendered-frame--shader-format-gate"})
|
||||
|
||||
def test_heading_link_duplicate_still_gets_a_suffix(self):
|
||||
body = "## See [ADR](a.md) notes\n\n## See [ADR](b.md) notes\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"see-adr-notes", "see-adr-notes-1"})
|
||||
|
||||
def test_heading_link_inside_a_code_span_stays_literal(self):
|
||||
# GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
|
||||
# the slug. Substituting links first made this `code-x-span`.
|
||||
slugs = docs_hygiene.markdown_slugs("## Code `[x](y)` span\n")
|
||||
self.assertEqual(slugs, {"code-xy-span"})
|
||||
|
||||
def test_heading_mixes_a_code_span_and_a_link(self):
|
||||
# Only the real link loses its URL; the code span keeps its text.
|
||||
slugs = docs_hygiene.markdown_slugs("## See `a` and [b](c.md)\n")
|
||||
self.assertEqual(slugs, {"see-a-and-b"})
|
||||
|
||||
def test_heading_double_backtick_code_span(self):
|
||||
# GitHub's own renderer gives `#use-a-b-cdmd-here` for this heading:
|
||||
# the inner single-backtick run closes the outer span early, so the
|
||||
# `[c](d.md)` after it is a real link and loses its URL. Asserting the
|
||||
# observed GitHub anchor keeps this honest rather than assuming the
|
||||
# "obvious" answer.
|
||||
slugs = docs_hygiene.markdown_slugs("## Use ``a `b` [c](d.md)`` here\n")
|
||||
self.assertEqual(slugs, {"use-a-b-cdmd-here"})
|
||||
|
||||
def test_heading_image_is_not_treated_as_a_link(self):
|
||||
# An image contributes its alt text through GitHub's rendering, but
|
||||
# the `(?<!\!)` guard must keep this path unchanged for now.
|
||||
slugs = docs_hygiene.markdown_slugs("##  caption\n")
|
||||
self.assertEqual(len(slugs), 1)
|
||||
|
||||
def test_fenced_code_block_ignored(self):
|
||||
body = "```\n# Not A Heading\n```\n\n# Real Heading\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertIn("real-heading", slugs)
|
||||
self.assertNotIn("not-a-heading", slugs)
|
||||
|
||||
def test_tilde_fence_ignored(self):
|
||||
body = "~~~\n# Not A Heading\n~~~\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertNotIn("not-a-heading", slugs)
|
||||
|
||||
def test_atx_levels(self):
|
||||
body = "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
for s in ("one", "two", "three", "four", "five", "six"):
|
||||
self.assertIn(s, slugs)
|
||||
|
||||
|
||||
class CheckLinksTests(unittest.TestCase):
|
||||
"""Exercise check_links with a synthetic in-memory file set."""
|
||||
|
||||
def _run(self, files):
|
||||
"""files: dict mapping repo-relative path -> Markdown body."""
|
||||
problems = []
|
||||
original_text = docs_hygiene.text
|
||||
|
||||
def fake_text(path):
|
||||
return files.get(path)
|
||||
|
||||
docs_hygiene.text = fake_text
|
||||
try:
|
||||
docs_hygiene.check_links(list(files), problems)
|
||||
finally:
|
||||
docs_hygiene.text = original_text
|
||||
return problems
|
||||
|
||||
def test_existing_heading_passes(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Hello World\n\n[link](b.md#hello-world)\n",
|
||||
"docs/b.md": "# Hello World\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_in_page_anchor_passes(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Hello World\n\n[link](#hello-world)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_nonexistent_heading_fails(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#no-such-heading)\n",
|
||||
"docs/b.md": "# Hello World\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#no-such-heading", problems[0])
|
||||
self.assertIn("heading not found", problems[0])
|
||||
|
||||
def test_in_page_nonexistent_heading_fails(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Real\n\n[link](#this-heading-does-not-exist)\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#this-heading-does-not-exist", problems[0])
|
||||
|
||||
def test_duplicate_heading_addressable(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#setup-1)\n",
|
||||
"docs/b.md": "# Setup\n\n# Setup\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_fenced_heading_not_a_slug(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#not-a-heading)\n",
|
||||
"docs/b.md": "```\n# Not A Heading\n```\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#not-a-heading", problems[0])
|
||||
|
||||
def test_external_url_with_fragment_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](https://example.com/page#nonexistent)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_mailto_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](mailto:foo@example.com#frag)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_protocol_relative_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](//example.com/page#frag)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_bare_hash_skipped(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](#)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_missing_file_still_reported(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](nonexistent.md#foo)\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("broken relative link", problems[0])
|
||||
|
||||
def test_fragment_on_non_markdown_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](image.png#foo)\n",
|
||||
"docs/image.png": None,
|
||||
})
|
||||
# image.png is binary (text returns None) but it exists in the
|
||||
# file list, so the link itself resolves; fragment is not checked.
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
|
||||
class MarkerTests(unittest.TestCase):
|
||||
"""The conflict-marker check must catch all four markers, including the diff3 one."""
|
||||
|
||||
def _markers(self, text):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "f.md").write_text(text, encoding="utf-8")
|
||||
previous = docs_hygiene.ROOT
|
||||
docs_hygiene.ROOT = root
|
||||
try:
|
||||
problems = []
|
||||
docs_hygiene.check_markers({"f.md": text}, problems)
|
||||
return problems
|
||||
finally:
|
||||
docs_hygiene.ROOT = previous
|
||||
|
||||
def test_every_marker_kind_is_reported(self):
|
||||
for line in ["<<<<<<< HEAD", "||||||| merged common ancestors", "=======", ">>>>>>> topic"]:
|
||||
problems = self._markers(line + "\n")
|
||||
self.assertEqual(len(problems), 1, f"{line!r} was not reported: {problems}")
|
||||
self.assertIn("f.md:1", problems[0])
|
||||
|
||||
def test_diff3_base_marker_is_reported(self):
|
||||
base = self._markers("||||||| merged common ancestors\n")
|
||||
self.assertEqual(len(base), 1, "the diff3 base marker must be reported")
|
||||
self.assertIn("conflict marker", base[0])
|
||||
|
||||
def test_a_diff3_block_reports_all_four_lines(self):
|
||||
block = "<<<<<<< HEAD\na\n||||||| merged common ancestors\nb\n=======\nc\n>>>>>>> topic\n"
|
||||
problems = self._markers(block)
|
||||
self.assertEqual(len(problems), 4, problems)
|
||||
|
||||
def test_ordinary_content_is_not_a_marker(self):
|
||||
for text in ["| a | b |\n", "||||||\n", "======\n", "prose with | pipes\n", "---\n"]:
|
||||
self.assertEqual(self._markers(text), [], f"{text!r} was wrongly reported")
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
"""check_workflows must reject unparseable YAML."""
|
||||
|
||||
def _check(self, text):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / ".github" / "workflows").mkdir(parents=True)
|
||||
(root / ".github" / "workflows" / "a.yml").write_text(text, encoding="utf-8")
|
||||
previous = docs_hygiene.ROOT
|
||||
docs_hygiene.ROOT = root
|
||||
try:
|
||||
problems = []
|
||||
docs_hygiene.check_workflows({".github/workflows/a.yml": text}, problems, require_yaml=True)
|
||||
return problems
|
||||
finally:
|
||||
docs_hygiene.ROOT = previous
|
||||
|
||||
def test_parses_a_valid_workflow(self):
|
||||
self.assertEqual(self._check("on: push\njobs:\n b:\n runs-on: ubuntu-latest\n"), [])
|
||||
|
||||
def test_reports_invalid_yaml(self):
|
||||
problems = self._check("on: [push\n")
|
||||
self.assertEqual(len(problems), 1, problems)
|
||||
self.assertIn("a.yml", problems[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -18,37 +18,6 @@ cmake -S "$ROOT_DIR/shims" -B "$BUILD_DIR" \
|
||||
|
||||
cmake --build "$BUILD_DIR" --parallel "$JOBS"
|
||||
|
||||
# bx_shader_bridge.dll (#445, #484): shader-transpiler/crates/dxbc-accc built for x86-64
|
||||
# Windows guests, linked with abi/defs/bx_shader_bridge.def so its export list and internal
|
||||
# name are the frozen ones. The verifier below then checks it like every other shim.
|
||||
# Cargo and rustc are resolved through rustup when present (a cargo earlier on PATH may have
|
||||
# no Windows std), and the build always goes to <repo>/target so no stale DLL is staged.
|
||||
BRIDGE_TARGET=x86_64-pc-windows-gnu
|
||||
if command -v rustup >/dev/null 2>&1; then
|
||||
BRIDGE_CARGO="$(cd "$ROOT_DIR" && rustup which cargo)"
|
||||
BRIDGE_RUSTC="$(cd "$ROOT_DIR" && rustup which rustc)"
|
||||
else
|
||||
BRIDGE_CARGO="$(command -v cargo || true)"
|
||||
BRIDGE_RUSTC="$(command -v rustc || true)"
|
||||
fi
|
||||
if [ -z "$BRIDGE_CARGO" ] || [ -z "$BRIDGE_RUSTC" ]; then
|
||||
echo "error: cargo/rustc not found; bx_shader_bridge.dll needs the Rust toolchain" >&2
|
||||
exit 1
|
||||
fi
|
||||
BRIDGE_LIBDIR="$("$BRIDGE_RUSTC" --print target-libdir --target "$BRIDGE_TARGET" 2>/dev/null || true)"
|
||||
if [ -z "$BRIDGE_LIBDIR" ] || ! ls "$BRIDGE_LIBDIR"/libstd-*.rlib >/dev/null 2>&1; then
|
||||
echo "error: $("$BRIDGE_RUSTC" --version) has no std for $BRIDGE_TARGET, needed for bx_shader_bridge.dll" >&2
|
||||
echo "error: install it with: rustup target add $BRIDGE_TARGET" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "=== Building bx_shader_bridge.dll with $("$BRIDGE_RUSTC" --version) ==="
|
||||
RUSTC="$BRIDGE_RUSTC" CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc \
|
||||
"$BRIDGE_CARGO" rustc --locked --release -j "$JOBS" --manifest-path "$ROOT_DIR/Cargo.toml" \
|
||||
-p dxbc-accc --lib --crate-type cdylib --target "$BRIDGE_TARGET" --target-dir "$ROOT_DIR/target" \
|
||||
-- -C link-arg="$ROOT_DIR/abi/defs/bx_shader_bridge.def"
|
||||
mkdir -p "$BUILD_DIR/bin"
|
||||
cp "$ROOT_DIR/target/$BRIDGE_TARGET/release/dxbc_accc.dll" "$BUILD_DIR/bin/bx_shader_bridge.dll"
|
||||
|
||||
echo "=== Verifying built PE32+ DLL Export Directories against abi/defs/*.def ==="
|
||||
python3 - "$ROOT_DIR/abi/defs" "$BUILD_DIR/bin" <<'PY'
|
||||
import os
|
||||
|
||||
Executable
+260
@@ -0,0 +1,260 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Run the integrated-workload acceptance sequence through `betterxen hybrid` on this Mac.
|
||||
# Every line printed is "ok <check>" or "FAIL <check>"; the exit status is non-zero if any
|
||||
# check failed. Raw JSON records and logs are kept under the output directory.
|
||||
#
|
||||
# scripts/hybrid/accept-integrated.sh <llvm-mingw-dir> <bottle> [soak-frames] [repeats]
|
||||
#
|
||||
# Exit 0: every check ran and passed. 1: a check failed. 2: the only deviations are the known
|
||||
# D3DMetal swapchain retention and/or checks reported NOT-RUN. NOT-RUN is never a pass.
|
||||
# Shader Model 6 needs Microsoft's DXC (scripts/hybrid/install-dxc.py); point
|
||||
# BETTERXEN_DXC_DIR at its bin/x64 directory.
|
||||
# Needs CrossOver, an existing win11_64 bottle, Rust 1.100.0, the pinned llvm-mingw
|
||||
# (https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/hybrid-toolchain.md), and for the on-screen check a GUI session with the
|
||||
# Screen Recording and Accessibility permissions (the latter for the keyboard check, which
|
||||
# brings the test window to the front: do not type while it runs). Opens small windows; do not
|
||||
# run on a busy machine or alongside anything else using the same bottle.
|
||||
set -u
|
||||
TC=${1:?usage: $0 <llvm-mingw-dir> <bottle> [soak-frames] [repeats]}
|
||||
BOTTLE=${2:?name an existing bottle}
|
||||
SOAK=${3:-20000}
|
||||
REPEATS=${4:-5}
|
||||
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
export RUSTUP_TOOLCHAIN=${RUSTUP_TOOLCHAIN:-1.100.0-aarch64-apple-darwin}
|
||||
mkdir -p "$ROOT/artifacts/acceptance" || exit 1
|
||||
OUT=$(mktemp -d "$ROOT/artifacts/acceptance/$(date -u +%Y%m%dT%H%M%SZ)-XXXXXX") || exit 1
|
||||
failed=0
|
||||
known=0
|
||||
not_run=0
|
||||
ok() { echo "ok $1"; }
|
||||
bad() { echo "FAIL $1"; failed=1; }
|
||||
|
||||
if [ -z "${BETTERXEN_RUNNER:-}" ]; then
|
||||
(cd "$ROOT" && cargo build --locked --release -p bx-cli) >"$OUT/build-runner.log" 2>&1 ||
|
||||
{ bad "build runner"; exit 1; }
|
||||
fi
|
||||
if [ -n "${BETTERXEN_WORKLOAD_DIR:-}" ]; then
|
||||
mkdir -p "$OUT/bin" || exit 1
|
||||
for name in d3d11-integrated d3d12-integrated d3d12-lifetime d3d12-wave-probe; do
|
||||
cp "$BETTERXEN_WORKLOAD_DIR/$name.exe" "$OUT/bin/" || exit 1
|
||||
done
|
||||
else
|
||||
"$ROOT/tests/conformance/test_d3d11_integrated/build.sh" "$TC" "$OUT/bin" >"$OUT/build-workload.log" 2>&1 ||
|
||||
{ bad "build workload"; exit 1; }
|
||||
"$ROOT/tests/conformance/test_d3d12_integrated/build.sh" "$TC" "$OUT/bin" >"$OUT/build-workload12.log" 2>&1 ||
|
||||
{ bad "build D3D12 workload"; exit 1; }
|
||||
for probe in lifetime wave; do
|
||||
"$ROOT/tests/conformance/test_d3d12_$probe/build.sh" "$TC" "$OUT/bin" >"$OUT/build-$probe.log" 2>&1 ||
|
||||
{ bad "build D3D12 $probe probe"; exit 1; }
|
||||
done
|
||||
fi
|
||||
BX=${BETTERXEN_RUNNER:-"${CARGO_TARGET_DIR:-$ROOT/target}/release/bx-cli"}
|
||||
HYBRID=${BETTERXEN_HYBRID_RUNNER:-"$(dirname "$BX")/bx-cli"}
|
||||
EXE12="$OUT/bin/d3d12-integrated.exe"
|
||||
EXE="$OUT/bin/d3d11-integrated.exe"
|
||||
# Unique executable names separate lifecycle observations from other bottles. Names are
|
||||
# never used as kill authority by the runner.
|
||||
RUN_ID=$(basename "$OUT")
|
||||
mv "$EXE" "$OUT/bin/d3d11-$RUN_ID.exe" || exit 1
|
||||
mv "$EXE12" "$OUT/bin/d3d12-$RUN_ID.exe" || exit 1
|
||||
EXE="$OUT/bin/d3d11-$RUN_ID.exe"
|
||||
EXE12="$OUT/bin/d3d12-$RUN_ID.exe"
|
||||
if [ "$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null)" = "$ROOT" ]; then
|
||||
git -C "$ROOT" rev-parse HEAD >"$OUT/commit.txt"
|
||||
git -C "$ROOT" status --porcelain >>"$OUT/commit.txt"
|
||||
elif [ -n "${BETTERXEN_SOURCE_COMMIT:-}" ]; then
|
||||
printf '%s\nprebuilt bundle; source archive SHA-256 verified by test.sh\n' "$BETTERXEN_SOURCE_COMMIT" >"$OUT/commit.txt"
|
||||
else
|
||||
bad "source commit unavailable; use a Git checkout or the verified bundle test.sh"
|
||||
exit 1
|
||||
fi
|
||||
"$BX" hybrid receipt >"$OUT/receipt.json" 2>&1
|
||||
|
||||
if "$BX" hybrid doctor --bottle "$BOTTLE" >"$OUT/doctor.json" 2>&1; then ok "A environment"; else
|
||||
bad "A environment (see doctor.json)"; exit 1; fi
|
||||
if "$BX" hybrid inspect "$EXE" >"$OUT/inspect.json" 2>&1; then ok "B executable identified"; else bad "B inspect"; fi
|
||||
|
||||
GATES=runtime.threads,runtime.memory,runtime.exceptions,runtime.time,runtime.files,graphics.init,shader.compile,frame.first,frame.continuous,resources.churn,input,memory.bounded,shutdown
|
||||
|
||||
# run <name> <expected-classification> [runner options...] -- [workload args...]
|
||||
run() {
|
||||
name=$1; want=$2; shift 2
|
||||
opts=""
|
||||
while [ $# -gt 0 ] && [ "$1" != -- ]; do opts="$opts $1"; shift; done
|
||||
shift
|
||||
# shellcheck disable=SC2086 # options are fixed words from this script
|
||||
"$BX" hybrid run --bottle "$BOTTLE" --expect "PASS integrated" --keep-output true --out "$OUT/raw" $opts -- "$EXE" "$@" \
|
||||
>"$OUT/$name.json" 2>"$OUT/$name.log"
|
||||
got=$(sed -n 's/^ "classification": "\(.*\)",$/\1/p' "$OUT/$name.json")
|
||||
case "$got" in
|
||||
$want) ok "$name ($got)" ;;
|
||||
*) bad "$name: expected $want, got ${got:-no record}" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
run C-F-G-H-full passed --require-gates "$GATES" --timeout 180 --stall-timeout 60 -- --frames 600
|
||||
run BC1-full passed --require-gates "$GATES,textures.bc1" --timeout 180 -- --frames 128 --bc1
|
||||
run BC1-negative failed_exit_1 --timeout 120 -- --frames 128 --bc1 --fault bc1
|
||||
|
||||
# a negative control counts only if the gate the fault targets is the one that failed
|
||||
intended() {
|
||||
case "$1" in
|
||||
input) echo input ;;
|
||||
stale) echo frame.continuous ;;
|
||||
bc1) echo textures.bc1 ;;
|
||||
*) echo "frame.first frame.continuous" ;;
|
||||
esac
|
||||
}
|
||||
detects() {
|
||||
# shellcheck disable=SC2046 # gate names are fixed words
|
||||
if python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/$1.json" $(intended "$2") >"$OUT/$1.gates.log" 2>&1;
|
||||
then ok "$1 failed its intended gate ($(cat "$OUT/$1.gates.log"))"
|
||||
else bad "$1: $(cat "$OUT/$1.gates.log")"; fi
|
||||
}
|
||||
detects BC1-negative bc1
|
||||
for scene in C-F-G-H-full BC1-full; do
|
||||
if python3 "$ROOT/scripts/hybrid/check-image-digest.py" "$OUT/$scene.json" >"$OUT/oracle-$scene.log" 2>&1;
|
||||
then ok "independent image oracle $scene"; else bad "independent image oracle $scene (see log)"; fi
|
||||
done
|
||||
for fault in color blank stale input depth; do
|
||||
run "negative-$fault" failed_exit_1 --timeout 120 -- --frames 128 --fault "$fault"
|
||||
detects "negative-$fault" "$fault"
|
||||
done
|
||||
# With Wine's crash dialog on, winedbg waits for a click and this times out;
|
||||
# scripts/hybrid/create-test-bottle.py turns it off in new test bottles.
|
||||
run negative-crash 'failed_exit_*' --timeout 240 -- --frames 128 --fault crash
|
||||
run recovery-after-crash passed --require-gates "$GATES" --timeout 120 -- --frames 128
|
||||
run negative-hang stalled --timeout 90 --stall-timeout 15 -- --frames 128 --fault hang
|
||||
if pgrep -f "$(basename "$EXE")" >/dev/null; then bad "hung workload still running after stop";
|
||||
else ok "hung workload removed"; fi
|
||||
run recovery-after-hang passed --require-gates "$GATES" --timeout 120 -- --frames 128
|
||||
|
||||
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE" \
|
||||
--keep "$OUT/window.png" >"$OUT/window.log" 2>&1; then ok "F on-screen frame"; else
|
||||
bad "F on-screen frame: $(cat "$OUT/window.log")"; fi
|
||||
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE" \
|
||||
--fault depth >"$OUT/window-negative.log" 2>&1; then bad "on-screen check accepted a wrong image";
|
||||
else
|
||||
if grep -q 'samples differ' "$OUT/window-negative.log"; then ok "on-screen negative control";
|
||||
else bad "on-screen negative control did not reach comparison"; fi
|
||||
fi
|
||||
|
||||
i=1
|
||||
while [ "$i" -le "$REPEATS" ]; do
|
||||
run "I-repeat-$i" passed --require-gates "$GATES" --timeout 180 -- --frames 600
|
||||
i=$((i + 1))
|
||||
done
|
||||
# Direct3D 12. Under D3DMetal (CrossOver 26.3) a destroyed D3D12 swapchain leaves a device
|
||||
# reference, so the `shutdown` gate fails. That is reported as KNOWN only when it is the sole
|
||||
# failing gate; any other failure is a failure.
|
||||
d12_summary() {
|
||||
python3 - "$1" <<'PY'
|
||||
import json, re, sys
|
||||
j = json.load(open(sys.argv[1]))
|
||||
failed = sorted(g["name"] for g in j["gates"] if not g["passed"])
|
||||
digest = "".join(re.findall(r"digest=([0-9a-f]+)", " ".join(g["detail"] for g in j["gates"])))
|
||||
backend = j["backend_detected"].split(" ")[0]
|
||||
print(j["classification"], backend, ",".join(failed) or "-", digest or "-")
|
||||
PY
|
||||
}
|
||||
digest11=$(sed -n 's/.*digest=\([0-9a-f]*\).*/\1/p' "$OUT/C-F-G-H-full.json" | head -1)
|
||||
BX_SECRET_PROBE=1 "$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 180 --stall-timeout 60 -- "$EXE12" \
|
||||
--expect-absent-env BX_SECRET_PROBE >"$OUT/d3d12-full.json" 2>"$OUT/d3d12-full.log"
|
||||
read -r class backend failed12 digest12 <<EOT
|
||||
$(d12_summary "$OUT/d3d12-full.json")
|
||||
EOT
|
||||
case "$class:$backend:$failed12" in
|
||||
passed:*:-) ok "D3D12 all gates (backend $backend)" ;;
|
||||
failed_exit_1:d3dmetal:shutdown)
|
||||
ok "D3D12 all gates but shutdown"
|
||||
known=1
|
||||
echo "KNOWN D3D12 shutdown: D3DMetal retains a device reference per swapchain" ;;
|
||||
*) bad "D3D12: $class backend=$backend failed=$failed12" ;;
|
||||
esac
|
||||
if [ -n "$digest11" ] && [ "$digest11" = "$digest12" ]; then ok "D3D11 and D3D12 pixel digests equal ($digest12)";
|
||||
else bad "pixel digests differ: d3d11=$digest11 d3d12=$digest12"; fi
|
||||
if python3 "$ROOT/scripts/hybrid/check-image-digest.py" "$OUT/d3d12-full.json" >"$OUT/oracle-d3d12.log" 2>&1;
|
||||
then ok "independent image oracle D3D12"; else bad "independent image oracle D3D12 (see log)"; fi
|
||||
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE12" \
|
||||
--keep "$OUT/window12.png" >"$OUT/window12.log" 2>&1; then ok "D3D12 on-screen frame";
|
||||
else bad "D3D12 on-screen frame: $(cat "$OUT/window12.log")"; fi
|
||||
for api in d3d11 d3d12; do
|
||||
case "$api" in d3d11) first_exe=$EXE ;; d3d12) first_exe=$EXE12 ;; esac
|
||||
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$first_exe" \
|
||||
--first-frame --keep "$OUT/first-$api.png" >"$OUT/first-$api.log" 2>&1;
|
||||
then ok "$api first frame on screen"; else bad "$api first frame on screen (see log)"; fi
|
||||
done
|
||||
for fault in color blank stale input depth upload; do
|
||||
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 90 -- "$EXE12" --frames 128 --fault "$fault" \
|
||||
>"$OUT/d3d12-negative-$fault.json" 2>/dev/null
|
||||
detects "d3d12-negative-$fault" "$fault"
|
||||
done
|
||||
|
||||
# Minimal swapchain lifetime probe: no application GPU work. The detach control must pass
|
||||
# and the deliberately retained reference must be caught, or the witness proves nothing.
|
||||
LIFE="$OUT/bin/d3d12-lifetime.exe"
|
||||
lifetime() {
|
||||
name=$1
|
||||
shift
|
||||
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 90 -- "$LIFE" "$@" \
|
||||
>"$OUT/$name.json" 2>"$OUT/$name.log"
|
||||
}
|
||||
if lifetime lifetime-detach-control --detach-witness; then ok "lifetime witness detaches";
|
||||
else bad "lifetime detach control (see lifetime-detach-control.log)"; fi
|
||||
lifetime lifetime-retained-negative --detach-witness --retain-app-reference
|
||||
if python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/lifetime-retained-negative.json" resources.private-data-detach >/dev/null 2>&1;
|
||||
then ok "lifetime witness catches a retained reference"; else bad "lifetime retained-reference control"; fi
|
||||
if lifetime lifetime-swapchain; then ok "D3D12 swapchain released"
|
||||
elif grep -q 'adapter=AMD Compatibility Mode' "$OUT/lifetime-swapchain.json" &&
|
||||
python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/lifetime-swapchain.json" resources.swapchain-release >/dev/null 2>&1; then
|
||||
known=1
|
||||
echo "KNOWN D3D12 swapchain retention under D3DMetal (minimal probe)"
|
||||
else bad "lifetime probe (see lifetime-swapchain.log)"; fi
|
||||
|
||||
DXC=${BETTERXEN_DXC_DIR:-$ROOT/artifacts/dependencies/dxc-v1.9.2609/bin/x64}
|
||||
if [ -f "$DXC/dxc.exe" ]; then
|
||||
if python3 "$ROOT/scripts/hybrid/accept-sm6.py" "$BX" "$BOTTLE" "$OUT/bin/d3d12-wave-probe.exe" "$DXC" "$OUT/sm6" \
|
||||
>"$OUT/sm6.log" 2>&1; then ok "Shader Model 6 GPU readback"; else bad "Shader Model 6: $(tail -1 "$OUT/sm6.log")"; fi
|
||||
else
|
||||
not_run=1
|
||||
echo "NOT-RUN Shader Model 6: no dxc.exe at $DXC"
|
||||
fi
|
||||
if python3 "$ROOT/tests/conformance/test_d3d12_integrated/send_keys.py" "$BX" "$BOTTLE" "$EXE12" >"$OUT/keys.log" 2>&1;
|
||||
then ok "H macOS keyboard events"; else bad "H keyboard: $(tail -1 "$OUT/keys.log")"; fi
|
||||
if python3 "$ROOT/tests/conformance/test_d3d12_integrated/send_keys.py" "$BX" "$BOTTLE" "$EXE12" --keys up,up \
|
||||
--expect fail >"$OUT/keys-negative.log" 2>&1; then ok "keyboard negative control";
|
||||
else bad "keyboard negative control"; fi
|
||||
if python3 "$ROOT/scripts/hybrid/accept-lifecycle.py" "$BX" "$BOTTLE" "$EXE" >"$OUT/lifecycle.log" 2>&1;
|
||||
then ok "lifecycle: signals, kill and stop, repeated launch"; else
|
||||
bad "lifecycle (see lifecycle.log)"; grep FAIL "$OUT/lifecycle.log"; fi
|
||||
|
||||
# Direct3D 12 is the primary target, so it is soaked first; Direct3D 11 stays as the control.
|
||||
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 1800 --stall-timeout 60 -- "$EXE12" \
|
||||
--frames "$SOAK" --verify-every 500 >"$OUT/I-soak-d3d12.json" 2>"$OUT/I-soak-d3d12.log"
|
||||
read -r class backend failed12 digest12 <<EOT
|
||||
$(d12_summary "$OUT/I-soak-d3d12.json")
|
||||
EOT
|
||||
case "$class:$backend:$failed12" in
|
||||
passed:*:-) ok "I-soak D3D12 ($SOAK frames)" ;;
|
||||
failed_exit_1:d3dmetal:shutdown)
|
||||
known=1
|
||||
ok "I-soak D3D12 all gates but the known shutdown ($SOAK frames)" ;;
|
||||
*) bad "I-soak D3D12: $class backend=$backend failed=$failed12" ;;
|
||||
esac
|
||||
run I-soak-d3d11 passed --require-gates "$GATES" --timeout 1800 --stall-timeout 60 -- --frames "$SOAK" --verify-every 500
|
||||
|
||||
echo "records: $OUT"
|
||||
python3 - "$OUT" "$failed" "$known" "$not_run" <<'PY'
|
||||
import json, pathlib, sys
|
||||
path = pathlib.Path(sys.argv[1])
|
||||
failed, known, not_run = map(int, sys.argv[2:])
|
||||
(path / "summary.json").write_text(json.dumps({
|
||||
"schema": "betterxen-integrated-acceptance/0",
|
||||
"unexpected_failures": bool(failed), "known_d3d12_swapchain_retention": bool(known),
|
||||
"checks_not_run": bool(not_run), "all_checks_passed": not (failed or known or not_run),
|
||||
}, indent=2) + "\n")
|
||||
PY
|
||||
[ "$failed" -eq 0 ] || exit 1
|
||||
[ "$known" -eq 0 ] && [ "$not_run" -eq 0 ] || exit 2
|
||||
exit 0
|
||||
Executable
+131
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Process lifecycle checks for the hybrid runner against an installed CrossOver.
|
||||
|
||||
Uses the Direct3D 11 workload: `--fault hang` makes a program that never exits, and a normal
|
||||
run shows recovery. Prints "ok"/"FAIL" per check and exits non-zero on any failure. Do not
|
||||
run anything else in the same bottle meanwhile: stopping a run stops the whole bottle.
|
||||
|
||||
usage: accept-lifecycle.py RUNNER BOTTLE D3D11_EXE [--launches N]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(ok, what):
|
||||
global failed
|
||||
failed |= not ok
|
||||
print(("ok " if ok else "FAIL ") + what, flush=True)
|
||||
|
||||
|
||||
def workload_pids(exe_name):
|
||||
out = subprocess.run(["/bin/ps", "-axo", "pid=,command="], capture_output=True, text=True).stdout
|
||||
pids = []
|
||||
for line in out.splitlines():
|
||||
pid, _, command = line.strip().partition(" ")
|
||||
command = command.strip()
|
||||
# the Windows program appears with a drive-letter command line
|
||||
if command[1:3] == ":\\" and exe_name.lower() in command.lower():
|
||||
pids.append(int(pid))
|
||||
return pids
|
||||
|
||||
|
||||
def wait_for(predicate, seconds):
|
||||
end = time.time() + seconds
|
||||
while time.time() < end:
|
||||
if predicate():
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("runner")
|
||||
p.add_argument("bottle")
|
||||
p.add_argument("exe")
|
||||
p.add_argument("--launches", type=int, default=20)
|
||||
a = p.parse_args()
|
||||
name = os.path.basename(a.exe)
|
||||
base = [a.runner, "hybrid", "run", "--bottle", a.bottle, "--timeout", "120"]
|
||||
if workload_pids(name):
|
||||
print(f"FAIL precondition: {name} is already running")
|
||||
return 1
|
||||
|
||||
def start(extra, out):
|
||||
return subprocess.Popen(base + ["--", a.exe] + extra, stdout=out, stderr=subprocess.DEVNULL,
|
||||
start_new_session=True)
|
||||
|
||||
def healthy(label):
|
||||
with tempfile.TemporaryFile("w+") as out:
|
||||
run = start(["--frames", "64"], out)
|
||||
code = run.wait(timeout=150)
|
||||
check(code == 0, f"{label}: next run passes")
|
||||
check(not workload_pids(name), f"{label}: nothing left running")
|
||||
|
||||
for sig, to_group in ((signal.SIGINT, True), (signal.SIGTERM, False), (signal.SIGHUP, False)):
|
||||
label = sig.name + (" to the process group" if to_group else "")
|
||||
with tempfile.TemporaryFile("w+") as out:
|
||||
run = start(["--frames", "64", "--fault", "hang"], out)
|
||||
if not wait_for(lambda: workload_pids(name), 60):
|
||||
check(False, f"{label}: workload never started")
|
||||
run.kill()
|
||||
continue
|
||||
time.sleep(2)
|
||||
began = time.time()
|
||||
(os.killpg if to_group else os.kill)(run.pid, sig)
|
||||
try:
|
||||
code = run.wait(timeout=40)
|
||||
except subprocess.TimeoutExpired:
|
||||
run.kill()
|
||||
check(False, f"{label}: supervisor did not exit")
|
||||
continue
|
||||
out.seek(0)
|
||||
try:
|
||||
record = json.load(out)
|
||||
except json.JSONDecodeError:
|
||||
record = {}
|
||||
check(code == 1 and record.get("classification") == "interrupted",
|
||||
f"{label}: classified {record.get('classification')} in {time.time() - began:.1f}s")
|
||||
check(wait_for(lambda: not workload_pids(name), 10), f"{label}: workload stopped")
|
||||
healthy(label)
|
||||
|
||||
with tempfile.TemporaryFile("w+") as out:
|
||||
run = start(["--frames", "64", "--fault", "hang"], out)
|
||||
started = wait_for(lambda: workload_pids(name), 60)
|
||||
time.sleep(2)
|
||||
run.kill()
|
||||
run.wait()
|
||||
# SIGKILL cannot be handled: the program is expected to survive until `stop`.
|
||||
check(started and bool(workload_pids(name)), "SIGKILL: program survives, as documented")
|
||||
subprocess.run([a.runner, "hybrid", "stop", "--bottle", a.bottle], timeout=60)
|
||||
check(wait_for(lambda: not workload_pids(name), 15), "SIGKILL: `hybrid stop` removes it")
|
||||
healthy("after stop")
|
||||
|
||||
passed = 0
|
||||
for launch in range(a.launches):
|
||||
with tempfile.TemporaryFile("w+") as out:
|
||||
code = start(["--frames", "64"], out).wait(timeout=150)
|
||||
passed += code == 0
|
||||
if code:
|
||||
out.seek(0)
|
||||
try:
|
||||
reason = json.load(out).get("classification")
|
||||
except json.JSONDecodeError:
|
||||
reason = "no record"
|
||||
print(f" launch {launch + 1}: {reason}", flush=True)
|
||||
check(passed == a.launches, f"repeated launch: {passed} of {a.launches} passed")
|
||||
check(not workload_pids(name), "repeated launch: nothing left running")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+102
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Compile original HLSL with external DXC, then verify actual Shader Model 6 GPU readback.
|
||||
|
||||
RUNNER BOTTLE PROBE_EXE DXC_BIN_DIR OUTPUT_DIR
|
||||
The dedicated test bottle must have Z: mapped to / (CrossOver's observed default).
|
||||
Expected float bit patterns below are derived from arithmetic, not the compiler or GPU.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def windows(path):
|
||||
return "Z:" + str(Path(path).resolve()).replace("/", "\\")
|
||||
|
||||
|
||||
def main():
|
||||
runner, bottle, probe, dxc, output = sys.argv[1:]
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
output = Path(output).resolve()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
dxc = Path(dxc).resolve() / "dxc.exe"
|
||||
base = [str(Path(runner).resolve()), "hybrid", "run", "--bottle", bottle,
|
||||
"--backend", "d3dmetal", "--timeout", "120", "--keep-output", "true", "--out", str(output / "raw")]
|
||||
|
||||
def run(name, command):
|
||||
result = subprocess.run(base + ["--"] + command, capture_output=True, text=True, timeout=180)
|
||||
(output / (name + ".json")).write_text(result.stdout)
|
||||
(output / (name + ".log")).write_text(result.stderr)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"{name} failed; see {output}")
|
||||
record = json.loads(result.stdout)
|
||||
# Read the complete supervised stdout; a successful exit alone proves no result.
|
||||
return Path(record["stdout_path"]).read_text(errors="replace")
|
||||
|
||||
caps = run("caps", [probe, "caps"])
|
||||
match = re.search(r"options1: hr=0x0+ wave_ops=1 wave_lane_count_min=(\d+) wave_lane_count_max=(\d+)", caps)
|
||||
if not match:
|
||||
raise RuntimeError("wave capability query did not succeed; SM6 acceptance unavailable")
|
||||
expectations = {"add_f32_4": [0x40000000, 0] * 4, "sum_f32_4": [0x40A00000] * 4}
|
||||
results = {}
|
||||
for name, words in [("lanes4", 4), ("add_f32_4", 8), ("sum_f32_4", 4)]:
|
||||
shader = output / (name + ".dxil")
|
||||
run("compile-" + name, [str(dxc), "-T", "cs_6_6", "-E", "main", "-Fo", windows(shader),
|
||||
windows(root / "tests/conformance/test_d3d12_wave/hlsl" / (name + ".hlsl"))])
|
||||
disassembly = run("dxil-" + name, [str(dxc), "-dumpbin", windows(shader)])
|
||||
operations = {
|
||||
"lanes4": [r"\bcall\b[^\n]*@dx\.op\.waveGetLaneIndex", r"\bcall\b[^\n]*@dx\.op\.waveGetLaneCount"],
|
||||
"sum_f32_4": [r"\bcall\b[^\n]*@dx\.op\.waveActiveOp\.f32"],
|
||||
"add_f32_4": [r"\bfadd\b"],
|
||||
}
|
||||
if any(not re.search(pattern, disassembly) for pattern in operations[name]):
|
||||
raise RuntimeError(f"{name}: compiled DXIL does not contain the operation being tested")
|
||||
text = run(name, [probe, "run", windows(shader), "1", str(words)])
|
||||
pairs = [(int(i), int(v, 16)) for i, v in re.findall(r"^out (\d+) 0x([0-9a-fA-F]+)$", text, re.M)]
|
||||
if [i for i, _ in pairs] != list(range(words)):
|
||||
raise RuntimeError(f"{name}: missing, duplicate or unexpected readback words")
|
||||
actual = [v for _, v in pairs]
|
||||
dispatch = re.search(r"dispatch_caps wave_ops=1 min=(\d+) max=(\d+)", text)
|
||||
if not dispatch:
|
||||
raise RuntimeError(f"{name}: no wave capabilities for the dispatch device")
|
||||
minimum, maximum = map(int, dispatch.groups())
|
||||
if name == "lanes4":
|
||||
width = actual[0] >> 8
|
||||
def valid_lanes(values):
|
||||
widths = {v >> 8 for v in values}
|
||||
lanes = {v & 255 for v in values}
|
||||
return (len(widths) == 1 and minimum <= width <= maximum and 4 <= width <= 128
|
||||
and not width & (width - 1) and len(lanes) == 4 and max(lanes) < width)
|
||||
if not valid_lanes(actual):
|
||||
raise RuntimeError(f"invalid or duplicate lane IDs or wave width: {actual}")
|
||||
wrong = actual.copy()
|
||||
wrong[0] ^= 0x80000000
|
||||
if valid_lanes(wrong):
|
||||
raise RuntimeError("lane invariant negative control failed")
|
||||
results[name] = {"actual": actual, "expected_properties": "one supported wave width; four distinct lane IDs below width", "negative_mismatches": 1}
|
||||
print("PASS SM6 lanes4: independent lane invariants and one-bit negative control")
|
||||
continue
|
||||
else:
|
||||
expected = expectations[name]
|
||||
mismatches = sum(a != b for a, b in zip(actual, expected))
|
||||
if mismatches:
|
||||
raise RuntimeError(f"{name}: {mismatches} incorrect GPU words: {actual}")
|
||||
# The deliberately wrong expectation must detect exactly one mismatch in this readback.
|
||||
wrong = expected.copy()
|
||||
wrong[0] ^= 1
|
||||
if sum(a != b for a, b in zip(actual, wrong)) != 1:
|
||||
raise RuntimeError(f"{name}: negative control failed")
|
||||
results[name] = {"actual": actual, "expected": expected, "negative_mismatches": 1}
|
||||
print(f"PASS SM6 {name}: {words} exact GPU words, one-bit negative control detected")
|
||||
(output / "summary.json").write_text(json.dumps({"schema": "betterxen-sm6/0", "passed": True, "results": results}, indent=2) + "\n")
|
||||
print("Unsupported double precision is not exercised or counted as passing.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (ValueError, OSError, RuntimeError, subprocess.SubprocessError, KeyError) as error:
|
||||
sys.exit(f"FAIL SM6: {error}")
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Produce a native runner and original redistributable workloads without starting CrossOver.
|
||||
set -eu
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
TC=${1:?usage: build-maintainer.sh LLVM_MINGW_DIR}
|
||||
TC=$(CDPATH='' cd -- "$TC" && pwd)
|
||||
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
|
||||
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-2}
|
||||
export RUSTUP_TOOLCHAIN=1.100.0-aarch64-apple-darwin
|
||||
OUT="$ROOT/artifacts/maintainer"
|
||||
mkdir -p "$OUT/bin" "$OUT/workloads" "$OUT/logs"
|
||||
cd "$ROOT"
|
||||
cargo build --locked --release --target aarch64-apple-darwin -p bx-cli \
|
||||
>"$OUT/logs/build.log" 2>&1 || { cat "$OUT/logs/build.log" >&2; exit 1; }
|
||||
for exe in bx-cli; do
|
||||
cp "${CARGO_TARGET_DIR:-$ROOT/target}/aarch64-apple-darwin/release/$exe" "$OUT/bin/$exe"
|
||||
file "$OUT/bin/$exe"
|
||||
[ "$(lipo -archs "$OUT/bin/$exe")" = arm64 ] || { echo "unexpected host architecture" >&2; exit 1; }
|
||||
otool -L "$OUT/bin/$exe" >"$OUT/logs/$exe-linkage.txt"
|
||||
python3 - "$OUT/logs/$exe-linkage.txt" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
libraries = [line.strip().split(' (', 1)[0] for line in Path(sys.argv[1]).read_text().splitlines()[1:]]
|
||||
if not libraries or any(not lib.startswith(('/usr/lib/', '/System/Library/')) for lib in libraries):
|
||||
sys.exit(f'non-system or missing host linkage: {libraries}')
|
||||
PY
|
||||
done
|
||||
scripts/hybrid/build-windows-workloads.sh "$TC" >"$OUT/logs/build-workloads.log" 2>&1 ||
|
||||
{ cat "$OUT/logs/build-workloads.log" >&2; exit 1; }
|
||||
for exe in selfcheck-c selfcheck-rust d3d11-clear d3d11-frameloop; do
|
||||
cp "artifacts/hybrid-workloads/x86_64/$exe.exe" "$OUT/workloads/"
|
||||
done
|
||||
for api in d3d11 d3d12; do
|
||||
"tests/conformance/test_${api}_integrated/build.sh" "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
|
||||
done
|
||||
tests/conformance/test_d3d12_lifetime/build.sh "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
|
||||
tests/conformance/test_d3d12_wave/build.sh "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
|
||||
python3 scripts/hybrid/collect-build-notices.py "$TC" "$OUT/licenses"
|
||||
git rev-parse HEAD >"$OUT/commit.txt"
|
||||
git status --porcelain >"$OUT/source-status.txt"
|
||||
"$OUT/bin/bx-cli" hybrid receipt >"$OUT/receipt.json"
|
||||
(cd "$OUT" && shasum -a 256 bin/* workloads/*.exe > SHA256SUMS)
|
||||
echo "Build and checksums: $OUT"
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Build BetterXen's original Windows workloads (issue #364) with a pinned cross toolchain and
|
||||
# write the results to artifacts/hybrid-workloads/<arch>/. Nothing is executed; the script ends
|
||||
# by printing `file` and the PE machine type of every output so a build that produced the wrong
|
||||
# architecture fails here.
|
||||
#
|
||||
# scripts/hybrid/build-windows-workloads.sh <llvm-mingw-dir>
|
||||
#
|
||||
# <llvm-mingw-dir> is an unpacked llvm-mingw release (https://github.com/mstorsjo/llvm-mingw;
|
||||
# wrappers/scripts ISC, compiler and runtime under their component licences);
|
||||
# see https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/hybrid-toolchain.md for the pinned
|
||||
# release and checksum. Rust workloads use the x86_64-pc-windows-gnullvm and
|
||||
# aarch64-pc-windows-gnullvm targets (rustup target add ...) linked with that toolchain.
|
||||
set -eu
|
||||
TC=$(CDPATH='' cd -- "${1:?usage: $0 <llvm-mingw-dir>}" && pwd)
|
||||
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
OUT="$ROOT/artifacts/hybrid-workloads"
|
||||
RUSTC_TC=${RUSTUP_TOOLCHAIN_FOR_WORKLOADS:-1.100.0}
|
||||
[ -x "$TC/bin/x86_64-w64-mingw32-clang" ] || { echo "no llvm-mingw at $TC" >&2; exit 1; }
|
||||
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
|
||||
|
||||
for arch in x86_64; do
|
||||
d="$OUT/$arch"; mkdir -p "$d"
|
||||
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
|
||||
-o "$d/selfcheck-c.exe" "$ROOT/tests/conformance/test_runtime_c/selfcheck.c"
|
||||
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
|
||||
-o "$d/d3d11-clear.exe" "$ROOT/tests/conformance/test_d3d11_clear/d3d11_clear.c" -ld3d11 -ldxgi
|
||||
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
|
||||
-o "$d/d3d11-frameloop.exe" "$ROOT/tests/conformance/test_d3d11_frameloop/frameloop.c" -ld3d11 -ldxgi -ldxguid -ld3dcompiler -lm
|
||||
env_arch=$(echo "$arch" | tr a-z A-Z)
|
||||
(
|
||||
export PATH="$TC/bin:$PATH"
|
||||
export "CARGO_TARGET_${env_arch}_PC_WINDOWS_GNULLVM_LINKER=$TC/bin/$arch-w64-mingw32-clang"
|
||||
export CARGO_ENCODED_RUSTFLAGS
|
||||
CARGO_ENCODED_RUSTFLAGS=$(printf '%s\037%s\037%s' '-C' 'link-arg=-Wl,--no-insert-timestamp' "--remap-path-prefix=$ROOT=/betterxen")
|
||||
cd "$ROOT/tests/conformance/support/win-selfcheck-rust"
|
||||
CARGO_TARGET_DIR="$OUT/rust-target" rustup run "$RUSTC_TC" cargo build --locked --release --target "$arch-pc-windows-gnullvm" -q
|
||||
)
|
||||
cp "$OUT/rust-target/$arch-pc-windows-gnullvm/release/win-selfcheck-rust.exe" "$d/selfcheck-rust.exe"
|
||||
done
|
||||
|
||||
fail=0
|
||||
for f in "$OUT"/x86_64/*.exe; do
|
||||
want=$(basename "$(dirname "$f")")
|
||||
desc=$(file -b "$f")
|
||||
case "$want:$desc" in
|
||||
x86_64:*"PE32+"*"x86-64"*) ok=ok ;;
|
||||
aarch64:*"PE32+"*"Aarch64"*|aarch64:*"PE32+"*"ARM64"*) ok=ok ;;
|
||||
*) ok=WRONG; fail=1 ;;
|
||||
esac
|
||||
echo "$ok $f: $desc"
|
||||
done
|
||||
exit $fail
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""A negative control counts only when the injected fault failed the gate it targets.
|
||||
|
||||
check-failed-gates.py RECORD.json GATE [GATE...]
|
||||
|
||||
Passes when the record is a non-zero workload exit and every named gate was reported
|
||||
and failed. A crash, a missing gate or an unrelated failure is not a detection.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
path, *wanted = sys.argv[1:]
|
||||
if not wanted:
|
||||
raise ValueError("name at least one gate")
|
||||
record = json.loads(Path(path).read_text())
|
||||
if record["classification"] != "failed_exit_1":
|
||||
raise ValueError(f"expected failed_exit_1, got {record['classification']}")
|
||||
reported = {gate["name"]: gate["passed"] for gate in record["gates"]}
|
||||
for name in wanted:
|
||||
if name not in reported:
|
||||
raise ValueError(f"gate {name} was never reported")
|
||||
if reported[name]:
|
||||
raise ValueError(f"gate {name} passed despite the injected fault")
|
||||
failed = sorted(name for name, passed in reported.items() if not passed)
|
||||
print(",".join(failed))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
sys.exit(f"FAIL negative control: {error}")
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Independent image oracle for the fixed scripted D3D11/D3D12 scene.
|
||||
|
||||
Build images by painting whole rectangles, independently of the workloads' pixel
|
||||
functions and GPU shaders. The fixed protocol is: far A at (32,32), near B at
|
||||
(96,96), 128-square quads with four 64-square colours; five 16-pixel key moves;
|
||||
rotate RGB to BRG; overwrite the top 16 rows with the frame number. Hash only the
|
||||
specified verification frames, in row-major RGBA order. No renderer or C oracle
|
||||
is called. The legacy digest seed is intentionally preserved (it differs from
|
||||
the standard FNV offset basis).
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
PALETTES = (((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)),
|
||||
((255, 255, 0), (0, 255, 255), (255, 0, 255), (128, 128, 128)))
|
||||
POSITIONS = ((96, 96), (112, 96), (128, 96), (128, 112), (112, 112), (112, 128))
|
||||
|
||||
|
||||
def image(frame, interval):
|
||||
pixels = bytearray(b"\x00\x00\x00\xff" * (256 * 256))
|
||||
|
||||
def rectangle(x, y, width, height, rgba):
|
||||
row = bytes(rgba) * width
|
||||
for line in range(y, y + height):
|
||||
start = (line * 256 + x) * 4
|
||||
pixels[start:start + width * 4] = row
|
||||
|
||||
# Painter's order is analytically equivalent to the scene's depth test.
|
||||
steps = min(frame // interval, 5)
|
||||
for palette, (x, y) in zip(PALETTES, ((32, 32), POSITIONS[steps])):
|
||||
for quadrant, (r, g, b) in enumerate(palette):
|
||||
rectangle(x + (quadrant % 2) * 64, y + (quadrant // 2) * 64, 64, 64, (b, r, g, 255))
|
||||
marker = (frame + 1) & 65535
|
||||
rectangle(0, 0, 256, 16, (marker & 255, marker >> 8, 77, 255))
|
||||
return pixels
|
||||
|
||||
|
||||
def expected_digest(frames, verify_every):
|
||||
interval = frames // 8
|
||||
selected = set(range(0, frames, verify_every)) | {0, frames - 1}
|
||||
selected.update(k * interval + 1 for k in range(1, 6) if k * interval + 1 < frames)
|
||||
digest = 1469598103934665603
|
||||
for frame in sorted(selected):
|
||||
for byte in image(frame, interval):
|
||||
digest = ((digest ^ byte) * 1099511628211) & 0xffffffffffffffff
|
||||
return f"{digest:016x}", len(selected)
|
||||
|
||||
|
||||
def main():
|
||||
record = json.loads(Path(sys.argv[1]).read_text())
|
||||
args = record["args"]
|
||||
if any(flag in args for flag in ["--fault", "--duration-s", "--external-input", "--interactive"]):
|
||||
raise ValueError("oracle accepts only the fixed scripted scene, without injected faults")
|
||||
frames = int(args[args.index("--frames") + 1]) if "--frames" in args else 600
|
||||
verify = int(args[args.index("--verify-every") + 1]) if "--verify-every" in args else 30
|
||||
if frames < 64 or verify < 1:
|
||||
raise ValueError("invalid verification schedule")
|
||||
gate = next(g for g in record["gates"] if g["name"] == "frame.continuous")
|
||||
if not gate["passed"]:
|
||||
raise ValueError("continuous rendering gate did not pass")
|
||||
observed = re.search(r"verified=(\d+) mismatched=0 digest=([0-9a-f]{16})", gate["detail"])
|
||||
expected, count = expected_digest(frames, verify)
|
||||
if not observed or observed.groups() != (str(count), expected):
|
||||
raise ValueError(f"independent digest mismatch: expected {count} verified frames, digest={expected}; {gate['detail']}")
|
||||
print(f"PASS independent image oracle: {count} frames digest={expected}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, StopIteration) as error:
|
||||
sys.exit(f"FAIL independent image oracle: {error}")
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
set -eu
|
||||
TC=${1:?usage: check-toolchain.sh LLVM_MINGW_DIR}
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
PIN=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["llvm_commit"])' "$ROOT/scripts/hybrid/toolchain.json")
|
||||
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
|
||||
for name in clang ld.lld; do
|
||||
[ -x "$TC/bin/$name" ] || { echo "missing $TC/bin/$name" >&2; exit 1; }
|
||||
lipo "$TC/bin/$name" -verify_arch arm64
|
||||
done
|
||||
"$TC/bin/x86_64-w64-mingw32-clang" --version | grep -F "$PIN" >/dev/null
|
||||
echo "verified ARM64-capable llvm-mingw compiler at $PIN" >&2
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Preserve unmodified notices for the standalone hybrid runner and Windows runtime."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
toolchain, output = map(lambda p: Path(p).resolve(), sys.argv[1:])
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
meta = json.loads(subprocess.check_output(["cargo", "metadata", "--locked", "--format-version", "1"], cwd=root))
|
||||
libc = [p for p in meta["packages"] if p["name"] == "libc"]
|
||||
if len(libc) != 1:
|
||||
sys.exit("expected exactly one locked libc dependency")
|
||||
package = libc[0]
|
||||
source = Path(package["manifest_path"]).parent
|
||||
shutil.copytree(source, output / "libc-source", dirs_exist_ok=True)
|
||||
notices = [source / "LICENSE-MIT", source / "LICENSE-APACHE"]
|
||||
for path in notices:
|
||||
shutil.copy2(path, output / ("libc-" + path.name))
|
||||
shutil.copy2(toolchain / "LICENSE.TXT", output / "llvm-mingw-LICENSE.TXT")
|
||||
for path in (toolchain / "x86_64-w64-mingw32/share/mingw32").glob("COPYING*"):
|
||||
shutil.copy2(path, output / ("mingw-" + path.name))
|
||||
sysroot = Path(subprocess.check_output(["rustc", "--print", "sysroot"], text=True).strip())
|
||||
docs = sysroot / "share/doc/rust"
|
||||
for name in ["COPYRIGHT.html", "COPYRIGHT-library.html"]:
|
||||
shutil.copy2(docs / name, output / ("rust-" + name))
|
||||
shutil.copytree(docs / "licenses", output / "rust-licenses", dirs_exist_ok=True)
|
||||
manifest = {"schema": "betterxen-build-notices/0", "rust": "1.100.0", "libc": {
|
||||
"version": package["version"], "license": package["license"], "source": package["source"]},
|
||||
"llvm_mingw": json.loads((root / "scripts/hybrid/toolchain.json").read_text()),
|
||||
"scope": "Standalone bx-cli plus original Windows workloads; no native research CLI or external proprietary components"}
|
||||
(output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Create a new dedicated test bottle, refusing to reuse an existing directory.
|
||||
|
||||
This uses CrossOver's observed cxbottle interface, not a vendor-supported automation API.
|
||||
The new bottle also has Wine's crash dialog turned off: with it on, a crashing program
|
||||
waits for a click and an unattended run only ends at its timeout.
|
||||
|
||||
RUNNER BOTTLE
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
runner, name = sys.argv[1:]
|
||||
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", name):
|
||||
sys.exit("use a simple new bottle name with letters, digits, dots, dashes or underscores")
|
||||
facts = json.loads(subprocess.check_output([runner, "crossover"], text=True))
|
||||
if not facts["installs"]:
|
||||
sys.exit("install CrossOver from CodeWeavers first")
|
||||
app = Path(facts["installs"][0]["path"])
|
||||
base = Path(facts.get("bottle_dir_preference") or "~/Library/Application Support/CrossOver/Bottles").expanduser()
|
||||
prefix = base / name
|
||||
if prefix.exists() or prefix.is_symlink():
|
||||
sys.exit(f"refusing to reuse {prefix}; choose a fresh dedicated name")
|
||||
subprocess.run([str(app / "Contents/SharedSupport/CrossOver/bin/cxbottle"), "--bottle", name,
|
||||
"--create", "--template", "win11_64"], check=True, timeout=180, stdout=sys.stderr)
|
||||
if not (prefix / "drive_c").is_dir():
|
||||
sys.exit(f"CrossOver did not create the expected bottle at {prefix}")
|
||||
with tempfile.TemporaryDirectory() as records:
|
||||
subprocess.run([str(Path(runner).resolve()), "run", "--bottle", name, "--timeout", "180", "--out", records, "--",
|
||||
str(prefix / "drive_c/windows/system32/reg.exe"), "add", r"HKCU\Software\Wine\WineDbg",
|
||||
"/v", "ShowCrashDialog", "/t", "REG_DWORD", "/d", "0", "/f"],
|
||||
check=True, timeout=300, stdout=sys.stderr)
|
||||
print(json.dumps({"schema": "betterxen-test-bottle/0", "bottle": name, "prefix": str(prefix), "created": True, "crash_dialog": False}))
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Install only open-source build dependencies. CrossOver and Apple tools remain external.
|
||||
set -eu
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
|
||||
command -v python3 >/dev/null
|
||||
command -v rustup >/dev/null || { echo "install native rustup from https://rustup.rs first" >&2; exit 1; }
|
||||
xcrun --find clang >/dev/null
|
||||
TC=$(python3 "$ROOT/scripts/hybrid/install-toolchain.py" "${1:-$HOME/Library/Caches/BetterXen/toolchains}")
|
||||
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
|
||||
rustup toolchain install 1.100.0 --profile minimal --component rustfmt --component clippy \
|
||||
--target aarch64-apple-darwin --target x86_64-pc-windows-gnullvm >&2
|
||||
printf '%s\n' "$TC"
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Install Microsoft's checksum-pinned open-source Windows DXC as an external guest tool."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
URL = "https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.9.2609/dxc_2026_09_29.zip"
|
||||
SHA256 = "ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1"
|
||||
|
||||
|
||||
def install(destination):
|
||||
destination = destination.expanduser().resolve()
|
||||
archive = destination / "dxc_2026_09_29.zip"
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if any(p != archive for p in destination.iterdir()):
|
||||
raise RuntimeError(f"{destination} already contains extracted files; choose a fresh installation directory")
|
||||
if not archive.exists():
|
||||
subprocess.run(["/usr/bin/curl", "--fail", "--location", "--retry", "3", "--connect-timeout", "30",
|
||||
URL, "-o", str(archive)], check=True)
|
||||
with archive.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if digest != SHA256:
|
||||
raise RuntimeError(f"DXC checksum mismatch: {digest}, expected {SHA256}")
|
||||
with zipfile.ZipFile(archive) as bundle:
|
||||
entries = []
|
||||
for member in bundle.infolist():
|
||||
# Microsoft's Windows zip uses backslashes; normalize before checking containment.
|
||||
name = member.filename.replace("\\", "/")
|
||||
if Path(name).is_absolute() or ".." in Path(name).parts or ":" in name or stat.S_ISLNK(member.external_attr >> 16):
|
||||
raise RuntimeError(f"invalid archive path {member.filename}")
|
||||
entries.append((member, name))
|
||||
for member, name in entries:
|
||||
path = destination / name
|
||||
if name.endswith("/"):
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with bundle.open(member) as source, path.open("xb") as target:
|
||||
shutil.copyfileobj(source, target)
|
||||
compiler = destination / "bin/x64/dxc.exe"
|
||||
if not compiler.is_file():
|
||||
raise RuntimeError("pinned archive lacks bin/x64/dxc.exe")
|
||||
print(compiler.parent)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
install(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / "Library/Caches/BetterXen/dxc-v1.9.2609")
|
||||
except (OSError, RuntimeError, zipfile.BadZipFile, subprocess.CalledProcessError) as error:
|
||||
sys.exit(str(error))
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Download the pinned external llvm-mingw release; print its installed path on stdout.
|
||||
|
||||
Only the checksum-verified archive is extracted. No compiler, workload or proprietary
|
||||
component is executed. Existing installations are never overwritten.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
|
||||
def install(destination):
|
||||
if not hasattr(tarfile, "data_filter"):
|
||||
raise RuntimeError("Python with tarfile.data_filter is required (Python 3.12 or newer)")
|
||||
pin = json.loads(Path(__file__).with_name("toolchain.json").read_text())
|
||||
destination = destination.expanduser().resolve()
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
archive = destination / pin["asset"]
|
||||
if not archive.exists():
|
||||
print(f'Downloading {pin["url"]}', file=sys.stderr)
|
||||
with tempfile.NamedTemporaryFile(dir=destination, delete=False) as out:
|
||||
temporary = Path(out.name)
|
||||
try:
|
||||
out.close()
|
||||
subprocess.run(["/usr/bin/curl", "--fail", "--location", "--retry", "3",
|
||||
"--connect-timeout", "30", "--output", str(temporary), pin["url"]], check=True)
|
||||
verify(temporary, pin["sha256"])
|
||||
# Publish without overwriting an archive installed by a concurrent invocation.
|
||||
os.link(temporary, archive)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
verify(archive, pin["sha256"])
|
||||
installed = destination / pin["asset"].removesuffix(".tar.xz")
|
||||
if installed.exists():
|
||||
raise RuntimeError(f"{installed} already exists; choose a fresh destination to avoid using a modified toolchain")
|
||||
with tempfile.TemporaryDirectory(prefix=".llvm-mingw-", dir=destination) as staging:
|
||||
with tarfile.open(archive, "r:xz") as bundle:
|
||||
# The pinned archive is trusted; also reject names escaping its single root.
|
||||
for member in bundle.getmembers():
|
||||
parts = Path(member.name).parts
|
||||
if not parts or parts[0] != installed.name or ".." in parts or Path(member.name).is_absolute():
|
||||
raise RuntimeError(f"unexpected archive path: {member.name}")
|
||||
bundle.extractall(staging, filter="data")
|
||||
os.rename(Path(staging) / installed.name, installed)
|
||||
print(f'Verified SHA-256 {pin["sha256"]}', file=sys.stderr)
|
||||
return installed
|
||||
|
||||
|
||||
def verify(path, expected):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
if digest.hexdigest() != expected:
|
||||
raise RuntimeError(f"checksum mismatch for {path}: got {digest.hexdigest()}, expected {expected}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
print(install(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / "Library/Caches/BetterXen/toolchains"))
|
||||
except (OSError, RuntimeError, tarfile.TarError, subprocess.CalledProcessError) as error:
|
||||
sys.exit(str(error))
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Private maintainer test bundle: original source, ARM64 runners and original Windows probes.
|
||||
set -eu
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
cd "$ROOT"
|
||||
[ -z "$(git status --porcelain)" ] || { echo "package requires a clean committed checkout" >&2; exit 1; }
|
||||
COMMIT=$(git rev-parse HEAD)
|
||||
OUT="$ROOT/artifacts/maintainer"
|
||||
[ "$(cat "$OUT/commit.txt")" = "$COMMIT" ] && [ ! -s "$OUT/source-status.txt" ] ||
|
||||
{ echo "rebuild from this clean commit before packaging" >&2; exit 1; }
|
||||
(cd "$OUT" && shasum -a 256 -c SHA256SUMS)
|
||||
mkdir -p "$ROOT/artifacts/packages"
|
||||
STAGE=$(mktemp -d "$ROOT/artifacts/packages/staging-XXXXXX")
|
||||
trap 'rm -rf "$STAGE"' EXIT HUP INT TERM
|
||||
NAME="betterxen-maintainer-$COMMIT"
|
||||
[ ! -e "$ROOT/artifacts/packages/$NAME.tar.gz" ] || { echo "artifact already exists; preserving it" >&2; exit 1; }
|
||||
mkdir "$STAGE/$NAME"
|
||||
mkdir "$STAGE/$NAME/bin"
|
||||
# bx-cli's only external dependency is libc (docs/licenses.md); CrossOver, Apple components,
|
||||
# compilers and DXC are never copied into the bundle.
|
||||
cp "$OUT/bin/bx-cli" "$STAGE/$NAME/bin/"
|
||||
mkdir "$STAGE/$NAME/workloads"
|
||||
for exe in selfcheck-c selfcheck-rust d3d11-clear d3d11-frameloop d3d11-integrated d3d12-integrated d3d12-lifetime d3d12-wave-probe; do
|
||||
cp "$OUT/workloads/$exe.exe" "$STAGE/$NAME/workloads/"
|
||||
done
|
||||
cp -R "$OUT/commit.txt" "$OUT/licenses" "$STAGE/$NAME/"
|
||||
(cd "$STAGE/$NAME" && shasum -a 256 bin/* workloads/*.exe > SHA256SUMS)
|
||||
cp LICENSE THIRD_PARTY_NOTICES.md docs/maintainer-testing.md "$STAGE/$NAME/"
|
||||
cp scripts/hybrid/test-bundle.sh "$STAGE/$NAME/test.sh"
|
||||
chmod +x "$STAGE/$NAME/test.sh"
|
||||
git archive --format=tar.gz --prefix=betterxen-source/ -o "$STAGE/$NAME/source.tar.gz" "$COMMIT"
|
||||
(cd "$STAGE/$NAME" && shasum -a 256 source.tar.gz > SOURCE-SHA256SUMS)
|
||||
tar -czf "$ROOT/artifacts/packages/$NAME.tar.gz" -C "$STAGE" "$NAME"
|
||||
(cd "$ROOT/artifacts/packages" && shasum -a 256 "$NAME.tar.gz" > "$NAME.tar.gz.sha256")
|
||||
echo "$ROOT/artifacts/packages/$NAME.tar.gz"
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Installed as test.sh at the root of a private maintainer bundle. No Rust or cross-compiler
|
||||
# is needed: both runners and original workload binaries were built from the recorded commit.
|
||||
set -eu
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
|
||||
BOTTLE=${1:?usage: ./test.sh NEW_DEDICATED_BOTTLE_NAME}
|
||||
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
|
||||
cd "$ROOT"
|
||||
/usr/bin/shasum -a 256 -c SHA256SUMS
|
||||
/usr/bin/shasum -a 256 -c SOURCE-SHA256SUMS
|
||||
BUNDLE_TEST=$(mktemp -d "$ROOT/test-XXXXXX")
|
||||
tar -xzf "$ROOT/source.tar.gz" -C "$BUNDLE_TEST"
|
||||
SOURCE="$BUNDLE_TEST/betterxen-source"
|
||||
BX="$ROOT/bin/bx-cli"
|
||||
python3 "$SOURCE/scripts/hybrid/create-test-bottle.py" "$BX" "$BOTTLE" >"$BUNDLE_TEST/bottle.json"
|
||||
"$BX" hybrid doctor --bottle "$BOTTLE" >"$BUNDLE_TEST/doctor.json"
|
||||
echo "Testing commit $(cat "$ROOT/commit.txt"); diagnostics under $BUNDLE_TEST"
|
||||
export BETTERXEN_RUNNER="$BX"
|
||||
export BETTERXEN_HYBRID_RUNNER="$BX"
|
||||
export BETTERXEN_WORKLOAD_DIR="$ROOT/workloads"
|
||||
export BETTERXEN_SOURCE_COMMIT
|
||||
BETTERXEN_SOURCE_COMMIT=$(cat "$ROOT/commit.txt")
|
||||
exec "$SOURCE/scripts/hybrid/accept-integrated.sh" unused "$BOTTLE"
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"release": "20261117",
|
||||
"asset": "llvm-mingw-20261117-ucrt-macos-universal.tar.xz",
|
||||
"url": "https://github.com/mstorsjo/llvm-mingw/releases/download/20261117/llvm-mingw-20261117-ucrt-macos-universal.tar.xz",
|
||||
"sha256": "98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa",
|
||||
"llvm_commit": "5b10d2d74929eae78912771222c9855af97496f4",
|
||||
"rust": "1.100.0"
|
||||
}
|
||||
@@ -185,9 +185,6 @@ pub enum Verdict {
|
||||
DeviceRemoved { reason: u32 },
|
||||
/// The GPU did not signal completion in time.
|
||||
TimedOut { detail: String },
|
||||
/// The device reported a highest shader model below the 6.6 the harness kernel
|
||||
/// requires. The field was parsed and printed before, but never judged (#567).
|
||||
UnsupportedShaderModel { reported: u8 },
|
||||
/// Every word still holds the sentinel: the kernel never wrote.
|
||||
KernelDidNotRun,
|
||||
/// The kernel wrote, but some words differ from the expected values.
|
||||
@@ -227,12 +224,6 @@ impl fmt::Display for Verdict {
|
||||
)
|
||||
}
|
||||
Self::TimedOut { detail } => write!(f, "FAIL: GPU timeout ({detail})"),
|
||||
Self::UnsupportedShaderModel { reported } => write!(
|
||||
f,
|
||||
"FAIL: highest shader model {}.{} is below the 6.6 the harness kernel requires",
|
||||
reported >> 4,
|
||||
reported & 0xf
|
||||
),
|
||||
Self::KernelDidNotRun => write!(
|
||||
f,
|
||||
"FAIL: all {WORDS} words still hold the sentinel 0x{SENTINEL:08x}; the kernel did not write"
|
||||
@@ -281,14 +272,6 @@ pub fn judge(report: &ProbeReport) -> Verdict {
|
||||
let incomplete = |reason: &str| Verdict::Incomplete {
|
||||
reason: reason.to_owned(),
|
||||
};
|
||||
// Every kernel the harness runs is SM 6.6. A device that reports less, or a
|
||||
// report with no shader_model record, must not pass on a matching readback
|
||||
// alone (#567). The live Rust test asserted this; the standalone verdict did not.
|
||||
match report.shader_model {
|
||||
Some(sm) if sm < 0x66 => return Verdict::UnsupportedShaderModel { reported: sm },
|
||||
None => return incomplete("no shader_model record"),
|
||||
Some(_) => {}
|
||||
}
|
||||
match report.dispatch {
|
||||
None => return incomplete("no dispatch record"),
|
||||
Some(d) if d != expected_dispatch => {
|
||||
@@ -358,29 +341,6 @@ mod tests {
|
||||
assert_eq!(judge(&report), Verdict::Pass);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shader_model_below_6_6_fails_even_with_a_matching_readback() {
|
||||
// The kernel is SM 6.6; the readback matching proves only that something wrote.
|
||||
for reported in ["0x65", "0x60"] {
|
||||
let lower = output(&good_words()).replace(
|
||||
"BXD3DM shader_model 0x66",
|
||||
&format!("BXD3DM shader_model {reported}"),
|
||||
);
|
||||
let report = parse_report(&lower).unwrap();
|
||||
assert_eq!(
|
||||
judge(&report),
|
||||
Verdict::UnsupportedShaderModel {
|
||||
reported: if reported == "0x65" { 0x65 } else { 0x60 }
|
||||
}
|
||||
);
|
||||
}
|
||||
// Without the record the harness cannot say the device can run the shader.
|
||||
let absent = output(&good_words()).replace("BXD3DM shader_model 0x66\n", "");
|
||||
let report = parse_report(&absent).unwrap();
|
||||
assert_eq!(report.shader_model, None);
|
||||
assert!(matches!(judge(&report), Verdict::Incomplete { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untouched_sentinel_means_the_kernel_did_not_run() {
|
||||
let report = parse_report(&output(&[SENTINEL; WORDS])).unwrap();
|
||||
|
||||
@@ -80,14 +80,12 @@ fn collect(rx: &Receiver<Event>, until: Instant) -> io::Result<(Vec<u8>, Vec<u8>
|
||||
Ok((stdout, stderr, true))
|
||||
}
|
||||
|
||||
/// `deadline: None` means the requested timeout is not representable on this clock, so the
|
||||
/// probe is allowed to run without one (#587).
|
||||
fn wait_until(child: &mut Child, deadline: Option<Instant>) -> io::Result<Option<ExitStatus>> {
|
||||
fn wait_until(child: &mut Child, deadline: Instant) -> io::Result<Option<ExitStatus>> {
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
}
|
||||
if deadline.is_some_and(|at| Instant::now() >= at) {
|
||||
if Instant::now() >= deadline {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
return Ok(None);
|
||||
@@ -114,13 +112,7 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
|
||||
command.env(key, value);
|
||||
}
|
||||
}
|
||||
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow, so a
|
||||
// huge value would abort the harness with exit 101 instead of one of its verdict codes
|
||||
// (#586). Saturate at the platform maximum instead: the probe then simply never times out.
|
||||
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow. When the
|
||||
// requested timeout is not representable the probe simply has no deadline; representing
|
||||
// that as `None` avoids inventing a fallback duration that might also not fit (#587).
|
||||
let deadline = Instant::now().checked_add(timeout);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut child = command.spawn()?;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
pump(
|
||||
@@ -134,11 +126,8 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
|
||||
tx,
|
||||
);
|
||||
let status = wait_until(&mut child, deadline)?;
|
||||
// With no deadline the probe has already exited, so draining still needs a bound.
|
||||
let drain_until = deadline
|
||||
.unwrap_or_else(Instant::now)
|
||||
.max(Instant::now() + DRAIN_GRACE);
|
||||
let (stdout, stderr, output_complete) = collect(&rx, drain_until)?;
|
||||
let (stdout, stderr, output_complete) =
|
||||
collect(&rx, deadline.max(Instant::now() + DRAIN_GRACE))?;
|
||||
Ok(ProbeRun {
|
||||
status,
|
||||
stdout: String::from_utf8_lossy(&stdout).into_owned(),
|
||||
@@ -172,35 +161,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrepresentable_deadline_leaves_the_probe_without_a_timeout() {
|
||||
// `checked_add` returns None for a timeout the clock cannot represent; the runner
|
||||
// must then wait for the probe normally instead of inventing a fallback duration
|
||||
// that could itself overflow (#587).
|
||||
let script = Script::new("nodeadline", "sleep 0.2; exit 0");
|
||||
let run = run_probe(
|
||||
&script.0,
|
||||
std::path::Path::new("/nonexistent/framework"),
|
||||
Duration::from_secs(u64::MAX),
|
||||
)
|
||||
.expect("an unrepresentable deadline must not abort the run");
|
||||
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
|
||||
assert!(run.output_complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overflowing_timeout_does_not_panic() {
|
||||
// u64::MAX seconds overflows `Instant + Duration`; before #586 this panicked.
|
||||
let script = Script::new("overflow", "exit 0");
|
||||
let run = run_probe(
|
||||
&script.0,
|
||||
std::path::Path::new("/nonexistent/framework"),
|
||||
Duration::from_secs(u64::MAX),
|
||||
);
|
||||
let run = run.expect("an overflowing timeout must still run the probe, not panic");
|
||||
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_the_framework_and_only_allowlisted_environment() {
|
||||
let script = Script::new("env", "echo \"args=$*\"; env; echo oops >&2; exit 3");
|
||||
@@ -226,70 +186,22 @@ mod tests {
|
||||
assert!(run.output_complete);
|
||||
}
|
||||
|
||||
/// Timeout for the tests below whose stand-in probe has to start and print before the
|
||||
/// deadline. Starting a freshly written script costs tens of milliseconds here and
|
||||
/// occasionally far more, so a few hundred milliseconds made these tests fail now and then
|
||||
/// (#479). They check what happens at the deadline, not how fast a script starts.
|
||||
const START_MARGIN: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Removes the pid file, and kills the recorded process if a failing test left it running.
|
||||
struct PidFile(PathBuf);
|
||||
|
||||
impl Drop for PidFile {
|
||||
fn drop(&mut self) {
|
||||
if std::thread::panicking()
|
||||
&& let Ok(pid) = std::fs::read_to_string(&self.0)
|
||||
{
|
||||
let _ = Command::new("/bin/kill").arg(pid.trim()).status();
|
||||
}
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kills_a_probe_that_exceeds_the_timeout() {
|
||||
let pid_file = PidFile(
|
||||
std::env::temp_dir().join(format!("bx-harness-probe's-{}.pid", std::process::id())),
|
||||
);
|
||||
let _ = std::fs::remove_file(&pid_file.0);
|
||||
// Pass the path as the value of --framework. The apostrophe tests literal path handling.
|
||||
// `exec` keeps the pid, so the recorded pid is the process that has to be killed.
|
||||
let script = Script::new(
|
||||
"hang",
|
||||
"echo $$ > \"$2\" || exit 1; echo started; exec sleep 30",
|
||||
);
|
||||
let script = Script::new("hang", "echo started; exec sleep 30");
|
||||
let started = Instant::now();
|
||||
let run = run_probe(&script.0, &pid_file.0, START_MARGIN).unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
let run = run_probe(&script.0, Path::new("/fw"), Duration::from_millis(300)).unwrap();
|
||||
assert!(run.status.is_none());
|
||||
// Output written before the kill is kept.
|
||||
assert_eq!(run.stdout, "started\n");
|
||||
// The probe ran until the deadline and no longer: it was killed, not waited for.
|
||||
assert!(elapsed >= START_MARGIN, "returned early after {elapsed:?}");
|
||||
assert!(
|
||||
elapsed < START_MARGIN + DRAIN_GRACE + Duration::from_secs(5),
|
||||
"returned after {elapsed:?}"
|
||||
);
|
||||
// The process is gone. `output_complete` is deliberately not asserted: tests run in
|
||||
// parallel, and a child spawned by another test at the wrong moment can inherit this
|
||||
// probe's pipe and hold it open (seen in 2 of 200 runs).
|
||||
let pid = std::fs::read_to_string(&pid_file.0).unwrap();
|
||||
let alive = Command::new("/bin/kill")
|
||||
.args(["-0", pid.trim()])
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(!alive, "probe {} survived the timeout", pid.trim());
|
||||
assert!(started.elapsed() < Duration::from_secs(10));
|
||||
}
|
||||
|
||||
/// The probe exits at once, but a background descendant inherits stdout and
|
||||
/// keeps it open well past the timeout.
|
||||
#[test]
|
||||
fn a_descendant_holding_the_pipes_cannot_outlast_the_deadline() {
|
||||
// The descendant has to outlive the bound asserted below by a wide margin.
|
||||
let script = Script::new("orphan", "sleep 6 & echo started");
|
||||
let timeout = START_MARGIN;
|
||||
let script = Script::new("orphan", "sleep 5 & echo started");
|
||||
let timeout = Duration::from_millis(500);
|
||||
let started = Instant::now();
|
||||
let run = run_probe(&script.0, Path::new("/fw"), timeout).unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
# dxbc-accc
|
||||
|
||||
Classifies D3D shader containers (`DXBC` with `DXIL`, legacy `SHDR`/`SHEX`, and `ACCC` chunks carrying BetterXen's synthetic `FSPX` table) and exposes the C ABI in [`abi/include/bx_shader_bridge.h`](../../../abi/include/bx_shader_bridge.h): `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal` and `bx_shader_free_buffer`.
|
||||
|
||||
## `FSPX` errors
|
||||
|
||||
A malformed `FSPX` table fails inspection with a `ParseError`; it never panics. Two bounds errors are kept apart (#599):
|
||||
|
||||
- **`FspxLayoutMismatch`:** a descriptor's offset lands inside the 16-byte header or the descriptor table, the region the synthetic layout reserves. The table does not follow BetterXen's clean-room layout. The error carries the section id, the offset and the table length.
|
||||
- **`FspxSectionOutOfBounds`:** a section starts after the table but runs past the end of the payload.
|
||||
|
||||
Both are still errors. Over the C ABI, both are `BX_SHADER_ERR_INVALID_BLOB`, so a caller of `bx_shader_inspect` cannot tell them apart yet; that would need an `[ABI]` change to `abi/include/bx_shader_bridge.h`.
|
||||
|
||||
## Guest access: `bx_shader_bridge.dll` (#445)
|
||||
|
||||
The shims that see shader bytecode (`d3d12_xs.dll`) are x86-64 Windows PE32+ DLLs running inside CrossOver. They cannot load the arm64 macOS library that `cargo build` produces on the host. The bridge reaches guests as a **Windows build of this same crate**, with no second implementation:
|
||||
|
||||
- **Build:** `cargo build --target x86_64-pc-windows-gnu` turns the crate's `cdylib` into a PE32+ DLL, published as `bx_shader_bridge.dll`. Its Export Address Table holds exactly the three header functions as direct RVAs. It imports only Windows system DLLs that Wine provides, so no MinGW runtime DLL. `guest/build.sh` enforces both. The allowlist is `KERNEL32`, `ntdll`, `bcryptprimitives`, `USERENV`, `WS2_32` and the `api-ms-win-crt-*` / `api-ms-win-core-*` sets.
|
||||
- **Callers:** a shim loads the bridge at run time with `GetProcAddress`, so a missing bridge is a logged condition, not a load failure of the shim.
|
||||
- **Full path:** it must load the bridge by **full path from its own directory**. That is `GetModuleFileNameW` of the shim's own module (for example via `GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, ...)`), plus `bx_shader_bridge.dll`, loaded with `LoadLibraryExW(..., LOAD_WITH_ALTERED_SEARCH_PATH)`.
|
||||
- **Why not the bare name:** a bare `LoadLibraryW(L"bx_shader_bridge.dll")` searches the guest EXE's directory first under the [standard search order](https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order). It can therefore miss a bridge staged next to the shims, or pick up a different copy.
|
||||
- **Staging:** the bridge is meant to be staged in the same directory as the shims that call it.
|
||||
- **Why not a host tool over captured logs:** the M2 gate needs the decision at `Create*PipelineState` time inside the guest. That means passing DXIL through and rejecting ACCC-only containers. An offline host tool could count shaders but could not act on them.
|
||||
|
||||
### Build and check
|
||||
|
||||
```sh
|
||||
rustup target add x86_64-pc-windows-gnu # once
|
||||
shader-transpiler/crates/dxbc-accc/guest/build.sh
|
||||
target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
|
||||
--exe target/bx-shader-bridge/check_bridge.exe
|
||||
```
|
||||
|
||||
`guest/build.sh` writes `bx_shader_bridge.dll` and `check_bridge.exe` to `target/bx-shader-bridge/`. It always builds into, and copies from, `<repo>/target`, whatever `CARGO_TARGET_DIR` says, so it cannot package a stale DLL. It resolves `cargo` and `rustc` through rustup, checks that this `rustc` has `std` for the Windows target, and prints which `rustc` it used. It fails if the Export Address Table holds anything other than the three entry points as direct RVAs (an ordinal-only entry or a forwarder fails it), or if any import is outside the allowlist above.
|
||||
|
||||
[`guest/check_bridge.c`](guest/check_bridge.c) is a C guest program built against the frozen header. It checks the struct layout with `_Static_assert`, loads the DLL by full path from its own directory, and sends nine containers through the DLL:
|
||||
- a real DXC SM 6.6 compute blob (from [`d3dmetal-harness`](../d3dmetal-harness/README.md));
|
||||
- synthetic DXIL pixel SM 6.0 with `RTS0`, once as is and once followed by 16 bytes past its declared size;
|
||||
- `ACCC` with an `FSPX` v1 stage section, and `ACCC` with an `FSPX` v0 stub;
|
||||
- `DXIL` + `ACCC`;
|
||||
- legacy `SHEX`;
|
||||
- two malformed blobs.
|
||||
|
||||
The program prints one `BXSHADER` line per container and a count line, and checks:
|
||||
- **Classification:**
|
||||
- kind, stage and shader model;
|
||||
- the declared container size;
|
||||
- the exact `DXIL` and `ACCC` chunk sizes and the root signature flag, each derived from the program's own chunk-table walk;
|
||||
- the digest, compared with header bytes 4..20 for every container, the real one included.
|
||||
- **Prepare:** exactly the declared container is copied, never the trailing bytes. ACCC-only and legacy are `BX_SHADER_ERR_UNSUPPORTED`. Malformed input is `BX_SHADER_ERR_INVALID_BLOB`, with output cleared.
|
||||
- **Free and argument errors:** freeing returned buffers, and null arguments at the DLL boundary.
|
||||
|
||||
Recorded run (one Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 `26.3.0.39832`, both a fresh prefix and a D3DMetal bottle):
|
||||
|
||||
```text
|
||||
BXSHADER counts dxil=3 accc_only=2 dual=1 legacy=1 unknown=0 invalid=2
|
||||
PASS: check_bridge (9 containers through bx_shader_bridge.dll)
|
||||
```
|
||||
|
||||
This is a synthetic, single-host result. It is not a measurement of any title's shader corpus, and not Xbox hardware.
|
||||
|
||||
Each of these faults compiled into the DLL fails the check: `dxil_chunk_size` clamped to 1, `accc_chunk_size` multiplied, the digest zeroed, `has_root_signature` set to 7, and the DXIL and ACCC kind numbers swapped. The last one also fails when it is rebuilt with `CARGO_TARGET_DIR` set elsewhere.
|
||||
|
||||
### Related work, owned elsewhere
|
||||
|
||||
Three of these pieces around this crate were recorded here as outstanding when this section was written and have since landed. The fourth is the trace summary of the records the shim emits.
|
||||
|
||||
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`, #445, #484):** present and in use. Its `LIBRARY` directive is `bx_shader_bridge.dll`, and `scripts/build-shims.sh` passes it to `cargo rustc` as `-C link-arg=…/abi/defs/bx_shader_bridge.def`, so the built DLL's export directory holds exactly the three header entry points and its internal name is `bx_shader_bridge.dll`, not `dxbc_accc.dll`. Cargo still names the built file `dxbc_accc.dll`; the script copies it to `build-shims/bin/bx_shader_bridge.dll`, and the verifier requires the export-directory name to match the `.def`.
|
||||
- **Staging in `scripts/build-shims.sh` (Track A, #484):** done. The script builds this crate for `x86_64-pc-windows-gnu`, copies the result to `build-shims/bin/bx_shader_bridge.dll`, and verifies its export directory with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. CI's hybrid job installs that target with its pinned toolchain, so `rustup target add x86_64-pc-windows-gnu` is only a one-off step for a local build, and the script stops with that hint when the target's `std` is missing.
|
||||
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (Track C, #466):** done. `CreateGraphicsPipelineState` and `CreateComputePipelineState` in `shims/d3d12_xs/proxy.cpp` run every stage through `BxShaderGate::admit` (`shims/d3d12_xs/shader_gate.cpp`), which calls `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` and emits `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` records through `bx_log_emit`. The bridge itself still writes its ACCC-only inspection line to the guest's stderr (`bx-shader event=prepare status=unsupported …`), because this crate does not link `bx_log_emit`; the JSONL records come from the shim.
|
||||
- **Trace summary of those records (`bx-cli trace`, Track A, #496):** the work to parse `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` into `bx-telemetry` and render them in `bx-cli trace` is tracked in #496. This bullet describes the split of responsibility only — it does not depend on that issue's status, and the crate's own behaviour is unaffected either way.
|
||||
|
||||
This change does not touch the crate's code or tests; the tests above still describe its own behavior.
|
||||
@@ -1,108 +0,0 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Builds bx_shader_bridge.dll (this crate for x86_64-pc-windows-gnu) and the guest check
|
||||
# check_bridge.exe into one directory (default: <repo>/target/bx-shader-bridge), then checks
|
||||
# the DLL: its Export Address Table holds exactly the three bx_shader_bridge.h entry points as
|
||||
# direct RVAs (no extra named or ordinal-only entries, no forwarders), and every imported DLL
|
||||
# is a system DLL Wine provides. Run the check under CrossOver afterwards, for example:
|
||||
# target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
|
||||
# --exe target/bx-shader-bridge/check_bridge.exe
|
||||
#
|
||||
# Needs: rustup with the x86_64-pc-windows-gnu target, x86_64-w64-mingw32-gcc / -objdump
|
||||
# (mingw-w64), and python3.
|
||||
set -eu
|
||||
|
||||
crate=$(cd "$(dirname "$0")/.." && pwd)
|
||||
root=$(cd "$crate/../../.." && pwd)
|
||||
out=${1:-$root/target/bx-shader-bridge}
|
||||
target=x86_64-pc-windows-gnu
|
||||
cc=${BX_MINGW_CC:-x86_64-w64-mingw32-gcc}
|
||||
objdump=${BX_MINGW_OBJDUMP:-x86_64-w64-mingw32-objdump}
|
||||
# Always build here and copy from here, whatever CARGO_TARGET_DIR or build.target-dir say,
|
||||
# so a stale DLL left elsewhere can never be packaged.
|
||||
target_dir=$root/target
|
||||
|
||||
for tool in "$cc" "$objdump" python3; do
|
||||
command -v "$tool" >/dev/null 2>&1 || { echo "build.sh: $tool not found" >&2; exit 1; }
|
||||
done
|
||||
|
||||
# Use one toolchain for both the target check and the build. With rustup, resolve cargo and
|
||||
# rustc through it (a cargo earlier on PATH, e.g. Homebrew's, has no Windows std).
|
||||
if command -v rustup >/dev/null 2>&1; then
|
||||
cargo=$(cd "$root" && rustup which cargo)
|
||||
rustc=$(cd "$root" && rustup which rustc)
|
||||
else
|
||||
cargo=$(command -v cargo) || { echo "build.sh: cargo not found" >&2; exit 1; }
|
||||
rustc=$(command -v rustc) || { echo "build.sh: rustc not found" >&2; exit 1; }
|
||||
fi
|
||||
libdir=$("$rustc" --print target-libdir --target "$target" 2>/dev/null || true)
|
||||
if [ -z "$libdir" ] || ! ls "$libdir"/libstd-*.rlib >/dev/null 2>&1; then
|
||||
echo "build.sh: $rustc ($("$rustc" --version)) has no std for $target" >&2
|
||||
echo "build.sh: install it with: rustup target add $target" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "build.sh: using $("$rustc" --version) at $rustc"
|
||||
|
||||
RUSTC=$rustc CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=$cc \
|
||||
"$cargo" build --locked --release -p dxbc-accc --target "$target" \
|
||||
--target-dir "$target_dir" --manifest-path "$root/Cargo.toml"
|
||||
mkdir -p "$out"
|
||||
cp "$target_dir/$target/release/dxbc_accc.dll" "$out/bx_shader_bridge.dll"
|
||||
dll=$out/bx_shader_bridge.dll
|
||||
|
||||
# Same reading of `objdump -p` as scripts/build-shims.sh: every populated Export Address Table
|
||||
# slot must be a direct RVA owned by one of the expected names.
|
||||
"$objdump" -p "$dll" | python3 -I -c '
|
||||
import re, sys
|
||||
expected = {"bx_shader_inspect", "bx_shader_prepare_for_d3dmetal", "bx_shader_free_buffer"}
|
||||
# The Windows-provided system DLLs a Rust std cdylib imports; anything else is an error.
|
||||
allowed = {"kernel32.dll", "ntdll.dll", "bcryptprimitives.dll", "userenv.dll", "ws2_32.dll"}
|
||||
allowed_prefixes = ("api-ms-win-crt-", "api-ms-win-core-")
|
||||
eat, names, imports, mode = {}, {}, [], None
|
||||
for line in sys.stdin:
|
||||
line = line.rstrip("\n")
|
||||
m = re.match(r"^\s*DLL Name:\s*(\S+)", line)
|
||||
if m:
|
||||
imports.append(m.group(1))
|
||||
if line.startswith("Export Address Table --"):
|
||||
mode = "eat"; continue
|
||||
if line.startswith("[Ordinal/Name Pointer] Table --"):
|
||||
mode = "names"; continue
|
||||
if not line.strip():
|
||||
mode = None; continue
|
||||
if mode == "eat":
|
||||
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(Export|Forwarder) RVA", line)
|
||||
if m:
|
||||
eat[int(m.group(1))] = m.group(2)
|
||||
elif mode == "names":
|
||||
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(\S+)", line)
|
||||
if m:
|
||||
names[m.group(2)] = int(m.group(1))
|
||||
errors = []
|
||||
if set(names) != expected:
|
||||
errors.append("named exports %s, want %s" % (sorted(names), sorted(expected)))
|
||||
owned = set(names.values())
|
||||
for ordinal, kind in sorted(eat.items()):
|
||||
if ordinal not in owned:
|
||||
errors.append("export @%d has no name (ordinal-only or stray entry)" % ordinal)
|
||||
if kind != "Export":
|
||||
errors.append("export @%d is a forwarder" % ordinal)
|
||||
for name, ordinal in names.items():
|
||||
if ordinal not in eat:
|
||||
errors.append("%s @%d missing from the Export Address Table" % (name, ordinal))
|
||||
for dll in imports:
|
||||
low = dll.lower()
|
||||
if low not in allowed and not low.startswith(allowed_prefixes):
|
||||
errors.append("unexpected import %s (only Wine-provided system DLLs are allowed)" % dll)
|
||||
if errors:
|
||||
sys.exit("build.sh: bx_shader_bridge.dll: " + "; ".join(errors))
|
||||
print("build.sh: exports %s; imports %s" % (" ".join(sorted(names)), " ".join(imports)))
|
||||
'
|
||||
|
||||
"$cc" -std=c11 -O2 -Wall -Wextra -Werror -static \
|
||||
-I"$root/abi/include" -I"$crate/../d3dmetal-harness/probe/shaders" \
|
||||
-o "$out/check_bridge.exe" "$crate/guest/check_bridge.c"
|
||||
|
||||
echo "built $dll"
|
||||
echo "built $out/check_bridge.exe"
|
||||
@@ -1,296 +0,0 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Guest-side check for bx_shader_bridge.dll, the x86-64 Windows build of this crate (#445).
|
||||
*
|
||||
* Runs as a PE32+ guest under CrossOver/Wine, loads the DLL by full path from its own directory,
|
||||
* and drives the three entry points from abi/include/bx_shader_bridge.h with synthetic
|
||||
* containers plus one real DXC SM 6.6 compute blob. It counts the classifications and checks
|
||||
* them, and the prepare/free behaviour, against expectations written here from the DXBC
|
||||
* layout and the frozen header, not from the Rust implementation.
|
||||
*
|
||||
* Output: "BXSHADER" lines with each blob's classification, one "BXSHADER counts" line, then
|
||||
* PASS or FAIL. Exit code 0 on success, 1 on a failed check, 2 if the DLL cannot be loaded.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <wchar.h>
|
||||
|
||||
#include "bx_shader_bridge.h"
|
||||
#include "fill_cs66.h" /* g_fill_cs66: DXC 1.9.2609 output, see d3dmetal-harness */
|
||||
|
||||
/* The Rust side asserts the same layout; agreeing here proves both sides read one struct. */
|
||||
_Static_assert(sizeof(bx_shader_kind_t) == 4, "C enum must be 4 bytes");
|
||||
_Static_assert(sizeof(bx_shader_inspection_t) == 48, "bx_shader_inspection_t size");
|
||||
_Static_assert(offsetof(bx_shader_inspection_t, container_size) == 16, "container_size offset");
|
||||
_Static_assert(offsetof(bx_shader_inspection_t, digest_hash) == 32, "digest_hash offset");
|
||||
|
||||
typedef bx_shader_status_t (*inspect_fn)(const uint8_t*, size_t, bx_shader_inspection_t*);
|
||||
typedef bx_shader_status_t (*prepare_fn)(const uint8_t*, size_t, uint8_t**, size_t*);
|
||||
typedef void (*free_fn)(uint8_t*, size_t);
|
||||
|
||||
static int failures;
|
||||
|
||||
#define CHECK(expr) \
|
||||
do { \
|
||||
if (!(expr)) { \
|
||||
fprintf(stderr, "FAIL: check_bridge line %d: %s\n", __LINE__, #expr); \
|
||||
++failures; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* --- Synthetic DXBC containers --- */
|
||||
|
||||
static void put32(uint8_t* at, uint32_t value) {
|
||||
at[0] = (uint8_t)value;
|
||||
at[1] = (uint8_t)(value >> 8);
|
||||
at[2] = (uint8_t)(value >> 16);
|
||||
at[3] = (uint8_t)(value >> 24);
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
const char* fourcc;
|
||||
const uint8_t* data;
|
||||
uint32_t size;
|
||||
} chunk_t;
|
||||
|
||||
/* DXBC layout: "DXBC", 16-byte digest, u32 version 1, u32 total size, u32 chunk count, then
|
||||
* one u32 offset per chunk; each chunk is fourcc, u32 size, payload. */
|
||||
static uint32_t build_dxbc(uint8_t* out, size_t cap, const chunk_t* chunks, uint32_t count) {
|
||||
uint32_t at = 32 + 4 * count;
|
||||
for (uint32_t i = 0; i < count; ++i) at += 8 + chunks[i].size;
|
||||
if (at > cap) abort();
|
||||
memcpy(out, "DXBC", 4);
|
||||
memset(out + 4, 0x5A, 16);
|
||||
put32(out + 20, 1);
|
||||
put32(out + 24, at);
|
||||
put32(out + 28, count);
|
||||
uint32_t offset = 32 + 4 * count;
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
put32(out + 32 + 4 * i, offset);
|
||||
memcpy(out + offset, chunks[i].fourcc, 4);
|
||||
put32(out + offset + 4, chunks[i].size);
|
||||
memcpy(out + offset + 8, chunks[i].data, chunks[i].size);
|
||||
offset += 8 + chunks[i].size;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
/* A 28-byte DxilProgramHeader: program version word (kind << 16 | major << 4 | minor), size
|
||||
* in dwords (7), "DXIL", DXIL version 1.0, bitcode offset 16, bitcode size 4, 4 bitcode bytes. */
|
||||
static void dxil_program(uint8_t out[28], uint32_t kind, uint32_t major, uint32_t minor) {
|
||||
memset(out, 0, 28);
|
||||
put32(out, kind << 16 | major << 4 | minor);
|
||||
put32(out + 4, 7);
|
||||
memcpy(out + 8, "DXIL", 4);
|
||||
put32(out + 12, 0x0100);
|
||||
put32(out + 16, 16);
|
||||
put32(out + 20, 4);
|
||||
put32(out + 24, 0xDEC011D1u);
|
||||
}
|
||||
|
||||
/* Size of the first chunk named fourcc in a well-formed container, 0 if absent. Written from
|
||||
* the DXBC layout, independently of the Rust parser. */
|
||||
static uint32_t get32(const uint8_t* at) {
|
||||
return (uint32_t)at[0] | (uint32_t)at[1] << 8 | (uint32_t)at[2] << 16 | (uint32_t)at[3] << 24;
|
||||
}
|
||||
|
||||
static int chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
|
||||
if (len < 32 || memcmp(bytes, "DXBC", 4) != 0) return 0;
|
||||
const uint32_t count = get32(bytes + 28);
|
||||
for (uint32_t i = 0; i < count && 36 + 4 * (size_t)i <= len; ++i) {
|
||||
const uint32_t offset = get32(bytes + 32 + 4 * i);
|
||||
if (offset + 8 <= len && memcmp(bytes + offset, fourcc, 4) == 0) {
|
||||
*size = get32(bytes + offset + 4);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* --- Cases --- */
|
||||
|
||||
typedef struct {
|
||||
const char* name;
|
||||
const uint8_t* bytes;
|
||||
size_t len;
|
||||
bx_shader_status_t inspect_status;
|
||||
bx_shader_kind_t kind;
|
||||
bx_shader_stage_t stage;
|
||||
uint32_t sm_major, sm_minor;
|
||||
uint32_t container_size; /* the container's declared size, which may be less than len */
|
||||
bx_shader_status_t prepare_status;
|
||||
} case_t;
|
||||
|
||||
static const char* kind_name(bx_shader_kind_t kind) {
|
||||
switch (kind) {
|
||||
case BX_SHADER_DXBC_DXIL: return "dxil";
|
||||
case BX_SHADER_DXBC_LEGACY: return "legacy";
|
||||
case BX_SHADER_DXBC_ACCC: return "accc_only";
|
||||
case BX_SHADER_DXBC_DUAL: return "dual";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
/* By full path beside this EXE, as a caller should (see the crate README). */
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD path_len = GetModuleFileNameW(NULL, path, MAX_PATH);
|
||||
wchar_t* slash = path_len && path_len < MAX_PATH ? wcsrchr(path, L'\\') : NULL;
|
||||
if (!slash || (size_t)(slash + 1 - path) + 21 > MAX_PATH) {
|
||||
fprintf(stderr, "FAIL: check_bridge: executable path too long\n");
|
||||
return 2;
|
||||
}
|
||||
wcscpy(slash + 1, L"bx_shader_bridge.dll");
|
||||
HMODULE dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
|
||||
if (!dll) {
|
||||
fprintf(stderr, "FAIL: check_bridge: bx_shader_bridge.dll not loaded (error %lu)\n", GetLastError());
|
||||
return 2;
|
||||
}
|
||||
inspect_fn inspect = (inspect_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_inspect");
|
||||
prepare_fn prepare = (prepare_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_prepare_for_d3dmetal");
|
||||
free_fn release = (free_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_free_buffer");
|
||||
if (!inspect || !prepare || !release) {
|
||||
fprintf(stderr, "FAIL: check_bridge: missing export\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
uint8_t dxil_cs66[28], dxil_ps60[28];
|
||||
dxil_program(dxil_cs66, 5, 6, 6); /* DXIL program kind 5 = compute */
|
||||
dxil_program(dxil_ps60, 0, 6, 0); /* kind 0 = pixel */
|
||||
const uint8_t rts0[4] = {1, 2, 3, 4};
|
||||
|
||||
/* FSPX v1 (BetterXen's synthetic layout): header "FSPX", version 1, 1 section, flags 0;
|
||||
* descriptor {id 1 (stage config), offset 28, size 12}; body {stage 6 compute, SM 6.0}. */
|
||||
uint8_t fspx_v1[40] = {0};
|
||||
memcpy(fspx_v1, "FSPX", 4);
|
||||
put32(fspx_v1 + 4, 1);
|
||||
put32(fspx_v1 + 8, 1);
|
||||
put32(fspx_v1 + 16, 1);
|
||||
put32(fspx_v1 + 20, 28);
|
||||
put32(fspx_v1 + 24, 12);
|
||||
put32(fspx_v1 + 28, BX_STAGE_COMPUTE);
|
||||
put32(fspx_v1 + 32, 6);
|
||||
put32(fspx_v1 + 36, 0);
|
||||
/* FSPX version 0: magic-only stub, no sections. */
|
||||
uint8_t fspx_v0[16] = {'F', 'S', 'P', 'X'};
|
||||
/* SM 5.0 compute SHEX token (program type 5 << 16 | 5 << 4 | 0) and a length dword. */
|
||||
uint8_t shex[8];
|
||||
put32(shex, 5u << 16 | 5u << 4);
|
||||
put32(shex + 4, 2);
|
||||
|
||||
static uint8_t ps60[256], accc_v1[256], accc_v0[256], dual[256], legacy[256];
|
||||
const chunk_t ps60_chunks[] = {{"RTS0", rts0, 4}, {"DXIL", dxil_ps60, 28}};
|
||||
const chunk_t accc_v1_chunks[] = {{"ACCC", fspx_v1, sizeof(fspx_v1)}};
|
||||
const chunk_t accc_v0_chunks[] = {{"ACCC", fspx_v0, sizeof(fspx_v0)}};
|
||||
const chunk_t dual_chunks[] = {{"DXIL", dxil_cs66, 28}, {"ACCC", fspx_v0, sizeof(fspx_v0)}};
|
||||
const chunk_t legacy_chunks[] = {{"SHEX", shex, sizeof(shex)}};
|
||||
const uint32_t ps60_len = build_dxbc(ps60, sizeof(ps60), ps60_chunks, 2);
|
||||
const uint32_t accc_v1_len = build_dxbc(accc_v1, sizeof(accc_v1), accc_v1_chunks, 1);
|
||||
const uint32_t accc_v0_len = build_dxbc(accc_v0, sizeof(accc_v0), accc_v0_chunks, 1);
|
||||
const uint32_t dual_len = build_dxbc(dual, sizeof(dual), dual_chunks, 2);
|
||||
const uint32_t legacy_len = build_dxbc(legacy, sizeof(legacy), legacy_chunks, 1);
|
||||
/* The pixel shader again, followed by 16 bytes that are not part of the container. */
|
||||
static uint8_t padded[256 + 16];
|
||||
memcpy(padded, ps60, ps60_len);
|
||||
memset(padded + ps60_len, 0xEE, 16);
|
||||
static const uint8_t truncated[20] = {'D', 'X', 'B', 'C'};
|
||||
static const uint8_t not_dxbc[64] = {'X', 'X', 'X', 'X'};
|
||||
|
||||
const case_t cases[] = {
|
||||
{"dxc_cs_6_6", g_fill_cs66, sizeof(g_fill_cs66), BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_COMPUTE, 6, 6,
|
||||
sizeof(g_fill_cs66), BX_SHADER_OK},
|
||||
{"synthetic_ps_6_0", ps60, ps60_len, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
|
||||
BX_SHADER_OK},
|
||||
{"trailing_bytes", padded, ps60_len + 16, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
|
||||
BX_SHADER_OK},
|
||||
{"accc_fspx_v1", accc_v1, accc_v1_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_COMPUTE, 6, 0, accc_v1_len,
|
||||
BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"accc_fspx_v0", accc_v0, accc_v0_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_UNKNOWN, 0, 0, accc_v0_len,
|
||||
BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"dual_dxil_accc", dual, dual_len, BX_SHADER_OK, BX_SHADER_DXBC_DUAL, BX_STAGE_COMPUTE, 6, 6, dual_len,
|
||||
BX_SHADER_OK},
|
||||
{"legacy_shex_5_0", legacy, legacy_len, BX_SHADER_OK, BX_SHADER_DXBC_LEGACY, BX_STAGE_COMPUTE, 5, 0,
|
||||
legacy_len, BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"truncated", truncated, sizeof(truncated), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN,
|
||||
0, 0, 0, BX_SHADER_ERR_INVALID_BLOB},
|
||||
{"not_dxbc", not_dxbc, sizeof(not_dxbc), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN, 0,
|
||||
0, 0, BX_SHADER_ERR_INVALID_BLOB},
|
||||
};
|
||||
const size_t count = sizeof(cases) / sizeof(cases[0]);
|
||||
|
||||
unsigned tally[5] = {0};
|
||||
unsigned invalid = 0;
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
const case_t* c = &cases[i];
|
||||
bx_shader_inspection_t info;
|
||||
memset(&info, 0xEE, sizeof(info));
|
||||
const bx_shader_status_t status = inspect(c->bytes, c->len, &info);
|
||||
printf("BXSHADER %s status=%d kind=%s stage=%d sm=%u.%u container_size=%u dxil=%u accc=%u rts0=%u\n",
|
||||
c->name, (int)status, kind_name(info.kind), (int)info.stage, info.shader_model_major,
|
||||
info.shader_model_minor, info.container_size, info.dxil_chunk_size, info.accc_chunk_size,
|
||||
info.has_root_signature);
|
||||
CHECK(status == c->inspect_status);
|
||||
if (status == BX_SHADER_OK) {
|
||||
if ((unsigned)info.kind < 5) ++tally[info.kind];
|
||||
CHECK(info.kind == c->kind);
|
||||
CHECK(info.stage == c->stage);
|
||||
CHECK(info.shader_model_major == c->sm_major && info.shader_model_minor == c->sm_minor);
|
||||
CHECK(info.container_size == c->container_size);
|
||||
/* Exact chunk sizes and the root signature flag, from this file's own chunk walk. */
|
||||
uint32_t want_dxil = 0, want_accc = 0, rts0_size = 0;
|
||||
chunk(c->bytes, c->len, "DXIL", &want_dxil);
|
||||
chunk(c->bytes, c->len, "ACCC", &want_accc);
|
||||
const uint32_t want_rts0 = (uint32_t)chunk(c->bytes, c->len, "RTS0", &rts0_size);
|
||||
CHECK(info.dxil_chunk_size == want_dxil);
|
||||
CHECK(info.accc_chunk_size == want_accc);
|
||||
CHECK(info.has_root_signature == want_rts0);
|
||||
CHECK((want_dxil != 0) == (c->kind == BX_SHADER_DXBC_DXIL || c->kind == BX_SHADER_DXBC_DUAL));
|
||||
CHECK((want_accc != 0) == (c->kind == BX_SHADER_DXBC_ACCC || c->kind == BX_SHADER_DXBC_DUAL));
|
||||
/* The digest is the container header's bytes 4..20, for every case. */
|
||||
CHECK(memcmp(info.digest_hash, c->bytes + 4, 16) == 0);
|
||||
} else {
|
||||
++invalid;
|
||||
const bx_shader_inspection_t zero = {0};
|
||||
CHECK(memcmp(&info, &zero, sizeof(info)) == 0); /* cleared on failure */
|
||||
}
|
||||
|
||||
uint8_t* copy = (uint8_t*)(uintptr_t)1;
|
||||
size_t copy_len = 1;
|
||||
const bx_shader_status_t prepared = prepare(c->bytes, c->len, ©, ©_len);
|
||||
CHECK(prepared == c->prepare_status);
|
||||
if (prepared == BX_SHADER_OK) {
|
||||
/* Only the declared container is copied, never bytes past it. */
|
||||
CHECK(copy && copy_len == c->container_size && memcmp(copy, c->bytes, c->container_size) == 0);
|
||||
release(copy, copy_len);
|
||||
} else {
|
||||
CHECK(copy == NULL && copy_len == 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Argument checks at the DLL boundary. */
|
||||
bx_shader_inspection_t info;
|
||||
CHECK(inspect(g_fill_cs66, sizeof(g_fill_cs66), NULL) == BX_SHADER_ERR_INVALID_BLOB);
|
||||
CHECK(inspect(NULL, 16, &info) == BX_SHADER_ERR_INVALID_BLOB);
|
||||
uint8_t* copy = NULL;
|
||||
CHECK(prepare(g_fill_cs66, sizeof(g_fill_cs66), NULL, NULL) == BX_SHADER_ERR_INVALID_BLOB);
|
||||
CHECK(prepare(NULL, 16, ©, &(size_t){0}) == BX_SHADER_ERR_INVALID_BLOB && copy == NULL);
|
||||
release(NULL, 0);
|
||||
|
||||
printf("BXSHADER counts dxil=%u accc_only=%u dual=%u legacy=%u unknown=%u invalid=%u\n",
|
||||
tally[BX_SHADER_DXBC_DXIL], tally[BX_SHADER_DXBC_ACCC], tally[BX_SHADER_DXBC_DUAL],
|
||||
tally[BX_SHADER_DXBC_LEGACY], tally[BX_SHADER_UNKNOWN], invalid);
|
||||
CHECK(tally[BX_SHADER_DXBC_DXIL] == 3 && tally[BX_SHADER_DXBC_ACCC] == 2 && tally[BX_SHADER_DXBC_DUAL] == 1);
|
||||
CHECK(tally[BX_SHADER_DXBC_LEGACY] == 1 && tally[BX_SHADER_UNKNOWN] == 0 && invalid == 2);
|
||||
|
||||
if (failures) {
|
||||
fprintf(stderr, "FAIL: check_bridge (%d failed checks)\n", failures);
|
||||
return 1;
|
||||
}
|
||||
printf("PASS: check_bridge (%u containers through bx_shader_bridge.dll)\n", (unsigned)count);
|
||||
return 0;
|
||||
}
|
||||
@@ -10,13 +10,6 @@
|
||||
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
|
||||
//! count is rejected before any descriptor is compared with another, so
|
||||
//! inspection stays allocation-free and the pairwise check stays bounded.
|
||||
//!
|
||||
//! A descriptor whose offset lands inside the 16-byte header or the
|
||||
//! descriptor table itself is a layout mismatch, reported apart from a
|
||||
//! section that runs past the end of the payload. Read through this layout,
|
||||
//! such a table is not merely truncated or corrupt: its descriptors do not
|
||||
//! mean `(id, offset, size)` relative to the payload as this module assumes.
|
||||
//! It is still an error, and the container is still refused.
|
||||
|
||||
use super::{ShaderStage, read_u32_le};
|
||||
|
||||
@@ -89,22 +82,9 @@ impl FspxInfo {
|
||||
pub(crate) enum FspxError {
|
||||
Truncated,
|
||||
BadVersion(u32),
|
||||
SectionOutOfBounds {
|
||||
section_id: u32,
|
||||
},
|
||||
/// The descriptor's offset lies inside the header plus descriptor table,
|
||||
/// the region this layout reserves, so the table does not follow it.
|
||||
LayoutMismatch {
|
||||
section_id: u32,
|
||||
offset: u32,
|
||||
table_end: u32,
|
||||
},
|
||||
DuplicateSection {
|
||||
section_id: u32,
|
||||
},
|
||||
Overlap {
|
||||
section_id: u32,
|
||||
},
|
||||
SectionOutOfBounds { section_id: u32 },
|
||||
DuplicateSection { section_id: u32 },
|
||||
Overlap { section_id: u32 },
|
||||
BadStageConfig,
|
||||
TooManySections(u32),
|
||||
}
|
||||
@@ -237,15 +217,6 @@ fn walk_sections(
|
||||
) -> Result<(), FspxError> {
|
||||
for index in 0..header.count {
|
||||
let (id, offset, size) = descriptor_at(payload, index)?;
|
||||
if usize::try_from(offset).is_ok_and(|start| start < header.table_end) {
|
||||
// `table_end` is at most 16 + 64 * 12 bytes, so it fits in u32.
|
||||
let table_end = u32::try_from(header.table_end).unwrap_or(u32::MAX);
|
||||
return Err(FspxError::LayoutMismatch {
|
||||
section_id: id,
|
||||
offset,
|
||||
table_end,
|
||||
});
|
||||
}
|
||||
let end = section_end(offset, size, header.table_end, payload.len())
|
||||
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
|
||||
for prev in 0..index {
|
||||
|
||||
@@ -9,10 +9,7 @@
|
||||
//! An `ACCC` payload that begins with `FSPX` uses the layout documented on
|
||||
//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table of
|
||||
//! at most [`FSPX_MAX_SECTIONS`] descriptors. A larger count is
|
||||
//! [`ParseError::FspxTooManySections`] before any pairwise comparison. A
|
||||
//! descriptor whose offset lands inside the header plus descriptor table is
|
||||
//! [`ParseError::FspxLayoutMismatch`], kept apart from
|
||||
//! [`ParseError::FspxSectionOutOfBounds`] (a section past the payload end).
|
||||
//! [`ParseError::FspxTooManySections`] before any pairwise comparison.
|
||||
//! Section 0 and section 7 are opaque header ranges, section 1 is the stage
|
||||
//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2
|
||||
//! code byte range. The code bytes are not decoded. This layout is synthetic.
|
||||
@@ -29,16 +26,13 @@
|
||||
//! at least 16. `BitcodeSize` must be non-zero, and `8 + BitcodeOffset +
|
||||
//! BitcodeSize` must fit in `SizeInUint32 * 4`. A zero-length bitcode is
|
||||
//! [`ParseError::BadDxilHeader`], matching DXC's `IsValidDxilProgramHeader`,
|
||||
//! so preparation does not copy it. A bitcode payload starting with `NOBC`
|
||||
//! marks a header-only container (no executable bitcode), which keeps `DXIL`
|
||||
//! size and stage metadata but does not classify as executable `DXIL`.
|
||||
//! so preparation does not copy it.
|
||||
//!
|
||||
//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`.
|
||||
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
|
||||
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
|
||||
//! including when an accompanying `FSPX` table is malformed, and logs only an
|
||||
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation
|
||||
//! is not implemented.
|
||||
//! copies `container_size` bytes when a `DXIL` chunk is present, including when
|
||||
//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only
|
||||
//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented.
|
||||
|
||||
mod c_abi;
|
||||
mod fspx;
|
||||
@@ -100,104 +94,22 @@ pub struct ShaderInspection {
|
||||
pub chunks: Vec<ChunkInfo>,
|
||||
}
|
||||
|
||||
impl ShaderInspection {
|
||||
/// Payload of the first chunk tagged `fourcc`, if present and fully
|
||||
/// inside the container. Returns `None` when absent, when the declared
|
||||
/// size would run past `container_size` or `container`, or when `offset`
|
||||
/// points into the DXBC header or chunk-offset table instead of a chunk
|
||||
/// header.
|
||||
///
|
||||
/// `container` must be the same bytes passed to [`inspect_dxbc`]; the
|
||||
/// inspection only stores chunk metadata, so the original container is
|
||||
/// required to slice out the payload. `ChunkInfo::offset` is relative to
|
||||
/// the start of the `DXBC` container and points at the 8-byte chunk
|
||||
/// header (fourcc + size), so the payload begins at `offset + 8`.
|
||||
///
|
||||
/// A zero-size chunk yields `Some(&[])`: the header is present and
|
||||
/// in-bounds, so an empty payload is a valid result rather than an
|
||||
/// absence. Callers that require a minimum size must check the returned
|
||||
/// slice length.
|
||||
///
|
||||
/// Only the already-parsed `self.chunks` table is consulted; the raw
|
||||
/// chunk table is not re-walked. When several chunks share `fourcc`,
|
||||
/// the first one in table order wins, matching the C++ `find_chunk`.
|
||||
pub fn chunk_payload<'a>(&self, container: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
let chunk = self.chunks.iter().find(|c| &c.fourcc == fourcc)?;
|
||||
let table_bytes = u64::try_from(self.chunks.len()).ok()?.checked_mul(4)?;
|
||||
let table_end = 32u64.checked_add(table_bytes)?;
|
||||
if u64::from(chunk.offset) < table_end {
|
||||
return None;
|
||||
}
|
||||
let start = u64::from(chunk.offset).checked_add(8)?;
|
||||
let end = start.checked_add(u64::from(chunk.size))?;
|
||||
if end > u64::from(self.container_size) {
|
||||
return None;
|
||||
}
|
||||
let start = usize::try_from(start).ok()?;
|
||||
let end = usize::try_from(end).ok()?;
|
||||
if end > container.len() {
|
||||
return None;
|
||||
}
|
||||
container.get(start..end)
|
||||
}
|
||||
|
||||
/// True when a chunk header tagged `fourcc` exists, whatever its
|
||||
/// declared size. Mirrors the C++ `has_chunk_tag`: presence without
|
||||
/// trusting the size.
|
||||
pub fn has_chunk_tag(&self, fourcc: &[u8; 4]) -> bool {
|
||||
self.chunks.iter().any(|c| &c.fourcc == fourcc)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ParseError {
|
||||
TooShort,
|
||||
BadMagic,
|
||||
UnsupportedVersion(u32),
|
||||
TruncatedChunkTable,
|
||||
ChunkOutOfBounds {
|
||||
index: usize,
|
||||
},
|
||||
ChunkOutOfBounds { index: usize },
|
||||
TruncatedContainer,
|
||||
FspxTruncated {
|
||||
chunk: usize,
|
||||
},
|
||||
FspxBadVersion {
|
||||
chunk: usize,
|
||||
version: u32,
|
||||
},
|
||||
FspxSectionOutOfBounds {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
},
|
||||
/// A descriptor's offset lands inside the `FSPX` header plus descriptor
|
||||
/// table (`table_end` bytes), which the synthetic layout reserves. The
|
||||
/// table does not follow BetterXen's clean-room layout; it is not reported
|
||||
/// as an out-of-bounds section. The container is still rejected.
|
||||
FspxLayoutMismatch {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
offset: u32,
|
||||
table_end: u32,
|
||||
},
|
||||
FspxDuplicateSection {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
},
|
||||
FspxSectionOverlap {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
},
|
||||
FspxBadStageConfig {
|
||||
chunk: usize,
|
||||
},
|
||||
FspxTooManySections {
|
||||
chunk: usize,
|
||||
count: u32,
|
||||
},
|
||||
BadDxilHeader {
|
||||
chunk: usize,
|
||||
},
|
||||
FspxTruncated { chunk: usize },
|
||||
FspxBadVersion { chunk: usize, version: u32 },
|
||||
FspxSectionOutOfBounds { chunk: usize, section_id: u32 },
|
||||
FspxDuplicateSection { chunk: usize, section_id: u32 },
|
||||
FspxSectionOverlap { chunk: usize, section_id: u32 },
|
||||
FspxBadStageConfig { chunk: usize },
|
||||
FspxTooManySections { chunk: usize, count: u32 },
|
||||
BadDxilHeader { chunk: usize },
|
||||
}
|
||||
|
||||
impl fmt::Display for ParseError {
|
||||
@@ -221,15 +133,6 @@ impl fmt::Display for ParseError {
|
||||
"FSPX section {section_id} out of bounds in chunk {chunk}"
|
||||
)
|
||||
}
|
||||
Self::FspxLayoutMismatch {
|
||||
chunk,
|
||||
section_id,
|
||||
offset,
|
||||
table_end,
|
||||
} => write!(
|
||||
f,
|
||||
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the synthetic FSPX layout"
|
||||
),
|
||||
Self::FspxDuplicateSection { chunk, section_id } => {
|
||||
write!(f, "duplicate FSPX section {section_id} in chunk {chunk}")
|
||||
}
|
||||
@@ -282,16 +185,6 @@ fn fspx_error(chunk: usize, err: fspx::FspxError) -> ParseError {
|
||||
fspx::FspxError::SectionOutOfBounds { section_id } => {
|
||||
ParseError::FspxSectionOutOfBounds { chunk, section_id }
|
||||
}
|
||||
fspx::FspxError::LayoutMismatch {
|
||||
section_id,
|
||||
offset,
|
||||
table_end,
|
||||
} => ParseError::FspxLayoutMismatch {
|
||||
chunk,
|
||||
section_id,
|
||||
offset,
|
||||
table_end,
|
||||
},
|
||||
fspx::FspxError::DuplicateSection { section_id } => {
|
||||
ParseError::FspxDuplicateSection { chunk, section_id }
|
||||
}
|
||||
@@ -316,22 +209,14 @@ fn record_fspx_stage(
|
||||
}
|
||||
}
|
||||
|
||||
enum DxilProgram {
|
||||
Executable((ShaderStage, u8, u8)),
|
||||
HeaderOnly((ShaderStage, u8, u8)),
|
||||
}
|
||||
|
||||
/// `DxilProgramHeader` check from the public DirectXShaderCompiler container.
|
||||
///
|
||||
/// `SizeInUint32 * 4` must cover the 24-byte header and fit in `payload`.
|
||||
/// `BitcodeOffset` is from the start of `DxilBitcodeHeader` at program byte 8
|
||||
/// and must be at least 16. `BitcodeSize` must be non-zero, and
|
||||
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program.
|
||||
///
|
||||
/// A bitcode payload beginning with `NOBC` is a header-only container (for
|
||||
/// example, reflection or signature metadata with bitcode stripped) and is
|
||||
/// reported as [`DxilProgram::HeaderOnly`] rather than executable DXIL.
|
||||
fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
|
||||
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program. The
|
||||
/// bitcode bytes are not decoded.
|
||||
fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
|
||||
const PROGRAM_PREFIX: u64 = 8;
|
||||
const BITCODE_HEADER: u64 = 16;
|
||||
const MIN_PROGRAM: u64 = PROGRAM_PREFIX + BITCODE_HEADER;
|
||||
@@ -360,16 +245,7 @@ fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
|
||||
if end > program_bytes {
|
||||
return Err(());
|
||||
}
|
||||
let bitcode_start =
|
||||
usize::try_from(PROGRAM_PREFIX + u64::from(bitcode_offset)).map_err(|_| ())?;
|
||||
let bitcode_end = usize::try_from(end).map_err(|_| ())?;
|
||||
let bitcode = payload.get(bitcode_start..bitcode_end).ok_or(())?;
|
||||
let stage = program_stage(program_version);
|
||||
if bitcode.starts_with(b"NOBC") {
|
||||
Ok(DxilProgram::HeaderOnly(stage))
|
||||
} else {
|
||||
Ok(DxilProgram::Executable(stage))
|
||||
}
|
||||
Ok(program_stage(program_version))
|
||||
}
|
||||
|
||||
struct ContainerLimit {
|
||||
@@ -476,37 +352,6 @@ fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKi
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DxilChunkState {
|
||||
has_executable: bool,
|
||||
size: u32,
|
||||
executable_stage: Option<(ShaderStage, u8, u8)>,
|
||||
header_only_stage: Option<(ShaderStage, u8, u8)>,
|
||||
}
|
||||
|
||||
impl DxilChunkState {
|
||||
/// Record a `DXIL` chunk, keeping executable metadata ahead of `NOBC`
|
||||
/// header-only placeholders regardless of chunk order.
|
||||
fn record(&mut self, chunk: usize, size: u32, payload: &[u8]) -> Result<(), ParseError> {
|
||||
match read_dxil_program(payload).map_err(|()| ParseError::BadDxilHeader { chunk })? {
|
||||
DxilProgram::Executable(stage) => {
|
||||
self.has_executable = true;
|
||||
self.size = size;
|
||||
self.executable_stage = Some(stage);
|
||||
}
|
||||
DxilProgram::HeaderOnly(stage) => {
|
||||
if !self.has_executable {
|
||||
self.size = size;
|
||||
}
|
||||
if self.header_only_stage.is_none() {
|
||||
self.header_only_stage = Some(stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not
|
||||
/// keep chunk or section lists.
|
||||
pub(crate) struct DxbcSummary {
|
||||
@@ -525,16 +370,24 @@ pub(crate) struct DxbcSummary {
|
||||
///
|
||||
/// A malformed `FSPX` table is still [`Err`], so inspection can report it.
|
||||
pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
|
||||
let mut dxil = DxilChunkState::default();
|
||||
let mut has_dxil = false;
|
||||
let mut has_accc = false;
|
||||
let mut has_legacy = false;
|
||||
let mut has_root_signature = false;
|
||||
let mut dxil_size = 0u32;
|
||||
let mut accc_size = 0u32;
|
||||
let mut dxil_stage = None;
|
||||
let mut legacy_stage = None;
|
||||
let mut fspx_stage = None;
|
||||
let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| {
|
||||
match &fourcc {
|
||||
b"DXIL" => dxil.record(index, size, payload)?,
|
||||
b"DXIL" => {
|
||||
let stage = read_dxil_program(payload)
|
||||
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
|
||||
has_dxil = true;
|
||||
dxil_size = size;
|
||||
dxil_stage = Some(stage);
|
||||
}
|
||||
b"ACCC" => {
|
||||
has_accc = true;
|
||||
accc_size = size;
|
||||
@@ -555,40 +408,36 @@ pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let (stage, shader_model_major, shader_model_minor) = dxil
|
||||
.executable_stage
|
||||
let (stage, shader_model_major, shader_model_minor) = dxil_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.or(dxil.header_only_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
Ok(DxbcSummary {
|
||||
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
|
||||
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
|
||||
stage,
|
||||
shader_model_major,
|
||||
shader_model_minor,
|
||||
container_size: header.container_size,
|
||||
digest: header.digest,
|
||||
has_root_signature,
|
||||
dxil_size: dxil.size,
|
||||
dxil_size,
|
||||
accc_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// `Ok(Some(container_size))` when the container is structurally valid and
|
||||
/// contains a `DXIL` chunk with an executable `DxilProgramHeader` (not a
|
||||
/// `NOBC` header-only placeholder). A malformed `FSPX` table does not hide that
|
||||
/// chunk. A `DXIL` fourcc whose payload is not a valid `DxilProgramHeader` is
|
||||
/// [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
|
||||
/// structurally valid and has no executable `DXIL` chunk.
|
||||
/// contains a `DXIL` chunk with a `DxilProgramHeader`. A malformed `FSPX`
|
||||
/// table does not hide that chunk. A `DXIL` fourcc whose payload is not that
|
||||
/// header is [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
|
||||
/// structurally valid and has no `DXIL` chunk.
|
||||
pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError> {
|
||||
let mut has_dxil = false;
|
||||
let header = visit_chunks(bytes, |index, _offset, fourcc, _size, payload| {
|
||||
if &fourcc == b"DXIL" {
|
||||
match read_dxil_program(payload) {
|
||||
Ok(DxilProgram::Executable(_)) => has_dxil = true,
|
||||
Ok(DxilProgram::HeaderOnly(_)) => {}
|
||||
Err(()) => return Err(ParseError::BadDxilHeader { chunk: index }),
|
||||
if read_dxil_program(payload).is_err() {
|
||||
return Err(ParseError::BadDxilHeader { chunk: index });
|
||||
}
|
||||
has_dxil = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -608,19 +457,27 @@ pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError
|
||||
/// container through.
|
||||
pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
|
||||
let mut chunks = Vec::new();
|
||||
let mut dxil = DxilChunkState::default();
|
||||
let mut has_dxil = false;
|
||||
let mut has_accc = false;
|
||||
let mut has_legacy = false;
|
||||
let mut has_root_signature = false;
|
||||
let mut dxil_size = 0u32;
|
||||
let mut accc_size = 0u32;
|
||||
let mut accc_is_fspx = false;
|
||||
let mut dxil_stage = None;
|
||||
let mut legacy_stage = None;
|
||||
let mut fspx_stage = None;
|
||||
let mut fspx = None;
|
||||
|
||||
let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| {
|
||||
match &fourcc {
|
||||
b"DXIL" => dxil.record(index, size, payload)?,
|
||||
b"DXIL" => {
|
||||
let stage = read_dxil_program(payload)
|
||||
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
|
||||
has_dxil = true;
|
||||
dxil_size = size;
|
||||
dxil_stage = Some(stage);
|
||||
}
|
||||
b"ACCC" => {
|
||||
has_accc = true;
|
||||
accc_size = size;
|
||||
@@ -658,22 +515,21 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let (stage, sm_major, sm_minor) = dxil
|
||||
.executable_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.or(dxil.header_only_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
let (stage, sm_major, sm_minor) =
|
||||
dxil_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
|
||||
Ok(ShaderInspection {
|
||||
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
|
||||
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
|
||||
stage,
|
||||
shader_model_major: sm_major,
|
||||
shader_model_minor: sm_minor,
|
||||
container_size: header.container_size,
|
||||
digest: header.digest,
|
||||
has_root_signature,
|
||||
dxil_size: dxil.size,
|
||||
dxil_size,
|
||||
accc_size,
|
||||
accc_is_fspx,
|
||||
fspx,
|
||||
@@ -1012,11 +868,9 @@ mod tests {
|
||||
),
|
||||
(
|
||||
fspx_header(1, 1, &[(1, 0, 4)], 28),
|
||||
ParseError::FspxLayoutMismatch {
|
||||
ParseError::FspxSectionOutOfBounds {
|
||||
chunk: 0,
|
||||
section_id: 1,
|
||||
offset: 0,
|
||||
table_end: 28,
|
||||
},
|
||||
),
|
||||
(
|
||||
@@ -1070,167 +924,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn truncated_prefixes_do_not_panic() {
|
||||
let mut nobc_dxil = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
nobc_dxil[24..28].copy_from_slice(b"NOBC");
|
||||
let blobs = [
|
||||
synthetic_dxil_blob(),
|
||||
build_synthetic_dxbc(&[(b"DXIL", &nobc_dxil)]),
|
||||
build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]),
|
||||
build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]),
|
||||
vec![0xFF; 64],
|
||||
];
|
||||
for blob in blobs {
|
||||
for len in 0..=blob.len() {
|
||||
let _ = inspect_dxbc(&blob[..len]);
|
||||
let _ = summarize_dxbc(&blob[..len]);
|
||||
let _ = dxil_container_len(&blob[..len]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A two-section table (`table_end` = 16 + 2 * 12 = 40) whose second
|
||||
/// descriptor's offset is `second_offset`. The first descriptor is a valid
|
||||
/// 12-byte stage section at 40, and the payload is 64 bytes long.
|
||||
fn fspx_two_sections(second_offset: u32) -> Vec<u8> {
|
||||
let mut payload = fspx_header(1, 2, &[(1, 40, 12), (6, second_offset, 4)], 64);
|
||||
payload[40..44].copy_from_slice(&6u32.to_le_bytes());
|
||||
payload[44..48].copy_from_slice(&6u32.to_le_bytes());
|
||||
payload
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fspx_offset_inside_header_or_table_is_layout_mismatch() {
|
||||
// Inside the 16-byte header, inside the first descriptor, inside the
|
||||
// descriptor itself, and the last reserved byte.
|
||||
for offset in [0u32, 8, 16, 28, 39] {
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(offset))]);
|
||||
let expected = ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 6,
|
||||
offset,
|
||||
table_end: 40,
|
||||
};
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(expected.clone()),
|
||||
"offset {offset}"
|
||||
);
|
||||
// The C ABI path walks the table through `scan_fspx`, not
|
||||
// `parse_fspx`, and must classify it the same way.
|
||||
assert_eq!(
|
||||
summarize_dxbc(&blob).map(|_| ()),
|
||||
Err(expected),
|
||||
"offset {offset}"
|
||||
);
|
||||
}
|
||||
|
||||
// The first byte after the table is outside the reserved region.
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(56))]);
|
||||
let info = inspect_dxbc(&blob).expect("offset at the end of the stage section");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert!(summarize_dxbc(&blob).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fspx_layout_mismatch_is_not_out_of_bounds() {
|
||||
// Past the payload end is still out of bounds, not a layout mismatch.
|
||||
let mut payload = fspx_two_sections(62);
|
||||
payload.truncate(64);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
|
||||
let out_of_bounds = ParseError::FspxSectionOutOfBounds {
|
||||
chunk: 0,
|
||||
section_id: 6,
|
||||
};
|
||||
assert_eq!(inspect_dxbc(&blob), Err(out_of_bounds.clone()));
|
||||
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(out_of_bounds));
|
||||
|
||||
// A reserved offset wins even when the size would also overrun.
|
||||
let mut payload = fspx_header(1, 1, &[(6, 20, u32::MAX)], 32);
|
||||
payload.truncate(32);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 6,
|
||||
offset: 20,
|
||||
table_end: 28,
|
||||
})
|
||||
);
|
||||
|
||||
let message = ParseError::FspxLayoutMismatch {
|
||||
chunk: 2,
|
||||
section_id: 6,
|
||||
offset: 20,
|
||||
table_end: 28,
|
||||
}
|
||||
.to_string();
|
||||
assert!(message.contains("section 6"), "{message}");
|
||||
assert!(message.contains("offset 20"), "{message}");
|
||||
assert!(message.contains("28-byte"), "{message}");
|
||||
assert!(message.contains("chunk 2"), "{message}");
|
||||
assert!(!message.contains("out of bounds"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_abi_still_refuses_fspx_layout_mismatch() {
|
||||
clear_shader_log();
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]);
|
||||
|
||||
let mut c_info = BxShaderInspection {
|
||||
kind: 99,
|
||||
..BxShaderInspection::default()
|
||||
};
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert_eq!(c_info.kind, 0);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arbitrary_fspx_tables_do_not_panic() {
|
||||
// Deterministic xorshift so a failure reproduces.
|
||||
let mut state = 0x9E37_79B9_7F4A_7C15u64;
|
||||
let mut next = || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
state
|
||||
};
|
||||
for round in 0..4096u32 {
|
||||
let len = 16 + (next() % 240) as usize;
|
||||
let mut payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
|
||||
payload[..4].copy_from_slice(b"FSPX");
|
||||
payload[4..8].copy_from_slice(&1u32.to_le_bytes());
|
||||
let count = round % (FSPX_MAX_SECTIONS as u32 + 2);
|
||||
payload[8..12].copy_from_slice(&count.to_le_bytes());
|
||||
// Keep some offsets small so the reserved-region branch is hit.
|
||||
if round % 2 == 0 {
|
||||
let mut at = 20;
|
||||
while at + 4 <= len.min(16 + count as usize * 12) {
|
||||
let small = (next() % 64) as u32;
|
||||
payload[at..at + 4].copy_from_slice(&small.to_le_bytes());
|
||||
at += 12;
|
||||
}
|
||||
}
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
|
||||
let _ = inspect_dxbc(&blob);
|
||||
let _ = summarize_dxbc(&blob);
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let _ = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_abi_inspect_and_passthrough_round_trip() {
|
||||
clear_shader_log();
|
||||
@@ -1563,245 +1268,6 @@ mod tests {
|
||||
assert!(log[0].contains("sm_minor=0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_is_not_classified_as_executable_dxil() {
|
||||
clear_shader_log();
|
||||
// Pixel shader (0), SM 6.6, with the four-byte NOBC placeholder instead of LLVM bitcode.
|
||||
let mut payload = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
payload[24..28].copy_from_slice(b"NOBC");
|
||||
let blob = build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &payload)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("valid DXBC with NOBC header-only DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Unknown);
|
||||
assert_eq!(info.stage, ShaderStage::Pixel);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
assert!(info.has_root_signature);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 0); // BX_SHADER_UNKNOWN
|
||||
assert_eq!(c_info.stage, 1); // BX_STAGE_PIXEL
|
||||
assert_eq!(c_info.shader_model_major, 6);
|
||||
assert_eq!(c_info.shader_model_minor, 6);
|
||||
assert_eq!(c_info.dxil_chunk_size, 28);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_accc_is_classified_as_accc_only_and_rejected() {
|
||||
clear_shader_log();
|
||||
let mut dxil = minimal_dxil_program((1u32 << 16) | (6u32 << 4) | 6u32);
|
||||
dxil[24..28].copy_from_slice(b"NOBC");
|
||||
let fspx = fspx_compute_stage();
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &dxil), (b"ACCC", &fspx)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("NOBC + ACCC container");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 0));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
assert_eq!(info.accc_size, 40);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 3); // BX_SHADER_DXBC_ACCC
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
let log = shader_log_lines();
|
||||
assert_eq!(log.len(), 1);
|
||||
assert!(log[0].contains("kind=accc_only(3)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_padded_bitcode_is_still_header_only() {
|
||||
let mut payload = vec![0u8; 32];
|
||||
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
|
||||
payload[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
payload[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||
payload[8..12].copy_from_slice(b"DXIL");
|
||||
payload[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
payload[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
payload[20..24].copy_from_slice(&8u32.to_le_bytes());
|
||||
payload[24..28].copy_from_slice(b"NOBC");
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &payload)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("padded NOBC DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Unknown);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_executable_and_nobc_dxil_preserves_executable_metadata() {
|
||||
let exec = minimal_dxil_program((5u32 << 16) | (6u32 << 4) | 5u32);
|
||||
let mut nobc = vec![0u8; 32];
|
||||
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
|
||||
nobc[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
nobc[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||
nobc[8..12].copy_from_slice(b"DXIL");
|
||||
nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
nobc[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
nobc[20..24].copy_from_slice(&8u32.to_le_bytes());
|
||||
nobc[24..28].copy_from_slice(b"NOBC");
|
||||
|
||||
// Executable first, NOBC second: executable stage and size must win.
|
||||
let blob_exec_first = build_synthetic_dxbc(&[(b"DXIL", &exec), (b"DXIL", &nobc)]);
|
||||
let info = inspect_dxbc(&blob_exec_first).expect("mixed DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Dxil);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 5));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
bx_shader_inspect(blob_exec_first.as_ptr(), blob_exec_first.len(), &mut c_info)
|
||||
},
|
||||
BX_SHADER_OK
|
||||
);
|
||||
assert_eq!(c_info.kind, 1); // BX_SHADER_DXBC_DXIL
|
||||
assert_eq!(c_info.stage, 6); // BX_STAGE_COMPUTE
|
||||
assert_eq!(c_info.dxil_chunk_size, 28);
|
||||
assert_eq!(
|
||||
dxil_container_len(&blob_exec_first),
|
||||
Ok(Some(blob_exec_first.len() as u32))
|
||||
);
|
||||
|
||||
// NOBC first, executable second: executable must still win.
|
||||
let blob_nobc_first = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"DXIL", &exec)]);
|
||||
let info2 = inspect_dxbc(&blob_nobc_first).expect("mixed DXIL reversed");
|
||||
assert_eq!(info2.kind, ShaderKind::Dxil);
|
||||
assert_eq!(info2.stage, ShaderStage::Compute);
|
||||
assert_eq!((info2.shader_model_major, info2.shader_model_minor), (6, 5));
|
||||
assert_eq!(info2.dxil_size, 28);
|
||||
let summary2 = summarize_dxbc(&blob_nobc_first).expect("mixed DXIL summary");
|
||||
assert_eq!(summary2.kind, ShaderKind::Dxil);
|
||||
assert_eq!(summary2.stage, ShaderStage::Compute);
|
||||
assert_eq!(summary2.dxil_size, 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_malformed_fspx_returns_invalid_blob() {
|
||||
clear_shader_log();
|
||||
let mut nobc = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
nobc[24..28].copy_from_slice(b"NOBC");
|
||||
let bad_fspx = fspx_header(99, 0, &[], 16);
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"ACCC", &bad_fspx)]);
|
||||
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxBadVersion {
|
||||
chunk: 1,
|
||||
version: 99,
|
||||
})
|
||||
);
|
||||
assert_eq!(dxil_container_len(&blob), Ok(None));
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxil_bitcode_bounds_and_offset_checks() {
|
||||
let prog = (5u32 << 16) | (6u32 << 4) | 6u32;
|
||||
|
||||
// Bitcode shorter than 4 bytes (`NOB`) must not misclassify as `NOBC` or read out of bounds.
|
||||
let mut short_bitcode = [0u8; 28];
|
||||
short_bitcode[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
short_bitcode[4..8].copy_from_slice(&7u32.to_le_bytes());
|
||||
short_bitcode[8..12].copy_from_slice(b"DXIL");
|
||||
short_bitcode[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
short_bitcode[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
short_bitcode[20..24].copy_from_slice(&3u32.to_le_bytes());
|
||||
short_bitcode[24..27].copy_from_slice(b"NOB");
|
||||
let blob_short = build_synthetic_dxbc(&[(b"DXIL", &short_bitcode)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_short).expect("3-byte bitcode").kind,
|
||||
ShaderKind::Dxil
|
||||
);
|
||||
|
||||
// `NOBC` check follows `BitcodeOffset`, not a fixed offset 24.
|
||||
let mut shifted_nobc = vec![0u8; 36];
|
||||
shifted_nobc[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
shifted_nobc[4..8].copy_from_slice(&9u32.to_le_bytes());
|
||||
shifted_nobc[8..12].copy_from_slice(b"DXIL");
|
||||
shifted_nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
shifted_nobc[16..20].copy_from_slice(&24u32.to_le_bytes());
|
||||
shifted_nobc[20..24].copy_from_slice(&4u32.to_le_bytes());
|
||||
shifted_nobc[32..36].copy_from_slice(b"NOBC");
|
||||
let blob_shifted_nobc = build_synthetic_dxbc(&[(b"DXIL", &shifted_nobc)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_shifted_nobc).expect("shifted NOBC").kind,
|
||||
ShaderKind::Unknown
|
||||
);
|
||||
assert_eq!(dxil_container_len(&blob_shifted_nobc), Ok(None));
|
||||
|
||||
// Bytes before `BitcodeOffset` containing `NOBC` do not make executable bitcode header-only.
|
||||
let mut shifted_exec = shifted_nobc;
|
||||
shifted_exec[24..28].copy_from_slice(b"NOBC");
|
||||
shifted_exec[32..36].copy_from_slice(&[0xD1, 0x11, 0xC0, 0xDE]);
|
||||
let blob_shifted_exec = build_synthetic_dxbc(&[(b"DXIL", &shifted_exec)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_shifted_exec)
|
||||
.expect("shifted executable")
|
||||
.kind,
|
||||
ShaderKind::Dxil
|
||||
);
|
||||
|
||||
// Overflowing bitcode offset / size must reject cleanly as `BadDxilHeader`.
|
||||
for (bitcode_off, bitcode_sz) in [(16u32, u32::MAX), (u32::MAX - 4, 4u32)] {
|
||||
let mut overflow = minimal_dxil_program(prog);
|
||||
overflow[16..20].copy_from_slice(&bitcode_off.to_le_bytes());
|
||||
overflow[20..24].copy_from_slice(&bitcode_sz.to_le_bytes());
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &overflow)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
assert_eq!(
|
||||
summarize_dxbc(&blob).map(|_| ()),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
assert_eq!(
|
||||
dxil_container_len(&blob),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn fspx_table_with_sections(count: u32) -> Vec<u8> {
|
||||
let count_usize = count as usize;
|
||||
let table_end = 16 + count_usize * 12;
|
||||
@@ -1836,99 +1302,4 @@ mod tests {
|
||||
fn ptr_sentinel() -> *mut u8 {
|
||||
std::ptr::dangling_mut()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_returns_sfi0_and_psv0_bytes() {
|
||||
let sfi0: [u8; 8] = [0x00, 0x40, 0, 0, 0, 0, 0, 0];
|
||||
let psv0: [u8; 28] = [
|
||||
24, 0, 0, 0, // info_size = 24
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, // lanes_min
|
||||
64, 0, 0, 0, // lanes_max
|
||||
];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &sfi0), (b"PSV0", &psv0)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid container");
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(sfi0.as_slice()));
|
||||
assert_eq!(info.chunk_payload(&blob, b"PSV0"), Some(psv0.as_slice()));
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
assert!(info.has_chunk_tag(b"PSV0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_rejects_declared_size_past_container() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4])]);
|
||||
let mut info = inspect_dxbc(&blob).expect("valid container");
|
||||
|
||||
// A declared size that runs past container_size must yield None, not
|
||||
// a panic and not a slice clipped to the container.
|
||||
info.chunks[0].size = u32::MAX;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
// Presence without trusting the size still holds.
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
|
||||
// A forged public ChunkInfo must not treat the DXBC header or offset
|
||||
// table as a chunk header.
|
||||
info.chunks[0].size = 4;
|
||||
info.chunks[0].offset = 0;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
|
||||
// A header offset past the container must also yield None.
|
||||
info.chunks[0].offset = u32::MAX;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
|
||||
// A chunk header that would end exactly one byte past the container.
|
||||
info.chunks[0].offset = info.container_size - 7;
|
||||
info.chunks[0].size = 0;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_absent_fourcc() {
|
||||
let blob = synthetic_dxil_blob();
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
assert!(!info.has_chunk_tag(b"SFI0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_zero_size_returns_empty_slice() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[])]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
let payload = info.chunk_payload(&blob, b"SFI0");
|
||||
assert_eq!(payload, Some(&[][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_exact_fit_at_container_end() {
|
||||
let payload = [0xAA, 0xBB, 0xCC, 0xDD];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &payload)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
// The chunk is the last thing in the container; payload ends exactly
|
||||
// at container_size.
|
||||
let chunk = &info.chunks[0];
|
||||
assert_eq!(
|
||||
u64::from(chunk.offset) + 8 + u64::from(chunk.size),
|
||||
u64::from(info.container_size)
|
||||
);
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(payload.as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_truncated_container_slice() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4, 5, 6, 7, 8])]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
// Pass a slice shorter than container_size.
|
||||
let short = &blob[..blob.len() - 4];
|
||||
assert_eq!(info.chunk_payload(short, b"SFI0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_first_duplicate_wins() {
|
||||
let first = [0x11, 0x22];
|
||||
let second = [0x33, 0x44, 0x55];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &first), (b"SFI0", &second)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert_eq!(info.chunks.len(), 2);
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(first.as_slice()));
|
||||
}
|
||||
}
|
||||
+3
-12
@@ -47,28 +47,19 @@ HRESULT WINAPI AcpHalCreate(void** out) {
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
// NDA constraint: the public Microsoft Learn page for AcpHal is gated behind
|
||||
// an Xbox developer NDA, so the true signatures and context layout are unknown
|
||||
// from public sources. BetterXen therefore returns E_NOTIMPL (not the console's
|
||||
// behaviour) and keeps the stub log so bx-cli trace still surfaces the call.
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void* context) {
|
||||
(void)context;
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
|
||||
return E_NOTIMPL;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
|
||||
return E_NOTIMPL;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
// A zero-capacity heap must not report S_OK: it can never satisfy an
|
||||
// allocation, so creating it is a caller error (#580). ApuAlloc already
|
||||
// refused such requests with E_OUTOFMEMORY.
|
||||
if (uint64_t(cached) + non_cached == 0) return E_INVALIDARG;
|
||||
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
|
||||
used = 0;
|
||||
capacity = uint64_t(cached) + non_cached;
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
d3d12_xs.cpp
|
||||
vmem.cpp
|
||||
presentx.cpp
|
||||
proxy.cpp
|
||||
proxy_generated.cpp
|
||||
shader_gate.cpp
|
||||
)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
|
||||
+19
-36
@@ -1,8 +1,8 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
/*
|
||||
* Track C (M1-C1, #414): Xbox Series D3D12 entry points over the host's d3d12.dll
|
||||
@@ -20,12 +20,9 @@ HMODULE get_host_d3d12() {
|
||||
return mod;
|
||||
}
|
||||
|
||||
void initialize_trace_flag() {
|
||||
static std::once_flag initialized;
|
||||
std::call_once(initialized, [] {
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
|
||||
});
|
||||
void refresh_trace_flag() {
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -43,7 +40,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
initialize_trace_flag();
|
||||
refresh_trace_flag();
|
||||
|
||||
using CreateFn = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
|
||||
HMODULE d3d12 = get_host_d3d12();
|
||||
@@ -56,24 +53,12 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
}
|
||||
|
||||
ID3D12Device* host = nullptr;
|
||||
char reuse[8] = {};
|
||||
/* Test hook. While the backing cache holds a host heap, that heap keeps the host
|
||||
device alive, and a real runtime then returns the same ID3D12Device. Set the
|
||||
variable so the next proxy wraps that device even if this host does not. */
|
||||
const bool reuse_backing = GetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", reuse, sizeof(reuse)) > 0 &&
|
||||
reuse[0] == '1' && reuse[1] == '\0';
|
||||
if (reuse_backing) {
|
||||
host = static_cast<ID3D12Device*>(bx_vmem_addref_backing_host());
|
||||
}
|
||||
HRESULT hr = S_OK;
|
||||
if (!host) {
|
||||
hr = create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr) || !host) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "D3D12CreateDevice hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "host_device_failed", detail);
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
HRESULT hr = create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr) || !host) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "D3D12CreateDevice hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "host_device_failed", detail);
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
|
||||
BxDeviceProxy* proxy = BxDeviceProxy::create(host);
|
||||
@@ -81,10 +66,6 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
if (!proxy) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
if (!bx_vmem_install_device_hooks(proxy)) {
|
||||
proxy->Release();
|
||||
return E_FAIL;
|
||||
}
|
||||
|
||||
/* Record how far up the ID3D12DeviceN chain the host goes: QueryInterface on the proxy stops there. */
|
||||
int highest = 0;
|
||||
@@ -96,10 +77,10 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
if (levels[i]) highest = i + 1;
|
||||
}
|
||||
char detail[256];
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"host_device=%p highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
|
||||
static_cast<void*>(proxy->h_ID3D12Device), highest, params ? "non-null" : "null", g_bx_trace_d3d);
|
||||
"host device wrapped; highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
|
||||
highest, params ? "non-null" : "null", g_bx_trace_d3d);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
|
||||
|
||||
hr = proxy->QueryInterface(riid, ppv);
|
||||
@@ -107,8 +88,10 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT WINAPI D3D12ConfigureVirtualMemoryX(PVOID config) {
|
||||
return bx_d3d12_configure_virtual_memory(config);
|
||||
/* Logged no-op: console startup sequences check SUCCEEDED(hr) before reserving virtual memory. */
|
||||
HRESULT WINAPI D3D12ConfigureVirtualMemoryX(PVOID /*config*/) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI D3D12SerializeVersionedRootSignature(
|
||||
|
||||
@@ -1,544 +0,0 @@
|
||||
#include "presentx.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <new>
|
||||
|
||||
#include "proxy.h"
|
||||
|
||||
/*
|
||||
* Track C (M2-C2, #465). See presentx.h for the contract and for what this is not.
|
||||
* Host DXGI is loaded on demand, like the host d3d12.dll in d3d12_xs.cpp.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr HRESULT kWaitTimedOut = static_cast<HRESULT>(0x800705B4u); /* HRESULT_FROM_WIN32(ERROR_TIMEOUT) */
|
||||
|
||||
bool is_device_removed_hr(HRESULT hr) {
|
||||
return hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_HUNG ||
|
||||
hr == DXGI_ERROR_DEVICE_RESET || hr == DXGI_ERROR_DRIVER_INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
void log_hr(bx_log_level_t level, const char* event, const char* what, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(level, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
/* Releases an already acquired lock and records its owner, so re-entry can be refused. */
|
||||
class SrwOwner {
|
||||
public:
|
||||
SrwOwner(SRWLOCK& lock, std::atomic<DWORD>& owner) : lock_(lock), owner_(owner) { owner_ = GetCurrentThreadId(); }
|
||||
~SrwOwner() {
|
||||
owner_ = 0;
|
||||
ReleaseSRWLockExclusive(&lock_);
|
||||
}
|
||||
SrwOwner(const SrwOwner&) = delete;
|
||||
SrwOwner& operator=(const SrwOwner&) = delete;
|
||||
|
||||
private:
|
||||
SRWLOCK& lock_;
|
||||
std::atomic<DWORD>& owner_;
|
||||
};
|
||||
|
||||
class BxPresentSwapChain final : public IBxPresentSwapChain {
|
||||
public:
|
||||
/* `queue_proxy` is referenced for the lifetime of the chain; `host_queue` is its host object. */
|
||||
static HRESULT create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
|
||||
const BxPresentDesc& desc, IBxPresentSwapChain** out);
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override;
|
||||
ULONG STDMETHODCALLTYPE AddRef() override;
|
||||
ULONG STDMETHODCALLTYPE Release() override;
|
||||
|
||||
HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) override;
|
||||
UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() override;
|
||||
HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) override;
|
||||
HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) override;
|
||||
HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) override;
|
||||
|
||||
private:
|
||||
BxPresentSwapChain() = default;
|
||||
~BxPresentSwapChain() = default;
|
||||
|
||||
HRESULT init(HWND window, const BxPresentDesc& desc);
|
||||
HRESULT signal_locked(UINT64* value);
|
||||
HRESULT wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms);
|
||||
HRESULT idle_locked(ULONGLONG start, DWORD timeout_ms);
|
||||
HRESULT post_present_failure(const char* event, const char* what, HRESULT hr, HRESULT live_device_result);
|
||||
HRESULT removed_reason();
|
||||
void destroy();
|
||||
|
||||
std::atomic<ULONG> refs_{1};
|
||||
SRWLOCK lock_ = SRWLOCK_INIT; /* guards the fence counter, the event and Present */
|
||||
ID3D12CommandQueue* queue_proxy_ = nullptr;
|
||||
ID3D12CommandQueue* host_queue_ = nullptr;
|
||||
HWND window_ = nullptr;
|
||||
IDXGISwapChain3* swap_ = nullptr;
|
||||
ID3D12Fence* fence_ = nullptr;
|
||||
HANDLE event_ = nullptr;
|
||||
std::atomic<DWORD> owner_{0}; /* thread holding lock_ */
|
||||
UINT64 last_signaled_ = 0;
|
||||
UINT64 presented_ = 0;
|
||||
bool needs_idle_ = false; /* post-present signal or wait failed; only an idle queue clears this */
|
||||
UINT64 buffer_value_[DXGI_MAX_SWAP_CHAIN_BUFFERS] = {};
|
||||
};
|
||||
|
||||
HRESULT BxPresentSwapChain::create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
|
||||
const BxPresentDesc& desc, IBxPresentSwapChain** out) {
|
||||
auto* self = new (std::nothrow) BxPresentSwapChain();
|
||||
if (!self) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
queue_proxy->AddRef();
|
||||
self->queue_proxy_ = queue_proxy;
|
||||
host_queue->AddRef();
|
||||
self->host_queue_ = host_queue;
|
||||
self->window_ = window;
|
||||
|
||||
HRESULT hr = self->init(window, desc);
|
||||
if (FAILED(hr)) {
|
||||
self->destroy(); /* nothing was submitted, so every partially created object can go */
|
||||
return hr;
|
||||
}
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::init(HWND window, const BxPresentDesc& desc) {
|
||||
static HMODULE dxgi = LoadLibraryA("dxgi.dll");
|
||||
using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**);
|
||||
auto create_factory = dxgi
|
||||
? reinterpret_cast<CreateFactoryFn>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory1")))
|
||||
: nullptr;
|
||||
if (!create_factory) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_dxgi_missing", "dxgi.dll!CreateDXGIFactory1 not available");
|
||||
return DXGI_ERROR_UNSUPPORTED;
|
||||
}
|
||||
|
||||
IDXGIFactory4* factory = nullptr;
|
||||
HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory));
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateDXGIFactory1", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
DXGI_SWAP_CHAIN_DESC1 sd = {};
|
||||
sd.Width = desc.width;
|
||||
sd.Height = desc.height;
|
||||
sd.Format = desc.format;
|
||||
sd.SampleDesc.Count = 1;
|
||||
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
sd.BufferCount = desc.buffer_count;
|
||||
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
|
||||
IDXGISwapChain1* swap1 = nullptr;
|
||||
/* For D3D12 the "device" argument of CreateSwapChainForHwnd is the command queue. */
|
||||
hr = factory->CreateSwapChainForHwnd(host_queue_, window, &sd, nullptr, nullptr, &swap1);
|
||||
if (SUCCEEDED(hr)) {
|
||||
/* Alt+Enter would require ResizeBuffers handling that the bridge does not have. */
|
||||
HRESULT assoc = factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER);
|
||||
if (FAILED(assoc)) {
|
||||
log_hr(BX_LOG_WARN, "present_window_association", "MakeWindowAssociation", assoc);
|
||||
}
|
||||
}
|
||||
factory->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateSwapChainForHwnd", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
hr = swap1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&swap_));
|
||||
swap1->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "QueryInterface(IDXGISwapChain3)", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence_));
|
||||
device->Release();
|
||||
}
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateFence", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
event_ = CreateEventA(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event_) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateEvent", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "width=%u height=%u format=%d buffers=%u",
|
||||
desc.width, desc.height, static_cast<int>(desc.format), desc.buffer_count);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_chain_created", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::removed_reason() {
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (FAILED(hr)) {
|
||||
return hr;
|
||||
}
|
||||
hr = device->GetDeviceRemovedReason();
|
||||
device->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::signal_locked(UINT64* value) {
|
||||
const UINT64 next = last_signaled_ + 1;
|
||||
HRESULT hr = host_queue_->Signal(fence_, next);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_signal_failed", "ID3D12CommandQueue::Signal", hr);
|
||||
return hr;
|
||||
}
|
||||
last_signaled_ = next;
|
||||
*value = next;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms) {
|
||||
for (;;) {
|
||||
const UINT64 completed = fence_->GetCompletedValue();
|
||||
if (completed == UINT64_MAX) { /* the documented value after device removal */
|
||||
HRESULT reason = removed_reason();
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", "fence", reason);
|
||||
return FAILED(reason) ? reason : DXGI_ERROR_DEVICE_REMOVED;
|
||||
}
|
||||
if (completed >= value) {
|
||||
return S_OK;
|
||||
}
|
||||
const ULONGLONG elapsed = GetTickCount64() - start;
|
||||
if (elapsed >= timeout_ms) {
|
||||
break;
|
||||
}
|
||||
HRESULT hr = fence_->SetEventOnCompletion(value, event_);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_wait_failed", "SetEventOnCompletion", hr);
|
||||
return hr;
|
||||
}
|
||||
const ULONGLONG elapsed_after_registration = GetTickCount64() - start;
|
||||
if (elapsed_after_registration >= timeout_ms) {
|
||||
continue; /* Recheck the fence before reporting a timeout. */
|
||||
}
|
||||
/* The event can be left over from an earlier timed-out wait, so the loop re-reads the fence. */
|
||||
DWORD waited = WaitForSingleObject(event_, static_cast<DWORD>(timeout_ms - elapsed_after_registration));
|
||||
if (waited == WAIT_FAILED) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
log_hr(BX_LOG_ERROR, "present_wait_failed", "WaitForSingleObject", hr);
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=%llu", static_cast<unsigned long>(timeout_ms),
|
||||
static_cast<unsigned long long>(value), static_cast<unsigned long long>(fence_->GetCompletedValue()));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::post_present_failure(const char* event, const char* what, HRESULT hr,
|
||||
HRESULT live_device_result) {
|
||||
const HRESULT removed = removed_reason();
|
||||
if (FAILED(removed)) {
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", what, removed);
|
||||
return removed;
|
||||
}
|
||||
needs_idle_ = true;
|
||||
if (event) {
|
||||
log_hr(BX_LOG_ERROR, event, what, hr);
|
||||
}
|
||||
if (is_device_removed_hr(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", what, hr);
|
||||
return hr;
|
||||
}
|
||||
return live_device_result;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::idle_locked(ULONGLONG start, DWORD timeout_ms) {
|
||||
if (GetTickCount64() - start >= timeout_ms) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=unknown; expired before Signal",
|
||||
static_cast<unsigned long>(timeout_ms), static_cast<unsigned long long>(last_signaled_ + 1));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
UINT64 value = 0;
|
||||
HRESULT hr = signal_locked(&value);
|
||||
return FAILED(hr) ? hr : wait_locked(value, start, timeout_ms);
|
||||
}
|
||||
|
||||
void BxPresentSwapChain::destroy() {
|
||||
if (swap_ && fence_ && event_) {
|
||||
HRESULT idle = idle_locked(GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (FAILED(idle) && SUCCEEDED(removed_reason())) {
|
||||
/* The device is alive and the GPU may still be using the back buffers. */
|
||||
log_hr(BX_LOG_ERROR, "present_chain_leaked", "queue not idle; GPU-visible objects deliberately not released", idle);
|
||||
/*
|
||||
* swap_, fence_, event_ and host_queue_ stay: pending work may touch them. The proxy
|
||||
* is only BetterXen's wrapper; host_queue_ keeps the host queue alive without it.
|
||||
*/
|
||||
ID3D12CommandQueue* proxy = queue_proxy_;
|
||||
delete this;
|
||||
proxy->Release();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const bool had_swap = swap_ != nullptr;
|
||||
ULONG swap_refs = 0;
|
||||
if (swap_) swap_refs = swap_->Release();
|
||||
if (fence_) fence_->Release();
|
||||
if (event_) CloseHandle(event_);
|
||||
if (had_swap) {
|
||||
/*
|
||||
* The count the host's Release returned. Non-zero means something else still references
|
||||
* the swapchain: back buffers or host pointers the caller holds, or the host itself
|
||||
* (see docs/research/d3dmetal-swapchain-references.md). It is reported, never "fixed up"
|
||||
* by releasing references this object does not own.
|
||||
*/
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "presented=%llu swapchain_release_returned=%lu",
|
||||
static_cast<unsigned long long>(presented_), static_cast<unsigned long>(swap_refs));
|
||||
bx_log_emit(swap_refs ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "present_chain_destroyed", detail);
|
||||
}
|
||||
ID3D12CommandQueue* host_queue = host_queue_;
|
||||
ID3D12CommandQueue* queue_proxy = queue_proxy_;
|
||||
delete this;
|
||||
if (host_queue) host_queue->Release();
|
||||
if (queue_proxy) queue_proxy->Release();
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::QueryInterface(REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (IsEqualGUID(riid, __uuidof(IUnknown)) || IsEqualGUID(riid, IID_IBxPresentSwapChain)) {
|
||||
AddRef();
|
||||
*ppv = static_cast<IBxPresentSwapChain*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxPresentSwapChain::AddRef() {
|
||||
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxPresentSwapChain::Release() {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
destroy();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetBuffer(UINT index, REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
HRESULT hr = swap_->GetBuffer(index, riid, ppv);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_WARN, "present_get_buffer_failed", "IDXGISwapChain::GetBuffer", hr);
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
UINT STDMETHODCALLTYPE BxPresentSwapChain::GetCurrentBackBufferIndex() {
|
||||
return swap_->GetCurrentBackBufferIndex();
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::Present(UINT sync_interval, UINT flags) {
|
||||
BX_D3D_TRACE("IBxPresentSwapChain", "Present");
|
||||
if (sync_interval > 4 || flags != 0 || !IsWindow(window_)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x window_alive=%d", sync_interval, flags,
|
||||
IsWindow(window_) ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", detail);
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
if (owner_ == GetCurrentThreadId()) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", "re-entered on the same thread");
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
/*
|
||||
* Never wait for the lock. Its holder may be inside the host's Present, and DXGI can make that
|
||||
* call wait for the window's thread: the caller here.
|
||||
*/
|
||||
if (!TryAcquireSRWLockExclusive(&lock_)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_busy", "another call holds the swapchain; nothing presented");
|
||||
return BX_PRESENT_E_BUSY;
|
||||
}
|
||||
SrwOwner guard(lock_, owner_);
|
||||
if (needs_idle_) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_needs_idle", "completion unconfirmed; nothing presented");
|
||||
return BX_PRESENT_E_NEEDS_IDLE;
|
||||
}
|
||||
const UINT presented_index = swap_->GetCurrentBackBufferIndex();
|
||||
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
/* Busy only after an earlier BX_PRESENT_E_NEXT_BUFFER_BUSY. Nothing is presented then. */
|
||||
const HRESULT ready = wait_locked(buffer_value_[presented_index], GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (FAILED(ready)) {
|
||||
return ready;
|
||||
}
|
||||
}
|
||||
HRESULT hr = swap_->Present(sync_interval, flags);
|
||||
if (FAILED(hr)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x hr=0x%08lx device_removed_reason=0x%08lx", sync_interval,
|
||||
flags, static_cast<unsigned long>(hr), static_cast<unsigned long>(removed_reason()));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_failed", detail);
|
||||
return hr;
|
||||
}
|
||||
++presented_;
|
||||
|
||||
UINT64 value = 0;
|
||||
HRESULT sync_hr = signal_locked(&value);
|
||||
if (FAILED(sync_hr)) {
|
||||
/* signal_locked already logged present_signal_failed when the device stays live. */
|
||||
return post_present_failure(nullptr, "signal after Present", sync_hr, BX_PRESENT_E_COMPLETION_UNCONFIRMED);
|
||||
}
|
||||
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
buffer_value_[presented_index] = value;
|
||||
}
|
||||
const UINT next = swap_->GetCurrentBackBufferIndex();
|
||||
if (next < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
sync_hr = wait_locked(buffer_value_[next], GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (sync_hr == kWaitTimedOut) {
|
||||
return BX_PRESENT_E_NEXT_BUFFER_BUSY;
|
||||
}
|
||||
if (FAILED(sync_hr)) {
|
||||
return post_present_failure("present_next_buffer_wait_failed", "wait_locked", sync_hr,
|
||||
BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED);
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::WaitForIdle(DWORD timeout_ms) {
|
||||
if (timeout_ms == 0 || timeout_ms == INFINITE) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (owner_ == GetCurrentThreadId()) {
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
while (!TryAcquireSRWLockExclusive(&lock_)) {
|
||||
if (GetTickCount64() - start >= timeout_ms) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", "swapchain busy in another call");
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
Sleep(1);
|
||||
}
|
||||
SrwOwner guard(lock_, owner_);
|
||||
const HRESULT hr = idle_locked(start, timeout_ms);
|
||||
if (hr == S_OK) {
|
||||
/* A signal queued after every presented frame has completed. */
|
||||
needs_idle_ = false;
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetHostSwapChain(REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return swap_->QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
bool desc_is_valid(const BxPresentDesc& d) {
|
||||
const bool format_ok = d.format == DXGI_FORMAT_R8G8B8A8_UNORM || d.format == DXGI_FORMAT_B8G8R8A8_UNORM ||
|
||||
d.format == DXGI_FORMAT_R10G10B10A2_UNORM || d.format == DXGI_FORMAT_R16G16B16A16_FLOAT;
|
||||
return format_ok && d.width >= 1 && d.width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.height >= 1 &&
|
||||
d.height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.buffer_count >= 2 &&
|
||||
d.buffer_count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
|
||||
}
|
||||
|
||||
/* COM tear-off: its own reference count, one reference on the queue, and the queue's identity. */
|
||||
class BxPresentQueue final : public IBxPresentQueue {
|
||||
public:
|
||||
explicit BxPresentQueue(ID3D12CommandQueue* queue_proxy) : queue_(queue_proxy) { queue_->AddRef(); }
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
|
||||
AddRef();
|
||||
*ppv = static_cast<IBxPresentQueue*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
return queue_->QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; }
|
||||
|
||||
ULONG STDMETHODCALLTYPE Release() override {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
ID3D12CommandQueue* queue = queue_;
|
||||
delete this;
|
||||
queue->Release();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) override {
|
||||
if (!out) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*out = nullptr;
|
||||
if (!desc) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (!window || !IsWindow(window) || !desc_is_valid(*desc)) {
|
||||
log_hr(BX_LOG_WARN, "present_create_rejected", "invalid window or description", DXGI_ERROR_INVALID_CALL);
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
ID3D12CommandQueue* host = nullptr;
|
||||
HRESULT hr = static_cast<IUnknown*>(bx_unwrap_raw(queue_))
|
||||
->QueryInterface(__uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "host command queue", hr);
|
||||
return hr;
|
||||
}
|
||||
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
|
||||
host->GetDesc(&queue_desc);
|
||||
if (queue_desc.Type != D3D12_COMMAND_LIST_TYPE_DIRECT) {
|
||||
log_hr(BX_LOG_WARN, "present_create_rejected", "queue is not a DIRECT queue", DXGI_ERROR_INVALID_CALL);
|
||||
hr = DXGI_ERROR_INVALID_CALL;
|
||||
} else {
|
||||
hr = BxPresentSwapChain::create(queue_, host, window, *desc, out);
|
||||
}
|
||||
host->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
private:
|
||||
~BxPresentQueue() = default;
|
||||
std::atomic<ULONG> refs_{1};
|
||||
ID3D12CommandQueue* queue_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
auto* bridge = new (std::nothrow) BxPresentQueue(queue_proxy);
|
||||
if (!bridge) {
|
||||
*ppv = nullptr;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*ppv = static_cast<IBxPresentQueue*>(bridge);
|
||||
return S_OK;
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_PRESENTX_H
|
||||
#define BETTERXEN_D3D12_XS_PRESENTX_H
|
||||
|
||||
/*
|
||||
* Track C (M2-C2, #465): the PresentX presentation bridge over host DXGI.
|
||||
*
|
||||
* THESE INTERFACES ARE DEFINED BY BETTERXEN. They are not the console's PresentX, whose
|
||||
* signature and structures are not defined in abi/, and no binary compatibility with any Xbox
|
||||
* interface is claimed. A guest that calls a console-only command queue slot still lands on the
|
||||
* proxy's logged stub.
|
||||
*
|
||||
* Use: QueryInterface the command queue returned by a D3D12XboxCreateDevice device for
|
||||
* IID_IBxPresentQueue, then create a swapchain on a Win32 window. No new DLL export is involved.
|
||||
*
|
||||
* This is a subset of the public DXGI flip model, not all of it: the caller records its own
|
||||
* resource transitions and every back buffer must be in D3D12_RESOURCE_STATE_PRESENT when it is
|
||||
* presented. D3D12 offers no way to query a resource's state, so the bridge cannot check this.
|
||||
* ResizeBuffers and fullscreen are not implemented.
|
||||
*/
|
||||
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <d3d12.h>
|
||||
#include <dxgi1_4.h>
|
||||
|
||||
/* {34127279-2D93-4642-88A6-97B834217B8A} */
|
||||
inline const GUID IID_IBxPresentQueue = {0x34127279, 0x2d93, 0x4642, {0x88, 0xa6, 0x97, 0xb8, 0x34, 0x21, 0x7b, 0x8a}};
|
||||
/* {DEC9F73E-DE84-4F87-9167-26203B3A1152} */
|
||||
inline const GUID IID_IBxPresentSwapChain = {0xdec9f73e, 0xde84, 0x4f87, {0x91, 0x67, 0x26, 0x20, 0x3b, 0x3a, 0x11, 0x52}};
|
||||
|
||||
/* Longest single GPU wait Present() performs, and the destructor's wait for the GPU. */
|
||||
inline constexpr DWORD BX_PRESENT_WAIT_MS = 5000;
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host, but the next back buffer is still busy.
|
||||
* Do not present that frame again. Call WaitForIdle until it returns S_OK before reusing a buffer.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_BUSY = static_cast<HRESULT>(0x80040201u);
|
||||
/*
|
||||
* Present() result: the frame was NOT handed to the host, because another Present or WaitForIdle
|
||||
* on this swapchain is in progress. Present never waits for that call. Try again after it returns.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_BUSY = static_cast<HRESULT>(0x80040202u);
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host, but the following fence signal failed on
|
||||
* a live device, so its completion is unknown. Do not present that frame again. Call WaitForIdle
|
||||
* until it returns S_OK before recording to any back buffer or presenting again. Device removal
|
||||
* returns the removal HRESULT unchanged instead.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_COMPLETION_UNCONFIRMED = static_cast<HRESULT>(0x80040203u);
|
||||
/*
|
||||
* Present() result: the frame was NOT handed to the host, because an earlier Present returned
|
||||
* BX_PRESENT_E_COMPLETION_UNCONFIRMED or BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED and no WaitForIdle
|
||||
* has succeeded since.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEEDS_IDLE = static_cast<HRESULT>(0x80040204u);
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host and signaled, but waiting on the next back
|
||||
* buffer failed on a live device (for example SetEventOnCompletion or WaitForSingleObject). Do not
|
||||
* present that frame again. Call WaitForIdle until it returns S_OK before reusing any back buffer
|
||||
* or presenting again. Device removal returns the removal HRESULT unchanged instead.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED = static_cast<HRESULT>(0x80040205u);
|
||||
|
||||
struct BxPresentDesc {
|
||||
UINT width; /* 1..16384; 0 ("use the window size") is not accepted */
|
||||
UINT height; /* 1..16384 */
|
||||
DXGI_FORMAT format; /* R8G8B8A8_UNORM, B8G8R8A8_UNORM, R10G10B10A2_UNORM or R16G16B16A16_FLOAT */
|
||||
UINT buffer_count; /* 2..DXGI_MAX_SWAP_CHAIN_BUFFERS */
|
||||
};
|
||||
|
||||
/*
|
||||
* One swapchain. Holds a reference on the command queue it was created from.
|
||||
* The final Release waits (bounded) for the queue to go idle. If that fails and the device
|
||||
* reports it has not been removed, it logs and deliberately leaks what pending GPU work may
|
||||
* still touch (swapchain, fence, event, host queue) and releases its queue proxy reference.
|
||||
* After device removal everything is released. Time spent inside the host's own Release is not bounded: on the
|
||||
* wined3d/vkd3d path (not D3DMetal) an intermittent stall in it was observed.
|
||||
*/
|
||||
struct IBxPresentSwapChain : public IUnknown {
|
||||
/* Same rules as IDXGISwapChain::GetBuffer. The caller owns the returned reference. */
|
||||
virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) = 0;
|
||||
virtual UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() = 0;
|
||||
/*
|
||||
* Waits (bounded) until the current back buffer is idle, calls IDXGISwapChain::Present,
|
||||
* signals a fence on the queue, then waits until the next back buffer is idle. It never waits
|
||||
* for another thread's call on this swapchain. Results:
|
||||
* - a DXGI success code, including DXGI_STATUS_OCCLUDED: presented, next buffer idle;
|
||||
* - HRESULT_FROM_WIN32(ERROR_TIMEOUT): NOT presented (the current buffer is still busy);
|
||||
* - BX_PRESENT_E_NEXT_BUFFER_BUSY: presented, see its definition;
|
||||
* - BX_PRESENT_E_BUSY: NOT presented, another call holds the swapchain;
|
||||
* - BX_PRESENT_E_COMPLETION_UNCONFIRMED: presented, the fence signal failed on a live device;
|
||||
* - BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED: presented, waiting on the next back buffer failed
|
||||
* on a live device;
|
||||
* - BX_PRESENT_E_NEEDS_IDLE: NOT presented, WaitForIdle must succeed first;
|
||||
* - another failure: the host's Present failure, a pre-Present fence wait or device failure
|
||||
* (nothing was presented), or a device-removal HRESULT (such as DXGI_ERROR_DEVICE_REMOVED
|
||||
* or DXGI_ERROR_DEVICE_RESET) observed after host Present, returned unchanged. If the
|
||||
* device still reports itself as live, WaitForIdle must succeed before the next Present.
|
||||
* The bounds cover BetterXen's own waits, not time spent inside the host's Present.
|
||||
*
|
||||
* The bridge itself returns DXGI_ERROR_INVALID_CALL, without calling the host, for a
|
||||
* sync_interval above 4, for any flag (none is supported, including DXGI_PRESENT_TEST),
|
||||
* once the window is destroyed, and when Present or WaitForIdle is re-entered on a thread
|
||||
* already inside one of them. D3DMetal 3.0 was observed to answer S_OK to the first three.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) = 0;
|
||||
/*
|
||||
* Waits until everything submitted to the queue before this call has finished. S_OK also ends
|
||||
* the recovery state left by a post-Present synchronization failure on a live device.
|
||||
* Only positive, finite timeouts are supported. Zero and INFINITE return E_INVALIDARG
|
||||
* without signaling. A timeout returns HRESULT_FROM_WIN32(ERROR_TIMEOUT).
|
||||
* Lock acquisition, fence signaling, and fence waiting share timeout_ms; if lock acquisition
|
||||
* uses the whole budget, WaitForIdle times out without signaling. Time spent inside host calls
|
||||
* reduces the remaining wait, but the bridge cannot interrupt those calls.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) = 0;
|
||||
/*
|
||||
* The host DXGI swapchain, for diagnostics and tests. The caller owns the reference and must
|
||||
* not call Present or ResizeBuffers on it: the bridge's buffer tracking would not follow.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) = 0;
|
||||
};
|
||||
|
||||
/* Tear-off on the command queue proxy; QueryInterface for any other IID returns the queue's answer. */
|
||||
struct IBxPresentQueue : public IUnknown {
|
||||
/*
|
||||
* The queue must be a DIRECT queue and `window` an existing window. Argument errors return
|
||||
* E_POINTER or DXGI_ERROR_INVALID_CALL; host failures are returned unchanged and logged.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) = 0;
|
||||
};
|
||||
|
||||
/* Internal to d3d12_xs.dll: the command queue proxy answers IID_IBxPresentQueue with this. */
|
||||
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv);
|
||||
|
||||
#endif /* BETTERXEN_D3D12_XS_PRESENTX_H */
|
||||
+14
-250
@@ -1,15 +1,8 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "presentx.h"
|
||||
|
||||
#include "shader_gate.h"
|
||||
|
||||
/* {6B1D5C0E-2F4A-4E0B-9A57-3C0E5D7B1A42}: private to this DLL, never handed to a host object. */
|
||||
const GUID IID_BxProxyHost = {0x6b1d5c0e, 0x2f4a, 0x4e0b, {0x9a, 0x57, 0x3c, 0x0e, 0x5d, 0x7b, 0x1a, 0x42}};
|
||||
@@ -139,11 +132,9 @@ bool log_shader(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTE
|
||||
well_formed = false;
|
||||
break;
|
||||
}
|
||||
/* ACCC counts too: the shader format gate (#466) decides what happens to it. */
|
||||
if (std::memcmp(bytes + off, "DXIL", 4) == 0 ||
|
||||
std::memcmp(bytes + off, "SHEX", 4) == 0 ||
|
||||
std::memcmp(bytes + off, "SHDR", 4) == 0 ||
|
||||
std::memcmp(bytes + off, "ACCC", 4) == 0) {
|
||||
std::memcmp(bytes + off, "SHDR", 4) == 0) {
|
||||
has_shader_chunk = true;
|
||||
}
|
||||
if (i < 16) {
|
||||
@@ -208,43 +199,13 @@ ULONG STDMETHODCALLTYPE BxDeviceProxy::AddRef() {
|
||||
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
}
|
||||
|
||||
bool BxDeviceProxy::bx_try_acquire_if_nonzero() {
|
||||
ULONG cur = refs_.load(std::memory_order_acquire);
|
||||
while (cur != 0) {
|
||||
if (refs_.compare_exchange_weak(cur, cur + 1, std::memory_order_acq_rel, std::memory_order_acquire)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool BxDeviceProxy::bx_try_release_last() {
|
||||
ULONG expected = 1;
|
||||
return refs_.compare_exchange_strong(expected, 0, std::memory_order_acq_rel, std::memory_order_acquire);
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxDeviceProxy::Release() {
|
||||
/* The 1->0 transition and a weak GetDevice acquire share g_section.
|
||||
GetDevice adds a reference only when the count is non-zero, so a proxy
|
||||
at zero is never brought back. Exactly one Release performs final cleanup. */
|
||||
ULONG cur = refs_.load(std::memory_order_acquire);
|
||||
for (;;) {
|
||||
if (cur == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (cur > 1) {
|
||||
if (refs_.compare_exchange_weak(cur, cur - 1, std::memory_order_acq_rel, std::memory_order_acquire)) {
|
||||
return cur - 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (bx_vmem_final_release(this)) {
|
||||
bx_release_hosts();
|
||||
delete this;
|
||||
return 0;
|
||||
}
|
||||
cur = refs_.load(std::memory_order_acquire);
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
bx_release_hosts();
|
||||
delete this;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT BxDeviceProxy::wrap_child(IUnknown* host_child, const char* what, REFIID riid, void** ppv) {
|
||||
@@ -384,25 +345,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateGraphicsPipelineState(const D3D12
|
||||
log_created("graphics pipeline state", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (!desc) {
|
||||
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(desc, riid, ppv);
|
||||
log_created("graphics pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
/* M2 shader format gate (#466): every stage is classified; an ACCC-only stage fails the PSO. */
|
||||
BxShaderGate gate;
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC admitted = *desc;
|
||||
HRESULT gated = gate.admit("graphics", "VS", desc->VS, admitted.VS);
|
||||
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "PS", desc->PS, admitted.PS);
|
||||
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "DS", desc->DS, admitted.DS);
|
||||
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "HS", desc->HS, admitted.HS);
|
||||
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "GS", desc->GS, admitted.GS);
|
||||
if (FAILED(gated)) {
|
||||
if (ppv) *ppv = nullptr;
|
||||
log_created("graphics pipeline state", gated);
|
||||
return gated;
|
||||
}
|
||||
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(&admitted, riid, ppv);
|
||||
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(desc, riid, ppv);
|
||||
log_created("graphics pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
@@ -414,147 +357,11 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateComputePipelineState(const D3D12_
|
||||
log_created("compute pipeline state", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (!desc) {
|
||||
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(desc, riid, ppv);
|
||||
log_created("compute pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
/* M2 shader format gate (#466): DXIL is passed on, an ACCC-only container is refused. */
|
||||
BxShaderGate gate;
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC admitted = *desc;
|
||||
const HRESULT gated = gate.admit("compute", "CS", desc->CS, admitted.CS);
|
||||
if (FAILED(gated)) {
|
||||
if (ppv) *ppv = nullptr;
|
||||
log_created("compute pipeline state", gated);
|
||||
return gated;
|
||||
}
|
||||
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(&admitted, riid, ppv);
|
||||
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(desc, riid, ppv);
|
||||
log_created("compute pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
/* Stream PSO subobjects (#576). A stream is a sequence of 8-byte-aligned records, each a
|
||||
* subobject type and a type-dependent payload. The real layout aligns the record, not the
|
||||
* payload: a payload whose type is only 4-byte aligned starts at offset 4, not 8. Measured
|
||||
* with the shim's own toolchain, that is the case for BLEND, SAMPLE_MASK, RASTERIZER,
|
||||
* DEPTH_STENCIL, DEPTH_STENCIL1, IB_STRIP_CUT_VALUE, PRIMITIVE_TOPOLOGY,
|
||||
* RENDER_TARGET_FORMATS, DEPTH_STENCIL_FORMAT, SAMPLE_DESC, NODE_MASK and FLAGS. Deriving
|
||||
* both the payload offset and the record size from the compiler keeps this table honest. */
|
||||
template<class Payload>
|
||||
struct alignas(void*) StreamRecord {
|
||||
/* alignas is on the CLASS, as in CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT: it pads the
|
||||
* whole record to 8 bytes but does not move a 4-byte-aligned payload off offset 4. */
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
Payload payload;
|
||||
};
|
||||
template<class Payload>
|
||||
constexpr size_t payload_at() { return offsetof(StreamRecord<Payload>, payload); }
|
||||
template<class Payload>
|
||||
constexpr size_t record_size() {
|
||||
return (offsetof(StreamRecord<Payload>, payload) + sizeof(Payload) + 7) & ~static_cast<size_t>(7);
|
||||
}
|
||||
|
||||
struct StreamSubobject {
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
size_t payload_offset;
|
||||
size_t record_size;
|
||||
const char* stage; /* non-null only for a shader subobject */
|
||||
};
|
||||
|
||||
#define BX_SUBOBJECT(tag, type, stage) \
|
||||
{tag, payload_at<type>(), record_size<type>(), stage}
|
||||
constexpr StreamSubobject kStreamSubobjects[] = {
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, void*, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE, "VS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE, "PS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, D3D12_SHADER_BYTECODE, "DS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, D3D12_SHADER_BYTECODE, "HS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, D3D12_SHADER_BYTECODE, "GS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, D3D12_SHADER_BYTECODE, "CS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, D3D12_STREAM_OUTPUT_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, D3D12_INPUT_LAYOUT_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, D3D12_CACHED_PIPELINE_STATE, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, D3D12_DEPTH_STENCIL_DESC1, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, D3D12_VIEW_INSTANCING_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE, "AS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE, "MS"),
|
||||
};
|
||||
#undef BX_SUBOBJECT
|
||||
|
||||
/* Pin the layout facts the walker depends on, measured with this toolchain. A header change
|
||||
* that moves a payload must fail to compile rather than desync the walk (#576 review). */
|
||||
static_assert(payload_at<D3D12_SHADER_BYTECODE>() == 8, "shader payloads sit at offset 8");
|
||||
static_assert(record_size<D3D12_SHADER_BYTECODE>() == 24, "a shader record is 24 bytes");
|
||||
static_assert(payload_at<UINT>() == 4, "4-byte payloads sit at offset 4, not 8");
|
||||
static_assert(record_size<UINT>() == 8, "a UINT record is 8 bytes");
|
||||
static_assert(payload_at<D3D12_BLEND_DESC>() == 4, "BLEND payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_RASTERIZER_DESC>() == 4, "RASTERIZER payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_RT_FORMAT_ARRAY>() == 4, "RT_FORMAT_ARRAY payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_DEPTH_STENCIL_DESC1>() == 4, "DEPTH_STENCIL1 payload sits at offset 4");
|
||||
static_assert(payload_at<void*>() == 8 && record_size<void*>() == 16, "root signature record");
|
||||
static_assert(payload_at<D3D12_INPUT_LAYOUT_DESC>() == 8, "INPUT_LAYOUT payload sits at offset 8");
|
||||
|
||||
const StreamSubobject* find_subobject(uint32_t type) {
|
||||
for (const StreamSubobject& entry : kStreamSubobjects) {
|
||||
if (static_cast<uint32_t>(entry.type) == type) return &entry;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* Copies the caller's stream into `copy` so the gate can substitute prepared bytecode without
|
||||
* touching memory it does not own, and records where each shader payload sits. An unknown tag,
|
||||
* or a payload that overruns SizeInBytes, is rejected. */
|
||||
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
|
||||
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names) {
|
||||
if (desc.SizeInBytes == 0 || !desc.pPipelineStateSubobjectStream) return E_INVALIDARG;
|
||||
const auto* source = static_cast<const uint8_t*>(desc.pPipelineStateSubobjectStream);
|
||||
copy.assign(source, source + desc.SizeInBytes);
|
||||
size_t offset = 0;
|
||||
while (offset < copy.size()) {
|
||||
if (copy.size() - offset < sizeof(SIZE_T)) return E_INVALIDARG;
|
||||
/* The tag is a 4-byte enum at the start of an 8-byte-aligned record; the rest of
|
||||
* those 8 bytes is padding a caller may leave uninitialized, so read only the enum
|
||||
* and step to the payload at offset sizeof(SIZE_T). */
|
||||
uint32_t raw = 0;
|
||||
std::memcpy(&raw, ©[offset], sizeof(raw));
|
||||
if (raw >= static_cast<uint32_t>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID)) return E_INVALIDARG;
|
||||
const StreamSubobject* entry = find_subobject(raw);
|
||||
if (!entry) return E_INVALIDARG;
|
||||
/* Microsoft's ID3D12Device2 rules reject a duplicated subobject type. */
|
||||
for (size_t seen = 0; seen < offset; ) {
|
||||
uint32_t prior = 0;
|
||||
std::memcpy(&prior, ©[seen], sizeof(prior));
|
||||
if (prior == raw) return E_INVALIDARG;
|
||||
const StreamSubobject* prior_entry = find_subobject(prior);
|
||||
if (!prior_entry) return E_INVALIDARG;
|
||||
seen += prior_entry->record_size;
|
||||
}
|
||||
const size_t payload = offset + entry->payload_offset;
|
||||
const size_t record = entry->record_size;
|
||||
if (copy.size() - offset < record) return E_INVALIDARG;
|
||||
if (entry->stage) {
|
||||
D3D12_SHADER_BYTECODE code{};
|
||||
std::memcpy(&code, ©[payload], sizeof(code));
|
||||
if (code.BytecodeLength != 0 && !code.pShaderBytecode) return E_INVALIDARG;
|
||||
stage_offsets.push_back(payload);
|
||||
stage_names.push_back(entry->stage);
|
||||
}
|
||||
offset += record;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("ID3D12Device2", "CreatePipelineState");
|
||||
if (!h_ID3D12Device2) {
|
||||
@@ -562,50 +369,12 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
|
||||
if (ppv) *ppv = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
if (ppv) *ppv = nullptr;
|
||||
if (!desc) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", "pso=stream bytes=0 shaders_not_parsed=1");
|
||||
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
/* M2 shader format gate (#576): the stream form classifies its stages like the desc forms,
|
||||
* so an ACCC-only container is refused instead of reaching D3DMetal unparsed. */
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
const HRESULT copied = copy_stream(*desc, stream, offsets, names);
|
||||
{
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=%d",
|
||||
static_cast<unsigned long long>(desc->SizeInBytes), offsets.empty() ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
|
||||
}
|
||||
if (FAILED(copied) || offsets.empty()) {
|
||||
const HRESULT hr = FAILED(copied) ? copied : h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
BxShaderGate gate;
|
||||
HRESULT gated = S_OK;
|
||||
for (size_t i = 0; i < offsets.size() && SUCCEEDED(gated); ++i) {
|
||||
D3D12_SHADER_BYTECODE in{};
|
||||
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
|
||||
D3D12_SHADER_BYTECODE out = in;
|
||||
gated = gate.admit("stream", names[i], in, out);
|
||||
/* `out` is either the caller's bytes or the gate's copy, which lives until `gate`
|
||||
* is destroyed, so only the pointer/length inside our own copy change. */
|
||||
if (SUCCEEDED(gated)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
|
||||
}
|
||||
if (FAILED(gated)) {
|
||||
log_created("stream pipeline state", gated);
|
||||
return gated;
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(&admitted, riid, ppv);
|
||||
/* The stream form is forwarded unparsed: only its size is recorded (sub-object walking is M2 work). */
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=1",
|
||||
static_cast<unsigned long long>(desc ? desc->SizeInBytes : 0));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
|
||||
HRESULT hr = h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
@@ -689,11 +458,6 @@ HRESULT STDMETHODCALLTYPE BxChildProxy<Gen>::QueryInterface(REFIID riid, void**
|
||||
*ppv = static_cast<Gen*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
if constexpr (std::is_same_v<Gen, BxCommandQueueProxyImpl>) {
|
||||
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
|
||||
return bx_present_query_queue(this, ppv); /* BetterXen's presentation bridge, presentx.h */
|
||||
}
|
||||
}
|
||||
return query_host_unproxied(host_identity_, Gen::kLeafName, riid, ppv);
|
||||
}
|
||||
|
||||
|
||||
@@ -53,12 +53,6 @@ public:
|
||||
ULONG STDMETHODCALLTYPE AddRef() override;
|
||||
ULONG STDMETHODCALLTYPE Release() override;
|
||||
|
||||
/* Compare-exchange increment. False when the count is already zero.
|
||||
Weak GetDevice calls this under g_section so a proxy at zero is never resurrected. */
|
||||
bool bx_try_acquire_if_nonzero();
|
||||
/* Compare-exchange 1 to 0. Caller holds g_section. True only for the thread that wins. */
|
||||
bool bx_try_release_last();
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID riid, void** ppv) override;
|
||||
HRESULT STDMETHODCALLTYPE CreateCommandQueue1(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID creator_id, REFIID riid, void** ppv) override;
|
||||
HRESULT STDMETHODCALLTYPE CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** ppv) override;
|
||||
|
||||
@@ -175,7 +175,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateHeap(const D3D12_HEAP_DESC * a
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
|
||||
BX_D3D_TRACE("ID3D12Device", "CreatePlacedResource");
|
||||
if (!h_ID3D12Device) { BX_VTABLE_STUB_LOG("ID3D12Device", 29u, "CreatePlacedResource"); return E_NOTIMPL; }
|
||||
return h_ID3D12Device->CreatePlacedResource(bx_unwrap(a0), a1, a2, a3, a4, a5, a6);
|
||||
return h_ID3D12Device->CreatePlacedResource(a0, a1, a2, a3, a4, a5, a6);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateReservedResource(const D3D12_RESOURCE_DESC * a0, D3D12_RESOURCE_STATES a1, const D3D12_CLEAR_VALUE * a2, REFIID a3, void ** a4) {
|
||||
@@ -385,7 +385,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource2(const D3D12
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource1(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
|
||||
BX_D3D_TRACE("ID3D12Device8", "CreatePlacedResource1");
|
||||
if (!h_ID3D12Device8) { BX_VTABLE_STUB_LOG("ID3D12Device8", 70u, "CreatePlacedResource1"); return E_NOTIMPL; }
|
||||
return bx_vmem_create_placed_resource1(h_ID3D12Device8, a0, a1, a2, a3, a4, a5, a6);
|
||||
return h_ID3D12Device8->CreatePlacedResource1(a0, a1, a2, a3, a4, a5, a6);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE BxDeviceProxyGen::CreateSamplerFeedbackUnorderedAccessView(ID3D12Resource * a0, ID3D12Resource * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
|
||||
@@ -421,7 +421,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource3(const D3D12
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource2(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_BARRIER_LAYOUT a3, const D3D12_CLEAR_VALUE * a4, UINT32 a5, DXGI_FORMAT * a6, REFIID a7, void ** a8) {
|
||||
BX_D3D_TRACE("ID3D12Device10", "CreatePlacedResource2");
|
||||
if (!h_ID3D12Device10) { BX_VTABLE_STUB_LOG("ID3D12Device10", 77u, "CreatePlacedResource2"); return E_NOTIMPL; }
|
||||
return bx_vmem_create_placed_resource2(h_ID3D12Device10, a0, a1, a2, a3, a4, a5, a6, a7, a8);
|
||||
return h_ID3D12Device10->CreatePlacedResource2(a0, a1, a2, a3, a4, a5, a6, a7, a8);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateReservedResource2(const D3D12_RESOURCE_DESC * a0, D3D12_BARRIER_LAYOUT a1, const D3D12_CLEAR_VALUE * a2, ID3D12ProtectedResourceSession * a3, UINT32 a4, DXGI_FORMAT * a5, REFIID a6, void ** a7) {
|
||||
@@ -634,7 +634,7 @@ HRESULT STDMETHODCALLTYPE BxCommandQueueProxyGen::SetName(const WCHAR * a0) {
|
||||
void STDMETHODCALLTYPE BxCommandQueueProxyGen::UpdateTileMappings(ID3D12Resource * a0, UINT a1, const D3D12_TILED_RESOURCE_COORDINATE * a2, const D3D12_TILE_REGION_SIZE * a3, ID3D12Heap * a4, UINT a5, const D3D12_TILE_RANGE_FLAGS * a6, const UINT * a7, const UINT * a8, D3D12_TILE_MAPPING_FLAGS a9) {
|
||||
BX_D3D_TRACE("ID3D12CommandQueue", "UpdateTileMappings");
|
||||
if (!h_ID3D12CommandQueue) { BX_VTABLE_STUB_LOG("ID3D12CommandQueue", 8u, "UpdateTileMappings"); return; }
|
||||
h_ID3D12CommandQueue->UpdateTileMappings(a0, a1, a2, a3, bx_unwrap(a4), a5, a6, a7, a8, a9);
|
||||
h_ID3D12CommandQueue->UpdateTileMappings(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE BxCommandQueueProxyGen::CopyTileMappings(ID3D12Resource * a0, const D3D12_TILED_RESOURCE_COORDINATE * a1, ID3D12Resource * a2, const D3D12_TILED_RESOURCE_COORDINATE * a3, const D3D12_TILE_REGION_SIZE * a4, D3D12_TILE_MAPPING_FLAGS a5) {
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_PROXY_GENERATED_H
|
||||
#define BETTERXEN_D3D12_XS_PROXY_GENERATED_H
|
||||
|
||||
/* HANDOFF targets: the host interface, then the caller's arguments unmodified. */
|
||||
HRESULT bx_vmem_create_placed_resource1(ID3D12Device8* host, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6);
|
||||
HRESULT bx_vmem_create_placed_resource2(ID3D12Device10* host, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_BARRIER_LAYOUT a3, const D3D12_CLEAR_VALUE * a4, UINT32 a5, DXGI_FORMAT * a6, REFIID a7, void ** a8);
|
||||
|
||||
class BxDeviceProxyGen : public ID3D12Device10 {
|
||||
public:
|
||||
static constexpr const char* kLeafName = "ID3D12Device10";
|
||||
|
||||
@@ -1,302 +0,0 @@
|
||||
#include "shader_gate.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <iterator>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_shader_bridge.h"
|
||||
|
||||
/*
|
||||
* The bridge is loaded on first use, only by full path from this DLL's own directory, where
|
||||
* build-shims.sh stages it with the shims (#484). A bare-name load would search the guest EXE's
|
||||
* directory and PATH first and could pick up a different copy. It is optional at load time, so a
|
||||
* missing bridge is a logged condition rather than a failure to load d3d12_xs.dll. Without it,
|
||||
* shaders are not classified, but a container that has an ACCC chunk and no DXIL chunk is still
|
||||
* refused, from a bounds-checked chunk scan, so it never reaches the host device.
|
||||
*
|
||||
* Constraint flags come from two public DXIL container parts, read here with bounds checks:
|
||||
* - SFI0 is one uint64 of feature flags (DXC DxilContainer.h, DxilShaderFeatureInfo). The bit
|
||||
* values are D3D_SHADER_FEATURE_* from the public DirectX-Headers d3dcommon.h (MIT):
|
||||
* WAVE_OPS 0x4000, INT64_OPS 0x8000, ATOMIC_INT64_ON_TYPED_RESOURCE 0x400000,
|
||||
* ATOMIC_INT64_ON_GROUP_SHARED 0x800000, ATOMIC_INT64_ON_DESCRIPTOR_HEAP_RESOURCE 0x10000000.
|
||||
* - PSV0 starts with a uint32 PSVRuntimeInfo size, then PSVRuntimeInfo0, whose 16-byte stage
|
||||
* union is followed by MinimumExpectedWaveLaneCount and MaximumExpectedWaveLaneCount (DXC
|
||||
* DxilPipelineStateValidation.h). DXC 1.9.2609 writes 64/64 there for [WaveSize(64)] and
|
||||
* 0/0xFFFFFFFF without it (checked on the #453 blobs).
|
||||
* 64-bit atomics on raw buffers set only INT64_OPS, so they cannot be told apart from other
|
||||
* 64-bit integer use here; see ADR 0008.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
using InspectFn = bx_shader_status_t (*)(const uint8_t*, size_t, bx_shader_inspection_t*);
|
||||
using PrepareFn = bx_shader_status_t (*)(const uint8_t*, size_t, uint8_t**, size_t*);
|
||||
using FreeFn = void (*)(uint8_t*, size_t);
|
||||
|
||||
struct Bridge {
|
||||
InspectFn inspect = nullptr;
|
||||
PrepareFn prepare = nullptr;
|
||||
FreeFn release = nullptr;
|
||||
};
|
||||
|
||||
Bridge g_bridge;
|
||||
INIT_ONCE g_bridge_once = INIT_ONCE_STATIC_INIT;
|
||||
|
||||
template <typename Fn>
|
||||
Fn proc(HMODULE module, const char* name) {
|
||||
return reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(module, name)));
|
||||
}
|
||||
|
||||
BOOL CALLBACK load_bridge(PINIT_ONCE, PVOID, PVOID*) {
|
||||
HMODULE self = nullptr;
|
||||
HMODULE module = nullptr;
|
||||
wchar_t path[MAX_PATH];
|
||||
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
reinterpret_cast<LPCWSTR>(&load_bridge), &self)) {
|
||||
const DWORD length = GetModuleFileNameW(self, path, MAX_PATH);
|
||||
wchar_t* slash = length && length < MAX_PATH ? std::wcsrchr(path, L'\\') : nullptr;
|
||||
constexpr wchar_t kName[] = L"bx_shader_bridge.dll";
|
||||
if (slash && static_cast<size_t>(slash + 1 - path) + std::size(kName) <= MAX_PATH) {
|
||||
std::memcpy(slash + 1, kName, sizeof(kName));
|
||||
module = LoadLibraryExW(path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
|
||||
}
|
||||
}
|
||||
if (module) {
|
||||
g_bridge.inspect = proc<InspectFn>(module, "bx_shader_inspect");
|
||||
g_bridge.prepare = proc<PrepareFn>(module, "bx_shader_prepare_for_d3dmetal");
|
||||
g_bridge.release = proc<FreeFn>(module, "bx_shader_free_buffer");
|
||||
}
|
||||
if (!g_bridge.inspect || !g_bridge.prepare || !g_bridge.release) {
|
||||
g_bridge = {};
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "shader_bridge_missing",
|
||||
module ? "bx_shader_bridge.dll lacks an entry point; shaders pass unclassified, ACCC-only refused"
|
||||
: "bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, "
|
||||
"ACCC-only refused");
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
const Bridge* bridge() {
|
||||
InitOnceExecuteOnce(&g_bridge_once, load_bridge, nullptr, nullptr);
|
||||
return g_bridge.inspect ? &g_bridge : nullptr;
|
||||
}
|
||||
|
||||
uint32_t read_u32(const uint8_t* at) {
|
||||
uint32_t value;
|
||||
std::memcpy(&value, at, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
/* The payload of the first chunk named `fourcc`, or null. Every read is bounds-checked, so this
|
||||
* is safe on a container nobody has validated (the no-bridge path relies on that). */
|
||||
const uint8_t* find_chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
|
||||
if (len < 32) return nullptr;
|
||||
const uint32_t count = read_u32(bytes + 28);
|
||||
for (uint32_t i = 0; i < count && 32 + 4 * static_cast<size_t>(i) + 4 <= len; ++i) {
|
||||
const uint32_t offset = read_u32(bytes + 32 + 4 * static_cast<size_t>(i));
|
||||
if (offset > len || len - offset < 8) continue;
|
||||
if (std::memcmp(bytes + offset, fourcc, 4) != 0) continue;
|
||||
const uint32_t chunk = read_u32(bytes + offset + 4);
|
||||
if (chunk > len - offset - 8) return nullptr;
|
||||
*size = chunk;
|
||||
return bytes + offset + 8;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* True when any chunk header in the table is tagged `fourcc`, whatever its declared size. */
|
||||
bool has_chunk_tag(const uint8_t* bytes, size_t len, const char* fourcc) {
|
||||
if (len < 32) return false;
|
||||
const uint32_t count = read_u32(bytes + 28);
|
||||
for (uint32_t i = 0; i < count && 32 + 4 * static_cast<size_t>(i) + 4 <= len; ++i) {
|
||||
const uint32_t offset = read_u32(bytes + 32 + 4 * static_cast<size_t>(i));
|
||||
if (offset <= len && len - offset >= 4 && std::memcmp(bytes + offset, fourcc, 4) == 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
struct Constraints {
|
||||
bool has_flags = false;
|
||||
uint64_t flags = 0;
|
||||
bool has_lanes = false;
|
||||
uint32_t lanes_min = 0;
|
||||
uint32_t lanes_max = 0;
|
||||
};
|
||||
|
||||
Constraints read_constraints(const uint8_t* bytes, size_t len) {
|
||||
Constraints c;
|
||||
uint32_t size = 0;
|
||||
if (const uint8_t* sfi0 = find_chunk(bytes, len, "SFI0", &size); sfi0 && size >= 8) {
|
||||
std::memcpy(&c.flags, sfi0, sizeof(c.flags));
|
||||
c.has_flags = true;
|
||||
}
|
||||
if (const uint8_t* psv0 = find_chunk(bytes, len, "PSV0", &size); psv0 && size >= 4) {
|
||||
const uint32_t info_size = read_u32(psv0);
|
||||
if (info_size >= 24 && size >= 4u + 24u) {
|
||||
c.lanes_min = read_u32(psv0 + 4 + 16);
|
||||
c.lanes_max = read_u32(psv0 + 4 + 20);
|
||||
c.has_lanes = true;
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
constexpr uint64_t kWaveOps = 0x4000;
|
||||
constexpr uint64_t kInt64Ops = 0x8000;
|
||||
constexpr uint64_t kAtomic64Typed = 0x400000;
|
||||
constexpr uint64_t kAtomic64GroupShared = 0x800000;
|
||||
constexpr uint64_t kAtomic64Heap = 0x10000000;
|
||||
|
||||
/* The [WaveSize(64)] case on its own (#591). A wider-than-32 wave is refused at PSO creation
|
||||
* rather than handed to a host that creates the pipeline and never runs it: the caller then
|
||||
* learns from a failed call instead of from a silently absent draw. Lowering 64 lanes to 32 is
|
||||
* a semantic transform (reductions, lane indices, 64-bit masks, cross-half permutes, barriers)
|
||||
* and is deferred. 64-bit atomics stay warn-only until their detection is complete (#589). */
|
||||
bool wave_wider_than_32(const Constraints& c) {
|
||||
return c.has_lanes && c.lanes_min > 32;
|
||||
}
|
||||
|
||||
/* Measured on D3DMetal (docs/research/d3dmetal-gpu-limits.md): pipelines that require a wave
|
||||
* wider than 32 lanes, or 64-bit atomics, are created but never run. */
|
||||
bool known_d3dmetal_gap(const Constraints& c) {
|
||||
return wave_wider_than_32(c)
|
||||
|| (c.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap));
|
||||
}
|
||||
const char* kind_name(bx_shader_kind_t kind) {
|
||||
switch (kind) {
|
||||
case BX_SHADER_DXBC_DXIL: return "dxil";
|
||||
case BX_SHADER_DXBC_LEGACY: return "legacy_dxbc";
|
||||
case BX_SHADER_DXBC_ACCC: return "accc_only";
|
||||
case BX_SHADER_DXBC_DUAL: return "dual";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
void log_gate(const char* pso_kind, const char* stage, size_t len, const bx_shader_inspection_t* info,
|
||||
const Constraints* c, const char* decision, HRESULT hr) {
|
||||
char lanes[32] = "none";
|
||||
if (c && c->has_lanes) {
|
||||
std::snprintf(lanes, sizeof(lanes), "%lu-%lu", static_cast<unsigned long>(c->lanes_min),
|
||||
static_cast<unsigned long>(c->lanes_max));
|
||||
}
|
||||
char detail[400];
|
||||
if (info) {
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"pso=%s stage=%s decision=%s hr=0x%08lx kind=%s shader_stage=%d sm=%lu.%lu bytes=%llu "
|
||||
"dxil=%lu accc=%lu sfi0=0x%llx wave_ops=%d int64_ops=%d atomic64=%s%s%s wave_lanes=%s",
|
||||
pso_kind, stage, decision, static_cast<unsigned long>(hr), kind_name(info->kind),
|
||||
static_cast<int>(info->stage), static_cast<unsigned long>(info->shader_model_major),
|
||||
static_cast<unsigned long>(info->shader_model_minor), static_cast<unsigned long long>(len),
|
||||
static_cast<unsigned long>(info->dxil_chunk_size),
|
||||
static_cast<unsigned long>(info->accc_chunk_size),
|
||||
static_cast<unsigned long long>(c ? c->flags : 0), c && (c->flags & kWaveOps) ? 1 : 0,
|
||||
c && (c->flags & kInt64Ops) ? 1 : 0,
|
||||
c && (c->flags & kAtomic64Typed) ? "typed," : "",
|
||||
c && (c->flags & kAtomic64GroupShared) ? "groupshared," : "",
|
||||
c && (c->flags & kAtomic64Heap) ? "heap," : "", lanes);
|
||||
} else {
|
||||
std::snprintf(detail, sizeof(detail), "pso=%s stage=%s decision=%s hr=0x%08lx bytes=%llu", pso_kind, stage,
|
||||
decision, static_cast<unsigned long>(hr), static_cast<unsigned long long>(len));
|
||||
}
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "shader_gate", detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
BxShaderGate::~BxShaderGate() {
|
||||
const Bridge* b = copy_count_ ? bridge() : nullptr;
|
||||
for (size_t i = 0; i < copy_count_; ++i) {
|
||||
if (b) b->release(copies_[i], copy_sizes_[i]);
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
|
||||
D3D12_SHADER_BYTECODE& out) {
|
||||
out = in;
|
||||
if (!in.pShaderBytecode || in.BytecodeLength == 0) return S_OK;
|
||||
const auto* bytes = static_cast<const uint8_t*>(in.pShaderBytecode);
|
||||
const size_t len = in.BytecodeLength;
|
||||
|
||||
const Bridge* b = bridge();
|
||||
if (!b) {
|
||||
/* No classifier: still keep ACCC-only containers away from the host (#478 review). */
|
||||
/* Any ACCC tag counts; only a DXIL chunk that fits counts as DXIL, so doubt refuses. */
|
||||
uint32_t size = 0;
|
||||
const bool dxbc = len >= 4 && std::memcmp(bytes, "DXBC", 4) == 0;
|
||||
if (dxbc && has_chunk_tag(bytes, len, "ACCC") && !find_chunk(bytes, len, "DXIL", &size)) {
|
||||
log_gate(pso_kind, stage, len, nullptr, nullptr, "reject_accc_only_unclassified", E_NOTIMPL);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
log_gate(pso_kind, stage, len, nullptr, nullptr, "pass_unclassified", S_OK);
|
||||
return S_OK;
|
||||
}
|
||||
bx_shader_inspection_t info{};
|
||||
if (b->inspect(bytes, len, &info) != BX_SHADER_OK) {
|
||||
/* Not a container the bridge understands; the host keeps its own validation. */
|
||||
log_gate(pso_kind, stage, len, nullptr, nullptr, "pass_uninspected", S_OK);
|
||||
return S_OK;
|
||||
}
|
||||
const Constraints constraints = read_constraints(bytes, len);
|
||||
switch (info.kind) {
|
||||
case BX_SHADER_DXBC_ACCC:
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "reject_accc_only", E_NOTIMPL);
|
||||
return E_NOTIMPL;
|
||||
case BX_SHADER_DXBC_DXIL:
|
||||
case BX_SHADER_DXBC_DUAL: {
|
||||
if (copy_count_ == kMaxCopies) {
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "copy_limit", E_UNEXPECTED);
|
||||
return E_UNEXPECTED;
|
||||
}
|
||||
uint8_t* copy = nullptr;
|
||||
size_t copy_len = 0;
|
||||
const bx_shader_status_t status = b->prepare(bytes, len, ©, ©_len);
|
||||
if (status != BX_SHADER_OK) {
|
||||
const HRESULT hr = status == BX_SHADER_ERR_OOM ? E_OUTOFMEMORY : E_INVALIDARG;
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "prepare_failed", hr);
|
||||
return hr;
|
||||
}
|
||||
copies_[copy_count_] = copy;
|
||||
copy_sizes_[copy_count_] = copy_len;
|
||||
++copy_count_;
|
||||
out.pShaderBytecode = copy;
|
||||
out.BytecodeLength = copy_len;
|
||||
/* A wave wider than 32 lanes is refused here (#591): D3DMetal creates such a
|
||||
* pipeline and never runs it, so returning S_OK would leave the caller with a
|
||||
* silent no-op. The stage keeps its copy alive via `gate` until the caller's
|
||||
* PSO call returns. */
|
||||
if (wave_wider_than_32(constraints)) {
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "reject_wave_wide", E_NOTIMPL);
|
||||
/* Keep the established gap-detail shape: the consumer (#593) strips a trailing
|
||||
* colon from the last value and treats `atomic64_flags` as always present, so
|
||||
* `wave_lanes_min` must not be the final field. */
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"pso=%s stage=%s wave_lanes_min=%lu atomic64_flags=0x%llx: a wave wider "
|
||||
"than 32 lanes is created but never run on D3DMetal (#453); refused at "
|
||||
"PSO creation (#591)",
|
||||
pso_kind, stage, static_cast<unsigned long>(constraints.lanes_min),
|
||||
static_cast<unsigned long long>(
|
||||
constraints.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap)));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "shader_d3dmetal_gap", detail);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "pass_dxil", S_OK);
|
||||
if (known_d3dmetal_gap(constraints)) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"pso=%s stage=%s wave_lanes_min=%lu atomic64_flags=0x%llx: D3DMetal creates such "
|
||||
"pipelines but does not run them (#453)",
|
||||
pso_kind, stage, static_cast<unsigned long>(constraints.lanes_min),
|
||||
static_cast<unsigned long long>(
|
||||
constraints.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap)));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "shader_d3dmetal_gap", detail);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
default:
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "pass_original", S_OK);
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* M2 Shader Format Gate (#466): classifies every shader handed to Create*PipelineState through
|
||||
* bx_shader_bridge.dll (abi/include/bx_shader_bridge.h, the Windows build of dxbc-accc, #445)
|
||||
* and decides what the host device receives. See docs/adr/0008-m2-shader-format-gate.md.
|
||||
*/
|
||||
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
class BxShaderGate {
|
||||
public:
|
||||
BxShaderGate() = default;
|
||||
~BxShaderGate();
|
||||
BxShaderGate(const BxShaderGate&) = delete;
|
||||
BxShaderGate& operator=(const BxShaderGate&) = delete;
|
||||
|
||||
/*
|
||||
* Logs one stage's classification (`shader_gate` event) and sets `out` to the bytecode the
|
||||
* host gets: the bridge's prepared DXIL copy for DXIL and dual containers, or `in` unchanged
|
||||
* for legacy DXBC, unclassifiable input, or when the bridge is missing (logged once as
|
||||
* `shader_bridge_missing`). Returns E_NOTIMPL for an ACCC-only container, which has no
|
||||
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge. Copies live until this
|
||||
* object is destroyed.
|
||||
*/
|
||||
HRESULT admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
|
||||
D3D12_SHADER_BYTECODE& out);
|
||||
|
||||
private:
|
||||
static constexpr size_t kMaxCopies = 5; /* VS, PS, DS, HS, GS */
|
||||
uint8_t* copies_[kMaxCopies] = {};
|
||||
size_t copy_sizes_[kMaxCopies] = {};
|
||||
size_t copy_count_ = 0;
|
||||
};
|
||||
@@ -9,9 +9,6 @@ Only method names, return types and parameter types are taken from the header:
|
||||
they are what an override must repeat verbatim to compile. Parameters are
|
||||
renamed positionally (a0, a1, ...). Methods listed in CUSTOM are declared but
|
||||
left for proxy.cpp to implement by hand (wrapping, unwrapping, logging).
|
||||
Methods listed in HANDOFF keep the generated trace and null-host stub, then pass
|
||||
the host interface and the caller's arguments, unmodified, to a free function
|
||||
whose declaration is generated from the same header signature.
|
||||
|
||||
Usage: python3 shims/d3d12_xs/tools/gen_proxy.py [path/to/d3d12.h]
|
||||
(default: located through `x86_64-w64-mingw32-g++ -E`)
|
||||
@@ -44,24 +41,11 @@ PROXIES = {
|
||||
}),
|
||||
}
|
||||
|
||||
# proxy class -> {method: free function}. The function receives the host interface of the method's
|
||||
# level followed by the caller's arguments; nothing is unwrapped. vmem.cpp implements both below
|
||||
# with the same placement validation and heap retention as CreatePlacedResource (slot 29).
|
||||
HANDOFF = {
|
||||
"BxDeviceProxyGen": {
|
||||
"CreatePlacedResource1": "bx_vmem_create_placed_resource1",
|
||||
"CreatePlacedResource2": "bx_vmem_create_placed_resource2",
|
||||
},
|
||||
}
|
||||
|
||||
# Interfaces that carry no host pointer of their own: their methods forward through the root level.
|
||||
ABSTRACT = {"IUnknown", "ID3D12Object", "ID3D12DeviceChild", "ID3D12Pageable", "ID3D12CommandList"}
|
||||
# A single-pointer parameter of one of these types may be one of our proxies and is unwrapped.
|
||||
# ID3D12Heap covers CreatePlacedResource, CreatePlacedResource1 and CreatePlacedResource2.
|
||||
# A wrapped heap passed straight through faults in the host (0xc0000005 on D3DMetal).
|
||||
MAYBE_PROXY = {"ID3D12CommandQueue", "ID3D12CommandAllocator", "ID3D12CommandList",
|
||||
"ID3D12GraphicsCommandList", "ID3D12Pageable", "ID3D12DeviceChild", "ID3D12Object",
|
||||
"ID3D12Heap", "ID3D12Heap1"}
|
||||
"ID3D12GraphicsCommandList", "ID3D12Pageable", "ID3D12DeviceChild", "ID3D12Object"}
|
||||
|
||||
IUNKNOWN = [
|
||||
("HRESULT", "QueryInterface", [("REFIID", ""), ("void **", "")]),
|
||||
@@ -130,7 +114,6 @@ def main():
|
||||
|
||||
h = ["// Generated by shims/d3d12_xs/tools/gen_proxy.py from the toolchain's <d3d12.h>. Do not edit by hand.",
|
||||
"#ifndef BETTERXEN_D3D12_XS_PROXY_GENERATED_H", "#define BETTERXEN_D3D12_XS_PROXY_GENERATED_H", ""]
|
||||
h_pre = []
|
||||
c = ["// Generated by shims/d3d12_xs/tools/gen_proxy.py from the toolchain's <d3d12.h>. Do not edit by hand.",
|
||||
'#include "proxy.h"', ""]
|
||||
|
||||
@@ -139,10 +122,6 @@ def main():
|
||||
levels = [i for i in chain if i not in ABSTRACT]
|
||||
root = levels[0]
|
||||
seen_custom = set()
|
||||
handoff = HANDOFF.get(cls, {})
|
||||
seen_handoff = set()
|
||||
if custom & handoff.keys():
|
||||
sys.exit(f"{cls}: methods in both CUSTOM and HANDOFF: {sorted(custom & handoff.keys())}")
|
||||
|
||||
h += [f"class {cls} : public {leaf} {{", "public:",
|
||||
f' static constexpr const char* kLeafName = "{leaf}";']
|
||||
@@ -180,18 +159,6 @@ def main():
|
||||
seen_custom.add(name)
|
||||
slot += 1
|
||||
continue
|
||||
if name in handoff:
|
||||
seen_handoff.add(name)
|
||||
fn = handoff[name]
|
||||
host_type = root if iface in ABSTRACT else iface
|
||||
h_pre.append(f"{ret} {fn}({host_type}* host{', ' if decl else ''}{decl});")
|
||||
call = f"{fn}({', '.join([host] + [f'a{n}' for n in range(len(params))])})"
|
||||
c += [f"{ret} STDMETHODCALLTYPE {cls}::{name}({decl}) {{",
|
||||
f' BX_D3D_TRACE("{iface}", "{name}");',
|
||||
f" if (!{host}) {{ {default_return(ret, iface, slot, name)} }}",
|
||||
f" {'' if ret == 'void' else 'return '}{call};", "}", ""]
|
||||
slot += 1
|
||||
continue
|
||||
args = []
|
||||
for n, (t, arr) in enumerate(params):
|
||||
bare = t.replace("const", "").replace(" ", "")
|
||||
@@ -210,9 +177,6 @@ def main():
|
||||
missing = custom - seen_custom
|
||||
if missing:
|
||||
sys.exit(f"{cls}: custom methods not found in header: {sorted(missing)}")
|
||||
missing = handoff.keys() - seen_handoff
|
||||
if missing:
|
||||
sys.exit(f"{cls}: hand-off methods not found in header: {sorted(missing)}")
|
||||
|
||||
h += ["", f" static constexpr unsigned kPublicSlotCount = {slot}u;",
|
||||
" /*",
|
||||
@@ -227,8 +191,6 @@ def main():
|
||||
h += ["", "protected:", f" ~{cls}() = default;", "};", ""]
|
||||
|
||||
h += ["#endif"]
|
||||
if h_pre:
|
||||
h[4:4] = ["/* HANDOFF targets: the host interface, then the caller's arguments unmodified. */"] + h_pre + [""]
|
||||
(OUT_DIR / "proxy_generated.h").write_text("\n".join(h) + "\n", encoding="utf-8")
|
||||
(OUT_DIR / "proxy_generated.cpp").write_text("\n".join(c), encoding="utf-8")
|
||||
print(f"wrote proxy_generated.h/.cpp from {header}")
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,157 +0,0 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_VMEM_H
|
||||
#define BETTERXEN_D3D12_XS_VMEM_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <windows.h>
|
||||
|
||||
/*
|
||||
* BetterXen-defined parameter block for D3D12ConfigureVirtualMemoryX.
|
||||
*
|
||||
* The export is PVOID and the frozen ABI has no size argument (abi/ is out of
|
||||
* scope). The first 8 bytes are therefore the initial probe: a magic word and
|
||||
* the following 32-bit value. Magic is 'BXVM' (0x4D565842); a matching header
|
||||
* and struct size select the full BetterXen block. A zero first word selects
|
||||
* the Xbox decoder, which checks the full block and may write its two address
|
||||
* outputs. Other headers (including unrecognized nonzero Xbox flags) fall
|
||||
* back with S_OK and no writes. A null pointer is not read.
|
||||
*
|
||||
* A block whose magic and size match is then checked in full. version is 1.
|
||||
* flags may be 0 or BX_D3D12_VMEM_FLAG_BACKING_HEAP. Any other flag bit, or a
|
||||
* non-zero reserved word, is not this struct either (logged S_OK, no write).
|
||||
* A recognised block with a bad size or a base_va that bx_xmem_query_region
|
||||
* does not resolve returns E_INVALIDARG even if its output is read-only. Valid
|
||||
* inputs with an initially unwritable output fall back with S_OK and a stub
|
||||
* log. A failed write after the accessibility check returns E_INVALIDARG.
|
||||
*
|
||||
* base_va is 0, or an address bx_xmem_query_region resolves. It is not a GPU pointer.
|
||||
* size_bytes is 0 or a 64 KiB multiple that does not exceed the active title limit.
|
||||
*
|
||||
* The call copies what it needs. The caller's pointer is not kept. cpu_pointer
|
||||
* is written only before this call returns: the persistent Map address of the
|
||||
* WRITE_BACK buffer if that backing heap already exists, otherwise 0. CreateHeap
|
||||
* does not write the block. A caller that needs the address after the backing
|
||||
* heap has been created calls D3D12ConfigureVirtualMemoryX again with the same
|
||||
* region (same base_va and size). That second call does not reset or recreate
|
||||
* the backing heap. It writes the current map into the new block. A nonzero
|
||||
* cpu_pointer is valid only while that backing buffer remains cached. Changing
|
||||
* the region or replacing the cache for another host device unmaps it, even if
|
||||
* the caller retains the heap. Callers must synchronize those operations with
|
||||
* access through the pointer and obtain a fresh pointer after replacement.
|
||||
*
|
||||
* CreateHeap returns that backing heap only when all of the following hold:
|
||||
* the block opted in with BX_D3D12_VMEM_FLAG_BACKING_HEAP, the region size is
|
||||
* non-zero, and the desc is the heap this file creates for the region:
|
||||
* Type CUSTOM, CPUPageProperty WRITE_BACK, MemoryPoolPreference L0,
|
||||
* SizeInBytes equal to the configured region, Alignment 0 or 64 KiB,
|
||||
* Flags exactly D3D12_HEAP_FLAG_NONE (the flag set used when the backing heap
|
||||
* is created), and CreationNodeMask and VisibleNodeMask each 0 or 1.
|
||||
* If the backing configuration changes during a backing request, CreateHeap
|
||||
* returns HRESULT_FROM_WIN32(ERROR_RETRY) and discards any newly allocated heap.
|
||||
* Any other CreateHeap is the host CreateHeap. The desc is not modified.
|
||||
* The live-heap budget charge is taken on create and dropped on the wrapper's
|
||||
* final Release. A resource created by CreatePlacedResource,
|
||||
* CreatePlacedResource1 or CreatePlacedResource2 holds the wrapper for its
|
||||
* lifetime, and all three validate the placement on every heap first.
|
||||
* GetDevice on every wrapper returns the BxDeviceProxy. An ordinary heap AddRefs
|
||||
* that proxy until the wrapper's final Release, matching BxChildProxy, so the
|
||||
* caller can release the device and keep the heap. The process-wide backing heap
|
||||
* does not AddRef. The cache would keep the device and its charge alive. That
|
||||
* pointer is weak. It is cleared when the heap leaves the cache (a new region
|
||||
* or a different host device) and when that proxy's last reference drops.
|
||||
* All three placement methods unwrap the wrapper to the host heap before the
|
||||
* host call. The cache records the host ID3D12Device
|
||||
* that built the heap. CreateHeap for a different host device releases the
|
||||
* heap and its buffer, credits the charge, and builds a new one. CreateHeap
|
||||
* for the same host device returns the cached heap. The check, the retarget,
|
||||
* and the caller's reference happen in one critical section.
|
||||
*
|
||||
* The layout must match tests/conformance/test_d3d12_placed/main.cpp.
|
||||
*/
|
||||
constexpr uint32_t BX_D3D12_VMEM_MAGIC = 0x4D565842u;
|
||||
constexpr uint32_t BX_D3D12_VMEM_FLAG_BACKING_HEAP = 0x1u;
|
||||
|
||||
struct BxD3d12VirtualMemoryConfig {
|
||||
uint32_t magic;
|
||||
uint32_t struct_size;
|
||||
uint32_t version;
|
||||
uint32_t flags;
|
||||
uint64_t base_va;
|
||||
uint64_t size_bytes;
|
||||
uint64_t reserved;
|
||||
uint64_t cpu_pointer;
|
||||
};
|
||||
static_assert(sizeof(BxD3d12VirtualMemoryConfig) == 48, "config block is 48 bytes");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, magic) == 0, "magic offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, struct_size) == 4, "struct_size offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, version) == 8, "version offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, flags) == 12, "flags offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, base_va) == 16, "base_va offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 24, "size_bytes offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 32, "reserved offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 40, "cpu_pointer offset");
|
||||
|
||||
/*
|
||||
* The Xbox virtual-memory configuration (D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION, d3d12_xs.h).
|
||||
*
|
||||
* Source: the authorized GDK documentation of D3D12ConfigureVirtualMemoryX and the
|
||||
* structure. Call-site observation of a project-authorized target build agrees with it: a
|
||||
* zero-initialized block with 3 or 4 in the page-table field and no flags.
|
||||
*
|
||||
* Documented: flags must be none (0); the GPU page table is sized in 4 MB units, at least 1
|
||||
* and clamped to 33 (default 5, 20 MB); the frame-buffer preserve size is 0 (none), -1 (the
|
||||
* legacy size, about 10 MB) or a byte count clamped to 64 MB; the two addresses are outputs,
|
||||
* the minimum always 2 GB; and the call fails with E_FAIL once a D3D12 device exists.
|
||||
*
|
||||
* The host does not size GPU page tables or keep a cross-process frame buffer, so the
|
||||
* decoder records both, writes the outputs and still logs BX_STUB_LOG. The maximum address
|
||||
* is documented only for the default size; for other sizes it is scaled linearly from that
|
||||
* value, an inference the log marks as max_estimated=1. A page count of 0 is refused: the
|
||||
* value of the header's DEFAULT constant is not documented.
|
||||
*/
|
||||
struct BxXboxVirtualMemoryConfig {
|
||||
uint32_t flags;
|
||||
uint32_t page_table_memory_4mb_page_count;
|
||||
uint32_t frame_buffer_preserve_memory_size_bytes;
|
||||
uint32_t padding;
|
||||
uint64_t minimum_valid_graphics_address;
|
||||
uint64_t maximum_valid_graphics_address;
|
||||
};
|
||||
static_assert(sizeof(BxXboxVirtualMemoryConfig) == 32, "Xbox config block is 32 bytes");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, flags) == 0, "flags offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, page_table_memory_4mb_page_count) == 4,
|
||||
"page_table_memory_4mb_page_count offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, frame_buffer_preserve_memory_size_bytes) == 8,
|
||||
"frame_buffer_preserve_memory_size_bytes offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address) == 16,
|
||||
"minimum_valid_graphics_address offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, maximum_valid_graphics_address) == 24,
|
||||
"maximum_valid_graphics_address offset");
|
||||
|
||||
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES = 5u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES = 33u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY = 0xFFFFFFFFu;
|
||||
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES = 64u * 1024u * 1024u;
|
||||
constexpr uint64_t BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS = 2ull * 1024ull * 1024ull * 1024ull;
|
||||
/* 159.375 GiB at the default 5 pages (20 MB), so 31.875 GiB per 4 MB page. */
|
||||
constexpr uint64_t BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE = 0x7F8000000ull;
|
||||
|
||||
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config);
|
||||
|
||||
/* Patches the device proxy vtable so CreateHeap and CreatePlacedResource run the code in vmem.cpp.
|
||||
CreatePlacedResource1 and CreatePlacedResource2 reach the same placement code through the
|
||||
generated proxy (gen_proxy.py HANDOFF), not through a vtable patch. */
|
||||
bool bx_vmem_install_device_hooks(void* device);
|
||||
|
||||
/* 1->0 Release of a device proxy, under g_section. Compare-exchanges the count from
|
||||
1 to 0 and clears every weak backing-heap pointer aimed at that proxy. Returns false
|
||||
when the count was no longer 1, so the caller retries. A true return is the only
|
||||
path into final cleanup. */
|
||||
bool bx_vmem_final_release(void* device_proxy);
|
||||
|
||||
/* AddRefs the host ID3D12Device that created the cached backing heap, or returns null.
|
||||
The test sets BX_D3D12_REUSE_BACKING_HOST=1 so a second proxy wraps this same host
|
||||
while the cache still holds it. */
|
||||
void* bx_vmem_addref_backing_host();
|
||||
|
||||
#endif /* BETTERXEN_D3D12_XS_VMEM_H */
|
||||
+14
-186
@@ -1,10 +1,6 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <new>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -14,30 +10,6 @@ constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
|
||||
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
|
||||
using Callback = void (WINAPI*)();
|
||||
|
||||
// GameInputEnumerationKind values from Microsoft's public GDK GameInput (v0) reference:
|
||||
// 0 = GameInputNoEnumeration, 1 = GameInputAsyncEnumeration, 2 = GameInputBlockingEnumeration.
|
||||
constexpr uint32_t kMaxEnumerationKind = 2;
|
||||
|
||||
struct SrwExclusiveLock {
|
||||
explicit SrwExclusiveLock(SRWLOCK& lock) : lock_(lock) { AcquireSRWLockExclusive(&lock_); }
|
||||
~SrwExclusiveLock() { ReleaseSRWLockExclusive(&lock_); }
|
||||
SrwExclusiveLock(const SrwExclusiveLock&) = delete;
|
||||
SrwExclusiveLock& operator=(const SrwExclusiveLock&) = delete;
|
||||
|
||||
private:
|
||||
SRWLOCK& lock_;
|
||||
};
|
||||
|
||||
struct RegisteredDeviceCallback {
|
||||
void* device = nullptr;
|
||||
uint32_t input_kind = 0;
|
||||
uint32_t status_filter = 0;
|
||||
uint32_t enumeration_kind = 0;
|
||||
void* context = nullptr;
|
||||
Callback callback = nullptr;
|
||||
bool stopped = false;
|
||||
};
|
||||
|
||||
template<class T>
|
||||
HRESULT unavailable(T* out) {
|
||||
if (!out) return E_POINTER;
|
||||
@@ -45,38 +17,9 @@ HRESULT unavailable(T* out) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
class GameInputDispatcher;
|
||||
|
||||
class GameInput final : public IUnknown {
|
||||
LONG refs = 0;
|
||||
SRWLOCK callback_lock_ = SRWLOCK_INIT;
|
||||
uint64_t next_token_ = 1;
|
||||
std::unordered_map<uint64_t, RegisteredDeviceCallback> callbacks_;
|
||||
std::atomic<uint32_t> focus_policy_{0};
|
||||
// Live IGameInputDispatcher reference count. >0 means GameInput is in
|
||||
// "manual dispatch" mode; 0 means "automatic dispatch" mode.
|
||||
std::atomic<uint32_t> dispatcher_refs_{0};
|
||||
|
||||
public:
|
||||
// Logs the manual/automatic dispatch mode transition. Purely atomic: it
|
||||
// never takes callback_lock_, so it cannot introduce lock ordering hazards.
|
||||
void note_dispatch_mode(const char* mode, uint32_t count) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "mode=%s live_dispatchers=%u", mode,
|
||||
static_cast<unsigned>(count));
|
||||
bx_log_emit(BX_LOG_INFO, "gameinput", "dispatch_mode", detail);
|
||||
}
|
||||
|
||||
void on_dispatcher_created() {
|
||||
const uint32_t count = dispatcher_refs_.fetch_add(1, std::memory_order_acq_rel) + 1;
|
||||
if (count == 1) note_dispatch_mode("manual", count);
|
||||
}
|
||||
|
||||
void on_dispatcher_released() {
|
||||
const uint32_t count = dispatcher_refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (count == 0) note_dispatch_mode("automatic", count);
|
||||
}
|
||||
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
@@ -111,32 +54,9 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 8, "RegisterReadingCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterDeviceCallback(
|
||||
void* device,
|
||||
uint32_t input_kind,
|
||||
uint32_t status_filter,
|
||||
uint32_t enumeration_kind,
|
||||
void* context,
|
||||
Callback callback,
|
||||
uint64_t* out_token
|
||||
) {
|
||||
if (out_token) *out_token = 0;
|
||||
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kMaxEnumerationKind) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
const uint64_t token = next_token_++;
|
||||
callbacks_.emplace(token, RegisteredDeviceCallback{
|
||||
device,
|
||||
input_kind,
|
||||
status_filter,
|
||||
enumeration_kind,
|
||||
context,
|
||||
callback,
|
||||
false,
|
||||
});
|
||||
if (out_token) *out_token = token;
|
||||
return S_OK;
|
||||
virtual HRESULT WINAPI RegisterDeviceCallback(void*, uint32_t, uint32_t, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 10, "RegisterSystemButtonCallback");
|
||||
@@ -146,22 +66,17 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 11, "RegisterKeyboardLayoutCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual void WINAPI StopCallback(uint64_t token) {
|
||||
if (token == 0) return;
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
auto it = callbacks_.find(token);
|
||||
if (it != callbacks_.end()) {
|
||||
it->second.stopped = true;
|
||||
}
|
||||
virtual void WINAPI StopCallback(uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 12, "StopCallback");
|
||||
}
|
||||
virtual bool WINAPI UnregisterCallback(uint64_t token, uint64_t /*timeout_us*/) {
|
||||
if (token == 0) return false;
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
return callbacks_.erase(token) > 0;
|
||||
virtual bool WINAPI UnregisterCallback(uint64_t, uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 13, "UnregisterCallback");
|
||||
return false;
|
||||
}
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
|
||||
return unavailable(out);
|
||||
}
|
||||
// Slot 14. Defined out of line below because it allocates
|
||||
// GameInputDispatcher, which in turn calls back into this class.
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out);
|
||||
virtual HRESULT WINAPI CreateAggregateDevice(uint32_t, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
|
||||
return unavailable(out);
|
||||
@@ -186,98 +101,11 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 20, "EnableOemDeviceSupport");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual void WINAPI SetFocusPolicy(uint32_t policy) {
|
||||
focus_policy_.store(policy, std::memory_order_relaxed);
|
||||
virtual void WINAPI SetFocusPolicy(uint32_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 21, "SetFocusPolicy");
|
||||
}
|
||||
};
|
||||
|
||||
// IGameInputDispatcher (GameInput v0): IUnknown + Dispatch + OpenWaitHandle.
|
||||
// Holding a reference puts GameInput in manual dispatch mode; releasing the
|
||||
// last one returns it to automatic dispatch mode.
|
||||
class GameInputDispatcher final : public IUnknown {
|
||||
LONG refs = 1;
|
||||
GameInput* owner_ = nullptr;
|
||||
|
||||
public:
|
||||
explicit GameInputDispatcher(GameInput* owner) : owner_(owner) {}
|
||||
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid == IID_IUnknown) {
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
// The GameInput v0 IGameInputDispatcher IID is not published in the
|
||||
// public Microsoft Learn / GDK documentation, so it is NOT guessed
|
||||
// here. Only IID_IUnknown is served; every other queried id is logged
|
||||
// (never silently ignored) and answered with E_NOINTERFACE.
|
||||
char guid[40];
|
||||
std::snprintf(guid, sizeof(guid), "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
|
||||
static_cast<unsigned long>(iid.Data1), iid.Data2, iid.Data3,
|
||||
iid.Data4[0], iid.Data4[1], iid.Data4[2], iid.Data4[3],
|
||||
iid.Data4[4], iid.Data4[5], iid.Data4[6], iid.Data4[7]);
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"IGameInputDispatcher iid=%s unsupported (v0 dispatcher IID not publicly documented)",
|
||||
guid);
|
||||
bx_log_emit(BX_LOG_WARN, "gameinput", "qi_unsupported", detail);
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override {
|
||||
const LONG count = InterlockedDecrement(&refs);
|
||||
if (count == 0) {
|
||||
GameInput* owner = owner_;
|
||||
owner_ = nullptr;
|
||||
if (owner) owner->on_dispatcher_released();
|
||||
delete this;
|
||||
}
|
||||
return static_cast<ULONG>(count);
|
||||
}
|
||||
|
||||
// Slot 3: bool Dispatch(uint64_t quotaInMicroseconds).
|
||||
// This shim has no real background input work, so the dispatch queue is
|
||||
// always empty. The documented "flush at least one item even at quota 0"
|
||||
// shape is honoured trivially: there is nothing to flush, so it returns
|
||||
// false (no work items remain) for every quota, including 0. No real work
|
||||
// is scheduled, and it never busy-waits or sleeps.
|
||||
virtual bool WINAPI Dispatch(uint64_t /*quota_us*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Slot 4: HRESULT OpenWaitHandle(HANDLE* waitHandle).
|
||||
// Returns a fresh manual-reset event on every call. The dispatcher owns
|
||||
// nothing after returning it: the caller closes it via CloseHandle.
|
||||
// LIMIT: the handle is created non-signaled and this shim never signals
|
||||
// it, because there is no background input work to make it ready. A
|
||||
// caller that waits on it with INFINITE will block forever; poll with a
|
||||
// timeout, or call Dispatch, instead.
|
||||
virtual HRESULT WINAPI OpenWaitHandle(HANDLE* out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
||||
if (!handle) {
|
||||
return HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
*out = handle;
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
HRESULT WINAPI GameInput::CreateDispatcher(void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
GameInputDispatcher* dispatcher = new (std::nothrow) GameInputDispatcher(this);
|
||||
if (!dispatcher) return E_OUTOFMEMORY;
|
||||
*out = dispatcher;
|
||||
// The GameInput singleton's own refcount is intentionally unchanged:
|
||||
// the dispatcher only moves the manual-dispatch mode counter.
|
||||
on_dispatcher_created();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
GameInput singleton;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <intrin.h>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
@@ -18,14 +17,6 @@ LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
|
||||
std::atomic_flag g_crash_logged{};
|
||||
std::atomic<bool> g_crash_in_flight{false};
|
||||
std::atomic<uint64_t> g_clwb_traps{0};
|
||||
|
||||
// Other AMD-only instructions Rosetta 2 (and Intel CPUs) raise #UD on. Their
|
||||
// counts reach the JSONL trace only: the frozen .def has no export for them.
|
||||
enum AmdKind { kClzero, kMonitorx, kMwaitx, kRdpru, kExtrq, kInsertq, kAmdKinds };
|
||||
constexpr const char* kAmdEvents[kAmdKinds] = {
|
||||
"clzero_trapped", "monitorx_trapped", "mwaitx_trapped",
|
||||
"rdpru_trapped", "extrq_trapped", "insertq_trapped"};
|
||||
std::atomic<uint64_t> g_amd_traps[kAmdKinds]{};
|
||||
bx_runtime_config_t g_config = {
|
||||
BX_ABI_VERSION,
|
||||
BX_PROFILE_LOCKHART,
|
||||
@@ -144,167 +135,6 @@ bool is_adx_opcode(const uint8_t* ip, size_t size) {
|
||||
return size - idx >= 4 && ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
|
||||
}
|
||||
|
||||
// Logs the first trap of a kind and then every power of two, as for clwb.
|
||||
void log_sampled_trap(const char* event, uint64_t count, uint64_t rip, size_t len) {
|
||||
if (count == 1 || (count & (count - 1)) == 0) {
|
||||
char msg[160];
|
||||
std::snprintf(msg, sizeof(msg),
|
||||
"rip=0x%016llx len=%zu total_traps=%llu",
|
||||
static_cast<unsigned long long>(rip), len,
|
||||
static_cast<unsigned long long>(count));
|
||||
bx_log_emit(BX_LOG_INFO, "runtime_veh", event, msg);
|
||||
}
|
||||
}
|
||||
|
||||
// The instruction encodings and architectural effects below are derived from
|
||||
// AMD APM vol. 3 (24594, rev. 3.36), Instruction Prefixes and CLZERO, MONITORX,
|
||||
// MWAITX, RDPRU, and vol. 4 (26568, rev. 3.25), EXTRQ and INSERTQ.
|
||||
struct AmdInstruction {
|
||||
AmdKind kind = kAmdKinds;
|
||||
size_t length = 0;
|
||||
bool address32 = false;
|
||||
size_t destination = 0;
|
||||
size_t source = 0;
|
||||
bool immediate = false;
|
||||
uint16_t field = 0;
|
||||
};
|
||||
|
||||
AmdInstruction decode_amd_instruction(const uint8_t* bytes, size_t size) {
|
||||
if (size < 3) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const bool address32 = bytes[0] == 0x67;
|
||||
const bool extract = bytes[0] == 0x66;
|
||||
const bool insert = bytes[0] == 0xF2;
|
||||
size_t offset = (address32 || extract || insert) ? 1 : 0;
|
||||
uint8_t rex = 0;
|
||||
if ((bytes[offset] & 0xF0) == 0x40) {
|
||||
rex = bytes[offset++];
|
||||
}
|
||||
if (size - offset < 3 || bytes[offset] != 0x0F) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const uint8_t opcode = bytes[offset + 1];
|
||||
const uint8_t operand = bytes[offset + 2];
|
||||
const size_t length = offset + 3;
|
||||
if (!extract && !insert && opcode == 0x01) {
|
||||
switch (operand) {
|
||||
case 0xFC: return {kClzero, length, address32};
|
||||
case 0xFA: return {kMonitorx, length, address32};
|
||||
case 0xFB: return address32 ? AmdInstruction{} : AmdInstruction{kMwaitx, length};
|
||||
case 0xFD: return address32 ? AmdInstruction{} : AmdInstruction{kRdpru, length};
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
if ((!extract && !insert) || (opcode != 0x78 && opcode != 0x79) ||
|
||||
(operand & 0xC0) != 0xC0) {
|
||||
return {};
|
||||
}
|
||||
const bool immediate = opcode == 0x78;
|
||||
const unsigned reg = (operand & 0x38) >> 3;
|
||||
if (immediate && (size - length < 2 || (extract && reg != 0))) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const size_t rm = (operand & 7) + ((rex & 1) ? 8 : 0);
|
||||
AmdInstruction result{extract ? kExtrq : kInsertq, length};
|
||||
result.destination = extract && immediate ? rm : reg + ((rex & 4) ? 8 : 0);
|
||||
result.source = rm;
|
||||
result.immediate = immediate;
|
||||
if (immediate) {
|
||||
result.length += 2;
|
||||
result.field = static_cast<uint16_t>(bytes[length + 1] * 256u + bytes[length]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void apply_sse4a(const AmdInstruction& instruction, CONTEXT& context) {
|
||||
M128A* registers = context.FltSave.XmmRegisters;
|
||||
M128A& destination = registers[instruction.destination];
|
||||
const M128A source = registers[instruction.source];
|
||||
const bool extract = instruction.kind == kExtrq;
|
||||
|
||||
// EXTRQ takes register controls from bits 13:0 and INSERTQ from 77:64.
|
||||
uint64_t field = instruction.field;
|
||||
if (!instruction.immediate) {
|
||||
field = extract ? source.Low : static_cast<uint64_t>(source.High);
|
||||
}
|
||||
const unsigned index = (field & 0x3F00) >> 8;
|
||||
const unsigned width = field & 0x3F;
|
||||
const uint64_t low_mask = width ? UINT64_MAX >> (64 - width) : UINT64_MAX;
|
||||
if (extract) {
|
||||
destination.Low = (destination.Low >> index) & low_mask;
|
||||
} else {
|
||||
const uint64_t positioned_mask = low_mask << index;
|
||||
destination.Low = (destination.Low & ~positioned_mask) |
|
||||
((source.Low << index) & positioned_mask);
|
||||
}
|
||||
// The APM leaves the upper quadword and out-of-range fields undefined.
|
||||
}
|
||||
|
||||
bool zero_guest_cache_line(uint64_t address, EXCEPTION_RECORD& exception) {
|
||||
// The supported guest has 64-byte cache lines. An aligned line fits
|
||||
// in one Windows page, including when the address is at the end of it.
|
||||
constexpr uintptr_t line_size = 64;
|
||||
const uintptr_t start = address & ~(line_size - 1);
|
||||
constexpr DWORD write_protections = PAGE_READWRITE | PAGE_WRITECOPY |
|
||||
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
MEMORY_BASIC_INFORMATION page{};
|
||||
if (VirtualQuery(reinterpret_cast<const void*>(start), &page, sizeof(page)) &&
|
||||
page.State == MEM_COMMIT && (page.Protect & write_protections) &&
|
||||
!(page.Protect & PAGE_GUARD)) {
|
||||
std::memset(reinterpret_cast<void*>(start), 0, line_size);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Pass the write fault on at the original guest RIP. Guard pages use
|
||||
// the same fallback, without Windows' one-shot guard-page semantics.
|
||||
exception.ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
|
||||
exception.NumberParameters = 2;
|
||||
exception.ExceptionInformation[0] = 1; // Write access.
|
||||
exception.ExceptionInformation[1] = start;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool apply_amd_instruction(const AmdInstruction& instruction, CONTEXT& context,
|
||||
EXCEPTION_RECORD& exception) {
|
||||
switch (instruction.kind) {
|
||||
case kClzero:
|
||||
return zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax)
|
||||
: context.Rax, exception);
|
||||
case kMonitorx:
|
||||
// There is no host monitor state. MWAITX may complete immediately.
|
||||
return true;
|
||||
case kMwaitx:
|
||||
// Approximate an early wakeup with one scheduler yield.
|
||||
SwitchToThread();
|
||||
return true;
|
||||
case kRdpru: {
|
||||
const uint32_t selector = static_cast<uint32_t>(context.Rcx);
|
||||
const uint64_t counter = selector < 2 ? __rdtsc() : 0;
|
||||
context.Rax = static_cast<uint32_t>(counter);
|
||||
context.Rdx = static_cast<uint32_t>(counter >> 32);
|
||||
|
||||
// The APM specifies zero for these five flags and marks CF modified.
|
||||
// BetterXen chooses a clear CF until its native behavior is verified.
|
||||
constexpr DWORD arithmetic_flags = (1u << 11) | (1u << 7) | (1u << 6) |
|
||||
(1u << 4) | (1u << 2) | (1u << 0);
|
||||
context.EFlags &= ~arithmetic_flags;
|
||||
return true;
|
||||
}
|
||||
case kExtrq:
|
||||
case kInsertq:
|
||||
apply_sse4a(instruction, context);
|
||||
return true;
|
||||
case kAmdKinds:
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
|
||||
// Wine can invoke the top-level filter again for the same terminal fault.
|
||||
if (ep && ep->ExceptionRecord && ep->ContextRecord &&
|
||||
@@ -368,25 +198,20 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
size_t len = decode_clwb_length(ip, size);
|
||||
if (len > 0) {
|
||||
uint64_t count = g_clwb_traps.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
log_sampled_trap("clwb_trapped", count, ep->ContextRecord->Rip, len);
|
||||
if (count == 1 || (count & (count - 1)) == 0) {
|
||||
char msg[160];
|
||||
std::snprintf(msg, sizeof(msg),
|
||||
"rip=0x%016llx len=%zu total_traps=%llu",
|
||||
static_cast<unsigned long long>(ep->ContextRecord->Rip),
|
||||
len,
|
||||
static_cast<unsigned long long>(count));
|
||||
bx_log_emit(BX_LOG_INFO, "runtime_veh", "clwb_trapped", msg);
|
||||
}
|
||||
ep->ContextRecord->Rip += len;
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
}
|
||||
|
||||
const AmdInstruction instruction = decode_amd_instruction(ip, size);
|
||||
if (instruction.length != 0) {
|
||||
if (!apply_amd_instruction(instruction, *ep->ContextRecord, *ep->ExceptionRecord)) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
const uint64_t count =
|
||||
g_amd_traps[instruction.kind].fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
log_sampled_trap(kAmdEvents[instruction.kind], count, ep->ContextRecord->Rip,
|
||||
instruction.length);
|
||||
ep->ContextRecord->Rip += instruction.length;
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
|
||||
if (g_config.enable_adx_tripwire && is_adx_opcode(ip, size)) {
|
||||
char msg[160];
|
||||
std::snprintf(msg, sizeof(msg),
|
||||
|
||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user